From a797729dd081531593630c8f117a5e22b5356e6a Mon Sep 17 00:00:00 2001 From: Sebastian G Date: Thu, 3 Sep 2026 11:10:58 +0200 Subject: [PATCH] feat(checkin): gym membership QR check-in (mobile-only) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a mobile-only gym check-in screen: saved membership codes shown as QR codes in a swipeable carousel, reached from a 'Check in' card on Home. Cards are added by typing the code, importing a photo, or scanning with the camera. Only the code value + symbology are stored — never a photo; the QR is regenerated from the value on every display. Rendering uses lean-qr (MIT); camera scan and photo decode use @capacitor-mlkit/barcode-scanning (Apache-2.0), pinned to the 7.x line for Capacitor 7. Both are documented in NOTICE.md and bundled only in the mobile build — the whole feature folds away in web/demo builds via MOBILE, so nothing new lands in the web bundle. No backend/schema change: gymCards rides the existing state sync and backup like every other field. Non-QR symbologies are readable but not reproducible, so capture refuses them rather than storing a code that would display wrong bars. Native wiring: CAMERA permission + ML Kit barcode_ui meta-data (AndroidManifest), NSCameraUsageDescription (iOS Info.plist), mlkit plugin registered via cap sync. Debug builds get an applicationIdSuffix '.test' and an 'OpenGymTest' label so a test build installs alongside the real app. --- NOTICE.md | 46 +++++ frontend/android/app/build.gradle | 6 + frontend/android/app/capacitor.build.gradle | 1 + .../app/src/debug/res/values/strings.xml | 7 + .../android/app/src/main/AndroidManifest.xml | 6 + frontend/android/capacitor.settings.gradle | 3 + frontend/ios/App/App/Info.plist | 2 + frontend/package-lock.json | 30 +++ frontend/package.json | 2 + frontend/src/App.jsx | 6 + frontend/src/components/Icon.jsx | 5 + frontend/src/components/QrCanvas.jsx | 33 ++++ frontend/src/index.css | 37 ++++ frontend/src/lib/qr.js | 67 +++++++ frontend/src/lib/scan.js | 109 +++++++++++ frontend/src/locales/es.js | 25 +++ frontend/src/store/useStore.js | 8 + frontend/src/views/CheckIn.jsx | 176 ++++++++++++++++++ frontend/src/views/Home.jsx | 18 ++ 19 files changed, 587 insertions(+) create mode 100644 frontend/android/app/src/debug/res/values/strings.xml create mode 100644 frontend/src/components/QrCanvas.jsx create mode 100644 frontend/src/lib/qr.js create mode 100644 frontend/src/lib/scan.js create mode 100644 frontend/src/views/CheckIn.jsx diff --git a/NOTICE.md b/NOTICE.md index a6a1cf2..0ae5a0a 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -123,3 +123,49 @@ English source produced with OpenAI Codex and Anthropic Claude Code language-model assistance. They are not copied from a separate Portuguese dataset. Their review status and translation policy are documented alongside the source files. + +## Gym check-in QR codes + +The mobile-only gym check-in feature (a saved membership code shown as a QR/barcode on the phone, +added by typing, importing a photo, or scanning with the camera) uses two third-party packages. +Both are permissively licensed and compatible with openGym's AGPL, and both are bundled only in +the mobile build — the web and demo builds never ship them. + +### QR/barcode rendering — `lean-qr` + +openGym renders each saved code on the phone with [**lean-qr**](https://github.com/davidje13/lean-qr) +by David Evans, used under the **MIT License** and reproduced below. Only the code's stored value +is kept; the picture is generated fresh from that value each time it is shown, never stored. + +``` +MIT License + +Copyright (c) 2021-2025 David Evans + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +### Camera scan & photo decode — `@capacitor-mlkit/barcode-scanning` + +Reading a code — from the camera or from an imported photo — uses the +[**@capacitor-mlkit/barcode-scanning**](https://github.com/capawesome-team/capacitor-mlkit) plugin +by the Capawesome Team (Robin Genz), a Capacitor wrapper around Google's ML Kit, used under the +**Apache License 2.0**. openGym pins the `7.x` line to stay on Capacitor 7. The full license text is +available at and in the package's own `LICENSE` file. +The decoded string is what openGym keeps; the photo itself is never stored. diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle index 98868cd..f477595 100644 --- a/frontend/android/app/build.gradle +++ b/frontend/android/app/build.gradle @@ -21,6 +21,12 @@ android { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } + debug { + // Test build installs side-by-side with the real app: its own applicationId, so both + // can live on one device. The name/icon label is overridden by the debug resource + // overlay in src/debug/res. The release build (the "real" app) is untouched. + applicationIdSuffix ".test" + } } } diff --git a/frontend/android/app/capacitor.build.gradle b/frontend/android/app/capacitor.build.gradle index af1bea9..815aa6b 100644 --- a/frontend/android/app/capacitor.build.gradle +++ b/frontend/android/app/capacitor.build.gradle @@ -9,6 +9,7 @@ android { apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle" dependencies { + implementation project(':capacitor-mlkit-barcode-scanning') implementation project(':capacitor-app') implementation project(':capacitor-filesystem') implementation project(':capacitor-local-notifications') diff --git a/frontend/android/app/src/debug/res/values/strings.xml b/frontend/android/app/src/debug/res/values/strings.xml new file mode 100644 index 0000000..eff2a58 --- /dev/null +++ b/frontend/android/app/src/debug/res/values/strings.xml @@ -0,0 +1,7 @@ + + + + OpenGymTest + OpenGymTest + diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml index d137fe6..d84111a 100644 --- a/frontend/android/app/src/main/AndroidManifest.xml +++ b/frontend/android/app/src/main/AndroidManifest.xml @@ -27,6 +27,10 @@ android:grantUriPermissions="true"> + + + @@ -36,4 +40,6 @@ on Android 12+. Where it isn't granted, scheduling silently falls back to inexact alarms — the reminder still arrives, just not to the minute. --> + + diff --git a/frontend/android/capacitor.settings.gradle b/frontend/android/capacitor.settings.gradle index d757f12..90dbbe8 100644 --- a/frontend/android/capacitor.settings.gradle +++ b/frontend/android/capacitor.settings.gradle @@ -2,6 +2,9 @@ include ':capacitor-android' project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor') +include ':capacitor-mlkit-barcode-scanning' +project(':capacitor-mlkit-barcode-scanning').projectDir = new File('../node_modules/@capacitor-mlkit/barcode-scanning/android') + include ':capacitor-app' project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android') diff --git a/frontend/ios/App/App/Info.plist b/frontend/ios/App/App/Info.plist index 8e81fcd..1987307 100644 --- a/frontend/ios/App/App/Info.plist +++ b/frontend/ios/App/App/Info.plist @@ -45,5 +45,7 @@ UIViewControllerBasedStatusBarAppearance + NSCameraUsageDescription + Used to scan your gym membership QR code so you can check in from the app. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index a4e04ce..57d6a3c 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,11 +9,13 @@ "version": "1.2.14", "license": "AGPL-3.0-or-later", "dependencies": { + "@capacitor-mlkit/barcode-scanning": "^7.5.0", "@capacitor/app": "^7.1.2", "@capacitor/core": "^7.6.8", "@capacitor/filesystem": "^7.1.8", "@capacitor/local-notifications": "^7.0.7", "@capacitor/share": "^7.0.4", + "lean-qr": "^2.7.3", "react": "^19.2.7", "react-dom": "^19.2.7", "react-router-dom": "^7.18.2", @@ -54,6 +56,25 @@ "node": ">=6.9.0" } }, + "node_modules/@capacitor-mlkit/barcode-scanning": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@capacitor-mlkit/barcode-scanning/-/barcode-scanning-7.5.0.tgz", + "integrity": "sha512-DBWRykYYLW0YMj/UzlQ0sVGn83mwGAJsbZVxFsd44pppEEy88OO04lxy9Esv5QpnNBIKPjSIqLWmSLuhoFGPaQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/capawesome-team/" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/capawesome" + } + ], + "license": "Apache-2.0", + "peerDependencies": { + "@capacitor/core": ">=7.0.0" + } + }, "node_modules/@capacitor/android": { "version": "7.6.8", "resolved": "https://registry.npmjs.org/@capacitor/android/-/android-7.6.8.tgz", @@ -3742,6 +3763,15 @@ "node": ">=6" } }, + "node_modules/lean-qr": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/lean-qr/-/lean-qr-2.7.3.tgz", + "integrity": "sha512-/eQryMvYyTL3dSMK/IlvSjUYG0ShQv62owXiFbGkSH+lFZzf4VOsPP+UInAgeUH/rPIyz59uQE9XHRbn9o8SyQ==", + "license": "MIT", + "bin": { + "lean-qr": "cli.mjs" + } + }, "node_modules/lightningcss": { "version": "1.32.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 7ee96e5..dded906 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -14,11 +14,13 @@ }, "license": "AGPL-3.0-or-later", "dependencies": { + "@capacitor-mlkit/barcode-scanning": "^7.5.0", "@capacitor/app": "^7.1.2", "@capacitor/core": "^7.6.8", "@capacitor/filesystem": "^7.1.8", "@capacitor/local-notifications": "^7.0.7", "@capacitor/share": "^7.0.4", + "lean-qr": "^2.7.3", "react": "^19.2.7", "react-dom": "^19.2.7", "react-router-dom": "^7.18.2", diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index b30af2f..bd0f340 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -5,6 +5,7 @@ import { useUI } from './store/useUI.js' import { bindUI } from './components/ui.jsx' import { ACCENTS } from './lib/format.js' import { setLang, useLang } from './lib/i18n.js' +import { MOBILE } from './lib/mobile.js' import { setNav } from './lib/nav.js' import { initBackButton } from './lib/back.js' import { useWakeLock } from './lib/wakelock.js' @@ -19,6 +20,7 @@ import TimerFlash from './components/TimerFlash.jsx' import Login from './views/Login.jsx' import MobileOnboarding from './views/MobileOnboarding.jsx' import Home from './views/Home.jsx' +import CheckIn from './views/CheckIn.jsx' import Plan from './views/Plan.jsx' import RoutineEdit from './views/RoutineEdit.jsx' import Workout from './views/Workout.jsx' @@ -110,6 +112,10 @@ function Shell() { {!authed ? : needsMobileOnboarding ? : ( } /> + {/* Gym check-in is mobile-only — it needs the native scanner and showing a QR to + a turnstile makes no sense in a browser tab. Off mobile the route falls through + to the catch-all redirect below. */} + {MOBILE && } />} } /> } /> } /> diff --git a/frontend/src/components/Icon.jsx b/frontend/src/components/Icon.jsx index b270cd3..033f3f1 100644 --- a/frontend/src/components/Icon.jsx +++ b/frontend/src/components/Icon.jsx @@ -112,6 +112,11 @@ const P = { signOut: <>, shuffle: <>, info: <>, + // Three position-detection squares plus a scatter of modules — reads as "QR / scan this" + // at tab-bar size without trying to draw a real (unscannable) code. + qr: <>, + camera: <>, + image: <>, warning: <>, } diff --git a/frontend/src/components/QrCanvas.jsx b/frontend/src/components/QrCanvas.jsx new file mode 100644 index 0000000..543e052 --- /dev/null +++ b/frontend/src/components/QrCanvas.jsx @@ -0,0 +1,33 @@ +import { useEffect, useRef, useState } from 'react' +import { renderQrToCanvas } from '../lib/qr.js' + +// Renders a gym check-in code as a QR image on a . lean-qr draws one module per pixel; +// CSS (.qr-canvas) scales it up with image-rendering: pixelated so it stays razor-sharp at any +// display size without re-generating. Regenerated from `value` on every change — we never store +// the picture (see lib/qr.js). +// +// The lib loads via dynamic import, so the first paint is a frame behind; a plain box holds the +// space until then. A render failure (empty value, lib load error) shows nothing rather than a +// broken canvas — the caller decides what an unusable card looks like. +export default function QrCanvas({ value, size = 240, className = '' }) { + const ref = useRef(null) + const [ok, setOk] = useState(false) + + useEffect(() => { + let alive = true + setOk(false) + renderQrToCanvas(ref.current, value) + .then(mods => { if (alive) setOk(mods > 0) }) + .catch(() => { if (alive) setOk(false) }) + return () => { alive = false } + }, [value]) + + return ( + + ) +} diff --git a/frontend/src/index.css b/frontend/src/index.css index ca0528e..cfbb542 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -1056,3 +1056,40 @@ h4.sec{ .exmedia img{height:380px} .hm-wrap{display:flex;flex-direction:column;align-items:center} } + +/* ------------------------------------------------------- gym check-in -- */ +/* Mobile-only feature (views/CheckIn.jsx): saved membership codes shown as QR, swiped + through horizontally. The rail is a scroll-snap track — one card per viewport, no JS + carousel — with a trailing "+" card to add another. */ +.ci-rail{ + display:flex;gap:14px;overflow-x:auto;scroll-snap-type:x mandatory; + -webkit-overflow-scrolling:touch;scrollbar-width:none; + padding:4px 0 8px;margin:0 -16px;padding-left:16px;padding-right:16px; +} +.ci-rail::-webkit-scrollbar{display:none} +.ci-card{ + scroll-snap-align:center;flex:0 0 100%;box-sizing:border-box; + background:var(--surface);border-radius:var(--r-xl);padding:22px 18px; + display:flex;flex-direction:column;align-items:center;gap:14px; +} +.ci-card .ci-label{font-size:19px;font-weight:600;letter-spacing:-.014em;text-align:center} +.ci-card .ci-value{font-size:14px;color:var(--label-2);word-break:break-all;text-align:center;font-variant-numeric:tabular-nums} +/* The QR itself: lean-qr paints 1 module per pixel, so scale it up with the browser's + nearest-neighbour so every module stays a crisp square instead of a blurred blob. White + quiet-zone padding is baked in by the renderer; the plate underneath just frames it. */ +.ci-qr-plate{background:#fff;border-radius:var(--r-lg);padding:16px} +.qr-canvas{display:block;image-rendering:pixelated;image-rendering:crisp-edges;transition:opacity var(--fast)} +/* the trailing add card — a big + on a dashed outline, same footprint as a real card */ +.ci-add{ + scroll-snap-align:center;flex:0 0 100%;box-sizing:border-box; + min-height:280px;border-radius:var(--r-xl); + border:2px dashed var(--surface-3);background:none;color:var(--label-2); + display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px; +} +.ci-add:active{background:var(--surface);transform:scale(.99)} +.ci-add .icn{font-size:40px;--icon-stroke:1.8} +.ci-add .ci-add-t{font-size:16px;font-weight:500} +/* dots under the rail — which card you're on. Purely a hint; the rail itself is the control. */ +.ci-dots{display:flex;justify-content:center;gap:7px;margin-top:4px} +.ci-dot{width:7px;height:7px;border-radius:50%;background:var(--surface-3);transition:background var(--fast),transform var(--fast)} +.ci-dot.on{background:var(--acc);transform:scale(1.15)} diff --git a/frontend/src/lib/qr.js b/frontend/src/lib/qr.js new file mode 100644 index 0000000..a3af848 --- /dev/null +++ b/frontend/src/lib/qr.js @@ -0,0 +1,67 @@ +// QR rendering for the gym check-in cards (mobile-only feature — see views/CheckIn.jsx). +// +// We never store a photo of a membership card, only its decoded value (+ its symbology in +// `fmt`). The picture a turnstile scanner reads is regenerated from that value every time the +// card is shown, here. +// +// lean-qr (MIT, see NOTICE.md) is loaded with a dynamic import so its ~4kB never lands in the +// web bundle — the whole feature is gated behind MOBILE, but the library itself is plain JS a +// static import would otherwise pull into every build. +// +// Scope: lean-qr generates QR codes only. A gym card is virtually always a QR code, and the +// capture flow (lib/scan.js) refuses any symbology we cannot faithfully reproduce, so a stored +// card is guaranteed renderable here — canRenderFmt() is the single source of that truth, shared +// by both sides. + +let _leanqr = null + +// Cached loader for lean-qr. Resolves once; every card after the first reuses the same module. +async function loadLeanQr() { + if (!_leanqr) _leanqr = await import('lean-qr') + return _leanqr +} + +// The symbologies we can both read (mlkit) AND redraw (lean-qr). Stored `fmt` is a lower-cased +// BarcodeFormat. Only QR qualifies: reproducing an EAN/Code128/etc. would need a 1D renderer we +// deliberately did not add, and a code we can't redraw faithfully is worse than not storing it — +// it would look scannable but carry the wrong bars. +export function canRenderFmt(fmt) { + return normalizeFmt(fmt) === 'qrcode' +} + +// mlkit reports BarcodeFormat as e.g. 'QR_CODE' | 'QrCode'; older callers may pass 'qr'. Fold +// them all to a stable lower-case token we store and compare on. +export function normalizeFmt(fmt) { + const s = String(fmt || '').toLowerCase().replace(/[^a-z0-9]/g, '') + if (s === 'qr' || s === 'qrcode') return 'qrcode' + return s +} + +// Draw `value` as a QR code onto `canvas` at 1 module per pixel; CSS scales it up with +// image-rendering: pixelated (see .qr-canvas in index.css) so it stays crisp at any size. +// `on`/`off` default to solid black on white — turnstile scanners want maximum contrast, not +// the app's theme colours, and a themed (e.g. lime-on-black) code fails to read on many +// readers. Returns the module count (QR size) so the caller can react if it wants. +export async function renderQrToCanvas(canvas, value, { on = '#000000', off = '#ffffff' } = {}) { + if (!canvas || !value) return 0 + const { generate, correction } = await loadLeanQr() + // Medium error correction: a good default that survives a scratched or partly-obscured phone + // screen without inflating the code so much it gets dense on small screens. + const code = generate(value, { minCorrectionLevel: correction.M }) + code.toCanvas(canvas, { + on: hexToRgba(on), + off: hexToRgba(off), + padX: 2, + padY: 2, + }) + return code.size +} + +// lean-qr wants colours as [r,g,b,a]. Accept a #rrggbb (or #rgb) string; anything else is +// treated as opaque black/white by the caller's defaults, so this only has to handle hex. +function hexToRgba(hex) { + let h = String(hex).replace('#', '') + if (h.length === 3) h = h.split('').map(c => c + c).join('') + const n = parseInt(h, 16) + return [(n >> 16) & 255, (n >> 8) & 255, n & 255, 255] +} diff --git a/frontend/src/lib/scan.js b/frontend/src/lib/scan.js new file mode 100644 index 0000000..f7bb9f8 --- /dev/null +++ b/frontend/src/lib/scan.js @@ -0,0 +1,109 @@ +// Capturing a gym check-in code (mobile-only — see views/CheckIn.jsx). Three ways in: +// 1. type it — no plugin, handled entirely in the view +// 2. import a photo — importCodeFromImage(file): decode a picture the user already has +// 3. scan with camera — scanCode(): live camera via ML Kit's own scanner UI +// +// Both plugin paths dynamic-import @capacitor-mlkit/barcode-scanning (Apache-2.0, see NOTICE.md) +// so it never lands in the web bundle — the whole feature is behind MOBILE, and every entry point +// here throws a plain Error off mobile rather than importing a native module that isn't there. +// +// What comes back is a normalized { value, fmt } (or null when the user cancels / nothing was +// found). `value` is the code's machine-readable content; `fmt` is a lower-cased symbology token +// matching lib/qr.js's normalizeFmt. The caller checks canRenderFmt(fmt) before saving — we can +// read many barcode kinds but only redraw QR, so a non-QR code is reported and refused there, not +// silently stored. +import { MOBILE } from './mobile.js' +import { normalizeFmt } from './qr.js' + +// A found barcode from either path → our stored shape. mlkit gives rawValue (machine-readable, +// what a turnstile actually reads) and a BarcodeFormat; we keep rawValue and fold the format. +function toCode(barcode) { + if (!barcode) return null + const value = barcode.rawValue || barcode.displayValue || '' + if (!value) return null + return { value, fmt: normalizeFmt(barcode.format) } +} + +// Live camera scan. On Android this opens Google's own full-screen scanner UI (no camera view we +// have to host); on iOS the plugin's native scanner. Returns the first barcode found, or null if +// the user backed out without scanning. Throws if scanning isn't supported or permission is hard- +// denied so the caller can explain why. +export async function scanCode() { + if (!MOBILE) throw new Error('Scanning is only available in the app') + const { BarcodeScanner } = await import('@capacitor-mlkit/barcode-scanning') + + const { supported } = await BarcodeScanner.isSupported() + if (!supported) throw new Error('unsupported') + + await ensureCameraPermission(BarcodeScanner) + await ensureScannerModule(BarcodeScanner) + + const { barcodes } = await BarcodeScanner.scan() + return barcodes && barcodes.length ? toCode(barcodes[0]) : null +} + +// Decode a barcode out of an image the user picked. mlkit's readBarcodesFromImage wants a local +// file PATH, and a browser only hands us a File/blob — so we bounce the bytes +// through the app's cache dir (reusing @capacitor/filesystem, already a dependency) to get a real +// path, decode, then delete the temp file. Returns the first barcode, or null if none was found. +export async function importCodeFromImage(file) { + if (!MOBILE) throw new Error('Importing is only available in the app') + if (!file) return null + const { BarcodeScanner } = await import('@capacitor-mlkit/barcode-scanning') + const { Filesystem, Directory } = await import('@capacitor/filesystem') + + const base64 = await fileToBase64(file) + const name = `checkin-import-${Date.now()}.${extOf(file.name)}` + let uri = null + try { + const w = await Filesystem.writeFile({ path: name, directory: Directory.Cache, data: base64 }) + uri = w.uri + const { barcodes } = await BarcodeScanner.readBarcodesFromImage({ path: uri }) + return barcodes && barcodes.length ? toCode(barcodes[0]) : null + } finally { + // Best effort — a leftover temp image in the cache dir is harmless, but tidy up anyway. + try { await Filesystem.deleteFile({ path: name, directory: Directory.Cache }) } catch (e) { /* */ } + } +} + +// Camera permission for the live scanner. checkPermissions first so an already-granted user never +// sees a prompt; request only when needed. A hard denial throws so the caller can point the user +// at Settings rather than silently doing nothing. +async function ensureCameraPermission(BarcodeScanner) { + let { camera } = await BarcodeScanner.checkPermissions() + if (camera !== 'granted' && camera !== 'limited') { + ({ camera } = await BarcodeScanner.requestPermissions()) + } + if (camera !== 'granted' && camera !== 'limited') throw new Error('permission-denied') +} + +// On Android the ML Kit scanner ships as an on-demand Google Play module, absent on first use. +// Install it (once) before scanning; a no-op / not-applicable on iOS, where the check simply +// reports available. Failures here are non-fatal — scan() will surface a clearer error if it +// truly can't proceed. +async function ensureScannerModule(BarcodeScanner) { + try { + if (!BarcodeScanner.isGoogleBarcodeScannerModuleAvailable) return + const { available } = await BarcodeScanner.isGoogleBarcodeScannerModuleAvailable() + if (!available) await BarcodeScanner.installGoogleBarcodeScannerModule() + } catch (e) { /* let scan() decide whether it can still run */ } +} + +// A File/Blob → bare base64 (no data: prefix), which Filesystem.writeFile expects. +function fileToBase64(file) { + return new Promise((resolve, reject) => { + const r = new FileReader() + r.onerror = () => reject(r.error || new Error('read failed')) + r.onload = () => { + const s = String(r.result || '') + const comma = s.indexOf(',') + resolve(comma === -1 ? s : s.slice(comma + 1)) + } + r.readAsDataURL(file) + }) +} + +function extOf(filename) { + const m = /\.([a-z0-9]+)$/i.exec(filename || '') + return m ? m[1].toLowerCase() : 'jpg' +} diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 1167792..ec7dbfd 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -743,4 +743,29 @@ export default { 'Set to 0 to go back to the default ({0}).': 'Pon 0 para volver al valor por defecto ({0}).', 'Applies to this exercise everywhere, not just this plan.': 'Se aplica a este ejercicio en todas partes, no solo en este plan.', 'You still log the total weight — the bar only feeds the per-side plate math.': 'Sigues registrando el peso total — la barra solo se usa para calcular los discos por lado.', + // Gym check-in (mobile-only) + 'Check in': 'Registrarse', + 'At the gym': 'En el gimnasio', + 'Show this at the gym': 'Muestra esto en el gimnasio', + 'Add your gym card': 'Añade tu tarjeta del gimnasio', + 'Add a card': 'Añadir una tarjeta', + 'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Escribe el número de tu tarjeta de socio, importa una foto o escanéala con la cámara. No hace falta otra app en el gimnasio — solo abre esta pantalla.', + 'Remove this card?': '¿Eliminar esta tarjeta?', + 'Scan it, import a photo, or type the code by hand.': 'Escanéala, importa una foto o escribe el código a mano.', + 'Scan': 'Escanear', + 'Import photo': 'Importar foto', + 'Label': 'Etiqueta', + 'e.g. FitZone downtown': 'p. ej. FitZone centro', + 'Code': 'Código', + 'Membership number or code': 'Número de socio o código', + 'Save card': 'Guardar tarjeta', + 'Gym card': 'Tarjeta del gimnasio', + 'Card added': 'Tarjeta añadida', + 'Nothing to save yet': 'Nada que guardar todavía', + "That's not a QR code — only QR cards can be shown here": 'Eso no es un código QR — aquí solo se pueden mostrar tarjetas QR', + 'No QR code found in that image': 'No se encontró ningún código QR en esa imagen', + 'Could not read that image': 'No se pudo leer esa imagen', + 'Camera permission is needed to scan. Enable it in Settings.': 'Se necesita permiso de cámara para escanear. Actívalo en Ajustes.', + 'Scanning is not available on this device.': 'El escaneo no está disponible en este dispositivo.', + 'Could not start the scanner': 'No se pudo iniciar el escáner', } diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index c86f7a8..2476cb7 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -29,6 +29,14 @@ export const DEF = { // lib/bar.js). Personal equipment, so it syncs with the account but never travels in a // shared plan. Logged weights stay the total — this only feeds the plate math. barWeights: {}, + // Gym check-in cards (mobile-only feature, see views/CheckIn.jsx). Each is a membership + // code shown as a QR/barcode at the gym's turnstile — added by typing it, importing a photo + // of the card, or scanning it. We only ever keep the code's VALUE, never a photo: the image + // is regenerated from `value` every time it's shown (lib/qr.js). `fmt` is the barcode symbology + // ('qrcode' | 'ean13' | 'code128' | … — lower-cased BarcodeFormat) so it renders as the same + // kind of code the gym issued. Just data, so it syncs and backs up like everything else. + // [{ id, label, value, fmt }] + gymCards: [], } const clone = o => JSON.parse(JSON.stringify(o)) diff --git a/frontend/src/views/CheckIn.jsx b/frontend/src/views/CheckIn.jsx new file mode 100644 index 0000000..6083f83 --- /dev/null +++ b/frontend/src/views/CheckIn.jsx @@ -0,0 +1,176 @@ +import { useEffect, useRef, useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useStore } from '../store/useStore.js' +import { useUI } from '../store/useUI.js' +import { uid } from '../lib/format.js' +import { t } from '../lib/i18n.js' +import { canRenderFmt } from '../lib/qr.js' +import { scanCode, importCodeFromImage } from '../lib/scan.js' +import Icon from '../components/Icon.jsx' +import QrCanvas from '../components/QrCanvas.jsx' +import { Button, TextField } from '../components/ui.jsx' +import { confirmSheet } from '../sheets.jsx' +import { tappable } from '../lib/use-sheet-keyboard.js' + +// Gym check-in (mobile-only, reached from the Home "Check in" card). Shows each saved membership +// code as a QR the turnstile can read, swiped through horizontally, with a trailing "+" to add +// another. We only ever store the code's value + symbology; the QR is regenerated from it here +// every time (see lib/qr.js), so nothing sensitive is kept as an image. +export default function CheckIn() { + const nav = useNavigate() + const cards = useStore(s => s.S.gymCards) || [] + const railRef = useRef(null) + const [active, setActive] = useState(0) + + // Which card the horizontal scroll has settled on — drives the little dots. Reading it off the + // scroll position keeps the rail itself the single control; no separate paging state to sync. + const onScroll = () => { + const rail = railRef.current + if (!rail) return + const i = Math.round(rail.scrollLeft / rail.clientWidth) + setActive(i) + } + + return
+
+ +
+

