From 8ec84b3c5cca27ca2cdfc68491e81e0218a54122 Mon Sep 17 00:00:00 2001 From: tisachi Date: Fri, 23 Oct 2026 17:25:56 +0200 Subject: [PATCH] Silownie: bytnosc i check-in QR - model GymPresence + sluznik (slot 30 min, merge luk), API /me/presence + POST /gyms/:id/check-in + admin occupancy/presence-stats + PATCH /plans/:id/gym; apka: strona check-inu, licznik teraz na karcie sirowni, modal przy starcie treningu (meldunek albo zmiana sirowni planu), historia wizyt w profilu, kod QR z drukiem; admin: kolumna teraz na liscie, karta telemetrii bytnosci, modal Kod QR (link na app) --- admin/package-lock.json | 338 +++++++++++---- admin/package.json | 2 + admin/src/api/types.ts | 24 ++ admin/src/components/gyms/GymQrModal.tsx | 95 ++++ admin/src/i18n/locales/en/gyms.json | 29 +- admin/src/i18n/locales/pl/gyms.json | 29 +- admin/src/pages/gyms/GymDetail.tsx | 124 ++++++ admin/src/pages/gyms/GymsList.tsx | 27 +- admin/src/styles.css | 17 + admin/test/GymDetail.test.tsx | 43 ++ admin/test/GymsList.test.tsx | 16 + admin/test/e2e/mock-api.ts | 35 ++ admin/test/e2e/presence.spec.ts | 44 ++ .../migration.sql | 41 ++ api/prisma/schema.prisma | 41 ++ api/src/app.ts | 6 + api/src/routes/gyms.ts | 32 +- api/src/routes/gyms/schemas.ts | 5 + api/src/routes/plans-schemas.ts | 6 + api/src/routes/plans.ts | 40 ++ api/src/routes/presence.ts | 189 ++++++++ api/src/routes/sessions.ts | 2 +- api/src/services/gyms/core.ts | 13 +- api/src/services/gyms/photos.ts | 6 +- api/src/services/plans.ts | 25 ++ api/src/services/presence.ts | 405 ++++++++++++++++++ api/src/services/scheduler.ts | 12 + api/src/services/sessions.ts | 14 +- api/src/swagger.ts | 146 +++++++ api/test/integration/plans.test.ts | 65 +++ api/test/integration/presence.test.ts | 299 +++++++++++++ api/test/unit/presence.test.ts | 277 ++++++++++++ api/test/unit/scheduler.test.ts | 25 ++ app/package-lock.json | 338 +++++++++++---- app/package.json | 2 + app/src/App.tsx | 2 + app/src/api/queries.ts | 58 +++ app/src/api/types.ts | 42 ++ app/src/components/gyms/GymQrModal.tsx | 94 ++++ .../presence/StartTrainingPresenceModal.tsx | 136 ++++++ app/src/i18n/index.ts | 5 + app/src/i18n/locales/en/presence.json | 64 +++ app/src/i18n/locales/pl/presence.json | 64 +++ app/src/lib/format.ts | 9 + app/src/pages/DayExecution.tsx | 113 ++++- app/src/pages/Login.tsx | 7 +- app/src/pages/gyms/GymCheckIn.tsx | 179 ++++++++ app/src/pages/gyms/GymDetail.tsx | 128 +++++- app/src/pages/profile/ProfileHistory.tsx | 171 +++++++- app/src/styles.css | 17 + app/test/e2e/mock-api.ts | 144 ++++++- app/test/e2e/presence.spec.ts | 250 +++++++++++ app/test/presence.test.tsx | 285 ++++++++++++ 53 files changed, 4413 insertions(+), 167 deletions(-) create mode 100644 admin/src/components/gyms/GymQrModal.tsx create mode 100644 admin/test/e2e/presence.spec.ts create mode 100644 api/prisma/migrations/20261023034841_add_gym_presence/migration.sql create mode 100644 api/src/routes/presence.ts create mode 100644 api/src/services/presence.ts create mode 100644 api/test/integration/presence.test.ts create mode 100644 api/test/unit/presence.test.ts create mode 100644 app/src/components/gyms/GymQrModal.tsx create mode 100644 app/src/components/presence/StartTrainingPresenceModal.tsx create mode 100644 app/src/i18n/locales/en/presence.json create mode 100644 app/src/i18n/locales/pl/presence.json create mode 100644 app/src/pages/gyms/GymCheckIn.tsx create mode 100644 app/test/e2e/presence.spec.ts create mode 100644 app/test/presence.test.tsx diff --git a/admin/package-lock.json b/admin/package-lock.json index 68b8ecf..f6397b9 100644 --- a/admin/package-lock.json +++ b/admin/package-lock.json @@ -14,10 +14,12 @@ "@radix-ui/react-separator": "^1.1.15", "@tailwindcss/vite": "^4.3.3", "@tanstack/react-query": "^5.62.0", + "@types/qrcode": "^1.5.6", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "i18next": "^26.4.7", "lucide-react": "^1.33.0", + "qrcode": "^1.5.4", "react": "^18.3.1", "react-dom": "^18.3.1", "react-i18next": "^17.0.20", @@ -1180,9 +1182,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1646,9 +1645,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1662,9 +1658,6 @@ "cpu": [ "arm" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1678,9 +1671,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1694,9 +1684,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1710,9 +1697,6 @@ "cpu": [ "loong64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1726,9 +1710,6 @@ "cpu": [ "loong64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1742,9 +1723,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1758,9 +1736,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1774,9 +1749,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1790,9 +1762,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1806,9 +1775,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1822,9 +1788,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1838,9 +1801,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2050,9 +2010,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2069,9 +2026,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2088,9 +2042,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2107,9 +2058,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2459,7 +2407,6 @@ "version": "26.2.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz", "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==", - "devOptional": true, "license": "MIT", "dependencies": { "undici-types": "~8.3.0" @@ -2472,6 +2419,15 @@ "devOptional": true, "license": "MIT" }, + "node_modules/@types/qrcode": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz", + "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/react": { "version": "18.3.31", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz", @@ -2978,7 +2934,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -2988,7 +2943,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, "license": "MIT", "dependencies": { "color-convert": "^2.0.1" @@ -3145,6 +3099,15 @@ "node": ">=6" } }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001809", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001809.tgz", @@ -3222,6 +3185,17 @@ "url": "https://polar.sh/cva" } }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, "node_modules/clsx": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", @@ -3235,7 +3209,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, "license": "MIT", "dependencies": { "color-name": "~1.1.4" @@ -3248,7 +3221,6 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, "license": "MIT" }, "node_modules/combined-stream": { @@ -3480,6 +3452,15 @@ } } }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/decimal.js": { "version": "10.6.0", "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", @@ -3545,6 +3526,12 @@ "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", "license": "MIT" }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, "node_modules/dom-accessibility-api": { "version": "0.5.16", "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", @@ -3584,6 +3571,12 @@ "dev": true, "license": "ISC" }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, "node_modules/enhanced-resolve": { "version": "5.24.5", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", @@ -4073,6 +4066,15 @@ "node": ">=6.9.0" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -4375,6 +4377,15 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -4688,9 +4699,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4711,9 +4719,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4734,9 +4739,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4757,9 +4759,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -5063,6 +5062,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -5093,7 +5101,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -5191,6 +5198,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/postcss": { "version": "8.5.26", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", @@ -5300,6 +5316,23 @@ "node": ">=6" } }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/react": { "version": "18.3.1", "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", @@ -5554,6 +5587,21 @@ "node": ">=8" } }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "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", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", @@ -5655,6 +5703,12 @@ "semver": "bin/semver.js" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -5708,6 +5762,32 @@ "dev": true, "license": "MIT" }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-indent": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", @@ -5974,7 +6054,6 @@ "version": "8.3.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", - "devOptional": true, "license": "MIT" }, "node_modules/update-browserslist-db": { @@ -6339,6 +6418,12 @@ "node": ">= 8" } }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -6366,6 +6451,20 @@ "node": ">=0.10.0" } }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/ws": { "version": "8.21.3", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", @@ -6405,6 +6504,12 @@ "dev": true, "license": "MIT" }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", @@ -6412,6 +6517,93 @@ "dev": true, "license": "ISC" }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yargs/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/admin/package.json b/admin/package.json index 0c970e4..52b9cf2 100644 --- a/admin/package.json +++ b/admin/package.json @@ -22,10 +22,12 @@ "@radix-ui/react-separator": "^1.1.15", "@tailwindcss/vite": "^4.3.3", "@tanstack/react-query": "^5.62.0", + "@types/qrcode": "^1.5.6", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "i18next": "^26.4.7", "lucide-react": "^1.33.0", + "qrcode": "^1.5.4", "react": "^18.3.1", "react-dom": "^18.3.1", "react-i18next": "^17.0.20", diff --git a/admin/src/api/types.ts b/admin/src/api/types.ts index e1439c5..1b1b4bf 100644 --- a/admin/src/api/types.ts +++ b/admin/src/api/types.ts @@ -191,6 +191,30 @@ export interface GymOwner { email: string; } +// ---------- bytność (telemetria admina, GET /admin/gyms/occupancy | /admin/gyms/:id/presence-stats) ---------- +export interface AdminOccupancyRow { + gymId: string; + name: string; + capacity: number | null; + count: number; +} + +export interface GymPresenceStatsData { + visits: number; + avgStayMinutes: number | null; + heatmap: { day: number; hour: number; count: number }[]; + topGyms: { gymId: string; gymName: string; visits: number }[]; + peak: number; + topEquipment: { equipmentId: string; name: string; nameEn: string | null; count: number }[]; + live: number; + visitsPerDay: number; +} + +export interface GymPresenceStatsResponse { + gym: { id: string; name: string; kind: GymKind; capacity: number | null }; + stats: GymPresenceStatsData; +} + export type ClaimStatus = 'PENDING' | 'APPROVED' | 'REJECTED'; export interface GymClaimDocument { diff --git a/admin/src/components/gyms/GymQrModal.tsx b/admin/src/components/gyms/GymQrModal.tsx new file mode 100644 index 0000000..7d166b5 --- /dev/null +++ b/admin/src/components/gyms/GymQrModal.tsx @@ -0,0 +1,95 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { QrCode } from 'lucide-react'; +import { toDataURL } from 'qrcode'; +import { Button, Modal } from '../ui'; +import { APP_URL } from '../../config'; + +/** + * Kod QR siłowni do naklejenia przy wejściu — prowadzi na APP_URL/gyms/:id/checkin. + * Druk przez window.print() + reguła @media print w styles.css (klasa .print-qr). + */ +export default function GymQrModal({ + open, + onClose, + gymId, + gymName, +}: { + open: boolean; + onClose: () => void; + gymId: string; + gymName: string; +}) { + const { t } = useTranslation('gyms'); + const link = `${APP_URL}/gyms/${gymId}/checkin`; + const [dataUrl, setDataUrl] = useState(null); + const [copied, setCopied] = useState(false); + + useEffect(() => { + setDataUrl(null); + setCopied(false); + if (!open) return; + let alive = true; + toDataURL(link, { width: 480, margin: 2, errorCorrectionLevel: 'M' }) + .then((url) => { + if (alive) setDataUrl(url); + }) + .catch(() => { + if (alive) setDataUrl(null); + }); + return () => { + alive = false; + }; + }, [open, link]); + + const download = () => { + if (!dataUrl) return; + const a = document.createElement('a'); + a.href = dataUrl; + a.download = `fitos-qr-${gymId}.png`; + a.click(); + }; + + const copy = async () => { + try { + await navigator.clipboard.writeText(link); + setCopied(true); + } catch { + /* clipboard niedostępny (brak HTTPS) — pomijamy */ + } + }; + + return ( + +
+

{t('presence.qrSubtitle')}

+
+ {dataUrl ? ( + {gymName} + ) : ( +
+
+ )} +
+

{link}

+
+
+ + + +
+
+ ); +} diff --git a/admin/src/i18n/locales/en/gyms.json b/admin/src/i18n/locales/en/gyms.json index b997b3b..c847f12 100644 --- a/admin/src/i18n/locales/en/gyms.json +++ b/admin/src/i18n/locales/en/gyms.json @@ -138,5 +138,32 @@ "addPhotos": "Add photos", "photoTypesError": "Allowed files: JPEG, PNG, WEBP (max 5 MB).", "photoMaxFilesError": "Maximum {{count}} files at once.", - "confirmDeletePhoto": "Delete this photo?" + "confirmDeletePhoto": "Delete this photo?", + "presenceNow": "now: {{count}} person", + "presenceNow_one": "now: {{count}} person", + "presenceNow_few": "now: {{count}} people", + "presenceNow_many": "now: {{count}} people", + "presenceNow_other": "now: {{count}} people", + "presenceFull": "full", + "presence": { + "title": "Presence", + "desc": "Gym check-ins (QR code / “I'm working out” button).", + "empty": "No presence data in this period.", + "live": "inside now", + "visits": "visits (30 days)", + "avgStay": "avg stay", + "visitsPerDay": "visits/day", + "peak": "hourly peak", + "minutesShort": "min", + "heatmap": "When people show up (day × hour)", + "topEquipment": "Most used equipment", + "qrGroup": "QR", + "qrAction": "QR code", + "qrTitle": "Gym QR code", + "qrSubtitle": "Scan and check in for your workout", + "qrPrint": "Print", + "qrDownload": "Download PNG", + "qrCopy": "Copy link", + "qrCopied": "Copied" + } } diff --git a/admin/src/i18n/locales/pl/gyms.json b/admin/src/i18n/locales/pl/gyms.json index 3196907..29bf498 100644 --- a/admin/src/i18n/locales/pl/gyms.json +++ b/admin/src/i18n/locales/pl/gyms.json @@ -140,5 +140,32 @@ "addPhotos": "Dodaj zdjęcia", "photoTypesError": "Dozwolone pliki: JPEG, PNG, WEBP (max 5 MB).", "photoMaxFilesError": "Maksymalnie {{count}} plików naraz.", - "confirmDeletePhoto": "Usunąć to zdjęcie?" + "confirmDeletePhoto": "Usunąć to zdjęcie?", + "presenceNow": "teraz: {{count}} osoba", + "presenceNow_one": "teraz: {{count}} osoba", + "presenceNow_few": "teraz: {{count}} osoby", + "presenceNow_many": "teraz: {{count}} osób", + "presenceNow_other": "teraz: {{count}} osób", + "presenceFull": "pełno", + "presence": { + "title": "Bytność", + "desc": "Meldunki na siłowni (kod QR / przycisk „Idę ćwiczyć”).", + "empty": "Brak danych bytności w tym okresie.", + "live": "teraz w środku", + "visits": "wizyty (30 dni)", + "avgStay": "śr. pobyt", + "visitsPerDay": "wizyt/dzień", + "peak": "rekord godzinowy", + "minutesShort": "min", + "heatmap": "Kiedy bywają (dzień × godzina)", + "topEquipment": "Najczęściej używane urządzenia", + "qrGroup": "QR", + "qrAction": "Kod QR", + "qrTitle": "Kod QR siłowni", + "qrSubtitle": "Zeskanuj i melduj się na treningu", + "qrPrint": "Drukuj", + "qrDownload": "Pobierz PNG", + "qrCopy": "Kopiuj link", + "qrCopied": "Skopiowano" + } } diff --git a/admin/src/pages/gyms/GymDetail.tsx b/admin/src/pages/gyms/GymDetail.tsx index 9dcd4bf..efb8335 100644 --- a/admin/src/pages/gyms/GymDetail.tsx +++ b/admin/src/pages/gyms/GymDetail.tsx @@ -9,6 +9,7 @@ import { MapPin, Megaphone, Pencil, + QrCode, ShieldCheck, Star, Trash2, @@ -21,6 +22,7 @@ import { import { useTopbar, type TopbarCustomGroup } from '../../topbar'; import { api } from '../../api/client'; import { AuthImage } from '../../components/AuthImage'; +import GymQrModal from '../../components/gyms/GymQrModal'; import { UserPicker } from '../../components/UserPicker'; import { AddressFields, addressPayload, isAddressComplete } from '../../components/AddressFields'; import { useAdminUsers } from '../users/user-queries'; @@ -32,6 +34,7 @@ import type { GymException, GymOwner, GymPhoto, + GymPresenceStatsResponse, } from '../../api/types'; import { EMPTY_SPEC_FIELDS, @@ -96,6 +99,106 @@ function HoursList({ gym }: { gym: Gym }) { ); } +/* Telemetria bytności (tylko REAL): live, wizyty, śr. czas, peak, heatmapa dzień×godzina, top urządzenia. */ +function PresenceTelemetry({ gymId }: { gymId: string }) { + const { t, i18n } = useTranslation('gyms'); + const { data, isLoading } = useQuery({ + queryKey: ['gym-presence-stats', gymId], + queryFn: () => api(`/admin/gyms/${gymId}/presence-stats`), + }); + if (isLoading) return ; + const s = data?.stats; + if (!s || s.visits === 0) { + return

{t('presence.empty')}

; + } + return ( +
+
+ {[ + { label: t('presence.live'), value: String(s.live) }, + { label: t('presence.visits'), value: String(s.visits) }, + { + label: t('presence.avgStay'), + value: + s.avgStayMinutes != null ? `${s.avgStayMinutes} ${t('presence.minutesShort')}` : '—', + }, + { label: t('presence.peak'), value: String(s.peak) }, + ].map((k) => ( +
+ {k.label} + {k.value} +
+ ))} +
+ + {s.heatmap.length > 0 && ( +
+
+ {t('presence.heatmap')} +
+
+ {Array.from({ length: 7 }, (_, day) => ( + + ))} +
+
+ )} + + {s.topEquipment.length > 0 && ( +
+
+ {t('presence.topEquipment')} +
+
+ {s.topEquipment.map((e) => ( + + {localizedName(e, i18n.language)} · {e.count} + + ))} +
+
+ )} +
+ ); +} + +/* Wiersz heatmapy: etykieta dnia + 24 kafle godziny (kolor ~ natężenie). */ +function FragmentRow({ day, stats }: { day: number; stats: GymPresenceStatsResponse['stats'] }) { + return ( + <> + + {dayFull(day).slice(0, 2)} + + {Array.from({ length: 24 }, (_, hour) => { + const cell = stats.heatmap.find((h) => h.day === day && h.hour === hour); + const intensity = cell && stats.peak > 0 ? cell.count / stats.peak : 0; + return ( + 0 + ? `color-mix(in srgb, var(--accent) ${Math.round(18 + intensity * 82)}%, var(--bg-input))` + : 'var(--bg-input)', + }} + /> + ); + })} + + ); +} + /* Mozaika galerii (odczyt): pierwsze zdjęcie duże, reszta siatką, „+N” na końcu — jak w apce. */ function GalleryMosaic({ gym }: { gym: Gym }) { const { t } = useTranslation('gyms'); @@ -551,6 +654,7 @@ export default function GymDetail() { const [equipmentOpen, setEquipmentOpen] = useState(false); const [ownersOpen, setOwnersOpen] = useState(false); const [announcementsOpen, setAnnouncementsOpen] = useState(false); + const [qrOpen, setQrOpen] = useState(false); const [confirmOpen, setConfirmOpen] = useState(false); const [busy, setBusy] = useState(false); @@ -592,6 +696,12 @@ export default function GymDetail() { icon: ImageIcon, actions: [{ label: t('groupGallery'), onClick: () => setGalleryOpen(true) }], } as TopbarCustomGroup, + { + id: 'qr', + label: t('presence.qrGroup'), + icon: QrCode, + actions: [{ label: t('presence.qrAction'), onClick: () => setQrOpen(true) }], + } as TopbarCustomGroup, ] : []), { @@ -728,6 +838,12 @@ export default function GymDetail() {
+ {gym.kind === 'REAL' && ( + + + + + )} @@ -811,6 +927,14 @@ export default function GymDetail() { > + {gym.kind === 'REAL' && ( + setQrOpen(false)} + gymId={gym.id} + gymName={gym.name} + /> + )} {t('common:counters.devices', { count: gym.equipment.length })} + {live && ( + + {t('presenceNow', { count: live.count })} + {gym.capacity != null ? ` (${gym.capacity})` : ''} + {gym.capacity != null && live.count >= gym.capacity + ? ` — ${t('presenceFull')}` + : ''} + + )}
@@ -129,6 +138,12 @@ export default function GymsList() { queryKey: ['gyms'], queryFn: () => api<{ gyms: Gym[] }>('/admin/gyms'), }); + // live occupancy — osobny query (licznik „teraz” na kartach REAL) + const { data: occupancyData } = useQuery({ + queryKey: ['gyms', 'occupancy'], + queryFn: () => api<{ gyms: AdminOccupancyRow[] }>('/admin/gyms/occupancy'), + }); + const occupancy = new Map((occupancyData?.gyms ?? []).map((o) => [o.gymId, o])); const query = useListSearch((s) => s.queries.gyms); const setQuery = useListSearch((s) => s.setQuery); @@ -163,7 +178,11 @@ export default function GymsList() {
{filtered.map((g) => ( - + ))}
diff --git a/admin/src/styles.css b/admin/src/styles.css index cacef11..b71bce5 100644 --- a/admin/src/styles.css +++ b/admin/src/styles.css @@ -361,3 +361,20 @@ input[type='checkbox']:disabled { opacity: 0.5; cursor: default; } + +/* Druk kodu QR siłowni: na wydruku tylko obszar QR (reszta strony niewidoczna). */ +@media print { + body * { + visibility: hidden; + } + .print-qr, + .print-qr * { + visibility: visible; + } + .print-qr { + position: fixed; + inset: 0; + margin: 0; + background: #fff; + } +} diff --git a/admin/test/GymDetail.test.tsx b/admin/test/GymDetail.test.tsx index d7f6f6b..8e22c79 100644 --- a/admin/test/GymDetail.test.tsx +++ b/admin/test/GymDetail.test.tsx @@ -8,6 +8,11 @@ import { useTopbarStore } from '../src/topbar/store'; import { Topbar } from '../src/topbar'; import type { Equipment, Gym, User } from '../src/api/types'; +// QR generowany przez stub — w jsdom canvas może być niedostępny +vi.mock('qrcode', () => ({ + toDataURL: vi.fn(async () => 'data:image/png;base64,MOCK'), +})); + const OWNER1 = { id: 'u-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' }; const G1: Gym = { @@ -82,6 +87,20 @@ function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) { calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : undefined }); if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] }); if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] }); + if (url.includes('/admin/gyms/g1/presence-stats')) + return jsonResponse(200, { + gym: { id: 'g1', name: gym.name, kind: gym.kind, capacity: gym.capacity }, + stats: { + visits: 40, + avgStayMinutes: 62, + heatmap: [{ day: 1, hour: 18, count: 7 }], + topGyms: [], + peak: 7, + topEquipment: [{ equipmentId: 'eq-1', name: 'sztanga', nameEn: null, count: 12 }], + live: 3, + visitsPerDay: 1.3, + }, + }); if (url.includes('/admin/users')) return jsonResponse(200, { users: [U1] }); if (url.endsWith('/admin/gyms/g1/equipment') && method === 'POST') { return jsonResponse(200, { @@ -151,6 +170,7 @@ describe('admin GymDetail page', () => { expect(config?.groups?.map((g) => g.id)).toEqual([ 'edit', 'gallery', + 'qr', 'equipment', 'owners', 'announcements', @@ -223,4 +243,27 @@ describe('admin GymDetail page', () => { userId: 'u1', }); }); + + it('pokazuje telemetrię bytności dla siłowni REAL', async () => { + stubGymFetch(); + renderGymDetail(); + expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); + + expect(await screen.findByText('Bytność')).toBeInTheDocument(); + expect(screen.getByText('teraz w środku')).toBeInTheDocument(); + expect(screen.getByText('40')).toBeInTheDocument(); // wizyty (30 dni) + expect(screen.getByText('62 min')).toBeInTheDocument(); + expect(screen.getByText('sztanga · 12')).toBeInTheDocument(); + }); + + it('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async () => { + stubGymFetch(); + renderGymDetail(); + expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); + + fireEvent.click(actionButton('Kod QR')); + const dialog = await screen.findByRole('dialog'); + expect(within(dialog).getByRole('img', { name: 'Gym A' })).toBeInTheDocument(); + expect(within(dialog).getByText(/\/gyms\/g1\/checkin/)).toBeInTheDocument(); + }); }); diff --git a/admin/test/GymsList.test.tsx b/admin/test/GymsList.test.tsx index d34150d..3786eed 100644 --- a/admin/test/GymsList.test.tsx +++ b/admin/test/GymsList.test.tsx @@ -89,4 +89,20 @@ describe('admin GymsList page', () => { expect(screen.queryByText('Gym A')).not.toBeInTheDocument(); expect(screen.getByText('Brak wyników dla podanego zapytania.')).toBeInTheDocument(); }); + + it('karty REAL pokazują licznik „teraz” z endpointu occupancy', async () => { + const realGym: Gym = { ...G1, kind: 'REAL' }; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes('/admin/gyms/occupancy')) + return jsonResponse(200, { gyms: [{ gymId: 'g1', name: 'Gym A', capacity: 50, count: 3 }] }); + return jsonResponse(200, { gyms: [realGym] }); + }), + ); + renderGyms(); + expect(await screen.findByText('Gym A')).toBeInTheDocument(); + expect(await screen.findByText('teraz: 3 osoby (50)')).toBeInTheDocument(); + }); }); diff --git a/admin/test/e2e/mock-api.ts b/admin/test/e2e/mock-api.ts index 3fef00f..10117a1 100644 --- a/admin/test/e2e/mock-api.ts +++ b/admin/test/e2e/mock-api.ts @@ -404,6 +404,41 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() }), ); + // Live occupancy listy siłowni (GET /admin/gyms/occupancy) — licznik „teraz” na kartach REAL. + page.route('**/api/v1/admin/gyms/occupancy', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + gyms: [{ gymId: 'gym-1', name: TEST_GYM.name, capacity: TEST_GYM.capacity, count: 7 }], + }), + }), + ); + + // Telemetria bytności (GET /admin/gyms/gym-1/presence-stats). + page.route('**/api/v1/admin/gyms/*/presence-stats', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + gym: { id: 'gym-1', name: TEST_GYM.name, kind: 'REAL', capacity: TEST_GYM.capacity }, + stats: { + visits: 96, + avgStayMinutes: 63, + heatmap: [ + { day: 1, hour: 18, count: 9 }, + { day: 4, hour: 19, count: 6 }, + ], + topGyms: [{ gymId: 'gym-1', name: TEST_GYM.name, count: 96 }], + peak: 9, + topEquipment: [{ equipmentId: 'eq-1', name: 'ławka', nameEn: 'Bench', count: 41 }], + live: 7, + visitsPerDay: 3.2, + }, + }), + }), + ); + // POST /gyms/gym-1/photos — upload (multipart, pole `photos`). page.route('**/api/v1/gyms/*/photos', (route) => { const req = route.request(); diff --git a/admin/test/e2e/presence.spec.ts b/admin/test/e2e/presence.spec.ts new file mode 100644 index 0000000..198d184 --- /dev/null +++ b/admin/test/e2e/presence.spec.ts @@ -0,0 +1,44 @@ +import type { Page } from '@playwright/test'; +import { test, expect } from './fixtures'; +import { mockApi, TEST_GYM } from './mock-api'; + +async function loginAsAdmin(page: Page) { + await page.goto('/login'); + await page.locator('input[type="email"]').fill('admin@fitos.pl'); + await page.locator('input[type="password"]').fill('haslo123'); + await page.getByRole('button', { name: 'Zaloguj' }).click(); + await expect(page).toHaveURL(/\/gyms$/); +} + +test('lista siłowni pokazuje licznik „teraz” na karcie REAL', async ({ page }) => { + mockApi(page, { gyms: { gyms: [TEST_GYM] } }); + await loginAsAdmin(page); + await expect(page.getByText('teraz: 7 osób (120)')).toBeVisible(); +}); + +test('detal REAL pokazuje kartę bytności z telemetrią', async ({ page }) => { + mockApi(page, { gyms: { gyms: [TEST_GYM] } }); + await loginAsAdmin(page); + await page.getByRole('link', { name: 'Fit Factory' }).click(); + await expect(page).toHaveURL(/\/gyms\/gym-1$/); + + await expect(page.getByRole('heading', { name: 'Bytność' })).toBeVisible(); + await expect(page.getByText('teraz w środku')).toBeVisible(); + await expect(page.getByText('7', { exact: true })).toBeVisible(); + await expect(page.getByText('wizyty (30 dni)')).toBeVisible(); + await expect(page.getByText('96', { exact: true })).toBeVisible(); + await expect(page.getByText('ławka · 41')).toBeVisible(); +}); + +test('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async ({ page }) => { + mockApi(page, { gyms: { gyms: [TEST_GYM] } }); + await loginAsAdmin(page); + await page.getByRole('link', { name: 'Fit Factory' }).click(); + await expect(page).toHaveURL(/\/gyms\/gym-1$/); + + await page.getByRole('button', { name: 'Kod QR' }).click(); + const dialog = page.getByRole('dialog'); + await expect(dialog.getByRole('heading', { name: 'Kod QR siłowni' })).toBeVisible(); + await expect(dialog.getByRole('img', { name: 'Fit Factory' })).toBeVisible(); + await expect(dialog.getByText(/\/gyms\/gym-1\/checkin/)).toBeVisible(); +}); diff --git a/api/prisma/migrations/20261023034841_add_gym_presence/migration.sql b/api/prisma/migrations/20261023034841_add_gym_presence/migration.sql new file mode 100644 index 0000000..1ecb0ca --- /dev/null +++ b/api/prisma/migrations/20261023034841_add_gym_presence/migration.sql @@ -0,0 +1,41 @@ +-- CreateEnum +CREATE TYPE "PresenceStatus" AS ENUM ('ACTIVE', 'EXPIRED', 'CLOSED'); + +-- CreateEnum +CREATE TYPE "PresenceSource" AS ENUM ('QR', 'MANUAL'); + +-- CreateTable +CREATE TABLE "GymPresence" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "gymId" TEXT NOT NULL, + "status" "PresenceStatus" NOT NULL DEFAULT 'ACTIVE', + "source" "PresenceSource" NOT NULL DEFAULT 'MANUAL', + "checkedInAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "lastActivityAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "closedAt" TIMESTAMP(3), + + CONSTRAINT "GymPresence_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "GymPresence_gymId_status_idx" ON "GymPresence"("gymId", "status"); + +-- CreateIndex +CREATE INDEX "GymPresence_userId_status_idx" ON "GymPresence"("userId", "status"); + +-- CreateIndex +CREATE INDEX "GymPresence_gymId_checkedInAt_idx" ON "GymPresence"("gymId", "checkedInAt"); + +-- CreateIndex +CREATE INDEX "GymPresence_userId_checkedInAt_idx" ON "GymPresence"("userId", "checkedInAt"); + +-- CreateIndex: at most one ACTIVE presence per user (enforced by the database, +-- so concurrent check-ins in two gyms can never both leave two ACTIVE rows). +CREATE UNIQUE INDEX "GymPresence_userId_active_key" ON "GymPresence"("userId") WHERE "status" = 'ACTIVE'; + +-- AddForeignKey +ALTER TABLE "GymPresence" ADD CONSTRAINT "GymPresence_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "GymPresence" ADD CONSTRAINT "GymPresence_gymId_fkey" FOREIGN KEY ("gymId") REFERENCES "Gym"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/api/prisma/schema.prisma b/api/prisma/schema.prisma index 6b439f3..d68ff75 100644 --- a/api/prisma/schema.prisma +++ b/api/prisma/schema.prisma @@ -91,6 +91,21 @@ enum UserStatus { BANNED } +/// Bytność na siłowni: ACTIVE = w oknie aktywności; EXPIRED = 30 min bez aktywności +/// (do wskrzeszenia przez re-check-in w trybie merge); CLOSED = domknięta +/// (wychodzę / przeniesienie do innej siłowni). +enum PresenceStatus { + ACTIVE + EXPIRED + CLOSED +} + +/// Źródło meldunku: QR (deep link /gyms/{id}/checkin) lub ręczny „Idę ćwiczyć". +enum PresenceSource { + QR + MANUAL +} + model User { id String @id @default(cuid()) email String @unique @@ -141,6 +156,7 @@ model User { notifications Notification[] announcementsAuthored Announcement[] @relation("AnnouncementAuthor") announcementReads AnnouncementRead[] + presences GymPresence[] } /// Audit trail of user actions (app + trainer level). Best-effort writes, @@ -330,6 +346,7 @@ model Gym { photos GymPhoto[] plans TrainingPlan[] announcements Announcement[] + presences GymPresence[] } /// Zdjęcie w galerii siłowni REAL. `order` = kolejność; okładka = najmniejsze `order` (tie → najstarsze `createdAt`). @@ -480,6 +497,30 @@ model GymException { @@index([date]) } +/// Bytność na siłowni (live occupancy) — niezależna od TrainingSession: meldunek +/// nie wymaga planu; zapisy w sesji only odświeżają slot (touch). +/// Inwariant: jedna ACTIVE na użytkownika pilnuje częściowy indeks unikalny +/// `GymPresence_userId_active_key` ("userId") WHERE status='ACTIVE' — utworzony +/// w migracji 20261023000000 (Prisma nie wspiera indeksów częściowych w schemacie). +model GymPresence { + id String @id @default(cuid()) + userId String + gymId String + status PresenceStatus @default(ACTIVE) + source PresenceSource @default(MANUAL) + checkedInAt DateTime @default(now()) + lastActivityAt DateTime @default(now()) + closedAt DateTime? + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade) + + @@index([gymId, status]) + @@index([userId, status]) + @@index([gymId, checkedInAt]) + @@index([userId, checkedInAt]) +} + model FocusArea { id String @id @default(cuid()) name String @unique diff --git a/api/src/app.ts b/api/src/app.ts index e3c9314..f6cb113 100644 --- a/api/src/app.ts +++ b/api/src/app.ts @@ -24,6 +24,7 @@ import { createCalendarRoutes } from './routes/calendar.js'; import { createTrainerRoutes } from './routes/trainer.js'; import { createMessageRoutes } from './routes/messages.js'; import { createFeedRoutes } from './routes/feed.js'; +import { createPresenceMeRoutes, createPresenceAdminRoutes } from './routes/presence.js'; import { createAdminRoutes } from './routes/admin.js'; import { createEquipmentRoutes } from './routes/equipment.js'; import { createEquipmentPublicRoutes } from './routes/equipmentPublic.js'; @@ -76,6 +77,8 @@ export function createApp(deps: AppDeps): express.Express { app.use('/api/v1/auth', createAuthRoutes(deps)); // /me/feed przed /me — inaczej zapytania o feed wpadałyby najpierw do routera /me. app.use('/api/v1/me/feed', createFeedRoutes(deps)); + // /me/presence przed /me — z tych samych powodów co /me/feed. + app.use('/api/v1/me/presence', createPresenceMeRoutes(deps)); app.use('/api/v1/me', createMeRoutes(deps)); app.use('/api/v1/exercises', createExercisePoolRoutes(deps)); app.use('/api/v1/focus-areas', createFocusAreaRoutes(deps)); @@ -87,6 +90,9 @@ export function createApp(deps: AppDeps): express.Express { app.use('/api/v1/calendar', createCalendarRoutes(deps)); app.use('/api/v1/trainer', createTrainerRoutes(deps)); app.use('/api/v1/messages', createMessageRoutes(deps)); + // telemetria bytności PRZED routerem admin — GET /admin/gyms/occupancy musi być + // zarejestrowany zanim /admin/gyms/:id przechwyci "occupancy" jako id siłowni. + app.use('/api/v1/admin', createPresenceAdminRoutes(deps)); app.use('/api/v1/admin', createAdminRoutes(deps)); app.use('/api/v1/admin/equipment', createEquipmentRoutes(deps)); app.use('/api/v1/admin/exercises', createExerciseRoutes(deps)); diff --git a/api/src/routes/gyms.ts b/api/src/routes/gyms.ts index 6b97e5a..02dd88c 100644 --- a/api/src/routes/gyms.ts +++ b/api/src/routes/gyms.ts @@ -16,7 +16,8 @@ import { } from '../services/gyms.js'; import { logActivity } from '../services/audit.js'; import { asyncHandler } from '../lib/asyncHandler.js'; -import { createGymSchema, rateGymSchema, updateGymSchema } from './gyms/schemas.js'; +import { checkIn } from '../services/presence.js'; +import { checkInSchema, createGymSchema, rateGymSchema, updateGymSchema } from './gyms/schemas.js'; import { createGymClaimRoutes } from './gyms/claims.js'; import { createGymInvitationRoutes } from './gyms/invitations.js'; import { createGymPhotoRoutes } from './gyms/photos.js'; @@ -111,6 +112,35 @@ export function createGymRoutes(deps: AppDeps) { }), ); + /** + * @openapi + * /gyms/{gymId}/check-in: + * post: + * summary: Check in to a real gym (QR deep link or manual "Idę ćwiczyć"); idempotent in the same gym, closes presence when moving A->B + * tags: [Gyms] + * requestBody: + * required: false + * content: + * application/json: + * schema: + * type: object + * properties: + * source: { type: string, enum: [QR, MANUAL], default: MANUAL } + * responses: + * 200: { description: OK, returns { presence: {...} } } + * 400: { description: VIRTUAL gym } + * 404: { description: Gym not found } + */ + router.post( + '/:gymId/check-in', + validate(checkInSchema), + asyncHandler(async (req, res) => { + const { source } = req.body as z.infer; + const result = await checkIn(prisma, req.user!.id, req.params.gymId, source); + res.json(result); + }), + ); + // Per-gym sub-routes: gallery photos, equipment instance photos, then equipment/exceptions. router.use('/:gymId/photos', createGymPhotoRoutes(deps)); router.use('/:gymId/equipment/:equipmentInstanceId/photos', createEquipmentPhotoRoutes(deps)); diff --git a/api/src/routes/gyms/schemas.ts b/api/src/routes/gyms/schemas.ts index 0c507f0..0621f08 100644 --- a/api/src/routes/gyms/schemas.ts +++ b/api/src/routes/gyms/schemas.ts @@ -36,6 +36,11 @@ export const rateGymSchema = z.object({ vote: z.enum(['UP', 'DOWN']), }); +/** Źródło meldunku: QR = deep link /gyms/{id}/checkin, MANUAL = przycisk „Idę ćwiczyć". */ +export const checkInSchema = z.object({ + source: z.enum(['QR', 'MANUAL']).default('MANUAL'), +}); + /** Multipart fields arrive as strings (multer) — gymAvailability is a JSON string. */ export const gymClaimSchema = z.object({ gymId: z.string().min(1).optional(), diff --git a/api/src/routes/plans-schemas.ts b/api/src/routes/plans-schemas.ts index 0cf949e..d201098 100644 --- a/api/src/routes/plans-schemas.ts +++ b/api/src/routes/plans-schemas.ts @@ -94,6 +94,12 @@ export const activateSchema = z.object({ startDate: z.string().refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date'), }); +// Zmiana informacyjnej siłowni planu (modal rozpoczęcia treningu) — wymaga pola gymId +// (null = wyczyść), bez reszty struktury; własność i członkostwo pilnuje serwis. +export const updatePlanGymSchema = z.object({ + gymId: z.string().min(1).nullable(), +}); + export const sharePlanSchema = z.object({ userId: z.string().min(1), }); diff --git a/api/src/routes/plans.ts b/api/src/routes/plans.ts index 4b8f22d..c24873b 100644 --- a/api/src/routes/plans.ts +++ b/api/src/routes/plans.ts @@ -17,6 +17,7 @@ import { sharePlan, unsharePlan, updatePlan, + updatePlanGym, } from '../services/plans.js'; import { logActivity } from '../services/audit.js'; import { asyncHandler } from '../lib/asyncHandler.js'; @@ -24,6 +25,7 @@ import { activateSchema, createPlanSchema, sharePlanSchema, + updatePlanGymSchema, updatePlanSchema, } from './plans-schemas.js'; @@ -147,6 +149,44 @@ export function createPlanRoutes({ prisma }: AppDeps) { }), ); + /** + * @openapi + * /plans/{id}/gym: + * patch: + * summary: Change the informational gym of a plan (owner only, any status; e.g. "start training" modal when the user checked in to a different gym). gymId:null clears it; the target gym requires membership. + * tags: [Plans] + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [gymId] + * properties: + * gymId: { type: string, nullable: true } + * responses: + * 200: { description: OK, returns { plan: { id, gym } } } + * 400: { description: Unknown gymId / owner is not a member of the gym } + * 404: { description: Plan not found or caller is not the owner } + */ + router.patch( + '/:id/gym', + validate(updatePlanGymSchema), + asyncHandler(async (req, res) => { + await assertPlanOwner(prisma, req.params.id, req.user!.id); + const { gymId } = req.body as z.infer; + const result = await updatePlanGym(prisma, req.params.id, req.user!.id, gymId); + await logActivity(prisma, { + actorId: req.user!.id, + action: 'plan.gym.updated', + entityType: 'plan', + entityId: req.params.id, + details: { gymId }, + }); + res.json(result); + }), + ); + /** * @openapi * /plans/{id}: diff --git a/api/src/routes/presence.ts b/api/src/routes/presence.ts new file mode 100644 index 0000000..5588bcc --- /dev/null +++ b/api/src/routes/presence.ts @@ -0,0 +1,189 @@ +import { Router } from 'express'; +import { z } from 'zod'; +import type { AppDeps } from '../deps.js'; +import { authenticate, requireAdmin } from '../middleware/auth.js'; +import { validate } from '../middleware/validate.js'; +import { asyncHandler } from '../lib/asyncHandler.js'; +import { + checkOut, + getActive, + getGymStats, + getHistory, + getLiveOccupancy, + getMyStats, + touch, +} from '../services/presence.js'; + +const rangeQuerySchema = z.object({ + from: z.coerce.date().optional(), + to: z.coerce.date().optional(), +}); + +const historyQuerySchema = rangeQuerySchema.extend({ + gymId: z.string().min(1).optional(), +}); + +/** Domyślny okres telemetrii: ostatnie 30 dni. */ +function resolveRange(query: { from?: Date; to?: Date }): { from: Date; to: Date } { + const to = query.to ?? new Date(); + const from = query.from ?? new Date(to.getTime() - 30 * 24 * 60 * 60 * 1000); + return { from, to }; +} + +/** + * /me/presence — bytność zalogowanego usera (check-out, heartbeat, historia, statystyki). + * Montowane PRZED /api/v1/me (wzorzec /me/feed), żeby router /me ich nie przejął. + */ +export function createPresenceMeRoutes({ prisma }: AppDeps) { + const router = Router(); + router.use(authenticate(prisma)); + + /** + * @openapi + * /me/presence: + * get: + * summary: Active presence of the caller (check-in state) + * tags: [Presence] + * responses: + * 200: { description: OK, returns { presence: object|null } } + */ + router.get( + '/', + asyncHandler(async (req, res) => { + const result = await getActive(prisma, req.user!.id); + res.json(result); + }), + ); + + /** + * @openapi + * /me/presence/check-out: + * post: + * summary: Leave the gym ("Wychodzę") — ACTIVE -> CLOSED + * tags: [Presence] + * responses: + * 200: { description: OK, returns { checkedOut: boolean } } + */ + router.post( + '/check-out', + asyncHandler(async (req, res) => { + const result = await checkOut(prisma, req.user!.id); + res.json(result); + }), + ); + + /** + * @openapi + * /me/presence/heartbeat: + * post: + * summary: Refresh the presence slot ("Wciąż tu jestem" / heartbeat z ekranu treningowego) + * tags: [Presence] + * responses: + * 200: { description: OK, returns { touched: boolean } } + */ + router.post( + '/heartbeat', + asyncHandler(async (req, res) => { + const result = await touch(prisma, req.user!.id); + res.json(result); + }), + ); + + /** + * @openapi + * /me/presence/history: + * get: + * summary: Visit history of the caller + * tags: [Presence] + * parameters: + * - { in: query, name: from, schema: { type: string, format: date-time } } + * - { in: query, name: to, schema: { type: string, format: date-time } } + * - { in: query, name: gymId, schema: { type: string } } + * responses: + * 200: { description: OK, returns { visits: [...] } } + */ + router.get( + '/history', + validate(historyQuerySchema, 'query'), + asyncHandler(async (req, res) => { + const query = req.query as z.infer; + const result = await getHistory(prisma, req.user!.id, query); + res.json(result); + }), + ); + + /** + * @openapi + * /me/presence/stats: + * get: + * summary: Visit stats of the caller (top gyms, day×hour heatmap, avg stay, top equipment) + * tags: [Presence] + * parameters: + * - { in: query, name: from, schema: { type: string, format: date-time } } + * - { in: query, name: to, schema: { type: string, format: date-time } } + * responses: + * 200: { description: OK, returns { stats: {...} } } + */ + router.get( + '/stats', + validate(rangeQuerySchema, 'query'), + asyncHandler(async (req, res) => { + const query = req.query as z.infer; + const result = await getMyStats(prisma, req.user!.id, query); + res.json(result); + }), + ); + + return router; +} + +/** + * Telemetria bytności dla admina platformy. Montowane PRZED /api/v1/admin + * (GET /gyms/occupancy musi trafić tu, zanim router adminów przechwyci go jako /gyms/:id). + */ +export function createPresenceAdminRoutes({ prisma }: AppDeps) { + const router = Router(); + router.use(authenticate(prisma), requireAdmin); + + /** + * @openapi + * /admin/gyms/occupancy: + * get: + * summary: Live occupancy of all real gyms (admin) + * tags: [Admin] + * responses: + * 200: { description: OK, returns { gyms: [{ gymId, name, capacity, count }] } } + */ + router.get( + '/gyms/occupancy', + asyncHandler(async (_req, res) => { + const result = await getLiveOccupancy(prisma); + res.json(result); + }), + ); + + /** + * @openapi + * /admin/gyms/{gymId}/presence-stats: + * get: + * summary: Presence telemetry of a gym (admin) — day×hour heatmap, avg stay, visits/day, peak, top equipment + * tags: [Admin] + * parameters: + * - { in: query, name: from, schema: { type: string, format: date-time } } + * - { in: query, name: to, schema: { type: string, format: date-time } } + * responses: + * 200: { description: OK, returns { gym, stats } } + * 404: { description: Gym not found } + */ + router.get( + '/gyms/:gymId/presence-stats', + validate(rangeQuerySchema, 'query'), + asyncHandler(async (req, res) => { + const query = req.query as z.infer; + const result = await getGymStats(prisma, req.params.gymId, resolveRange(query)); + res.json(result); + }), + ); + + return router; +} diff --git a/api/src/routes/sessions.ts b/api/src/routes/sessions.ts index 78bcc07..6d66907 100644 --- a/api/src/routes/sessions.ts +++ b/api/src/routes/sessions.ts @@ -66,7 +66,7 @@ export function createSessionRoutes({ prisma }: AppDeps) { * @openapi * /days/{dayId}: * get: - * summary: Training day details (status, date, sessions) + * summary: Training day details (status, date, sessions, plan with informational gym) * tags: [Sessions] * responses: * 200: { description: OK } diff --git a/api/src/services/gyms/core.ts b/api/src/services/gyms/core.ts index 2bf7d9c..23113e4 100644 --- a/api/src/services/gyms/core.ts +++ b/api/src/services/gyms/core.ts @@ -8,6 +8,7 @@ import { gymCoverInclude, gymEquipmentInclude } from './includes.js'; import { coverUrlOf } from './photos.js'; import { announceHoursChange } from '../announcements.js'; import { notifyGymDeleted } from '../feed.js'; +import { countActiveByGym } from '../presence.js'; export type GymKind = 'VIRTUAL' | 'REAL'; @@ -45,10 +46,20 @@ export async function listUserGyms(prisma: PrismaClient, userId: string) { include: { gym: { include: { ...gymEquipmentInclude, ...gymCoverInclude } } }, orderBy: { gym: { name: 'asc' } }, }); + // Publiczny licznik „teraz: N" — tylko REAL (VIRTUAL nie przyjmuje meldunków). + const counts = await countActiveByGym( + prisma, + memberships.filter((m) => m.gym.kind === 'REAL').map((m) => m.gym.id), + ); return { gyms: memberships.map((m) => { const { photos, ...gym } = m.gym; - return { ...gym, coverPhoto: coverUrlOf(gym.id, photos), roles: m.roles }; + return { + ...gym, + coverPhoto: coverUrlOf(gym.id, photos), + roles: m.roles, + currentOccupancy: gym.kind === 'REAL' ? (counts.get(gym.id) ?? 0) : null, + }; }), }; } diff --git a/api/src/services/gyms/photos.ts b/api/src/services/gyms/photos.ts index 1186d8e..e21796b 100644 --- a/api/src/services/gyms/photos.ts +++ b/api/src/services/gyms/photos.ts @@ -10,6 +10,7 @@ import { storedFileName, } from '../../lib/uploads.js'; import { gymEquipmentWithPhotosInclude, gymPhotosInclude } from './includes.js'; +import { countActiveByGym } from '../presence.js'; export interface GymPhotoDto { id: string; @@ -118,7 +119,10 @@ export async function getGymPublic( const membership = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId, gymId } }, }); - return { gym: gymToDto(gym), roles: membership?.roles ?? [], isAdmin }; + // Publiczny licznik „teraz: N" — tylko REAL (VIRTUAL nie przyjmuje meldunków). + const currentOccupancy = + gym.kind === 'REAL' ? ((await countActiveByGym(prisma, [gymId])).get(gymId) ?? 0) : null; + return { gym: { ...gymToDto(gym), currentOccupancy }, roles: membership?.roles ?? [], isAdmin }; } export interface UploadedPhotoFile { diff --git a/api/src/services/plans.ts b/api/src/services/plans.ts index 0b50239..6b8d309 100644 --- a/api/src/services/plans.ts +++ b/api/src/services/plans.ts @@ -201,6 +201,31 @@ export async function createPlan( }; } +/** + * Zmiana informacyjnej siłowni planu — dozwolona również dla planu ACTIVE + * (modal rozpoczęcia treningu: user stawił się w innej siłowni niż zamierzona). + * Tylko właściciel; docelowa siłownia musi być siłownią, której jest członkiem. + */ +export async function updatePlanGym( + prisma: PrismaClient, + planId: string, + userId: string, + gymId: string | null, +) { + const plan = await prisma.trainingPlan.findUnique({ + where: { id: planId }, + select: { id: true, userId: true }, + }); + if (!plan || plan.userId !== userId) throw notFound('Plan not found'); + await validateGymMembership(prisma, gymId, userId); + const updated = await prisma.trainingPlan.update({ + where: { id: plan.id }, + data: { gymId: gymId ?? null }, + select: { id: true, gym: { select: { id: true, name: true } } }, + }); + return { plan: { id: updated.id, gym: updated.gym } }; +} + export async function getPlan(prisma: PrismaClient, planId: string, userId: string) { const plan = await assertPlanAccess(prisma, planId, userId); // `shares` eksponowane tylko dla właściciela (lista odbiorców do dialogu diff --git a/api/src/services/presence.ts b/api/src/services/presence.ts new file mode 100644 index 0000000..3c6ef21 --- /dev/null +++ b/api/src/services/presence.ts @@ -0,0 +1,405 @@ +import type { Prisma, PrismaClient } from '@prisma/client'; +import { badRequest, notFound } from '../lib/errors.js'; + +export type PresenceSourceInput = 'QR' | 'MANUAL'; + +/** Slot bytności: 30 min bez aktywności -> EXPIRED (uwalnia licznik). */ +export const PRESENCE_SLOT_MS = 30 * 60 * 1000; +/** Merge luk: re-check-in w tej samej siłowni ≤15 min po wygaśnięciu wskrzesza segment. */ +export const PRESENCE_MERGE_MS = 15 * 60 * 1000; + +interface PresenceRow { + id: string; + userId: string; + gymId: string; + status: 'ACTIVE' | 'EXPIRED' | 'CLOSED'; + source: 'QR' | 'MANUAL'; + checkedInAt: Date; + lastActivityAt: Date; + closedAt: Date | null; +} + +/** Koniec bytności: CLOSED ma closedAt; EXPIRED/ACTIVE — ostatnia aktywność. */ +function endOf(p: PresenceRow): Date { + return p.closedAt ?? p.lastActivityAt ?? p.checkedInAt; +} + +function durationMinutes(p: PresenceRow): number { + const end = endOf(p); + const ms = end.getTime() - p.checkedInAt.getTime(); + return ms > 0 ? Math.round(ms / 60_000) : 0; +} + +function visitDto(p: PresenceRow, gymName: string) { + return { + id: p.id, + gymId: p.gymId, + gymName, + status: p.status, + source: p.source, + checkedInAt: p.checkedInAt, + lastActivityAt: p.lastActivityAt, + closedAt: p.closedAt, + durationMinutes: durationMinutes(p), + }; +} + +/** + * Meldunek na siłowni (tylko REAL). Maszyna stanów: + * - ACTIVE w tej samej siłowni → zwróć istniejącą (idempotentnie); + * - ACTIVE w innej siłowni → domknij (CLOSED) i melduj tutaj (ruch A→B); + * - EXPIRED w tej samej siłowni ≤15 min od ostatniej aktywności → wskrześ (merge luk); + * - w przeciwnym razie nowy segment. + * Serializacja per użytkownik na blokadzie doradczej (wzorzec startSession); + * częściowy indeks unikalny (userId WHERE ACTIVE) jest ostatnią linią obrony. + */ +export async function checkIn( + prisma: PrismaClient, + userId: string, + gymId: string, + source: PresenceSourceInput, +) { + const gym = await prisma.gym.findUnique({ + where: { id: gymId }, + select: { id: true, name: true, kind: true }, + }); + if (!gym) throw notFound('Gym not found'); + if (gym.kind !== 'REAL') throw badRequest('Check-in is available only for real gyms'); + const now = new Date(); + const presence = await prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${userId}))`; + const active = await tx.gymPresence.findFirst({ where: { userId, status: 'ACTIVE' } }); + if (active && active.gymId === gymId) return active; + if (active) { + // Przeniesienie A→B: stara bytność zostaje domknięta na teraz. + await tx.gymPresence.update({ + where: { id: active.id }, + data: { status: 'CLOSED', closedAt: now }, + }); + } + const expired = await tx.gymPresence.findFirst({ + where: { + userId, + gymId, + status: 'EXPIRED', + lastActivityAt: { gte: new Date(now.getTime() - PRESENCE_MERGE_MS) }, + }, + orderBy: { lastActivityAt: 'desc' }, + }); + if (expired) { + return tx.gymPresence.update({ + where: { id: expired.id }, + data: { + status: 'ACTIVE', + lastActivityAt: now, + closedAt: null, + // merge: jedno QR w historii segmentu czyni cały segment meldunkiem QR + source: expired.source === 'QR' || source === 'QR' ? 'QR' : 'MANUAL', + }, + }); + } + return tx.gymPresence.create({ data: { userId, gymId, source } }); + }); + return { presence: { ...presence, gymName: gym.name } }; +} + +/** "Wychodzę": ACTIVE -> CLOSED. Brak aktywnej bytności = no-op. */ +export async function checkOut(prisma: PrismaClient, userId: string) { + const result = await prisma.gymPresence.updateMany({ + where: { userId, status: 'ACTIVE' }, + data: { status: 'CLOSED', closedAt: new Date() }, + }); + return { checkedOut: result.count > 0 }; +} + +/** Odświeżenie slotu (heartbeat / "Wciąż tu jestem" / zapisy w sesji). Brak ACTIVE = no-op. */ +export async function touch(prisma: PrismaClient, userId: string) { + const result = await prisma.gymPresence.updateMany({ + where: { userId, status: 'ACTIVE' }, + data: { lastActivityAt: new Date() }, + }); + return { touched: result.count > 0 }; +} + +/** + * Best-effort touch z hooka sesji treningowej: błąd bytności nie może wywrócić + * zapisu serii — po cichu pomiń (scheduler i tak domknie wygasły slot). + */ +export async function touchPresenceBestEffort(prisma: PrismaClient, userId: string): Promise { + try { + await touch(prisma, userId); + } catch { + // best-effort celowo: bytność nie jest krytyczna dla zapisu treningu + } +} + +/** Sweep schedulera: ACTIVE bez aktywności >30 min -> EXPIRED. Zwraca liczbę zmian. */ +export async function expireStale(prisma: PrismaClient, now = new Date()): Promise { + const cutoff = new Date(now.getTime() - PRESENCE_SLOT_MS); + const result = await prisma.gymPresence.updateMany({ + where: { status: 'ACTIVE', lastActivityAt: { lt: cutoff } }, + data: { status: 'EXPIRED' }, + }); + return result.count; +} + +export async function getActive(prisma: PrismaClient, userId: string) { + const presence = await prisma.gymPresence.findFirst({ + where: { userId, status: 'ACTIVE' }, + include: { gym: { select: { id: true, name: true, capacity: true } } }, + }); + if (!presence) return { presence: null }; + return { + presence: { + id: presence.id, + gymId: presence.gym.id, + gymName: presence.gym.name, + gymCapacity: presence.gym.capacity, + status: presence.status, + source: presence.source, + checkedInAt: presence.checkedInAt, + lastActivityAt: presence.lastActivityAt, + closedAt: presence.closedAt, + }, + }; +} + +interface RangeQuery { + from?: Date; + to?: Date; +} + +function rangeWhere(range: RangeQuery): Prisma.GymPresenceWhereInput { + const w: Prisma.DateTimeFilter = {}; + if (range.from) w.gte = range.from; + if (range.to) w.lte = range.to; + return Object.keys(w).length > 0 ? { checkedInAt: w } : {}; +} + +export async function getHistory( + prisma: PrismaClient, + userId: string, + query: RangeQuery & { gymId?: string }, +) { + const presences = await prisma.gymPresence.findMany({ + where: { userId, ...(query.gymId ? { gymId: query.gymId } : {}), ...rangeWhere(query) }, + include: { gym: { select: { name: true } } }, + orderBy: { checkedInAt: 'desc' }, + take: 200, + }); + return { visits: presences.map((p) => visitDto(p, p.gym.name)) }; +} + +interface EquipmentStat { + equipmentId: string; + name: string; + nameEn: string | null; + count: number; +} + +interface StatsInput { + visits: number; + avgStayMinutes: number | null; + heatmap: { day: number; hour: number; count: number }[]; + topGyms: { gymId: string; gymName: string; visits: number }[]; + peak: number; + topEquipment: EquipmentStat[]; +} + +/** + * Agregaty z bytności (on-the-fly, bez rollupów). Heatmapa dzień×godzina w strefie + * procesu (TZ kontenera — jak scheduler), zapis UTC. + */ +async function buildStats(prisma: PrismaClient, presences: PresenceRow[]): Promise { + if (presences.length === 0) { + return { + visits: 0, + avgStayMinutes: null, + heatmap: [], + topGyms: [], + peak: 0, + topEquipment: [], + }; + } + // histogram dzień×godzina (0=pon ... 6=niedz, godzina lokalna procesu) + const heat = new Map(); + for (const p of presences) { + const day = (p.checkedInAt.getDay() + 6) % 7; + const hour = p.checkedInAt.getHours(); + const key = `${day}:${hour}`; + heat.set(key, (heat.get(key) ?? 0) + 1); + } + const heatmap = [...heat.entries()].map(([key, count]) => { + const [day, hour] = key.split(':').map(Number); + return { day, hour, count }; + }); + + // średni czas pobytu (end = closedAt ?? lastActivityAt) + const durations = presences + .map((p) => endOf(p).getTime() - p.checkedInAt.getTime()) + .filter((ms) => ms > 0); + const avgStayMinutes = + durations.length > 0 + ? Math.round(durations.reduce((a, b) => a + b, 0) / durations.length / 60_000) + : null; + + // peak = maksymalna jednoczesna liczba bytności (linia zamiatająca po przedziałach) + const events: { t: number; d: 1 | -1 }[] = []; + for (const p of presences) { + events.push({ t: p.checkedInAt.getTime(), d: 1 }); + events.push({ t: endOf(p).getTime(), d: -1 }); + } + events.sort((a, b) => a.t - b.t || a.d - b.d); + let peak = 0; + let running = 0; + for (const e of events) { + running += e.d; + if (running > peak) peak = running; + } + + // top siłownie + const byGym = new Map(); + for (const p of presences) byGym.set(p.gymId, (byGym.get(p.gymId) ?? 0) + 1); + const gymIds = [...byGym.keys()]; + const gyms = await prisma.gym.findMany({ + where: { id: { in: gymIds } }, + select: { id: true, name: true }, + }); + const gymNameById = new Map(gyms.map((g) => [g.id, g.name])); + const topGyms = gymIds + .map((id) => ({ gymId: id, gymName: gymNameById.get(id) ?? '', visits: byGym.get(id) ?? 0 })) + .filter((g) => g.gymName) + .sort((a, b) => b.visits - a.visits || a.gymName.localeCompare(b.gymName, 'pl')) + .slice(0, 5); + + // top urządzenia: okno bytności → sesje z startedAt w oknie → + // SessionExercise(!removed) → Exercise → Equipment (bez ręcznego wyboru sprzętu) + const topEquipment = await topEquipmentOf(prisma, presences); + + return { visits: presences.length, avgStayMinutes, heatmap, topGyms, peak, topEquipment }; +} + +async function topEquipmentOf( + prisma: PrismaClient, + presences: PresenceRow[], +): Promise { + const windowsByUser = new Map(); + let minStart = Infinity; + let maxEnd = -Infinity; + for (const p of presences) { + const start = p.checkedInAt.getTime(); + const end = Math.max(endOf(p).getTime(), start); + const list = windowsByUser.get(p.userId) ?? []; + list.push({ start, end }); + windowsByUser.set(p.userId, list); + if (start < minStart) minStart = start; + if (end > maxEnd) maxEnd = end; + } + if (!windowsByUser.size) return []; + const sessions = await prisma.trainingSession.findMany({ + where: { + startedAt: { gte: new Date(minStart), lte: new Date(maxEnd) }, + day: { week: { plan: { userId: { in: [...windowsByUser.keys()] } } } }, + }, + select: { + startedAt: true, + day: { select: { week: { select: { plan: { select: { userId: true } } } } } }, + exercises: { + where: { removed: false }, + select: { + exercise: { select: { equipment: { select: { id: true, name: true, nameEn: true } } } }, + }, + }, + }, + }); + const counts = new Map(); + for (const s of sessions) { + const userId = s.day.week.plan.userId; + const t = s.startedAt.getTime(); + const inWindow = (windowsByUser.get(userId) ?? []).some((w) => t >= w.start && t <= w.end); + if (!inWindow) continue; + for (const se of s.exercises) { + for (const eq of se.exercise.equipment) { + const cur = counts.get(eq.id); + if (cur) cur.count += 1; + else counts.set(eq.id, { equipmentId: eq.id, name: eq.name, nameEn: eq.nameEn, count: 1 }); + } + } + } + return [...counts.values()] + .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name, 'pl')) + .slice(0, 10); +} + +/** Statystyki bytności usera (sekcja „Moje wizyty" w profilu). */ +export async function getMyStats(prisma: PrismaClient, userId: string, range: RangeQuery) { + const presences = await prisma.gymPresence.findMany({ + where: { userId, ...rangeWhere(range) }, + orderBy: { checkedInAt: 'asc' }, + }); + return { stats: await buildStats(prisma, presences) }; +} + +/** Publiczny licznik „teraz: N" dla listy/szczegółów siłowni (null dla VIRTUAL — liczy caller). */ +export async function countActiveByGym(prisma: PrismaClient, gymIds: string[]) { + if (gymIds.length === 0) return new Map(); + const grouped = await prisma.gymPresence.groupBy({ + by: ['gymId'], + where: { gymId: { in: gymIds }, status: 'ACTIVE' }, + _count: { _all: true }, + }); + return new Map(grouped.map((g) => [g.gymId, g._count._all])); +} + +/** Live occupancy wszystkich siłowni (panel admina). */ +export async function getLiveOccupancy(prisma: PrismaClient) { + const grouped = await prisma.gymPresence.groupBy({ + by: ['gymId'], + where: { status: 'ACTIVE' }, + _count: { _all: true }, + }); + const countByGym = new Map(grouped.map((g) => [g.gymId, g._count._all])); + const gyms = await prisma.gym.findMany({ + where: { id: { in: [...countByGym.keys()] }, kind: 'REAL' }, + select: { id: true, name: true, capacity: true }, + orderBy: { name: 'asc' }, + }); + return { + gyms: gyms.map((g) => ({ + gymId: g.id, + name: g.name, + capacity: g.capacity, + count: countByGym.get(g.id) ?? 0, + })), + }; +} + +/** + * Telemetria siłowni (panel admina): heatmapa dzień×godzina (strefa TZ procesu, + * zapis UTC), śr. czas, wizyty/dzień, top urządzenia, peak. On-the-fly. + */ +export async function getGymStats( + prisma: PrismaClient, + gymId: string, + range: Required, +) { + const gym = await prisma.gym.findUnique({ + where: { id: gymId }, + select: { id: true, name: true, kind: true, capacity: true }, + }); + if (!gym) throw notFound('Gym not found'); + const [presences, live] = await Promise.all([ + prisma.gymPresence.findMany({ + where: { gymId, ...rangeWhere(range) }, + orderBy: { checkedInAt: 'asc' }, + }), + prisma.gymPresence.count({ where: { gymId, status: 'ACTIVE' } }), + ]); + const stats = await buildStats(prisma, presences); + const dayMs = 24 * 60 * 60 * 1000; + const days = Math.max(1, Math.ceil((range.to.getTime() - range.from.getTime()) / dayMs)); + return { + gym: { id: gym.id, name: gym.name, kind: gym.kind, capacity: gym.capacity }, + stats: { ...stats, live, visitsPerDay: Math.round((stats.visits / days) * 10) / 10 }, + }; +} diff --git a/api/src/services/scheduler.ts b/api/src/services/scheduler.ts index 42e5d5b..a65bb86 100644 --- a/api/src/services/scheduler.ts +++ b/api/src/services/scheduler.ts @@ -1,5 +1,6 @@ import type { PrismaClient } from '@prisma/client'; import { logger } from '../lib/logger.js'; +import { expireStale } from './presence.js'; /** * Background jobs (every 60s): @@ -12,6 +13,7 @@ import { logger } from '../lib/logger.js'; * abandonment — an abandoned training is not retryable). * 4. Auto-complete active plans when all days are completed/skipped. * 5. Remove gym schedule exceptions whose date is in the past. + * 6. Release presence slots: ACTIVE presence without activity for 30 min -> EXPIRED. */ export function startScheduler(prisma: PrismaClient): void { const tick = async () => { @@ -92,6 +94,16 @@ export function startScheduler(prisma: PrismaClient): void { }); if (removedExceptions.count > 0) logger.info({ count: removedExceptions.count }, 'Removed past gym exceptions'); + + // Sloty bytności wygasają niezależnie od reszty sweepów — własny catch, + // żeby awaria licznika "teraz" nie zatrzymywała porządków treningowych. + try { + const expiredPresences = await expireStale(prisma, now); + if (expiredPresences > 0) + logger.info({ count: expiredPresences }, 'Expired gym presences (30 min idle)'); + } catch (e) { + logger.error({ err: e }, 'Presence expiry failed'); + } } catch (e) { logger.error({ err: e }, 'Scheduler tick failed'); } diff --git a/api/src/services/sessions.ts b/api/src/services/sessions.ts index 317e236..2d37fb4 100644 --- a/api/src/services/sessions.ts +++ b/api/src/services/sessions.ts @@ -1,5 +1,6 @@ import type { Prisma, PrismaClient } from '@prisma/client'; import { badRequest, conflict, notFound } from '../lib/errors.js'; +import { touchPresenceBestEffort } from './presence.js'; export interface UpdateExerciseInput { hidden?: boolean; @@ -142,7 +143,11 @@ export async function getDay(prisma: PrismaClient, dayId: string, userId: string const day = await prisma.planDay.findUnique({ where: { id: dayId }, include: { - week: { include: { plan: true } }, + week: { + include: { + plan: { include: { gym: { select: { id: true, name: true } } } }, + }, + }, sessions: { orderBy: { startedAt: 'desc' } }, exercises: { orderBy: { order: 'asc' }, @@ -158,6 +163,8 @@ export async function getDay(prisma: PrismaClient, dayId: string, userId: string status: day.status, dayOfWeek: day.dayOfWeek, planId: day.week.planId, + // siłownia planu do modala check-inu przy rozpoczynaniu treningu + plan: { id: day.week.planId, gym: day.week.plan.gym }, sessions: day.sessions.map((s) => ({ id: s.id, status: s.status, startedAt: s.startedAt })), exercises: day.exercises.map((e) => ({ id: e.id, @@ -218,6 +225,8 @@ export async function addExercise( }, }); }); + // realna aktywność treningowa odświeża slot bytności (best-effort) + await touchPresenceBestEffort(prisma, userId); return { exerciseId: exercise.id, order: exercise.order }; } @@ -236,6 +245,7 @@ export async function updateExercise( await inSessionTransaction(prisma, exercise.sessionId, (tx) => tx.sessionExercise.update({ where: { id: exercise.id }, data }), ); + await touchPresenceBestEffort(prisma, userId); return { ok: true }; } @@ -271,6 +281,7 @@ export async function addSet(prisma: PrismaClient, exerciseId: string, userId: s data: { exerciseId: exercise.id, index: (maxIndex._max.index ?? -1) + 1 }, }); }); + await touchPresenceBestEffort(prisma, userId); return { setId: set.id, index: set.index }; } @@ -295,6 +306,7 @@ export async function updateSet( const updated = await inSessionTransaction(prisma, set.exercise.sessionId, (tx) => tx.sessionSet.update({ where: { id: set.id }, data }), ); + await touchPresenceBestEffort(prisma, userId); return { set: updated }; } diff --git a/api/src/swagger.ts b/api/src/swagger.ts index b75a5cc..cdb1c37 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -528,6 +528,84 @@ export const openapi: Record = { ], }, }, + '/gyms/{gymId}/check-in': { + post: { + tags: ['Gyms'], + summary: + 'Check in to a real gym (QR deep link source=QR or manual "Idę ćwiczyć"). Idempotent when already checked in to the same gym; closes the previous presence when moving A->B; revives an EXPIRED presence of the same gym via gap-merge (<=15 min since last activity)', + security: [{ bearerAuth: [] }], + parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }], + requestBody: { + required: false, + content: { + 'application/json': { + schema: { + type: 'object', + properties: { + source: { type: 'string', enum: ['QR', 'MANUAL'], default: 'MANUAL' }, + }, + }, + }, + }, + }, + responses: { + 200: { description: 'OK, returns { presence }' }, + 400: { description: 'VIRTUAL gym rejects check-in' }, + 404: { description: 'Gym not found' }, + }, + }, + }, + '/me/presence': { + get: { + tags: ['Presence'], + summary: 'Active presence of the caller (null when not checked in)', + security: [{ bearerAuth: [] }], + responses: { 200: { description: 'OK, returns { presence: object|null }' } }, + }, + }, + '/me/presence/check-out': { + post: { + tags: ['Presence'], + summary: 'Leave the gym ("Wychodzę") — ACTIVE -> CLOSED; no-op without an active presence', + security: [{ bearerAuth: [] }], + responses: { 200: { description: 'OK, returns { checkedOut: boolean }' } }, + }, + }, + '/me/presence/heartbeat': { + post: { + tags: ['Presence'], + summary: + "Refresh the presence slot ('Wciąż tu jestem' / workout-screen heartbeat, client throttles to 60s)", + security: [{ bearerAuth: [] }], + responses: { 200: { description: 'OK, returns { touched: boolean }' } }, + }, + }, + '/me/presence/history': { + get: { + tags: ['Presence'], + summary: 'Visit history of the caller', + security: [{ bearerAuth: [] }], + parameters: [ + { name: 'from', in: 'query', schema: { type: 'string', format: 'date-time' } }, + { name: 'to', in: 'query', schema: { type: 'string', format: 'date-time' } }, + { name: 'gymId', in: 'query', schema: { type: 'string' } }, + ], + responses: { 200: { description: 'OK, returns { visits: [...] }' } }, + }, + }, + '/me/presence/stats': { + get: { + tags: ['Presence'], + summary: + "Visit stats ('Moje wizyty'): top gyms, day×hour heatmap, avg stay, top equipment (derived from sessions started within presence windows)", + security: [{ bearerAuth: [] }], + parameters: [ + { name: 'from', in: 'query', schema: { type: 'string', format: 'date-time' } }, + { name: 'to', in: 'query', schema: { type: 'string', format: 'date-time' } }, + ], + responses: { 200: { description: 'OK, returns { stats }' } }, + }, + }, '/me/feed': { get: { tags: ['Feed'], @@ -995,6 +1073,33 @@ export const openapi: Record = { parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], }, }, + '/plans/{id}/gym': { + patch: { + tags: ['Plans'], + summary: + "Change the informational gym of a plan (owner only, any status). Used by the 'start training' presence modal when the user shows up at a different gym than the plan points to. Requires membership of the target gym.", + description: 'Writes an ActivityLog entry: plan.gym.updated.', + security: [{ bearerAuth: [] }], + parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + requestBody: { + required: true, + content: { + 'application/json': { + schema: { + type: 'object', + required: ['gymId'], + properties: { gymId: { type: 'string', nullable: true } }, + }, + }, + }, + }, + responses: { + 200: { description: 'OK, returns { plan: { id, gym } }' }, + 400: { description: 'Unknown gymId / owner is not a member of the gym' }, + 404: { description: 'Plan not found or caller is not the owner' }, + }, + }, + }, '/plans/{id}/activate': { post: { tags: ['Plans'], @@ -1103,6 +1208,20 @@ export const openapi: Record = { }, }, }, + '/days/{dayId}': { + get: { + tags: ['Sessions'], + summary: + 'Training day details (status, date, sessions, exercises, plan with gym for the check-in modal)', + security: [{ bearerAuth: [] }], + parameters: [{ name: 'dayId', in: 'path', required: true, schema: { type: 'string' } }], + responses: { + 200: { description: 'Day with sessions, exercises and plan (plan.gym may be null)' }, + 401: { description: 'Unauthorized' }, + 404: { description: 'Day not found' }, + }, + }, + }, '/days/{dayId}/sessions': { post: { tags: ['Sessions'], @@ -1251,6 +1370,33 @@ export const openapi: Record = { ], }, }, + '/admin/gyms/occupancy': { + get: { + tags: ['Admin'], + summary: 'Live occupancy of all real gyms (admin)', + security: [{ bearerAuth: [] }], + responses: { + 200: { description: 'OK, returns { gyms: [{ gymId, name, capacity, count }] }' }, + }, + }, + }, + '/admin/gyms/{id}/presence-stats': { + get: { + tags: ['Admin'], + summary: + 'Presence telemetry of a gym (admin): live count, day×hour heatmap, avg stay, visits/day, peak, top equipment (default range: last 30 days)', + security: [{ bearerAuth: [] }], + parameters: [ + { name: 'id', in: 'path', required: true, schema: { type: 'string' } }, + { name: 'from', in: 'query', schema: { type: 'string', format: 'date-time' } }, + { name: 'to', in: 'query', schema: { type: 'string', format: 'date-time' } }, + ], + responses: { + 200: { description: 'OK, returns { gym, stats }' }, + 404: { description: 'Gym not found' }, + }, + }, + }, '/admin/gyms': { get: { tags: ['Admin'], diff --git a/api/test/integration/plans.test.ts b/api/test/integration/plans.test.ts index ef99cc6..43eaa90 100644 --- a/api/test/integration/plans.test.ts +++ b/api/test/integration/plans.test.ts @@ -1199,3 +1199,68 @@ describe('plans: PATCH with startDate (update + activate)', () => { expect(detail.body.plan.startDate).toBeNull(); }); }); + +describe('PATCH /plans/:id/gym — zmiana siłowni planu (modal rozpoczęcia treningu)', () => { + it('changes the informational gym of an ACTIVE plan (owner + member) and returns the gym', async () => { + const app = buildApp(); + const { user, token } = await registerViaApi(); + const gym = await prisma.gym.create({ data: { name: `Plan Gym ${rand()}`, kind: 'REAL' } }); + await prisma.gymMembership.create({ data: { userId: user.id, gymId: gym.id, roles: ['MEMBER'] } }); + const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' }); + + const res = await app + .patch(`/api/v1/plans/${plan.id}/gym`) + .set('Authorization', `Bearer ${token}`) + .send({ gymId: gym.id }); + expect(res.status).toBe(200); + expect(res.body.plan).toEqual({ id: plan.id, gym: { id: gym.id, name: gym.name } }); + const row = await prisma.trainingPlan.findUnique({ where: { id: plan.id } }); + expect(row?.gymId).toBe(gym.id); + + const cleared = await app + .patch(`/api/v1/plans/${plan.id}/gym`) + .set('Authorization', `Bearer ${token}`) + .send({ gymId: null }); + expect(cleared.status).toBe(200); + expect(cleared.body.plan.gym).toBeNull(); + }); + + it('rejects a gym the owner is not a member of with 400 and an unknown gym with 400', async () => { + const app = buildApp(); + const { user, token } = await registerViaApi(); + const foreign = await prisma.gym.create({ data: { name: `Foreign Gym ${rand()}`, kind: 'REAL' } }); + const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' }); + + const notMember = await app + .patch(`/api/v1/plans/${plan.id}/gym`) + .set('Authorization', `Bearer ${token}`) + .send({ gymId: foreign.id }); + expect(notMember.status).toBe(400); + expect(notMember.body.error.message).toMatch(/member/i); + + const unknown = await app + .patch(`/api/v1/plans/${plan.id}/gym`) + .set('Authorization', `Bearer ${token}`) + .send({ gymId: 'nope' }); + expect(unknown.status).toBe(400); + expect(unknown.body.error.message).toMatch(/Unknown gymId/); + }); + + it('returns 404 for another user plan and 400 when gymId field is missing', async () => { + const app = buildApp(); + const { user } = await registerViaApi(); + const intruder = await registerViaApi(); + const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' }); + const res = await app + .patch(`/api/v1/plans/${plan.id}/gym`) + .set('Authorization', `Bearer ${intruder.token}`) + .send({ gymId: null }); + expect(res.status).toBe(404); + + const missing = await app + .patch(`/api/v1/plans/${plan.id}/gym`) + .set('Authorization', `Bearer ${intruder.token}`) + .send({}); + expect(missing.status).toBe(400); + }); +}); diff --git a/api/test/integration/presence.test.ts b/api/test/integration/presence.test.ts new file mode 100644 index 0000000..68c0087 --- /dev/null +++ b/api/test/integration/presence.test.ts @@ -0,0 +1,299 @@ +import { describe, it, expect, beforeAll } from 'vitest'; +import { prisma } from '../../src/lib/prisma.js'; +import { + buildApp, + createExercise, + createUserWithToken, + rand, + seedPlan, + seedSession, +} from '../helpers.js'; + +describe('presence — check-in, occupancy, telemetria', () => { + let realGymId: string; + let virtualGymId: string; + let member: { user: { id: string }; token: string }; + + beforeAll(async () => { + const real = await prisma.gym.create({ + data: { name: `Presence Gym ${rand()}`, kind: 'REAL', capacity: 50 }, + }); + realGymId = real.id; + const virtual = await prisma.gym.create({ + data: { name: `Presence Virtual ${rand()}`, kind: 'VIRTUAL' }, + }); + virtualGymId = virtual.id; + member = await createUserWithToken(); + await prisma.gymMembership.create({ + data: { userId: member.user.id, gymId: realGymId, roles: ['MEMBER'] }, + }); + await prisma.gymMembership.create({ + data: { userId: member.user.id, gymId: virtualGymId, roles: ['MEMBER'] }, + }); + }); + + const auth = (token: string) => ({ Authorization: `Bearer ${token}` }); + + it('POST /gyms/:id/check-in creates an ACTIVE presence (source QR)', async () => { + const app = buildApp(); + const { user, token } = await createUserWithToken(); + const res = await app + .post(`/api/v1/gyms/${realGymId}/check-in`) + .set(auth(token)) + .send({ source: 'QR' }); + expect(res.status).toBe(200); + expect(res.body.presence).toMatchObject({ userId: user.id, gymId: realGymId, status: 'ACTIVE', source: 'QR' }); + const row = await prisma.gymPresence.findFirst({ where: { userId: user.id } }); + expect(row?.status).toBe('ACTIVE'); + }); + + it('defaults source to MANUAL', async () => { + const app = buildApp(); + const { token } = await createUserWithToken(); + const res = await app + .post(`/api/v1/gyms/${realGymId}/check-in`) + .set(auth(token)) + .send({}); + expect(res.status).toBe(200); + expect(res.body.presence.source).toBe('MANUAL'); + }); + + it('is idempotent — checking in to the same gym twice returns the same presence', async () => { + const app = buildApp(); + const { token } = await createUserWithToken(); + const first = await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({}); + const second = await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({}); + expect(second.status).toBe(200); + expect(second.body.presence.id).toBe(first.body.presence.id); + }); + + it('rejects check-in to a VIRTUAL gym with 400', async () => { + const app = buildApp(); + const { token } = await createUserWithToken(); + const res = await app + .post(`/api/v1/gyms/${virtualGymId}/check-in`) + .set(auth(token)) + .send({}); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('BAD_REQUEST'); + }); + + it('rejects check-in to an unknown gym with 404 and without auth with 401', async () => { + const app = buildApp(); + const { token } = await createUserWithToken(); + const missing = await app.post('/api/v1/gyms/unknown/check-in').set(auth(token)).send({}); + expect(missing.status).toBe(404); + const anon = await app.post(`/api/v1/gyms/${realGymId}/check-in`).send({}); + expect(anon.status).toBe(401); + }); + + it('moving A->B closes the old presence and opens a new one', async () => { + const app = buildApp(); + const gymA = await prisma.gym.create({ data: { name: `Gym A ${rand()}`, kind: 'REAL' } }); + const gymB = await prisma.gym.create({ data: { name: `Gym B ${rand()}`, kind: 'REAL' } }); + const { user, token } = await createUserWithToken(); + await app.post(`/api/v1/gyms/${gymA.id}/check-in`).set(auth(token)).send({}); + const moved = await app.post(`/api/v1/gyms/${gymB.id}/check-in`).set(auth(token)).send({}); + expect(moved.status).toBe(200); + expect(moved.body.presence.gymId).toBe(gymB.id); + + const state = await app.get('/api/v1/me/presence').set(auth(token)); + expect(state.body.presence).toMatchObject({ gymId: gymB.id, status: 'ACTIVE', gymName: gymB.name }); + + const closedA = await prisma.gymPresence.findFirst({ + where: { userId: user.id, gymId: gymA.id }, + }); + expect(closedA?.status).toBe('CLOSED'); + expect(closedA?.closedAt).toBeInstanceOf(Date); + }); + + it('partial unique index blocks two ACTIVE presences per user at the DB level', async () => { + const { user } = await createUserWithToken(); + const gymC = await prisma.gym.create({ data: { name: `Gym C ${rand()}`, kind: 'REAL' } }); + const gymD = await prisma.gym.create({ data: { name: `Gym D ${rand()}`, kind: 'REAL' } }); + await prisma.gymPresence.create({ data: { userId: user.id, gymId: gymC.id } }); + await expect( + prisma.gymPresence.create({ data: { userId: user.id, gymId: gymD.id } }), + ).rejects.toMatchObject({ code: 'P2002' }); + }); + + it('GET /gyms exposes currentOccupancy for REAL and null for VIRTUAL', async () => { + const app = buildApp(); + const { token: visitorToken } = await createUserWithToken(); + await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(visitorToken)).send({}); + + const res = await app.get('/api/v1/gyms').set(auth(member.token)); + expect(res.status).toBe(200); + const real = res.body.gyms.find((g: { id: string }) => g.id === realGymId); + const virtual = res.body.gyms.find((g: { id: string }) => g.id === virtualGymId); + expect(real.currentOccupancy).toBeGreaterThanOrEqual(1); + expect(virtual.currentOccupancy).toBeNull(); + }); + + it('GET /gyms/:id exposes currentOccupancy', async () => { + const app = buildApp(); + const res = await app.get(`/api/v1/gyms/${realGymId}`).set(auth(member.token)); + expect(res.status).toBe(200); + expect(res.body.gym.currentOccupancy).toBeGreaterThanOrEqual(1); + // VIRTUAL jest widoczny tylko dla zarządców — promuj członkostwo do OWNER + await prisma.gymMembership.update({ + where: { userId_gymId: { userId: member.user.id, gymId: virtualGymId } }, + data: { roles: ['MEMBER', 'OWNER'] }, + }); + const virtualRes = await app.get(`/api/v1/gyms/${virtualGymId}`).set(auth(member.token)); + expect(virtualRes.status).toBe(200); + expect(virtualRes.body.gym.currentOccupancy).toBeNull(); + }); + + it('heartbeat refreshes the slot; check-out closes the presence', async () => { + const app = buildApp(); + const { user, token } = await createUserWithToken(); + await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({}); + // cofnij aktywność o 10 min, żeby przesunięcie było mierzalne + await prisma.gymPresence.updateMany({ + where: { userId: user.id }, + data: { lastActivityAt: new Date(Date.now() - 10 * 60 * 1000) }, + }); + + const beat = await app.post('/api/v1/me/presence/heartbeat').set(auth(token)); + expect(beat.status).toBe(200); + expect(beat.body).toEqual({ touched: true }); + const touched = await prisma.gymPresence.findFirst({ where: { userId: user.id } }); + expect(touched!.lastActivityAt.getTime()).toBeGreaterThan(Date.now() - 9 * 60 * 1000); + + const out = await app.post('/api/v1/me/presence/check-out').set(auth(token)); + expect(out.body).toEqual({ checkedOut: true }); + const state = await app.get('/api/v1/me/presence').set(auth(token)); + expect(state.body.presence).toBeNull(); + const again = await app.post('/api/v1/me/presence/check-out').set(auth(token)); + expect(again.body).toEqual({ checkedOut: false }); + }); + + it('heartbeat without an active presence is a no-op', async () => { + const app = buildApp(); + const { token } = await createUserWithToken(); + const beat = await app.post('/api/v1/me/presence/heartbeat').set(auth(token)); + expect(beat.body).toEqual({ touched: false }); + }); + + it('GET /me/presence/history lists visits with gym name and duration', async () => { + const app = buildApp(); + const { token } = await createUserWithToken(); + await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({ source: 'QR' }); + await app.post('/api/v1/me/presence/check-out').set(auth(token)); + const res = await app.get('/api/v1/me/presence/history').set(auth(token)); + expect(res.status).toBe(200); + expect(res.body.visits).toHaveLength(1); + expect(res.body.visits[0]).toMatchObject({ + gymId: realGymId, + status: 'CLOSED', + source: 'QR', + }); + expect(res.body.visits[0].durationMinutes).toBeGreaterThanOrEqual(0); + // filtr po gymId działa + const filtered = await app + .get(`/api/v1/me/presence/history?gymId=${virtualGymId}`) + .set(auth(token)); + expect(filtered.body.visits).toHaveLength(0); + }); + + it('GET /me/presence/stats aggregates the caller visits', async () => { + const app = buildApp(); + const { token } = await createUserWithToken(); + await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({}); + const res = await app.get('/api/v1/me/presence/stats').set(auth(token)); + expect(res.status).toBe(200); + expect(res.body.stats.visits).toBe(1); + expect(res.body.stats.topGyms[0]).toMatchObject({ gymId: realGymId }); + }); + + it('zapis serii w sesji przesuwa lastActivityAt aktywnej bytności (hook)', async () => { + const app = buildApp(); + const { user, token } = await createUserWithToken(); + await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({}); + const exercise = await createExercise(); + const plan = await seedPlan({ + userId: user.id, + status: 'ACTIVE', + startDate: new Date(Date.UTC(2026, 9, 19)), + weeks: [ + { + index: 0, + days: [ + { + dayOfWeek: 1, + date: new Date(Date.UTC(2026, 9, 19)), + exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0 }] }], + }, + ], + }, + ], + }); + const day = plan.weeks[0].days[0]; + const session = await seedSession(day.id, { + status: 'IN_PROGRESS', + exercises: [ + { + exerciseId: exercise.id, + planExerciseId: day.exercises[0].id, + order: 0, + sets: [{ planSetId: day.exercises[0].sets[0].id, reps: null }], + }, + ], + }); + // cofnij aktywność, żeby przesunięcie było mierzalne + await prisma.gymPresence.updateMany({ + where: { userId: user.id }, + data: { lastActivityAt: new Date(Date.now() - 10 * 60 * 1000) }, + }); + + const setId = session.exercises[0].sets[0].id; + const patch = await app + .patch(`/api/v1/sessions/sets/${setId}`) + .set(auth(token)) + .send({ reps: 10 }); + expect(patch.status).toBe(200); + + const row = await prisma.gymPresence.findFirst({ where: { userId: user.id } }); + expect(row!.lastActivityAt.getTime()).toBeGreaterThan(Date.now() - 9 * 60 * 1000); + }); + + it('admin occupancy lists live gyms; forbidden for non-admins', async () => { + const app = buildApp(); + const admin = await createUserWithToken({ isAdmin: true }); + const gym = await prisma.gym.create({ data: { name: `Occupied ${rand()}`, kind: 'REAL' } }); + const visitor = await createUserWithToken(); + await app.post(`/api/v1/gyms/${gym.id}/check-in`).set(auth(visitor.token)).send({}); + + const res = await app.get('/api/v1/admin/gyms/occupancy').set(auth(admin.token)); + expect(res.status).toBe(200); + const found = res.body.gyms.find((g: { gymId: string }) => g.gymId === gym.id); + expect(found).toMatchObject({ name: gym.name, count: 1 }); + + const denied = await app.get('/api/v1/admin/gyms/occupancy').set(auth(member.token)); + expect(denied.status).toBe(403); + }); + + it('admin presence-stats exposes telemetry for a gym', async () => { + const app = buildApp(); + const admin = await createUserWithToken({ isAdmin: true }); + const res = await app + .get(`/api/v1/admin/gyms/${realGymId}/presence-stats`) + .set(auth(admin.token)); + expect(res.status).toBe(200); + expect(res.body.gym.id).toBe(realGymId); + expect(res.body.stats.visits).toBeGreaterThanOrEqual(1); + expect(res.body.stats.live).toBeGreaterThanOrEqual(1); + expect(res.body.stats.visitsPerDay).toBeGreaterThanOrEqual(0); + expect(Array.isArray(res.body.stats.heatmap)).toBe(true); + + const missing = await app + .get('/api/v1/admin/gyms/unknown/presence-stats') + .set(auth(admin.token)); + expect(missing.status).toBe(404); + const denied = await app + .get(`/api/v1/admin/gyms/${realGymId}/presence-stats`) + .set(auth(member.token)); + expect(denied.status).toBe(403); + }); +}); diff --git a/api/test/unit/presence.test.ts b/api/test/unit/presence.test.ts new file mode 100644 index 0000000..837d947 --- /dev/null +++ b/api/test/unit/presence.test.ts @@ -0,0 +1,277 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { + checkIn, + checkOut, + expireStale, + getMyStats, + touch, +} from '../../src/services/presence.js'; + +const NOW = new Date(2026, 9, 22, 12, 0, 0); + +function presenceRow(overrides: Record = {}) { + return { + id: 'p1', + userId: 'u1', + gymId: 'g1', + status: 'ACTIVE', + source: 'MANUAL', + checkedInAt: NOW, + lastActivityAt: NOW, + closedAt: null, + ...overrides, + }; +} + +function mockPrisma() { + const prisma: any = { + gym: { findUnique: vi.fn(), findMany: vi.fn() }, + gymPresence: { + findFirst: vi.fn(), + findMany: vi.fn(), + create: vi.fn(), + update: vi.fn(), + updateMany: vi.fn(), + count: vi.fn(), + }, + trainingSession: { findMany: vi.fn() }, + $executeRaw: vi.fn().mockResolvedValue(1), + $transaction: vi.fn(), + }; + prisma.$transaction.mockImplementation(async (cb: (tx: unknown) => Promise) => + cb(prisma), + ); + prisma.gym.findUnique.mockResolvedValue({ id: 'g1', name: 'Siłownia', kind: 'REAL' }); + prisma.gymPresence.create.mockImplementation(async ({ data }: any) => + presenceRow({ id: 'p-new', ...data, status: 'ACTIVE', checkedInAt: NOW, lastActivityAt: NOW }), + ); + prisma.gymPresence.update.mockImplementation(async ({ where, data }: any) => + presenceRow({ id: where.id, ...data }), + ); + prisma.gymPresence.updateMany.mockResolvedValue({ count: 1 }); + prisma.trainingSession.findMany.mockResolvedValue([]); + return prisma; +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(NOW); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('checkIn', () => { + it('404 when the gym does not exist', async () => { + const prisma = mockPrisma(); + prisma.gym.findUnique.mockResolvedValue(null); + await expect(checkIn(prisma, 'u1', 'g1', 'MANUAL')).rejects.toMatchObject({ status: 404 }); + }); + + it('400 for VIRTUAL gyms (only REAL accept check-ins)', async () => { + const prisma = mockPrisma(); + prisma.gym.findUnique.mockResolvedValue({ id: 'g1', name: 'V', kind: 'VIRTUAL' }); + await expect(checkIn(prisma, 'u1', 'g1', 'MANUAL')).rejects.toMatchObject({ + status: 400, + message: 'Check-in is available only for real gyms', + }); + expect(prisma.gymPresence.create).not.toHaveBeenCalled(); + }); + + it('is idempotent when already checked in to the same gym', async () => { + const prisma = mockPrisma(); + prisma.gymPresence.findFirst.mockResolvedValue(presenceRow({ id: 'p1' })); + const { presence } = await checkIn(prisma, 'u1', 'g1', 'MANUAL'); + expect(presence.id).toBe('p1'); + expect(prisma.gymPresence.create).not.toHaveBeenCalled(); + expect(prisma.gymPresence.update).not.toHaveBeenCalled(); + expect(prisma.gymPresence.updateMany).not.toHaveBeenCalled(); + }); + + it('closes the old presence when moving A->B and opens a new one', async () => { + const prisma = mockPrisma(); + prisma.gymPresence.findFirst + .mockResolvedValueOnce(presenceRow({ id: 'p-a', gymId: 'gA' })) // ACTIVE w innej siłowni + .mockResolvedValueOnce(null); // brak EXPIRED w docelowej + const { presence } = await checkIn(prisma, 'u1', 'gB', 'MANUAL'); + expect(prisma.gymPresence.update).toHaveBeenCalledWith({ + where: { id: 'p-a' }, + data: { status: 'CLOSED', closedAt: NOW }, + }); + expect(prisma.gymPresence.create).toHaveBeenCalledWith({ + data: { userId: 'u1', gymId: 'gB', source: 'MANUAL' }, + }); + expect(presence.id).toBe('p-new'); + }); + + it('revives an EXPIRED presence via gap-merge when <=15 min since last activity', async () => { + const prisma = mockPrisma(); + const expired = presenceRow({ + id: 'p-old', + status: 'EXPIRED', + lastActivityAt: new Date(NOW.getTime() - 10 * 60 * 1000), + closedAt: null, + }); + prisma.gymPresence.findFirst.mockImplementation(async ({ where }: any) => { + if (where.status === 'ACTIVE') return null; + if (where.status === 'EXPIRED' && where.lastActivityAt) return expired; + return null; + }); + const { presence } = await checkIn(prisma, 'u1', 'g1', 'MANUAL'); + expect(presence.id).toBe('p-old'); + expect(prisma.gymPresence.create).not.toHaveBeenCalled(); + expect(prisma.gymPresence.update).toHaveBeenCalledWith({ + where: { id: 'p-old' }, + data: { status: 'ACTIVE', lastActivityAt: NOW, closedAt: null, source: 'MANUAL' }, + }); + }); + + it('starts a new segment when the expired presence is older than 15 min', async () => { + const prisma = mockPrisma(); + prisma.gymPresence.findFirst.mockResolvedValue(null); // merge wyklucza >15 min (filtr w where) + const { presence } = await checkIn(prisma, 'u1', 'g1', 'MANUAL'); + expect(presence.id).toBe('p-new'); + expect(prisma.gymPresence.create).toHaveBeenCalled(); + // filtr okna merge musi ograniczać EXPIRED do 15 minut + const expiredQuery = prisma.gymPresence.findFirst.mock.calls.find( + ([args]: any) => args.where.status === 'EXPIRED', + ); + expect(expiredQuery![0].where.lastActivityAt.gte).toEqual( + new Date(NOW.getTime() - 15 * 60 * 1000), + ); + }); + + it('merge promotes the source to QR if either check-in was QR', async () => { + const prisma = mockPrisma(); + const expired = presenceRow({ + id: 'p-old', + status: 'EXPIRED', + source: 'QR', + lastActivityAt: new Date(NOW.getTime() - 5 * 60 * 1000), + }); + prisma.gymPresence.findFirst.mockImplementation(async ({ where }: any) => { + if (where.status === 'EXPIRED') return expired; + return null; + }); + await checkIn(prisma, 'u1', 'g1', 'MANUAL'); + expect(prisma.gymPresence.update).toHaveBeenCalledWith({ + where: { id: 'p-old' }, + data: expect.objectContaining({ source: 'QR' }), + }); + }); + + it('serializes concurrent check-ins per user with an advisory lock', async () => { + const prisma = mockPrisma(); + prisma.gymPresence.findFirst.mockResolvedValue(null); + await checkIn(prisma, 'u1', 'g1', 'QR'); + expect(prisma.$executeRaw).toHaveBeenCalled(); + expect(prisma.$executeRaw.mock.calls[0][0].join('')).toContain('pg_advisory_xact_lock'); + }); +}); + +describe('checkOut', () => { + it('closes the active presence (ACTIVE -> CLOSED)', async () => { + const prisma = mockPrisma(); + const result = await checkOut(prisma, 'u1'); + expect(prisma.gymPresence.updateMany).toHaveBeenCalledWith({ + where: { userId: 'u1', status: 'ACTIVE' }, + data: { status: 'CLOSED', closedAt: NOW }, + }); + expect(result).toEqual({ checkedOut: true }); + }); + + it('is a no-op without an active presence', async () => { + const prisma = mockPrisma(); + prisma.gymPresence.updateMany.mockResolvedValue({ count: 0 }); + const result = await checkOut(prisma, 'u1'); + expect(result).toEqual({ checkedOut: false }); + }); +}); + +describe('touch', () => { + it('refreshes lastActivityAt of the active presence', async () => { + const prisma = mockPrisma(); + const result = await touch(prisma, 'u1'); + expect(prisma.gymPresence.updateMany).toHaveBeenCalledWith({ + where: { userId: 'u1', status: 'ACTIVE' }, + data: { lastActivityAt: NOW }, + }); + expect(result).toEqual({ touched: true }); + }); + + it('is a no-op without an active presence', async () => { + const prisma = mockPrisma(); + prisma.gymPresence.updateMany.mockResolvedValue({ count: 0 }); + const result = await touch(prisma, 'u1'); + expect(result).toEqual({ touched: false }); + }); +}); + +describe('expireStale', () => { + it('releases slots idle for more than 30 min (ACTIVE -> EXPIRED)', async () => { + const prisma = mockPrisma(); + const count = await expireStale(prisma, NOW); + expect(prisma.gymPresence.updateMany).toHaveBeenCalledWith({ + where: { status: 'ACTIVE', lastActivityAt: { lt: new Date(NOW.getTime() - 30 * 60 * 1000) } }, + data: { status: 'EXPIRED' }, + }); + expect(count).toBe(1); + }); +}); + +describe('getMyStats', () => { + it('returns empty aggregates when the user has no visits', async () => { + const prisma = mockPrisma(); + prisma.gymPresence.findMany.mockResolvedValue([]); + const { stats } = await getMyStats(prisma, 'u1', {}); + expect(stats).toEqual({ + visits: 0, + avgStayMinutes: null, + heatmap: [], + topGyms: [], + peak: 0, + topEquipment: [], + }); + }); + + it('aggregates visits, avg stay, peak, top gyms and derives top equipment from session windows', async () => { + const prisma = mockPrisma(); + const monday = new Date(2026, 9, 19, 18, 0, 0); // poniedziałek 18:00 lokalnie + prisma.gymPresence.findMany.mockResolvedValue([ + presenceRow({ id: 'p1', checkedInAt: monday, lastActivityAt: new Date(monday.getTime() + 60 * 60 * 1000) }), + presenceRow({ + id: 'p2', + checkedInAt: new Date(2026, 9, 19, 18, 30, 0), + lastActivityAt: new Date(2026, 9, 19, 19, 0, 0), + }), + ]); + prisma.gym.findMany.mockResolvedValue([{ id: 'g1', name: 'Siłownia' }]); + // sesja startedAt w oknie bytności → ćwiczenie z urządzeniem + prisma.trainingSession.findMany.mockResolvedValue([ + { + startedAt: new Date(2026, 9, 19, 18, 10, 0), + day: { week: { plan: { userId: 'u1' } } }, + exercises: [{ exercise: { equipment: [{ id: 'e1', name: 'Sztanga', nameEn: 'Barbell' }] } }], + }, + // sesja poza oknem — nie liczy się + { + startedAt: new Date(2026, 9, 19, 22, 0, 0), + day: { week: { plan: { userId: 'u1' } } }, + exercises: [{ exercise: { equipment: [{ id: 'e2', name: 'Hantle', nameEn: null }] } }], + }, + ]); + const { stats } = await getMyStats(prisma, 'u1', {}); + expect(stats.visits).toBe(2); + // p1: 60 min, p2: 30 min → średnia 45 + expect(stats.avgStayMinutes).toBe(45); + // peak: nakładające się okna → 2 jednocześnie + expect(stats.peak).toBe(2); + expect(stats.topGyms).toEqual([{ gymId: 'g1', gymName: 'Siłownia', visits: 2 }]); + expect(stats.topEquipment).toEqual([ + { equipmentId: 'e1', name: 'Sztanga', nameEn: 'Barbell', count: 1 }, + ]); + // heatmapa: poniedziałek (dzień 0) × godzina 18 + expect(stats.heatmap).toContainEqual({ day: 0, hour: 18, count: 2 }); + }); +}); diff --git a/api/test/unit/scheduler.test.ts b/api/test/unit/scheduler.test.ts index 071d35f..7cdde48 100644 --- a/api/test/unit/scheduler.test.ts +++ b/api/test/unit/scheduler.test.ts @@ -6,11 +6,15 @@ const sessionUpdateMany = vi.fn(); const sessionFindMany = vi.fn(); const planFindMany = vi.fn(); const planUpdate = vi.fn(); +const presenceUpdateMany = vi.fn(); +const exceptionDeleteMany = vi.fn(); const prisma = { planDay: { updateMany: planDayUpdateMany }, trainingSession: { updateMany: sessionUpdateMany, findMany: sessionFindMany }, trainingPlan: { findMany: planFindMany, update: planUpdate }, + gymPresence: { updateMany: presenceUpdateMany }, + gymException: { deleteMany: exceptionDeleteMany }, } as never; const NOW = new Date(2026, 7, 22, 12, 0, 0); @@ -29,6 +33,8 @@ beforeEach(() => { sessionFindMany.mockReset().mockResolvedValue([]); planFindMany.mockReset().mockResolvedValue([]); planUpdate.mockReset().mockResolvedValue({}); + presenceUpdateMany.mockReset().mockResolvedValue({ count: 0 }); + exceptionDeleteMany.mockReset().mockResolvedValue({ count: 0 }); }); afterEach(() => { @@ -126,4 +132,23 @@ describe('scheduler', () => { await expect(tickOnce()).resolves.toBeUndefined(); expect(sessionUpdateMany).not.toHaveBeenCalled(); }); + + it('expires presence slots after 30 min without activity', async () => { + presenceUpdateMany.mockResolvedValue({ count: 3 }); + await tickOnce(); + expect(presenceUpdateMany).toHaveBeenCalledWith({ + where: { + status: 'ACTIVE', + lastActivityAt: { lt: new Date(NOW.getTime() - 30 * 60 * 1000) }, + }, + data: { status: 'EXPIRED' }, + }); + }); + + it('presence expiry failure does not crash the tick', async () => { + presenceUpdateMany.mockRejectedValue(new Error('db down')); + await expect(tickOnce()).resolves.toBeUndefined(); + // reszta sweepów wykonała się mimo awarii licznika "teraz" + expect(planDayUpdateMany).toHaveBeenCalled(); + }); }); diff --git a/app/package-lock.json b/app/package-lock.json index 00756a0..002c468 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -14,10 +14,12 @@ "@radix-ui/react-separator": "^1.1.15", "@tailwindcss/vite": "^4.3.3", "@tanstack/react-query": "^5.62.0", + "@types/qrcode": "^1.5.6", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "i18next": "^26.4.7", "lucide-react": "^1.33.0", + "qrcode": "^1.5.4", "react": "^18.3.1", "react-dom": "^18.3.1", "react-i18next": "^17.0.20", @@ -1180,9 +1182,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1646,9 +1645,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1662,9 +1658,6 @@ "cpu": [ "arm" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1678,9 +1671,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1694,9 +1684,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1710,9 +1697,6 @@ "cpu": [ "loong64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1726,9 +1710,6 @@ "cpu": [ "loong64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1742,9 +1723,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1758,9 +1736,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1774,9 +1749,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1790,9 +1762,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1806,9 +1775,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1822,9 +1788,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1838,9 +1801,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2050,9 +2010,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2069,9 +2026,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2088,9 +2042,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2107,9 +2058,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2459,7 +2407,6 @@ "version": "26.2.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz", "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==", - "devOptional": true, "license": "MIT", "dependencies": { "undici-types": "~8.3.0" @@ -2472,6 +2419,15 @@ "devOptional": true, "license": "MIT" }, + "node_modules/@types/qrcode": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz", + "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/react": { "version": "18.3.31", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz", @@ -2978,7 +2934,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -2988,7 +2943,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, "license": "MIT", "dependencies": { "color-convert": "^2.0.1" @@ -3145,6 +3099,15 @@ "node": ">=6" } }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001809", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001809.tgz", @@ -3222,6 +3185,17 @@ "url": "https://polar.sh/cva" } }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, "node_modules/clsx": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", @@ -3235,7 +3209,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, "license": "MIT", "dependencies": { "color-name": "~1.1.4" @@ -3248,7 +3221,6 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, "license": "MIT" }, "node_modules/combined-stream": { @@ -3480,6 +3452,15 @@ } } }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/decimal.js": { "version": "10.6.0", "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", @@ -3545,6 +3526,12 @@ "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", "license": "MIT" }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, "node_modules/dom-accessibility-api": { "version": "0.5.16", "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", @@ -3584,6 +3571,12 @@ "dev": true, "license": "ISC" }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, "node_modules/enhanced-resolve": { "version": "5.24.5", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", @@ -4073,6 +4066,15 @@ "node": ">=6.9.0" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -4375,6 +4377,15 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -4688,9 +4699,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4711,9 +4719,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4734,9 +4739,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4757,9 +4759,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -5063,6 +5062,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -5093,7 +5101,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -5191,6 +5198,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/postcss": { "version": "8.5.26", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", @@ -5307,6 +5323,23 @@ "node": ">=6" } }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/react": { "version": "18.3.1", "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", @@ -5554,6 +5587,21 @@ "node": ">=8" } }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "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", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", @@ -5655,6 +5703,12 @@ "semver": "bin/semver.js" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -5708,6 +5762,32 @@ "dev": true, "license": "MIT" }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-indent": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", @@ -5974,7 +6054,6 @@ "version": "8.3.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", - "devOptional": true, "license": "MIT" }, "node_modules/update-browserslist-db": { @@ -6339,6 +6418,12 @@ "node": ">= 8" } }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -6366,6 +6451,20 @@ "node": ">=0.10.0" } }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/ws": { "version": "8.21.3", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", @@ -6405,6 +6504,12 @@ "dev": true, "license": "MIT" }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", @@ -6412,6 +6517,93 @@ "dev": true, "license": "ISC" }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yargs/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/app/package.json b/app/package.json index ec00555..75fefc8 100644 --- a/app/package.json +++ b/app/package.json @@ -22,10 +22,12 @@ "@radix-ui/react-separator": "^1.1.15", "@tailwindcss/vite": "^4.3.3", "@tanstack/react-query": "^5.62.0", + "@types/qrcode": "^1.5.6", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "i18next": "^26.4.7", "lucide-react": "^1.33.0", + "qrcode": "^1.5.4", "react": "^18.3.1", "react-dom": "^18.3.1", "react-i18next": "^17.0.20", diff --git a/app/src/App.tsx b/app/src/App.tsx index 0125f8b..c560c9c 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -20,6 +20,7 @@ import ProfileProgress from './pages/profile/ProfileProgress'; import ProfileClaims from './pages/profile/ProfileClaims'; import Gyms from './pages/gyms/Gyms'; import GymDetail from './pages/gyms/GymDetail'; +import GymCheckIn from './pages/gyms/GymCheckIn'; import Trainees from './pages/trainees/Trainees'; import TraineeDetail from './pages/trainees/TraineeDetail'; import Invitations from './pages/Invitations'; @@ -67,6 +68,7 @@ export default function App() { } /> } /> } /> + } /> api<{ presence: ActivePresence | null }>('/me/presence'), + }); +} + +/** Meldunek w siłowni REAL (tylko z jawnego kliknięcia; serwer idempotentnie zwraca istniejącą). */ +export function checkIn(gymId: string, source: PresenceSource = 'MANUAL') { + return api<{ presence: ActivePresence & { gymName: string } }>( + `/gyms/${encodeURIComponent(gymId)}/check-in`, + { method: 'POST', body: { source } }, + ); +} + +export function checkOutPresence() { + return api<{ checkedOut: boolean }>('/me/presence/check-out', { method: 'POST' }); +} + +/** Odświeżenie slotu bytności (heartbeat / „Wciąż tu jestem"); brak aktywnej = no-op. */ +export function presenceHeartbeat() { + return api<{ touched: boolean }>('/me/presence/heartbeat', { method: 'POST' }); +} + +export function usePresenceHistory(gymId?: string) { + return useQuery({ + queryKey: ['me', 'presence', 'history', gymId ?? 'all'], + queryFn: () => + api<{ visits: PresenceVisit[] }>( + `/me/presence/history${gymId ? `?gymId=${encodeURIComponent(gymId)}` : ''}`, + ), + }); +} + +export function usePresenceStats() { + return useQuery({ + queryKey: ['me', 'presence', 'stats'], + queryFn: () => api<{ stats: PresenceStats }>('/me/presence/stats'), + }); +} + /** Dodaje zdjęcia do galerii siłowni REAL (multipart, pole `photos`). */ export function addGymPhotos(gymId: string, files: File[]) { const form = new FormData(); @@ -520,6 +567,17 @@ export function reopenPlan(id: string) { return api(`/plans/${id}/reopen`, { method: 'POST' }); } +/** + * Zmiana informacyjnej siłowni planu (właściciel, dowolny status) — modal rozpoczęcia + * treningu, gdy user stawił się w innej siłowni niż plan wskazuje. + */ +export function updatePlanGym(planId: string, gymId: string | null) { + return api<{ plan: { id: string; gym: { id: string; name: string } | null } }>( + `/plans/${planId}/gym`, + { method: 'PATCH', body: { gymId } }, + ); +} + // ---------- sessions ---------- export function useSession(id: string) { return useQuery({ diff --git a/app/src/api/types.ts b/app/src/api/types.ts index 3c55ce0..5ff90aa 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -141,6 +141,8 @@ export interface Gym { equipment: GymEquipment[]; /** Okładka galerii (pierwsze zdjęcie) — tylko siłownie REAL; null = brak zdjęć. */ coverPhoto: string | null; + /** Live „teraz: N" (aktywne bytności); null dla VIRTUAL (brak meldunków). */ + currentOccupancy?: number | null; } /** Odpowiedź detalu siłowni (GET /gyms/:id): siłownia + galeria + role zalogowanego. */ @@ -150,6 +152,46 @@ export interface GymDetailResponse { isAdmin: boolean; } +// ---------- bytność (check-in / live occupancy) ---------- +export type PresenceStatus = 'ACTIVE' | 'EXPIRED' | 'CLOSED'; +export type PresenceSource = 'QR' | 'MANUAL'; + +/** Aktywna bytność zalogowanego (GET /me/presence); null = brak meldunku. */ +export interface ActivePresence { + id: string; + gymId: string; + gymName: string; + gymCapacity: number | null; + status: PresenceStatus; + source: PresenceSource; + checkedInAt: string; + lastActivityAt: string; + closedAt: string | null; +} + +/** Wpis historii wizyt (GET /me/presence/history). */ +export interface PresenceVisit { + id: string; + gymId: string; + gymName: string; + status: PresenceStatus; + source: PresenceSource; + checkedInAt: string; + lastActivityAt: string; + closedAt: string | null; + durationMinutes: number; +} + +/** Statystyki bytności (GET /me/presence/stats): heatmapa dzień(0=pon..6=niedz)×godzina. */ +export interface PresenceStats { + visits: number; + avgStayMinutes: number | null; + heatmap: { day: number; hour: number; count: number }[]; + topGyms: { gymId: string; gymName: string; visits: number }[]; + peak: number; + topEquipment: { equipmentId: string; name: string; nameEn: string | null; count: number }[]; +} + /** Wpis listy wirtualnych siłowni: publiczne (z ocenami) + własne prywatne (bez ocen). */ export interface VirtualGym { id: string; diff --git a/app/src/components/gyms/GymQrModal.tsx b/app/src/components/gyms/GymQrModal.tsx new file mode 100644 index 0000000..a7e8c80 --- /dev/null +++ b/app/src/components/gyms/GymQrModal.tsx @@ -0,0 +1,94 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { QrCode } from 'lucide-react'; +import { toDataURL } from 'qrcode'; +import { Button, Modal } from '../ui'; +import { useToast } from '../toast'; + +/** + * Kod QR do naklejenia na siłownię — prowadzi na /gyms/:id/checkin. + * Druk przez window.print() + reguła @media print w styles.css (klasa .print-qr). + */ +export default function GymQrModal({ + open, + onClose, + gymId, + gymName, +}: { + open: boolean; + onClose: () => void; + gymId: string; + gymName: string; +}) { + const { t } = useTranslation('presence'); + const { push } = useToast(); + const link = `${window.location.origin}/gyms/${gymId}/checkin`; + const [dataUrl, setDataUrl] = useState(null); + + useEffect(() => { + setDataUrl(null); + if (!open) return; + let alive = true; + toDataURL(link, { width: 480, margin: 2, errorCorrectionLevel: 'M' }) + .then((url) => { + if (alive) setDataUrl(url); + }) + .catch(() => { + if (alive) setDataUrl(null); + }); + return () => { + alive = false; + }; + }, [open, link]); + + const download = () => { + if (!dataUrl) return; + const a = document.createElement('a'); + a.href = dataUrl; + a.download = `fitos-qr-${gymId}.png`; + a.click(); + }; + + const copy = async () => { + try { + await navigator.clipboard.writeText(link); + push(t('qr.copied'), 'success'); + } catch { + /* clipboard niedostępny (brak HTTPS) — pomijamy */ + } + }; + + return ( + +
+

{t('qr.subtitle')}

+
+ {dataUrl ? ( + {gymName} + ) : ( +
+
+ )} +
+

{link}

+
+
+ + + +
+
+ ); +} diff --git a/app/src/components/presence/StartTrainingPresenceModal.tsx b/app/src/components/presence/StartTrainingPresenceModal.tsx new file mode 100644 index 0000000..86d9844 --- /dev/null +++ b/app/src/components/presence/StartTrainingPresenceModal.tsx @@ -0,0 +1,136 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { ActivePresence } from '../../api/types'; +import { Button, Modal, Select } from '../ui'; + +/** + * Modal przy rozpoczynaniu treningu, gdy user nie ma meldunku w siłowni planu. + * Nigdy nie blokuje treningu — zawsze jest „Kontynuuj bez meldunku". + */ +export default function StartTrainingPresenceModal({ + open, + onClose, + planGym, + presence, + gyms, + busy, + onCheckIn, + onChangePlanGym, + onContinue, +}: { + open: boolean; + onClose: () => void; + planGym: { id: string; name: string } | null; + presence: ActivePresence | null; + /** REAL siłownie, w których user ma członkostwo (pick „inna siłownia"). */ + gyms: { id: string; name: string }[]; + busy?: boolean; + /** Meldunek w wybranej siłowni (opcjonalnie też przepięcie siłowni planu). */ + onCheckIn: (gymId: string, opts?: { alsoChangePlanGym?: boolean }) => void; + /** Przepięcie siłowni planu bez zmiany meldunku (user już meldowany gdzie indziej). */ + onChangePlanGym: (gymId: string) => void; + /** Start treningu bez meldunku. */ + onContinue: () => void; +}) { + const { t } = useTranslation('presence'); + const [otherOpen, setOtherOpen] = useState(false); + const [selected, setSelected] = useState(''); + const [changePlan, setChangePlan] = useState(false); + + useEffect(() => { + if (open) { + setOtherOpen(false); + setSelected(''); + setChangePlan(false); + } + }, [open]); + + const mismatch = presence != null && planGym != null && presence.gymId !== planGym.id; + const pickerGyms = gyms.filter((g) => g.id !== planGym?.id); + + return ( + + {mismatch ? ( + <> +

+ {t('startModal.mismatch', { + checkedIn: presence.gymName, + planGym: planGym.name, + })} +

+
+ + + +
+ + ) : ( + <> +

+ {planGym ? t('startModal.planGym', { gym: planGym.name }) : t('startModal.noPlanGym')} +

+
+ {planGym && !otherOpen && ( + + )} + {!otherOpen && pickerGyms.length > 0 && ( + + )} + {otherOpen && ( +
+ + {planGym && ( + + )} + +
+ )} + +
+ + )} +
+ ); +} diff --git a/app/src/i18n/index.ts b/app/src/i18n/index.ts index f118d65..fa63569 100644 --- a/app/src/i18n/index.ts +++ b/app/src/i18n/index.ts @@ -19,6 +19,7 @@ import plInvitations from './locales/pl/invitations.json'; import plFeed from './locales/pl/feed.json'; import plProfile from './locales/pl/profile.json'; import plTrainees from './locales/pl/trainees.json'; +import plPresence from './locales/pl/presence.json'; import enCommon from './locales/en/common.json'; import enAuth from './locales/en/auth.json'; import enErrors from './locales/en/errors.json'; @@ -32,6 +33,7 @@ import enInvitations from './locales/en/invitations.json'; import enFeed from './locales/en/feed.json'; import enProfile from './locales/en/profile.json'; import enTrainees from './locales/en/trainees.json'; +import enPresence from './locales/en/presence.json'; export const NAMESPACES = [ 'common', @@ -47,6 +49,7 @@ export const NAMESPACES = [ 'feed', 'profile', 'trainees', + 'presence', ] as const; export type Namespace = (typeof NAMESPACES)[number]; @@ -65,6 +68,7 @@ const resources = { feed: plFeed, profile: plProfile, trainees: plTrainees, + presence: plPresence, }, en: { common: enCommon, @@ -80,6 +84,7 @@ const resources = { feed: enFeed, profile: enProfile, trainees: enTrainees, + presence: enPresence, }, } as const; diff --git a/app/src/i18n/locales/en/presence.json b/app/src/i18n/locales/en/presence.json new file mode 100644 index 0000000..5825702 --- /dev/null +++ b/app/src/i18n/locales/en/presence.json @@ -0,0 +1,64 @@ +{ + "title": "Check-in", + "intro": "Check in before your workout — your peers see the correct “now” count for this gym.", + "checkIn": "I'm working out", + "checkingIn": "Checking in…", + "checkedInHere": "You're in since {{time}}", + "checkOut": "Check out", + "stillHere": "I'm still here", + "stillHereDone": "Slot refreshed", + "activeElsewhere": "You are checked in at {{gym}}.", + "switchHere": "Switch to this gym", + "virtualNotice": "This is a virtual gym — check-in only works for real gyms.", + "notFound": "Gym not found", + "toastCheckedIn": "Checked in — have a great workout", + "toastCheckedOut": "Checked out", + "toastMoved": "Checked in at {{gym}}", + "now": "now: {{count}} person", + "now_one": "now: {{count}} person", + "now_few": "now: {{count}} people", + "now_many": "now: {{count}} people", + "now_other": "now: {{count}} people", + "full": "full", + "qr": { + "group": "QR", + "action": "QR code", + "title": "Gym QR code", + "subtitle": "Scan and check in for your workout", + "print": "Print", + "download": "Download PNG", + "copy": "Copy link", + "copied": "Link copied" + }, + "visits": { + "title": "My visits", + "empty": "No visits yet — check in from the gym's QR code or with the “I'm working out” button.", + "sourceQr": "QR", + "sourceManual": "Manual", + "duration": "{{min}} min", + "count": "{{count}} visit", + "count_one": "{{count}} visit", + "count_few": "{{count}} visits", + "count_many": "{{count}} visits", + "count_other": "{{count}} visits", + "avgStay": "Average stay", + "topGyms": "Most visited gyms", + "topEquipment": "Most used equipment", + "heatmap": "When you train (day × hour)" + }, + "startModal": { + "title": "Starting a workout at the gym", + "planGym": "Your plan points to {{gym}}.", + "noPlanGym": "Pick the gym you are starting your workout at.", + "otherGym": "I'm at a different gym", + "chooseGym": "Choose a gym", + "checkInHere": "Check me in", + "checkInPlanGym": "Check in at {{gym}}", + "changePlanGym": "Also change the plan's gym to this one", + "mismatch": "You are checked in at {{checkedIn}}, but your plan points to {{planGym}}.", + "changePlan": "Change the plan's gym to {{gym}}", + "continueAnyway": "Continue without checking in", + "continue": "Continue", + "toastPlanGymChanged": "Plan gym changed to {{gym}}" + } +} diff --git a/app/src/i18n/locales/pl/presence.json b/app/src/i18n/locales/pl/presence.json new file mode 100644 index 0000000..6a37e95 --- /dev/null +++ b/app/src/i18n/locales/pl/presence.json @@ -0,0 +1,64 @@ +{ + "title": "Meldunek", + "intro": "Zamelduj się przed treningiem — koledzy zobaczą prawidłowy licznik „teraz” na tej siłowni.", + "checkIn": "Idę ćwiczyć", + "checkingIn": "Melduję…", + "checkedInHere": "Jesteś od {{time}}", + "checkOut": "Wychodzę", + "stillHere": "Wciąż tu jestem", + "stillHereDone": "Slot odświeżony", + "activeElsewhere": "Jesteś zameldowany w siłowni {{gym}}.", + "switchHere": "Przepnij na tę siłownię", + "virtualNotice": "To wirtualna siłownia — meldunek działa tylko na realnych siłowniach.", + "notFound": "Nie znaleziono siłowni", + "toastCheckedIn": "Zameldowany — udanego treningu", + "toastCheckedOut": "Wymeldowany", + "toastMoved": "Zameldowany w {{gym}}", + "now": "teraz: {{count}} osoba", + "now_one": "teraz: {{count}} osoba", + "now_few": "teraz: {{count}} osoby", + "now_many": "teraz: {{count}} osób", + "now_other": "teraz: {{count}} osób", + "full": "pełno", + "qr": { + "group": "QR", + "action": "Kod QR", + "title": "Kod QR siłowni", + "subtitle": "Zeskanuj i melduj się na treningu", + "print": "Drukuj", + "download": "Pobierz PNG", + "copy": "Kopiuj link", + "copied": "Link skopiowany" + }, + "visits": { + "title": "Moje wizyty", + "empty": "Brak wizyt — zamelduj się z kodu QR siłowni lub przyciskiem „Idę ćwiczyć”.", + "sourceQr": "QR", + "sourceManual": "Ręcznie", + "duration": "{{min}} min", + "count": "{{count}} wizyta", + "count_one": "{{count}} wizyta", + "count_few": "{{count}} wizyty", + "count_many": "{{count}} wizyt", + "count_other": "{{count}} wizyt", + "avgStay": "Średni pobyt", + "topGyms": "Najczęściej odwiedzane siłownie", + "topEquipment": "Najczęściej używane urządzenia", + "heatmap": "Kiedy ćwiczysz (dzień × godzina)" + }, + "startModal": { + "title": "Rozpoczynam trening na siłowni", + "planGym": "Twój plan wskazuje na siłownię {{gym}}.", + "noPlanGym": "Wybierz siłownię, w której zaczynasz trening.", + "otherGym": "Jestem w innej siłowni", + "chooseGym": "Wybierz siłownię", + "checkInHere": "Melduję się", + "checkInPlanGym": "Zamelduj się w {{gym}}", + "changePlanGym": "Zmień siłownię planu na tę", + "mismatch": "Jesteś zameldowany w {{checkedIn}}, a plan wskazuje na {{planGym}}.", + "changePlan": "Zmień siłownię planu na {{gym}}", + "continueAnyway": "Kontynuuj bez meldunku", + "continue": "Kontynuuj", + "toastPlanGymChanged": "Zmieniono siłownię planu na {{gym}}" + } +} diff --git a/app/src/lib/format.ts b/app/src/lib/format.ts index 4002f48..ce46f19 100644 --- a/app/src/lib/format.ts +++ b/app/src/lib/format.ts @@ -39,6 +39,15 @@ export function fmtDateTime(iso: string | null | undefined): string { }); } +/** Sama godzina „HH:MM" (Intl wg języka; bytność: „Jesteś od 18:03"). */ +export function fmtTime(iso: string | null | undefined): string { + if (!iso) return '—'; + return new Date(iso).toLocaleTimeString(currentTag(), { + hour: '2-digit', + minute: '2-digit', + }); +} + /** Czas względny: „przed chwilą”, „5 min temu”, „wczoraj”, potem data. */ export function timeAgo(iso: string | null | undefined): string { if (!iso) return '—'; diff --git a/app/src/pages/DayExecution.tsx b/app/src/pages/DayExecution.tsx index 229fe01..faec699 100644 --- a/app/src/pages/DayExecution.tsx +++ b/app/src/pages/DayExecution.tsx @@ -7,12 +7,17 @@ import { abandonSession, addSessionExercise, addSessionSet, + checkIn, completeSession, deleteSessionSet, + presenceHeartbeat, reopenSession, setSessionExerciseState, startSession, + updatePlanGym, + useActivePresence, useExercises, + useGyms, useSession, updateSessionSet, } from '../api/queries'; @@ -24,6 +29,7 @@ import { api } from '../api/client'; import { playAlarm } from '../lib/sound'; import { useToast } from '../components/toast'; import { useTopbar } from '../topbar'; +import StartTrainingPresenceModal from '../components/presence/StartTrainingPresenceModal'; import { Badge, Button, @@ -529,6 +535,11 @@ export default function DayExecution() { const { data: exData } = useExercises(); const { push } = useToast(); const { t } = useTranslation('plans'); + const { t: tp } = useTranslation('presence'); + const { data: presenceData } = useActivePresence(); + const { data: gymsData } = useGyms(); + const presence = presenceData?.presence ?? null; + const [startModalOpen, setStartModalOpen] = useState(false); // Find session for the day via plan detail (sessions are listed on days) const [sessionId, setSessionId] = useState(null); @@ -654,6 +665,8 @@ export default function DayExecution() { date: string | null; status: string; dayOfWeek: number; + planId: string | null; + planGym: { id: string; name: string } | null; } | null>(null); useEffect(() => { @@ -669,10 +682,18 @@ export default function DayExecution() { date: string | null; status: string; dayOfWeek: number; + planId: string; + plan?: { id: string; gym: { id: string; name: string } | null } | null; sessions: { id: string; status: string; startedAt: string | null }[]; }; }>(`/days/${dayId}`); - setDayInfo({ date: data.day.date, status: data.day.status, dayOfWeek: data.day.dayOfWeek }); + setDayInfo({ + date: data.day.date, + status: data.day.status, + dayOfWeek: data.day.dayOfWeek, + planId: data.day.planId ?? null, + planGym: data.day.plan?.gym ?? null, + }); // startujemy od aktywnej; inaczej najnowsza sesja dnia — po porzuconej i // drugiej sesji sessions[0] to stara (abandonowana), która zasłaniałaby // ukończoną i blokowała „Wznów trening" @@ -704,6 +725,80 @@ export default function DayExecution() { } }; + // start przez modal meldunku: zgodny meldunek = start bez pytań, inaczej modal + const requestStart = () => { + const pg = dayInfo?.planGym ?? null; + if (presence && pg && presence.gymId === pg.id) { + void start(); + return; + } + setStartModalOpen(true); + }; + + const startFromModal = async () => { + setStartModalOpen(false); + await start(); + }; + + const startCheckIn = async (gymId: string, opts?: { alsoChangePlanGym?: boolean }) => { + try { + await checkIn(gymId, 'MANUAL'); + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['me', 'presence'] }), + queryClient.invalidateQueries({ queryKey: ['gyms'] }), + ]); + if (opts?.alsoChangePlanGym && dayInfo?.planId) { + const name = (gymsData?.gyms ?? []).find((g) => g.id === gymId)?.name ?? ''; + await updatePlanGym(dayInfo.planId, gymId); + push(tp('startModal.toastPlanGymChanged', { gym: name }), 'success'); + await queryClient.invalidateQueries({ queryKey: ['plans'] }); + } + } catch (e) { + setError(e instanceof Error ? e.message : t('exec.genericError')); + return; + } + await startFromModal(); + }; + + const startChangePlanGym = async (gymId: string) => { + if (!dayInfo?.planId) { + await startFromModal(); + return; + } + try { + const name = presence?.gymName ?? ''; + await updatePlanGym(dayInfo.planId, gymId); + push(tp('startModal.toastPlanGymChanged', { gym: name }), 'success'); + await queryClient.invalidateQueries({ queryKey: ['plans'] }); + } catch (e) { + setError(e instanceof Error ? e.message : t('exec.genericError')); + return; + } + await startFromModal(); + }; + + // trening w toku = aktywność na siłowni: odświeżaj slot bytności, gdy karta widoczna + useEffect(() => { + if (session?.status !== 'IN_PROGRESS') return; + let last = Date.now(); + const beat = () => { + if (document.visibilityState !== 'visible') return; + last = Date.now(); + presenceHeartbeat().catch(() => { + /* brak aktywnej bytności / awaria — następnym razem */ + }); + }; + const iv = setInterval(beat, 5 * 60 * 1000); + const onVis = () => { + if (document.visibilityState === 'visible' && Date.now() - last > 60 * 1000) beat(); + }; + document.addEventListener('visibilitychange', onVis); + return () => { + clearInterval(iv); + document.removeEventListener('visibilitychange', onVis); + }; + }, [session?.status]); + const complete = async () => { if (!session) return; // niezapisany bonus nie może przeżyć sesji — koniec dopiero po jego domknięciu @@ -931,7 +1026,7 @@ export default function DayExecution() { (!session || session.status !== 'IN_PROGRESS') && (

{t('exec.plannedDayHint')}

-
@@ -1051,6 +1146,20 @@ export default function DayExecution() { /> )} + + setStartModalOpen(false)} + planGym={dayInfo?.planGym ?? null} + presence={presence} + gyms={(gymsData?.gyms ?? []) + .filter((g) => g.kind === 'REAL') + .map((g) => ({ id: g.id, name: g.name }))} + busy={busy} + onCheckIn={(gymId, opts) => void startCheckIn(gymId, opts)} + onChangePlanGym={(gymId) => void startChangePlanGym(gymId)} + onContinue={() => void startFromModal()} + /> ); } diff --git a/app/src/pages/Login.tsx b/app/src/pages/Login.tsx index 01bbf8f..95678b8 100644 --- a/app/src/pages/Login.tsx +++ b/app/src/pages/Login.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Link, useNavigate } from 'react-router-dom'; +import { Link, useNavigate, useSearchParams } from 'react-router-dom'; import { useAuth } from '../store/auth'; import AuthShell from '../components/AuthShell'; import { Button, ErrorText, Field, Input } from '../components/ui'; @@ -12,6 +12,7 @@ export default function Login() { const { t } = useTranslation(); const { login } = useAuth(); const navigate = useNavigate(); + const [searchParams] = useSearchParams(); const [email, setEmail] = useState(() => localStorage.getItem(REMEMBER_KEY) ?? ''); const [password, setPassword] = useState(''); const [remember, setRemember] = useState(() => Boolean(localStorage.getItem(REMEMBER_KEY))); @@ -26,7 +27,9 @@ export default function Login() { await login(email, password); if (remember) localStorage.setItem(REMEMBER_KEY, email); else localStorage.removeItem(REMEMBER_KEY); - navigate('/'); + // deep-link QR może wymagać logowania — wracamy na stronę z ?next= + const next = searchParams.get('next'); + navigate(next && next.startsWith('/') && !next.startsWith('//') ? next : '/'); } catch (err) { setError(apiErrorMessage(err, t, t('errors:loginFailed'))); } finally { diff --git a/app/src/pages/gyms/GymCheckIn.tsx b/app/src/pages/gyms/GymCheckIn.tsx new file mode 100644 index 0000000..fa7ce56 --- /dev/null +++ b/app/src/pages/gyms/GymCheckIn.tsx @@ -0,0 +1,179 @@ +import { useState } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { useQueryClient } from '@tanstack/react-query'; +import { ArrowLeft, LogOut, MapPin, Users } from 'lucide-react'; +import { checkIn, checkOutPresence, useActivePresence, useGymDetail } from '../../api/queries'; +import { fmtTime } from '../../lib/format'; +import { Button, Card, ErrorText, Loading } from '../../components/ui'; +import { AuthImage } from '../../components/AuthImage'; +import { useToast } from '../../components/toast'; +import { useTopbar } from '../../topbar'; + +/** + * Strona deep-linku QR: /gyms/:id/checkin. Meldunek NIGDY nie dzieje się sam + * — użytkownik klika „Idę ćwiczyć" (tryb MANUAL) albo „Przepnij na tę siłownię". + */ +export default function GymCheckIn() { + const { id } = useParams(); + const { t } = useTranslation('presence'); + const { push } = useToast(); + const queryClient = useQueryClient(); + const { data, isLoading, error } = useGymDetail(id); + const { data: presenceData, isLoading: presenceLoading } = useActivePresence(); + const [busy, setBusy] = useState(false); + + const gym = data?.gym; + const presence = presenceData?.presence ?? null; + + useTopbar({ title: gym?.name ?? t('title'), back: gym ? `/gyms/${gym.id}` : '/gyms' }); + + const invalidateAll = async () => { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['me', 'presence'] }), + queryClient.invalidateQueries({ queryKey: ['gyms'] }), + queryClient.invalidateQueries({ queryKey: ['gym', id] }), + ]); + }; + + const doCheckIn = async () => { + if (!gym) return; + setBusy(true); + try { + await checkIn(gym.id, 'MANUAL'); + await invalidateAll(); + push(t('toastCheckedIn'), 'success'); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setBusy(false); + } + }; + + const doSwitch = async () => { + if (!gym) return; + setBusy(true); + try { + await checkIn(gym.id, 'MANUAL'); + await invalidateAll(); + push(t('toastMoved', { gym: gym.name }), 'success'); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setBusy(false); + } + }; + + const doCheckOut = async () => { + setBusy(true); + try { + await checkOutPresence(); + await invalidateAll(); + push(t('toastCheckedOut'), 'info'); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setBusy(false); + } + }; + + if (isLoading || presenceLoading) return ; + if (error || !gym) { + return ( + <> + + + {t('common:back')} + + {t('notFound')} + + ); + } + + const checkedInHere = presence != null && presence.gymId === gym.id; + const elsewhere = presence != null && presence.gymId !== gym.id; + const isReal = gym.kind === 'REAL'; + + return ( +
+ +
+ {gym.coverPhoto ? ( + + ) : ( + + ); +} diff --git a/app/src/pages/gyms/GymDetail.tsx b/app/src/pages/gyms/GymDetail.tsx index 6320bc5..197883e 100644 --- a/app/src/pages/gyms/GymDetail.tsx +++ b/app/src/pages/gyms/GymDetail.tsx @@ -9,16 +9,21 @@ import { Megaphone, MapPin, Pencil, + QrCode, UserPlus, Users, Wrench, } from 'lucide-react'; import { + checkIn, + checkOutPresence, createGymAnnouncement, createGymException, deleteGym, deleteGymAnnouncement, deleteGymException, + presenceHeartbeat, + useActivePresence, useGymAnnouncements, useGymDetail, useGymExceptions, @@ -53,6 +58,7 @@ import { normalizeAvailability, TIME_SLOTS, dayFull } from '../../lib/availabili import ClaimModal from '../../components/gyms/ClaimModal'; import InviteGymModal from '../../components/gyms/InviteGymModal'; import GymGallery from '../../components/gyms/GymGallery'; +import GymQrModal from '../../components/gyms/GymQrModal'; import { EquipmentSection, GymEditForm } from './GymSections'; /* Lista godzin otwarcia: wiersz na dzień (czytelna w wąskiej kolumnie), „dziś” wyróżnione. */ @@ -381,9 +387,12 @@ export default function GymDetail() { const queryClient = useQueryClient(); const { push } = useToast(); const { t } = useTranslation('gyms'); + const { t: tp } = useTranslation('presence'); const { data, isLoading, error } = useGymDetail(id); const { data: claimsData } = useMyGymClaims(); + const { data: presenceData } = useActivePresence(); const gym = data?.gym; + const presence = presenceData?.presence ?? null; const canManage = (data?.isAdmin ?? false) || (data?.roles ?? []).includes('OWNER'); const isOwner = (data?.roles ?? []).includes('OWNER'); const claim = (claimsData?.claims ?? []).find((c) => c.gymId === id) ?? null; @@ -398,6 +407,55 @@ export default function GymDetail() { const [galleryOpen, setGalleryOpen] = useState(false); const [equipmentOpen, setEquipmentOpen] = useState(false); const [announcementsOpen, setAnnouncementsOpen] = useState(false); + const [qrOpen, setQrOpen] = useState(false); + const [presenceBusy, setPresenceBusy] = useState(false); + + const invalidatePresence = async () => { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['me', 'presence'] }), + queryClient.invalidateQueries({ queryKey: ['gyms'] }), + queryClient.invalidateQueries({ queryKey: ['gym', id] }), + ]); + }; + + const doCheckIn = async () => { + if (!gym) return; + setPresenceBusy(true); + try { + await checkIn(gym.id, 'MANUAL'); + await invalidatePresence(); + push(tp('toastCheckedIn'), 'success'); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setPresenceBusy(false); + } + }; + + const doCheckOut = async () => { + setPresenceBusy(true); + try { + await checkOutPresence(); + await invalidatePresence(); + push(tp('toastCheckedOut'), 'info'); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setPresenceBusy(false); + } + }; + + const doStillHere = async () => { + setPresenceBusy(true); + try { + await presenceHeartbeat(); + push(tp('stillHereDone'), 'info'); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setPresenceBusy(false); + } + }; const remove = async () => { if (!gym) return; @@ -453,6 +511,16 @@ export default function GymDetail() { } as TopbarCustomGroup, ] : []), + ...(gym.kind === 'REAL' + ? [ + { + id: 'qr', + label: tp('qr.group'), + icon: QrCode, + actions: [{ label: tp('qr.action'), onClick: () => setQrOpen(true) }], + } as TopbarCustomGroup, + ] + : []), { id: 'equipment', label: t('detail.groupEquipment'), @@ -511,7 +579,41 @@ export default function GymDetail() { ] : undefined; - useTopbar({ title: t('nav:gyms'), back: '/gyms', groups, actions: ownerActions }); + // Meldunek bytności (REAL) — akcje dla każdego użytkownika siłowni. + const presenceActions: TopbarAction[] | undefined = + gym && gym.kind === 'REAL' + ? presence && presence.gymId === gym.id + ? [ + { + label: tp('stillHere'), + variant: 'secondary', + disabled: presenceBusy, + onClick: () => void doStillHere(), + }, + { + label: tp('checkOut'), + variant: 'secondary', + disabled: presenceBusy, + onClick: () => void doCheckOut(), + }, + ] + : [ + { + label: tp('checkIn'), + variant: 'secondary', + disabled: presenceBusy, + onClick: () => void doCheckIn(), + }, + ] + : undefined; + + const topActions = [...(presenceActions ?? []), ...(ownerActions ?? [])]; + useTopbar({ + title: t('nav:gyms'), + back: '/gyms', + groups, + actions: topActions.length > 0 ? topActions : undefined, + }); if (isLoading) return ; if (error || !gym) { @@ -575,6 +677,22 @@ export default function GymDetail() { {gym.capacity != null ? t('detail.places', { count: gym.capacity }) : '—'} + {gym.kind === 'REAL' && gym.currentOccupancy != null && ( + = gym.capacity + ? 'bg-danger/75' + : 'bg-white/14' + }`} + > + + )} {t('common:counters.devices', { count: gym.equipment.length })} @@ -716,6 +834,14 @@ export default function GymDetail() { > + {gym.kind === 'REAL' && isOwner && ( + setQrOpen(false)} + gymId={gym.id} + gymName={gym.name} + /> + )} {gym.kind === 'VIRTUAL' && ( )} + + + + ); +} + +/* Sekcja bytności: lista wizyt + skróty (najczęstsze siłownie/urządzenia) + heatmapa dzień×godzina. */ +function PresenceVisits() { + const { t, i18n } = useTranslation('presence'); + const { data: histData, isLoading } = usePresenceHistory(); + const { data: statsData } = usePresenceStats(); + const visits = histData?.visits ?? []; + const stats = statsData?.stats; + + if (isLoading) { + return ( + + + + + ); + } + + const peak = stats?.peak ?? 0; + + return ( + + 0 && stats + ? `${t('visits.count', { count: stats.visits })} · ${t('visits.avgStay')}: ${ + stats.avgStayMinutes ?? 0 + } min` + : undefined + } + /> + {visits.length === 0 ? ( +

{t('visits.empty')}

+ ) : ( +
+
+ {visits.slice(0, 12).map((v) => ( +
+ + {fmtDate(v.checkedInAt)} + + {v.gymName} + + {fmtTime(v.checkedInAt)}–{fmtTime(v.closedAt ?? v.lastActivityAt)} + + + {t('visits.duration', { min: v.durationMinutes })} + + + {v.source === 'QR' ? t('visits.sourceQr') : t('visits.sourceManual')} + +
+ ))} +
+ + {stats && stats.heatmap.length > 0 && ( +
+
+ {t('visits.heatmap')} +
+
+ {Array.from({ length: 7 }, (_, day) => ( + + ))} +
+
+ )} + + {stats && stats.topGyms.length > 0 && ( +
+
+ {t('visits.topGyms')} +
+
+ {stats.topGyms.map((g) => ( + + {g.gymName} · {g.visits} + + ))} +
+
+ )} + + {stats && stats.topEquipment.length > 0 && ( +
+
+ {t('visits.topEquipment')} +
+
+ {stats.topEquipment.map((e) => ( + + {localizedName(e, i18n.language)} · {e.count} + + ))} +
+
+ )} +
+ )} +
+ ); +} + +/* Wiersz heatmapy: etykieta dnia + 24 kafle godziny (kolor ~ natężenie). */ +function FragmentRow({ + day, + stats, + peak, +}: { + day: number; + stats: { heatmap: { day: number; hour: number; count: number }[] }; + peak: number; +}) { + return ( + <> + + {dayName(day + 1).slice(0, 2)} + + {Array.from({ length: 24 }, (_, hour) => { + const cell = stats.heatmap.find((h) => h.day === day && h.hour === hour); + const intensity = cell && peak > 0 ? cell.count / peak : 0; + return ( + 0 + ? `color-mix(in srgb, var(--accent) ${Math.round(18 + intensity * 82)}%, var(--bg-input))` + : 'var(--bg-input)', + }} + /> + ); + })} ); } diff --git a/app/src/styles.css b/app/src/styles.css index 745e101..d88f0c0 100644 --- a/app/src/styles.css +++ b/app/src/styles.css @@ -375,3 +375,20 @@ input[type='checkbox']:disabled { opacity: 0.5; cursor: default; } + +/* Druk kodu QR siłowni: na wydruku tylko obszar QR (reszta strony niewidoczna). */ +@media print { + body * { + visibility: hidden; + } + .print-qr, + .print-qr * { + visibility: visible; + } + .print-qr { + position: fixed; + inset: 0; + margin: 0; + background: #fff; + } +} diff --git a/app/test/e2e/mock-api.ts b/app/test/e2e/mock-api.ts index 66efde6..dcb903f 100644 --- a/app/test/e2e/mock-api.ts +++ b/app/test/e2e/mock-api.ts @@ -904,6 +904,12 @@ export interface MockApiOptions { bodyParameters?: unknown; /** Wpisy feedu GET /me/feed (domyślnie: pusty; stateful: oznaczanie przeczytania). */ feed?: { items: { source: string; id: string; read?: boolean }[] }; + /** Aktywna bytność GET /me/presence (domyślnie: brak; stateful: POST check-in aktualizuje). */ + presence?: unknown; + /** Wpisy GET /me/presence/history (domyślnie: []; check-in zamyka aktywną jako wizytę). */ + presenceHistory?: unknown; + /** Ciało GET /me/presence/stats (domyślnie: puste statystyki). */ + presenceStats?: unknown; } /** @@ -931,8 +937,59 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { history, bodyParameters, feed, + presence, + presenceHistory, + presenceStats, } = opts; + // Stateful: bytność (check-in) — aktywna obecność + zamknięte wizyty; occupancy liczy się z niej. + interface MockPresenceVisit { + id: string; + gymId: string; + gymName: string; + status: string; + source: string; + checkedInAt: string; + lastActivityAt: string; + closedAt: string | null; + durationMinutes: number; + } + const GYM_PRESENCE_INFO: Record = { + 'gym-1': { name: 'Żelazna Świątynia', capacity: 50 }, + 'gym-2': { name: 'Mega Gym', capacity: null }, + }; + let activePresence: MockPresenceVisit | null = (presence ?? null) as MockPresenceVisit | null; + const presenceVisits: MockPresenceVisit[] = JSON.parse( + JSON.stringify(presenceHistory ?? []), + ) as MockPresenceVisit[]; + const closeActivePresence = () => { + if (!activePresence) return; + const closedAt = new Date().toISOString(); + presenceVisits.unshift({ + ...activePresence, + status: 'CLOSED', + closedAt, + durationMinutes: Math.max( + 1, + Math.round((Date.now() - new Date(activePresence.checkedInAt).getTime()) / 60000), + ), + }); + activePresence = null; + }; + const occupancyOf = (gymId: string) => (activePresence?.gymId === gymId ? 1 : 0); + const withOccupancy = (body: unknown) => { + if (!body || typeof body !== 'object') return body; + const b = body as { gyms?: { kind?: string; id: string }[] }; + if (!Array.isArray(b.gyms)) return body; + return { + ...b, + gyms: b.gyms.map((g) => ({ + ...g, + currentOccupancy: g.kind === 'REAL' ? occupancyOf(g.id) : null, + })), + }; + }; + // Stateful: equipment added via POST /gyms/:id/equipment persists on refetch. // Instancje (GymEquipment.id) — powtórne dodanie typu = NOWA instancja. const ownedGymEquipment = TEST_GYM_OWNED.equipment.map((e) => ({ @@ -981,7 +1038,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { photos.length ? `/gyms/gym-1/photos/${photos[0].id}` : null; const gymDetailBody = () => JSON.stringify({ - gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment, photos: [...gymPhotosState], coverPhoto: coverOf(gymPhotosState) }, + gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment, photos: [...gymPhotosState], coverPhoto: coverOf(gymPhotosState), currentOccupancy: occupancyOf('gym-1') }, roles: ['OWNER', 'TRAINER'], isAdmin: false, }); @@ -1213,7 +1270,9 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { return route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify(myGymsBody), + body: JSON.stringify( + withOccupancy(myGymsBody), + ), }); }); @@ -1268,10 +1327,19 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { if (req.method() === 'DELETE') { return route.fulfill({ status: 204 }); } + // GET — dla gym-2 oddaję dołączalną Mega Gym (deep-link check-in testuje inną siłownię) + const segId = req.url().match(/gyms\/([^/?]+)/)?.[1] ?? ''; + if (segId === TEST_GYM_JOINABLE.id) { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ gym: { ...TEST_GYM_JOINABLE, currentOccupancy: occupancyOf(TEST_GYM_JOINABLE.id) }, roles: [], isAdmin: false }), + }); + } return route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment } }), + body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment, currentOccupancy: occupancyOf('gym-1') } }), }); }); @@ -1711,6 +1779,76 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { body: JSON.stringify(TEST_MY_EXERCISE_PROGRESS), }), ); + + // ---------- bytność (check-in, QR, occupancy) ---------- + page.route('**/api/v1/gyms/*/check-in', (route) => { + const req = route.request(); + if (req.method() !== 'POST') return route.fallback(); + const gymId = req.url().match(/gyms\/([^/]+)\/check-in/)?.[1] ?? ''; + const info = GYM_PRESENCE_INFO[gymId] ?? { name: gymId, capacity: null }; + const src = (req.postDataJSON() as { source?: string } | null)?.source ?? 'MANUAL'; + if (activePresence && activePresence.gymId === gymId) { + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }) }); + } + closeActivePresence(); + const now = new Date().toISOString(); + activePresence = { + id: 'presence-1', + gymId, + gymName: info.name, + gymCapacity: info.capacity, + status: 'ACTIVE', + source: src, + checkedInAt: now, + lastActivityAt: now, + closedAt: null, + durationMinutes: 0, + }; + return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }) }); + }); + + page.route('**/api/v1/me/presence/check-out', (route) => { + closeActivePresence(); + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ checkedOut: true }) }); + }); + + page.route('**/api/v1/me/presence/heartbeat', (route) => + route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ touched: activePresence != null }) }), + ); + + page.route('**/api/v1/me/presence/history*', (route) => + route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ visits: presenceVisits }) }), + ); + + page.route('**/api/v1/me/presence/stats', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify( + presenceStats ?? { + stats: { visits: presenceVisits.length, avgStayMinutes: null, heatmap: [], topGyms: [], peak: 0, topEquipment: [] }, + }, + ), + }), + ); + + page.route('**/api/v1/me/presence', (route) => + route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }) }), + ); + + // zmiana siłowni planu (modal rozpoczęcia treningu) + page.route('**/api/v1/plans/*/gym', (route) => { + const req = route.request(); + if (req.method() !== 'PATCH') return route.fallback(); + const planId = req.url().match(/plans\/([^/]+)\/gym/)?.[1] ?? ''; + const gymId = (req.postDataJSON() as { gymId?: string | null } | null)?.gymId ?? null; + const info = gymId ? GYM_PRESENCE_INFO[gymId] ?? { name: gymId } : null; + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ plan: { id: planId, gym: gymId ? { id: gymId, name: info!.name } : null } }), + }); + }); } /** diff --git a/app/test/e2e/presence.spec.ts b/app/test/e2e/presence.spec.ts new file mode 100644 index 0000000..5b2f970 --- /dev/null +++ b/app/test/e2e/presence.spec.ts @@ -0,0 +1,250 @@ +import { test, expect, type Page } from './fixtures'; +import { mockApi, TEST_DAY, TEST_SESSION, TEST_USER } from './mock-api'; + +/* Bytność na siłowni: QR check-in, live occupancy, modal rozpoczęcia treningu, historia wizyt. */ + +const GYM1_PRESENCE = { + id: 'presence-1', + gymId: 'gym-1', + gymName: 'Żelazna Świątynia', + gymCapacity: 50, + status: 'ACTIVE', + source: 'MANUAL', + checkedInAt: '2026-10-23T17:05:00.000Z', + lastActivityAt: '2026-10-23T17:05:00.000Z', + closedAt: null, +}; + +const GYM2_PRESENCE = { + ...GYM1_PRESENCE, + gymId: 'gym-2', + gymName: 'Mega Gym', + gymCapacity: null, +}; + +async function login(page: Page) { + await page.goto('/login'); + await page.locator('input[type="email"]').fill('test@fitos.pl'); + await page.locator('input[type="password"]').fill('haslo123'); + await page.getByRole('button', { name: 'Zaloguj' }).click(); + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); +} + +async function openGymDetail(page: Page) { + await page.getByRole('link', { name: 'Siłownie' }).click(); + await page.getByRole('link', { name: 'Żelazna Świątynia' }).click(); +} + +/* Dzień PLANNED bez sesji + uruchamianie sesji — do testów modala rozpoczęcia. */ +function mockStartableDay(page: Page, planGym: { id: string; name: string } | null, opts = {}) { + mockApi(page, opts); + page.route('**/api/v1/days/day-1', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + day: { + ...TEST_DAY, + status: 'PLANNED', + sessions: [], + planId: 'plan-1', + plan: { id: 'plan-1', gym: planGym }, + }, + }), + }), + ); + page.route('**/api/v1/days/day-1/sessions', (route) => { + if (route.request().method() !== 'POST') return route.fallback(); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ sessionId: 'sess-new' }), + }); + }); + page.route('**/api/v1/sessions/sess-new', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ session: { ...TEST_SESSION, id: 'sess-new' } }), + }), + ); +} + +test('meldunek i wymeldowanie z menu kontekstowego siłowni + licznik „teraz”', async ({ page }) => { + mockApi(page); + await login(page); + await openGymDetail(page); + + // badge live-occupancy w hero (REAL; 0 aktywne bytności) + await expect(page.getByText('teraz: 0 osób')).toBeVisible(); + + // akcja „Idę ćwiczyć” w topbarze + await page.getByRole('button', { name: 'Idę ćwiczyć' }).click(); + await expect(page.getByText('Zameldowany — udanego treningu')).toBeVisible(); + + // po meldunku: akcje „Wciąż tu jestem” + „Wychodzę”, licznik rośnie + await expect(page.getByRole('button', { name: 'Wychodzę' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Wciąż tu jestem' })).toBeVisible(); + await expect(page.getByText('teraz: 1 osoba')).toBeVisible(); + + await page.getByRole('button', { name: 'Wychodzę' }).click(); + await expect(page.getByText('Wymeldowany')).toBeVisible(); + await expect(page.getByRole('button', { name: 'Idę ćwiczyć' })).toBeVisible(); +}); + +test('modal kodu QR właściciela pokazuje kod i link do strony check-inu', async ({ page }) => { + mockApi(page); + await login(page); + await openGymDetail(page); + + // akcja „Kod QR” grupy „QR” w menu kontekstowym (desktop = inline; tylko REAL + OWNER) + await page.getByRole('button', { name: 'Kod QR' }).click(); + + const dialog = page.getByRole('dialog'); + await expect(dialog.getByText('Kod QR siłowni')).toBeVisible(); + await expect(dialog.getByRole('img', { name: 'Żelazna Świątynia' })).toBeVisible(); + await expect(dialog.getByText(/\/gyms\/gym-1\/checkin/)).toBeVisible(); +}); + +test('strona deep-linku QR: meldunek, status „jesteś od”, wymeldowanie', async ({ page }) => { + mockApi(page); + await login(page); + // init() przy przeładowaniu wywołuje /auth/refresh — mock musi oddać token, + // żeby goto('/gyms/gym-1/checkin') utrzymało sesję (rejestrujemy PO logowaniu, + // inaczej /login od razu redirectowałby na dashboard) + page.route('**/api/v1/auth/refresh', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ accessToken: 'test-access-token', user: TEST_USER }), + }), + ); + await page.goto('/gyms/gym-1/checkin'); + + // stan: brak meldunku → CTA „Idę ćwiczyć” + await expect(page.getByRole('button', { name: 'Idę ćwiczyć' })).toBeVisible(); + await page.getByRole('button', { name: 'Idę ćwiczyć' }).click(); + + // stan: meldunek w tej siłowni → „Jesteś od …” + „Wychodzę” + await expect(page.getByText(/Jesteś od/)).toBeVisible(); + await page.getByRole('button', { name: 'Wychodzę' }).click(); + await expect(page.getByText('Wymeldowany')).toBeVisible(); +}); + +test('strona deep-linku QR innej siłowni: „Jesteś zameldowany …” + przepięcie', async ({ page }) => { + mockApi(page, { presence: GYM1_PRESENCE }); + await login(page); + page.route('**/api/v1/auth/refresh', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ accessToken: 'test-access-token', user: TEST_USER }), + }), + ); + await page.goto('/gyms/gym-2/checkin'); + + await expect(page.getByText('Jesteś zameldowany w siłowni Żelazna Świątynia.')).toBeVisible(); + await page.getByRole('button', { name: 'Przepnij na tę siłownię' }).click(); + await expect(page.getByText('Zameldowany w Mega Gym')).toBeVisible(); + await expect(page.getByText(/Jesteś od/)).toBeVisible(); +}); + +test('start treningu bez meldunku: modal z opcją „Kontynuuj bez meldunku”', async ({ page }) => { + mockStartableDay(page, { id: 'gym-1', name: 'Żelazna Świątynia' }); + await login(page); + await page.getByRole('button', { name: 'Wykonaj trening' }).click(); + + const started = page.waitForRequest((r) => r.url().includes('/days/day-1/sessions')); + await page.getByRole('button', { name: 'Rozpocznij sesję' }).click(); + + const dialog = page.getByRole('dialog'); + await expect(dialog.getByText('Rozpoczynam trening na siłowni')).toBeVisible(); + await expect(dialog.getByText('Twój plan wskazuje na siłownię Żelazna Świątynia.')).toBeVisible(); + + await dialog.getByRole('button', { name: 'Kontynuuj bez meldunku' }).click(); + await started; + await expect(page.getByRole('button', { name: 'Ukończ sesję' })).toBeVisible(); +}); + +test('start treningu: meldunek w siłowni planu z modala i start', async ({ page }) => { + mockStartableDay(page, { id: 'gym-1', name: 'Żelazna Świątynia' }); + await login(page); + await page.getByRole('button', { name: 'Wykonaj trening' }).click(); + + const checkIn = page.waitForRequest( + (r) => r.url().includes('/gyms/gym-1/check-in') && r.method() === 'POST', + ); + await page.getByRole('button', { name: 'Rozpocznij sesję' }).click(); + await page.getByRole('dialog').getByRole('button', { name: 'Melduję się' }).click(); + await checkIn; + + await expect(page.getByRole('button', { name: 'Ukończ sesję' })).toBeVisible(); +}); + +test('start treningu z poprawnym meldunkiem: bez modala, od razu sesja', async ({ page }) => { + mockStartableDay(page, { id: 'gym-1', name: 'Żelazna Świątynia' }, { presence: GYM1_PRESENCE }); + await login(page); + await page.getByRole('button', { name: 'Wykonaj trening' }).click(); + + await page.getByRole('button', { name: 'Rozpocznij sesję' }).click(); + await expect(page.getByText('Rozpoczynam trening na siłowni')).toHaveCount(0); + await expect(page.getByRole('button', { name: 'Ukończ sesję' })).toBeVisible(); +}); + +test('mismatch meldunku z planem: zmiana siłowni planu i start', async ({ page }) => { + mockStartableDay(page, { id: 'gym-1', name: 'Żelazna Świątynia' }, { presence: GYM2_PRESENCE }); + await login(page); + await page.getByRole('button', { name: 'Wykonaj trening' }).click(); + + await page.getByRole('button', { name: 'Rozpocznij sesję' }).click(); + const dialog = page.getByRole('dialog'); + await expect( + dialog.getByText('Jesteś zameldowany w Mega Gym, a plan wskazuje na Żelazna Świątynia.'), + ).toBeVisible(); + + const patch = page.waitForRequest( + (r) => r.url().includes('/plans/plan-1/gym') && r.method() === 'PATCH', + ); + await dialog.getByRole('button', { name: 'Zmień siłownię planu na Mega Gym' }).click(); + await patch; + + await expect(page.getByText('Zmieniono siłownię planu na Mega Gym')).toBeVisible(); + await expect(page.getByRole('button', { name: 'Ukończ sesję' })).toBeVisible(); +}); + +test('profil → historia treningów: sekcja „Moje wizyty” z listą wizyt', async ({ page }) => { + mockApi(page, { + presenceHistory: [ + { + id: 'visit-1', + gymId: 'gym-1', + gymName: 'Żelazna Świątynia', + status: 'CLOSED', + source: 'QR', + checkedInAt: '2026-10-20T17:00:00.000Z', + lastActivityAt: '2026-10-20T18:15:00.000Z', + closedAt: '2026-10-20T18:15:00.000Z', + durationMinutes: 75, + }, + ], + presenceStats: { + stats: { + visits: 1, + avgStayMinutes: 75, + heatmap: [{ day: 1, hour: 18, count: 1 }], + topGyms: [{ gymId: 'gym-1', gymName: 'Żelazna Świątynia', visits: 1 }], + peak: 1, + topEquipment: [{ equipmentId: 'eq-1', name: 'Sztanga', nameEn: null, count: 1 }], + }, + }, + }); + await login(page); + await page.getByRole('link', { name: 'Profil' }).click(); + await page.getByRole('link', { name: /Historia treningów/ }).click(); + await expect(page.getByRole('heading', { name: 'Historia treningów', level: 2 })).toBeVisible(); + + await expect(page.getByRole('heading', { name: 'Moje wizyty' })).toBeVisible(); + await expect(page.getByText('Żelazna Świątynia', { exact: true }).first()).toBeVisible(); + await expect(page.getByText('75 min', { exact: true })).toBeVisible(); + await expect(page.getByText('QR', { exact: true })).toBeVisible(); +}); diff --git a/app/test/presence.test.tsx b/app/test/presence.test.tsx new file mode 100644 index 0000000..b8a5b51 --- /dev/null +++ b/app/test/presence.test.tsx @@ -0,0 +1,285 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter } from 'react-router-dom'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import App from '../src/App'; +import { useAuth } from '../src/store/auth'; +import { setAccessToken } from '../src/api/client'; +import type { ActivePresence, User } from '../src/api/types'; +import GymQrModal from '../src/components/gyms/GymQrModal'; +import StartTrainingPresenceModal from '../src/components/presence/StartTrainingPresenceModal'; + +// QR generowany przez stub — w jsdom canvas może być niedostępny +vi.mock('qrcode', () => ({ + toDataURL: vi.fn(async () => 'data:image/png;base64,MOCK'), +})); + +const USER: User = { + id: 'u1', + email: 'jan@test.local', + firstName: 'Jan', + lastName: 'Kowalski', + age: 30, + heightCm: 180, + phone: null, + isAdmin: false, + availability: null, + priorities: null, + exclusions: null, + developMuscles: [], + canDoMuscles: [], + difficultMuscles: [], + avoidMuscles: [], + createdAt: '2026-08-22T10:00:00.000Z', +}; + +function jsonResponse(status: number, body: unknown) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function presence(gymId: string, gymName: string): ActivePresence { + return { + id: 'p1', + gymId, + gymName, + gymCapacity: 50, + status: 'ACTIVE', + source: 'MANUAL', + checkedInAt: '2026-10-23T16:00:00.000Z', + lastActivityAt: '2026-10-23T16:00:00.000Z', + closedAt: null, + }; +} + +function gymBody(kind: 'REAL' | 'VIRTUAL' = 'REAL') { + return { + gym: { + id: 'gym-1', + name: 'Żelazna Świątynia', + location: 'Warszawa', + availability: null, + capacity: 50, + kind, + isPrivate: false, + equipment: [], + coverPhoto: null, + photos: [], + currentOccupancy: kind === 'REAL' ? 3 : null, + }, + roles: ['MEMBER'], + isAdmin: false, + }; +} + +interface StubOpts { + presence?: ActivePresence | null; + gymKind?: 'REAL' | 'VIRTUAL'; +} + +function mockApi(opts: StubOpts = {}) { + let current = opts.presence ?? null; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + const method = init?.method || 'GET'; + if (url.includes('/auth/refresh')) + return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } }); + if (url.includes('/auth/login')) + return jsonResponse(200, { user: USER, accessToken: 'tok-1' }); + if (url.includes('/me/presence/history')) return jsonResponse(200, { visits: [] }); + if (url.includes('/me/presence/stats')) + return jsonResponse(200, { + stats: { visits: 0, avgStayMinutes: null, heatmap: [], topGyms: [], peak: 0, topEquipment: [] }, + }); + if (url.includes('/me/presence/check-out') && method === 'POST') { + current = null; + return jsonResponse(200, { checkedOut: true }); + } + if (url.includes('/me/presence/heartbeat') && method === 'POST') + return jsonResponse(200, { touched: current != null }); + if (url.includes('/me/presence')) return jsonResponse(200, { presence: current }); + if (url.includes('/gyms/gym-1/check-in') && method === 'POST') { + current = presence('gym-1', 'Żelazna Świątynia'); + return jsonResponse(201, { presence: current }); + } + if (url.includes('/gyms/gym-1')) return jsonResponse(200, gymBody(opts.gymKind ?? 'REAL')); + if (url.includes('/me/active-session')) return jsonResponse(200, { session: null }); + if (url.includes('/me/feed/unread-count')) return jsonResponse(200, { count: 0 }); + if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] }); + if (url.includes('/gyms/invitations')) return jsonResponse(200, { invitations: [] }); + if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] }); + if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] }); + if (url.includes('/dashboard')) + return jsonResponse(200, { + killstreak: 0, + activePlan: null, + nextTraining: null, + progress: null, + }); + return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } }); + }), + ); +} + +// logowanie przez formularz z powrotem na stronę z ?next= (deep-link QR) +async function loginTo(tester: ReturnType, next: string) { + expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument(); + const email = document.querySelector('input[type="email"]') as HTMLInputElement; + const password = document.querySelector('input[type="password"]') as HTMLInputElement; + await tester.type(email, 'jan@test.local'); + await tester.type(password, 'Password123!'); + await tester.click(screen.getByRole('button', { name: 'Zaloguj' })); + if (next.includes('checkin')) { + // treść strony = karta siłowni (h2 z nazwą); topbar w unitach nie jest źródłem asercji + expect( + await screen.findByRole('heading', { name: 'Żelazna Świątynia', level: 2 }), + ).toBeInTheDocument(); + } else { + expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument(); + } +} + +function renderAt(path: string) { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } }, + }); + render( + + + + + , + ); +} + +function renderIsolated(ui: React.ReactElement) { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } }, + }); + render( + + {ui} + , + ); +} + +beforeEach(() => { + setAccessToken(null); + localStorage.clear(); + useAuth.setState({ user: null, ready: false }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Strona check-inu (deep-link QR)', () => { + it('bez meldunku: CTA „Idę ćwiczyć” → stan zameldowany', async () => { + mockApi({ presence: null }); + const tester = userEvent.setup(); + renderAt(`/login?next=${encodeURIComponent('/gyms/gym-1/checkin')}`); + await loginTo(tester, '/gyms/gym-1/checkin'); + + expect(await screen.findByText(/Zamelduj się przed treningiem/)).toBeInTheDocument(); + await tester.click(screen.getByRole('button', { name: 'Idę ćwiczyć' })); + + expect(await screen.findByText('Zameldowany — udanego treningu')).toBeInTheDocument(); + expect(await screen.findByRole('button', { name: 'Wychodzę' })).toBeInTheDocument(); + }); + + it('meldunek w innej siłowni: komunikat + „Przepnij na tę siłownię”', async () => { + mockApi({ presence: presence('gym-9', 'Inna Siłownia') }); + const tester = userEvent.setup(); + renderAt(`/login?next=${encodeURIComponent('/gyms/gym-1/checkin')}`); + await loginTo(tester, '/gyms/gym-1/checkin'); + + expect( + await screen.findByText('Jesteś zameldowany w siłowni Inna Siłownia.'), + ).toBeInTheDocument(); + await tester.click(screen.getByRole('button', { name: 'Przepnij na tę siłownię' })); + expect(await screen.findByText('Zameldowany w Żelazna Świątynia')).toBeInTheDocument(); + }); + + it('siłownia wirtualna: brak meldunku — komunikat', async () => { + mockApi({ presence: null, gymKind: 'VIRTUAL' }); + const tester = userEvent.setup(); + renderAt(`/login?next=${encodeURIComponent('/gyms/gym-1/checkin')}`); + await loginTo(tester, '/gyms/gym-1/checkin'); + + expect(await screen.findByText(/To wirtualna siłownia/)).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Idę ćwiczyć' })).not.toBeInTheDocument(); + }); +}); + +describe('Modal kodu QR', () => { + it('renderuje wygenerowany obraz QR', async () => { + renderIsolated( + undefined} gymId="gym-1" gymName="Żelazna Świątynia" />, + ); + expect(await screen.findByRole('img', { name: 'Żelazna Świątynia' })).toBeInTheDocument(); + }); +}); + +describe('Modal rozpoczęcia treningu', () => { + it('mismatch: oferuje zmianę siłowni planu na siłownię meldunku', async () => { + const onChangePlanGym = vi.fn(); + renderIsolated( + undefined} + planGym={{ id: 'gym-1', name: 'Żelazna Świątynia' }} + presence={presence('gym-2', 'Mega Gym')} + gyms={[]} + onCheckIn={vi.fn()} + onChangePlanGym={onChangePlanGym} + onContinue={vi.fn()} + />, + ); + const tester = userEvent.setup(); + await tester.click(await screen.findByRole('button', { name: 'Zmień siłownię planu na Mega Gym' })); + expect(onChangePlanGym).toHaveBeenCalledWith('gym-2'); + }); + + it('brak meldunku: „Melduję się” melduje w siłowni planu', async () => { + const onCheckIn = vi.fn(); + renderIsolated( + undefined} + planGym={{ id: 'gym-1', name: 'Żelazna Świątynia' }} + presence={null} + gyms={[]} + onCheckIn={onCheckIn} + onChangePlanGym={vi.fn()} + onContinue={vi.fn()} + />, + ); + const tester = userEvent.setup(); + await tester.click(await screen.findByRole('button', { name: 'Melduję się' })); + expect(onCheckIn).toHaveBeenCalledWith('gym-1'); + }); + + it('brak meldunku: „Kontynuuj bez meldunku” startuje bez meldunku', async () => { + const onContinue = vi.fn(); + renderIsolated( + undefined} + planGym={{ id: 'gym-1', name: 'Żelazna Świątynia' }} + presence={null} + gyms={[]} + onCheckIn={vi.fn()} + onChangePlanGym={vi.fn()} + onContinue={onContinue} + />, + ); + const tester = userEvent.setup(); + await tester.click(await screen.findByRole('button', { name: 'Kontynuuj bez meldunku' })); + expect(onContinue).toHaveBeenCalled(); + }); +});