diff --git a/backend/package-lock.json b/backend/package-lock.json index 0189ff2..5d2f335 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -13,6 +13,7 @@ "fastify": "^5.8.5", "mysql2": "^3.11.3", "pino": "^9.4.0", + "sharp": "^0.34.0", "zod": "^3.23.8" }, "devDependencies": { @@ -25,6 +26,15 @@ "npm": ">=10.0.0" } }, + "node_modules/@emnapi/runtime": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz", + "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", @@ -585,6 +595,363 @@ "toad-cache": "^3.7.0" } }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.0.tgz", + "integrity": "sha512-BLT8CQ234EOJFN4NCAkZUkJr2lyXavD+aQH/Jc2skPqAJTMjKeH2BUulaZNkd4MJ9hcCicTdupcbCRg4bto0Ow==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.1.0" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.0.tgz", + "integrity": "sha512-FZLxjWEtz+QbxZbtFb+f6AbD47/M9k6GuZ9dedTFdsgI9HwUMvyinxFMAeyP1fJZkJBw999Ht5Cus4sqpFlBPg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.1.0" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.1.0.tgz", + "integrity": "sha512-HZ/JUmPwrJSoM4DIQPv/BfNh9yrOA8tlBbqbLz4JZ5uew2+o22Ik+tHQJcih7QJuSa0zo5coHTfD5J8inqj9DA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.1.0.tgz", + "integrity": "sha512-Xzc2ToEmHN+hfvsl9wja0RlnXEgpKNmftriQp6XzY/RaSfwD9th+MSh0WQKzUreLKKINb3afirxW7A0fz2YWuQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.1.0.tgz", + "integrity": "sha512-s8BAd0lwUIvYCJyRdFqvsj+BJIpDBSxs6ivrOPm/R7piTs5UIwY5OjXrP2bqXC9/moGsyRa37eYWYCOGVXxVrA==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.1.0.tgz", + "integrity": "sha512-IVfGJa7gjChDET1dK9SekxFFdflarnUB8PwW8aGwEoF3oAsSDuNUTYS+SKDOyOJxQyDC1aPFMuRYLoDInyV9Ew==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.1.0.tgz", + "integrity": "sha512-tiXxFZFbhnkWE2LA8oQj7KYR+bWBkiV2nilRldT7bqoEZ4HiDOcePr9wVDAZPi/Id5fT1oY9iGnDq20cwUz8lQ==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.1.0.tgz", + "integrity": "sha512-xukSwvhguw7COyzvmjydRb3x/09+21HykyapcZchiCUkTThEQEOMtBj9UhkaBRLuBrgLFzQ2wbxdeCCJW/jgJA==", + "cpu": [ + "s390x" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.1.0.tgz", + "integrity": "sha512-yRj2+reB8iMg9W5sULM3S74jVS7zqSzHG3Ol/twnAAkAhnGQnpjj6e4ayUz7V+FpKypwgs82xbRdYtchTTUB+Q==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.1.0.tgz", + "integrity": "sha512-jYZdG+whg0MDK+q2COKbYidaqW/WTz0cc1E+tMAusiDygrM4ypmSCjOJPmFTvHHJ8j/6cAGyeDWZOsK06tP33w==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.1.0.tgz", + "integrity": "sha512-wK7SBdwrAiycjXdkPnGCPLjYb9lD4l6Ze2gSdAGVZrEL05AOUJESWU2lhlC+Ffn5/G+VKuSm6zzbQSzFX/P65A==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.0.tgz", + "integrity": "sha512-MfbqXi4zdy0CsSONwESFzrdpzcNSN66qbt8a7CdesOFfZHmlPXgC+xOy+2SLYn6+MFi/06qngGRIje7vfAV/5Q==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.1.0" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.0.tgz", + "integrity": "sha512-fpvIy7rPdTegqthhUNAaQikg8CzNUGxuf7VTIs5HEQllCTL322rBDuGHVoH/pZ6Qms9enHe++DsUoG/Ux93E1A==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.1.0" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.0.tgz", + "integrity": "sha512-04jdT+VCZIqj0RoTEpWXh0lErZC9prhkxEZWrQdGt1MZ368SlvXpKkXCD4Ww5ISc3LexBmfnAW/+ErUmD9sRPQ==", + "cpu": [ + "s390x" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.1.0" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.0.tgz", + "integrity": "sha512-Y98V1d5vh8RIpf+pUb7U9a0SGzfPa7x7KPXsqtvb7i52L7HXAMv5U0aaOdnnf/CAqVUVaTJajINJ3KyrLcwByQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.1.0" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.0.tgz", + "integrity": "sha512-pmsehGlQIOlAQ8lgtDxpGInXXMAV6JrFwoJ0Ib9PpsVYuwFM+Soa9mVZMfsTO+u9dBhCMEn2AP3mRUljgpGYvQ==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.1.0" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.0.tgz", + "integrity": "sha512-t80LMHorxyKGIPWIX3Qyamg72vj/TGYLyOvzjvkywvNmlQurgHu3ZI2aZnUc5YQlrKPOovnwkVmTEbH+YllQ5Q==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.1.0" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.0.tgz", + "integrity": "sha512-oI6xsOqLHhRA3LSZb07KW3dMAmo1PpyAxwdHkuiC5+N8HzodpqXusOtzBEXKeFG8Za5ycry0xLYsu7hG5aUxoQ==", + "cpu": [ + "wasm32" + ], + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.4.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.0.tgz", + "integrity": "sha512-ofcDYsjJJ1zya9s/GCnXjbFIhTw5/gRVr+SivAGPMXmAml/rLLyDu/HtWntvhiacnL4VYvtgMFw/B2Zz/kgoWQ==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.0.tgz", + "integrity": "sha512-S0X+Uty7Qe6tBfTigFEInchNsGYM/uRjuF1ixi8mLubMfTClmbnVIMxR2/cD5I5Z1m6lHP5D6ASneM3qsF3KFA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@lukeed/ms": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz", @@ -677,6 +1044,43 @@ "node": ">= 6.0.0" } }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, "node_modules/cookie": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", @@ -705,6 +1109,14 @@ "node": ">=6" } }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "engines": { + "node": ">=8" + } + }, "node_modules/esbuild": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", @@ -915,6 +1327,11 @@ "node": ">= 10" } }, + "node_modules/is-arrayish": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", + "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==" + }, "node_modules/is-property": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", @@ -1194,6 +1611,53 @@ "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==" }, + "node_modules/sharp": { + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.0.tgz", + "integrity": "sha512-l7K33wCojhluT82RQXKm3X/y9Y6yBioJ4GaOlGT67yDv8bXZcU3aOlxUM0W1zUUKQjOoIh3VcfQEKHVW9AyijQ==", + "hasInstallScript": true, + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.7.1" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.0", + "@img/sharp-darwin-x64": "0.34.0", + "@img/sharp-libvips-darwin-arm64": "1.1.0", + "@img/sharp-libvips-darwin-x64": "1.1.0", + "@img/sharp-libvips-linux-arm": "1.1.0", + "@img/sharp-libvips-linux-arm64": "1.1.0", + "@img/sharp-libvips-linux-ppc64": "1.1.0", + "@img/sharp-libvips-linux-s390x": "1.1.0", + "@img/sharp-libvips-linux-x64": "1.1.0", + "@img/sharp-libvips-linuxmusl-arm64": "1.1.0", + "@img/sharp-libvips-linuxmusl-x64": "1.1.0", + "@img/sharp-linux-arm": "0.34.0", + "@img/sharp-linux-arm64": "0.34.0", + "@img/sharp-linux-s390x": "0.34.0", + "@img/sharp-linux-x64": "0.34.0", + "@img/sharp-linuxmusl-arm64": "0.34.0", + "@img/sharp-linuxmusl-x64": "0.34.0", + "@img/sharp-wasm32": "0.34.0", + "@img/sharp-win32-ia32": "0.34.0", + "@img/sharp-win32-x64": "0.34.0" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", + "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, "node_modules/sonic-boom": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", @@ -1240,6 +1704,12 @@ "node": ">=12" } }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "optional": true + }, "node_modules/tsx": { "version": "4.22.4", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz", diff --git a/backend/package.json b/backend/package.json index 81c89b6..c3ccf3f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -17,7 +17,7 @@ "db:migrate:verify": "npm run build && node dist/db/migrate-cli.js verify", "db:migrate:down": "npm run build && node dist/db/migrate-cli.js down", "test:mysql:migration": "npm run build && node tests/mysql-migration-roundtrip.test.mjs", - "test": "npm run build && node tests/backend-contract.test.mjs && node tests/migration-contract.test.mjs && node tests/mysql-pool-contract.test.mjs && node tests/migration-runner.test.mjs && node tests/legacy-money.test.mjs && node tests/legacy-read-repository.test.mjs && node tests/task-repository.test.mjs && node tests/platform-config-repository.test.mjs && node tests/auth.test.mjs && node tests/rbac.test.mjs && node tests/user-management.test.mjs && node tests/store-room.test.mjs" + "test": "npm run build && node tests/backend-contract.test.mjs && node tests/migration-contract.test.mjs && node tests/mysql-pool-contract.test.mjs && node tests/migration-runner.test.mjs && node tests/legacy-money.test.mjs && node tests/legacy-read-repository.test.mjs && node tests/task-repository.test.mjs && node tests/platform-config-repository.test.mjs && node tests/auth.test.mjs && node tests/rbac.test.mjs && node tests/user-management.test.mjs && node tests/store-room.test.mjs && node tests/content-management.test.mjs" }, "dependencies": { "@fastify/cors": "^11.2.0", @@ -25,6 +25,7 @@ "fastify": "^5.8.5", "mysql2": "^3.11.3", "pino": "^9.4.0", + "sharp": "^0.34.0", "zod": "^3.23.8" }, "devDependencies": { diff --git a/backend/src/app.ts b/backend/src/app.ts index 02566e8..6a1e738 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -17,6 +17,10 @@ import { registerStoreRoomRoutes, type StoreRoomRouteOptions } from './routes/store-room-management.js'; +import { + registerContentRoutes, + type ContentRouteOptions +} from './routes/content-management.js'; export interface BuildAppOptions { config?: AppConfig; @@ -24,6 +28,7 @@ export interface BuildAppOptions { auth?: AuthRouteOptions; userManagement?: UserManagementRouteOptions; storeRoom?: StoreRoomRouteOptions; + content?: ContentRouteOptions; } declare module 'fastify' { @@ -78,6 +83,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise; + }>; + }; +} + +export interface AdvertisementInput { + scopeType: 'PLATFORM' | 'TENANT' | 'STORE'; + storeId?: string | null; + title: string; + imageAssetId: string; + targetType: 'NONE' | 'PAGE' | 'URL'; + targetValue: string; + startsAt?: Date | null; + endsAt?: Date | null; + status: 'DRAFT' | 'ACTIVE' | 'INACTIVE'; + sortOrder: number; +} + +interface IdRow extends RowDataPacket { id: string } +interface VersionRow extends RowDataPacket { nextVersion: number } +interface ContentRow extends RowDataPacket { + id: string; scopeType: string; storeId: string | null; title: string; imageUrl: string; + targetType: string; targetValue: string; startsAt: Date | null; endsAt: Date | null; + status: string; sortOrder: number; +} + +export class ContentError extends Error { + constructor(public readonly code: string) { super(code); } +} + +export class ContentRepository { + constructor(private readonly pool: MySqlPool) {} + + async registerAsset(actor: ManagementActor, storeId: string | undefined, image: StoredImage) { + if (storeId) this.assertStoreScope(actor, storeId); + return this.transaction(async (connection) => { + const [result] = await connection.execute( + `INSERT INTO qipai_media_assets + (tenant_id, store_id, storage_path, public_url, mime_type, byte_size, + width, height, checksum_sha256, created_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)`, + [actor.tenantId, storeId ?? null, image.storagePath, image.publicUrl, image.mimeType, + image.byteSize, image.width, image.height, image.checksumSha256, actor.userId] + ); + const assetId = String(result.insertId); + await this.audit(connection, actor, 'MEDIA_ASSET_REGISTERED', 'MEDIA_ASSET', assetId); + return { assetId, url: image.publicUrl }; + }); + } + + async saveDecoration(actor: ManagementActor, input: DecorationInput) { + this.assertStoreScope(actor, input.storeId); + return this.transaction(async (connection) => { + await this.lockStore(connection, actor.tenantId, input.storeId); + const [versions] = await connection.execute( + `SELECT COALESCE(MAX(version), 0) + 1 AS nextVersion + FROM qipai_store_decorations + WHERE tenant_id = ? AND store_id = ? FOR UPDATE`, + [actor.tenantId, input.storeId] + ); + const version = Number(versions[0]?.nextVersion ?? 1); + const [result] = await connection.execute( + `INSERT INTO qipai_store_decorations + (tenant_id, store_id, template_code, schema_version, content_json, + status, version, created_by) + VALUES (?, ?, ?, ?, ?, 'DRAFT', ?, ?)`, + [actor.tenantId, input.storeId, input.templateCode, input.schemaVersion, + JSON.stringify(input.content), version, actor.userId] + ); + await this.audit(connection, actor, 'DECORATION_DRAFT_CREATED', 'DECORATION', String(result.insertId)); + return { decorationId: String(result.insertId), version }; + }); + } + + async publishDecoration(actor: ManagementActor, decorationId: string, storeId: string) { + this.assertStoreScope(actor, storeId); + return this.transaction(async (connection) => { + const [rows] = await connection.execute( + `SELECT id FROM qipai_store_decorations + WHERE tenant_id = ? AND store_id = ? AND id = ? AND deleted_at IS NULL FOR UPDATE`, + [actor.tenantId, storeId, decorationId] + ); + if (!rows[0]) throw new ContentError('DECORATION_NOT_FOUND'); + await connection.execute( + `UPDATE qipai_store_decorations SET status = 'ARCHIVED' + WHERE tenant_id = ? AND store_id = ? AND status = 'PUBLISHED'`, + [actor.tenantId, storeId] + ); + await connection.execute( + `UPDATE qipai_store_decorations SET status = 'PUBLISHED', + published_at = UTC_TIMESTAMP(3) + WHERE tenant_id = ? AND store_id = ? AND id = ?`, + [actor.tenantId, storeId, decorationId] + ); + await this.audit(connection, actor, 'DECORATION_PUBLISHED', 'DECORATION', decorationId); + return { decorationId, published: true }; + }); + } + + async listAdvertisements(actor: ManagementActor) { + const scope = this.adScope(actor); + const [rows] = await this.pool.execute( + `SELECT a.id, a.scope_type AS scopeType, a.store_id AS storeId, a.title, + m.public_url AS imageUrl, a.target_type AS targetType, + a.target_value AS targetValue, a.starts_at AS startsAt, a.ends_at AS endsAt, + a.status, a.sort_order AS sortOrder + FROM qipai_advertisements a + INNER JOIN qipai_media_assets m ON m.id = a.image_asset_id AND m.tenant_id = a.tenant_id + WHERE a.tenant_id = ? AND a.deleted_at IS NULL AND ${scope.sql} + ORDER BY a.sort_order, a.id DESC`, + [actor.tenantId, ...scope.params] + ); + return rows.map((row) => ({ ...row, id: String(row.id), storeId: row.storeId && String(row.storeId) })); + } + + async saveAdvertisement(actor: ManagementActor, input: AdvertisementInput) { + this.assertAdScope(actor, input); + return this.transaction(async (connection) => { + const [result] = await connection.execute( + `INSERT INTO qipai_advertisements + (tenant_id, scope_type, store_id, title, image_asset_id, target_type, + target_value, starts_at, ends_at, status, sort_order, created_by) + SELECT ?, ?, ?, ?, m.id, ?, ?, ?, ?, ?, ?, ? + FROM qipai_media_assets m + WHERE m.tenant_id = ? AND m.id = ? AND m.deleted_at IS NULL`, + [actor.tenantId, input.scopeType, input.storeId ?? null, input.title, + input.targetType, input.targetValue, input.startsAt ?? null, input.endsAt ?? null, + input.status, input.sortOrder, actor.userId, actor.tenantId, input.imageAssetId] + ); + if (result.affectedRows !== 1) throw new ContentError('IMAGE_ASSET_NOT_FOUND'); + const advertisementId = String(result.insertId); + await this.audit(connection, actor, 'ADVERTISEMENT_CREATED', 'ADVERTISEMENT', advertisementId); + return { advertisementId }; + }); + } + + private assertAdScope(actor: ManagementActor, input: AdvertisementInput) { + const tenantManager = actor.access.capabilities.includes('tenant.manage') + || actor.access.roles.includes('PLATFORM_ADMIN'); + if (input.scopeType === 'PLATFORM' && !actor.access.roles.includes('PLATFORM_ADMIN')) { + throw new ContentError('PLATFORM_AD_FORBIDDEN'); + } + if (input.scopeType === 'TENANT' && !tenantManager) throw new ContentError('TENANT_AD_FORBIDDEN'); + if (input.scopeType === 'STORE') { + if (!input.storeId) throw new ContentError('STORE_REQUIRED'); + this.assertStoreScope(actor, input.storeId); + } + } + + private assertStoreScope(actor: ManagementActor, storeId: string) { + if (actor.access.capabilities.includes('tenant.manage') + || actor.access.roles.includes('PLATFORM_ADMIN')) return; + if (!actor.access.capabilities.includes('store.operation.write') + || !actor.access.storeIds.includes(storeId)) { + throw new ContentError('STORE_SCOPE_FORBIDDEN'); + } + } + + private adScope(actor: ManagementActor) { + if (actor.access.capabilities.includes('tenant.manage') + || actor.access.roles.includes('PLATFORM_ADMIN')) return { sql: '1 = 1', params: [] as string[] }; + if (actor.access.storeIds.length === 0) return { sql: "a.scope_type = 'TENANT'", params: [] as string[] }; + return { + sql: `(a.scope_type = 'TENANT' OR (a.scope_type = 'STORE' + AND a.store_id IN (${actor.access.storeIds.map(() => '?').join(',')})))`, + params: actor.access.storeIds + }; + } + + private async lockStore(connection: PoolConnection, tenantId: string, storeId: string) { + const [rows] = await connection.execute( + `SELECT id FROM qipai_stores + WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL FOR UPDATE`, + [tenantId, storeId] + ); + if (!rows[0]) throw new ContentError('STORE_NOT_FOUND'); + } + + private async audit( + connection: PoolConnection, actor: ManagementActor, + action: string, resourceType: string, resourceId: string + ) { + await connection.execute( + `INSERT INTO qipai_audit_logs + (tenant_id, actor_type, actor_id, action, resource_type, resource_id, + trace_id, ip, user_agent, metadata) + VALUES (?, 'USER', ?, ?, ?, ?, ?, ?, ?, JSON_OBJECT())`, + [actor.tenantId, actor.userId, action, resourceType, resourceId, + actor.traceId, actor.ip, actor.userAgent.slice(0, 255)] + ); + } + + private async transaction(work: (connection: PoolConnection) => Promise) { + const connection = await this.pool.getConnection(); + try { + await connection.beginTransaction(); + const result = await work(connection); + await connection.commit(); + return result; + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + } +} diff --git a/backend/src/content/media-storage.ts b/backend/src/content/media-storage.ts new file mode 100644 index 0000000..2202014 --- /dev/null +++ b/backend/src/content/media-storage.ts @@ -0,0 +1,77 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { extname, resolve, sep } from 'node:path'; +import sharp from 'sharp'; + +export interface StoredImage { + storagePath: string; + publicUrl: string; + mimeType: 'image/webp'; + byteSize: number; + width: number; + height: number; + checksumSha256: string; +} + +export class MediaValidationError extends Error { + constructor(public readonly code: string) { super(code); } +} + +export class MediaStorage { + constructor( + private readonly root: string, + private readonly publicBaseUrl = 'https://api.txyundm.cn/uploads' + ) {} + + async storeImage(input: { + tenantId: string; + storeId?: string; + originalName: string; + contentType: string; + body: Buffer; + }): Promise { + if (input.body.length === 0 || input.body.length > 8 * 1024 * 1024) { + throw new MediaValidationError('IMAGE_SIZE_INVALID'); + } + if (!['image/jpeg', 'image/png', 'image/webp'].includes(input.contentType)) { + throw new MediaValidationError('IMAGE_TYPE_INVALID'); + } + if (!['.jpg', '.jpeg', '.png', '.webp'].includes(extname(input.originalName).toLowerCase())) { + throw new MediaValidationError('IMAGE_EXTENSION_INVALID'); + } + let result: Buffer; + let metadata: sharp.Metadata; + try { + const source = sharp(input.body, { failOn: 'warning', limitInputPixels: 40_000_000 }); + metadata = await source.metadata(); + if (!metadata.width || !metadata.height) throw new Error('missing dimensions'); + result = await source + .rotate() + .resize({ width: 1920, height: 1920, fit: 'inside', withoutEnlargement: true }) + .webp({ quality: 82 }) + .toBuffer(); + } catch { + throw new MediaValidationError('IMAGE_DECODE_FAILED'); + } + const outputMetadata = await sharp(result).metadata(); + const relativeDirectory = ['tenants', input.tenantId, input.storeId ? `stores/${input.storeId}` : 'shared']; + const directory = resolve(this.root, ...relativeDirectory); + const safeRoot = resolve(this.root); + if (directory !== safeRoot && !directory.startsWith(`${safeRoot}${sep}`)) { + throw new MediaValidationError('IMAGE_PATH_INVALID'); + } + await mkdir(directory, { recursive: true }); + const fileName = `${randomUUID()}.webp`; + await writeFile(resolve(directory, fileName), result, { flag: 'wx' }); + const urlPath = [...relativeDirectory, fileName].join('/'); + return { + storagePath: urlPath, + publicUrl: `${this.publicBaseUrl}/${urlPath}`, + mimeType: 'image/webp', + byteSize: result.length, + width: outputMetadata.width ?? metadata.width ?? 0, + height: outputMetadata.height ?? metadata.height ?? 0, + checksumSha256: createHash('sha256').update(result).digest('hex') + }; + } +} diff --git a/backend/src/db/migration-runner.ts b/backend/src/db/migration-runner.ts index ed2ee5d..13f0786 100644 --- a/backend/src/db/migration-runner.ts +++ b/backend/src/db/migration-runner.ts @@ -27,7 +27,8 @@ const migrationFiles: Record = { 'database/migrations/2026061804_m02b_wechat_auth.up.sql', 'database/migrations/2026061805_m02c_rbac.up.sql', 'database/migrations/2026061806_m02d_user_management.up.sql', - 'database/migrations/2026061807_m03a_store_room_domain.up.sql' + 'database/migrations/2026061807_m03a_store_room_domain.up.sql', + 'database/migrations/2026061808_m03b_decoration_ads_media.up.sql' ], verify: [ 'database/migrations/2026061601_m01b_core_schema.verify.sql', @@ -36,9 +37,11 @@ const migrationFiles: Record = { 'database/migrations/2026061804_m02b_wechat_auth.verify.sql', 'database/migrations/2026061805_m02c_rbac.verify.sql', 'database/migrations/2026061806_m02d_user_management.verify.sql', - 'database/migrations/2026061807_m03a_store_room_domain.verify.sql' + 'database/migrations/2026061807_m03a_store_room_domain.verify.sql', + 'database/migrations/2026061808_m03b_decoration_ads_media.verify.sql' ], down: [ + 'database/migrations/2026061808_m03b_decoration_ads_media.down.sql', 'database/migrations/2026061807_m03a_store_room_domain.down.sql', 'database/migrations/2026061806_m02d_user_management.down.sql', 'database/migrations/2026061805_m02c_rbac.down.sql', @@ -168,7 +171,8 @@ export async function executeMigrationPlan( 3, 7, 1, 5, 3, 7, 1, 1, 3, 1, - 3, 6, 13, 1 + 3, 6, 13, 1, + 3, 3, 1 ][index] ?? 1; if (!Array.isArray(result) || result.length < minimumRows) { throw new Error( diff --git a/backend/src/routes/content-management.ts b/backend/src/routes/content-management.ts new file mode 100644 index 0000000..31f1cce --- /dev/null +++ b/backend/src/routes/content-management.ts @@ -0,0 +1,161 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import { z } from 'zod'; +import type { AuthRepository } from '../auth/auth-repository.js'; +import { authenticateAccessToken } from '../auth/authenticate.js'; +import type { AccessProfile } from '../auth/rbac-repository.js'; +import type { ManagementActor } from '../auth/user-management-repository.js'; +import { ContentError, type ContentRepository } from '../content/content-repository.js'; +import { MediaStorage, MediaValidationError } from '../content/media-storage.js'; + +const idSchema = z.object({ id: z.string().regex(/^[1-9]\d{0,19}$/) }); +const storeQuerySchema = z.object({ storeId: z.string().regex(/^[1-9]\d{0,19}$/) }); +const componentSchema = z.object({ + type: z.enum(['HERO', 'NOTICE', 'GALLERY', 'CONTACT', 'ROOM_LIST']), + props: z.record(z.unknown()) +}); +const decorationSchema = z.object({ + storeId: z.string().regex(/^[1-9]\d{0,19}$/), + templateCode: z.string().trim().min(1).max(64), + schemaVersion: z.number().int().min(1).max(100), + content: z.object({ components: z.array(componentSchema).max(50) }) +}); +const adSchema = z.object({ + scopeType: z.enum(['PLATFORM', 'TENANT', 'STORE']), + storeId: z.string().regex(/^[1-9]\d{0,19}$/).nullable().optional(), + title: z.string().trim().min(1).max(128), + imageAssetId: z.string().regex(/^[1-9]\d{0,19}$/), + targetType: z.enum(['NONE', 'PAGE', 'URL']).default('NONE'), + targetValue: z.string().trim().max(512).default(''), + startsAt: z.coerce.date().nullable().optional(), + endsAt: z.coerce.date().nullable().optional(), + status: z.enum(['DRAFT', 'ACTIVE', 'INACTIVE']).default('DRAFT'), + sortOrder: z.number().int().min(-100000).max(100000).default(0) +}).refine((value) => !value.startsAt || !value.endsAt || value.endsAt > value.startsAt); + +export interface ContentRouteOptions { + repository: Pick; + mediaStorage: MediaStorage; + authRepository: Pick; + accessControl: { getAccessProfile(tenantId: string, userId: string): Promise }; + jwtSecret: string; +} + +export async function registerContentRoutes(app: FastifyInstance, options: ContentRouteOptions) { + if (!app.hasContentTypeParser('application/octet-stream')) { + app.addContentTypeParser( + 'application/octet-stream', + { parseAs: 'buffer', bodyLimit: 8 * 1024 * 1024 }, + (_request, body, done) => done(null, body) + ); + } + app.post('/admin-api/media/images', async (request, reply) => { + const actor = await requireContentManager(request, reply, options); + if (!actor) return; + const storeIdResult = z.string().regex(/^[1-9]\d{0,19}$/).optional() + .safeParse(singleHeader(request.headers['x-store-id'])); + const originalName = singleHeader(request.headers['x-file-name']); + if (!storeIdResult.success || !originalName || !Buffer.isBuffer(request.body)) { + return invalid(reply, request.traceId); + } + const storeId = storeIdResult.data; + return handle(reply, request.traceId, async () => { + const image = await options.mediaStorage.storeImage({ + tenantId: actor.tenantId, storeId, originalName, + contentType: singleHeader(request.headers['x-image-content-type']) ?? '', + body: request.body as Buffer + }); + return reply.status(201).send({ + code: 0, data: await options.repository.registerAsset(actor, storeId, image), + traceId: request.traceId + }); + }); + }); + app.post('/admin-api/decorations', async (request, reply) => { + const actor = await requireContentManager(request, reply, options); + const body = decorationSchema.safeParse(request.body); + if (!actor || !body.success) return actor ? invalid(reply, request.traceId) : undefined; + return handle(reply, request.traceId, async () => reply.status(201).send({ + code: 0, data: await options.repository.saveDecoration(actor, body.data), + traceId: request.traceId + })); + }); + app.post('/admin-api/decorations/:id/publish', async (request, reply) => { + const actor = await requireContentManager(request, reply, options); + const params = idSchema.safeParse(request.params); + const query = storeQuerySchema.safeParse(request.query); + if (!actor || !params.success || !query.success) { + return actor ? invalid(reply, request.traceId) : undefined; + } + return handle(reply, request.traceId, async () => ({ + code: 0, + data: await options.repository.publishDecoration(actor, params.data.id, query.data.storeId), + traceId: request.traceId + })); + }); + app.get('/admin-api/advertisements', async (request, reply) => { + const actor = await requireContentManager(request, reply, options); + if (!actor) return; + return { code: 0, data: await options.repository.listAdvertisements(actor), + traceId: request.traceId }; + }); + app.post('/admin-api/advertisements', async (request, reply) => { + const actor = await requireContentManager(request, reply, options); + const body = adSchema.safeParse(request.body); + if (!actor || !body.success) return actor ? invalid(reply, request.traceId) : undefined; + return handle(reply, request.traceId, async () => reply.status(201).send({ + code: 0, data: await options.repository.saveAdvertisement(actor, body.data), + traceId: request.traceId + })); + }); +} + +async function requireContentManager( + request: FastifyRequest, reply: FastifyReply, options: ContentRouteOptions +): Promise { + const auth = await authenticateAccessToken( + request.headers.authorization, options.authRepository, options.jwtSecret + ); + if (!auth) { + reply.status(401).send({ code: 'AUTH_SESSION_INVALID', message: 'Authentication required.', + traceId: request.traceId }); + return null; + } + const access = await options.accessControl.getAccessProfile( + auth.session.tenantId, auth.session.user.id + ); + if (!access.capabilities.some((item) => + item === 'store.operation.write' || item === 'tenant.manage' + ) && !access.roles.includes('PLATFORM_ADMIN')) { + reply.status(403).send({ code: 'CONTENT_MANAGEMENT_FORBIDDEN', + message: 'Content management permission is required.', traceId: request.traceId }); + return null; + } + return { + tenantId: auth.session.tenantId, userId: auth.session.user.id, access, + traceId: request.traceId, ip: request.ip, userAgent: request.headers['user-agent'] ?? '' + }; +} + +async function handle(reply: FastifyReply, traceId: string, work: () => Promise) { + try { + return await work(); + } catch (error) { + if (!(error instanceof ContentError) && !(error instanceof MediaValidationError)) throw error; + const forbidden = error.code.endsWith('_FORBIDDEN'); + return reply.status(forbidden ? 403 : 400).send({ + code: error.code, message: 'The content request is invalid or not allowed.', traceId + }); + } +} + +function singleHeader(value: string | string[] | undefined) { + return Array.isArray(value) ? value[0] : value; +} + +function invalid(reply: FastifyReply, traceId: string) { + return reply.status(400).send({ + code: 'INVALID_CONTENT_REQUEST', message: 'The content request is invalid.', traceId + }); +} diff --git a/backend/src/server.ts b/backend/src/server.ts index 611f086..60546d7 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -7,6 +7,9 @@ import { RbacRepository } from './auth/rbac-repository.js'; import { parseWechatAppSecrets, WechatHttpClient } from './auth/wechat-client.js'; import { UserManagementRepository } from './auth/user-management-repository.js'; import { StoreRoomRepository } from './stores/store-room-repository.js'; +import { ContentRepository } from './content/content-repository.js'; +import { MediaStorage } from './content/media-storage.js'; +import { resolve } from 'node:path'; const config = loadConfig(); const pool = createMySqlPool(config); @@ -34,6 +37,13 @@ const app = await buildApp({ authRepository, accessControl, jwtSecret: config.auth.jwtSecret + }, + content: { + repository: new ContentRepository(pool), + mediaStorage: new MediaStorage(resolve(process.cwd(), 'shared', 'uploads')), + authRepository, + accessControl, + jwtSecret: config.auth.jwtSecret } }); app.addHook('onClose', async () => { diff --git a/backend/tests/content-management.test.mjs b/backend/tests/content-management.test.mjs new file mode 100644 index 0000000..66177b0 --- /dev/null +++ b/backend/tests/content-management.test.mjs @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import sharp from 'sharp'; +import { MediaStorage, MediaValidationError } from '../dist/content/media-storage.js'; +import { ContentError, ContentRepository } from '../dist/content/content-repository.js'; + +const root = await mkdtemp(join(tmpdir(), 'qipai-media-')); +try { + const png = await sharp({ + create: { width: 2400, height: 1200, channels: 3, background: '#336699' } + }).png().toBuffer(); + const storage = new MediaStorage(root); + const image = await storage.storeImage({ + tenantId: '7', storeId: '11', originalName: 'banner.png', + contentType: 'image/png', body: png + }); + assert.equal(image.mimeType, 'image/webp'); + assert.ok(image.width <= 1920); + assert.match(image.storagePath, /^tenants\/7\/stores\/11\/.+\.webp$/); + assert.ok((await readFile(join(root, ...image.storagePath.split('/')))).length > 0); + await assert.rejects( + () => storage.storeImage({ + tenantId: '7', originalName: 'bad.txt', contentType: 'text/plain', + body: Buffer.from('not an image') + }), + (error) => error instanceof MediaValidationError && error.code === 'IMAGE_TYPE_INVALID' + ); +} finally { + await rm(root, { recursive: true, force: true }); +} + +const storeActor = { + tenantId: '7', userId: '21', + access: { + roles: ['STORE_ADMIN'], capabilities: ['store.operation.write'], storeIds: ['11'] + }, + traceId: 'trace', ip: '127.0.0.1', userAgent: 'test' +}; +const repository = new ContentRepository({ async execute() { return [[], []]; } }); +await assert.rejects( + () => repository.saveAdvertisement(storeActor, { + scopeType: 'PLATFORM', title: 'x', imageAssetId: '1', + targetType: 'NONE', targetValue: '', status: 'DRAFT', sortOrder: 0 + }), + (error) => error instanceof ContentError && error.code === 'PLATFORM_AD_FORBIDDEN' +); + +console.log('PASS: M03-B image compression, tenant paths and advertisement scope validation are present.'); diff --git a/backend/tests/migration-contract.test.mjs b/backend/tests/migration-contract.test.mjs index 8bf5406..c38b984 100644 --- a/backend/tests/migration-contract.test.mjs +++ b/backend/tests/migration-contract.test.mjs @@ -30,6 +30,9 @@ const userManagementVerifySql = read('database/migrations/2026061806_m02d_user_m const storeRoomUpSql = read('database/migrations/2026061807_m03a_store_room_domain.up.sql'); const storeRoomDownSql = read('database/migrations/2026061807_m03a_store_room_domain.down.sql'); const storeRoomVerifySql = read('database/migrations/2026061807_m03a_store_room_domain.verify.sql'); +const contentUpSql = read('database/migrations/2026061808_m03b_decoration_ads_media.up.sql'); +const contentDownSql = read('database/migrations/2026061808_m03b_decoration_ads_media.down.sql'); +const contentVerifySql = read('database/migrations/2026061808_m03b_decoration_ads_media.verify.sql'); const coreTables = [ 'qipai_schema_migrations', @@ -147,5 +150,15 @@ assert.match(storeRoomUpSql, /configuration_status VARCHAR/); assert.match(storeRoomUpSql, /operational_status VARCHAR/); assert.match(storeRoomUpSql, /weekday_price_cents INT UNSIGNED/); assert.match(storeRoomUpSql, /CHECK \(ends_at > starts_at\)/); +for (const table of [ + 'qipai_media_assets', 'qipai_store_decorations', 'qipai_advertisements' +]) { + assert.match(contentUpSql, new RegExp(`CREATE TABLE IF NOT EXISTS ${table}`)); + assert.match(contentDownSql, new RegExp(`DROP TABLE IF EXISTS ${table}`)); + assert.match(contentVerifySql, new RegExp(`'${table}'`)); +} +assert.match(contentUpSql, /schema_version INT UNSIGNED/); +assert.match(contentUpSql, /scope_type VARCHAR/); +assert.match(contentUpSql, /checksum_sha256 CHAR\(64\)/); -console.log('PASS: M01-B through M03-A migration contracts are present.'); +console.log('PASS: M01-B through M03-B migration contracts are present.'); diff --git a/backend/tests/migration-runner.test.mjs b/backend/tests/migration-runner.test.mjs index 25bef74..65a5f5d 100644 --- a/backend/tests/migration-runner.test.mjs +++ b/backend/tests/migration-runner.test.mjs @@ -18,7 +18,8 @@ assert.match(plan.file, /2026061803_m02a_tenant_apps\.up\.sql/); assert.match(plan.file, /2026061804_m02b_wechat_auth\.up\.sql/); assert.match(plan.file, /2026061805_m02c_rbac\.up\.sql/); assert.match(plan.file, /2026061806_m02d_user_management\.up\.sql/); -assert.match(plan.file, /2026061807_m03a_store_room_domain\.up\.sql$/); +assert.match(plan.file, /2026061807_m03a_store_room_domain\.up\.sql/); +assert.match(plan.file, /2026061808_m03b_decoration_ads_media\.up\.sql$/); assert.match(plan.checksum, /^[a-f0-9]{64}$/); assert.ok(plan.statements.length >= 11); diff --git a/backend/tests/mysql-migration-roundtrip.test.mjs b/backend/tests/mysql-migration-roundtrip.test.mjs index 7639f8c..03af9d5 100644 --- a/backend/tests/mysql-migration-roundtrip.test.mjs +++ b/backend/tests/mysql-migration-roundtrip.test.mjs @@ -14,6 +14,7 @@ import { AuthRepository } from '../dist/auth/auth-repository.js'; import { RbacRepository } from '../dist/auth/rbac-repository.js'; import { UserManagementRepository } from '../dist/auth/user-management-repository.js'; import { StoreRoomRepository, StoreRoomError } from '../dist/stores/store-room-repository.js'; +import { ContentRepository, ContentError } from '../dist/content/content-repository.js'; import { executeMigrationPlan, loadMigrationPlan, @@ -21,11 +22,13 @@ import { } from '../dist/db/migration-runner.js'; const expectedTables = [ + 'qipai_advertisements', 'qipai_async_tasks', 'qipai_audit_logs', 'qipai_auth_sessions', 'qipai_devices', 'qipai_legacy_table_mappings', + 'qipai_media_assets', 'qipai_members', 'qipai_orders', 'qipai_outbox_events', @@ -39,6 +42,7 @@ const expectedTables = [ 'qipai_rooms', 'qipai_schema_migrations', 'qipai_store_business_hours', + 'qipai_store_decorations', 'qipai_stores', 'qipai_tenant_apps', 'qipai_tenant_configs', @@ -68,10 +72,10 @@ async function readMigrationVersions(pool) { const [rows] = await pool.query( `SELECT version, name FROM qipai_schema_migrations - WHERE version IN (?, ?, ?, ?, ?, ?, ?) + WHERE version IN (?, ?, ?, ?, ?, ?, ?, ?) ORDER BY version`, ['2026061601', '2026061802', '2026061803', '2026061804', - '2026061805', '2026061806', '2026061807'] + '2026061805', '2026061806', '2026061807', '2026061808'] ); return rows; } @@ -389,6 +393,70 @@ async function assertStoreRoomDomain(pool, context) { ]); } +async function assertContentManagement(pool, context) { + const [adminRows] = await pool.query( + `SELECT u.id FROM qipai_users u + INNER JOIN qipai_user_roles ur ON ur.tenant_id = u.tenant_id AND ur.user_id = u.id + INNER JOIN qipai_roles r ON r.id = ur.role_id AND r.tenant_id = ur.tenant_id + WHERE u.tenant_id = ? AND r.code = 'TENANT_ADMIN' LIMIT 1`, + [context.tenantId] + ); + const [storeRows] = await pool.query( + `SELECT id FROM qipai_stores WHERE tenant_id = ? AND name = 'M03A Store' LIMIT 1`, + [context.tenantId] + ); + const adminId = String(adminRows[0].id); + const storeId = String(storeRows[0].id); + const rbac = new RbacRepository(pool); + const access = await rbac.getAccessProfile(context.tenantId, adminId); + const actor = { + tenantId: context.tenantId, userId: adminId, access, + traceId: 'm03b-live-test', ip: '127.0.0.1', userAgent: 'M03-B live test' + }; + const repository = new ContentRepository(pool); + const asset = await repository.registerAsset(actor, storeId, { + storagePath: `tenants/${context.tenantId}/stores/${storeId}/sanitized.webp`, + publicUrl: `https://api.txyundm.cn/uploads/tenants/${context.tenantId}/stores/${storeId}/sanitized.webp`, + mimeType: 'image/webp', byteSize: 1024, width: 1200, height: 600, + checksumSha256: 'a'.repeat(64) + }); + const draft1 = await repository.saveDecoration(actor, { + storeId, templateCode: 'classic', schemaVersion: 1, + content: { components: [{ type: 'HERO', props: { assetId: asset.assetId } }] } + }); + const draft2 = await repository.saveDecoration(actor, { + storeId, templateCode: 'modern', schemaVersion: 1, + content: { components: [{ type: 'ROOM_LIST', props: {} }] } + }); + assert.equal(draft1.version, 1); + assert.equal(draft2.version, 2); + await repository.publishDecoration(actor, draft1.decorationId, storeId); + await repository.publishDecoration(actor, draft2.decorationId, storeId); + const [decorationRows] = await pool.query( + `SELECT version, status FROM qipai_store_decorations + WHERE tenant_id = ? AND store_id = ? ORDER BY version`, + [context.tenantId, storeId] + ); + assert.deepEqual(decorationRows, [ + { version: 1, status: 'ARCHIVED' }, + { version: 2, status: 'PUBLISHED' } + ]); + const ad = await repository.saveAdvertisement(actor, { + scopeType: 'STORE', storeId, title: 'Store banner', imageAssetId: asset.assetId, + targetType: 'PAGE', targetValue: '/pages/index/index', + startsAt: null, endsAt: null, status: 'ACTIVE', sortOrder: 1 + }); + assert.match(ad.advertisementId, /^[1-9]\d*$/); + assert.equal((await repository.listAdvertisements(actor))[0].scopeType, 'STORE'); + await assert.rejects( + () => repository.saveAdvertisement(actor, { + scopeType: 'PLATFORM', title: 'forbidden', imageAssetId: asset.assetId, + targetType: 'NONE', targetValue: '', status: 'DRAFT', sortOrder: 0 + }), + (error) => error instanceof ContentError && error.code === 'PLATFORM_AD_FORBIDDEN' + ); +} + const config = loadConfig(); assert.equal(config.mysql.passwordConfigured, true, 'Live migration test requires a temporary password.'); assert.match( @@ -419,13 +487,15 @@ try { { version: '2026061804', name: 'm02b_wechat_auth' }, { version: '2026061805', name: 'm02c_rbac' }, { version: '2026061806', name: 'm02d_user_management' }, - { version: '2026061807', name: 'm03a_store_room_domain' } + { version: '2026061807', name: 'm03a_store_room_domain' }, + { version: '2026061808', name: 'm03b_decoration_ads_media' } ]); await assertTaskDurability(pool); const loginContext = await assertPlatformTenantIsolation(pool); await assertRevocableAuthSession(pool, loginContext); await assertUserManagement(pool, loginContext); await assertStoreRoomDomain(pool, loginContext); + await assertContentManagement(pool, loginContext); await assertLegacyCompatibility(pool); console.log('PASS: first up, verify, tenant isolation and revocable auth checks completed.'); @@ -444,7 +514,8 @@ try { { version: '2026061804', name: 'm02b_wechat_auth' }, { version: '2026061805', name: 'm02c_rbac' }, { version: '2026061806', name: 'm02d_user_management' }, - { version: '2026061807', name: 'm03a_store_room_domain' } + { version: '2026061807', name: 'm03a_store_room_domain' }, + { version: '2026061808', name: 'm03b_decoration_ads_media' } ]); await assertLegacyCompatibility(pool); console.log('PASS: second up and verify restored the schema.'); @@ -485,7 +556,11 @@ try { 'room category and integer-cent pricing', 'configuration and operational status separation', 'room disabled period', - 'cross-store management rejection' + 'cross-store management rejection', + 'tenant-isolated media asset', + 'versioned decoration publish and archive', + 'store advertisement delivery scope', + 'platform advertisement rejection' ] }, null, 2)); } finally { diff --git a/database/migrations/2026061808_m03b_decoration_ads_media.down.sql b/database/migrations/2026061808_m03b_decoration_ads_media.down.sql new file mode 100644 index 0000000..97431fa --- /dev/null +++ b/database/migrations/2026061808_m03b_decoration_ads_media.down.sql @@ -0,0 +1,4 @@ +DELETE FROM qipai_schema_migrations WHERE version = '2026061808'; +DROP TABLE IF EXISTS qipai_advertisements; +DROP TABLE IF EXISTS qipai_store_decorations; +DROP TABLE IF EXISTS qipai_media_assets; diff --git a/database/migrations/2026061808_m03b_decoration_ads_media.up.sql b/database/migrations/2026061808_m03b_decoration_ads_media.up.sql new file mode 100644 index 0000000..e309d64 --- /dev/null +++ b/database/migrations/2026061808_m03b_decoration_ads_media.up.sql @@ -0,0 +1,74 @@ +CREATE TABLE IF NOT EXISTS qipai_media_assets ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + store_id BIGINT UNSIGNED NULL, + kind VARCHAR(32) NOT NULL DEFAULT 'IMAGE', + storage_path VARCHAR(512) NOT NULL, + public_url VARCHAR(512) NOT NULL, + mime_type VARCHAR(64) NOT NULL, + byte_size INT UNSIGNED NOT NULL, + width INT UNSIGNED NOT NULL, + height INT UNSIGNED NOT NULL, + checksum_sha256 CHAR(64) NOT NULL, + created_by BIGINT UNSIGNED NULL, + created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + deleted_at DATETIME(3) NULL, + CONSTRAINT fk_qipai_media_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id), + CONSTRAINT fk_qipai_media_store FOREIGN KEY (store_id) REFERENCES qipai_stores(id), + CONSTRAINT fk_qipai_media_creator FOREIGN KEY (created_by) REFERENCES qipai_users(id), + UNIQUE KEY uq_qipai_media_tenant_checksum (tenant_id, checksum_sha256), + KEY idx_qipai_media_store_time (tenant_id, store_id, created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS qipai_store_decorations ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + store_id BIGINT UNSIGNED NOT NULL, + template_code VARCHAR(64) NOT NULL, + schema_version INT UNSIGNED NOT NULL, + content_json JSON NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'DRAFT', + version INT UNSIGNED NOT NULL DEFAULT 1, + published_at DATETIME(3) NULL, + created_by BIGINT UNSIGNED NULL, + created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3), + deleted_at DATETIME(3) NULL, + CONSTRAINT fk_qipai_decorations_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id), + CONSTRAINT fk_qipai_decorations_store FOREIGN KEY (store_id) REFERENCES qipai_stores(id), + CONSTRAINT fk_qipai_decorations_creator FOREIGN KEY (created_by) REFERENCES qipai_users(id), + UNIQUE KEY uq_qipai_decorations_version (tenant_id, store_id, version), + KEY idx_qipai_decorations_published (tenant_id, store_id, status, published_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS qipai_advertisements ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + scope_type VARCHAR(32) NOT NULL, + store_id BIGINT UNSIGNED NULL, + title VARCHAR(128) NOT NULL, + image_asset_id BIGINT UNSIGNED NOT NULL, + target_type VARCHAR(32) NOT NULL DEFAULT 'NONE', + target_value VARCHAR(512) NOT NULL DEFAULT '', + starts_at DATETIME(3) NULL, + ends_at DATETIME(3) NULL, + status VARCHAR(32) NOT NULL DEFAULT 'DRAFT', + sort_order INT NOT NULL DEFAULT 0, + created_by BIGINT UNSIGNED NULL, + created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3), + deleted_at DATETIME(3) NULL, + CONSTRAINT fk_qipai_ads_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id), + CONSTRAINT fk_qipai_ads_store FOREIGN KEY (store_id) REFERENCES qipai_stores(id), + CONSTRAINT fk_qipai_ads_asset FOREIGN KEY (image_asset_id) REFERENCES qipai_media_assets(id), + CONSTRAINT fk_qipai_ads_creator FOREIGN KEY (created_by) REFERENCES qipai_users(id), + KEY idx_qipai_ads_delivery (tenant_id, scope_type, store_id, status, starts_at, ends_at), + CONSTRAINT chk_qipai_ads_scope CHECK ( + (scope_type = 'STORE' AND store_id IS NOT NULL) + OR (scope_type IN ('PLATFORM', 'TENANT') AND store_id IS NULL) + ), + CONSTRAINT chk_qipai_ads_window CHECK (ends_at IS NULL OR starts_at IS NULL OR ends_at > starts_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +INSERT IGNORE INTO qipai_schema_migrations (version, name) +VALUES ('2026061808', 'm03b_decoration_ads_media'); diff --git a/database/migrations/2026061808_m03b_decoration_ads_media.verify.sql b/database/migrations/2026061808_m03b_decoration_ads_media.verify.sql new file mode 100644 index 0000000..07e0da6 --- /dev/null +++ b/database/migrations/2026061808_m03b_decoration_ads_media.verify.sql @@ -0,0 +1,13 @@ +SELECT table_name FROM information_schema.tables +WHERE table_schema = DATABASE() + AND table_name IN ('qipai_media_assets', 'qipai_store_decorations', 'qipai_advertisements') +ORDER BY table_name; + +SELECT table_name, index_name FROM information_schema.statistics +WHERE table_schema = DATABASE() + AND ((table_name = 'qipai_media_assets' AND index_name = 'uq_qipai_media_tenant_checksum') + OR (table_name = 'qipai_store_decorations' AND index_name = 'uq_qipai_decorations_version') + OR (table_name = 'qipai_advertisements' AND index_name = 'idx_qipai_ads_delivery')) +GROUP BY table_name, index_name ORDER BY table_name; + +SELECT version, name FROM qipai_schema_migrations WHERE version = '2026061808'; diff --git a/docs/api-changelog/2026-06-18-M03-B-content.md b/docs/api-changelog/2026-06-18-M03-B-content.md new file mode 100644 index 0000000..b1760db --- /dev/null +++ b/docs/api-changelog/2026-06-18-M03-B-content.md @@ -0,0 +1,11 @@ +# M03-B 装修、广告与媒体 API + +- `POST /admin-api/media/images`:二进制图片上传;通过 `x-file-name`、`x-image-content-type` 和可选 `x-store-id` 提供元数据。 +- `POST /admin-api/decorations`:保存版本化装修草稿。 +- `POST /admin-api/decorations/:id/publish?storeId=...`:发布指定版本并归档旧版本。 +- `GET /admin-api/advertisements` +- `POST /admin-api/advertisements` + +图片仅接受 JPEG、PNG、WebP,最大 8 MiB、最大 4000 万输入像素,最长边压缩至 1920 并转为 WebP。文件按租户和门店目录隔离。 + +广告范围分为平台、租户和门店。平台广告仅平台管理员可创建,门店广告必须通过门店数据范围校验。 diff --git a/docs/db-changelog/2026-06-18-M03-B-content.md b/docs/db-changelog/2026-06-18-M03-B-content.md new file mode 100644 index 0000000..c942689 --- /dev/null +++ b/docs/db-changelog/2026-06-18-M03-B-content.md @@ -0,0 +1,8 @@ +# M03-B 装修、广告与媒体数据库变更 + +- 迁移版本:`2026061808` +- `qipai_media_assets`:租户素材、尺寸、哈希和公开 URL。 +- `qipai_store_decorations`:模板代码、Schema 版本、内容 JSON、发布版本。 +- `qipai_advertisements`:平台/租户/门店广告、投放时间、跳转和排序。 + +同一门店每次保存装修都会生成递增版本;发布新版本时旧版本转为 `ARCHIVED`。素材唯一索引包含 `tenant_id`,禁止跨租户引用。 diff --git a/docs/devlogs/2026-06-18-M03-B-装修广告与媒体.md b/docs/devlogs/2026-06-18-M03-B-装修广告与媒体.md new file mode 100644 index 0000000..07dd9b5 --- /dev/null +++ b/docs/devlogs/2026-06-18-M03-B-装修广告与媒体.md @@ -0,0 +1,28 @@ +# M03-B 装修、广告与媒体 + +- 日期:2026-06-18 +- 起始 commit:`7e9b534` +- 工程 commit:本阶段工程提交 +- ENGINEERING_DELTA=YES +- 子阶段状态:待 push 与远端校验 + +## 工程增量 + +- 平台、租户、门店三级广告及权限边界。 +- 门店装修草稿、版本递增、发布和旧版本归档。 +- JPEG/PNG/WebP 上传、解码校验、限像素、压缩转 WebP。 +- 租户/门店目录隔离、素材哈希去重和数据库归属校验。 +- 装修组件采用版本化 Schema,首版支持 HERO、NOTICE、GALLERY、CONTACT、ROOM_LIST。 + +## 验证 + +- Windows 全量 `npm test` 通过。 +- WSL MySQL 8.4.9:`up → verify → down → up → verify` 通过。 +- 真实迁移语句:up 44、verify 26、down 41。 +- 实测装修版本 1 发布后被版本 2 归档、门店广告读取和平台广告越权拒绝。 + +## 影响 + +- 新增 `sharp` 图片处理依赖。 +- 生产上传根目录仍为后端 `shared/uploads`,由部署目录映射到统一上传目录。 +- 生产迁移和目录权限配置必须通过 Ubuntu 菜单执行。 diff --git a/scripts/dev/wsl/mysql-migration-roundtrip.sh b/scripts/dev/wsl/mysql-migration-roundtrip.sh index 876b2dd..0f2e11b 100644 --- a/scripts/dev/wsl/mysql-migration-roundtrip.sh +++ b/scripts/dev/wsl/mysql-migration-roundtrip.sh @@ -93,6 +93,6 @@ export QIPAI_MYSQL_USER="${username}" export QIPAI_MYSQL_PASSWORD="${password}" export QIPAI_MYSQL_CONNECTION_LIMIT=2 -echo "INFO: MySQL ${mysql_version}; running M01-B through M03-A migration roundtrip in a temporary database." +echo "INFO: MySQL ${mysql_version}; running M01-B through M03-B migration roundtrip in a temporary database." npm --prefix backend run test:mysql:migration -echo "PASS: M01-B through M03-A live MySQL migration roundtrip completed." +echo "PASS: M01-B through M03-B live MySQL migration roundtrip completed."