{t('Check in')}

+
{cards.length ? t('Show this at the gym') : t('Add your gym card')}
+
+
+ +
+ {cards.map(card => )} + +
+ + {(cards.length > 0) &&
+ {cards.map((c, i) => )} + {/* the add card is a slide too, so it gets a dot */} + = cards.length ? ' on' : '')} /> +
} + + {!cards.length &&
+ {t('Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.')} +
} +
+} + +// One saved card: its label, the QR, and the raw value underneath (handy when a reader is fussy +// and a staff member types it in). Long-press / the trash button removes it. +function CardFace({ card }) { + const update = useStore(s => s.update) + const remove = () => confirmSheet({ + title: t('Remove this card?'), + message: card.label, + confirmText: t('Remove'), + danger: true, + onConfirm: () => update(s => { s.gymCards = (s.gymCards || []).filter(c => c.id !== card.id) }), + }) + return
+
+
{card.label}
+ +
+
+
{card.value}
+
+} + +/* ------------------------------------------------------------- add-card sheet -- */ + +// Opens the add-card sheet. Co-located with the view (not sheets.jsx) because the whole feature +// is mobile-only and pulls in the native scanner — keeping it here keeps that out of the shared, +// web-bundled sheets module. +export function openAddCard() { + useUI.getState().openSheet(close => ) +} + +function saveCard({ label, value, fmt }) { + const update = useStore.getState().update + const toast = useUI.getState().toast + const trimmed = (value || '').trim() + if (!trimmed) { toast(t('Nothing to save yet')); return false } + // We can read many barcode kinds but only redraw QR faithfully — refuse anything else rather + // than store a code that would display as the wrong bars at the turnstile. + if (fmt && !canRenderFmt(fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return false } + update(s => { + if (!Array.isArray(s.gymCards)) s.gymCards = [] + s.gymCards.push({ id: uid(), label: (label || '').trim() || t('Gym card'), value: trimmed, fmt: 'qrcode' }) + }) + toast(t('Card added')) + return true +} + +function AddCard({ close }) { + const [label, setLabel] = useState('') + const [value, setValue] = useState('') + const [busy, setBusy] = useState(false) + const fileRef = useRef(null) + const toast = useUI(s => s.toast) + + const commitTyped = () => { if (saveCard({ label, value, fmt: 'qrcode' })) close() } + + // Camera scan: hands off to the native scanner, comes back with a value we drop straight into + // the form so the user can still name it before saving. + const doScan = async () => { + setBusy(true) + try { + const code = await scanCode() + if (!code) return // user backed out + if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return } + setValue(code.value) + } catch (e) { + toast(scanErrorMessage(e)) + } finally { setBusy(false) } + } + + const onFile = async ev => { + const file = ev.target.files && ev.target.files[0] + ev.target.value = '' // let the same file be picked again later + if (!file) return + setBusy(true) + try { + const code = await importCodeFromImage(file) + if (!code) { toast(t('No QR code found in that image')); return } + if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return } + setValue(code.value) + } catch (e) { + toast(t('Could not read that image')) + } finally { setBusy(false) } + } + + return <> +

