Merge dev into production release without education
This commit is contained in:
commit
fc541f024d
50 files changed
+2986
-458
No files matched your search
Binary file not shown.
|
After Width: | Height: | Size: 237 KiB |
Generated
+266
@@ -8,6 +8,7 @@
|
||||
"name": "flockpal-backend",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@asteasolutions/zod-to-openapi": "7.3.4",
|
||||
"@types/nodemailer": "^8.0.0",
|
||||
"bullmq": "^5.76.4",
|
||||
"cors": "2.8.5",
|
||||
@@ -22,9 +23,11 @@
|
||||
"qrcode": "^1.5.4",
|
||||
"sharp": "^0.34.5",
|
||||
"stripe": "^22.0.2",
|
||||
"swagger-ui-express": "5.0.1",
|
||||
"zod": "3.24.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@apidevtools/swagger-parser": "13.1.0",
|
||||
"@types/cors": "2.8.17",
|
||||
"@types/express": "4.17.21",
|
||||
"@types/morgan": "1.9.9",
|
||||
@@ -32,10 +35,79 @@
|
||||
"@types/pdfkit": "^0.17.6",
|
||||
"@types/pg": "8.11.10",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/swagger-ui-express": "4.1.8",
|
||||
"tsx": "4.19.2",
|
||||
"typescript": "5.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@apidevtools/json-schema-ref-parser": {
|
||||
"version": "16.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@apidevtools/json-schema-ref-parser/-/json-schema-ref-parser-16.0.3.tgz",
|
||||
"integrity": "sha512-7lZp4XCTZhU/AgiGpIG+j4uJeWPdGbpQ+8wqXrzuHy+tboKsjSacjGH9/kNThRDIFhMWHF3ba+ejS8J3PeSI1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"js-yaml": "^5.4.2",
|
||||
"undici": "^8.10.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.19.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/json-schema": "^7.0.15"
|
||||
}
|
||||
},
|
||||
"node_modules/@apidevtools/openapi-schemas": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@apidevtools/openapi-schemas/-/openapi-schemas-2.1.0.tgz",
|
||||
"integrity": "sha512-Zc1AlqrJlX3SlpupFGpiLi2EbteyP7fXmUOGup6/DnkRgjP9bgMM/ag+n91rsv0U1Gpz0H3VILA/o3bW7Ua6BQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@apidevtools/swagger-methods": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@apidevtools/swagger-methods/-/swagger-methods-3.0.2.tgz",
|
||||
"integrity": "sha512-QAkD5kK2b1WfjDS/UQn/qQkbwF31uqRjPTrsCs5ZG9BQGAkjwvqGFjjPqAuzac/IYzpPtRzjCP1WrTuAIjMrXg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@apidevtools/swagger-parser": {
|
||||
"version": "13.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@apidevtools/swagger-parser/-/swagger-parser-13.1.0.tgz",
|
||||
"integrity": "sha512-dkCuqCWh5U7u0aurmmc/qvel2KeKDxHTwVtUdYonndIpD7mXV6AVaWNdvaja2HAy628z7FT/Qdz8sCgzwhgwKg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@apidevtools/json-schema-ref-parser": "^16.0.3",
|
||||
"@apidevtools/openapi-schemas": "^2.1.0",
|
||||
"@apidevtools/swagger-methods": "^3.0.2",
|
||||
"@types/json-schema": "^7.0.15",
|
||||
"ajv": "^8.20.0",
|
||||
"ajv-draft-04": "^1.0.0",
|
||||
"call-me-maybe": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.19.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"openapi-types": ">=7"
|
||||
}
|
||||
},
|
||||
"node_modules/@asteasolutions/zod-to-openapi": {
|
||||
"version": "7.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@asteasolutions/zod-to-openapi/-/zod-to-openapi-7.3.4.tgz",
|
||||
"integrity": "sha512-/2rThQ5zPi9OzVwes6U7lK1+Yvug0iXu25olp7S0XsYmOqnyMfxH7gdSQjn/+DSOHRg7wnotwGJSyL+fBKdnEA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"openapi3-ts": "^4.1.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^3.20.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
|
||||
@@ -1027,6 +1099,13 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@scarf/scarf": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",
|
||||
"integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@swc/helpers": {
|
||||
"version": "0.5.23",
|
||||
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
|
||||
@@ -1100,6 +1179,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/json-schema": {
|
||||
"version": "7.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/morgan": {
|
||||
"version": "1.9.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/morgan/-/morgan-1.9.9.tgz",
|
||||
@@ -1195,6 +1281,17 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/swagger-ui-express": {
|
||||
"version": "4.1.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/swagger-ui-express/-/swagger-ui-express-4.1.8.tgz",
|
||||
"integrity": "sha512-AhZV8/EIreHFmBV5wAs0gzJUNq9JbbSXgJLQubCC0jtIo6prnI9MIRRxnU4MZX9RB9yXxF1V4R7jtLl/Wcj31g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/express": "*",
|
||||
"@types/serve-static": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/accepts": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
|
||||
@@ -1208,6 +1305,38 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "8.20.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
|
||||
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
"json-schema-traverse": "^1.0.0",
|
||||
"require-from-string": "^2.0.2"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/epoberezkin"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv-draft-04": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv-draft-04/-/ajv-draft-04-1.0.0.tgz",
|
||||
"integrity": "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"ajv": "^8.5.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ajv": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
@@ -1232,6 +1361,13 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
|
||||
"dev": true,
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/array-flatten": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||
@@ -1373,6 +1509,13 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/call-me-maybe": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz",
|
||||
"integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/camelcase": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
||||
@@ -1756,6 +1899,23 @@
|
||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.8",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
|
||||
"integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fastify"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/finalhandler": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
|
||||
@@ -2055,6 +2215,36 @@
|
||||
"integrity": "sha512-qR0HB5uP6wCuRMrWPTrkMaev7MJZwJuuw4fnwAzRgP4J4/F8RwtodOKpGp4XpqsLBFzzgqIO42efFAyz2Et6KQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "5.4.2",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.2.tgz",
|
||||
"integrity": "sha512-m+aqu+LwO1O6sIopafj8HUVl5aawITwZQe/yHpMCKjaWBaA/d07B/QdMb3529REftiU+RMMHL3Vlsw3hON7vWg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/puzrin"
|
||||
},
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/nodeca"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"js-yaml": "bin/js-yaml.mjs"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-traverse": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/linebreak": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
|
||||
@@ -2329,6 +2519,23 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/openapi-types": {
|
||||
"version": "12.1.3",
|
||||
"resolved": "https://registry.npmjs.org/openapi-types/-/openapi-types-12.1.3.tgz",
|
||||
"integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/openapi3-ts": {
|
||||
"version": "4.6.1",
|
||||
"resolved": "https://registry.npmjs.org/openapi3-ts/-/openapi3-ts-4.6.1.tgz",
|
||||
"integrity": "sha512-XW9MOldkhoICNeXVzzmXzmOW5G73ppOEGmh7fLCqHjgfdEYCGGN+00MlVCeUZgovjjfC56j9tvtDt1zGabNjjA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"yaml": "^2.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||
@@ -2732,6 +2939,16 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-from-string": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
||||
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-main-filename": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||
@@ -3041,6 +3258,30 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/swagger-ui-dist": {
|
||||
"version": "5.33.0",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.33.0.tgz",
|
||||
"integrity": "sha512-wpdK+m6BU5yj6pmUdMskZVTSWYG4DLglAx3sIhylloY37i8O37IrH+YEpqdXNfpaTGxILRBFzUqLF2jKqbfI7A==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@scarf/scarf": "=1.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/swagger-ui-express": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-express/-/swagger-ui-express-5.0.1.tgz",
|
||||
"integrity": "sha512-SrNU3RiBGTLLmFU8GIJdOdanJTl4TOmT27tt3bWWHppqYmAZ6IDuEuBvMU6nZq0zLEe6b/1rACXCgLZqO6ZfrA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"swagger-ui-dist": ">=5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= v0.10.32"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"express": ">=4.0.0 || >=5.0.0-beta"
|
||||
}
|
||||
},
|
||||
"node_modules/tiny-inflate": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
|
||||
@@ -3109,6 +3350,16 @@
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "8.11.2",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-8.11.2.tgz",
|
||||
"integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=22.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.20.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
|
||||
@@ -3203,6 +3454,21 @@
|
||||
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yaml": {
|
||||
"version": "2.9.1",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz",
|
||||
"integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==",
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"yaml": "bin.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/eemeli"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "15.4.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"worker": "node dist/worker.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@asteasolutions/zod-to-openapi": "7.3.4",
|
||||
"@types/nodemailer": "^8.0.0",
|
||||
"bullmq": "^5.76.4",
|
||||
"cors": "2.8.5",
|
||||
@@ -28,9 +29,11 @@
|
||||
"qrcode": "^1.5.4",
|
||||
"sharp": "^0.34.5",
|
||||
"stripe": "^22.0.2",
|
||||
"swagger-ui-express": "5.0.1",
|
||||
"zod": "3.24.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@apidevtools/swagger-parser": "13.1.0",
|
||||
"@types/cors": "2.8.17",
|
||||
"@types/express": "4.17.21",
|
||||
"@types/morgan": "1.9.9",
|
||||
@@ -38,6 +41,7 @@
|
||||
"@types/pdfkit": "^0.17.6",
|
||||
"@types/pg": "8.11.10",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/swagger-ui-express": "4.1.8",
|
||||
"tsx": "4.19.2",
|
||||
"typescript": "5.7.2"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// Rebuild the email-safe PNG from the app's SVG tracks and background palette.
|
||||
// Run from backend: node scripts/generate-email-background.mjs
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import sharp from 'sharp';
|
||||
const css = await readFile(new URL('../../frontend/src/index.css', import.meta.url), 'utf8');
|
||||
const encoded = css.match(/background-image: url\("data:image\/svg\+xml,([^"\n]+)"\)/)?.[1];
|
||||
if (!encoded) throw new Error('App bird-track background was not found');
|
||||
const tracks = decodeURIComponent(encoded);
|
||||
const gradients = `<defs><linearGradient id="wash" x2="0" y2="1"><stop stop-color="#fef5e7"/><stop offset=".46" stop-color="#e9ddba"/><stop offset="1" stop-color="#d9eadf"/></linearGradient>${[[14,10,22,'#de7c3a',.28],[82,12,20,'#35886e',.26],[24,84,22,'#ddb34e',.2],[86,78,24,'#2b765c',.24],[62,54,16,'#3072a0',.14]].map(([x,y,r,color,opacity],i)=>`<radialGradient id="glow${i}" cx="${x}%" cy="${y}%" r="${r}%"><stop stop-color="${color}" stop-opacity="${opacity}"/><stop offset="1" stop-color="${color}" stop-opacity="0"/></radialGradient>`).join('')}</defs>`;
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="1100" viewBox="0 0 1600 2200">${gradients}<rect width="1600" height="2200" fill="url(#wash)"/>${[0,1,2,3,4].map(i=>`<rect width="1600" height="2200" fill="url(#glow${i})"/>`).join('')}<g opacity=".42">${tracks.replace(/^<svg[^>]*>/,'').replace(/<\/svg>$/,'')}</g></svg>`;
|
||||
await writeFile(new URL('../assets/email-background.png', import.meta.url), await sharp(Buffer.from(svg)).png().toBuffer());
|
||||
|
||||
await writeFile(new URL('../../frontend/public/email-background.png', import.meta.url), await readFile(new URL('../assets/email-background.png', import.meta.url)));
|
||||
+203
-396
@@ -1,3 +1,46 @@
|
||||
import { unassignedBirdMatchSchema, claimBirdSchema } from './birdMembershipSchemas.js';
|
||||
import { hasUnassignedBird, removeBirdFromFlock, claimUnassignedBird } from './repositories/birdMembershipRepository.js';
|
||||
import { behaviorTypeSchema, behaviorOccurrenceSchema, behaviorRangeSchema } from './behaviorSchemas.js';
|
||||
import { listBehaviorTypes, createBehaviorType, listBehaviorOccurrences, saveBehaviorOccurrence, deleteBehaviorOccurrence } from './repositories/behaviorRepository.js';
|
||||
import {
|
||||
dateStringSchema,
|
||||
chartColorSchema,
|
||||
photoDataUrlSchema,
|
||||
photoUrlSchema,
|
||||
magicLinkRequestSchema,
|
||||
switchWorkspaceSchema,
|
||||
workspaceTypeSchema,
|
||||
workspaceRoleSchema,
|
||||
billingPlanSchema,
|
||||
billingIntervalSchema,
|
||||
integrationTokenScopeSchema,
|
||||
birdGenderSchema,
|
||||
rescueVerificationStatusSchema,
|
||||
rescueOnboardingSchema,
|
||||
workspaceSchema,
|
||||
createWorkspaceSchema,
|
||||
workspaceMemberSchema,
|
||||
flockTransferSchema,
|
||||
lostBirdReportSchema,
|
||||
publicProfileCodeSchema,
|
||||
birdTransferCodeSchema,
|
||||
birdProfileListSchema,
|
||||
verifiedLocationDetailsSchema,
|
||||
locationSearchSchema,
|
||||
birdSchema,
|
||||
memorializeBirdSchema,
|
||||
memorialReminderPreferenceSchema,
|
||||
birdTimelineEventSchema,
|
||||
weightSchema,
|
||||
vetVisitSchema,
|
||||
medicationSchema,
|
||||
medicationAdministrationSchema,
|
||||
flockNoteSchema,
|
||||
} from './schemas.js';
|
||||
import { mountApiDocs } from './docs/router.js';
|
||||
import { buildEmailLayout } from './emails/emailLayout.js';
|
||||
import { buildWeightReminderEmail } from './emails/weightReminderEmail.js';
|
||||
import type { WeightReminder } from './reminders/weightReminders.js';
|
||||
import crypto from 'crypto';
|
||||
import { existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
@@ -8,7 +51,7 @@ import express, { type NextFunction, type Request, type Response } from 'express
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import helmet from 'helmet';
|
||||
import morgan from 'morgan';
|
||||
import nodemailer, { type SendMailOptions } from 'nodemailer';
|
||||
import nodemailer from 'nodemailer';
|
||||
import Stripe from 'stripe';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -46,7 +89,6 @@ import {
|
||||
findBirdsByBandId,
|
||||
createVetVisitForBird,
|
||||
createWeightForBird,
|
||||
deleteBird,
|
||||
deleteMedicationForBird,
|
||||
deleteVetVisitForBird,
|
||||
getBirdById,
|
||||
@@ -190,163 +232,6 @@ const allowedOrigins = Array.from(
|
||||
),
|
||||
);
|
||||
|
||||
const dateStringSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
const chartColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/);
|
||||
const photoDataUrlSchema = z
|
||||
.string()
|
||||
.regex(/^data:image\/(?:png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$/)
|
||||
.max(1_500_000);
|
||||
const photoUrlSchema = z.string().trim().url().max(2000);
|
||||
|
||||
const magicLinkRequestSchema = z.object({
|
||||
name: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
email: z.string().trim().email().max(255),
|
||||
redirectTo: z.string().trim().url().max(2000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
const switchWorkspaceSchema = z.object({
|
||||
workspaceId: z.coerce.number().int().positive(),
|
||||
});
|
||||
|
||||
const workspaceTypeSchema = z.enum(['standard', 'rescue']);
|
||||
const workspaceRoleSchema = z.enum(['owner', 'assistant', 'caregiver', 'viewer']);
|
||||
const billingPlanSchema = z.enum(['household_basic', 'household_plus', 'household_macaw', 'household_hyacinth_macaw']);
|
||||
const billingIntervalSchema = z.enum(['monthly', 'yearly']);
|
||||
const integrationTokenScopeSchema = z.enum(['read_only', 'read_write']);
|
||||
const birdGenderSchema = z.enum(['unknown', 'male', 'female', 'male_dna', 'female_dna']);
|
||||
const rescueVerificationStatusSchema = z.enum(['pending', 'approved', 'rejected']);
|
||||
const rescueOnboardingSchema = z.object({
|
||||
name: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
city: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
state: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
ein: z.string().trim().max(32).optional().or(z.literal('')),
|
||||
website: z.string().trim().url().max(2000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
const workspaceSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
workspaceType: workspaceTypeSchema,
|
||||
billingEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
billingPlan: billingPlanSchema.optional(),
|
||||
billingInterval: billingIntervalSchema.optional(),
|
||||
rescueOnboarding: rescueOnboardingSchema.optional(),
|
||||
});
|
||||
|
||||
const createWorkspaceSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
workspaceType: workspaceTypeSchema,
|
||||
billingEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
billingPlan: billingPlanSchema.optional(),
|
||||
billingInterval: billingIntervalSchema.optional(),
|
||||
rescueOnboarding: rescueOnboardingSchema.optional(),
|
||||
});
|
||||
|
||||
const workspaceMemberSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
email: z.string().trim().email().max(255),
|
||||
role: workspaceRoleSchema,
|
||||
});
|
||||
|
||||
const flockTransferSchema = z.object({
|
||||
destinationOwnerEmail: z.string().trim().email().max(255),
|
||||
});
|
||||
|
||||
const lostBirdReportSchema = z.object({
|
||||
tagId: z.string().trim().min(1).max(80),
|
||||
finderName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
finderEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
foundLocation: z.string().trim().max(255).optional().or(z.literal('')),
|
||||
message: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
const publicProfileCodeSchema = z.string().trim().regex(/^[A-Za-z0-9_-]{8,32}$/);
|
||||
const birdTransferCodeSchema = z.string().trim().regex(/^[A-Za-z0-9_-]{12,32}$/);
|
||||
const birdProfileListSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(1000)
|
||||
.refine(
|
||||
(value) => value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean).length <= 3,
|
||||
'Use no more than three list items.',
|
||||
)
|
||||
.optional()
|
||||
.or(z.literal(''));
|
||||
|
||||
const verifiedLocationDetailsSchema = z
|
||||
.object({
|
||||
label: z.string().trim().max(220).optional().or(z.literal('')),
|
||||
city: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
region: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
country: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
countryCode: z.string().trim().max(2).optional().or(z.literal('')),
|
||||
latitude: z.coerce.number().min(-90).max(90).optional().nullable().or(z.literal('')),
|
||||
longitude: z.coerce.number().min(-180).max(180).optional().nullable().or(z.literal('')),
|
||||
precision: z.enum(['city', 'region', 'country']).optional(),
|
||||
provider: z.literal('mapbox').optional().nullable(),
|
||||
providerPlaceId: z.string().trim().max(220).optional().or(z.literal('')),
|
||||
})
|
||||
.optional()
|
||||
.nullable();
|
||||
|
||||
const locationSearchSchema = z.object({
|
||||
q: z.string().trim().min(3).max(120),
|
||||
});
|
||||
|
||||
const birdSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
tagId: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
species: z.string().trim().min(1).max(120),
|
||||
motivators: birdProfileListSchema,
|
||||
demotivators: birdProfileListSchema,
|
||||
favoriteSnack: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationLabel: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationDetails: verifiedLocationDetailsSchema,
|
||||
vetClinicName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
vetClinicAddress: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
vetAccountNumber: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
vetDoctorName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
gender: birdGenderSchema.optional(),
|
||||
hatchDay: dateStringSchema.optional().or(z.literal('')),
|
||||
dateOfBirth: dateStringSchema.optional().or(z.literal('')),
|
||||
gotchaDay: dateStringSchema.optional().or(z.literal('')),
|
||||
chartColor: chartColorSchema.optional(),
|
||||
photoDataUrl: z.union([photoDataUrlSchema, photoUrlSchema, z.literal('')]).optional(),
|
||||
notifyOnDob: z.boolean().optional(),
|
||||
notifyOnGotchaDay: z.boolean().optional(),
|
||||
publicProfileEnabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const memorializeBirdSchema = z.object({
|
||||
memorializedOn: dateStringSchema,
|
||||
memorialNote: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
notifyOnMemorialDay: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const memorialReminderPreferenceSchema = z.object({
|
||||
notifyOnMemorialDay: z.boolean(),
|
||||
});
|
||||
|
||||
const birdTimelineEventSchema = z
|
||||
.object({
|
||||
eventType: z.enum(['location_updated', 'owner_changed', 'manual_note']),
|
||||
eventDate: dateStringSchema.optional().or(z.literal('')),
|
||||
locationLabel: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationDetails: verifiedLocationDetailsSchema,
|
||||
note: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
value.eventType === 'owner_changed' ||
|
||||
Boolean(
|
||||
value.locationLabel?.trim() ||
|
||||
value.note?.trim() ||
|
||||
value.locationDetails?.city?.trim() ||
|
||||
value.locationDetails?.region?.trim() ||
|
||||
value.locationDetails?.country?.trim(),
|
||||
),
|
||||
'Add a location or note for this timeline item.',
|
||||
);
|
||||
|
||||
type VerifiedLocationDetailsInput = z.infer<typeof verifiedLocationDetailsSchema>;
|
||||
|
||||
const normalizeVerifiedLocationDetails = (value: VerifiedLocationDetailsInput) => {
|
||||
@@ -466,57 +351,6 @@ const normalizeMapboxLocationFeature = (feature: MapboxGeocodeFeature): Verified
|
||||
});
|
||||
};
|
||||
|
||||
const weightSchema = z.object({
|
||||
weightGrams: z.coerce.number().positive().max(10000),
|
||||
recordedOn: dateStringSchema,
|
||||
notes: z.string().trim().max(280).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
const vetVisitSchema = z.object({
|
||||
visitedOn: dateStringSchema,
|
||||
clinicName: z.string().trim().min(1).max(160),
|
||||
reason: z.string().trim().min(1).max(160),
|
||||
notes: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
const medicationSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
dosage: z.string().trim().min(1).max(160),
|
||||
frequency: z.enum(['once_daily', 'twice_daily', 'every_8_hours', 'every_6_hours', 'as_needed']),
|
||||
doseSchedule: z
|
||||
.array(
|
||||
z.object({
|
||||
key: z.string().trim().min(1).max(80),
|
||||
label: z.string().trim().min(1).max(80),
|
||||
time: z.string().trim().regex(/^$|^\d{2}:\d{2}$/),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(8),
|
||||
route: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
startDate: dateStringSchema,
|
||||
endDate: dateStringSchema.optional().or(z.literal('')),
|
||||
notes: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
remindersEnabled: z.boolean().optional(),
|
||||
})
|
||||
.refine((value) => !value.endDate || value.endDate >= value.startDate, {
|
||||
message: 'End date must be on or after start date.',
|
||||
path: ['endDate'],
|
||||
});
|
||||
|
||||
const medicationAdministrationSchema = z.object({
|
||||
administeredOn: dateStringSchema,
|
||||
administrationSlot: z.string().trim().min(1).max(80).default('dose-1'),
|
||||
status: z.enum(['administered', 'missed']),
|
||||
notes: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
const flockNoteSchema = z.object({
|
||||
birdId: z.string().uuid().optional().nullable().or(z.literal('')),
|
||||
body: z.string().trim().min(1).max(5000),
|
||||
});
|
||||
|
||||
const integrationTokenCreateSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
scope: integrationTokenScopeSchema.default('read_write'),
|
||||
@@ -978,6 +812,7 @@ const oauthProviders = {
|
||||
};
|
||||
|
||||
app.disable('x-powered-by');
|
||||
mountApiDocs(app);
|
||||
app.use(helmet({ crossOriginResourcePolicy: false }));
|
||||
app.use(
|
||||
cors({
|
||||
@@ -1340,12 +1175,14 @@ const sendMagicLink = async ({
|
||||
'',
|
||||
'This link expires in 15 minutes and can only be used once.',
|
||||
].join('\n'),
|
||||
html: `
|
||||
<p>Hi ${name || 'there'},</p>
|
||||
...await buildEmailLayout({ eyebrow: 'Sign in', headline: 'Your FlockPal sign-in link',
|
||||
contentHtml: `
|
||||
<p>Hi ${escapeHtml(name || 'there')},</p>
|
||||
<p>Use this secure link to sign in to FlockPal:</p>
|
||||
<p><a href="${magicLinkUrl}">Sign in to FlockPal</a></p>
|
||||
<p>This link expires in 15 minutes and can only be used once.</p>
|
||||
`,
|
||||
`,
|
||||
action: { url: magicLinkUrl, label: 'Sign in to FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -1416,27 +1253,6 @@ const getMilestoneYearCount = (reminder: BirdMilestoneReminderCandidateRow) => {
|
||||
return Number.isFinite(sourceYear) ? Math.max(0, reminder.reminder_year - sourceYear) : 0;
|
||||
};
|
||||
|
||||
const getFlockPalLogoAttachment = () => {
|
||||
const logoPath = path.join(process.cwd(), 'assets', 'flockpal-logo.png');
|
||||
|
||||
if (!existsSync(logoPath)) {
|
||||
console.warn(`Unable to load FlockPal email logo from ${logoPath}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
filename: 'flockpal-logo.png',
|
||||
path: logoPath,
|
||||
cid: 'flockpal-logo',
|
||||
contentDisposition: 'inline' as const,
|
||||
};
|
||||
};
|
||||
|
||||
const getEmailTrackPatternDataUrl = () => {
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="680" height="188" viewBox="0 0 680 188"><defs><linearGradient id="wash" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#fef5e7"/><stop offset=".52" stop-color="#e9ddba"/><stop offset="1" stop-color="#d9eadf"/></linearGradient><symbol id="track" viewBox="0 0 160 160"><rect x="66" y="12" width="28" height="136" rx="14" transform="rotate(30 80 80)"/><rect x="66" y="12" width="28" height="136" rx="14" transform="rotate(-30 80 80)"/></symbol></defs><rect width="680" height="188" fill="url(#wash)"/><g opacity=".68"><use href="#track" x="20" y="16" width="88" height="88" fill="#5bb3b7" transform="rotate(-12 64 60)"/><use href="#track" x="126" y="74" width="78" height="78" fill="#7eb773" transform="rotate(18 165 113)"/><use href="#track" x="232" y="20" width="104" height="104" fill="#f3a24a" transform="rotate(-26 284 72)"/><use href="#track" x="378" y="72" width="86" height="86" fill="#898b93" transform="rotate(28 421 115)"/><use href="#track" x="492" y="18" width="98" height="98" fill="#b9c945" transform="rotate(-18 541 67)"/><use href="#track" x="592" y="84" width="66" height="66" fill="#5bb3b7" transform="rotate(34 625 117)"/></g><g opacity=".32"><use href="#track" x="66" y="112" width="46" height="46" fill="#f3a24a" transform="rotate(36 89 135)"/><use href="#track" x="190" y="122" width="42" height="42" fill="#5bb3b7" transform="rotate(-20 211 143)"/><use href="#track" x="344" y="18" width="44" height="44" fill="#7eb773" transform="rotate(18 366 40)"/><use href="#track" x="474" y="126" width="48" height="48" fill="#f3a24a" transform="rotate(-34 498 150)"/><use href="#track" x="626" y="18" width="42" height="42" fill="#898b93" transform="rotate(22 647 39)"/></g></svg>`;
|
||||
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
||||
};
|
||||
|
||||
const parseDataImage = (dataUrl: string) => {
|
||||
const match = /^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/.exec(dataUrl);
|
||||
if (!match) {
|
||||
@@ -1581,22 +1397,6 @@ const loadBirdReportPhotoBuffer = async (bird: BirdRow) => {
|
||||
return Buffer.from(await imageResponse.arrayBuffer());
|
||||
};
|
||||
|
||||
const getDefaultBirdPhotoAttachment = () => {
|
||||
const defaultPhotoPath = path.join(process.cwd(), 'assets', 'yoda-default.png');
|
||||
|
||||
if (!existsSync(defaultPhotoPath)) {
|
||||
console.warn(`Unable to load default bird photo from ${defaultPhotoPath}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
filename: 'yoda-default.png',
|
||||
path: defaultPhotoPath,
|
||||
cid: 'flockpal-default-bird-photo',
|
||||
contentDisposition: 'inline' as const,
|
||||
};
|
||||
};
|
||||
|
||||
const sendRescueStatusNotification = async ({
|
||||
workspace,
|
||||
ownerEmail,
|
||||
@@ -1646,7 +1446,8 @@ const sendRescueStatusNotification = async ({
|
||||
to: rescueStatusNotificationEmail,
|
||||
subject,
|
||||
text: lines.join('\n'),
|
||||
html: `
|
||||
...await buildEmailLayout({ eyebrow: 'Rescue status', headline: 'Rescue flock update',
|
||||
contentHtml: `
|
||||
<p>A rescue flock was ${eventLabel}.</p>
|
||||
<ul>
|
||||
<li><strong>Rescue flock:</strong> ${escapedWorkspaceName}</li>
|
||||
@@ -1656,7 +1457,9 @@ const sendRescueStatusNotification = async ({
|
||||
<li><strong>Flock ID:</strong> ${workspace.id}</li>
|
||||
</ul>
|
||||
${escapedNote ? `<p><strong>Note:</strong> ${escapedNote}</p>` : ''}
|
||||
`,
|
||||
`,
|
||||
action: { url: frontendBaseUrl, label: 'Open FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return { delivered: true };
|
||||
@@ -1795,13 +1598,15 @@ const issueBirdTransferInvite = async ({
|
||||
to: email,
|
||||
subject,
|
||||
text,
|
||||
html: `
|
||||
...await buildEmailLayout({ eyebrow: 'Bird transfer', headline: 'A bird is joining your flock',
|
||||
contentHtml: `
|
||||
<p>Hi there,</p>
|
||||
<p><strong>${escapeHtml(sourceWorkspaceName)}</strong> wants to transfer <strong>${escapeHtml(birdName)}</strong> to your FlockPal account.</p>
|
||||
<p>Use this secure invite link to sign in or create your account. FlockPal will automatically create your receiving flock and complete any pending bird transfers for this email.</p>
|
||||
<p><a href="${magicLinkUrl}">Accept bird transfer in FlockPal</a></p>
|
||||
<p>This link expires in 15 minutes and can only be used once.</p>
|
||||
`,
|
||||
`,
|
||||
action: { url: magicLinkUrl, label: 'Accept bird transfer' },
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -1857,7 +1662,8 @@ const sendLostBirdReportNotification = async ({
|
||||
replyTo: emptyToNull(report.finderEmail) ?? undefined,
|
||||
subject,
|
||||
text: lines.join('\n'),
|
||||
html: `
|
||||
...await buildEmailLayout({ eyebrow: 'Found bird report', headline: 'A possible match for your bird',
|
||||
contentHtml: `
|
||||
<p>A possible found bird report was submitted for <strong>${escapeHtml(bird.name)}</strong>.</p>
|
||||
<ul>
|
||||
<li><strong>Band ID:</strong> ${escapeHtml(bird.tag_id ?? 'Not recorded')}</li>
|
||||
@@ -1869,7 +1675,9 @@ const sendLostBirdReportNotification = async ({
|
||||
<li><strong>Message:</strong> ${escapeHtml(message)}</li>
|
||||
</ul>
|
||||
<p>FlockPal does not verify found bird reports. Please use care before sharing personal information or arranging a pickup.</p>
|
||||
`,
|
||||
`,
|
||||
action: { url: frontendBaseUrl, label: 'Open FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return { delivered: true };
|
||||
@@ -1945,7 +1753,7 @@ const buildMedicationReminderCopy = (reminder: MedicationReminderCandidateRow) =
|
||||
return {
|
||||
subject: `${reminder.medication_name} reminder for ${reminder.name}`,
|
||||
eyebrow: 'Medication Reminder',
|
||||
headline: `${slotLabel} time for ${reminder.name}`,
|
||||
headline: `Medication time for ${reminder.name}`,
|
||||
intro: `${reminder.name} is due for ${reminder.medication_name} at ${doseTime}.`,
|
||||
body: `Dose: ${reminder.dosage}${route}.`,
|
||||
detailLabel: `${slotLabel} at ${doseTime}`,
|
||||
@@ -1966,32 +1774,6 @@ const sendBirdMilestoneReminderNotification = async ({
|
||||
}
|
||||
|
||||
const copy = buildBirdMilestoneReminderCopy(reminder);
|
||||
const attachments: NonNullable<SendMailOptions['attachments']> = [];
|
||||
const logoAttachment = getFlockPalLogoAttachment();
|
||||
const trackPatternDataUrl = getEmailTrackPatternDataUrl();
|
||||
const uploadedBirdPhoto = reminder.photo_data_url ? parseDataImage(reminder.photo_data_url) : null;
|
||||
const defaultBirdPhoto = uploadedBirdPhoto ? null : getDefaultBirdPhotoAttachment();
|
||||
const birdPhotoCid = uploadedBirdPhoto ? 'bird-photo' : defaultBirdPhoto ? defaultBirdPhoto.cid : '';
|
||||
|
||||
if (logoAttachment) {
|
||||
attachments.push(logoAttachment);
|
||||
}
|
||||
|
||||
if (uploadedBirdPhoto) {
|
||||
attachments.push({
|
||||
filename: `${reminder.name.replace(/[^a-z0-9_-]+/gi, '-').toLowerCase() || 'bird'}-photo`,
|
||||
content: uploadedBirdPhoto.content,
|
||||
contentType: uploadedBirdPhoto.contentType,
|
||||
cid: birdPhotoCid,
|
||||
contentDisposition: 'inline',
|
||||
});
|
||||
} else if (defaultBirdPhoto) {
|
||||
attachments.push(defaultBirdPhoto);
|
||||
}
|
||||
|
||||
const birdPhotoHtml = birdPhotoCid
|
||||
? `<img src="cid:${birdPhotoCid}" alt="${escapeHtml(reminder.name)}" style="display: block; width: 148px; height: 148px; border-radius: 28px; object-fit: cover; border: 4px solid #fff8ef; box-shadow: 0 14px 30px rgba(38, 51, 49, 0.18);" />`
|
||||
: `<div style="display: grid; place-items: center; width: 148px; height: 148px; border-radius: 28px; background: linear-gradient(135deg, #fff8ef, #eaf7ef); border: 4px solid #fff8ef; box-shadow: 0 14px 30px rgba(38, 51, 49, 0.18); color: #238a5a; font-size: 64px; font-weight: 800;">${escapeHtml(reminder.name.slice(0, 1).toUpperCase())}</div>`;
|
||||
const lines = [
|
||||
copy.headline,
|
||||
'',
|
||||
@@ -2016,43 +1798,18 @@ const sendBirdMilestoneReminderNotification = async ({
|
||||
bcc: uniqueRecipients,
|
||||
subject: copy.subject,
|
||||
text: lines.join('\n'),
|
||||
attachments,
|
||||
html: `
|
||||
<div style="margin: 0; padding: 28px; background-color: #fef5e7; background-image: url('${trackPatternDataUrl}'), radial-gradient(circle at 14% 10%, rgba(222, 124, 58, 0.24), transparent 22%), radial-gradient(circle at 82% 12%, rgba(53, 136, 110, 0.22), transparent 20%), linear-gradient(180deg, #fef5e7 0%, #e9ddba 46%, #d9eadf 100%); background-repeat: repeat, no-repeat, no-repeat, no-repeat; font-family: Arial, sans-serif; color: #1f2a2a; line-height: 1.6;">
|
||||
<div style="max-width: 680px; margin: 0 auto 18px;">
|
||||
<img src="${trackPatternDataUrl}" alt="" style="display: block; width: 100%; max-width: 680px; height: auto; border-radius: 26px;" />
|
||||
</div>
|
||||
<div style="max-width: 680px; margin: 0 auto; overflow: hidden; border-radius: 30px; background-color: #e7f4e9; background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.44), transparent 42%), linear-gradient(180deg, rgba(235, 247, 237, 0.98), rgba(211, 235, 220, 0.96)); border: 1px solid rgba(53, 129, 98, 0.34); box-shadow: 0 22px 44px rgba(89, 48, 42, 0.14);">
|
||||
<div style="padding: 24px 28px; background-color: #edf8ef; background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.46), transparent 46%), linear-gradient(180deg, rgba(242, 250, 243, 0.98), rgba(220, 241, 226, 0.94)); border-bottom: 1px solid rgba(53, 129, 98, 0.18);">
|
||||
${
|
||||
logoAttachment
|
||||
? '<img src="cid:flockpal-logo" alt="FlockPal" style="display: block; width: 180px; max-width: 72%; height: auto;" />'
|
||||
: '<strong style="display: block; color: #238a5a; font-size: 22px;">FlockPal</strong>'
|
||||
}
|
||||
</div>
|
||||
<div style="padding: 30px 28px;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; padding: 0 24px 20px 0; width: 160px;">
|
||||
${birdPhotoHtml}
|
||||
</td>
|
||||
<td style="vertical-align: top; padding: 0 0 20px;">
|
||||
<h1 style="margin: 0 0 12px; color: #1f2a2a; font-size: 30px; line-height: 1.12;">${escapeHtml(copy.headline)}</h1>
|
||||
<p style="margin: 0; color: #63562d; font-size: 17px;">${escapeHtml(copy.intro)}</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p style="margin: 4px 0 18px; font-size: 16px;">${escapeHtml(copy.body)}</p>
|
||||
<p style="margin: 0;">
|
||||
<a href="${frontendBaseUrl}" style="display: inline-block; padding: 12px 18px; border-radius: 999px; background: linear-gradient(135deg, #238a5a, #2f8f98); color: #ffffff; text-decoration: none; font-weight: 700; box-shadow: 0 12px 24px rgba(72, 97, 62, 0.16);">Open FlockPal</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style="max-width: 680px; margin: 18px auto 0;">
|
||||
<img src="${trackPatternDataUrl}" alt="" style="display: block; width: 100%; max-width: 680px; height: auto; border-radius: 26px;" />
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
...await buildEmailLayout({
|
||||
bird: reminder,
|
||||
eyebrow: copy.eyebrow,
|
||||
headline: copy.headline,
|
||||
preheader: copy.intro,
|
||||
contentHtml: `<p style="margin:0 0 16px;font-size:16px;">${escapeHtml(copy.intro)}</p>
|
||||
<p>${escapeHtml(copy.body)}</p>
|
||||
<p><strong>${escapeHtml(reminder.name)}</strong> · ${escapeHtml(reminder.species)}</p>
|
||||
<p>${escapeHtml(`${copy.eventName}: ${copy.milestoneLabel}`)}</p>
|
||||
`,
|
||||
action: { url: frontendBaseUrl, label: 'Open FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return { delivered: true };
|
||||
@@ -2072,35 +1829,6 @@ const sendMedicationReminderNotification = async ({
|
||||
}
|
||||
|
||||
const copy = buildMedicationReminderCopy(reminder);
|
||||
const attachments: NonNullable<SendMailOptions['attachments']> = [];
|
||||
const logoAttachment = getFlockPalLogoAttachment();
|
||||
const trackPatternDataUrl = getEmailTrackPatternDataUrl();
|
||||
const uploadedBirdPhoto = reminder.photo_data_url ? parseDataImage(reminder.photo_data_url) : null;
|
||||
const defaultBirdPhoto = uploadedBirdPhoto ? null : getDefaultBirdPhotoAttachment();
|
||||
const birdPhotoCid = uploadedBirdPhoto ? 'bird-photo' : defaultBirdPhoto ? defaultBirdPhoto.cid : '';
|
||||
|
||||
if (logoAttachment) {
|
||||
attachments.push(logoAttachment);
|
||||
}
|
||||
|
||||
if (uploadedBirdPhoto) {
|
||||
attachments.push({
|
||||
filename: `${reminder.name.replace(/[^a-z0-9_-]+/gi, '-').toLowerCase() || 'bird'}-photo`,
|
||||
content: uploadedBirdPhoto.content,
|
||||
contentType: uploadedBirdPhoto.contentType,
|
||||
cid: birdPhotoCid,
|
||||
contentDisposition: 'inline',
|
||||
});
|
||||
} else if (defaultBirdPhoto) {
|
||||
attachments.push(defaultBirdPhoto);
|
||||
}
|
||||
|
||||
const birdPhotoHtml = birdPhotoCid
|
||||
? `<img src="cid:${birdPhotoCid}" alt="${escapeHtml(reminder.name)}" style="display: block; width: 148px; height: 148px; border-radius: 28px; object-fit: cover; border: 4px solid #fff8ef; box-shadow: 0 14px 30px rgba(38, 51, 49, 0.18);" />`
|
||||
: `<div style="display: grid; place-items: center; width: 148px; height: 148px; border-radius: 28px; background: linear-gradient(135deg, #fff8ef, #eaf7ef); border: 4px solid #fff8ef; box-shadow: 0 14px 30px rgba(38, 51, 49, 0.18); color: #238a5a; font-size: 64px; font-weight: 800;">${escapeHtml(reminder.name.slice(0, 1).toUpperCase())}</div>`;
|
||||
const medicationNotesHtml = reminder.medication_notes
|
||||
? `<p style="margin: 0 0 18px; font-size: 15px; color: #63562d;"><strong>Medication notes:</strong> ${escapeHtml(reminder.medication_notes)}</p>`
|
||||
: '';
|
||||
const lines = [
|
||||
copy.headline,
|
||||
'',
|
||||
@@ -2127,46 +1855,18 @@ const sendMedicationReminderNotification = async ({
|
||||
bcc: uniqueRecipients,
|
||||
subject: copy.subject,
|
||||
text: lines.join('\n'),
|
||||
attachments,
|
||||
html: `
|
||||
<div style="margin: 0; padding: 28px; background-color: #fef5e7; background-image: url('${trackPatternDataUrl}'), radial-gradient(circle at 14% 10%, rgba(222, 124, 58, 0.24), transparent 22%), radial-gradient(circle at 82% 12%, rgba(53, 136, 110, 0.22), transparent 20%), linear-gradient(180deg, #fef5e7 0%, #e9ddba 46%, #d9eadf 100%); background-repeat: repeat, no-repeat, no-repeat, no-repeat; font-family: Arial, sans-serif; color: #1f2a2a; line-height: 1.6;">
|
||||
<div style="max-width: 680px; margin: 0 auto 18px;">
|
||||
<img src="${trackPatternDataUrl}" alt="" style="display: block; width: 100%; max-width: 680px; height: auto; border-radius: 26px;" />
|
||||
</div>
|
||||
<div style="max-width: 680px; margin: 0 auto; overflow: hidden; border-radius: 30px; background-color: #e7f4e9; background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.44), transparent 42%), linear-gradient(180deg, rgba(235, 247, 237, 0.98), rgba(211, 235, 220, 0.96)); border: 1px solid rgba(53, 129, 98, 0.34); box-shadow: 0 22px 44px rgba(89, 48, 42, 0.14);">
|
||||
<div style="padding: 24px 28px; background-color: #edf8ef; background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.46), transparent 46%), linear-gradient(180deg, rgba(242, 250, 243, 0.98), rgba(220, 241, 226, 0.94)); border-bottom: 1px solid rgba(53, 129, 98, 0.18);">
|
||||
${
|
||||
logoAttachment
|
||||
? '<img src="cid:flockpal-logo" alt="FlockPal" style="display: block; width: 180px; max-width: 72%; height: auto;" />'
|
||||
: '<strong style="display: block; color: #238a5a; font-size: 22px;">FlockPal</strong>'
|
||||
}
|
||||
</div>
|
||||
<div style="padding: 30px 28px;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; padding: 0 24px 20px 0; width: 160px;">
|
||||
${birdPhotoHtml}
|
||||
</td>
|
||||
<td style="vertical-align: top; padding: 0 0 20px;">
|
||||
<p style="margin: 0 0 8px; color: #238a5a; font-size: 13px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.08em;">${escapeHtml(copy.eyebrow)}</p>
|
||||
<h1 style="margin: 0 0 12px; color: #1f2a2a; font-size: 30px; line-height: 1.12;">${escapeHtml(copy.headline)}</h1>
|
||||
<p style="margin: 0; color: #63562d; font-size: 17px;">${escapeHtml(copy.intro)}</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p style="margin: 4px 0 10px; font-size: 16px;">${escapeHtml(copy.body)}</p>
|
||||
<p style="margin: 0 0 18px; font-size: 15px; color: #63562d;"><strong>Schedule:</strong> ${escapeHtml(copy.detailLabel)}</p>
|
||||
${medicationNotesHtml}
|
||||
<p style="margin: 0;">
|
||||
<a href="${frontendBaseUrl}" style="display: inline-block; padding: 12px 18px; border-radius: 999px; background: linear-gradient(135deg, #238a5a, #2f8f98); color: #ffffff; text-decoration: none; font-weight: 700; box-shadow: 0 12px 24px rgba(72, 97, 62, 0.16);">Open FlockPal</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style="max-width: 680px; margin: 18px auto 0;">
|
||||
<img src="${trackPatternDataUrl}" alt="" style="display: block; width: 100%; max-width: 680px; height: auto; border-radius: 26px;" />
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
...await buildEmailLayout({
|
||||
bird: reminder,
|
||||
eyebrow: copy.eyebrow,
|
||||
headline: copy.headline,
|
||||
preheader: copy.intro,
|
||||
contentHtml: `<p style="margin:0 0 16px;font-size:16px;">${escapeHtml(copy.intro)}</p>
|
||||
<p>${escapeHtml(copy.body)}</p>
|
||||
<p><strong>${escapeHtml(reminder.name)}</strong> · ${escapeHtml(reminder.species)}</p>
|
||||
<p>${escapeHtml(copy.detailLabel)}</p>
|
||||
${reminder.medication_notes ? `<p><strong>Medication notes:</strong> ${escapeHtml(reminder.medication_notes)}</p>` : ''}`,
|
||||
action: { url: frontendBaseUrl, label: 'Open FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return { delivered: true };
|
||||
@@ -2216,6 +1916,17 @@ export const runBirdMilestoneReminders = async (runDate = getDateInTimeZone()) =
|
||||
};
|
||||
};
|
||||
|
||||
export const sendWeightReminderNotification = async (reminders: WeightReminder[]): Promise<boolean> => {
|
||||
if (!mailTransport || !reminders.length) return false;
|
||||
const first = reminders[0];
|
||||
const result = await mailTransport.sendMail({
|
||||
from: smtpFromName ? `"${smtpFromName}" <${smtpFromEmail}>` : smtpFromEmail,
|
||||
to: first.recipient,
|
||||
...await buildWeightReminderEmail(reminders, frontendBaseUrl),
|
||||
});
|
||||
return result.accepted.length > 0;
|
||||
};
|
||||
|
||||
export const runMedicationReminders = async (runDate = getDateInTimeZone(), currentTime = getTimeInTimeZone()) => {
|
||||
const reminders = await listDueMedicationReminders(runDate, currentTime);
|
||||
let sent = 0;
|
||||
@@ -3636,6 +3347,27 @@ app.get('/api/locations/search', requireAuth, locationSearchLimiter, async (req:
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/birds/unassigned-match', requireAuth, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = unassignedBirdMatchSchema.safeParse(req.query);
|
||||
if (!parsed.success) { res.status(400).json({ error: 'Enter a known band ID.' }); return; }
|
||||
try {
|
||||
res.json({ available: await hasUnassignedBird(parsed.data.tagId) });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
|
||||
app.post('/api/birds/claim', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = claimBirdSchema.safeParse(req.body);
|
||||
if (!parsed.success) { res.status(400).json({ error: 'A known band ID and confirmation to bring in existing history are required.' }); return; }
|
||||
try {
|
||||
const birdId = await claimUnassignedBird(parsed.data.tagId, req.auth!.workspace.id, req.auth!.user.id);
|
||||
if (!birdId) { res.status(409).json({ error: 'No unassigned bird is available with that band ID. It may already have joined a flock.' }); return; }
|
||||
const bird = await getBirdById(birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(409).json({ error: 'The bird is no longer in this flock. Refresh the flock to continue.' }); return; }
|
||||
await writeAuditLog(req.auth!, 'bird.claimed', 'bird', bird.id, bird.name, { tagId: bird.tag_id });
|
||||
res.status(200).json({ bird: normalizeBird(bird), historyImported: true });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
|
||||
app.get('/api/birds', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const [birds, memorializedBirds] = await Promise.all([
|
||||
@@ -3784,6 +3516,11 @@ app.post('/api/birds', requireAuth, requireWriteAccess, requireWorkspaceRole(['o
|
||||
let uploadedObjectKeyToCleanup: string | null = null;
|
||||
|
||||
try {
|
||||
const tagId = normalizeBandId(parsed.data.tagId);
|
||||
if (tagId && await hasUnassignedBird(tagId)) {
|
||||
res.status(409).json({ code: 'bird_history_available', error: 'An unassigned bird has this band ID. Confirm adding the existing bird with its history instead of creating a new profile.' });
|
||||
return;
|
||||
}
|
||||
const birdId = crypto.randomUUID();
|
||||
const photoStorage = await resolveBirdPhotoStorage({
|
||||
birdId,
|
||||
@@ -4240,16 +3977,15 @@ app.delete('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspa
|
||||
return;
|
||||
}
|
||||
|
||||
const deleted = await deleteBird(req.params.birdId, req.auth!.workspace.id);
|
||||
const removed = await removeBirdFromFlock(req.params.birdId, req.auth!.workspace.id, req.auth!.user.id);
|
||||
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'Bird not found.' });
|
||||
if (!removed) {
|
||||
res.status(404).json({ error: 'Bird not found or no longer removable.' });
|
||||
return;
|
||||
}
|
||||
|
||||
await writeAuditLog(req.auth!, 'bird.deleted', 'bird', bird.id, bird.name);
|
||||
await writeAuditLog(req.auth!, 'bird.removed_from_flock', 'bird', bird.id, bird.name);
|
||||
res.status(204).send();
|
||||
await deleteBirdPhotoObjectIfNeeded(bird.photo_object_key);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -4326,6 +4062,77 @@ app.patch('/api/birds/:birdId/memorial-reminders', requireAuth, requireWriteAcce
|
||||
}
|
||||
});
|
||||
|
||||
// Behavior types are flock-scoped; occurrences follow their bird across flock transfers.
|
||||
app.get('/api/birds/:birdId/behavior-types', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
if (!z.string().uuid().safeParse(req.params.birdId).success) { res.status(400).json({ error: 'Invalid bird ID.' }); return; }
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
res.json({ behaviorTypes: await listBehaviorTypes(req.auth!.workspace.id, bird.id) });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.post('/api/birds/:birdId/behavior-types', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = behaviorTypeSchema.safeParse(req.body);
|
||||
if (!parsed.success || !z.string().uuid().safeParse(req.params.birdId).success) { res.status(400).json({ error: 'Invalid behavior type payload.' }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
if (!ensureBirdWritable(bird, res)) return;
|
||||
const behaviorType = await createBehaviorType(req.auth!.workspace.id, parsed.data.name, parsed.data.description);
|
||||
await writeAuditLog(req.auth!, 'behavior_type.created', 'behavior_type', behaviorType.id, parsed.data.name);
|
||||
res.status(201).json({ behaviorType });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.get('/api/birds/:birdId/behaviors', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = behaviorRangeSchema.safeParse(req.query);
|
||||
if (!parsed.success || !z.string().uuid().safeParse(req.params.birdId).success) { res.status(400).json({ error: 'Invalid behavior date range or bird ID.' }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
res.json({ occurrences: await listBehaviorOccurrences(bird.id, req.auth!.workspace.id, parsed.data.from, parsed.data.to, parsed.data.behaviorTypeId) });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.post('/api/birds/:birdId/behaviors', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
if (!z.string().uuid().safeParse(req.params.birdId).success) { res.status(400).json({ error: 'Invalid ID.' }); return; }
|
||||
const parsed = behaviorOccurrenceSchema.safeParse(req.body);
|
||||
if (!parsed.success) { res.status(400).json({ error: 'Invalid behavior payload.', details: parsed.error.flatten() }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
if (!ensureBirdWritable(bird, res)) return;
|
||||
const occurrence = await saveBehaviorOccurrence(bird.id, req.auth!.workspace.id, parsed.data);
|
||||
if (!occurrence) { res.status(404).json({ error: 'Occurrence or behavior type not found, or bird is no longer editable.' }); return; }
|
||||
await writeAuditLog(req.auth!, 'behavior.created', 'behavior_occurrence', occurrence.id, bird.name, { birdId: bird.id });
|
||||
res.status(201).json({ occurrence });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.put('/api/birds/:birdId/behaviors/:occurrenceId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
if (!z.string().uuid().safeParse(req.params.birdId).success || !z.string().uuid().safeParse(req.params.occurrenceId).success) { res.status(400).json({ error: 'Invalid ID.' }); return; }
|
||||
const parsed = behaviorOccurrenceSchema.safeParse(req.body);
|
||||
if (!parsed.success) { res.status(400).json({ error: 'Invalid behavior payload.', details: parsed.error.flatten() }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
if (!ensureBirdWritable(bird, res)) return;
|
||||
const occurrence = await saveBehaviorOccurrence(bird.id, req.auth!.workspace.id, parsed.data, req.params.occurrenceId);
|
||||
if (!occurrence) { res.status(404).json({ error: 'Occurrence or behavior type not found, or bird is no longer editable.' }); return; }
|
||||
await writeAuditLog(req.auth!, 'behavior.updated', 'behavior_occurrence', occurrence.id, bird.name, { birdId: bird.id });
|
||||
res.status(200).json({ occurrence });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.delete('/api/birds/:birdId/behaviors/:occurrenceId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
if (!z.string().uuid().safeParse(req.params.birdId).success || !z.string().uuid().safeParse(req.params.occurrenceId).success) { res.status(400).json({ error: 'Invalid ID.' }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
if (!ensureBirdWritable(bird, res)) return;
|
||||
const occurrence = await deleteBehaviorOccurrence(bird.id, req.auth!.workspace.id, req.params.occurrenceId);
|
||||
if (!occurrence) { res.status(404).json({ error: 'Occurrence or behavior type not found, or bird is no longer editable.' }); return; }
|
||||
await writeAuditLog(req.auth!, 'behavior.deleted', 'behavior_occurrence', occurrence.id, bird.name, { birdId: bird.id });
|
||||
res.status(204).send();
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
|
||||
app.get('/api/birds/:birdId/weights', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const days = Math.min(Math.max(Number(req.query.days ?? 30), 1), 425);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const behaviorTypeSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
description: z.string().trim().max(2000).nullable().optional(),
|
||||
});
|
||||
export const behaviorOccurrenceSchema = z.object({
|
||||
behaviorTypeId: z.string().uuid(),
|
||||
occurredAt: z.string().datetime({ offset: true }),
|
||||
durationSeconds: z.number().finite().positive().max(31536000).nullable().optional(),
|
||||
severity: z.number().int().min(1).max(5).nullable().optional(),
|
||||
notes: z.string().trim().max(10000).nullable().optional(),
|
||||
});
|
||||
export const behaviorRangeSchema = z.object({
|
||||
from: z.string().datetime({ offset: true }),
|
||||
to: z.string().datetime({ offset: true }),
|
||||
behaviorTypeId: z.string().uuid().optional(),
|
||||
}).refine(({ from, to }) => Date.parse(to) > Date.parse(from) && Date.parse(to) - Date.parse(from) <= 32 * 86400000, {
|
||||
message: 'Choose a date range of up to 32 days, with to after from.',
|
||||
});
|
||||
export type BehaviorInput = z.infer<typeof behaviorOccurrenceSchema>;
|
||||
|
||||
export type BehaviorType = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
export type BehaviorOccurrence = {
|
||||
id: string;
|
||||
birdId: string;
|
||||
behaviorTypeId: string;
|
||||
behaviorName: string;
|
||||
occurredAt: Date;
|
||||
durationSeconds: number | null;
|
||||
severity: number | null;
|
||||
notes: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const unassignedBirdMatchSchema = z.object({
|
||||
tagId: z.string().trim().min(1).max(80).refine(
|
||||
(value) => !['unknown', 'not recorded', 'n/a', 'na', 'none'].includes(value.toLowerCase()),
|
||||
'Enter a known band ID.',
|
||||
),
|
||||
});
|
||||
export const claimBirdSchema = unassignedBirdMatchSchema.extend({ confirmHistory: z.literal(true) });
|
||||
@@ -23,6 +23,21 @@ export class DatabaseClient {
|
||||
return this.pool.query<T>(text, params);
|
||||
}
|
||||
|
||||
async transaction<T>(operation: (client: pg.PoolClient) => Promise<T>): Promise<T> {
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await operation(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
await this.pool.end();
|
||||
}
|
||||
|
||||
@@ -269,7 +269,9 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
ADD COLUMN IF NOT EXISTS notify_on_memorial_day BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
ALTER TABLE birds
|
||||
ALTER COLUMN tag_id DROP NOT NULL;
|
||||
ALTER COLUMN tag_id DROP NOT NULL,
|
||||
ALTER COLUMN workspace_id DROP NOT NULL,
|
||||
ALTER COLUMN workspace_id DROP DEFAULT;
|
||||
|
||||
UPDATE birds
|
||||
SET tag_id = NULL
|
||||
@@ -416,6 +418,9 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
ON flock_notes (bird_id, updated_at DESC)
|
||||
WHERE bird_id IS NOT NULL;
|
||||
|
||||
-- Bird-specific notes remain attached while their bird is between flocks.
|
||||
ALTER TABLE flock_notes ALTER COLUMN workspace_id DROP NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_log_entries (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
@@ -446,6 +451,17 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
UNIQUE (bird_id, recorded_on)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS weight_reminder_deliveries (
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
activity_at TIMESTAMPTZ NOT NULL,
|
||||
recipient TEXT NOT NULL,
|
||||
claim_token UUID NOT NULL,
|
||||
claimed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
delivered_at TIMESTAMPTZ,
|
||||
PRIMARY KEY (bird_id, workspace_id, activity_at, recipient)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS vet_visits (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
@@ -549,6 +565,37 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
CREATE INDEX IF NOT EXISTS idx_medication_administrations_medication_date
|
||||
ON medication_administrations (medication_id, administered_on DESC, created_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS behavior_types (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
workspace_id INTEGER REFERENCES workspaces(id) ON DELETE SET NULL,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
is_default BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
description TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_behavior_types_workspace_name
|
||||
ON behavior_types (workspace_id, lower(name)) WHERE workspace_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_behavior_types_default_name
|
||||
ON behavior_types (lower(name)) WHERE is_default;
|
||||
INSERT INTO behavior_types (name, is_default) VALUES
|
||||
('Screaming / vocalization', TRUE), ('Biting / aggression', TRUE), ('Feather plucking', TRUE),
|
||||
('Repetitive behavior', TRUE), ('Excessive scratching', TRUE), ('Hiding / withdrawal', TRUE),
|
||||
('Unusual posture', TRUE), ('Food refusal', TRUE), ('Other', TRUE)
|
||||
ON CONFLICT DO NOTHING;
|
||||
CREATE TABLE IF NOT EXISTS behavior_occurrences (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
behavior_type_id UUID NOT NULL REFERENCES behavior_types(id),
|
||||
occurred_at TIMESTAMPTZ NOT NULL,
|
||||
duration_seconds DOUBLE PRECISION CHECK (duration_seconds > 0 AND duration_seconds <= 31536000),
|
||||
severity SMALLINT CHECK (severity BETWEEN 1 AND 5),
|
||||
notes TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_behavior_occurrences_bird_time ON behavior_occurrences (bird_id, occurred_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_behavior_occurrences_bird_type_time ON behavior_occurrences (bird_id, behavior_type_id, occurred_at DESC);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { once } from 'node:events';
|
||||
import test from 'node:test';
|
||||
import express from 'express';
|
||||
import SwaggerParser from '@apidevtools/swagger-parser';
|
||||
import ts from 'typescript';
|
||||
import { customerOpenApi } from './openapi.js';
|
||||
import { mountApiDocs } from './router.js';
|
||||
import { birdSchema, medicationSchema } from '../schemas.js';
|
||||
|
||||
const appSource = await readFile(new URL('../app.ts', import.meta.url), 'utf8');
|
||||
const ast = ts.createSourceFile('app.ts', appSource, ts.ScriptTarget.Latest, true);
|
||||
|
||||
test('customer specification is valid OpenAPI and has unique operation IDs', async () => {
|
||||
await SwaggerParser.validate(JSON.parse(JSON.stringify(customerOpenApi)));
|
||||
const ids = Object.values(customerOpenApi.paths).flatMap((path) => Object.values(path!).map((operation) => operation.operationId));
|
||||
assert.equal(new Set(ids).size, ids.length);
|
||||
assert.deepEqual(customerOpenApi.servers, [{ url: '/api', description: 'This FlockPal instance' }]);
|
||||
});
|
||||
|
||||
test('documented operations exactly match customer integration routes and permissions', () => {
|
||||
const expected: string[] = [];
|
||||
for (const statement of ast.statements) {
|
||||
if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)) continue;
|
||||
const call = statement.expression;
|
||||
if (!ts.isPropertyAccessExpression(call.expression) || call.expression.expression.getText(ast) !== 'app') continue;
|
||||
const method = call.expression.name.text;
|
||||
if (!['get', 'post', 'put', 'delete', 'patch'].includes(method)) continue;
|
||||
const [pathArg, ...args] = call.arguments;
|
||||
if (!pathArg || !ts.isStringLiteral(pathArg)) continue;
|
||||
const middleware = args.filter(ts.isIdentifier).map((arg) => arg.text);
|
||||
if (!middleware.includes('requireAuth') || middleware.includes('requireSessionAuth') || middleware.includes('requireAdmin')) continue;
|
||||
const path = pathArg.text.replace(/^\/api/, '').replace(/:(\w+)/g, '{$1}');
|
||||
expected.push(`${method} ${path}`);
|
||||
const operation = (customerOpenApi.paths[path] as Record<string, any> | undefined)?.[method];
|
||||
assert.ok(operation, `Missing ${method} ${path}`);
|
||||
assert.deepEqual(operation.security, [{ IntegrationToken: [] }]);
|
||||
if (middleware.includes('requireWriteAccess')) {
|
||||
assert.match(operation.description, /read_write/);
|
||||
assert.ok(operation.responses['402']);
|
||||
assert.ok(operation.responses['403']);
|
||||
}
|
||||
const roleCall = args.find((arg) => ts.isCallExpression(arg) && arg.expression.getText(ast) === 'requireWorkspaceRole');
|
||||
if (roleCall && ts.isCallExpression(roleCall)) {
|
||||
for (const match of roleCall.getText(ast).matchAll(/'([^']+)'/g)) assert.ok(operation.description.includes(match[1]));
|
||||
}
|
||||
}
|
||||
const actual = Object.entries(customerOpenApi.paths).flatMap(([path, item]) => Object.keys(item!).map((method) => `${method} ${path}`));
|
||||
assert.deepEqual(actual.sort(), expected.sort());
|
||||
assert.equal(actual.length, 35);
|
||||
});
|
||||
|
||||
test('response models cover the actual serialized fields', () => {
|
||||
const components = customerOpenApi.components!.schemas!;
|
||||
const names: Record<string, string> = { normalizeWorkspace: 'workspace', normalizeWorkspaceMember: 'member', normalizeBird: 'bird', normalizeWeight: 'weight', normalizeVetVisit: 'vetVisit', normalizeMedication: 'medication', normalizeMedicationAdministration: 'administration', normalizeFlockNote: 'note', normalizeBirdTimelineEvent: 'timeline' };
|
||||
for (const statement of ast.statements) {
|
||||
if (!ts.isVariableStatement(statement)) continue;
|
||||
for (const declaration of statement.declarationList.declarations) {
|
||||
const model = names[declaration.name.getText(ast)];
|
||||
if (!model) continue;
|
||||
const fn = declaration.initializer;
|
||||
assert.ok(fn && ts.isArrowFunction(fn) && ts.isParenthesizedExpression(fn.body));
|
||||
const body = fn.body.expression;
|
||||
assert.ok(ts.isObjectLiteralExpression(body));
|
||||
const keys = body.properties.map((property) => property.name!.getText(ast));
|
||||
const schema = components[model];
|
||||
assert.ok(schema && !('$ref' in schema));
|
||||
assert.deepEqual(Object.keys(schema.properties!).sort(), keys.sort(), model);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('shared validators retain custom rules and document required request fields', () => {
|
||||
assert.equal(birdSchema.safeParse({ name: 'Yoda', species: 'Parrot', motivators: 'one\ntwo\nthree\nfour' }).success, false);
|
||||
assert.equal(medicationSchema.safeParse({ name: 'Medicine', dosage: '1 ml', frequency: 'once_daily', doseSchedule: [{ key: 'morning', label: 'Morning', time: '08:00' }], startDate: '2026-09-27', endDate: '2026-09-26' }).success, false);
|
||||
const bird = customerOpenApi.components!.schemas!.BirdInput;
|
||||
assert.ok(!('$ref' in bird));
|
||||
assert.deepEqual(bird.required, ['name', 'species']);
|
||||
});
|
||||
|
||||
test('Swagger UI, initialization, assets and specification are served locally with compatible CSP', async (t) => {
|
||||
const app = express();
|
||||
mountApiDocs(app);
|
||||
const server = app.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
t.after(() => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve())));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== 'string');
|
||||
const base = `http://127.0.0.1:${address.port}`;
|
||||
const page = await fetch(`${base}/api/docs/`);
|
||||
assert.equal(page.status, 200);
|
||||
const html = await page.text();
|
||||
assert.match(html, /FlockPal API Reference/);
|
||||
const csp = page.headers.get('content-security-policy')!;
|
||||
assert.match(csp, /script-src 'self'/);
|
||||
assert.match(csp, /connect-src 'self'/);
|
||||
assert.ok(!csp.includes('upgrade-insecure-requests'));
|
||||
for (const asset of ['swagger-ui.css', 'swagger-ui-bundle.js', 'swagger-ui-standalone-preset.js', 'swagger-ui-init.js']) {
|
||||
const response = await fetch(`${base}/api/docs/${asset}`);
|
||||
assert.equal(response.status, 200, asset);
|
||||
const content = await response.text();
|
||||
assert.ok(content.length > 0);
|
||||
if (asset === 'swagger-ui-init.js') {
|
||||
assert.match(content, /\/api\/openapi.json/);
|
||||
assert.match(content, /"persistAuthorization": false/);
|
||||
assert.match(content, /"validatorUrl": null/);
|
||||
}
|
||||
}
|
||||
const spec = await fetch(`${base}/api/openapi.json`);
|
||||
assert.equal(spec.status, 200);
|
||||
assert.match(spec.headers.get('content-type')!, /application\/json/);
|
||||
assert.deepEqual(await spec.json(), customerOpenApi);
|
||||
const redirect = await fetch(`${base}/api/docs`, { redirect: 'manual' });
|
||||
assert.equal(redirect.status, 301);
|
||||
assert.equal(redirect.headers.get('location'), '/api/docs/');
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { unassignedBirdMatchSchema, claimBirdSchema } from '../birdMembershipSchemas.js';
|
||||
import { behaviorTypeSchema, behaviorOccurrenceSchema } from '../behaviorSchemas.js';
|
||||
import { z } from 'zod';
|
||||
import { extendZodWithOpenApi, OpenAPIRegistry, OpenApiGeneratorV3, type RouteConfig } from '@asteasolutions/zod-to-openapi';
|
||||
import { birdSchema, workspaceMemberSchema, workspaceRoleSchema, flockNoteSchema, locationSearchSchema,
|
||||
weightSchema, vetVisitSchema, medicationSchema, medicationAdministrationSchema } from '../schemas.js';
|
||||
import * as responses from './responses.js';
|
||||
|
||||
extendZodWithOpenApi(z);
|
||||
const registry = new OpenAPIRegistry();
|
||||
registry.registerComponent('securitySchemes', 'IntegrationToken', {
|
||||
type: 'http', scheme: 'bearer', bearerFormat: 'flpt_…',
|
||||
description: 'Paste your integration token, without the Bearer prefix. Create it in FlockPal Settings → Integration tokens.',
|
||||
});
|
||||
const models = Object.fromEntries(Object.entries(responses).map(([name, schema]) => [name, registry.register(name.replace('Response', ''), schema)]));
|
||||
const error = registry.register('Error', z.object({
|
||||
error: z.string(), code: z.string().optional(),
|
||||
details: z.object({ formErrors: z.array(z.string()), fieldErrors: z.record(z.array(z.string())) }).optional(),
|
||||
}));
|
||||
const json = (schema: z.ZodTypeAny, example?: unknown) => ({ 'application/json': { schema, ...(example ? { example } : {}) } });
|
||||
const errors: Record<number, string> = {
|
||||
400: 'Invalid request.', 401: 'Missing, expired, revoked, or invalid integration token.',
|
||||
402: 'Workspace is read-only: subscription must be active/trialing, or rescue verification approved.',
|
||||
403: 'Insufficient token scope or workspace role.', 404: 'Resource not found in this workspace, or cannot be changed.',
|
||||
409: 'Conflict: duplicate band/tag ID, duplicate weight date, or memorialized bird is read-only.',
|
||||
500: 'Internal server error.', 502: 'Location provider request failed.', 503: 'Location search is not configured.',
|
||||
};
|
||||
type Endpoint = {
|
||||
method: 'get' | 'post' | 'put' | 'delete'; path: string; summary: string; tag: string;
|
||||
response?: z.ZodTypeAny; body?: z.ZodTypeAny; example?: unknown; query?: z.AnyZodObject;
|
||||
description?: string; status?: number; errors?: number[]; roles?: string[];
|
||||
};
|
||||
const careRoles = ['owner', 'assistant', 'caregiver'];
|
||||
function endpoint(config: Endpoint) {
|
||||
const write = config.method !== 'get';
|
||||
const params = Object.fromEntries([...config.path.matchAll(/\{(\w+)\}/g)].map((match) => [match[1], z.string().uuid()]));
|
||||
const responseMap: RouteConfig['responses'] = {
|
||||
[config.status ?? (config.method === 'delete' ? 204 : config.method === 'post' ? 201 : 200)]: {
|
||||
description: config.method === 'delete' ? 'Deleted successfully. No response body.' : 'Success.',
|
||||
...(config.response ? { content: json(config.response) } : {}),
|
||||
},
|
||||
429: { description: 'Rate limit exceeded. General limit: 300 requests per 15 minutes per IP; location search additionally allows 40 per 15 minutes.',
|
||||
headers: { 'Retry-After': { schema: { type: 'string' }, description: 'Seconds until retry.' } },
|
||||
content: { 'text/html': { schema: { type: 'string' } }, 'application/json': { schema: error } } },
|
||||
};
|
||||
for (const status of new Set([401, 500, ...(write ? [402, 403] : []), ...(config.body || config.query ? [400] : []), ...(config.errors ?? [])])) {
|
||||
responseMap[status] = { description: errors[status], content: json(error) };
|
||||
}
|
||||
registry.registerPath({
|
||||
method: config.method, path: config.path, summary: config.summary, tags: [config.tag],
|
||||
operationId: `${config.method}_${config.path.replace(/[{}]/g, '').replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_/, '')}`,
|
||||
description: [config.description, write ? `Requires a read_write token and an active writable workspace. Allowed roles: ${(config.roles ?? careRoles).join(', ')}.` : 'Accepts read_only or read_write integration tokens.'].filter(Boolean).join('\n\n'),
|
||||
security: [{ IntegrationToken: [] }],
|
||||
request: {
|
||||
...(Object.keys(params).length ? { params: z.object(params) } : {}),
|
||||
...(config.query ? { query: config.query } : {}),
|
||||
...(config.body ? { body: { required: true, content: json(config.body, config.example) } } : {}),
|
||||
},
|
||||
responses: responseMap,
|
||||
});
|
||||
}
|
||||
const one = (name: string, model: z.ZodTypeAny) => z.object({ [name]: model });
|
||||
const many = (name: string, model: z.ZodTypeAny) => one(name, z.array(model));
|
||||
endpoint({ method: 'get', path: '/workspace', summary: 'Get the token’s workspace', tag: 'Workspace', response: one('workspace', models.workspaceResponse) });
|
||||
endpoint({ method: 'get', path: '/workspace/members', summary: 'List workspace members', tag: 'Workspace', response: many('members', models.memberResponse) });
|
||||
endpoint({ method: 'post', path: '/workspace/members', summary: 'Add or update a workspace member', tag: 'Workspace', body: registry.register('MemberInput', workspaceMemberSchema), response: one('member', models.memberResponse), roles: ['owner', 'assistant'] });
|
||||
endpoint({ method: 'put', path: '/workspace/members/{memberId}', summary: 'Change a member’s role', tag: 'Workspace', body: z.object({ role: workspaceRoleSchema }), response: one('member', models.memberResponse), roles: ['owner', 'assistant'], errors: [404], description: 'Only the billing owner can promote collaborators to owner. Additional protections apply to changing your own or the billing owner’s membership.' });
|
||||
endpoint({ method: 'delete', path: '/workspace/members/{memberId}', summary: 'Remove a workspace member', tag: 'Workspace', roles: ['owner', 'assistant'], errors: [404], description: 'Protected memberships cannot be removed.' });
|
||||
endpoint({ method: 'get', path: '/notes', summary: 'List flock notes', tag: 'Notes', response: many('notes', models.noteResponse) });
|
||||
endpoint({ method: 'post', path: '/notes', summary: 'Create a flock note', tag: 'Notes', body: registry.register('NoteInput', flockNoteSchema), response: one('note', models.noteResponse), errors: [404], example: { body: 'Enjoyed a new enrichment activity today.' } });
|
||||
endpoint({ method: 'delete', path: '/notes/{noteId}', summary: 'Delete a flock note', tag: 'Notes', errors: [404] });
|
||||
endpoint({ method: 'get', path: '/locations/search', summary: 'Search for a location', tag: 'Locations', query: locationSearchSchema, response: many('results', models.locationResponse), errors: [502, 503], description: 'Search cities, regions, and countries. Requires 3–120 characters; returns up to three matches. Additional rate limit: 40 requests per 15 minutes per IP.' });
|
||||
endpoint({ method: 'get', path: '/birds/unassigned-match', summary: 'Check for an unassigned bird by band ID', tag: 'Birds', query: unassignedBirdMatchSchema, response: z.object({ available: z.boolean() }), errors: [403], description: 'Requires owner, assistant, or caregiver role. Returns only availability, not profile details. Matching ignores case and surrounding whitespace; partial and unknown IDs do not match.' });
|
||||
endpoint({ method: 'post', path: '/birds/claim', summary: 'Add an unassigned bird with its existing history', tag: 'Birds', body: claimBirdSchema, response: z.object({ bird: models.birdResponse, historyImported: z.literal(true) }), status: 200, errors: [409], description: 'Requires confirmHistory: true. Atomically assigns the existing bird to the current flock, preserving its ID, profile, photo, and history. Existing profile details are used. Birds already in a flock cannot be claimed.' });
|
||||
endpoint({ method: 'get', path: '/birds', summary: 'List active and memorialized birds', tag: 'Birds', response: z.object({ birds: z.array(models.birdResponse), memorializedBirds: z.array(models.birdResponse) }) });
|
||||
const birdInput = registry.register('BirdInput', birdSchema);
|
||||
const birdDescription = 'motivators and demotivators each allow up to three non-empty lines. hatchDay takes precedence over the legacy dateOfBirth field. photoDataUrl accepts an image data URL or HTTP(S) URL; returned photo links may expire.';
|
||||
endpoint({ method: 'post', path: '/birds', summary: 'Create a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [409], description: birdDescription, example: { name: 'Yoda', species: 'African grey' } });
|
||||
endpoint({ method: 'put', path: '/birds/{birdId}', summary: 'Update a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [404, 409], description: `Submit the full editable profile: omitted optional fields may be cleared or reset. ${birdDescription}` });
|
||||
endpoint({ method: 'delete', path: '/birds/{birdId}', summary: 'Remove a bird from its flock', tag: 'Birds', errors: [404, 409], description: 'Unassigns the bird without deleting its profile, photo, or care history. Bird-specific notes follow the bird; flock-wide notes and workspace audit logs stay in the old flock. Public sharing is disabled and pending transfers are revoked. An exact band ID match can later bring the bird and its history into a flock.' });
|
||||
endpoint({ method: 'get', path: '/birds/{birdId}/timeline', summary: 'List bird timeline events', tag: 'Birds', response: many('events', models.timelineResponse), errors: [404] });
|
||||
for (const resource of [
|
||||
{ path: 'weights', single: 'weight', plural: 'weights', id: 'weightId', tag: 'Weights', input: weightSchema, model: models.weightResponse },
|
||||
{ path: 'vet-visits', single: 'vetVisit', plural: 'vetVisits', id: 'visitId', tag: 'Vet visits', input: vetVisitSchema, model: models.vetVisitResponse },
|
||||
{ path: 'medications', single: 'medication', plural: 'medications', id: 'medicationId', tag: 'Medications', input: medicationSchema, model: models.medicationResponse },
|
||||
]) {
|
||||
const path = `/birds/{birdId}/${resource.path}`;
|
||||
const body = registry.register(`${resource.single}Input`, resource.input);
|
||||
const description = resource.path === 'medications' ? 'endDate must be on or after startDate. Supply 1–8 doseSchedule entries with unique application-defined keys; use a key as administrationSlot when recording a dose.' : undefined;
|
||||
endpoint({ method: 'get', path, summary: `List ${resource.tag.toLowerCase()}`, tag: resource.tag, response: many(resource.plural, resource.model),
|
||||
...(resource.path === 'weights' ? { query: z.object({ days: z.coerce.number().min(1).max(425).default(30) }), description: 'Lookback window in days; defaults to 30. Numeric values are clamped to 1–425. Returns an empty list when no matching records exist.' } : {}) });
|
||||
endpoint({ method: 'post', path, summary: `Create ${resource.single === 'vetVisit' ? 'a vet visit' : `a ${resource.single}`}`, tag: resource.tag, body, response: one(resource.single, resource.model), errors: [404, 409], description,
|
||||
...(resource.path === 'weights' ? { example: { weightGrams: 425, recordedOn: '2026-09-27', notes: 'Morning weight' } } : {}) });
|
||||
endpoint({ method: 'put', path: `${path}/{${resource.id}}`, summary: `Update ${resource.single === 'vetVisit' ? 'a vet visit' : `a ${resource.single}`}`, tag: resource.tag, body, response: one(resource.single, resource.model), errors: [404, 409],
|
||||
description: resource.path === 'weights' ? 'Only the three most recent weight records are editable. Older records return 404. One weight entry is allowed per bird per date.' : `Submit the full editable record; omitted optional fields may be reset. ${description ?? ''}` });
|
||||
if (resource.path !== 'weights') endpoint({ method: 'delete', path: `${path}/{${resource.id}}`, summary: `Delete ${resource.single === 'vetVisit' ? 'a vet visit' : 'a medication'}`, tag: resource.tag, errors: [404, 409] });
|
||||
}
|
||||
endpoint({ method: 'get', path: '/birds/{birdId}/medication-administrations', summary: 'List medication administrations', tag: 'Medications', response: many('administrations', models.administrationResponse) });
|
||||
endpoint({ method: 'post', path: '/birds/{birdId}/medications/{medicationId}/administrations', summary: 'Record or update a medication dose', tag: 'Medications', body: registry.register('AdministrationInput', medicationAdministrationSchema), response: one('administration', models.administrationResponse), errors: [404, 409], description: 'Creates or updates the record for this medication, date, and administrationSlot. Use a doseSchedule key for administrationSlot; it defaults to dose-1. Returns 201 for both creation and update.' });
|
||||
|
||||
const behaviorTypeResponse = registry.register('BehaviorType', z.object({
|
||||
id: z.string().uuid(), name: z.string(), description: z.string().nullable(), createdAt: z.string().datetime(),
|
||||
}));
|
||||
const behaviorResponse = registry.register('BehaviorOccurrence', z.object({
|
||||
id: z.string().uuid(), birdId: z.string().uuid(), behaviorTypeId: z.string().uuid(), behaviorName: z.string(),
|
||||
occurredAt: z.string().datetime(), durationSeconds: z.number().nullable(), severity: z.number().int().min(1).max(5).nullable(),
|
||||
notes: z.string().nullable(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
|
||||
}));
|
||||
endpoint({ method: 'get', path: '/birds/{birdId}/behavior-types', summary: 'List available behavior types', tag: 'Behavior Journal', response: many('behaviorTypes', behaviorTypeResponse), errors: [400, 404], description: 'Includes common behaviors, flock custom behaviors, and behaviors in this bird’s transferred history.' });
|
||||
endpoint({ method: 'post', path: '/birds/{birdId}/behavior-types', summary: 'Create a reusable flock behavior type', tag: 'Behavior Journal', body: behaviorTypeSchema, response: one('behaviorType', behaviorTypeResponse), errors: [404, 409], description: 'Names are unique within the flock, ignoring case. An existing type is returned for a duplicate name.' });
|
||||
endpoint({ method: 'get', path: '/birds/{birdId}/behaviors', summary: 'List behavior occurrences in a date range', tag: 'Behavior Journal', response: many('occurrences', behaviorResponse), query: z.object({ from: z.string().datetime({ offset: true }), to: z.string().datetime({ offset: true }), behaviorTypeId: z.string().uuid().optional() }), errors: [404], description: 'From is inclusive; to is exclusive. The range must be positive and at most 32 days. Send local month boundaries with their UTC offsets or converted to UTC. Results are newest first; individual events are never aggregated.' });
|
||||
endpoint({ method: 'post', path: '/birds/{birdId}/behaviors', summary: 'Record a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409], description: 'Duration is optional and measured in seconds. Intensity is optional, from 1 to 5. Occurrence timestamps require a time zone offset.' });
|
||||
endpoint({ method: 'put', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Edit a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409] });
|
||||
endpoint({ method: 'delete', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Delete a behavior occurrence', tag: 'Behavior Journal', errors: [400, 404, 409] });
|
||||
|
||||
export const customerOpenApi = new OpenApiGeneratorV3(registry.definitions).generateDocument({
|
||||
openapi: '3.0.3',
|
||||
info: { title: 'FlockPal Customer API', version: '0.1.0', description: `Connect your flock to scripts and automation tools such as n8n.
|
||||
|
||||
### Getting started
|
||||
1. Sign in to FlockPal and open Settings → Integration tokens.
|
||||
2. Create a read_only token for reading, or read_write for changes. Copy the secret when shown; it is only displayed once.
|
||||
3. Click Authorize and paste the token (without the Bearer prefix). Requests send Authorization: Bearer flpt_….
|
||||
|
||||
Tokens are scoped to the workspace where they were created and use the creating user’s current membership permissions. Create separate tokens for other workspaces. Expired or revoked tokens return 401.
|
||||
|
||||
Writes require read_write scope, an allowed role, and an active/trialing subscription or approved rescue workspace. Memorialized birds are read-only. Try it out sends real requests to this FlockPal instance, including changes and deletions; authorization is not persisted across reloads.
|
||||
|
||||
This reference covers customer integration endpoints. Manage tokens, authentication, billing, transfers, and memorialization in the FlockPal application. Photo URLs returned by the API can be used directly and may expire.
|
||||
|
||||
The general rate limit is 300 requests per 15 minutes per IP; location search also has a 40-request limit. On 429, wait for Retry-After before retrying.` },
|
||||
servers: [{ url: '/api', description: 'This FlockPal instance' }],
|
||||
tags: ['Workspace', 'Birds', 'Weights', 'Vet visits', 'Medications', 'Notes', 'Locations', 'Behavior Journal'].map((name) => ({ name })),
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { z } from 'zod';
|
||||
import { birdGenderSchema, workspaceRoleSchema } from '../schemas.js';
|
||||
|
||||
const id = z.string().uuid();
|
||||
const text = z.string().nullable();
|
||||
const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
const timestamp = z.string().datetime({ offset: true });
|
||||
export const locationResponse = z.object({
|
||||
label: text, city: text, region: text, country: text, countryCode: text,
|
||||
latitude: z.number().nullable(), longitude: z.number().nullable(),
|
||||
precision: z.enum(['city', 'region', 'country']).nullable(), verifiedAt: timestamp, provider: z.literal('mapbox').nullable(), providerPlaceId: text,
|
||||
});
|
||||
export const workspaceResponse = z.object({
|
||||
id: z.number().int(), name: z.string(), workspaceType: z.enum(['standard', 'rescue']), billingEmail: text,
|
||||
billingPlan: z.enum(['rescue_free', 'household_basic', 'household_plus', 'household_macaw', 'household_hyacinth_macaw']),
|
||||
billingInterval: z.enum(['monthly', 'yearly']),
|
||||
subscriptionStatus: z.enum(['active', 'trialing', 'past_due', 'canceled', 'unpaid', 'none']),
|
||||
stripeCustomerId: text, stripeSubscriptionId: text,
|
||||
rescueVerificationStatus: z.enum(['not_required', 'pending', 'approved', 'rejected']),
|
||||
createdAt: timestamp, updatedAt: timestamp,
|
||||
});
|
||||
export const memberResponse = z.object({
|
||||
id, workspaceId: z.number().int(), userId: id.nullable(), inviteEmail: z.string(), name: z.string(),
|
||||
role: workspaceRoleSchema, acceptedAt: timestamp.nullable(), createdAt: timestamp,
|
||||
});
|
||||
export const birdResponse = z.object({
|
||||
id, workspaceId: z.number().int(), name: z.string(), tagId: text, species: z.string(),
|
||||
motivators: text, demotivators: text, favoriteSnack: text, locationLabel: text,
|
||||
locationDetails: locationResponse.nullable(), vetClinicName: text, vetClinicAddress: text,
|
||||
vetAccountNumber: text, vetDoctorName: text, gender: birdGenderSchema,
|
||||
hatchDay: date.nullable(), dateOfBirth: date.nullable(), gotchaDay: date.nullable(), chartColor: z.string(),
|
||||
photoDataUrl: text.describe('Photo URL or legacy data URL. Storage-backed URLs expire; refresh the bird list to obtain a new URL.'),
|
||||
photoObjectKey: text, photoContentType: text, photoUpdatedAt: timestamp.nullable(),
|
||||
notifyOnDob: z.boolean(), notifyOnGotchaDay: z.boolean(), publicProfileCode: text, publicProfileEnabled: z.boolean(),
|
||||
memorializedAt: timestamp.nullable(), memorializedOn: date.nullable(), memorialNote: text,
|
||||
notifyOnMemorialDay: z.boolean(), createdAt: timestamp,
|
||||
latestWeightGrams: z.number().nullable(), latestRecordedOn: date.nullable(),
|
||||
});
|
||||
export const weightResponse = z.object({ id, birdId: id, weightGrams: z.number(), recordedOn: date, notes: text });
|
||||
export const vetVisitResponse = z.object({ id, birdId: id, visitedOn: date, clinicName: z.string(), reason: z.string(), notes: text });
|
||||
export const medicationResponse = z.object({
|
||||
id, birdId: id, name: z.string(), dosage: z.string(),
|
||||
frequency: z.enum(['once_daily', 'twice_daily', 'every_8_hours', 'every_6_hours', 'as_needed']),
|
||||
doseSchedule: z.array(z.object({ key: z.string(), label: z.string(), time: z.string() })),
|
||||
route: text, startDate: date, endDate: date.nullable(), notes: text, remindersEnabled: z.boolean(),
|
||||
});
|
||||
export const administrationResponse = z.object({
|
||||
id, medicationId: id, birdId: id, administeredOn: date, administrationSlot: z.string(),
|
||||
status: z.enum(['administered', 'missed']), notes: text, createdByUserId: id.nullable(), createdAt: timestamp,
|
||||
});
|
||||
export const noteResponse = z.object({
|
||||
id, workspaceId: z.number().int(), birdId: id.nullable(), birdName: text, title: z.string(), body: z.string(),
|
||||
createdByUserId: id.nullable(), createdByName: text, createdAt: timestamp, updatedAt: timestamp,
|
||||
});
|
||||
export const timelineResponse = z.object({
|
||||
id, birdId: id, eventType: z.enum(['profile_created', 'transferred', 'location_updated', 'owner_changed', 'manual_note', 'removed_from_flock', 'joined_flock']),
|
||||
fromWorkspaceId: z.number().int().nullable(), toWorkspaceId: z.number().int().nullable(),
|
||||
fromWorkspaceName: text, toWorkspaceName: text, fromOwnerEmail: text, toOwnerEmail: text,
|
||||
locationLabel: text, locationDetails: locationResponse.nullable(), note: text, eventDate: date,
|
||||
createdByUserId: id.nullable(), createdAt: timestamp,
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Express } from 'express';
|
||||
import helmet from 'helmet';
|
||||
import swaggerUi from 'swagger-ui-express';
|
||||
import { customerOpenApi } from './openapi.js';
|
||||
|
||||
// Mount before application middleware so docs do not consume API rate limits.
|
||||
// Swagger assets and initialization are served locally; no external validator is used.
|
||||
export function mountApiDocs(app: Express) {
|
||||
app.get('/api/openapi.json', helmet(), (_req, res) => res.json(customerOpenApi));
|
||||
app.use('/api/docs', helmet({
|
||||
contentSecurityPolicy: { directives: {
|
||||
'script-src': ["'self'"],
|
||||
'connect-src': ["'self'"],
|
||||
// Keep local HTTP development usable; production transport is handled by the proxy.
|
||||
'upgrade-insecure-requests': null,
|
||||
} },
|
||||
}), swaggerUi.serve, swaggerUi.setup(undefined, {
|
||||
customSiteTitle: 'FlockPal API Reference',
|
||||
swaggerOptions: {
|
||||
url: '/api/openapi.json', validatorUrl: null, persistAuthorization: false,
|
||||
displayRequestDuration: true, docExpansion: 'none',
|
||||
},
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import sharp from 'sharp';
|
||||
import type { WeightReminder } from '../reminders/weightReminders.js';
|
||||
import { getS3ImageStorageConfig } from '../storage/imageStorageConfig.js';
|
||||
import { getSignedS3ObjectUrl } from '../storage/s3Client.js';
|
||||
|
||||
const asset = (name: string) => new URL(`../../assets/${name}`, import.meta.url);
|
||||
const thumbnail = (content: Buffer) => sharp(content).rotate().resize(192, 192, { fit: 'cover' }).jpeg({ quality: 80 }).toBuffer();
|
||||
|
||||
export const loadWeightReminderPortrait = async (bird: Pick<WeightReminder, 'bird_id' | 'photo_object_key' | 'photo_data_url'>): Promise<Buffer> => {
|
||||
try {
|
||||
if (bird.photo_object_key) {
|
||||
const config = getS3ImageStorageConfig();
|
||||
if (config) {
|
||||
const response = await fetch(getSignedS3ObjectUrl({ config, objectKey: bird.photo_object_key, expiresInSeconds: 300 }), {
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Photo storage returned ${response.status}`);
|
||||
return await thumbnail(Buffer.from(await response.arrayBuffer()));
|
||||
}
|
||||
}
|
||||
const match = bird.photo_data_url?.match(/^data:image\/(?:png|jpe?g|webp|gif);base64,(.+)$/);
|
||||
if (match) return await thumbnail(Buffer.from(match[1], 'base64'));
|
||||
} catch {
|
||||
console.warn(`Unable to load weight reminder portrait for bird ${bird.bird_id}; using default portrait.`);
|
||||
}
|
||||
return thumbnail(await readFile(asset('yoda-default.png')));
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { buildEmailLayout } from './emailLayout.js';
|
||||
|
||||
test('shared layout escapes copy and embeds the app background and bird portrait', async () => {
|
||||
const mail = await buildEmailLayout({
|
||||
backgroundUrl: 'https://flockpal.test/email-background.png',
|
||||
eyebrow: 'Medication <reminder>', headline: 'Medication time for Kiwi & Peep',
|
||||
contentHtml: '<p>Morning at 8:00 AM</p>',
|
||||
action: { url: 'https://flockpal.test/?a=1&b=2', label: 'Open <FlockPal>' },
|
||||
bird: { id: 'bird-1', name: 'Kiwi & Peep', photo_data_url: null, photo_object_key: null },
|
||||
});
|
||||
const html = String(mail.html);
|
||||
assert.match(html, /Medication <reminder>/);
|
||||
assert.match(html, /Medication time for Kiwi & Peep/);
|
||||
assert.match(html, /a=1&b=2/);
|
||||
assert.match(html, /Open <FlockPal>/);
|
||||
assert.match(html, /Morning at 8:00 AM/);
|
||||
assert.match(html, /background="https:\/\/flockpal.test\/email-background.png"/);
|
||||
assert.match(html, /background-image:url\('https:\/\/flockpal.test\/email-background.png'\)/);
|
||||
assert.doesNotMatch(html, /flockpal-pattern|cid:flockpal-background/);
|
||||
assert.doesNotMatch(html, /48-hour|weights are overdue|data:image/);
|
||||
for (const attachment of mail.attachments ?? []) {
|
||||
assert.ok(html.includes(`cid:${attachment.cid}`));
|
||||
assert.equal(attachment.contentDisposition, 'inline');
|
||||
assert.ok(Buffer.isBuffer(attachment.content));
|
||||
}
|
||||
assert.equal((html.match(/<table\b/g) ?? []).length, (html.match(/<\/table>/g) ?? []).length);
|
||||
assert.equal((html.match(/<td\b/g) ?? []).length, (html.match(/<\/td>/g) ?? []).length);
|
||||
});
|
||||
|
||||
test('transactional layout omits optional portrait, action and reminder footer', async () => {
|
||||
const mail = await buildEmailLayout({ eyebrow: 'Rescue status', headline: 'Flock update', contentHtml: '<p>Status changed</p>' });
|
||||
assert.equal(mail.attachments?.length, 1);
|
||||
assert.doesNotMatch(String(mail.html), /bird-portrait|<a |48-hour/);
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import type { SendMailOptions } from 'nodemailer';
|
||||
import sharp from 'sharp';
|
||||
import { loadWeightReminderPortrait } from './birdPortrait.js';
|
||||
|
||||
export const escapeHtml = (value: string) => value.replace(/[&<>"']/g, char => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
||||
})[char]!);
|
||||
const asset = (name: string) => new URL(`../../assets/${name}`, import.meta.url);
|
||||
|
||||
export const buildEmailLayout = async ({ eyebrow, headline, preheader = headline, contentHtml, action, footer, bird, backgroundUrl = process.env.EMAIL_BACKGROUND_URL || new URL('/email-background.png', process.env.FRONTEND_URL || 'http://localhost:3000').href }: {
|
||||
eyebrow: string;
|
||||
headline: string;
|
||||
preheader?: string;
|
||||
/** Trusted markup; escape all dynamic values before passing them. */
|
||||
contentHtml: string;
|
||||
action?: { url: string; label: string };
|
||||
footer?: string;
|
||||
backgroundUrl?: string;
|
||||
bird?: { id: string; name: string; photo_data_url: string | null; photo_object_key: string | null };
|
||||
}): Promise<Pick<SendMailOptions, 'html' | 'attachments'>> => ({
|
||||
attachments: [
|
||||
{ filename: 'flockpal-logo.png', cid: 'flockpal-logo', contentType: 'image/png', contentDisposition: 'inline', content: await sharp(await readFile(asset('flockpal-logo.png'))).resize({ width: 480 }).png().toBuffer() },
|
||||
...(bird ? [{ filename: 'bird-portrait.jpg', cid: 'bird-portrait', contentType: 'image/jpeg', contentDisposition: 'inline' as const, content: await loadWeightReminderPortrait({ bird_id: bird.id, photo_data_url: bird.photo_data_url, photo_object_key: bird.photo_object_key }) }] : []),
|
||||
],
|
||||
html: `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
|
||||
<body style="margin:0;padding:0;background-color:#fef5e7;">
|
||||
<div style="display:none;max-height:0;overflow:hidden;mso-hide:all;">${escapeHtml(preheader)}</div>
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;background-color:#fef5e7;font-family:Arial,sans-serif;color:#1f2a2a;line-height:1.5;">
|
||||
<tr><td align="center" background="${escapeHtml(backgroundUrl)}" style="padding:24px 12px;background-color:#fef5e7;background-image:url('${escapeHtml(backgroundUrl)}');background-position:center top;background-repeat:repeat;background-size:100% auto;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:600px;background-color:#edf8ef;border:1px solid #d3e5d8;border-radius:24px;">
|
||||
<tr><td align="center" style="padding:24px;border-bottom:1px solid #d3e5d8;">
|
||||
<img src="cid:flockpal-logo" width="220" alt="FlockPal" style="display:block;width:220px;max-width:100%;height:auto;border:0;" />
|
||||
</td></tr>
|
||||
<tr><td style="padding:24px;">
|
||||
<p style="margin:0 0 8px;font-size:12px;font-weight:bold;letter-spacing:1.5px;color:#238a5a;text-transform:uppercase;">${escapeHtml(eyebrow)}</p>
|
||||
<h1 style="margin:0 0 12px;font-size:26px;line-height:1.2;word-break:break-word;">${escapeHtml(headline)}</h1>
|
||||
${bird ? `<img src="cid:bird-portrait" width="76" height="76" alt="${escapeHtml(bird.name)}" style="display:block;border:0;border-radius:16px;margin:0 0 16px;" />` : ''}
|
||||
${contentHtml}
|
||||
${action ? `<table role="presentation" cellspacing="0" cellpadding="0" style="margin-top:24px;"><tr><td bgcolor="#238a5a" style="border-radius:24px;text-align:center;"><a href="${escapeHtml(action.url)}" style="display:inline-block;padding:13px 22px;border:1px solid #238a5a;border-radius:24px;color:#ffffff;font-size:16px;font-weight:bold;text-decoration:none;">${escapeHtml(action.label)}</a></td></tr></table>` : ''}
|
||||
${footer ? `<p style="margin:20px 0 0;font-size:13px;color:#52645b;">${escapeHtml(footer)}</p>` : ''}
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="margin:16px 0 0;color:#52645b;font-size:12px;">FlockPal · A little care, every day.</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body></html>`,
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { test } from 'node:test';
|
||||
import sharp from 'sharp';
|
||||
import { buildWeightReminderEmail, loadWeightReminderPortrait } from './weightReminderEmail.js';
|
||||
import type { WeightReminder } from '../reminders/weightReminders.js';
|
||||
|
||||
const bird: WeightReminder = {
|
||||
bird_id: 'bird-1', workspace_id: 1, bird_name: 'Kiwi & <Peep>', species: 'Cockatiel',
|
||||
workspace_name: 'Our <Flock>', activity_at: '2026-09-01T12:00:00Z', recipient: 'owner@example.test',
|
||||
photo_data_url: null, photo_object_key: null,
|
||||
};
|
||||
|
||||
test('branded grouped email embeds distinct portraits and escapes dynamic content', async () => {
|
||||
const mail = await buildWeightReminderEmail([bird, { ...bird, bird_id: 'bird-2', bird_name: 'Yoda' }], 'https://flockpal.test/?a=1&b=2');
|
||||
assert.equal(mail.attachments?.length, 3);
|
||||
assert.deepEqual(mail.attachments?.map(a => a.cid), ['flockpal-logo', 'weight-bird-0', 'weight-bird-1']);
|
||||
for (const attachment of mail.attachments ?? []) {
|
||||
assert.equal(attachment.contentDisposition, 'inline');
|
||||
assert.ok(Buffer.isBuffer(attachment.content));
|
||||
assert.ok(String(mail.html).includes(`cid:${attachment.cid}`));
|
||||
}
|
||||
assert.match(String(mail.html), /Kiwi & <Peep>/);
|
||||
assert.match(String(mail.html), /Our <Flock>/);
|
||||
assert.match(String(mail.html), /a=1&b=2/);
|
||||
assert.match(String(mail.text), /Kiwi & <Peep>/);
|
||||
});
|
||||
|
||||
test('database portrait is resized and invalid photos fall back to the default', async () => {
|
||||
const source = await readFile(new URL('../../assets/yoda.png', import.meta.url));
|
||||
const photo = await loadWeightReminderPortrait({ ...bird, photo_data_url: `data:image/png;base64,${source.toString('base64')}` });
|
||||
const metadata = await sharp(photo).metadata();
|
||||
assert.equal(metadata.width, 192);
|
||||
assert.equal(metadata.height, 192);
|
||||
assert.equal(metadata.format, 'jpeg');
|
||||
assert.deepEqual(await loadWeightReminderPortrait({ ...bird, photo_data_url: 'data:image/png;base64,broken' }), await loadWeightReminderPortrait(bird));
|
||||
});
|
||||
|
||||
test('private S3 portrait is downloaded and embedded rather than linked', async (t) => {
|
||||
const env = { IMAGE_STORAGE_PROVIDER: 's3', S3_ENDPOINT: 'https://storage.example.test', S3_REGION: 'us-east-1', S3_BUCKET: 'portraits', S3_ACCESS_KEY_ID: 'test', S3_SECRET_ACCESS_KEY: 'test' };
|
||||
const previous = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]]));
|
||||
Object.assign(process.env, env);
|
||||
try {
|
||||
const source = await readFile(new URL('../../assets/yoda.png', import.meta.url));
|
||||
t.mock.method(globalThis, 'fetch', async (url: string) => {
|
||||
assert.match(String(url), /private-bird.png/);
|
||||
return new Response(source);
|
||||
});
|
||||
const photo = await loadWeightReminderPortrait({ ...bird, photo_object_key: 'private-bird.png' });
|
||||
assert.equal((await sharp(photo).metadata()).width, 192);
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(globalThis, 'fetch', async () => new Response('', { status: 404 }));
|
||||
assert.deepEqual(await loadWeightReminderPortrait({ ...bird, photo_object_key: 'missing.png' }), await loadWeightReminderPortrait(bird));
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(previous)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { buildEmailLayout, escapeHtml } from './emailLayout.js';
|
||||
import type { SendMailOptions } from 'nodemailer';
|
||||
import type { WeightReminder } from '../reminders/weightReminders.js';
|
||||
import { loadWeightReminderPortrait } from './birdPortrait.js';
|
||||
export { loadWeightReminderPortrait } from './birdPortrait.js';
|
||||
|
||||
export const buildWeightReminderEmail = async (
|
||||
reminders: WeightReminder[],
|
||||
frontendUrl: string,
|
||||
loadPortrait = loadWeightReminderPortrait,
|
||||
): Promise<Pick<SendMailOptions, 'subject' | 'text' | 'html' | 'attachments'>> => {
|
||||
if (!reminders.length) throw new Error('A weight reminder email requires at least one bird');
|
||||
const flock = reminders[0].workspace_name;
|
||||
const attachments: NonNullable<SendMailOptions['attachments']> = [];
|
||||
const rows: string[] = [];
|
||||
for (const [index, bird] of reminders.entries()) {
|
||||
const cid = `weight-bird-${index}`;
|
||||
attachments.push({ filename: `${cid}.jpg`, cid, content: await loadPortrait(bird), contentType: 'image/jpeg', contentDisposition: 'inline' });
|
||||
rows.push(`<tr>
|
||||
<td width="88" style="padding:16px 12px 16px 0;border-bottom:1px solid #d3e5d8;vertical-align:middle;">
|
||||
<img src="cid:${cid}" width="76" height="76" alt="${escapeHtml(bird.bird_name)}" style="display:block;border:0;border-radius:16px;" />
|
||||
</td>
|
||||
<td style="padding:16px 0;border-bottom:1px solid #d3e5d8;vertical-align:middle;word-break:break-word;">
|
||||
<p style="margin:0 0 4px;font-size:18px;font-weight:bold;color:#1f2a2a;">${escapeHtml(bird.bird_name)}</p>
|
||||
<p style="margin:0;font-size:14px;color:#52645b;">${escapeHtml(bird.species)}</p>
|
||||
<p style="margin:6px 0 0;font-size:13px;color:#63562d;">Ready for a weight check</p>
|
||||
</td>
|
||||
</tr>`);
|
||||
}
|
||||
const layout = await buildEmailLayout({
|
||||
eyebrow: 'Daily weight reminder',
|
||||
headline: 'A little check-in for your flock',
|
||||
preheader: `A little check-in for ${flock}: it's time to log your birds' weights.`,
|
||||
contentHtml: `<p style="margin:0 0 16px;font-size:16px;">These birds in <strong>${escapeHtml(flock)}</strong> haven't had a new weight entry in at least 48 hours.</p><table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;table-layout:fixed;">${rows.join('')}</table>`,
|
||||
action: { url: frontendUrl, label: 'Record their weights' },
|
||||
footer: "You'll receive a daily reminder while weights are overdue. A new weight entry restarts the 48-hour clock.",
|
||||
});
|
||||
return {
|
||||
subject: `Weight reminders for ${flock}`,
|
||||
text: `Daily weight reminder — ${flock}\n\nThese birds haven't had a new weight entry in at least 48 hours:\n\n${reminders.map(bird => `- ${bird.bird_name} (${bird.species})`).join('\n')}\n\nOpen FlockPal to record their weights: ${frontendUrl}\n\nYou'll receive a daily reminder while weights are overdue.`,
|
||||
...layout,
|
||||
attachments: [...(layout.attachments ?? []), ...attachments],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Queue } from 'bullmq';
|
||||
import { getReminderDate } from '../reminders/reminderDate.js';
|
||||
import { redisConnection } from './redisConnection.js';
|
||||
|
||||
export const weightReminderQueueName = 'weight-reminders';
|
||||
export const weightReminderQueue = new Queue(weightReminderQueueName, {
|
||||
connection: redisConnection,
|
||||
defaultJobOptions: {
|
||||
attempts: 3,
|
||||
backoff: { type: 'exponential', delay: 60_000 },
|
||||
removeOnComplete: 100,
|
||||
removeOnFail: 1000,
|
||||
},
|
||||
});
|
||||
|
||||
export const enqueueDailyWeightReminder = (now = new Date()) => {
|
||||
const runDate = getReminderDate(now);
|
||||
return weightReminderQueue.add('check-overdue-weights', { runDate }, {
|
||||
jobId: `weight-reminders-${runDate}`,
|
||||
});
|
||||
};
|
||||
|
||||
export const startWeightReminderScheduler = async () => {
|
||||
// Remove the previous five-minute schedule during upgrades and when disabled.
|
||||
await weightReminderQueue.removeJobScheduler('weight-reminders');
|
||||
if (process.env.WEIGHT_REMINDERS_ENABLED === 'false') return () => {};
|
||||
await weightReminderQueue.setGlobalConcurrency(1);
|
||||
let lastRunDate = '';
|
||||
const runIfNeeded = async () => {
|
||||
const now = new Date();
|
||||
const runDate = getReminderDate(now);
|
||||
if (lastRunDate === runDate) return;
|
||||
await enqueueDailyWeightReminder(now);
|
||||
lastRunDate = runDate;
|
||||
};
|
||||
const check = () => {
|
||||
void runIfNeeded().catch(error => console.error('Weight reminder scheduler failed', error));
|
||||
};
|
||||
const startup = setTimeout(check, 15_000);
|
||||
const interval = setInterval(check, 60 * 60_000);
|
||||
return () => { clearTimeout(startup); clearInterval(interval); };
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { getReminderDate } from './reminderDate.js';
|
||||
|
||||
test('daily reminder dates use the configured zone across midnight and DST', () => {
|
||||
const previous = process.env.MILESTONE_REMINDER_TIME_ZONE;
|
||||
try {
|
||||
process.env.MILESTONE_REMINDER_TIME_ZONE = 'America/New_York';
|
||||
assert.equal(getReminderDate(new Date('2026-09-06T03:59:59Z')), '2026-09-05');
|
||||
assert.equal(getReminderDate(new Date('2026-09-06T04:00:00Z')), '2026-09-06');
|
||||
assert.equal(getReminderDate(new Date('2026-03-08T06:59:59Z')), '2026-03-08');
|
||||
assert.equal(getReminderDate(new Date('2026-03-08T07:00:00Z')), '2026-03-08');
|
||||
assert.equal(getReminderDate(new Date('2026-11-01T05:30:00Z')), '2026-11-01');
|
||||
assert.equal(getReminderDate(new Date('2026-11-01T06:30:00Z')), '2026-11-01');
|
||||
process.env.MILESTONE_REMINDER_TIME_ZONE = 'UTC';
|
||||
assert.equal(getReminderDate(new Date('2026-09-06T03:59:59Z')), '2026-09-06');
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.MILESTONE_REMINDER_TIME_ZONE;
|
||||
else process.env.MILESTONE_REMINDER_TIME_ZONE = previous;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
export const getReminderTimeZone = () => process.env.MILESTONE_REMINDER_TIME_ZONE?.trim() || 'America/New_York';
|
||||
|
||||
export const getReminderDate = (now = new Date()) => new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: getReminderTimeZone(), year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
}).format(now);
|
||||
@@ -0,0 +1,61 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { runWeightReminders, type WeightReminder } from './weightReminders.js';
|
||||
|
||||
const bird = (id: string, workspace = 1, recipient = 'owner@example.com'): WeightReminder => ({
|
||||
species: 'Cockatiel', photo_data_url: null, photo_object_key: null,
|
||||
bird_id: id, workspace_id: workspace, recipient,
|
||||
bird_name: id, workspace_name: `Flock ${workspace}`, activity_at: '2026-09-01T12:00:00Z',
|
||||
});
|
||||
|
||||
test('groups overdue birds into one email per flock and recipient', async () => {
|
||||
const sent: WeightReminder[][] = [];
|
||||
const finished: boolean[] = [];
|
||||
const result = await runWeightReminders(async (birds) => { sent.push(birds); return true; }, {
|
||||
list: async () => [bird('a'), bird('b'), bird('c', 2), bird('a', 1, 'caregiver@example.com')],
|
||||
claim: async () => true,
|
||||
finish: async (_token, delivered) => { finished.push(delivered); },
|
||||
});
|
||||
assert.deepEqual(sent.map((group) => group.map((item) => item.bird_id)), [['a', 'b'], ['c'], ['a']]);
|
||||
assert.deepEqual(finished, [true, true, true, true]);
|
||||
assert.equal(result.sent, 3);
|
||||
});
|
||||
|
||||
test('omits birds whose claim was lost or whose weight changed', async () => {
|
||||
const sent: WeightReminder[][] = [];
|
||||
await runWeightReminders(async (birds) => { sent.push(birds); return true; }, {
|
||||
list: async () => [bird('a'), bird('b')],
|
||||
claim: async (reminder) => reminder.bird_id === 'b', finish: async () => {},
|
||||
});
|
||||
assert.deepEqual(sent.map((group) => group.map((item) => item.bird_id)), [['b']]);
|
||||
});
|
||||
|
||||
test('does not email when all claims are unavailable', async () => {
|
||||
await runWeightReminders(async () => { assert.fail('Unexpected email'); }, {
|
||||
list: async () => [bird('a')], claim: async () => false, finish: async () => {},
|
||||
});
|
||||
});
|
||||
|
||||
test('missing SMTP releases all claims without recording delivery', async () => {
|
||||
const finished: boolean[] = [];
|
||||
const result = await runWeightReminders(async () => false, {
|
||||
list: async () => [bird('a'), bird('b')], claim: async () => true,
|
||||
finish: async (_token, delivered) => { finished.push(delivered); },
|
||||
});
|
||||
assert.deepEqual(finished, [false, false]);
|
||||
assert.equal(result.sent, 0);
|
||||
});
|
||||
|
||||
test('SMTP failure releases claims and still processes other flocks', async () => {
|
||||
const finished: boolean[] = [];
|
||||
const result = await runWeightReminders(async (birds) => {
|
||||
if (birds[0].workspace_id === 1) throw new Error('SMTP unavailable');
|
||||
return true;
|
||||
}, {
|
||||
list: async () => [bird('a'), bird('b'), bird('c', 2)], claim: async () => true,
|
||||
finish: async (_token, delivered) => { finished.push(delivered); },
|
||||
});
|
||||
assert.deepEqual(finished, [false, false, true]);
|
||||
assert.equal(result.sent, 1);
|
||||
assert.equal(result.failed, 1);
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { getReminderTimeZone } from './reminderDate.js';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { db } from '../db/client.js';
|
||||
|
||||
export type WeightReminder = {
|
||||
bird_id: string;
|
||||
workspace_id: number;
|
||||
bird_name: string;
|
||||
species: string;
|
||||
photo_data_url: string | null;
|
||||
photo_object_key: string | null;
|
||||
workspace_name: string;
|
||||
activity_at: string;
|
||||
recipient: string;
|
||||
};
|
||||
|
||||
// Use entry creation time: recorded_on is a date and cannot measure elapsed hours.
|
||||
// Editing an existing entry does not reset the reminder clock.
|
||||
export const listDueWeightReminders = async () => {
|
||||
const result = await db.query<WeightReminder>(`
|
||||
WITH activity AS (
|
||||
SELECT birds.id AS bird_id, birds.workspace_id, birds.name AS bird_name,
|
||||
workspaces.name AS workspace_name,
|
||||
GREATEST(birds.created_at, COALESCE(MAX(weight_records.created_at), birds.created_at)) AS activity_at
|
||||
FROM birds
|
||||
JOIN workspaces ON workspaces.id = birds.workspace_id
|
||||
LEFT JOIN weight_records ON weight_records.bird_id = birds.id
|
||||
WHERE birds.memorialized_at IS NULL
|
||||
GROUP BY birds.id, workspaces.name
|
||||
), recipients AS (
|
||||
SELECT DISTINCT workspace_id, LOWER(TRIM(users.email)) AS recipient
|
||||
FROM workspace_members
|
||||
JOIN users ON users.id = workspace_members.user_id
|
||||
WHERE accepted_at IS NOT NULL
|
||||
AND role IN ('owner', 'assistant', 'caregiver')
|
||||
)
|
||||
SELECT activity.bird_id, activity.workspace_id, activity.bird_name, activity.workspace_name,
|
||||
activity.activity_at::text, recipients.recipient, birds.species, birds.photo_data_url, birds.photo_object_key
|
||||
FROM activity
|
||||
JOIN recipients USING (workspace_id)
|
||||
JOIN birds ON birds.id = activity.bird_id
|
||||
WHERE activity_at <= CURRENT_TIMESTAMP - INTERVAL '48 hours'
|
||||
AND recipients.recipient <> ''
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM weight_reminder_deliveries d
|
||||
WHERE d.bird_id = activity.bird_id AND d.workspace_id = activity.workspace_id
|
||||
AND d.activity_at = activity.activity_at AND d.recipient = recipients.recipient
|
||||
AND ((d.delivered_at AT TIME ZONE $1)::date >= (CURRENT_TIMESTAMP AT TIME ZONE $1)::date
|
||||
OR (d.delivered_at IS NULL AND d.claimed_at > CURRENT_TIMESTAMP - INTERVAL '15 minutes'))
|
||||
)
|
||||
ORDER BY activity.workspace_id, activity.bird_id, recipients.recipient
|
||||
`, [getReminderTimeZone()]);
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
export const claimWeightReminder = async (reminder: WeightReminder, token: string) => {
|
||||
const result = await db.query(`
|
||||
INSERT INTO weight_reminder_deliveries (bird_id, workspace_id, activity_at, recipient, claim_token)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM birds
|
||||
WHERE id = $1 AND workspace_id = $2 AND memorialized_at IS NULL
|
||||
AND GREATEST(created_at, COALESCE((SELECT MAX(created_at) FROM weight_records WHERE bird_id = $1), created_at)) = $3::timestamptz
|
||||
)
|
||||
ON CONFLICT (bird_id, workspace_id, activity_at, recipient) DO UPDATE
|
||||
SET claim_token = EXCLUDED.claim_token, claimed_at = CURRENT_TIMESTAMP, delivered_at = NULL
|
||||
WHERE (weight_reminder_deliveries.delivered_at AT TIME ZONE $6)::date < (CURRENT_TIMESTAMP AT TIME ZONE $6)::date
|
||||
OR (weight_reminder_deliveries.delivered_at IS NULL
|
||||
AND weight_reminder_deliveries.claimed_at <= CURRENT_TIMESTAMP - INTERVAL '15 minutes')
|
||||
RETURNING bird_id
|
||||
`, [reminder.bird_id, reminder.workspace_id, reminder.activity_at, reminder.recipient, token, getReminderTimeZone()]);
|
||||
return Boolean(result.rowCount);
|
||||
};
|
||||
|
||||
export const finishWeightReminder = async (token: string, delivered: boolean) => {
|
||||
if (delivered) {
|
||||
await db.query('UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP WHERE claim_token = $1', [token]);
|
||||
} else {
|
||||
await db.query('DELETE FROM weight_reminder_deliveries WHERE claim_token = $1 AND delivered_at IS NULL', [token]);
|
||||
}
|
||||
};
|
||||
|
||||
type Dependencies = {
|
||||
list: typeof listDueWeightReminders;
|
||||
claim: typeof claimWeightReminder;
|
||||
finish: typeof finishWeightReminder;
|
||||
};
|
||||
|
||||
export const runWeightReminders = async (
|
||||
send: (reminders: WeightReminder[]) => Promise<boolean>,
|
||||
dependencies: Dependencies = { list: listDueWeightReminders, claim: claimWeightReminder, finish: finishWeightReminder },
|
||||
) => {
|
||||
const reminders = await dependencies.list();
|
||||
const result = { checked: reminders.length, sent: 0, skipped: 0, failed: 0 };
|
||||
const groups = new Map<string, WeightReminder[]>();
|
||||
for (const reminder of reminders) {
|
||||
const key = JSON.stringify([reminder.workspace_id, reminder.recipient]);
|
||||
groups.set(key, [...(groups.get(key) ?? []), reminder]);
|
||||
}
|
||||
for (const group of groups.values()) {
|
||||
const claimed: { reminder: WeightReminder; token: string }[] = [];
|
||||
let delivered = false;
|
||||
try {
|
||||
for (const reminder of group) {
|
||||
const token = randomUUID();
|
||||
if (await dependencies.claim(reminder, token)) claimed.push({ reminder, token });
|
||||
else result.skipped += 1;
|
||||
}
|
||||
if (!claimed.length) continue;
|
||||
delivered = await send(claimed.map(({ reminder }) => reminder));
|
||||
for (const { token } of claimed) await dependencies.finish(token, delivered);
|
||||
if (delivered) result.sent += 1;
|
||||
else result.skipped += claimed.length;
|
||||
} catch (error) {
|
||||
result.failed += 1;
|
||||
// Keep leases if SMTP accepted the email but saving delivery failed.
|
||||
if (!delivered) {
|
||||
for (const { token } of claimed) {
|
||||
await dependencies.finish(token, false).catch((cleanupError) => console.error('Weight reminder claim cleanup failed', cleanupError));
|
||||
}
|
||||
}
|
||||
console.error(`Weight reminder failed for flock ${group[0].workspace_id}`, error);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import { db } from '../db/client.js';
|
||||
import type { BehaviorInput, BehaviorType, BehaviorOccurrence } from '../behaviorSchemas.js';
|
||||
|
||||
const typeFields = `id, name, description, created_at AS "createdAt"`;
|
||||
const occurrenceFields = `o.id, o.bird_id AS "birdId", o.behavior_type_id AS "behaviorTypeId",
|
||||
t.name AS "behaviorName", o.occurred_at AS "occurredAt", o.duration_seconds AS "durationSeconds",
|
||||
o.severity, o.notes, o.created_at AS "createdAt", o.updated_at AS "updatedAt"`;
|
||||
|
||||
export async function listBehaviorTypes(workspaceId: number, birdId: string) {
|
||||
// Include types used by this bird before a flock transfer, without exposing other flock types.
|
||||
return (await db.query<BehaviorType>(`SELECT ${typeFields} FROM behavior_types t
|
||||
WHERE is_default OR workspace_id = $1 OR EXISTS (
|
||||
SELECT 1 FROM behavior_occurrences o JOIN birds b ON b.id = o.bird_id
|
||||
WHERE o.behavior_type_id = t.id AND b.id = $2 AND b.workspace_id = $1)
|
||||
ORDER BY name`, [workspaceId, birdId])).rows;
|
||||
}
|
||||
export async function createBehaviorType(workspaceId: number, name: string, description?: string | null) {
|
||||
return (await db.query<BehaviorType>(`INSERT INTO behavior_types (workspace_id, name, description) VALUES ($1, $2, $3)
|
||||
ON CONFLICT (workspace_id, lower(name)) WHERE workspace_id IS NOT NULL
|
||||
DO UPDATE SET name = behavior_types.name RETURNING ${typeFields}`, [workspaceId, name, description || null])).rows[0];
|
||||
}
|
||||
export async function listBehaviorOccurrences(birdId: string, workspaceId: number, from: string, to: string, typeId?: string) {
|
||||
return (await db.query<BehaviorOccurrence>(`SELECT ${occurrenceFields} FROM behavior_occurrences o
|
||||
JOIN birds b ON b.id = o.bird_id JOIN behavior_types t ON t.id = o.behavior_type_id
|
||||
WHERE b.id = $1 AND b.workspace_id = $2 AND o.occurred_at >= $3 AND o.occurred_at < $4
|
||||
AND ($5::uuid IS NULL OR o.behavior_type_id = $5) ORDER BY o.occurred_at DESC, o.id`,
|
||||
[birdId, workspaceId, from, to, typeId || null])).rows;
|
||||
}
|
||||
export async function saveBehaviorOccurrence(birdId: string, workspaceId: number, input: BehaviorInput, id?: string) {
|
||||
const params = [birdId, workspaceId, input.behaviorTypeId, input.occurredAt, input.durationSeconds ?? null, input.severity ?? null, input.notes || null];
|
||||
// Keep authorization in the mutation as well as the route to protect against concurrent transfers.
|
||||
const allowed = `EXISTS (SELECT 1 FROM birds b WHERE b.id = $1 AND b.workspace_id = $2 AND b.memorialized_at IS NULL)
|
||||
AND EXISTS (SELECT 1 FROM behavior_types t WHERE t.id = $3 AND
|
||||
(t.is_default OR t.workspace_id = $2 OR EXISTS
|
||||
(SELECT 1 FROM behavior_occurrences previous WHERE previous.bird_id = $1 AND previous.behavior_type_id = t.id)))`;
|
||||
const mutation = id
|
||||
? `UPDATE behavior_occurrences SET behavior_type_id = $3, occurred_at = $4, duration_seconds = $5,
|
||||
severity = $6, notes = $7, updated_at = CURRENT_TIMESTAMP WHERE bird_id = $1 AND id = $8 AND ${allowed} RETURNING *`
|
||||
: `INSERT INTO behavior_occurrences (bird_id, behavior_type_id, occurred_at, duration_seconds, severity, notes)
|
||||
SELECT $1, $3, $4, $5, $6, $7 WHERE ${allowed} RETURNING *`;
|
||||
return (await db.query<BehaviorOccurrence>(`WITH saved AS (${mutation}) SELECT ${occurrenceFields}
|
||||
FROM saved o JOIN behavior_types t ON t.id = o.behavior_type_id`, id ? [...params, id] : params)).rows[0];
|
||||
}
|
||||
export async function deleteBehaviorOccurrence(birdId: string, workspaceId: number, id: string) {
|
||||
return (await db.query<{ id: string }>(`DELETE FROM behavior_occurrences o USING birds b WHERE o.bird_id = b.id
|
||||
AND b.id = $1 AND b.workspace_id = $2 AND b.memorialized_at IS NULL AND o.id = $3 RETURNING o.id`, [birdId, workspaceId, id])).rows[0];
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { db } from '../db/client.js';
|
||||
|
||||
// Only reveal whether an exact normalized band match is available, never its profile or former flock.
|
||||
export async function hasUnassignedBird(tagId: string): Promise<boolean> {
|
||||
const result = await db.query<{ id: string }>(
|
||||
`SELECT id FROM birds WHERE workspace_id IS NULL AND memorialized_at IS NULL
|
||||
AND LOWER(BTRIM(tag_id)) = LOWER(BTRIM($1)) LIMIT 1`, [tagId],
|
||||
);
|
||||
return result.rows.length > 0;
|
||||
}
|
||||
|
||||
export async function removeBirdFromFlock(birdId: string, workspaceId: number, userId: string): Promise<boolean> {
|
||||
return db.transaction(async (client) => {
|
||||
const result = await client.query<{ id: string }>(
|
||||
`UPDATE birds SET workspace_id = NULL, public_profile_enabled = FALSE
|
||||
WHERE id = $1 AND workspace_id = $2 AND memorialized_at IS NULL RETURNING id`, [birdId, workspaceId],
|
||||
);
|
||||
if (!result.rows.length) return false;
|
||||
await client.query(`UPDATE flock_notes SET workspace_id = NULL WHERE bird_id = $1`, [birdId]);
|
||||
await client.query(`UPDATE bird_transfer_codes SET revoked_at = CURRENT_TIMESTAMP
|
||||
WHERE bird_id = $1 AND completed_at IS NULL AND revoked_at IS NULL`, [birdId]);
|
||||
await client.query(`DELETE FROM pending_bird_transfers WHERE bird_id = $1 AND completed_at IS NULL`, [birdId]);
|
||||
await client.query(`INSERT INTO bird_timeline_events
|
||||
(bird_id, event_type, from_workspace_id, from_workspace_name, note, created_by_user_id)
|
||||
SELECT $1, 'removed_from_flock', id, name, 'Removed from flock; profile and history retained.', $3
|
||||
FROM workspaces WHERE id = $2`, [birdId, workspaceId, userId]);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export async function claimUnassignedBird(tagId: string, workspaceId: number, userId: string): Promise<string | null> {
|
||||
return db.transaction(async (client) => {
|
||||
// The row lock and repeated unassigned predicate prevent competing flocks from claiming the same bird.
|
||||
const match = await client.query<{ id: string }>(
|
||||
`SELECT id FROM birds WHERE workspace_id IS NULL AND memorialized_at IS NULL
|
||||
AND LOWER(BTRIM(tag_id)) = LOWER(BTRIM($1)) FOR UPDATE`, [tagId],
|
||||
);
|
||||
if (!match.rows.length) return null;
|
||||
const birdId = match.rows[0].id;
|
||||
const claimed = await client.query(`UPDATE birds SET workspace_id = $2, public_profile_enabled = FALSE
|
||||
WHERE id = $1 AND workspace_id IS NULL RETURNING id`, [birdId, workspaceId]);
|
||||
if (!claimed.rows.length) return null;
|
||||
await client.query(`UPDATE flock_notes SET workspace_id = $2 WHERE bird_id = $1 AND workspace_id IS NULL`, [birdId, workspaceId]);
|
||||
await client.query(`INSERT INTO bird_timeline_events
|
||||
(bird_id, event_type, to_workspace_id, to_workspace_name, note, created_by_user_id)
|
||||
SELECT $1, 'joined_flock', id, name, 'Added by matching band ID; existing profile and history retained.', $3
|
||||
FROM workspaces WHERE id = $2`, [birdId, workspaceId, userId]);
|
||||
return birdId;
|
||||
});
|
||||
}
|
||||
@@ -789,18 +789,6 @@ export const updateMemorialReminderPreference = async ({
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const deleteBird = async (birdId: string, workspaceId: number) => {
|
||||
const result = await db.query<{ id: string }>(
|
||||
`DELETE FROM birds
|
||||
WHERE id = $1
|
||||
AND workspace_id = $2
|
||||
RETURNING id`,
|
||||
[birdId, workspaceId],
|
||||
);
|
||||
|
||||
return Boolean(result.rowCount);
|
||||
};
|
||||
|
||||
export const transferBirdToWorkspace = async (birdId: string, sourceWorkspaceId: number, targetWorkspaceId: number) => {
|
||||
const result = await db.query<BirdRow>(
|
||||
`UPDATE birds
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// Shared runtime validation and API documentation schemas.
|
||||
export const dateStringSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
export const chartColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/);
|
||||
export const photoDataUrlSchema = z
|
||||
.string()
|
||||
.regex(/^data:image\/(?:png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$/)
|
||||
.max(1_500_000);
|
||||
export const photoUrlSchema = z.string().trim().url().max(2000);
|
||||
|
||||
export const magicLinkRequestSchema = z.object({
|
||||
name: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
email: z.string().trim().email().max(255),
|
||||
redirectTo: z.string().trim().url().max(2000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const switchWorkspaceSchema = z.object({
|
||||
workspaceId: z.coerce.number().int().positive(),
|
||||
});
|
||||
|
||||
export const workspaceTypeSchema = z.enum(['standard', 'rescue']);
|
||||
export const workspaceRoleSchema = z.enum(['owner', 'assistant', 'caregiver', 'viewer']);
|
||||
export const billingPlanSchema = z.enum(['household_basic', 'household_plus', 'household_macaw', 'household_hyacinth_macaw']);
|
||||
export const billingIntervalSchema = z.enum(['monthly', 'yearly']);
|
||||
export const integrationTokenScopeSchema = z.enum(['read_only', 'read_write']);
|
||||
export const birdGenderSchema = z.enum(['unknown', 'male', 'female', 'male_dna', 'female_dna']);
|
||||
export const rescueVerificationStatusSchema = z.enum(['pending', 'approved', 'rejected']);
|
||||
export const rescueOnboardingSchema = z.object({
|
||||
name: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
city: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
state: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
ein: z.string().trim().max(32).optional().or(z.literal('')),
|
||||
website: z.string().trim().url().max(2000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const workspaceSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
workspaceType: workspaceTypeSchema,
|
||||
billingEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
billingPlan: billingPlanSchema.optional(),
|
||||
billingInterval: billingIntervalSchema.optional(),
|
||||
rescueOnboarding: rescueOnboardingSchema.optional(),
|
||||
});
|
||||
|
||||
export const createWorkspaceSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
workspaceType: workspaceTypeSchema,
|
||||
billingEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
billingPlan: billingPlanSchema.optional(),
|
||||
billingInterval: billingIntervalSchema.optional(),
|
||||
rescueOnboarding: rescueOnboardingSchema.optional(),
|
||||
});
|
||||
|
||||
export const workspaceMemberSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
email: z.string().trim().email().max(255),
|
||||
role: workspaceRoleSchema,
|
||||
});
|
||||
|
||||
export const flockTransferSchema = z.object({
|
||||
destinationOwnerEmail: z.string().trim().email().max(255),
|
||||
});
|
||||
|
||||
export const lostBirdReportSchema = z.object({
|
||||
tagId: z.string().trim().min(1).max(80),
|
||||
finderName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
finderEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
foundLocation: z.string().trim().max(255).optional().or(z.literal('')),
|
||||
message: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const publicProfileCodeSchema = z.string().trim().regex(/^[A-Za-z0-9_-]{8,32}$/);
|
||||
export const birdTransferCodeSchema = z.string().trim().regex(/^[A-Za-z0-9_-]{12,32}$/);
|
||||
export const birdProfileListSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(1000)
|
||||
.refine(
|
||||
(value) => value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean).length <= 3,
|
||||
'Use no more than three list items.',
|
||||
)
|
||||
.optional()
|
||||
.or(z.literal(''));
|
||||
|
||||
export const verifiedLocationDetailsSchema = z
|
||||
.object({
|
||||
label: z.string().trim().max(220).optional().or(z.literal('')),
|
||||
city: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
region: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
country: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
countryCode: z.string().trim().max(2).optional().or(z.literal('')),
|
||||
latitude: z.coerce.number().min(-90).max(90).optional().nullable().or(z.literal('')),
|
||||
longitude: z.coerce.number().min(-180).max(180).optional().nullable().or(z.literal('')),
|
||||
precision: z.enum(['city', 'region', 'country']).optional(),
|
||||
provider: z.literal('mapbox').optional().nullable(),
|
||||
providerPlaceId: z.string().trim().max(220).optional().or(z.literal('')),
|
||||
})
|
||||
.optional()
|
||||
.nullable();
|
||||
|
||||
export const locationSearchSchema = z.object({
|
||||
q: z.string().trim().min(3).max(120),
|
||||
});
|
||||
|
||||
export const birdSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
tagId: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
species: z.string().trim().min(1).max(120),
|
||||
motivators: birdProfileListSchema,
|
||||
demotivators: birdProfileListSchema,
|
||||
favoriteSnack: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationLabel: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationDetails: verifiedLocationDetailsSchema,
|
||||
vetClinicName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
vetClinicAddress: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
vetAccountNumber: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
vetDoctorName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
gender: birdGenderSchema.optional(),
|
||||
hatchDay: dateStringSchema.optional().or(z.literal('')),
|
||||
dateOfBirth: dateStringSchema.optional().or(z.literal('')),
|
||||
gotchaDay: dateStringSchema.optional().or(z.literal('')),
|
||||
chartColor: chartColorSchema.optional(),
|
||||
photoDataUrl: z.union([photoDataUrlSchema, photoUrlSchema, z.literal('')]).optional(),
|
||||
notifyOnDob: z.boolean().optional(),
|
||||
notifyOnGotchaDay: z.boolean().optional(),
|
||||
publicProfileEnabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const memorializeBirdSchema = z.object({
|
||||
memorializedOn: dateStringSchema,
|
||||
memorialNote: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
notifyOnMemorialDay: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const memorialReminderPreferenceSchema = z.object({
|
||||
notifyOnMemorialDay: z.boolean(),
|
||||
});
|
||||
|
||||
export const birdTimelineEventSchema = z
|
||||
.object({
|
||||
eventType: z.enum(['location_updated', 'owner_changed', 'manual_note']),
|
||||
eventDate: dateStringSchema.optional().or(z.literal('')),
|
||||
locationLabel: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationDetails: verifiedLocationDetailsSchema,
|
||||
note: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
value.eventType === 'owner_changed' ||
|
||||
Boolean(
|
||||
value.locationLabel?.trim() ||
|
||||
value.note?.trim() ||
|
||||
value.locationDetails?.city?.trim() ||
|
||||
value.locationDetails?.region?.trim() ||
|
||||
value.locationDetails?.country?.trim(),
|
||||
),
|
||||
'Add a location or note for this timeline item.',
|
||||
);
|
||||
|
||||
export const weightSchema = z.object({
|
||||
weightGrams: z.coerce.number().positive().max(10000),
|
||||
recordedOn: dateStringSchema,
|
||||
notes: z.string().trim().max(280).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const vetVisitSchema = z.object({
|
||||
visitedOn: dateStringSchema,
|
||||
clinicName: z.string().trim().min(1).max(160),
|
||||
reason: z.string().trim().min(1).max(160),
|
||||
notes: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const medicationSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
dosage: z.string().trim().min(1).max(160),
|
||||
frequency: z.enum(['once_daily', 'twice_daily', 'every_8_hours', 'every_6_hours', 'as_needed']),
|
||||
doseSchedule: z
|
||||
.array(
|
||||
z.object({
|
||||
key: z.string().trim().min(1).max(80),
|
||||
label: z.string().trim().min(1).max(80),
|
||||
time: z.string().trim().regex(/^$|^\d{2}:\d{2}$/),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(8),
|
||||
route: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
startDate: dateStringSchema,
|
||||
endDate: dateStringSchema.optional().or(z.literal('')),
|
||||
notes: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
remindersEnabled: z.boolean().optional(),
|
||||
})
|
||||
.refine((value) => !value.endDate || value.endDate >= value.startDate, {
|
||||
message: 'End date must be on or after start date.',
|
||||
path: ['endDate'],
|
||||
});
|
||||
|
||||
export const medicationAdministrationSchema = z.object({
|
||||
administeredOn: dateStringSchema,
|
||||
administrationSlot: z.string().trim().min(1).max(80).default('dose-1'),
|
||||
status: z.enum(['administered', 'missed']),
|
||||
notes: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const flockNoteSchema = z.object({
|
||||
birdId: z.string().uuid().optional().nullable().or(z.literal('')),
|
||||
body: z.string().trim().min(1).max(5000),
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { deleteS3Object, putS3Object } from '../storage/s3Client.js';
|
||||
|
||||
type BirdPhotoMigrationRow = {
|
||||
id: string;
|
||||
workspace_id: number;
|
||||
workspace_id: number | null;
|
||||
name: string;
|
||||
photo_data_url: string;
|
||||
};
|
||||
|
||||
@@ -54,7 +54,7 @@ export const buildBirdPhotoObjectKey = ({
|
||||
extension,
|
||||
now = new Date(),
|
||||
}: {
|
||||
workspaceId: number;
|
||||
workspaceId: number | null;
|
||||
birdId: string;
|
||||
extension: string;
|
||||
now?: Date;
|
||||
@@ -63,7 +63,7 @@ export const buildBirdPhotoObjectKey = ({
|
||||
const safeExtension = extension.replace(/^\./, '').toLowerCase() || 'bin';
|
||||
const timestamp = now.toISOString().replace(/[:.]/g, '-');
|
||||
|
||||
return `${prefix}/workspace-${workspaceId}/${birdId}/${timestamp}.${safeExtension}`;
|
||||
return `${prefix}/${workspaceId === null ? 'unassigned' : `workspace-${workspaceId}`}/${birdId}/${timestamp}.${safeExtension}`;
|
||||
};
|
||||
|
||||
export const getImageExtensionFromContentType = (contentType: string) => {
|
||||
|
||||
@@ -94,7 +94,7 @@ export type IntegrationTokenRow = {
|
||||
|
||||
export type BirdRow = {
|
||||
id: string;
|
||||
workspace_id: number;
|
||||
workspace_id: number | null;
|
||||
name: string;
|
||||
tag_id: string | null;
|
||||
species: string;
|
||||
@@ -129,6 +129,7 @@ export type BirdRow = {
|
||||
};
|
||||
|
||||
export type LostBirdMatchRow = BirdRow & {
|
||||
workspace_id: number;
|
||||
workspace_name: string;
|
||||
workspace_billing_email: string | null;
|
||||
};
|
||||
@@ -136,6 +137,7 @@ export type LostBirdMatchRow = BirdRow & {
|
||||
export type BirdMilestoneReminderType = 'hatch_day' | 'gotcha_day' | 'memorial_day';
|
||||
|
||||
export type BirdMilestoneReminderCandidateRow = BirdRow & {
|
||||
workspace_id: number;
|
||||
workspace_name: string;
|
||||
reminder_type: BirdMilestoneReminderType;
|
||||
reminder_date: string;
|
||||
@@ -176,7 +178,7 @@ export type BirdTransferCodeRow = {
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type BirdTimelineEventType = 'profile_created' | 'transferred' | 'location_updated' | 'owner_changed' | 'manual_note';
|
||||
export type BirdTimelineEventType = 'profile_created' | 'transferred' | 'location_updated' | 'owner_changed' | 'manual_note' | 'removed_from_flock' | 'joined_flock';
|
||||
|
||||
export type BirdTimelineEventRow = {
|
||||
id: string;
|
||||
@@ -234,6 +236,7 @@ export type MedicationDoseScheduleItem = {
|
||||
};
|
||||
|
||||
export type MedicationReminderCandidateRow = BirdRow & {
|
||||
workspace_id: number;
|
||||
workspace_name: string;
|
||||
medication_id: string;
|
||||
medication_name: string;
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { runWeightReminders } from './reminders/weightReminders.js';
|
||||
import { weightReminderQueue, weightReminderQueueName, startWeightReminderScheduler } from './queues/weightReminderQueue.js';
|
||||
import { Worker } from 'bullmq';
|
||||
|
||||
import { ensureSchema } from './db/schema.js';
|
||||
import { db } from './db/client.js';
|
||||
import {
|
||||
sendWeightReminderNotification,
|
||||
runBirdMilestoneReminders,
|
||||
runMedicationReminders,
|
||||
startBirdMilestoneReminderScheduler,
|
||||
@@ -29,6 +32,8 @@ import {
|
||||
import { redisConnection } from './queues/redisConnection.js';
|
||||
import { renderAdoptionReportForBird } from './reports/adoptionReportJob.js';
|
||||
|
||||
let stopWeightReminderScheduler: (() => void) | undefined;
|
||||
let weightReminderWorker: Worker | null = null;
|
||||
let birdMilestoneWorker: Worker<BirdMilestoneReminderJobData, BirdMilestoneReminderJobResult> | null = null;
|
||||
let medicationReminderWorker: Worker<MedicationReminderJobData, MedicationReminderJobResult> | null = null;
|
||||
let adoptionReportWorker: Worker<AdoptionReportJobData, AdoptionReportJobResult> | null = null;
|
||||
@@ -93,6 +98,16 @@ const startWorker = async () => {
|
||||
console.error(`Adoption report job failed: id=${job?.id ?? 'unknown'}, birdId=${job?.data.birdId ?? 'unknown'}`, error);
|
||||
});
|
||||
|
||||
weightReminderWorker = new Worker(weightReminderQueueName, async () => {
|
||||
if (process.env.WEIGHT_REMINDERS_ENABLED === 'false') return;
|
||||
const result = await runWeightReminders(sendWeightReminderNotification);
|
||||
console.log('Weight reminder job completed', result);
|
||||
return result;
|
||||
}, { connection: redisConnection, concurrency: 1 });
|
||||
weightReminderWorker.on('failed', (job, error) => {
|
||||
console.error(`Weight reminder job failed: id=${job?.id ?? 'unknown'}`, error);
|
||||
});
|
||||
stopWeightReminderScheduler = await startWeightReminderScheduler();
|
||||
startBirdMilestoneReminderScheduler();
|
||||
startMedicationReminderScheduler();
|
||||
console.log('FlockPal worker started.');
|
||||
@@ -100,6 +115,9 @@ const startWorker = async () => {
|
||||
|
||||
const shutdown = async (signal: string) => {
|
||||
console.log(`FlockPal worker received ${signal}; shutting down.`);
|
||||
stopWeightReminderScheduler?.();
|
||||
await weightReminderWorker?.close();
|
||||
await weightReminderQueue.close();
|
||||
await birdMilestoneWorker?.close();
|
||||
await medicationReminderWorker?.close();
|
||||
await adoptionReportWorker?.close();
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Run against the disposable database described in docs/BEHAVIOR_JOURNAL.md.
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
Object.assign(process.env, {
|
||||
POSTGRES_HOST: '127.0.0.1', POSTGRES_PORT: '55439', POSTGRES_DB: 'behavior_test',
|
||||
POSTGRES_USER: 'postgres', POSTGRES_PASSWORD: 'behavior_test_only', PORT: '55440',
|
||||
MILESTONE_REMINDERS_ENABLED: 'false', MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'false',
|
||||
});
|
||||
const { db } = await import('../dist/db/client.js');
|
||||
const { ensureSchema } = await import('../dist/db/schema.js');
|
||||
let server;
|
||||
let logs = '';
|
||||
try {
|
||||
await ensureSchema();
|
||||
await ensureSchema(); // Schema and seed must be safe to re-run.
|
||||
const workspace = 100000 + Math.floor(Math.random() * 1000000000);
|
||||
const otherWorkspace = workspace + 1;
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, 'Journal test', 'rescue', 'approved'), ($2, 'Other test', 'rescue', 'approved')`, [workspace, otherWorkspace]);
|
||||
const user = randomUUID();
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Journal tester')`, [user, `${user}@example.test`]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, 'journal@example.test', 'Journal tester', 'owner', NOW())`, [workspace, user]);
|
||||
const token = randomUUID();
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
const bird = randomUUID(), otherBird = randomUUID(), secondBird = randomUUID();
|
||||
for (const [id, flock] of [[bird, workspace], [secondBird, workspace], [otherBird, otherWorkspace]]) {
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, species) VALUES ($1, $2, 'Journal bird', 'Parrot')`, [id, flock]);
|
||||
}
|
||||
server = spawn(process.execPath, [fileURLToPath(new URL('../dist/app.js', import.meta.url))], { cwd: '/tmp', env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
server.stdout.on('data', (data) => { logs += data; }); server.stderr.on('data', (data) => { logs += data; });
|
||||
for (let attempt = 0; attempt < 100 && !logs.includes('listening'); attempt++) await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
assert.match(logs, /listening/, logs);
|
||||
async function api(path, method = 'GET', body, status = 200, authenticated = true) {
|
||||
const response = await fetch(`http://127.0.0.1:55440/api${path}`, { method, headers: { 'Content-Type': 'application/json', ...(authenticated ? { Authorization: `Bearer ${token}` } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
||||
const data = response.status === 204 ? null : await response.json();
|
||||
assert.equal(response.status, status, JSON.stringify(data)); return data;
|
||||
}
|
||||
const base = `/birds/${bird}`;
|
||||
const range = '?from=2026-10-01T00:00:00-04:00&to=2026-11-01T00:00:00-04:00';
|
||||
const types = (await api(`${base}/behavior-types`)).behaviorTypes;
|
||||
assert.equal(types.length, 9);
|
||||
const custom = (await api(`${base}/behavior-types`, 'POST', { name: 'Wing stretching', description: 'Observed stretching' }, 201)).behaviorType;
|
||||
const duplicate = (await api(`${base}/behavior-types`, 'POST', { name: 'wing stretching' }, 201)).behaviorType;
|
||||
assert.equal(custom.id, duplicate.id);
|
||||
const foreignType = (await db.query(`INSERT INTO behavior_types (workspace_id, name) VALUES ($1, 'Private behavior') RETURNING id`, [otherWorkspace])).rows[0].id;
|
||||
const input = { behaviorTypeId: custom.id, occurredAt: '2026-10-05T23:30:12.123-04:00', durationSeconds: 90, severity: 3, notes: 'Observed after play' };
|
||||
const first = (await api(`${base}/behaviors`, 'POST', input, 201)).occurrence;
|
||||
assert.equal(first.occurredAt, '2026-10-06T03:30:12.123Z');
|
||||
const second = (await api(`${base}/behaviors`, 'POST', { ...input, behaviorTypeId: types[0].id }, 201)).occurrence;
|
||||
await api(`${base}/behaviors`, 'POST', { ...input, occurredAt: '2026-11-01T00:00:00-04:00' }, 201);
|
||||
assert.equal((await api(`${base}/behaviors${range}`)).occurrences.length, 2);
|
||||
assert.equal((await api(`${base}/behaviors${range}&behaviorTypeId=${custom.id}`)).occurrences.length, 1);
|
||||
assert.equal((await api(`/birds/${secondBird}/behaviors${range}`)).occurrences.length, 0);
|
||||
const edited = (await api(`${base}/behaviors/${first.id}`, 'PUT', { ...input, notes: 'Edited note', severity: null, durationSeconds: null })).occurrence;
|
||||
assert.equal(edited.notes, 'Edited note'); assert.equal(edited.severity, null); assert.equal(edited.durationSeconds, null);
|
||||
assert.equal(edited.createdAt, first.createdAt); assert.equal(edited.occurredAt, first.occurredAt);
|
||||
for (const bad of [{ severity: 6 }, { durationSeconds: -1 }, { occurredAt: '2026-02-30T12:00:00Z' }, { occurredAt: '2026-10-05T12:00:00' }]) await api(`${base}/behaviors`, 'POST', { ...input, ...bad }, 400);
|
||||
await api(`${base}/behaviors`, 'POST', { ...input, behaviorTypeId: foreignType }, 404);
|
||||
await api(`/birds/${otherBird}/behavior-types`, 'GET', undefined, 404);
|
||||
await api(`/birds/${otherBird}/behaviors${range}`, 'GET', undefined, 404);
|
||||
await api(`/birds/${otherBird}/behaviors`, 'POST', input, 404);
|
||||
await api(`/birds/${secondBird}/behaviors/${first.id}`, 'PUT', input, 404);
|
||||
await api(`/birds/${secondBird}/behaviors/${first.id}`, 'DELETE', undefined, 404);
|
||||
await api(`${base}/behavior-types`, 'GET', undefined, 401, false);
|
||||
await api(`${base}/behaviors?from=invalid&to=invalid`, 'GET', undefined, 400);
|
||||
await db.query(`UPDATE workspace_members SET role = 'viewer' WHERE user_id = $1`, [user]);
|
||||
await api(`${base}/behaviors`, 'POST', input, 403);
|
||||
await api(`${base}/behaviors/${first.id}`, 'PUT', input, 403);
|
||||
await api(`${base}/behaviors/${first.id}`, 'DELETE', undefined, 403);
|
||||
await db.query(`UPDATE workspace_members SET role = 'owner' WHERE user_id = $1`, [user]);
|
||||
await db.query(`UPDATE workspaces SET rescue_verification_status = 'pending' WHERE id = $1`, [workspace]);
|
||||
await api(`${base}/behaviors`, 'POST', input, 402);
|
||||
await db.query(`UPDATE workspaces SET rescue_verification_status = 'approved' WHERE id = $1`, [workspace]);
|
||||
await db.query(`UPDATE birds SET memorialized_at = NOW() WHERE id = $1`, [bird]);
|
||||
await api(`${base}/behaviors`, 'POST', input, 409);
|
||||
await api(`${base}/behaviors/${first.id}`, 'DELETE', undefined, 409);
|
||||
await db.query(`UPDATE birds SET memorialized_at = NULL WHERE id = $1`, [bird]);
|
||||
await api(`${base}/behaviors/${second.id}`, 'DELETE', undefined, 204);
|
||||
assert.equal((await api(`${base}/behaviors${range}`)).occurrences.length, 1);
|
||||
// Transfer the bird: old flock loses access, new flock retains normalized history.
|
||||
await db.query(`UPDATE birds SET workspace_id = $1 WHERE id = $2`, [otherWorkspace, bird]);
|
||||
await api(`${base}/behaviors${range}`, 'GET', undefined, 404);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, 'journal@example.test', 'Journal tester', 'owner', NOW())`, [otherWorkspace, user]);
|
||||
await db.query(`UPDATE auth_sessions SET active_workspace_id = $1 WHERE user_id = $2`, [otherWorkspace, user]);
|
||||
assert.equal((await api(`${base}/behaviors${range}`)).occurrences[0].behaviorName, 'Wing stretching');
|
||||
assert.ok((await api(`${base}/behavior-types`)).behaviorTypes.some((type) => type.id === custom.id));
|
||||
await api(`${base}/behaviors/${first.id}`, 'PUT', input);
|
||||
console.log('PASS: schema repeatability; defaults/custom types; create/edit/delete; bird/behavior/month filters; timestamp precision; auth/role/billing/memorial restrictions; flock isolation and transfer history.');
|
||||
} finally {
|
||||
if (server && server.exitCode === null) { const exited = once(server, 'exit'); server.kill('SIGTERM'); await exited; }
|
||||
await db.close();
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Uses only the disposable database and API ports documented in docs/BIRD_MEMBERSHIP.md.
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
Object.assign(process.env, {
|
||||
POSTGRES_HOST: '127.0.0.1', POSTGRES_PORT: '55439', POSTGRES_DB: 'behavior_test',
|
||||
POSTGRES_USER: 'postgres', POSTGRES_PASSWORD: 'behavior_test_only', PORT: '55440',
|
||||
MILESTONE_REMINDERS_ENABLED: 'false', MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'false',
|
||||
});
|
||||
const { db } = await import('../dist/db/client.js');
|
||||
const { ensureSchema } = await import('../dist/db/schema.js');
|
||||
const { removeBirdFromFlock, claimUnassignedBird } = await import('../dist/repositories/birdMembershipRepository.js');
|
||||
let server;
|
||||
let output = '';
|
||||
try {
|
||||
await ensureSchema();
|
||||
await ensureSchema();
|
||||
const baseId = 100000 + Math.floor(Math.random() * 1000000000);
|
||||
const accounts = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const workspace = baseId + i, user = randomUUID(), token = randomUUID(), email = `${user}@example.test`;
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, $2, 'rescue', 'approved')`, [workspace, `Membership test ${i}`]);
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Tester')`, [user, email]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Tester', 'owner', NOW())`, [workspace, user, email]);
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
accounts.push({ workspace, user, token });
|
||||
}
|
||||
const [source, destination, rival] = accounts;
|
||||
const bird = randomUUID(), tagId = `BAND-${randomUUID()}`, publicCode = randomUUID().slice(0, 20);
|
||||
const photo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a2ioAAAAASUVORK5CYII=';
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, tag_id, species, photo_data_url, public_profile_code, public_profile_enabled)
|
||||
VALUES ($1, $2, 'Preserved bird', $3, 'Parrot', $4, $5, TRUE)`, [bird, source.workspace, tagId, photo, publicCode]);
|
||||
await db.query(`INSERT INTO weight_records (bird_id, weight_grams, recorded_on) VALUES ($1, 120, CURRENT_DATE)`, [bird]);
|
||||
await db.query(`INSERT INTO vet_visits (bird_id, visited_on, clinic_name, reason) VALUES ($1, CURRENT_DATE, 'Clinic', 'Checkup')`, [bird]);
|
||||
const med = (await db.query(`INSERT INTO medications (bird_id, name, dosage, frequency, start_date) VALUES ($1, 'Existing medication', '1 ml', 'Daily', CURRENT_DATE) RETURNING id`, [bird])).rows[0].id;
|
||||
await db.query(`INSERT INTO medication_administrations (medication_id, bird_id, administered_on, status) VALUES ($1, $2, CURRENT_DATE, 'administered')`, [med, bird]);
|
||||
const behaviorType = (await db.query(`INSERT INTO behavior_types (workspace_id, name) VALUES ($1, 'Existing custom behavior') RETURNING id`, [source.workspace])).rows[0].id;
|
||||
await db.query(`INSERT INTO behavior_occurrences (bird_id, behavior_type_id, occurred_at, notes) VALUES ($1, $2, NOW(), 'Existing occurrence')`, [bird, behaviorType]);
|
||||
const birdNote = (await db.query(`INSERT INTO flock_notes (workspace_id, bird_id, title, body) VALUES ($1, $2, 'Bird note', 'Keep with bird') RETURNING id`, [source.workspace, bird])).rows[0].id;
|
||||
await db.query(`INSERT INTO flock_notes (workspace_id, title, body) VALUES ($1, 'Flock only', 'Keep in source flock')`, [source.workspace]);
|
||||
const transferCode = randomUUID().slice(0, 20);
|
||||
await db.query(`INSERT INTO bird_transfer_codes (code, bird_id, source_workspace_id, requested_by_user_id) VALUES ($1, $2, $3, $4)`, [transferCode, bird, source.workspace, source.user]);
|
||||
await db.query(`INSERT INTO pending_bird_transfers (bird_id, source_workspace_id, destination_owner_email, requested_by_user_id) VALUES ($1, $2, 'pending@example.test', $3)`, [bird, source.workspace, source.user]);
|
||||
// A late failure must roll back the bird, notes, and transfer changes together.
|
||||
await assert.rejects(() => removeBirdFromFlock(bird, source.workspace, randomUUID()));
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, source.workspace);
|
||||
assert.equal((await db.query(`SELECT revoked_at FROM bird_transfer_codes WHERE code = $1`, [transferCode])).rows[0].revoked_at, null);
|
||||
server = spawn(process.execPath, [fileURLToPath(new URL('../dist/app.js', import.meta.url))], { cwd: '/tmp', env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
server.stdout.on('data', (data) => { output += data; }); server.stderr.on('data', (data) => { output += data; });
|
||||
for (let i = 0; i < 100 && !output.includes('listening'); i++) await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
assert.match(output, /listening/, output);
|
||||
async function api(account, path, method = 'GET', body, status = 200) {
|
||||
const response = await fetch(`http://127.0.0.1:55440/api${path}`, { method, headers: { 'Content-Type': 'application/json', ...(account ? { Authorization: `Bearer ${account.token}` } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
||||
const data = response.status === 204 ? null : await response.json();
|
||||
if (status !== null) assert.equal(response.status, status, JSON.stringify(data));
|
||||
return { status: response.status, data };
|
||||
}
|
||||
const matchPath = `/birds/unassigned-match?${new URLSearchParams({ tagId })}`;
|
||||
assert.deepEqual((await api(destination, matchPath)).data, { available: false });
|
||||
await api(destination, '/birds/claim', 'POST', { tagId, confirmHistory: true }, 409);
|
||||
await api(destination, `/birds/${bird}`, 'DELETE', undefined, 404);
|
||||
await api(source, `/birds/${bird}`, 'DELETE', undefined, 204);
|
||||
const removed = (await db.query(`SELECT * FROM birds WHERE id = $1`, [bird])).rows[0];
|
||||
assert.equal(removed.workspace_id, null); assert.equal(removed.photo_data_url, photo); assert.equal(removed.public_profile_enabled, false);
|
||||
for (const table of ['weight_records', 'vet_visits', 'medications', 'medication_administrations', 'behavior_occurrences', 'flock_notes']) {
|
||||
assert.equal((await db.query(`SELECT COUNT(*)::int AS count FROM ${table} WHERE bird_id = $1`, [bird])).rows[0].count, 1, table);
|
||||
}
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM flock_notes WHERE id = $1`, [birdNote])).rows[0].workspace_id, null);
|
||||
assert.ok((await db.query(`SELECT revoked_at FROM bird_transfer_codes WHERE code = $1`, [transferCode])).rows[0].revoked_at);
|
||||
assert.equal((await db.query(`SELECT COUNT(*)::int AS count FROM pending_bird_transfers WHERE bird_id = $1`, [bird])).rows[0].count, 0);
|
||||
assert.equal((await api(source, '/birds')).data.birds.length, 0);
|
||||
assert.equal((await api(source, '/notes')).data.notes.length, 1);
|
||||
assert.equal((await api(source, `/birds/${bird}/weights`)).data.weights.length, 0);
|
||||
await api(null, `/public/birds/${publicCode}`, 'GET', undefined, 404);
|
||||
assert.deepEqual((await api(destination, matchPath)).data, { available: true });
|
||||
await api(null, matchPath, 'GET', undefined, 401);
|
||||
await api(destination, '/birds/unassigned-match?tagId=unknown', 'GET', undefined, 400);
|
||||
assert.deepEqual((await api(destination, `/birds/unassigned-match?tagId=${encodeURIComponent(tagId.slice(0, -1))}`)).data, { available: false });
|
||||
await api(destination, '/birds/claim', 'POST', { tagId }, 400);
|
||||
await db.query(`UPDATE workspace_members SET role = 'viewer' WHERE user_id = $1`, [destination.user]);
|
||||
await api(destination, matchPath, 'GET', undefined, 403);
|
||||
await api(destination, '/birds/claim', 'POST', { tagId, confirmHistory: true }, 403);
|
||||
await db.query(`UPDATE workspace_members SET role = 'owner' WHERE user_id = $1`, [destination.user]);
|
||||
await db.query(`UPDATE workspaces SET rescue_verification_status = 'pending' WHERE id = $1`, [destination.workspace]);
|
||||
await api(destination, '/birds/claim', 'POST', { tagId, confirmHistory: true }, 402);
|
||||
await db.query(`UPDATE workspaces SET rescue_verification_status = 'approved' WHERE id = $1`, [destination.workspace]);
|
||||
assert.equal((await api(destination, '/birds', 'POST', { name: 'New name should not replace existing', species: 'Parrot', tagId }, 409)).data.code, 'bird_history_available');
|
||||
await assert.rejects(() => claimUnassignedBird(tagId, destination.workspace, randomUUID()));
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, null);
|
||||
const claimed = (await api(destination, '/birds/claim', 'POST', { tagId: ` ${tagId.toLowerCase()} `, confirmHistory: true })).data;
|
||||
assert.equal(claimed.bird.id, bird); assert.equal(claimed.bird.name, 'Preserved bird'); assert.equal(claimed.historyImported, true); assert.equal(claimed.bird.photoDataUrl, photo);
|
||||
assert.equal((await api(destination, `/birds/${bird}/weights`)).data.weights.length, 1);
|
||||
assert.equal((await api(destination, `/birds/${bird}/vet-visits`)).data.vetVisits.length, 1);
|
||||
assert.equal((await api(destination, '/notes')).data.notes[0].id, birdNote);
|
||||
assert.equal((await api(source, '/notes')).data.notes.length, 1);
|
||||
assert.ok((await api(destination, `/birds/${bird}/behavior-types`)).data.behaviorTypes.some((type) => type.id === behaviorType));
|
||||
const timeline = (await api(destination, `/birds/${bird}/timeline`)).data.events;
|
||||
assert.ok(timeline.some((event) => event.eventType === 'removed_from_flock'));
|
||||
assert.ok(timeline.some((event) => event.eventType === 'joined_flock'));
|
||||
await api(source, `/birds/${bird}`, 'DELETE', undefined, 404);
|
||||
await api(rival, '/birds/claim', 'POST', { tagId, confirmHistory: true }, 409);
|
||||
// Remove again and race two different flocks. Exactly one claim must succeed.
|
||||
await api(destination, `/birds/${bird}`, 'DELETE', undefined, 204);
|
||||
const race = await Promise.all([source, rival].map((account) => api(account, '/birds/claim', 'POST', { tagId, confirmHistory: true }, null)));
|
||||
assert.deepEqual(race.map((result) => result.status).sort(), [200, 409]);
|
||||
const bandless = randomUUID();
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, species) VALUES ($1, $2, 'No band', 'Parrot')`, [bandless, source.workspace]);
|
||||
await api(source, `/birds/${bandless}`, 'DELETE', undefined, 204);
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bandless])).rows[0].workspace_id, null);
|
||||
console.log('PASS: reversible flock removal, retained profile/photo/all care records, notes isolation, sharing/transfer revocation, exact normalized band matching, explicit history consent, permissions, rollback, and concurrent claims.');
|
||||
} finally {
|
||||
if (server && server.exitCode === null) { const done = once(server, 'exit'); server.kill('SIGTERM'); await done; }
|
||||
await db.close();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_USER: flockpal_test
|
||||
POSTGRES_PASSWORD: isolated_test_password
|
||||
POSTGRES_DB: flockpal_weight_test
|
||||
ports:
|
||||
- '127.0.0.1:25432:5432'
|
||||
tmpfs:
|
||||
- /var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U flockpal_test -d flockpal_weight_test']
|
||||
interval: 1s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
command: ['redis-server', '--save', '', '--appendonly', 'no']
|
||||
ports:
|
||||
- '127.0.0.1:26379:6379'
|
||||
mail:
|
||||
image: axllent/mailpit:latest
|
||||
ports:
|
||||
- '127.0.0.1:21025:1025'
|
||||
- '127.0.0.1:28025:8025'
|
||||
@@ -0,0 +1,182 @@
|
||||
// Run only against disposable local Postgres, Redis, and Mailpit services.
|
||||
// See docs/WEIGHT_REMINDER_TESTING.md for the isolated Compose setup.
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
Object.assign(process.env, {
|
||||
POSTGRES_HOST: '127.0.0.1', POSTGRES_PORT: '25432', POSTGRES_DB: 'flockpal_weight_test',
|
||||
POSTGRES_USER: 'flockpal_test', POSTGRES_PASSWORD: 'isolated_test_password',
|
||||
REDIS_URL: 'redis://127.0.0.1:26379',
|
||||
SMTP_HOST: '127.0.0.1', SMTP_PORT: '21025', SMTP_SECURE: 'false',
|
||||
SMTP_USER: '', SMTP_PASS: '', SMTP_FROM_EMAIL: 'reminders@flockpal.test', SMTP_FROM_NAME: 'FlockPal Test',
|
||||
FRONTEND_URL: 'http://flockpal.test', MILESTONE_REMINDERS_ENABLED: 'false',
|
||||
MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'true',
|
||||
MILESTONE_REMINDER_TIME_ZONE: 'America/New_York',
|
||||
});
|
||||
const { db } = await import('../dist/db/client.js');
|
||||
const { ensureSchema } = await import('../dist/db/schema.js');
|
||||
const { getReminderDate } = await import('../dist/reminders/reminderDate.js');
|
||||
const { listDueWeightReminders, claimWeightReminder, finishWeightReminder } = await import('../dist/reminders/weightReminders.js');
|
||||
const { weightReminderQueue, startWeightReminderScheduler, enqueueDailyWeightReminder } = await import('../dist/queues/weightReminderQueue.js');
|
||||
const workers = [];
|
||||
let logs = '';
|
||||
const poll = async (check, label) => {
|
||||
const deadline = Date.now() + 30_000;
|
||||
while (Date.now() < deadline) {
|
||||
if (await check()) return;
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
throw new Error(`Timed out: ${label}\n${logs}`);
|
||||
};
|
||||
const messages = async () => (await (await fetch('http://127.0.0.1:28025/api/v1/messages')).json()).messages;
|
||||
const startWorker = () => {
|
||||
const child = spawn(process.execPath, [fileURLToPath(new URL('../dist/worker.js', import.meta.url))], {
|
||||
cwd: '/tmp', env: process.env, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
child.stdout.on('data', data => { logs += data; });
|
||||
child.stderr.on('data', data => { logs += data; });
|
||||
workers.push(child);
|
||||
};
|
||||
const stopWorkers = async () => {
|
||||
const exits = workers.map(child => once(child, 'exit'));
|
||||
for (const child of workers) child.kill('SIGTERM');
|
||||
await Promise.all(exits);
|
||||
workers.length = 0;
|
||||
};
|
||||
const drain = async () => {
|
||||
await poll(async () => {
|
||||
const counts = await weightReminderQueue.getJobCounts('active', 'waiting');
|
||||
return !counts.active && !counts.waiting;
|
||||
}, 'queue drain');
|
||||
};
|
||||
const runJob = async () => {
|
||||
const job = await weightReminderQueue.add('integration-check', {});
|
||||
await poll(async () => ['completed', 'failed'].includes(await job.getState()), 'manual job');
|
||||
assert.equal(await job.getState(), 'completed');
|
||||
return (await weightReminderQueue.getJob(job.id)).returnvalue;
|
||||
};
|
||||
try {
|
||||
await ensureSchema();
|
||||
await ensureSchema();
|
||||
assert.equal((await db.query('SELECT COUNT(*)::int AS count FROM birds')).rows[0].count, 0, 'Use a fresh disposable database');
|
||||
assert.equal((await messages()).length, 0, 'Use a fresh email catcher');
|
||||
await db.query("INSERT INTO workspaces (id, name) VALUES (101, 'Test Flock'), (102, 'Other Flock')");
|
||||
const ids = {};
|
||||
for (const [role, accepted] of [['owner', true], ['assistant', true], ['caregiver', true], ['viewer', true], ['pending', false]]) {
|
||||
const id = randomUUID(); ids[role] = id;
|
||||
await db.query('INSERT INTO users (id, email, name) VALUES ($1, $2, $3)', [id, `${role}@example.test`, role]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at)
|
||||
VALUES (101, $1, $2, $3, $4, ${accepted ? 'CURRENT_TIMESTAMP' : 'NULL'})`, [id, `${role}@example.test`, role, role === 'pending' ? 'caregiver' : role]);
|
||||
}
|
||||
await db.query("INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES (102, $1, 'owner@example.test', 'owner', 'owner', CURRENT_TIMESTAMP)", [ids.owner]);
|
||||
const birds = {};
|
||||
for (const [name, age, memorial, workspace] of [
|
||||
['Kiwi & <Peep>', 72, false, 101], ['Boundary', 48, false, 101],
|
||||
['No weights', null, false, 101], ['Recent', 47, false, 101],
|
||||
['Memorial', 72, true, 101], ['Other bird', 72, false, 102],
|
||||
]) {
|
||||
const id = randomUUID(); birds[name] = id;
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, species, created_at, memorialized_at)
|
||||
VALUES ($1, $2, $3, 'Cockatiel', CURRENT_TIMESTAMP - INTERVAL '100 hours', ${memorial ? 'CURRENT_TIMESTAMP' : 'NULL'})`, [id, workspace, name]);
|
||||
if (age !== null) await db.query("INSERT INTO weight_records (bird_id, weight_grams, recorded_on, created_at) VALUES ($1, 90, CURRENT_DATE - 3, CURRENT_TIMESTAMP - $2 * INTERVAL '1 hour')", [id, age]);
|
||||
}
|
||||
const portrait = await readFile(new URL('../assets/yoda.png', import.meta.url));
|
||||
await db.query('UPDATE birds SET photo_data_url = $1 WHERE id = $2', [`data:image/png;base64,${portrait.toString('base64')}`, birds['Kiwi & <Peep>']]);
|
||||
const due = await listDueWeightReminders();
|
||||
assert.equal(due.length, 10);
|
||||
assert.deepEqual(new Set(due.map(b => b.recipient)), new Set(['owner@example.test', 'assistant@example.test', 'caregiver@example.test']));
|
||||
const candidate = due[0];
|
||||
const tokens = [randomUUID(), randomUUID()];
|
||||
const claims = await Promise.all(tokens.map(token => claimWeightReminder(candidate, token)));
|
||||
assert.equal(claims.filter(Boolean).length, 1, 'Only one concurrent claim wins');
|
||||
await finishWeightReminder(tokens[claims.indexOf(true)], false);
|
||||
console.log('PASS: schema initialization is repeatable; eligibility, roles, and concurrent claims');
|
||||
|
||||
// Simulate the schedule present before upgrading to daily reminders.
|
||||
await weightReminderQueue.upsertJobScheduler('weight-reminders', { every: 300_000 }, { name: 'check-overdue-weights', data: {} });
|
||||
startWorker(); startWorker();
|
||||
await poll(async () => (await messages()).length === 4, 'initial grouped emails');
|
||||
await drain();
|
||||
const initial = await messages();
|
||||
const bodies = await Promise.all(initial.map(async message => (await fetch(`http://127.0.0.1:28025/api/v1/message/${message.ID}`)).json()));
|
||||
for (const body of bodies) {
|
||||
if (body.Subject === 'Weight reminders for Test Flock') {
|
||||
for (const name of ['Kiwi & <Peep>', 'Boundary', 'No weights']) assert.ok(body.Text.includes(name));
|
||||
assert.ok(body.HTML.includes('Kiwi & <Peep>'));
|
||||
assert.ok(!body.Text.includes('Memorial'));
|
||||
assert.ok(!body.Text.includes('Recent'));
|
||||
assert.ok(!body.Text.includes('Other bird'));
|
||||
} else {
|
||||
assert.equal(body.Subject, 'Weight reminders for Other Flock');
|
||||
assert.ok(body.Text.includes('Other bird'));
|
||||
assert.ok(!body.Text.includes('Boundary'));
|
||||
}
|
||||
assert.equal(body.To.length, 1);
|
||||
const inline = body.Inline ?? [];
|
||||
assert.ok(inline.some(attachment => attachment.ContentID === 'flockpal-logo'));
|
||||
assert.equal(inline.filter(attachment => attachment.ContentID.startsWith('weight-bird-')).length, body.Subject === 'Weight reminders for Test Flock' ? 3 : 1);
|
||||
assert.ok(body.HTML.includes('Daily weight reminder'));
|
||||
assert.ok(body.HTML.includes('Record their weights'));
|
||||
}
|
||||
assert.equal((await weightReminderQueue.getJobSchedulers()).length, 0);
|
||||
await poll(async () => Boolean(await weightReminderQueue.getJob(`weight-reminders-${getReminderDate()}`)), 'startup daily scheduler');
|
||||
const dailyJobs = await Promise.all([enqueueDailyWeightReminder(), enqueueDailyWeightReminder()]);
|
||||
assert.equal(dailyJobs[0].id, dailyJobs[1].id);
|
||||
await drain();
|
||||
assert.equal(await weightReminderQueue.getGlobalConcurrency(), 1);
|
||||
assert.equal((await runJob()).sent, 0);
|
||||
assert.equal((await messages()).length, 4);
|
||||
console.log('PASS: two real workers, one daily job, legacy schedule removed, grouped SMTP delivery, escaping, flock isolation, no immediate duplicates');
|
||||
|
||||
await db.query("UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP");
|
||||
assert.equal((await runJob()).sent, 0);
|
||||
await db.query("UPDATE weight_reminder_deliveries SET delivered_at = ((CURRENT_TIMESTAMP AT TIME ZONE 'America/New_York')::date::timestamp AT TIME ZONE 'America/New_York') - INTERVAL '1 second'");
|
||||
assert.equal((await runJob()).sent, 4);
|
||||
assert.equal((await messages()).length, 8);
|
||||
await db.query("INSERT INTO weight_records (bird_id, weight_grams, recorded_on) VALUES ($1, 91, CURRENT_DATE)", [birds.Boundary]);
|
||||
await db.query("UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP - INTERVAL '49 hours'");
|
||||
assert.ok((await listDueWeightReminders()).every(b => b.bird_id !== birds.Boundary));
|
||||
assert.equal((await runJob()).sent, 4);
|
||||
console.log('PASS: no repeat on the same local date, daily repeat, fresh weight resets eligibility');
|
||||
|
||||
await stopWorkers();
|
||||
await db.query("UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP - INTERVAL '49 hours'");
|
||||
const beforeFailures = (await messages()).length;
|
||||
process.env.SMTP_HOST = '';
|
||||
startWorker();
|
||||
assert.equal((await runJob()).sent, 0);
|
||||
assert.equal((await listDueWeightReminders()).length, 7);
|
||||
await stopWorkers();
|
||||
|
||||
process.env.SMTP_HOST = '127.0.0.1';
|
||||
process.env.SMTP_PORT = '21026'; // No SMTP listener: exercise a real refused connection.
|
||||
startWorker();
|
||||
const failed = await runJob();
|
||||
assert.equal(failed.failed, 4);
|
||||
assert.equal(failed.sent, 0);
|
||||
assert.equal((await listDueWeightReminders()).length, 7);
|
||||
assert.equal((await messages()).length, beforeFailures);
|
||||
await stopWorkers();
|
||||
|
||||
process.env.SMTP_PORT = '21025';
|
||||
startWorker();
|
||||
await runJob();
|
||||
await poll(async () => (await messages()).length === beforeFailures + 4, 'delivery after SMTP recovery');
|
||||
await drain();
|
||||
await stopWorkers();
|
||||
console.log('PASS: missing SMTP, real SMTP connection failure, released claims, successful retry');
|
||||
|
||||
process.env.WEIGHT_REMINDERS_ENABLED = 'false';
|
||||
await startWeightReminderScheduler();
|
||||
assert.equal((await weightReminderQueue.getJobSchedulers()).length, 0);
|
||||
console.log('PASS: graceful worker shutdown and disabled scheduler removal');
|
||||
console.log('All Postgres / Redis / SMTP integration checks passed.');
|
||||
} finally {
|
||||
for (const child of workers) child.kill('SIGKILL');
|
||||
await weightReminderQueue.close();
|
||||
await db.close();
|
||||
}
|
||||
Reference in new issue
Block a user