{t('Add a card')}

+
{t('Scan it, import a photo, or type the code by hand.')}
+ +
+ + +
+ + + setLabel(e.target.value)} placeholder={t('e.g. FitZone downtown')} style={{ marginBottom: 12 }} /> + + + setValue(e.target.value)} placeholder={t('Membership number or code')} inputMode="text" style={{ marginBottom: 16 }} /> + + {value.trim() &&
} + + + + + +} + +// Map the thrown reasons from lib/scan.js to something a person can act on. +function scanErrorMessage(e) { + const m = String(e && e.message) + if (m === 'permission-denied') return t('Camera permission is needed to scan. Enable it in Settings.') + if (m === 'unsupported') return t('Scanning is not available on this device.') + return t('Could not start the scanner') +} diff --git a/frontend/src/views/Home.jsx b/frontend/src/views/Home.jsx index 158a459..c597218 100644 --- a/frontend/src/views/Home.jsx +++ b/frontend/src/views/Home.jsx @@ -10,6 +10,7 @@ import Icon from '../components/Icon.jsx' import { Button } from '../components/ui.jsx' import { tappable } from '../lib/use-sheet-keyboard.js' import { glyphOf } from '../lib/glyphs.js' +import { MOBILE } from '../lib/mobile.js' // Home = what to do now + a quick glance. Deep charts & history live in Stats. export default function Home() { @@ -94,6 +95,23 @@ export default function Home() { + {/* Mobile-only: jump to the gym check-in cards (QR membership codes). Shown here as a quick + tap on arrival at the gym; the whole feature folds away in web/demo builds via MOBILE. */} + {MOBILE && ( +
nav('/checkin'))}> +
+
+ +
+
{t('At the gym')}
+
{t('Check in')}
+
+
+ +
+
+ )} + {!S.routines.length && !S.active && (