commit 654104cbed3c21a49622f962df19170756c5252d Author: ssbg04 Date: Sun May 17 00:12:57 2026 +0800 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..64e230d --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.claude +.vscode +assets + +backend/node_modules +requirements \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..99302ed --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +"# TIS_RMS" diff --git a/backend/.example.env b/backend/.example.env new file mode 100644 index 0000000..9cbb5c4 --- /dev/null +++ b/backend/.example.env @@ -0,0 +1,6 @@ +PORT=3000 +JWT_SECRET=tis_rms_super_secret_key_2026 +DB_PATH=./data/tis_rms.db +UPLOAD_PATH=./uploads +# Root folder where auto-created student directories are stored +STUDENT_DIR_ROOT=./data/students diff --git a/backend/data/students/Garcia_Cris Charles_108297100170/meow.txt b/backend/data/students/Garcia_Cris Charles_108297100170/meow.txt new file mode 100644 index 0000000..e69de29 diff --git a/backend/data/tis_rms.db b/backend/data/tis_rms.db new file mode 100644 index 0000000..fc6a002 Binary files /dev/null and b/backend/data/tis_rms.db differ diff --git a/backend/index.js b/backend/index.js new file mode 100644 index 0000000..1b339f0 --- /dev/null +++ b/backend/index.js @@ -0,0 +1,52 @@ +const express = require('express'); +const cors = require('cors'); +const morgan = require('morgan'); +const path = require('path'); +require('dotenv').config(); + +const { initSchema } = require('./src/models/schema'); +const authRoutes = require('./src/routes/auth'); +const studentRoutes = require('./src/routes/students'); +const documentRoutes = require('./src/routes/documents'); +const dashboardRoutes = require('./src/routes/dashboard'); +const setupRoutes = require('./src/routes/setup'); +const gradeRoutes = require('./src/routes/grades'); +const userRoutes = require('./src/routes/users'); +const reportsRoutes = require('./src/routes/reports'); +const archivesRoutes = require('./src/routes/archives'); +const folderRoutes = require('./src/routes/folders'); +const requirementRoutes = require('./src/routes/requirements'); +require('./src/services/retentionEngine'); // Start retention engine + +const app = express(); +const PORT = process.env.PORT || 3000; + +// Initialize Database +initSchema(); + +// Middleware +app.use(cors()); +app.use(express.json()); +app.use(morgan('dev')); +app.use('/uploads', express.static(path.join(__dirname, 'uploads'))); + +// Routes +app.use('/api/auth', authRoutes); +app.use('/api/students', studentRoutes); +app.use('/api/documents', documentRoutes); +app.use('/api/dashboard', dashboardRoutes); +app.use('/api/setup', setupRoutes); +app.use('/api/grades', gradeRoutes); +app.use('/api/users', userRoutes); +app.use('/api/reports', reportsRoutes); +app.use('/api/archives', archivesRoutes); +app.use('/api/folders', folderRoutes); +app.use('/api/requirements', requirementRoutes); + +app.get('/', (req, res) => { + res.json({ message: 'TIS RMS API is running' }); +}); + +app.listen(PORT, () => { + console.log(`Server running on port ${PORT}`); +}); diff --git a/backend/package-lock.json b/backend/package-lock.json new file mode 100644 index 0000000..0cb100a --- /dev/null +++ b/backend/package-lock.json @@ -0,0 +1,1631 @@ +{ + "name": "backend", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "backend", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "bcrypt": "^6.0.0", + "better-sqlite3": "^12.9.0", + "cors": "^2.8.6", + "dotenv": "^17.4.2", + "express": "^5.2.1", + "jsonwebtoken": "^9.0.3", + "morgan": "^1.10.1", + "multer": "^2.1.1", + "node-cron": "^4.2.1" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/basic-auth": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", + "integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/basic-auth/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/bcrypt": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-6.0.0.tgz", + "integrity": "sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-addon-api": "^8.3.0", + "node-gyp-build": "^4.8.4" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/better-sqlite3": { + "version": "12.9.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.9.0.tgz", + "integrity": "sha512-wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", + "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/morgan": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.1.tgz", + "integrity": "sha512-223dMRJtI/l25dJKWpgij2cMtywuG/WiUKXdvwfbhGKBhy1puASqXwFzmWZ7+K73vUPoR7SS2Qz2cI/g9MKw0A==", + "license": "MIT", + "dependencies": { + "basic-auth": "~2.0.1", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-finished": "~2.3.0", + "on-headers": "~1.1.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/morgan/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/morgan/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/morgan/node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.1.1.tgz", + "integrity": "sha512-mo+QTzKlx8R7E5ylSXxWzGoXoZbOsRMpyitcht8By2KHvMbf3tjwosZ/Mu/XYU6UuJ3VZnODIrak5ZrPiPyB6A==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 10.16.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "3.92.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.92.0.tgz", + "integrity": "sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-addon-api": { + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.7.0.tgz", + "integrity": "sha512-9MdFxmkKaOYVTV+XVRG8ArDwwQ77XIgIPyKASB1k3JPq3M8fGQQQE3YpMOrKm6g//Ktx8ivZr8xo1Qmtqub+GA==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/node-cron": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-4.2.1.tgz", + "integrity": "sha512-lgimEHPE/QDgFlywTd8yTR61ptugX3Qer29efeyWw2rv259HtGBNn1vZVmp8lB9uo9wC0t/AT4iGqXxia+CJFg==", + "license": "ISC", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "license": "MIT", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..d17f128 --- /dev/null +++ b/backend/package.json @@ -0,0 +1,25 @@ +{ + "name": "backend", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start": "node index.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "dependencies": { + "bcrypt": "^6.0.0", + "better-sqlite3": "^12.9.0", + "cors": "^2.8.6", + "dotenv": "^17.4.2", + "express": "^5.2.1", + "jsonwebtoken": "^9.0.3", + "morgan": "^1.10.1", + "multer": "^2.1.1", + "node-cron": "^4.2.1" + } +} diff --git a/backend/src/config/db.js b/backend/src/config/db.js new file mode 100644 index 0000000..d8e1b58 --- /dev/null +++ b/backend/src/config/db.js @@ -0,0 +1,16 @@ +const Database = require('better-sqlite3'); +const path = require('path'); +const fs = require('fs'); +require('dotenv').config(); + +const dbPath = process.env.DB_PATH || './data/tis_rms.db'; +const dbDir = path.dirname(dbPath); + +if (!fs.existsSync(dbDir)) { + fs.mkdirSync(dbDir, { recursive: true }); +} + +const db = new Database(dbPath, { verbose: console.log }); +db.pragma('foreign_keys = ON'); + +module.exports = db; diff --git a/backend/src/controllers/archiveController.js b/backend/src/controllers/archiveController.js new file mode 100644 index 0000000..bf1123d --- /dev/null +++ b/backend/src/controllers/archiveController.js @@ -0,0 +1,134 @@ +const db = require('../config/db'); + +exports.getArchivedStudents = (req, res) => { + const { + search = '', + page = 1, + limit = 10, + status = 'All Statuses', + } = req.query; + + const pageNum = Math.max(1, parseInt(page)); + const limitNum = Math.min(100, Math.max(1, parseInt(limit))); + const offset = (pageNum - 1) * limitNum; + + try { + const conditions = []; + const params = []; + + // Base condition: only archived statuses + if (status === 'All Statuses' || !status) { + conditions.push(`s.status IN ('Graduated', 'Transferred Out', 'Dropped')`); + } else { + conditions.push(`s.status = ?`); + params.push(status); + } + + if (search.trim()) { + const like = `%${search.trim()}%`; + conditions.push(`(s.lrn LIKE ? OR s.first_name LIKE ? OR s.last_name LIKE ? OR s.middle_name LIKE ?)`); + params.push(like, like, like, like); + } + + const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''; + + // Count query + const countSql = ` + SELECT COUNT(DISTINCT s.id) as total + FROM students s + ${whereClause} + `; + const total = db.prepare(countSql).get(params).total; + + // Fetch query + const fetchSql = ` + SELECT + s.id, s.lrn, s.first_name, s.middle_name, s.last_name, s.extension, + s.status, s.created_at, + date(s.created_at) as archivedDate, + CASE + WHEN s.status = 'Graduated' THEN date(s.created_at, '+5 years') + WHEN s.status = 'Transferred Out' THEN date(s.created_at, '+5 years') + WHEN s.status = 'Dropped' THEN date(s.created_at, '+3 years') + ELSE date(s.created_at, '+5 years') + END as expiryDate + FROM students s + ${whereClause} + ORDER BY s.last_name ASC, s.first_name ASC + LIMIT ? OFFSET ? + `; + + const students = db.prepare(fetchSql).all([...params, limitNum, offset]); + + const currentDate = new Date().toISOString().split('T')[0]; + + const archives = students.map(student => { + const nameParts = [student.last_name + ',', student.first_name]; + if (student.middle_name) nameParts.push(student.middle_name.charAt(0) + '.'); + if (student.extension) nameParts.push(student.extension); + + const isExpired = student.expiryDate < currentDate; + + return { + id: student.id, + lrn: student.lrn, + name: nameParts.join(' '), + status: student.status, + archivedDate: student.archivedDate, + expiryDate: student.expiryDate, + isExpired: isExpired + }; + }); + + res.json({ + archives, + pagination: { + total, + page: pageNum, + limit: limitNum, + totalPages: Math.ceil(total / limitNum), + }, + }); + } catch (error) { + console.error('getArchivedStudents error:', error); + res.status(500).json({ message: 'Failed to fetch archives', error: error.message }); + } +}; + +exports.restoreArchive = (req, res) => { + const { id } = req.params; + + const existing = db.prepare('SELECT id, status FROM students WHERE id = ?').get(id); + if (!existing) return res.status(404).json({ message: 'Student not found.' }); + + try { + db.transaction(() => { + // Restore student status to Enrolled + db.prepare("UPDATE students SET status = 'Enrolled' WHERE id = ?").run(id); + + // Restore documents from Archived to Verified (assuming if they had an archive, they were verified, or just set to Verified) + db.prepare("UPDATE documents SET status = 'Verified', retention_date = NULL WHERE student_id = ? AND status = 'Archived'").run(id); + })(); + + res.json({ message: 'Record restored to active successfully' }); + } catch (error) { + console.error('restoreArchive error:', error); + res.status(500).json({ message: 'Failed to restore record', error: error.message }); + } +}; + +exports.purgeArchive = (req, res) => { + const { id } = req.params; + + const existing = db.prepare('SELECT id FROM students WHERE id = ?').get(id); + if (!existing) return res.status(404).json({ message: 'Student not found.' }); + + try { + // Due to CASCADE DELETE on constraints in schema.js, deleting the student will delete their documents, grades, and enrollments + db.prepare('DELETE FROM students WHERE id = ?').run(id); + res.json({ message: 'Record permanently purged successfully' }); + } catch (error) { + console.error('purgeArchive error:', error); + res.status(500).json({ message: 'Failed to purge record', error: error.message }); + } +}; diff --git a/backend/src/controllers/authController.js b/backend/src/controllers/authController.js new file mode 100644 index 0000000..0e63454 --- /dev/null +++ b/backend/src/controllers/authController.js @@ -0,0 +1,181 @@ +const db = require('../config/db'); +const bcrypt = require('bcrypt'); +const jwt = require('jsonwebtoken'); +require('dotenv').config(); + +// POST /api/auth/login +exports.login = (req, res) => { + const { username, password } = req.body; + + try { + const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username); + + if (!user || !bcrypt.compareSync(password, user.password)) { + return res.status(401).json({ message: 'Invalid username or password' }); + } + + const token = jwt.sign( + { id: user.id, username: user.username, role: user.role }, + process.env.JWT_SECRET, + { expiresIn: '30d' } // Extended for Remember Me support + ); + + res.json({ + token, + user: { + id: user.id, + username: user.username, + role: user.role, + firstName: user.first_name, + lastName: user.last_name + } + }); + } catch (error) { + res.status(500).json({ message: 'Login failed', error: error.message }); + } +}; + +// GET /api/auth/profile +exports.getProfile = (req, res) => { + try { + const user = db.prepare('SELECT id, username, first_name, middle_name, last_name, extension, role, email, phone FROM users WHERE id = ?').get(req.user.id); + res.json(user); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch profile', error: error.message }); + } +}; + +// PUT /api/auth/profile +exports.updateProfile = (req, res) => { + const { firstName, middleName, lastName, extension, phone, email } = req.body; + try { + db.prepare(` + UPDATE users + SET first_name = ?, middle_name = ?, last_name = ?, extension = ?, phone = ?, email = ?, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `).run(firstName, middleName, lastName, extension, phone, email, req.user.id); + res.json({ message: 'Profile updated successfully' }); + } catch (error) { + res.status(500).json({ message: 'Failed to update profile', error: error.message }); + } +}; + +// PUT /api/auth/change-password — requires currentPassword + newPassword +exports.changePassword = (req, res) => { + const { currentPassword, newPassword, confirmPassword } = req.body; + + if (!currentPassword || !newPassword || !confirmPassword) { + return res.status(400).json({ message: 'All password fields are required.' }); + } + if (newPassword !== confirmPassword) { + return res.status(400).json({ message: 'New passwords do not match.' }); + } + if (newPassword.length < 6) { + return res.status(400).json({ message: 'New password must be at least 6 characters.' }); + } + + try { + const user = db.prepare('SELECT password FROM users WHERE id = ?').get(req.user.id); + + if (!bcrypt.compareSync(currentPassword, user.password)) { + return res.status(400).json({ message: 'Current password is incorrect.' }); + } + + const hashedNewPassword = bcrypt.hashSync(newPassword, 10); + db.prepare('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?') + .run(hashedNewPassword, req.user.id); + + res.json({ message: 'Password changed successfully.' }); + } catch (error) { + res.status(500).json({ message: 'Failed to change password', error: error.message }); + } +}; + +// POST /api/auth/forgot-password — admin/teacher submits a reset request +exports.requestPasswordReset = (req, res) => { + const { username, newPassword, confirmPassword } = req.body; + + if (!username || !newPassword || !confirmPassword) { + return res.status(400).json({ message: 'All fields are required.' }); + } + if (newPassword !== confirmPassword) { + return res.status(400).json({ message: 'Passwords do not match.' }); + } + if (newPassword.length < 6) { + return res.status(400).json({ message: 'Password must be at least 6 characters.' }); + } + + try { + const user = db.prepare('SELECT id, role FROM users WHERE username = ?').get(username); + if (!user) { + return res.status(404).json({ message: 'Username not found.' }); + } + if (user.role === 'super_admin') { + return res.status(403).json({ message: 'Super Admin cannot submit password reset requests.' }); + } + + // Cancel any existing pending request for this user + db.prepare("DELETE FROM password_reset_requests WHERE user_id = ? AND status = 'pending'").run(user.id); + + const hashedPassword = bcrypt.hashSync(newPassword, 10); + db.prepare(` + INSERT INTO password_reset_requests (user_id, new_password_hash) + VALUES (?, ?) + `).run(user.id, hashedPassword); + + res.json({ message: 'Password reset request submitted. Awaiting Super Admin approval.' }); + } catch (error) { + res.status(500).json({ message: 'Failed to submit request', error: error.message }); + } +}; + +// GET /api/auth/reset-requests — super admin views pending requests +exports.getResetRequests = (req, res) => { + try { + const requests = db.prepare(` + SELECT r.id, r.status, r.requested_at, + u.id as user_id, u.username, u.first_name, u.last_name, u.role + FROM password_reset_requests r + JOIN users u ON r.user_id = u.id + WHERE r.status = 'pending' + ORDER BY r.requested_at ASC + `).all(); + res.json(requests); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch requests', error: error.message }); + } +}; + +// PUT /api/auth/reset-requests/:id/approve — super admin approves +exports.approveResetRequest = (req, res) => { + const { id } = req.params; + try { + const request = db.prepare("SELECT * FROM password_reset_requests WHERE id = ? AND status = 'pending'").get(id); + if (!request) return res.status(404).json({ message: 'Request not found or already reviewed.' }); + + db.prepare('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?') + .run(request.new_password_hash, request.user_id); + db.prepare(`UPDATE password_reset_requests SET status = 'approved', reviewed_at = CURRENT_TIMESTAMP, reviewed_by = ? WHERE id = ?`) + .run(req.user.id, id); + + res.json({ message: 'Password reset approved and applied.' }); + } catch (error) { + res.status(500).json({ message: 'Failed to approve request', error: error.message }); + } +}; + +// PUT /api/auth/reset-requests/:id/reject — super admin rejects +exports.rejectResetRequest = (req, res) => { + const { id } = req.params; + try { + const request = db.prepare("SELECT * FROM password_reset_requests WHERE id = ? AND status = 'pending'").get(id); + if (!request) return res.status(404).json({ message: 'Request not found or already reviewed.' }); + + db.prepare(`UPDATE password_reset_requests SET status = 'rejected', reviewed_at = CURRENT_TIMESTAMP, reviewed_by = ? WHERE id = ?`) + .run(req.user.id, id); + + res.json({ message: 'Password reset request rejected.' }); + } catch (error) { + res.status(500).json({ message: 'Failed to reject request', error: error.message }); + } +}; diff --git a/backend/src/controllers/dashboardController.js b/backend/src/controllers/dashboardController.js new file mode 100644 index 0000000..8e2d6de --- /dev/null +++ b/backend/src/controllers/dashboardController.js @@ -0,0 +1,37 @@ +const db = require('../config/db'); + +exports.getStats = (req, res) => { + try { + const totalStudents = db.prepare('SELECT COUNT(*) as count FROM students').get().count; + const printQueueCount = db.prepare('SELECT COUNT(*) as count FROM print_queue').get().count; + const pendingVerifications = db.prepare("SELECT COUNT(*) as count FROM documents WHERE status = 'Pending'").get().count; + const activeUsers = db.prepare('SELECT COUNT(*) as count FROM users').get().count; + + res.json({ + totalStudents, + printQueueCount, + pendingVerifications, + activeUsers + }); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch stats', error: error.message }); + } +}; + +exports.getPendingTasks = (req, res) => { + try { + // Pending tasks are documents that need verification + const pendingDocs = db.prepare(` + SELECT d.id, d.file_name, d.created_at, s.first_name, s.last_name + FROM documents d + JOIN students s ON d.student_id = s.id + WHERE d.status = 'Pending' + ORDER BY d.created_at DESC + LIMIT 10 + `).all(); + + res.json(pendingDocs); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch pending tasks', error: error.message }); + } +}; diff --git a/backend/src/controllers/documentController.js b/backend/src/controllers/documentController.js new file mode 100644 index 0000000..be84e18 --- /dev/null +++ b/backend/src/controllers/documentController.js @@ -0,0 +1,330 @@ +const db = require('../config/db'); +const multer = require('multer'); +const path = require('path'); +const fs = require('fs'); + +const STUDENT_DIR_ROOT = process.env.STUDENT_DIR_ROOT + ? path.resolve(process.env.STUDENT_DIR_ROOT) + : path.resolve(__dirname, '../../../data/students'); + +const sanitizeFolderName = (str) => + (str || '').replace(/[<>:"/\\|?*\x00-\x1F]/g, '').trim(); + +// Configure Multer +const storage = multer.diskStorage({ + destination: (req, file, cb) => { + // We expect studentId in req.body + const { studentId, documentType } = req.body; + + let uploadPath = process.env.UPLOAD_PATH ? path.resolve(process.env.UPLOAD_PATH) : path.resolve(__dirname, '../../../data/uploads'); + + if (studentId) { + try { + const student = db.prepare('SELECT lrn, first_name, last_name FROM students WHERE id = ?').get(studentId); + if (student) { + const folderName = `${sanitizeFolderName(student.last_name)}_${sanitizeFolderName(student.first_name)}_${student.lrn}`; + uploadPath = path.join(STUDENT_DIR_ROOT, folderName); + + if (documentType) { + uploadPath = path.join(uploadPath, sanitizeFolderName(documentType)); + } + } + } catch (err) { + console.error('Error fetching student for upload path:', err); + } + } + + if (!fs.existsSync(uploadPath)) { + fs.mkdirSync(uploadPath, { recursive: true }); + } + cb(null, uploadPath); + }, + filename: (req, file, cb) => { + cb(null, `${Date.now()}-${file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_')}`); + } +}); + +const upload = multer({ + storage, + limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit + fileFilter: (req, file, cb) => { + // Only allow certain file types + const allowedMimeTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg']; + if (allowedMimeTypes.includes(file.mimetype)) { + cb(null, true); + } else { + cb(new Error('Invalid file format. Only PDF, JPG, and PNG are allowed.'), false); + } + } +}); + +exports.uploadMiddleware = (req, res, next) => { + upload.single('document')(req, res, (err) => { + if (err) { + return res.status(400).json({ message: err.message }); + } + next(); + }); +}; + +exports.uploadDocument = (req, res) => { + const { studentId, requirementId, documentType } = req.body; + const file = req.file; + + if (!file) return res.status(400).json({ message: 'No file uploaded' }); + if (!studentId) return res.status(400).json({ message: 'Student ID is required' }); + if (!documentType) return res.status(400).json({ message: 'Document Type is required' }); + + try { + const reqId = requirementId && requirementId !== 'null' ? requirementId : null; + + const result = db.prepare(` + INSERT INTO documents (student_id, requirement_id, file_name, file_path, document_type, status, uploaded_by) + VALUES (?, ?, ?, ?, ?, 'Pending', ?) + `).run(studentId, reqId, file.originalname, file.path, documentType, req.user.id); + + res.status(201).json({ id: result.lastInsertRowid, message: 'Document uploaded successfully' }); + } catch (error) { + console.error('Upload Error:', error); + res.status(500).json({ message: 'Failed to upload document', error: error.message }); + } +}; + +exports.getAllDocuments = (req, res) => { + const { + search = '', + page = 1, + limit = 20, + status = '', + documentType = '', + gradeLevel = '', + schoolYear = '' + } = req.query; + + const pageNum = Math.max(1, parseInt(page)); + const limitNum = Math.min(100, Math.max(1, parseInt(limit))); + const offset = (pageNum - 1) * limitNum; + + try { + const conditions = []; + const params = []; + + if (search.trim()) { + const like = `%${search.trim()}%`; + conditions.push(`(s.lrn LIKE ? OR s.first_name LIKE ? OR s.last_name LIKE ? OR d.file_name LIKE ?)`); + params.push(like, like, like, like); + } + + if (status.trim() && status !== 'All Statuses') { + conditions.push(`d.status = ?`); + params.push(status.trim()); + } + + if (documentType.trim() && documentType !== 'All Types') { + conditions.push(`d.document_type = ?`); + params.push(documentType.trim()); + } + + if (gradeLevel.trim()) { + conditions.push(`e.grade_level = ?`); + params.push(gradeLevel.trim()); + } + + if (schoolYear.trim()) { + conditions.push(`ay.year_range = ?`); + params.push(schoolYear.trim()); + } + + const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''; + + const joins = ` + LEFT JOIN students s ON d.student_id = s.id + LEFT JOIN enrollments e ON s.id = e.student_id + LEFT JOIN academic_years ay ON e.academic_year_id = ay.id + `; + + const countSql = ` + SELECT COUNT(DISTINCT d.id) as total + FROM documents d + ${joins} + ${whereClause} + `; + const total = db.prepare(countSql).get(params).total; + + const fetchSql = ` + SELECT DISTINCT + d.id, d.student_id, d.file_name, d.document_type, d.status, d.created_at, d.file_path, + s.lrn as student_lrn, + s.first_name || ' ' || s.last_name as student_name + FROM documents d + ${joins} + ${whereClause} + ORDER BY d.created_at DESC + LIMIT ? OFFSET ? + `; + + const documents = db.prepare(fetchSql).all([...params, limitNum, offset]); + + const mappedDocs = documents.map(d => ({ + id: d.id, + studentId: d.student_id, + fileName: d.file_name, + documentType: d.document_type, + status: d.status, + createdAt: d.created_at, + studentLrn: d.student_lrn, + studentName: d.student_name, + size: 'Unknown', // Not storing size in DB right now + filePath: d.file_path + })); + + res.json({ + documents: mappedDocs, + pagination: { + total, + page: pageNum, + limit: limitNum, + totalPages: Math.ceil(total / limitNum) + } + }); + + } catch (error) { + console.error('getAllDocuments error:', error); + res.status(500).json({ message: 'Failed to fetch documents', error: error.message }); + } +}; + +exports.getRequirements = (req, res) => { + try { + const requirements = db.prepare('SELECT * FROM document_requirements ORDER BY name ASC').all(); + res.json(requirements); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch document requirements', error: error.message }); + } +}; + +exports.getDocumentsByStudent = (req, res) => { + try { + const documents = db.prepare(` + SELECT d.*, dr.name as requirement_name + FROM documents d + LEFT JOIN document_requirements dr ON d.requirement_id = dr.id + WHERE d.student_id = ? + `).all(req.params.studentId); + res.json(documents); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch documents', error: error.message }); + } +}; + +exports.updateStatus = (req, res) => { + const { status } = req.body; + if (!['Pending', 'Verified', 'Draft', 'Archived', 'Rejected'].includes(status)) { + return res.status(400).json({ message: 'Invalid status' }); + } + try { + db.prepare('UPDATE documents SET status = ? WHERE id = ?').run(status, req.params.id); + res.json({ message: 'Document status updated' }); + } catch (error) { + res.status(500).json({ message: 'Failed to update status', error: error.message }); + } +}; + +exports.deleteDocument = (req, res) => { + try { + const document = db.prepare('SELECT file_path FROM documents WHERE id = ?').get(req.params.id); + if (!document) return res.status(404).json({ message: 'Document not found' }); + + // Delete file from disk + if (fs.existsSync(document.file_path)) { + fs.unlinkSync(document.file_path); + } + + db.prepare('DELETE FROM documents WHERE id = ?').run(req.params.id); + res.json({ message: 'Document deleted successfully' }); + } catch (error) { + res.status(500).json({ message: 'Failed to delete document', error: error.message }); + } +}; + +// ============================================================ +// GET /api/documents/print-queue — get print queue for user +// ============================================================ +exports.getPrintQueue = (req, res) => { + try { + const userId = req.user.id; + const queue = db.prepare(` + SELECT pq.id as queue_id, pq.document_id, pq.added_at, + d.file_name, d.file_path, d.document_type, d.status, + s.first_name || ' ' || s.last_name as student_name, + s.lrn as student_lrn + FROM print_queue pq + JOIN documents d ON pq.document_id = d.id + LEFT JOIN students s ON d.student_id = s.id + WHERE pq.user_id = ? + ORDER BY pq.added_at DESC + `).all(userId); + res.json(queue); + } catch (error) { + console.error('getPrintQueue error:', error); + res.status(500).json({ message: 'Failed to fetch print queue', error: error.message }); + } +}; + +// ============================================================ +// POST /api/documents/print-queue — add document to print queue +// ============================================================ +exports.addToPrintQueue = (req, res) => { + const { documentId } = req.body; + const userId = req.user.id; + + if (!documentId) return res.status(400).json({ message: 'Document ID is required' }); + + try { + const document = db.prepare('SELECT id FROM documents WHERE id = ?').get(documentId); + if (!document) return res.status(404).json({ message: 'Document not found' }); + + // Check if already in queue for this user + const existing = db.prepare('SELECT id FROM print_queue WHERE document_id = ? AND user_id = ?').get(documentId, userId); + if (existing) { + return res.status(409).json({ message: 'Document already in print queue' }); + } + + const result = db.prepare('INSERT INTO print_queue (document_id, user_id) VALUES (?, ?)').run(documentId, userId); + res.status(201).json({ id: result.lastInsertRowid, message: 'Added to print queue' }); + } catch (error) { + console.error('addToPrintQueue error:', error); + res.status(500).json({ message: 'Failed to add to print queue', error: error.message }); + } +}; + +// ============================================================ +// DELETE /api/documents/print-queue/:queueId — remove from print queue +// ============================================================ +exports.removeFromPrintQueue = (req, res) => { + const { queueId } = req.params; + const userId = req.user.id; + try { + const item = db.prepare('SELECT id FROM print_queue WHERE id = ? AND user_id = ?').get(queueId, userId); + if (!item) return res.status(404).json({ message: 'Queue item not found' }); + db.prepare('DELETE FROM print_queue WHERE id = ?').run(queueId); + res.json({ message: 'Removed from print queue' }); + } catch (error) { + console.error('removeFromPrintQueue error:', error); + res.status(500).json({ message: 'Failed to remove from print queue', error: error.message }); + } +}; + +// ============================================================ +// DELETE /api/documents/print-queue — clear all from user's queue +// ============================================================ +exports.clearPrintQueue = (req, res) => { + const userId = req.user.id; + try { + db.prepare('DELETE FROM print_queue WHERE user_id = ?').run(userId); + res.json({ message: 'Print queue cleared' }); + } catch (error) { + console.error('clearPrintQueue error:', error); + res.status(500).json({ message: 'Failed to clear print queue', error: error.message }); + } +}; diff --git a/backend/src/controllers/folderController.js b/backend/src/controllers/folderController.js new file mode 100644 index 0000000..d278aba --- /dev/null +++ b/backend/src/controllers/folderController.js @@ -0,0 +1,347 @@ +const db = require('../config/db'); +const path = require('path'); +const fs = require('fs'); + +// Configurable student directory root +const STUDENT_DIR_ROOT = process.env.STUDENT_DIR_ROOT + ? path.resolve(process.env.STUDENT_DIR_ROOT) + : path.resolve(__dirname, '../../../data/students'); + +const sanitizeFolderName = (str) => + (str || '').replace(/[<>:"/\\|?*\x00-\x1F]/g, '').trim(); + +// ============================================================ +// GET /api/folders — list folders (manual + auto-created) +// ============================================================ +exports.getFolders = (req, res) => { + const { studentId, parentId, search = '' } = req.query; + + try { + const conditions = []; + const params = []; + + if (studentId) { + conditions.push('student_id = ?'); + params.push(studentId); + } + + if (parentId !== undefined) { + if (parentId === 'null' || parentId === '') { + conditions.push('parent_id IS NULL'); + } else { + conditions.push('parent_id = ?'); + params.push(parseInt(parentId)); + } + } + + if (search.trim()) { + conditions.push('name LIKE ?'); + params.push(`%${search.trim()}%`); + } + + const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''; + + const sql = ` + SELECT f.*, + s.lrn, s.first_name, s.last_name, + u.username as created_by_username, + (SELECT COUNT(*) FROM documents d WHERE d.student_id = f.student_id) as document_count + FROM document_folders f + LEFT JOIN students s ON f.student_id = s.id + LEFT JOIN users u ON f.created_by = u.id + ${whereClause} + ORDER BY f.name ASC + `; + + const folders = db.prepare(sql).all(params); + res.json(folders); + } catch (error) { + console.error('getFolders error:', error); + res.status(500).json({ message: 'Failed to fetch folders', error: error.message }); + } +}; + +// ============================================================ +// POST /api/folders — create manual folder +// ============================================================ +exports.createFolder = (req, res) => { + const { name, parentId, studentId, category } = req.body; + const userId = req.user.id; + + if (!name || !name.trim()) { + return res.status(400).json({ message: 'Folder name is required' }); + } + + // Validate: either studentId or parentId must be provided + if (!studentId && !parentId) { + return res.status(400).json({ message: 'Either student_id or parent_id is required' }); + } + + // Check for duplicate folder name in same scope + let duplicateCheckSql = ''; + let duplicateParams = []; + + if (studentId) { + duplicateCheckSql = 'SELECT id FROM document_folders WHERE name = ? AND student_id = ? AND parent_id IS NULL'; + duplicateParams = [name.trim(), studentId]; + } else if (parentId) { + duplicateCheckSql = 'SELECT id FROM document_folders WHERE name = ? AND parent_id = ?'; + duplicateParams = [name.trim(), parentId]; + } + + const existing = db.prepare(duplicateCheckSql).get(...duplicateParams); + if (existing) { + return res.status(409).json({ message: 'A folder with this name already exists in this location' }); + } + + try { + // Create in database + const result = db.prepare(` + INSERT INTO document_folders (name, parent_id, student_id, category, created_by) + VALUES (?, ?, ?, ?, ?) + `).run( + name.trim(), + parentId ? parseInt(parentId) : null, + studentId ? parseInt(studentId) : null, + category || null, + userId + ); + + // Optionally create physical folder if it relates to a student + if (studentId) { + const student = db.prepare('SELECT lrn, first_name, last_name FROM students WHERE id = ?').get(studentId); + if (student) { + const folderName = `${sanitizeFolderName(student.last_name)}_${sanitizeFolderName(student.first_name)}_${student.lrn}`; + const basePath = path.join(STUDENT_DIR_ROOT, folderName); + + // Create category subfolder if category provided + let folderPath = basePath; + if (category) { + folderPath = path.join(basePath, sanitizeFolderName(category)); + } + + // Create parent path first + if (!fs.existsSync(basePath)) { + fs.mkdirSync(basePath, { recursive: true }); + } + + if (!fs.existsSync(folderPath)) { + fs.mkdirSync(folderPath, { recursive: true }); + } + } + } + + res.status(201).json({ + id: result.lastInsertRowid, + message: 'Folder created successfully' + }); + } catch (error) { + console.error('createFolder error:', error); + res.status(500).json({ message: 'Failed to create folder', error: error.message }); + } +}; + +// ============================================================ +// PUT /api/folders/:id — rename folder +// ============================================================ +exports.renameFolder = (req, res) => { + const { id } = req.params; + const { name } = req.body; + + if (!name || !name.trim()) { + return res.status(400).json({ message: 'New folder name is required' }); + } + + const folder = db.prepare('SELECT * FROM document_folders WHERE id = ?').get(id); + if (!folder) { + return res.status(404).json({ message: 'Folder not found' }); + } + + // Check for duplicate in same scope + let duplicateCheckSql = ''; + let duplicateParams = []; + + if (folder.parent_id) { + duplicateCheckSql = 'SELECT id FROM document_folders WHERE name = ? AND parent_id = ? AND id != ?'; + duplicateParams = [name.trim(), folder.parent_id, id]; + } else if (folder.student_id) { + duplicateCheckSql = 'SELECT id FROM document_folders WHERE name = ? AND student_id = ? AND parent_id IS NULL AND id != ?'; + duplicateParams = [name.trim(), folder.student_id, id]; + } + + if (duplicateCheckSql) { + const existing = db.prepare(duplicateCheckSql).get(...duplicateParams); + if (existing) { + return res.status(409).json({ message: 'A folder with this name already exists in this location' }); + } + } + + try { + db.prepare(` + UPDATE document_folders SET name = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? + `).run(name.trim(), id); + + res.json({ message: 'Folder renamed successfully' }); + } catch (error) { + console.error('renameFolder error:', error); + res.status(500).json({ message: 'Failed to rename folder', error: error.message }); + } +}; + +// ============================================================ +// DELETE /api/folders/:id — delete folder +// ============================================================ +exports.deleteFolder = (req, res) => { + const { id } = req.params; + + const folder = db.prepare('SELECT * FROM document_folders WHERE id = ?').get(id); + if (!folder) { + return res.status(404).json({ message: 'Folder not found' }); + } + + // Check if folder has children + const children = db.prepare('SELECT COUNT(*) as count FROM document_folders WHERE parent_id = ?').get(id); + if (children.count > 0) { + return res.status(400).json({ message: 'Cannot delete folder with subfolders' }); + } + + try { + db.prepare('DELETE FROM document_folders WHERE id = ?').run(id); + res.json({ message: 'Folder deleted successfully' }); + } catch (error) { + console.error('deleteFolder error:', error); + res.status(500).json({ message: 'Failed to delete folder', error: error.message }); + } +}; + +// ============================================================ +// GET /api/folders/student/:studentId — get student document folder +// ============================================================ +exports.getStudentFolder = (req, res) => { + const { studentId } = req.params; + + try { + const student = db.prepare('SELECT * FROM students WHERE id = ?').get(studentId); + if (!student) { + return res.status(404).json({ message: 'Student not found' }); + } + + // Get or create student folder record + let folder = db.prepare(` + SELECT * FROM document_folders + WHERE student_id = ? AND parent_id IS NULL + `).get(studentId); + + if (!folder) { + // Auto-create folder record + const folderName = `${student.last_name}_${student.first_name}_${student.lrn}`; + const result = db.prepare(` + INSERT INTO document_folders (name, student_id, category, created_by) + VALUES (?, ?, 'root', NULL) + `).run(folderName, studentId); + + folder = { + id: result.lastInsertRowid, + name: folderName, + student_id: studentId, + category: 'root' + }; + } + + // Get all subfolders for this student + const subfolders = db.prepare(` + SELECT * FROM document_folders + WHERE student_id = ? AND parent_id IS NOT NULL + ORDER BY name ASC + `).all(studentId); + + // Get physical folder contents + const folderPath = path.join(STUDENT_DIR_ROOT, + `${sanitizeFolderName(student.last_name)}_${sanitizeFolderName(student.first_name)}_${student.lrn}`); + + let physicalFolders = []; + let physicalFiles = []; + + if (fs.existsSync(folderPath)) { + const entries = fs.readdirSync(folderPath, { withFileTypes: true }); + physicalFolders = entries + .filter(e => e.isDirectory()) + .map(e => ({ name: e.name, isDirectory: true })); + physicalFiles = entries + .filter(e => e.isFile()) + .map(e => ({ name: e.name, isDirectory: false })); + } + + res.json({ + ...folder, + student: { + id: student.id, + lrn: student.lrn, + firstName: student.first_name, + lastName: student.last_name + }, + subfolders, + physicalFolders, + physicalFiles, + folderPath + }); + } catch (error) { + console.error('getStudentFolder error:', error); + res.status(500).json({ message: 'Failed to get student folder', error: error.message }); + } +}; + +// ============================================================ +// POST /api/folders/sync — sync DB folders with physical storage +// ============================================================ +exports.syncFolders = (req, res) => { + const { studentId } = req.body; + + try { + const student = db.prepare('SELECT * FROM students WHERE id = ?').get(studentId); + if (!student) { + return res.status(404).json({ message: 'Student not found' }); + } + + const folderPath = path.join(STUDENT_DIR_ROOT, + `${sanitizeFolderName(student.last_name)}_${sanitizeFolderName(student.first_name)}_${student.lrn}`); + + if (!fs.existsSync(folderPath)) { + fs.mkdirSync(folderPath, { recursive: true }); + } + + // Read physical folders + const entries = fs.readdirSync(folderPath, { withFileTypes: true }); + const physicalDirs = entries.filter(e => e.isDirectory()).map(e => e.name); + + // Get existing DB folders for this student + const existingFolders = db.prepare(` + SELECT name FROM document_folders + WHERE student_id = ? AND parent_id IS NOT NULL + `).all(studentId); + const dbFolderNames = new Set(existingFolders.map(f => f.name)); + + // Add missing folders to DB + const newFolders = []; + for (const dirName of physicalDirs) { + if (!dbFolderNames.has(dirName)) { + // Determine category from folder name or use folder name + const category = dirName; + db.prepare(` + INSERT INTO document_folders (name, student_id, category, created_by) + VALUES (?, ?, ?, NULL) + `).run(dirName, studentId, category); + newFolders.push(dirName); + } + } + + res.json({ + message: 'Folders synced successfully', + newFolders, + totalFolders: physicalDirs.length + }); + } catch (error) { + console.error('syncFolders error:', error); + res.status(500).json({ message: 'Failed to sync folders', error: error.message }); + } +}; \ No newline at end of file diff --git a/backend/src/controllers/gradeController.js b/backend/src/controllers/gradeController.js new file mode 100644 index 0000000..918fe2c --- /dev/null +++ b/backend/src/controllers/gradeController.js @@ -0,0 +1,82 @@ +const db = require('../config/db'); + +exports.enrollStudent = (req, res) => { + const { studentId, academicYearId, sectionId, gradeLevel, trackStrand } = req.body; + try { + const result = db.prepare(` + INSERT INTO enrollments (student_id, academic_year_id, section_id, grade_level, track_strand) + VALUES (?, ?, ?, ?, ?) + `).run(studentId, academicYearId, sectionId, gradeLevel, trackStrand); + res.status(201).json({ id: result.lastInsertRowid, message: 'Student enrolled successfully' }); + } catch (error) { + res.status(500).json({ message: 'Enrollment failed', error: error.message }); + } +}; + +exports.getGradesByEnrollment = (req, res) => { + try { + const grades = db.prepare(` + SELECT g.*, s.title, s.code, s.category + FROM grades g + JOIN subjects s ON g.subject_id = s.id + WHERE g.enrollment_id = ? + `).all(req.params.enrollmentId); + res.json(grades); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch grades', error: error.message }); + } +}; + +exports.updateGrades = (req, res) => { + const { enrollmentId, subjectId, q1, q2, q3, q4, sem1, sem2, finalGrade, remarks } = req.body; + try { + const existing = db.prepare('SELECT id FROM grades WHERE enrollment_id = ? AND subject_id = ?').get(enrollmentId, subjectId); + + if (existing) { + db.prepare(` + UPDATE grades + SET q1 = ?, q2 = ?, q3 = ?, q4 = ?, sem1 = ?, sem2 = ?, final_grade = ?, remarks = ? + WHERE id = ? + `).run(q1, q2, q3, q4, sem1, sem2, finalGrade, remarks, existing.id); + } else { + db.prepare(` + INSERT INTO grades (enrollment_id, subject_id, q1, q2, q3, q4, sem1, sem2, final_grade, remarks) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(enrollmentId, subjectId, q1, q2, q3, q4, sem1, sem2, finalGrade, remarks); + } + res.json({ message: 'Grades updated successfully' }); + } catch (error) { + res.status(500).json({ message: 'Failed to update grades', error: error.message }); + } +}; + +exports.getSF10Data = (req, res) => { + const { studentId } = req.params; + try { + const student = db.prepare('SELECT * FROM students WHERE id = ?').get(studentId); + if (!student) return res.status(404).json({ message: 'Student not found' }); + + const enrollments = db.prepare(` + SELECT e.*, ay.year_range, s.name as section_name + FROM enrollments e + JOIN academic_years ay ON e.academic_year_id = ay.id + JOIN sections s ON e.section_id = s.id + WHERE e.student_id = ? + ORDER BY e.grade_level ASC + `).all(studentId); + + const data = enrollments.map(enrollment => { + const grades = db.prepare(` + SELECT g.*, sub.title, sub.code, sub.category + FROM grades g + JOIN subjects sub ON g.subject_id = sub.id + WHERE g.enrollment_id = ? + `).all(enrollment.id); + return { ...enrollment, grades }; + }); + + res.json({ student, history: data }); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch SF10 data', error: error.message }); + } +}; diff --git a/backend/src/controllers/reportsController.js b/backend/src/controllers/reportsController.js new file mode 100644 index 0000000..13dde68 --- /dev/null +++ b/backend/src/controllers/reportsController.js @@ -0,0 +1,145 @@ +const db = require('../config/db'); + +// GET /api/reports/academic-years +exports.getAcademicYears = (req, res) => { + try { + const years = db.prepare('SELECT * FROM academic_years ORDER BY id DESC').all(); + res.json(years); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch academic years', error: error.message }); + } +}; + +// GET /api/reports/stats?academicYearId=1 +exports.getStats = (req, res) => { + const { academicYearId } = req.query; + try { + let totalStudents; + if (academicYearId) { + totalStudents = db.prepare( + 'SELECT COUNT(DISTINCT student_id) as count FROM enrollments WHERE academic_year_id = ?' + ).get(academicYearId).count; + } else { + totalStudents = db.prepare('SELECT COUNT(*) as count FROM students').get().count; + } + + const pendingDocs = db.prepare("SELECT COUNT(*) as count FROM documents WHERE status = 'Pending'").get().count; + const verifiedDocs = db.prepare("SELECT COUNT(*) as count FROM documents WHERE status = 'Verified'").get().count; + const printQueueCount = db.prepare('SELECT COUNT(*) as count FROM print_queue').get().count; + const totalDocs = pendingDocs + verifiedDocs; + const verificationRate = totalDocs > 0 ? Math.round((verifiedDocs / totalDocs) * 100) : 0; + + res.json({ totalStudents, pendingDocs, verifiedDocs, printQueueCount, verificationRate }); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch report stats', error: error.message }); + } +}; + +// GET /api/reports/enrollment-by-grade?academicYearId=1 +exports.getEnrollmentByGrade = (req, res) => { + const { academicYearId } = req.query; + try { + let rows; + if (academicYearId) { + rows = db.prepare(` + SELECT grade_level, COUNT(*) as count + FROM enrollments + WHERE academic_year_id = ? + GROUP BY grade_level + ORDER BY grade_level ASC + `).all(academicYearId); + } else { + rows = db.prepare(` + SELECT grade_level, COUNT(*) as count + FROM enrollments + GROUP BY grade_level + ORDER BY grade_level ASC + `).all(); + } + res.json(rows); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch enrollment data', error: error.message }); + } +}; + +// GET /api/reports/document-status +exports.getDocumentStatus = (req, res) => { + try { + const rows = db.prepare(` + SELECT status, COUNT(*) as count FROM documents GROUP BY status + `).all(); + const result = { Pending: 0, Verified: 0, Draft: 0, Archived: 0 }; + rows.forEach(r => { result[r.status] = r.count; }); + res.json(result); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch document status', error: error.message }); + } +}; + +// GET /api/reports/export-data?academicYearId=1 — Full data payload for Excel export +exports.getExportData = (req, res) => { + const { academicYearId } = req.query; + try { + // Enrollment summary per grade level + let enrollmentByGrade; + if (academicYearId) { + enrollmentByGrade = db.prepare(` + SELECT e.grade_level, COUNT(DISTINCT e.student_id) as total_students, + ay.year_range + FROM enrollments e + JOIN academic_years ay ON e.academic_year_id = ay.id + WHERE e.academic_year_id = ? + GROUP BY e.grade_level + ORDER BY e.grade_level ASC + `).all(academicYearId); + } else { + enrollmentByGrade = db.prepare(` + SELECT e.grade_level, COUNT(DISTINCT e.student_id) as total_students, + 'All Years' as year_range + FROM enrollments e + GROUP BY e.grade_level + ORDER BY e.grade_level ASC + `).all(); + } + + // Document status breakdown + const docStatusRows = db.prepare(` + SELECT status, COUNT(*) as count FROM documents GROUP BY status + `).all(); + const documentStatus = { Pending: 0, Verified: 0, Draft: 0, Archived: 0 }; + docStatusRows.forEach(r => { documentStatus[r.status] = r.count; }); + + // Student detail list with document compliance + let students; + if (academicYearId) { + students = db.prepare(` + SELECT s.lrn, s.first_name, s.last_name, s.sex, e.grade_level, + COUNT(CASE WHEN d.status = 'Verified' THEN 1 END) as verified_docs, + COUNT(CASE WHEN d.status = 'Pending' THEN 1 END) as pending_docs + FROM students s + JOIN enrollments e ON s.id = e.student_id AND e.academic_year_id = ? + LEFT JOIN documents d ON s.id = d.student_id + GROUP BY s.id + ORDER BY s.last_name ASC + LIMIT 500 + `).all(academicYearId); + } else { + students = db.prepare(` + SELECT s.lrn, s.first_name, s.last_name, s.sex, + MAX(e.grade_level) as grade_level, + COUNT(CASE WHEN d.status = 'Verified' THEN 1 END) as verified_docs, + COUNT(CASE WHEN d.status = 'Pending' THEN 1 END) as pending_docs + FROM students s + LEFT JOIN enrollments e ON s.id = e.student_id + LEFT JOIN documents d ON s.id = d.student_id + GROUP BY s.id + ORDER BY s.last_name ASC + LIMIT 500 + `).all(); + } + + res.json({ enrollmentByGrade, documentStatus, students }); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch export data', error: error.message }); + } +}; diff --git a/backend/src/controllers/requirementController.js b/backend/src/controllers/requirementController.js new file mode 100644 index 0000000..f1f742c --- /dev/null +++ b/backend/src/controllers/requirementController.js @@ -0,0 +1,358 @@ +const db = require('../config/db'); + +// ============================================================ +// GET /api/requirements — get all document requirements +// ============================================================ +exports.getRequirements = (req, res) => { + const { category, isMandatory, isEnabled, search = '' } = req.query; + + try { + const conditions = []; + const params = []; + + if (category) { + conditions.push('category = ?'); + params.push(category); + } + + if (isEnabled !== undefined && isEnabled !== '') { + conditions.push('is_enabled = ?'); + params.push(isEnabled === 'true' ? 1 : 0); + } + + if (isMandatory !== undefined && isMandatory !== '') { + conditions.push('is_mandatory = ?'); + params.push(isMandatory === 'true' ? 1 : 0); + } + + if (search.trim()) { + conditions.push('(name LIKE ? OR description LIKE ?)'); + params.push(`%${search.trim()}%`, `%${search.trim()}%`); + } + + const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''; + + const sql = ` + SELECT * FROM document_requirements + ${whereClause} + ORDER BY category ASC, name ASC + `; + + const requirements = db.prepare(sql).all(params); + res.json(requirements); + } catch (error) { + console.error('getRequirements error:', error); + res.status(500).json({ message: 'Failed to fetch requirements', error: error.message }); + } +}; + +// ============================================================ +// GET /api/requirements/:id — get single requirement +// ============================================================ +exports.getRequirementById = (req, res) => { + try { + const requirement = db.prepare('SELECT * FROM document_requirements WHERE id = ?').get(req.params.id); + if (!requirement) { + return res.status(404).json({ message: 'Requirement not found' }); + } + res.json(requirement); + } catch (error) { + console.error('getRequirementById error:', error); + res.status(500).json({ message: 'Failed to fetch requirement', error: error.message }); + } +}; + +// ============================================================ +// POST /api/requirements — create new requirement (Super Admin) +// ============================================================ +exports.createRequirement = (req, res) => { + const { + name, + description, + category, + isMandatory = true, + isEnabled = true, + dueDate, + acceptedFileTypes = 'pdf,jpg,jpeg,png', + schoolLevels = 'JHS,SHS' + } = req.body; + + // Validation + const errors = []; + if (!name || !name.trim()) errors.push('Name is required'); + if (!category || !['JHS', 'SHS'].includes(category)) errors.push('Category must be JHS or SHS'); + + if (errors.length) { + return res.status(400).json({ message: errors[0], errors }); + } + + // Check duplicate + const existing = db.prepare('SELECT id FROM document_requirements WHERE name = ? AND category = ?') + .get(name.trim(), category); + if (existing) { + return res.status(409).json({ message: 'A requirement with this name already exists for this category' }); + } + + try { + const result = db.prepare(` + INSERT INTO document_requirements ( + name, description, category, is_mandatory, is_enabled, + due_date, accepted_file_types, school_levels + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `).run( + name.trim(), + description?.trim() || null, + category, + isMandatory ? 1 : 0, + isEnabled ? 1 : 0, + dueDate || null, + acceptedFileTypes, + schoolLevels + ); + + res.status(201).json({ + id: result.lastInsertRowid, + message: 'Requirement created successfully' + }); + } catch (error) { + console.error('createRequirement error:', error); + res.status(500).json({ message: 'Failed to create requirement', error: error.message }); + } +}; + +// ============================================================ +// PUT /api/requirements/:id — update requirement (Super Admin) +// ============================================================ +exports.updateRequirement = (req, res) => { + const { id } = req.params; + const { + name, + description, + category, + isMandatory, + isEnabled, + dueDate, + acceptedFileTypes, + schoolLevels + } = req.body; + + const requirement = db.prepare('SELECT * FROM document_requirements WHERE id = ?').get(id); + if (!requirement) { + return res.status(404).json({ message: 'Requirement not found' }); + } + + // Check duplicate if name or category changed + if ((name && name.trim() !== requirement.name) || (category && category !== requirement.category)) { + const duplicate = db.prepare('SELECT id FROM document_requirements WHERE name = ? AND category = ? AND id != ?') + .get(name?.trim() || requirement.name, category || requirement.category, id); + if (duplicate) { + return res.status(409).json({ message: 'A requirement with this name already exists for this category' }); + } + } + + try { + db.prepare(` + UPDATE document_requirements SET + name = COALESCE(?, name), + description = COALESCE(?, description), + category = COALESCE(?, category), + is_mandatory = COALESCE(?, is_mandatory), + is_enabled = COALESCE(?, is_enabled), + due_date = ?, + accepted_file_types = COALESCE(?, accepted_file_types), + school_levels = COALESCE(?, school_levels), + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `).run( + name?.trim(), + description?.trim(), + category, + isMandatory !== undefined ? (isMandatory ? 1 : 0) : null, + isEnabled !== undefined ? (isEnabled ? 1 : 0) : null, + dueDate, + acceptedFileTypes, + schoolLevels, + id + ); + + res.json({ message: 'Requirement updated successfully' }); + } catch (error) { + console.error('updateRequirement error:', error); + res.status(500).json({ message: 'Failed to update requirement', error: error.message }); + } +}; + +// ============================================================ +// DELETE /api/requirements/:id — delete requirement (Super Admin) +// ============================================================ +exports.deleteRequirement = (req, res) => { + const { id } = req.params; + + const requirement = db.prepare('SELECT * FROM document_requirements WHERE id = ?').get(id); + if (!requirement) { + return res.status(404).json({ message: 'Requirement not found' }); + } + + // Check if any documents are linked to this requirement + const linkedDocs = db.prepare('SELECT COUNT(*) as count FROM documents WHERE requirement_id = ?').get(id); + if (linkedDocs.count > 0) { + return res.status(400).json({ + message: 'Cannot delete requirement that has documents attached. Please remove linked documents first.' + }); + } + + try { + db.prepare('DELETE FROM document_requirements WHERE id = ?').run(id); + res.json({ message: 'Requirement deleted successfully' }); + } catch (error) { + console.error('deleteRequirement error:', error); + res.status(500).json({ message: 'Failed to delete requirement', error: error.message }); + } +}; + +// ============================================================ +// GET /api/requirements/settings — get requirements for settings panel +// ============================================================ +exports.getRequirementsSettings = (req, res) => { + try { + // Get JHS requirements + const jhsRequirements = db.prepare(` + SELECT * FROM document_requirements + WHERE category = 'JHS' + ORDER BY name ASC + `).all(); + + // Get SHS requirements + const shsRequirements = db.prepare(` + SELECT * FROM document_requirements + WHERE category = 'SHS' + ORDER BY name ASC + `).all(); + + // Get document types for dropdown + const documentTypes = db.prepare(` + SELECT DISTINCT name FROM document_requirements + ORDER BY name ASC + `).all(); + + res.json({ + jhs: jhsRequirements, + shs: shsRequirements, + documentTypes: documentTypes.map(d => d.name) + }); + } catch (error) { + console.error('getRequirementsSettings error:', error); + res.status(500).json({ message: 'Failed to fetch settings', error: error.message }); + } +}; + +// ============================================================ +// PUT /api/requirements/bulk — bulk update requirements (Super Admin) +// ============================================================ +exports.bulkUpdateRequirements = (req, res) => { + const { requirements } = req.body; + + if (!Array.isArray(requirements) || requirements.length === 0) { + return res.status(400).json({ message: 'Requirements array is required' }); + } + + try { + const updateStmt = db.prepare(` + UPDATE document_requirements SET + is_mandatory = ?, + is_enabled = ?, + due_date = ?, + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `); + + db.transaction(() => { + for (const req of requirements) { + if (req.id) { + updateStmt.run( + req.isMandatory ? 1 : 0, + req.isEnabled ? 1 : 0, + req.dueDate || null, + req.id + ); + } + } + })(); + + res.json({ message: 'Requirements updated successfully' }); + } catch (error) { + console.error('bulkUpdateRequirements error:', error); + res.status(500).json({ message: 'Failed to bulk update requirements', error: error.message }); + } +}; + +// ============================================================ +// GET /api/requirements/missing/:studentId — get missing requirements for student +// ============================================================ +exports.getMissingRequirements = (req, res) => { + const { studentId } = req.params; + + try { + // Get student's current grade level + const enrollment = db.prepare(` + SELECT grade_level FROM enrollments + WHERE student_id = ? + ORDER BY id DESC LIMIT 1 + `).get(studentId); + + if (!enrollment) { + return res.status(404).json({ message: 'Student has no enrollment records' }); + } + + const category = enrollment.grade_level <= 10 ? 'JHS' : 'SHS'; + + // Get mandatory requirements not yet fulfilled + const missing = db.prepare(` + SELECT dr.* FROM document_requirements dr + WHERE dr.category = ? + AND dr.is_mandatory = 1 + AND dr.is_enabled = 1 + AND dr.id NOT IN ( + SELECT requirement_id FROM documents + WHERE student_id = ? AND status = 'Verified' AND requirement_id IS NOT NULL + ) + ORDER BY dr.name ASC + `).all(category, studentId); + + // Get requirements with documents but not verified + const pending = db.prepare(` + SELECT dr.*, d.id as doc_id, d.file_name, d.status as doc_status + FROM document_requirements dr + JOIN documents d ON d.requirement_id = dr.id + WHERE dr.category = ? + AND d.student_id = ? + AND d.status != 'Verified' + ORDER BY dr.name ASC + `).all(category, studentId); + + // Get all verified documents + const verified = db.prepare(` + SELECT dr.*, d.id as doc_id, d.file_name + FROM document_requirements dr + JOIN documents d ON d.requirement_id = dr.id + WHERE dr.category = ? + AND d.student_id = ? + AND d.status = 'Verified' + ORDER BY dr.name ASC + `).all(category, studentId); + + res.json({ + category, + gradeLevel: enrollment.grade_level, + missing, + pending, + verified, + totalRequired: missing.length + pending.length, + totalVerified: verified.length + }); + } catch (error) { + console.error('getMissingRequirements error:', error); + res.status(500).json({ message: 'Failed to fetch missing requirements', error: error.message }); + } +}; \ No newline at end of file diff --git a/backend/src/controllers/setupController.js b/backend/src/controllers/setupController.js new file mode 100644 index 0000000..4b0ba62 --- /dev/null +++ b/backend/src/controllers/setupController.js @@ -0,0 +1,40 @@ +const db = require('../config/db'); + +exports.getAllAcademicYears = (req, res) => { + try { + const years = db.prepare('SELECT * FROM academic_years ORDER BY year_range DESC').all(); + res.json(years); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch academic years', error: error.message }); + } +}; + +exports.createAcademicYear = (req, res) => { + const { yearRange } = req.body; + try { + const result = db.prepare('INSERT INTO academic_years (year_range) VALUES (?)').run(yearRange); + res.status(201).json({ id: result.lastInsertRowid, message: 'Academic year created' }); + } catch (error) { + res.status(500).json({ message: 'Failed to create academic year', error: error.message }); + } +}; + +exports.getSectionsByYear = (req, res) => { + try { + const sections = db.prepare('SELECT * FROM sections WHERE academic_year_id = ?').all(req.params.yearId); + res.json(sections); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch sections', error: error.message }); + } +}; + +exports.createSection = (req, res) => { + const { name, gradeLevel, academicYearId } = req.body; + try { + const result = db.prepare('INSERT INTO sections (name, grade_level, academic_year_id) VALUES (?, ?, ?)') + .run(name, gradeLevel, academicYearId); + res.status(201).json({ id: result.lastInsertRowid, message: 'Section created' }); + } catch (error) { + res.status(500).json({ message: 'Failed to create section', error: error.message }); + } +}; diff --git a/backend/src/controllers/studentController.js b/backend/src/controllers/studentController.js new file mode 100644 index 0000000..f852c71 --- /dev/null +++ b/backend/src/controllers/studentController.js @@ -0,0 +1,304 @@ +const db = require('../config/db'); +const fs = require('fs'); +const path = require('path'); + +// ============================================================ +// CONFIG — student directory root (configurable via .env) +// ============================================================ +const STUDENT_DIR_ROOT = process.env.STUDENT_DIR_ROOT + ? path.resolve(process.env.STUDENT_DIR_ROOT) + : path.resolve(__dirname, '../../../data/students'); + +// ============================================================ +// HELPER — sanitize a string for use in a folder name +// ============================================================ +const sanitizeFolderName = (str) => + (str || '').replace(/[<>:"/\\|?*\x00-\x1F]/g, '').trim(); + +// ============================================================ +// HELPER — validate LRN (exactly 12 digits) +// ============================================================ +const isValidLRN = (lrn) => /^\d{12}$/.test((lrn || '').trim()); + +// ============================================================ +// GET /api/students — paginated, searchable, filterable +// ============================================================ +exports.getAllStudents = (req, res) => { + const { + search = '', + page = 1, + limit = 10, + gradeLevel = '', // e.g. "7", "8", ... "12" + status = '', // e.g. "Enrolled" + } = req.query; + + const pageNum = Math.max(1, parseInt(page)); + const limitNum = Math.min(100, Math.max(1, parseInt(limit))); + const offset = (pageNum - 1) * limitNum; + + try { + // ---- Build WHERE clauses ---- + const conditions = []; + const params = []; + + if (search.trim()) { + const like = `%${search.trim()}%`; + conditions.push(`(s.lrn LIKE ? OR s.first_name LIKE ? OR s.last_name LIKE ? OR s.middle_name LIKE ?)`); + params.push(like, like, like, like); + } + + if (status.trim()) { + conditions.push(`s.status = ?`); + params.push(status.trim()); + } + + // grade_level lives in enrollments (latest) + const gradeJoin = gradeLevel.trim() + ? `JOIN enrollments e_latest ON e_latest.student_id = s.id + AND e_latest.id = (SELECT MAX(id) FROM enrollments WHERE student_id = s.id)` + : ''; + if (gradeLevel.trim()) { + conditions.push(`e_latest.grade_level = ?`); + params.push(parseInt(gradeLevel)); + } + + const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''; + + // ---- Count query ---- + const countSql = ` + SELECT COUNT(DISTINCT s.id) as total + FROM students s + ${gradeJoin} + ${whereClause} + `; + const total = db.prepare(countSql).get(params).total; + + // ---- Fetch query ---- + const fetchSql = ` + SELECT DISTINCT + s.id, s.lrn, s.first_name, s.middle_name, s.last_name, + s.extension, s.sex, s.birth_date, s.status, s.created_at, + ( + SELECT grade_level FROM enrollments + WHERE student_id = s.id ORDER BY id DESC LIMIT 1 + ) as latest_grade_level, + ( + SELECT sec.name FROM enrollments enr + JOIN sections sec ON sec.id = enr.section_id + WHERE enr.student_id = s.id ORDER BY enr.id DESC LIMIT 1 + ) as latest_section + FROM students s + ${gradeJoin} + ${whereClause} + ORDER BY s.last_name ASC, s.first_name ASC + LIMIT ? OFFSET ? + `; + + const students = db.prepare(fetchSql).all([...params, limitNum, offset]); + + // ---- Attach missingDocumentsCount badge ---- + const studentsWithBadges = students.map(student => { + const missingDocs = db.prepare(` + SELECT COUNT(*) as count + FROM document_requirements dr + WHERE dr.is_mandatory = 1 + AND dr.category = ( + SELECT CASE WHEN grade_level <= 10 THEN 'JHS' ELSE 'SHS' END + FROM enrollments WHERE student_id = ? ORDER BY id DESC LIMIT 1 + ) + AND dr.id NOT IN ( + SELECT requirement_id FROM documents + WHERE student_id = ? AND status = 'Verified' AND requirement_id IS NOT NULL + ) + `).get(student.id, student.id)?.count ?? 0; + + return { ...student, missingDocumentsCount: missingDocs }; + }); + + res.json({ + students: studentsWithBadges, + pagination: { + total, + page: pageNum, + limit: limitNum, + totalPages: Math.ceil(total / limitNum), + }, + }); + } catch (error) { + console.error('getAllStudents error:', error); + res.status(500).json({ message: 'Failed to fetch students', error: error.message }); + } +}; + +// ============================================================ +// GET /api/students/:id — single student with enrollments +// ============================================================ +exports.getStudentById = (req, res) => { + try { + const student = db.prepare('SELECT * FROM students WHERE id = ?').get(req.params.id); + if (!student) return res.status(404).json({ message: 'Student not found' }); + + const enrollments = db.prepare(` + SELECT e.*, ay.year_range, sec.name as section_name + FROM enrollments e + JOIN academic_years ay ON e.academic_year_id = ay.id + JOIN sections sec ON e.section_id = sec.id + WHERE e.student_id = ? + ORDER BY e.id DESC + `).all(student.id); + + res.json({ ...student, enrollments }); + } catch (error) { + console.error('getStudentById error:', error); + res.status(500).json({ message: 'Failed to fetch student details', error: error.message }); + } +}; + +// ============================================================ +// POST /api/students — create + auto-create directory +// ============================================================ +exports.createStudent = (req, res) => { + const { lrn, firstName, middleName, lastName, extension, sex, birthDate } = req.body; + + // ---- Server-side validation ---- + const errors = []; + if (!lrn || !isValidLRN(lrn)) errors.push('LRN must be exactly 12 digits.'); + if (!firstName || !firstName.trim()) errors.push('First name is required.'); + if (!lastName || !lastName.trim()) errors.push('Last name is required.'); + if (!sex || !['Male', 'Female'].includes(sex)) errors.push('Sex must be Male or Female.'); + if (!birthDate) errors.push('Date of birth is required.'); + else { + const dob = new Date(birthDate); + if (isNaN(dob.getTime())) errors.push('Invalid date of birth format.'); + else if (dob > new Date()) errors.push('Date of birth cannot be in the future.'); + } + if (errors.length) return res.status(400).json({ message: errors[0], errors }); + + // ---- Duplicate LRN check ---- + const existing = db.prepare('SELECT id FROM students WHERE lrn = ?').get(lrn.trim()); + if (existing) return res.status(409).json({ message: `A student with LRN ${lrn} already exists.` }); + + try { + // ---- Insert in transaction ---- + const insertResult = db.transaction(() => { + const result = db.prepare(` + INSERT INTO students (lrn, first_name, middle_name, last_name, extension, sex, birth_date) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run( + lrn.trim(), + firstName.trim(), + middleName?.trim() || null, + lastName.trim(), + extension?.trim() || null, + sex, + birthDate + ); + return result; + })(); + + const newId = insertResult.lastInsertRowid; + + // ---- Auto-create student directory ---- + const folderName = `${sanitizeFolderName(lastName)}_${sanitizeFolderName(firstName)}_${lrn.trim()}`; + const studentDir = path.join(STUDENT_DIR_ROOT, folderName); + if (!fs.existsSync(studentDir)) { + fs.mkdirSync(studentDir, { recursive: true }); + } + + // ---- Auto-create folder record in database ---- + try { + db.prepare(` + INSERT INTO document_folders (name, student_id, category, created_by) + VALUES (?, ?, 'root', ?) + `).run(folderName, newId, req.user?.id || null); + } catch (folderError) { + console.error('Warning: Failed to create folder record:', folderError.message); + } + + res.status(201).json({ + id: newId, + message: 'Student created successfully', + directoryPath: studentDir, + }); + } catch (error) { + console.error('createStudent error:', error); + // SQLite unique constraint gives SQLITE_CONSTRAINT + if (error.message && error.message.includes('UNIQUE')) { + return res.status(409).json({ message: `A student with LRN ${lrn} already exists.` }); + } + res.status(500).json({ message: 'Failed to create student', error: error.message }); + } +}; + +// ============================================================ +// PUT /api/students/:id — update student record +// ============================================================ +exports.updateStudent = (req, res) => { + const { id } = req.params; + const { lrn, firstName, middleName, lastName, extension, sex, birthDate, status } = req.body; + + // ---- Server-side validation ---- + const errors = []; + if (!lrn || !isValidLRN(lrn)) errors.push('LRN must be exactly 12 digits.'); + if (!firstName || !firstName.trim()) errors.push('First name is required.'); + if (!lastName || !lastName.trim()) errors.push('Last name is required.'); + if (!sex || !['Male', 'Female'].includes(sex)) errors.push('Sex must be Male or Female.'); + if (!birthDate) errors.push('Date of birth is required.'); + if (status && !['Enrolled', 'Graduated', 'Transferred Out', 'Dropped'].includes(status)) { + errors.push('Invalid status value.'); + } + if (errors.length) return res.status(400).json({ message: errors[0], errors }); + + // ---- Existence check ---- + const existing = db.prepare('SELECT id FROM students WHERE id = ?').get(id); + if (!existing) return res.status(404).json({ message: 'Student not found.' }); + + // ---- Duplicate LRN check (excluding self) ---- + const duplicate = db.prepare('SELECT id FROM students WHERE lrn = ? AND id != ?').get(lrn.trim(), id); + if (duplicate) return res.status(409).json({ message: `Another student already has LRN ${lrn}.` }); + + try { + db.prepare(` + UPDATE students + SET lrn = ?, first_name = ?, middle_name = ?, last_name = ?, + extension = ?, sex = ?, birth_date = ?, status = ? + WHERE id = ? + `).run( + lrn.trim(), + firstName.trim(), + middleName?.trim() || null, + lastName.trim(), + extension?.trim() || null, + sex, + birthDate, + status || 'Enrolled', + id + ); + + res.json({ message: 'Student updated successfully' }); + } catch (error) { + console.error('updateStudent error:', error); + if (error.message && error.message.includes('UNIQUE')) { + return res.status(409).json({ message: `Another student already has LRN ${lrn}.` }); + } + res.status(500).json({ message: 'Failed to update student', error: error.message }); + } +}; + +// ============================================================ +// DELETE /api/students/:id +// ============================================================ +exports.deleteStudent = (req, res) => { + const { id } = req.params; + + const existing = db.prepare('SELECT id FROM students WHERE id = ?').get(id); + if (!existing) return res.status(404).json({ message: 'Student not found.' }); + + try { + db.prepare('DELETE FROM students WHERE id = ?').run(id); + res.json({ message: 'Student deleted successfully' }); + } catch (error) { + console.error('deleteStudent error:', error); + res.status(500).json({ message: 'Failed to delete student', error: error.message }); + } +}; diff --git a/backend/src/controllers/userController.js b/backend/src/controllers/userController.js new file mode 100644 index 0000000..a546c99 --- /dev/null +++ b/backend/src/controllers/userController.js @@ -0,0 +1,135 @@ +const db = require('../config/db'); +const bcrypt = require('bcrypt'); + +// GET /api/users - List all users +exports.getUsers = (req, res) => { + try { + const users = db.prepare( + 'SELECT id, username, first_name, middle_name, last_name, extension, role, email, phone, created_at FROM users ORDER BY role, last_name' + ).all(); + res.json(users); + } catch (error) { + res.status(500).json({ message: 'Failed to fetch users', error: error.message }); + } +}; + +// POST /api/users - Create a new user +exports.createUser = (req, res) => { + const { username, firstName, middleName, lastName, extension, role, email, phone } = req.body; + // Password is optional — auto-generated if not provided + let providedPassword = req.body.password; + + if (!username || !firstName || !lastName || !role) { + return res.status(400).json({ message: 'Username, first name, last name, and role are required.' }); + } + + const validRoles = ['admin', 'teacher']; // Super admin can only be created by seeding + if (!validRoles.includes(role)) { + return res.status(400).json({ message: 'Invalid role. Must be admin or teacher.' }); + } + + // Auto-generate a secure temporary password if none was provided + const generatePassword = () => { + const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789!@#'; + let pwd = ''; + for (let i = 0; i < 10; i++) pwd += chars[Math.floor(Math.random() * chars.length)]; + return pwd; + }; + + const temporaryPassword = (providedPassword && providedPassword.trim().length >= 6) + ? providedPassword.trim() + : generatePassword(); + + try { + const existing = db.prepare('SELECT id FROM users WHERE username = ?').get(username); + if (existing) { + return res.status(409).json({ message: `Username "${username}" is already taken.` }); + } + + const hashedPassword = bcrypt.hashSync(temporaryPassword, 10); + const result = db.prepare(` + INSERT INTO users (username, password, first_name, middle_name, last_name, extension, role, email, phone) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(username, hashedPassword, firstName, middleName || null, lastName, extension || null, role, email || null, phone || null); + + // Return the plaintext password ONCE — it will never be retrievable again + res.status(201).json({ + message: 'User created successfully', + userId: result.lastInsertRowid, + temporaryPassword, + }); + } catch (error) { + res.status(500).json({ message: 'Failed to create user', error: error.message }); + } +}; + +// PUT /api/users/:id - Update a user +exports.updateUser = (req, res) => { + const { id } = req.params; + const { firstName, middleName, lastName, extension, role, email, phone } = req.body; + + const validRoles = ['super_admin', 'admin', 'teacher']; + if (role && !validRoles.includes(role)) { + return res.status(400).json({ message: 'Invalid role.' }); + } + + try { + const user = db.prepare('SELECT id, role FROM users WHERE id = ?').get(id); + if (!user) return res.status(404).json({ message: 'User not found.' }); + + // Prevent modifying super_admin role + if (user.role === 'super_admin' && role && role !== 'super_admin') { + return res.status(403).json({ message: 'Cannot change the Super Admin role.' }); + } + // Preserve super_admin role — cannot be changed to anything else + const effectiveRole = user.role === 'super_admin' ? 'super_admin' : (role || user.role); + + db.prepare(` + UPDATE users + SET first_name = ?, middle_name = ?, last_name = ?, extension = ?, role = ?, email = ?, phone = ?, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `).run(firstName, middleName || null, lastName, extension || null, effectiveRole, email || null, phone || null, id); + + res.json({ message: 'User updated successfully' }); + } catch (error) { + res.status(500).json({ message: 'Failed to update user', error: error.message }); + } +}; + +// PUT /api/users/:id/reset-password - Reset a user's password +exports.resetPassword = (req, res) => { + const { id } = req.params; + const newPassword = 'changeme123'; + + try { + const user = db.prepare('SELECT id, role FROM users WHERE id = ?').get(id); + if (!user) return res.status(404).json({ message: 'User not found.' }); + if (user.role === 'super_admin') { + return res.status(403).json({ message: 'Cannot reset the Super Admin password via this route.' }); + } + + const hashed = bcrypt.hashSync(newPassword, 10); + db.prepare('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(hashed, id); + + res.json({ message: `Password has been reset to "${newPassword}".` }); + } catch (error) { + res.status(500).json({ message: 'Failed to reset password', error: error.message }); + } +}; + +// DELETE /api/users/:id - Delete a user +exports.deleteUser = (req, res) => { + const { id } = req.params; + try { + const user = db.prepare('SELECT id, role FROM users WHERE id = ?').get(id); + if (!user) return res.status(404).json({ message: 'User not found.' }); + if (user.role === 'super_admin') { + return res.status(403).json({ message: 'Cannot delete the Super Admin account.' }); + } + + db.prepare('DELETE FROM users WHERE id = ?').run(id); + res.json({ message: 'User deleted successfully' }); + } catch (error) { + res.status(500).json({ message: 'Failed to delete user', error: error.message }); + } +}; diff --git a/backend/src/middleware/auth.js b/backend/src/middleware/auth.js new file mode 100644 index 0000000..503bc4c --- /dev/null +++ b/backend/src/middleware/auth.js @@ -0,0 +1,26 @@ +const jwt = require('jsonwebtoken'); +require('dotenv').config(); + +const authenticateToken = (req, res, next) => { + const authHeader = req.headers['authorization']; + const token = authHeader && authHeader.split(' ')[1]; + + if (!token) return res.status(401).json({ message: 'Authentication token required' }); + + jwt.verify(token, process.env.JWT_SECRET, (err, user) => { + if (err) return res.status(403).json({ message: 'Invalid or expired token' }); + req.user = user; + next(); + }); +}; + +const authorizeRoles = (...roles) => { + return (req, res, next) => { + if (!roles.includes(req.user.role)) { + return res.status(403).json({ message: 'Access denied: Insufficient permissions' }); + } + next(); + }; +}; + +module.exports = { authenticateToken, authorizeRoles }; diff --git a/backend/src/models/schema.js b/backend/src/models/schema.js new file mode 100644 index 0000000..73ee388 --- /dev/null +++ b/backend/src/models/schema.js @@ -0,0 +1,235 @@ +const db = require('../config/db'); +const bcrypt = require('bcrypt'); + +const initSchema = () => { + // Enable WAL mode for better performance + db.pragma('journal_mode = WAL'); + + db.transaction(() => { + // 1. Users Table + db.prepare(` + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT UNIQUE NOT NULL, + password TEXT NOT NULL, + first_name TEXT NOT NULL, + middle_name TEXT, + last_name TEXT NOT NULL, + extension TEXT, + role TEXT CHECK(role IN ('super_admin', 'admin', 'teacher')) NOT NULL, + email TEXT, + phone TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `).run(); + + // 2. AcademicYears Table + db.prepare(` + CREATE TABLE IF NOT EXISTS academic_years ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + year_range TEXT UNIQUE NOT NULL, -- e.g., "2023-2024" + status TEXT CHECK(status IN ('active', 'inactive')) DEFAULT 'active' + ) + `).run(); + + // 2b. Sections Table + db.prepare(` + CREATE TABLE IF NOT EXISTS sections ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + grade_level INTEGER NOT NULL, + academic_year_id INTEGER, + FOREIGN KEY (academic_year_id) REFERENCES academic_years(id) ON DELETE CASCADE + ) + `).run(); + + // 3. Subjects Table + db.prepare(` + CREATE TABLE IF NOT EXISTS subjects ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + code TEXT UNIQUE NOT NULL, + title TEXT NOT NULL, + category TEXT CHECK(category IN ('JHS', 'SHS_CORE', 'SHS_APPLIED', 'SHS_SPECIALIZED')) NOT NULL + ) + `).run(); + + // 4. Students Table + db.prepare(` + CREATE TABLE IF NOT EXISTS students ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + lrn TEXT UNIQUE NOT NULL, + first_name TEXT NOT NULL, + middle_name TEXT, + last_name TEXT NOT NULL, + extension TEXT, + sex TEXT CHECK(sex IN ('Male', 'Female')) NOT NULL, + birth_date DATE NOT NULL, + status TEXT DEFAULT 'Enrolled', -- Enrolled, Graduated, Transferred Out, Dropped + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `).run(); + + // 5. Enrollments Table + db.prepare(` + CREATE TABLE IF NOT EXISTS enrollments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + student_id INTEGER NOT NULL, + academic_year_id INTEGER NOT NULL, + section_id INTEGER NOT NULL, + grade_level INTEGER NOT NULL, + track_strand TEXT, -- For SHS + FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE, + FOREIGN KEY (academic_year_id) REFERENCES academic_years(id), + FOREIGN KEY (section_id) REFERENCES sections(id) + ) + `).run(); + + // 6. Grades Table + db.prepare(` + CREATE TABLE IF NOT EXISTS grades ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + enrollment_id INTEGER NOT NULL, + subject_id INTEGER NOT NULL, + q1 REAL, q2 REAL, q3 REAL, q4 REAL, -- JHS + sem1 REAL, sem2 REAL, -- SHS + final_grade REAL, + remarks TEXT, + FOREIGN KEY (enrollment_id) REFERENCES enrollments(id) ON DELETE CASCADE, + FOREIGN KEY (subject_id) REFERENCES subjects(id) + ) + `).run(); + + // 8. DocumentRequirements Table (Enhanced) + db.prepare(` + CREATE TABLE IF NOT EXISTS document_requirements ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + description TEXT, + category TEXT CHECK(category IN ('JHS', 'SHS')) NOT NULL, + is_mandatory INTEGER DEFAULT 1, + is_enabled INTEGER DEFAULT 1, + due_date DATE, + accepted_file_types TEXT DEFAULT 'pdf,jpg,jpeg,png', + school_levels TEXT DEFAULT 'JHS,SHS', + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `).run(); + + // 8b. DocumentFolders Table (for manual folder management) + db.prepare(` + CREATE TABLE IF NOT EXISTS document_folders ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + parent_id INTEGER, + student_id INTEGER, + category TEXT, + created_by INTEGER, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (parent_id) REFERENCES document_folders(id) ON DELETE CASCADE, + FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE, + FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL + ) + `).run(); + + // 7. Documents Table + db.prepare(` + CREATE TABLE IF NOT EXISTS documents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + student_id INTEGER NOT NULL, + requirement_id INTEGER, + file_name TEXT NOT NULL, + file_path TEXT NOT NULL, + document_type TEXT, + status TEXT CHECK(status IN ('Pending', 'Verified', 'Draft', 'Archived')) DEFAULT 'Pending', + retention_date DATE, + uploaded_by INTEGER, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE, + FOREIGN KEY (requirement_id) REFERENCES document_requirements(id), + FOREIGN KEY (uploaded_by) REFERENCES users(id) + ) + `).run(); + + // 9. PrintQueue & Notifications + db.prepare(` + CREATE TABLE IF NOT EXISTS print_queue ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + document_id INTEGER NOT NULL, + user_id INTEGER NOT NULL, + added_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `).run(); + + db.prepare(` + CREATE TABLE IF NOT EXISTS notifications ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER, -- NULL means global + title TEXT NOT NULL, + message TEXT NOT NULL, + is_read INTEGER DEFAULT 0, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `).run(); + + // 10. Password Reset Requests Table + db.prepare(` + CREATE TABLE IF NOT EXISTS password_reset_requests ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + new_password_hash TEXT NOT NULL, + status TEXT CHECK(status IN ('pending', 'approved', 'rejected')) DEFAULT 'pending', + requested_at DATETIME DEFAULT CURRENT_TIMESTAMP, + reviewed_at DATETIME, + reviewed_by INTEGER, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (reviewed_by) REFERENCES users(id) + ) + `).run(); + + // Seed Super Admin if not exists + const superAdmin = db.prepare("SELECT * FROM users WHERE username = 'superadmin'").get(); + if (!superAdmin) { + const hashedPassword = bcrypt.hashSync('admin123', 10); + db.prepare(` + INSERT INTO users (username, password, first_name, last_name, role) + VALUES ('superadmin', ?, 'System', 'Developer', 'super_admin') + `).run(hashedPassword); + console.log('Default Super Admin created: superadmin / admin123'); + } + + // Seed default document requirements if none exist + const existingReqs = db.prepare("SELECT COUNT(*) as count FROM document_requirements").get(); + if (existingReqs.count === 0) { + const defaultRequirements = [ + { name: 'Form 137', description: 'Official copy of grades from previous school', category: 'JHS', is_mandatory: 1 }, + { name: 'Form 137', description: 'Official copy of grades from previous school', category: 'SHS', is_mandatory: 1 }, + { name: 'PSA Birth Certificate', description: 'Philippine Statistics Authority birth certificate', category: 'JHS', is_mandatory: 1 }, + { name: 'PSA Birth Certificate', description: 'Philippine Statistics Authority birth certificate', category: 'SHS', is_mandatory: 1 }, + { name: 'Good Moral Certificate', description: 'Certificate of good moral character', category: 'JHS', is_mandatory: 1 }, + { name: 'Good Moral Certificate', description: 'Certificate of good moral character', category: 'SHS', is_mandatory: 1 }, + { name: 'Medical Certificate', description: 'Physical and medical examination result', category: 'JHS', is_mandatory: 1 }, + { name: 'Medical Certificate', description: 'Physical and medical examination result', category: 'SHS', is_mandatory: 1 }, + { name: 'Report Card (Form 138)', description: 'Latest report card from previous school', category: 'JHS', is_mandatory: 1 }, + { name: 'Report Card (Form 138)', description: 'Latest report card from previous school', category: 'SHS', is_mandatory: 1 }, + { name: '2x2 Photo', description: 'Two pieces of 2x2 colored ID photos', category: 'JHS', is_mandatory: 1 }, + { name: '2x2 Photo', description: 'Two pieces of 2x2 colored ID photos', category: 'SHS', is_mandatory: 1 }, + ]; + const insertReq = db.prepare(` + INSERT INTO document_requirements (name, description, category, is_mandatory, is_enabled, accepted_file_types, school_levels) + VALUES (?, ?, ?, ?, 1, 'pdf,jpg,jpeg,png', 'JHS,SHS') + `); + for (const req of defaultRequirements) { + insertReq.run(req.name, req.description, req.category, req.is_mandatory); + } + console.log('Default document requirements seeded'); + } + })(); +}; + +module.exports = { initSchema }; diff --git a/backend/src/routes/archives.js b/backend/src/routes/archives.js new file mode 100644 index 0000000..fbe9a17 --- /dev/null +++ b/backend/src/routes/archives.js @@ -0,0 +1,13 @@ +const express = require('express'); +const router = express.Router(); +const archiveController = require('../controllers/archiveController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +// All routes require authentication +router.get('/', authenticateToken, archiveController.getArchivedStudents); + +// Restore and Purge restricted to super_admin & admin +router.post('/:id/restore', authenticateToken, authorizeRoles('super_admin', 'admin'), archiveController.restoreArchive); +router.delete('/:id', authenticateToken, authorizeRoles('super_admin', 'admin'), archiveController.purgeArchive); + +module.exports = router; diff --git a/backend/src/routes/auth.js b/backend/src/routes/auth.js new file mode 100644 index 0000000..253c11d --- /dev/null +++ b/backend/src/routes/auth.js @@ -0,0 +1,16 @@ +const express = require('express'); +const router = express.Router(); +const authController = require('../controllers/authController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +router.post('/login', authController.login); +router.get('/profile', authenticateToken, authController.getProfile); +router.put('/profile', authenticateToken, authController.updateProfile); +router.put('/change-password', authenticateToken, authController.changePassword); +router.post('/forgot-password', authController.requestPasswordReset); // Public — no token needed +router.get('/reset-requests', authenticateToken, authorizeRoles('super_admin'), authController.getResetRequests); +router.put('/reset-requests/:id/approve', authenticateToken, authorizeRoles('super_admin'), authController.approveResetRequest); +router.put('/reset-requests/:id/reject', authenticateToken, authorizeRoles('super_admin'), authController.rejectResetRequest); + +module.exports = router; + diff --git a/backend/src/routes/dashboard.js b/backend/src/routes/dashboard.js new file mode 100644 index 0000000..b81894d --- /dev/null +++ b/backend/src/routes/dashboard.js @@ -0,0 +1,9 @@ +const express = require('express'); +const router = express.Router(); +const dashboardController = require('../controllers/dashboardController'); +const { authenticateToken } = require('../middleware/auth'); + +router.get('/stats', authenticateToken, dashboardController.getStats); +router.get('/pending-tasks', authenticateToken, dashboardController.getPendingTasks); + +module.exports = router; diff --git a/backend/src/routes/documents.js b/backend/src/routes/documents.js new file mode 100644 index 0000000..997aabc --- /dev/null +++ b/backend/src/routes/documents.js @@ -0,0 +1,20 @@ +const express = require('express'); +const router = express.Router(); +const documentController = require('../controllers/documentController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +router.get('/', authenticateToken, documentController.getAllDocuments); +router.get('/requirements', authenticateToken, documentController.getRequirements); + +// Print Queue routes — must be BEFORE /:id routes to avoid conflict +router.get('/print-queue', authenticateToken, documentController.getPrintQueue); +router.post('/print-queue', authenticateToken, documentController.addToPrintQueue); +router.delete('/print-queue/clear', authenticateToken, documentController.clearPrintQueue); +router.delete('/print-queue/:queueId', authenticateToken, documentController.removeFromPrintQueue); + +router.post('/upload', authenticateToken, documentController.uploadMiddleware, documentController.uploadDocument); +router.get('/student/:studentId', authenticateToken, documentController.getDocumentsByStudent); +router.patch('/:id/status', authenticateToken, authorizeRoles('super_admin', 'admin'), documentController.updateStatus); +router.delete('/:id', authenticateToken, authorizeRoles('super_admin', 'admin'), documentController.deleteDocument); + +module.exports = router; diff --git a/backend/src/routes/folders.js b/backend/src/routes/folders.js new file mode 100644 index 0000000..e167fcd --- /dev/null +++ b/backend/src/routes/folders.js @@ -0,0 +1,16 @@ +const express = require('express'); +const router = express.Router(); +const folderController = require('../controllers/folderController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +// Public routes (with auth) +router.get('/', authenticateToken, folderController.getFolders); +router.get('/student/:studentId', authenticateToken, folderController.getStudentFolder); +router.post('/sync', authenticateToken, authorizeRoles('super_admin', 'admin'), folderController.syncFolders); + +// Admin/Super Admin routes +router.post('/', authenticateToken, authorizeRoles('super_admin', 'admin'), folderController.createFolder); +router.put('/:id', authenticateToken, authorizeRoles('super_admin', 'admin'), folderController.renameFolder); +router.delete('/:id', authenticateToken, authorizeRoles('super_admin', 'admin'), folderController.deleteFolder); + +module.exports = router; \ No newline at end of file diff --git a/backend/src/routes/grades.js b/backend/src/routes/grades.js new file mode 100644 index 0000000..729666c --- /dev/null +++ b/backend/src/routes/grades.js @@ -0,0 +1,11 @@ +const express = require('express'); +const router = express.Router(); +const gradeController = require('../controllers/gradeController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +router.post('/enroll', authenticateToken, authorizeRoles('super_admin', 'admin'), gradeController.enrollStudent); +router.get('/enrollment/:enrollmentId', authenticateToken, gradeController.getGradesByEnrollment); +router.post('/update', authenticateToken, authorizeRoles('super_admin', 'admin'), gradeController.updateGrades); +router.get('/sf10/:studentId', authenticateToken, gradeController.getSF10Data); + +module.exports = router; diff --git a/backend/src/routes/reports.js b/backend/src/routes/reports.js new file mode 100644 index 0000000..bdb963f --- /dev/null +++ b/backend/src/routes/reports.js @@ -0,0 +1,12 @@ +const express = require('express'); +const router = express.Router(); +const reportsController = require('../controllers/reportsController'); +const { authenticateToken } = require('../middleware/auth'); + +router.get('/academic-years', authenticateToken, reportsController.getAcademicYears); +router.get('/stats', authenticateToken, reportsController.getStats); +router.get('/enrollment-by-grade', authenticateToken, reportsController.getEnrollmentByGrade); +router.get('/document-status', authenticateToken, reportsController.getDocumentStatus); +router.get('/export-data', authenticateToken, reportsController.getExportData); + +module.exports = router; diff --git a/backend/src/routes/requirements.js b/backend/src/routes/requirements.js new file mode 100644 index 0000000..02d9d50 --- /dev/null +++ b/backend/src/routes/requirements.js @@ -0,0 +1,18 @@ +const express = require('express'); +const router = express.Router(); +const requirementController = require('../controllers/requirementController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +// Public routes (all authenticated users) +router.get('/', authenticateToken, requirementController.getRequirements); +router.get('/settings', authenticateToken, requirementController.getRequirementsSettings); +router.get('/missing/:studentId', authenticateToken, requirementController.getMissingRequirements); +router.get('/:id', authenticateToken, requirementController.getRequirementById); + +// Super Admin routes only +router.post('/', authenticateToken, authorizeRoles('super_admin'), requirementController.createRequirement); +router.put('/bulk', authenticateToken, authorizeRoles('super_admin'), requirementController.bulkUpdateRequirements); +router.put('/:id', authenticateToken, authorizeRoles('super_admin'), requirementController.updateRequirement); +router.delete('/:id', authenticateToken, authorizeRoles('super_admin'), requirementController.deleteRequirement); + +module.exports = router; \ No newline at end of file diff --git a/backend/src/routes/setup.js b/backend/src/routes/setup.js new file mode 100644 index 0000000..9f427eb --- /dev/null +++ b/backend/src/routes/setup.js @@ -0,0 +1,11 @@ +const express = require('express'); +const router = express.Router(); +const setupController = require('../controllers/setupController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +router.get('/academic-years', authenticateToken, setupController.getAllAcademicYears); +router.post('/academic-years', authenticateToken, authorizeRoles('super_admin', 'admin'), setupController.createAcademicYear); +router.get('/academic-years/:yearId/sections', authenticateToken, setupController.getSectionsByYear); +router.post('/sections', authenticateToken, authorizeRoles('super_admin', 'admin'), setupController.createSection); + +module.exports = router; diff --git a/backend/src/routes/students.js b/backend/src/routes/students.js new file mode 100644 index 0000000..a9c48ef --- /dev/null +++ b/backend/src/routes/students.js @@ -0,0 +1,15 @@ +const express = require('express'); +const router = express.Router(); +const studentController = require('../controllers/studentController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +// All routes require authentication +router.get('/', authenticateToken, studentController.getAllStudents); +router.get('/:id', authenticateToken, studentController.getStudentById); + +// Create / Update / Delete restricted to super_admin & admin +router.post('/', authenticateToken, authorizeRoles('super_admin', 'admin'), studentController.createStudent); +router.put('/:id', authenticateToken, authorizeRoles('super_admin', 'admin'), studentController.updateStudent); +router.delete('/:id', authenticateToken, authorizeRoles('super_admin', 'admin'), studentController.deleteStudent); + +module.exports = router; diff --git a/backend/src/routes/users.js b/backend/src/routes/users.js new file mode 100644 index 0000000..f71d11f --- /dev/null +++ b/backend/src/routes/users.js @@ -0,0 +1,13 @@ +const express = require('express'); +const router = express.Router(); +const userController = require('../controllers/userController'); +const { authenticateToken, authorizeRoles } = require('../middleware/auth'); + +// All routes require authentication + role guard +router.get('/', authenticateToken, authorizeRoles('super_admin', 'admin'), userController.getUsers); +router.post('/', authenticateToken, authorizeRoles('super_admin'), userController.createUser); +router.put('/:id', authenticateToken, authorizeRoles('super_admin'), userController.updateUser); +router.put('/:id/reset-password', authenticateToken, authorizeRoles('super_admin'), userController.resetPassword); +router.delete('/:id', authenticateToken, authorizeRoles('super_admin'), userController.deleteUser); + +module.exports = router; diff --git a/backend/src/services/retentionEngine.js b/backend/src/services/retentionEngine.js new file mode 100644 index 0000000..4d13fdc --- /dev/null +++ b/backend/src/services/retentionEngine.js @@ -0,0 +1,41 @@ +const cron = require('node-cron'); +const db = require('../config/db'); + +// Retention Engine Logic +// Runs every day at midnight +cron.schedule('0 0 * * *', () => { + console.log('Running Retention Engine...'); + + db.transaction(() => { + const now = new Date(); + + // 1. Process Graduated Students (Docs -> Archive 5 years) + // Set retention_date for documents of graduated students if not set + db.prepare(` + UPDATE documents + SET retention_date = date(created_at, '+5 years'), status = 'Archived' + WHERE student_id IN (SELECT id FROM students WHERE status = 'Graduated') + AND status != 'Archived' + `).run(); + + // 2. Process Transferred Out Students (Docs -> Archive 3 years) + db.prepare(` + UPDATE documents + SET retention_date = date(created_at, '+3 years'), status = 'Archived' + WHERE student_id IN (SELECT id FROM students WHERE status = 'Transferred Out') + AND status != 'Archived' + `).run(); + + // 3. Process Dropped Students (Docs -> Archive 2 years) + db.prepare(` + UPDATE documents + SET retention_date = date(created_at, '+2 years'), status = 'Archived' + WHERE student_id IN (SELECT id FROM students WHERE status = 'Dropped') + AND status != 'Archived' + `).run(); + + console.log('Retention Engine task completed.'); + })(); +}); + +console.log('Retention Engine service initialized.'); diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/frontend/.metadata b/frontend/.metadata new file mode 100644 index 0000000..f22c42b --- /dev/null +++ b/frontend/.metadata @@ -0,0 +1,33 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "00b0c91f06209d9e4a41f71b7a512d6eb3b9c694" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + base_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + - platform: android + create_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + base_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + - platform: windows + create_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + base_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..92d1efb --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,17 @@ +# frontend + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/frontend/analysis_options.yaml b/frontend/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/frontend/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/frontend/android/.gitignore b/frontend/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/frontend/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/frontend/android/app/build.gradle.kts b/frontend/android/app/build.gradle.kts new file mode 100644 index 0000000..9d58cab --- /dev/null +++ b/frontend/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.teamsb.tis_rms" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.teamsb.tis_rms" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/frontend/android/app/src/debug/AndroidManifest.xml b/frontend/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/frontend/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..a3926e9 --- /dev/null +++ b/frontend/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/android/app/src/main/kotlin/com/teamsb/tis_rms/MainActivity.kt b/frontend/android/app/src/main/kotlin/com/teamsb/tis_rms/MainActivity.kt new file mode 100644 index 0000000..32976e4 --- /dev/null +++ b/frontend/android/app/src/main/kotlin/com/teamsb/tis_rms/MainActivity.kt @@ -0,0 +1,5 @@ +package com.teamsb.tis_rms + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/frontend/android/app/src/main/res/drawable-hdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-hdpi/android12splash.png new file mode 100644 index 0000000..cd58799 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-hdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-hdpi/splash.png b/frontend/android/app/src/main/res/drawable-hdpi/splash.png new file mode 100644 index 0000000..cd58799 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-hdpi/splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-mdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-mdpi/android12splash.png new file mode 100644 index 0000000..23ef4dc Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-mdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-mdpi/splash.png b/frontend/android/app/src/main/res/drawable-mdpi/splash.png new file mode 100644 index 0000000..23ef4dc Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-mdpi/splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-night-hdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-night-hdpi/android12splash.png new file mode 100644 index 0000000..cd58799 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-night-hdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-night-mdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-night-mdpi/android12splash.png new file mode 100644 index 0000000..23ef4dc Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-night-mdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-night-xhdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-night-xhdpi/android12splash.png new file mode 100644 index 0000000..4516e76 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-night-xhdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png new file mode 100644 index 0000000..e5db34f Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png new file mode 100644 index 0000000..4b45387 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-v21/background.png b/frontend/android/app/src/main/res/drawable-v21/background.png new file mode 100644 index 0000000..99d8f46 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-v21/background.png differ diff --git a/frontend/android/app/src/main/res/drawable-v21/launch_background.xml b/frontend/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..3cc4948 --- /dev/null +++ b/frontend/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/frontend/android/app/src/main/res/drawable-xhdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-xhdpi/android12splash.png new file mode 100644 index 0000000..4516e76 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-xhdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-xhdpi/splash.png b/frontend/android/app/src/main/res/drawable-xhdpi/splash.png new file mode 100644 index 0000000..4516e76 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-xhdpi/splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-xxhdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-xxhdpi/android12splash.png new file mode 100644 index 0000000..e5db34f Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-xxhdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-xxhdpi/splash.png b/frontend/android/app/src/main/res/drawable-xxhdpi/splash.png new file mode 100644 index 0000000..e5db34f Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-xxhdpi/splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-xxxhdpi/android12splash.png b/frontend/android/app/src/main/res/drawable-xxxhdpi/android12splash.png new file mode 100644 index 0000000..4b45387 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-xxxhdpi/android12splash.png differ diff --git a/frontend/android/app/src/main/res/drawable-xxxhdpi/splash.png b/frontend/android/app/src/main/res/drawable-xxxhdpi/splash.png new file mode 100644 index 0000000..4b45387 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable-xxxhdpi/splash.png differ diff --git a/frontend/android/app/src/main/res/drawable/background.png b/frontend/android/app/src/main/res/drawable/background.png new file mode 100644 index 0000000..99d8f46 Binary files /dev/null and b/frontend/android/app/src/main/res/drawable/background.png differ diff --git a/frontend/android/app/src/main/res/drawable/launch_background.xml b/frontend/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..3cc4948 --- /dev/null +++ b/frontend/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..a05eee3 Binary files /dev/null and b/frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..0d64d0b Binary files /dev/null and b/frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..08e4c20 Binary files /dev/null and b/frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..e08d9cc Binary files /dev/null and b/frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4773aad Binary files /dev/null and b/frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/frontend/android/app/src/main/res/values-night-v31/styles.xml b/frontend/android/app/src/main/res/values-night-v31/styles.xml new file mode 100644 index 0000000..9d38747 --- /dev/null +++ b/frontend/android/app/src/main/res/values-night-v31/styles.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/frontend/android/app/src/main/res/values-night/styles.xml b/frontend/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..dbc9ea9 --- /dev/null +++ b/frontend/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/frontend/android/app/src/main/res/values-v31/styles.xml b/frontend/android/app/src/main/res/values-v31/styles.xml new file mode 100644 index 0000000..70292bf --- /dev/null +++ b/frontend/android/app/src/main/res/values-v31/styles.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/frontend/android/app/src/main/res/values/styles.xml b/frontend/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..0d1fa8f --- /dev/null +++ b/frontend/android/app/src/main/res/values/styles.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/frontend/android/app/src/profile/AndroidManifest.xml b/frontend/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/frontend/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/frontend/android/build.gradle.kts b/frontend/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/frontend/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/frontend/android/gradle.properties b/frontend/android/gradle.properties new file mode 100644 index 0000000..fbee1d8 --- /dev/null +++ b/frontend/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/frontend/android/gradle/wrapper/gradle-wrapper.properties b/frontend/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/frontend/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/frontend/android/settings.gradle.kts b/frontend/android/settings.gradle.kts new file mode 100644 index 0000000..ca7fe06 --- /dev/null +++ b/frontend/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/frontend/lib/core/constants/app_colors.dart b/frontend/lib/core/constants/app_colors.dart new file mode 100644 index 0000000..421393f --- /dev/null +++ b/frontend/lib/core/constants/app_colors.dart @@ -0,0 +1,26 @@ +import 'package:flutter/material.dart'; + +class AppColors { + // Prevent instantiation + AppColors._(); + + // Primary Brand Colors + static const Color primaryGreen = Color(0xFF1C8248); + static const Color darkGreen = Color(0xFF085F32); + + // Backgrounds + static const Color pageBackground = Color(0xFFF9F9F9); // Off-white/Beige + static const Color surfaceWhite = Colors.white; // Cards, Dialogs + static const Color inputBackground = Color(0xFFE5E5E5); + + // Text Colors + static const Color textPrimary = Color(0xFF1A1A1A); + static const Color textSecondary = Color(0xFF666666); + static const Color textMuted = Color(0xFF999999); + + // Status Colors + static const Color error = Colors.redAccent; + static const Color warning = Colors.orange; + static const Color success = Color(0xFF1C8248); + static const Color info = Colors.blue; +} \ No newline at end of file diff --git a/frontend/lib/core/constants/app_sizes.dart b/frontend/lib/core/constants/app_sizes.dart new file mode 100644 index 0000000..843efad --- /dev/null +++ b/frontend/lib/core/constants/app_sizes.dart @@ -0,0 +1,20 @@ +class AppSizes { + // Prevent instantiation + AppSizes._(); + + // Padding & Margins + static const double p4 = 4.0; + static const double p8 = 8.0; + static const double p12 = 12.0; + static const double p16 = 16.0; // Default Standard Padding + static const double p20 = 20.0; + static const double p24 = 24.0; // Screen Edge Padding + static const double p32 = 32.0; + static const double p48 = 48.0; + + // Border Radii + static const double radiusSmall = 4.0; + static const double radiusMedium = 8.0; // Standard for Inputs/Buttons + static const double radiusLarge = 12.0; // Standard for Cards/Modals + static const double radiusCircular = 100.0; +} \ No newline at end of file diff --git a/frontend/lib/core/network/api_constants.dart b/frontend/lib/core/network/api_constants.dart new file mode 100644 index 0000000..83b74fd --- /dev/null +++ b/frontend/lib/core/network/api_constants.dart @@ -0,0 +1,7 @@ +class ApiConstants { + // IMPORTANT: For Android Emulator testing, use 10.0.2.2 + // For physical LAN testing, use the IPv4 of the Host PC (e.g., 192.168.1.X) + // For Windows Host app testing, 127.0.0.1 is fine. + // static const String baseUrl = 'http://127.0.0.1:3000/api'; + static const String baseUrl = 'http://192.168.1.107:3000/api'; +} \ No newline at end of file diff --git a/frontend/lib/core/theme/app_theme.dart b/frontend/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..f85ec42 --- /dev/null +++ b/frontend/lib/core/theme/app_theme.dart @@ -0,0 +1,154 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import '../constants/app_colors.dart'; +import '../constants/app_sizes.dart'; + +class AppTheme { + // Prevent instantiation + AppTheme._(); + + static ThemeData get lightTheme { + return ThemeData( + useMaterial3: true, + scaffoldBackgroundColor: AppColors.pageBackground, + primaryColor: AppColors.primaryGreen, + + // Color Scheme + colorScheme: ColorScheme.fromSeed( + seedColor: AppColors.primaryGreen, + primary: AppColors.primaryGreen, + secondary: AppColors.darkGreen, + surface: AppColors.surfaceWhite, + error: AppColors.error, + ), + + // AppBar Theme + appBarTheme: AppBarTheme( + backgroundColor: AppColors.surfaceWhite, + elevation: 1, + shadowColor: Colors.black.withOpacity(0.05), + scrolledUnderElevation: 0, + iconTheme: const IconThemeData(color: AppColors.textPrimary), + titleTextStyle: GoogleFonts.inter( + color: AppColors.textPrimary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + + // Card Theme + cardTheme: CardThemeData( + color: AppColors.surfaceWhite, + elevation: 2, + shadowColor: Colors.black.withOpacity(0.08), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + margin: EdgeInsets.zero, + ), + + // Elevated Button Theme + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primaryGreen, + foregroundColor: Colors.white, + elevation: 2, + shadowColor: AppColors.primaryGreen.withOpacity(0.4), + padding: const EdgeInsets.symmetric( + horizontal: AppSizes.p24, + vertical: AppSizes.p16, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + textStyle: GoogleFonts.inter( + fontSize: 14, + fontWeight: FontWeight.w600, + letterSpacing: 0.5, + ), + ), + ), + + // Outlined Button Theme + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + foregroundColor: AppColors.primaryGreen, + side: const BorderSide(color: AppColors.primaryGreen, width: 1.5), + padding: const EdgeInsets.symmetric( + horizontal: AppSizes.p24, + vertical: AppSizes.p16, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + textStyle: GoogleFonts.inter( + fontSize: 14, + fontWeight: FontWeight.w600, + letterSpacing: 0.5, + ), + ), + ), + + // Text Button Theme + textButtonTheme: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: AppColors.primaryGreen, + padding: const EdgeInsets.symmetric( + horizontal: AppSizes.p16, + vertical: AppSizes.p12, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + textStyle: GoogleFonts.inter( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + + // Default Input Decoration (Text Fields) + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: AppColors.inputBackground, + contentPadding: const EdgeInsets.symmetric( + horizontal: AppSizes.p16, + vertical: AppSizes.p16, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + borderSide: BorderSide.none, + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + borderSide: const BorderSide(color: AppColors.primaryGreen, width: 2.0), + ), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + borderSide: const BorderSide(color: AppColors.error, width: 1.5), + ), + focusedErrorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + borderSide: const BorderSide(color: AppColors.error, width: 2.0), + ), + hintStyle: GoogleFonts.inter(color: AppColors.textMuted), + labelStyle: GoogleFonts.inter(color: AppColors.textSecondary), + ), + + // ListTile Theme + listTileTheme: ListTileThemeData( + contentPadding: const EdgeInsets.symmetric(horizontal: AppSizes.p16), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusSmall), + ), + ), + + // Font Family & Typography + textTheme: GoogleFonts.interTextTheme(), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/domain/entities/archive_model.dart b/frontend/lib/domain/entities/archive_model.dart new file mode 100644 index 0000000..3604187 --- /dev/null +++ b/frontend/lib/domain/entities/archive_model.dart @@ -0,0 +1,31 @@ +class ArchiveModel { + final int id; + final String lrn; + final String name; + final String status; + final String archivedDate; + final String expiryDate; + final bool isExpired; + + ArchiveModel({ + required this.id, + required this.lrn, + required this.name, + required this.status, + required this.archivedDate, + required this.expiryDate, + required this.isExpired, + }); + + factory ArchiveModel.fromJson(Map json) { + return ArchiveModel( + id: (json['id'] as num).toInt(), + lrn: json['lrn'] as String, + name: json['name'] as String, + status: json['status'] as String, + archivedDate: json['archivedDate'] as String, + expiryDate: json['expiryDate'] as String, + isExpired: json['isExpired'] as bool, + ); + } +} diff --git a/frontend/lib/domain/entities/dashboard_models.dart b/frontend/lib/domain/entities/dashboard_models.dart new file mode 100644 index 0000000..c0e3831 --- /dev/null +++ b/frontend/lib/domain/entities/dashboard_models.dart @@ -0,0 +1,48 @@ +class DashboardStats { + final int totalStudents; + final int printQueueCount; + final int pendingVerifications; + final int activeUsers; + + DashboardStats({ + required this.totalStudents, + required this.printQueueCount, + required this.pendingVerifications, + required this.activeUsers, + }); + + factory DashboardStats.fromJson(Map json) { + return DashboardStats( + totalStudents: json['totalStudents'] ?? 0, + printQueueCount: json['printQueueCount'] ?? 0, + pendingVerifications: json['pendingVerifications'] ?? 0, + activeUsers: json['activeUsers'] ?? 0, + ); + } +} + +class PendingTask { + final int id; + final String fileName; + final String createdAt; + final String firstName; + final String lastName; + + PendingTask({ + required this.id, + required this.fileName, + required this.createdAt, + required this.firstName, + required this.lastName, + }); + + factory PendingTask.fromJson(Map json) { + return PendingTask( + id: json['id'] ?? 0, + fileName: json['file_name'] ?? 'Unknown', + createdAt: json['created_at'] ?? '', + firstName: json['first_name'] ?? 'Unknown', + lastName: json['last_name'] ?? '', + ); + } +} diff --git a/frontend/lib/domain/entities/document_model.dart b/frontend/lib/domain/entities/document_model.dart new file mode 100644 index 0000000..37f0e74 --- /dev/null +++ b/frontend/lib/domain/entities/document_model.dart @@ -0,0 +1,61 @@ +class DocumentModel { + final int id; + final int? studentId; + final int? requirementId; + final String fileName; + final String filePath; + final String? documentType; + final String status; // 'Pending', 'Verified', 'Draft', 'Archived', 'Rejected' + final DateTime? retentionDate; + final DateTime createdAt; + + // Extra fields for UI display + final String? studentLrn; + final String? studentName; + final String? size; + + DocumentModel({ + required this.id, + this.studentId, + this.requirementId, + required this.fileName, + required this.filePath, + this.documentType, + required this.status, + this.retentionDate, + required this.createdAt, + this.studentLrn, + this.studentName, + this.size, + }); + + factory DocumentModel.fromJson(Map json) { + return DocumentModel( + id: json['id'] as int, + studentId: json['student_id'] as int?, + requirementId: json['requirement_id'] as int?, + fileName: json['fileName'] ?? json['file_name'] ?? '', + filePath: json['filePath'] ?? json['file_path'] ?? '', + documentType: json['documentType'] ?? json['document_type'], + status: json['status'] as String? ?? 'Pending', + retentionDate: json['retention_date'] != null ? DateTime.parse(json['retention_date']) : null, + createdAt: json['createdAt'] != null ? DateTime.parse(json['createdAt']) : (json['created_at'] != null ? DateTime.parse(json['created_at']) : DateTime.now()), + studentLrn: json['studentLrn'], + studentName: json['studentName'], + size: json['size'], + ); + } + + Map toJson() { + return { + 'id': id, + 'student_id': studentId, + 'requirement_id': requirementId, + 'file_name': fileName, + 'file_path': filePath, + 'document_type': documentType, + 'status': status, + 'retention_date': retentionDate?.toIso8601String(), + }; + } +} \ No newline at end of file diff --git a/frontend/lib/domain/entities/document_requirement_model.dart b/frontend/lib/domain/entities/document_requirement_model.dart new file mode 100644 index 0000000..dea4ce5 --- /dev/null +++ b/frontend/lib/domain/entities/document_requirement_model.dart @@ -0,0 +1,83 @@ +class DocumentRequirementModel { + final int id; + final String name; + final String? description; + final String category; // 'JHS', 'SHS' + final bool isMandatory; + final bool isEnabled; + final DateTime? dueDate; + final String acceptedFileTypes; + final String schoolLevels; + final DateTime? createdAt; + final DateTime? updatedAt; + + DocumentRequirementModel({ + required this.id, + required this.name, + this.description, + required this.category, + required this.isMandatory, + this.isEnabled = true, + this.dueDate, + this.acceptedFileTypes = 'pdf,jpg,jpeg,png', + this.schoolLevels = 'JHS,SHS', + this.createdAt, + this.updatedAt, + }); + + factory DocumentRequirementModel.fromJson(Map json) { + return DocumentRequirementModel( + id: json['id'] as int, + name: json['name'] as String, + description: json['description'] as String?, + category: json['category'] as String, + isMandatory: json['is_mandatory'] == 1 || json['is_mandatory'] == true, + isEnabled: json['is_enabled'] == 1 || json['is_enabled'] == true, + dueDate: json['due_date'] != null ? DateTime.parse(json['due_date']) : null, + acceptedFileTypes: json['accepted_file_types'] ?? 'pdf,jpg,jpeg,png', + schoolLevels: json['school_levels'] ?? 'JHS,SHS', + createdAt: json['created_at'] != null ? DateTime.parse(json['created_at']) : null, + updatedAt: json['updated_at'] != null ? DateTime.parse(json['updated_at']) : null, + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'description': description, + 'category': category, + 'isMandatory': isMandatory, + 'isEnabled': isEnabled, + 'dueDate': dueDate?.toIso8601String(), + 'acceptedFileTypes': acceptedFileTypes, + 'schoolLevels': schoolLevels, + }; + } + + DocumentRequirementModel copyWith({ + int? id, + String? name, + String? description, + String? category, + bool? isMandatory, + bool? isEnabled, + DateTime? dueDate, + String? acceptedFileTypes, + String? schoolLevels, + }) { + return DocumentRequirementModel( + id: id ?? this.id, + name: name ?? this.name, + description: description ?? this.description, + category: category ?? this.category, + isMandatory: isMandatory ?? this.isMandatory, + isEnabled: isEnabled ?? this.isEnabled, + dueDate: dueDate ?? this.dueDate, + acceptedFileTypes: acceptedFileTypes ?? this.acceptedFileTypes, + schoolLevels: schoolLevels ?? this.schoolLevels, + createdAt: createdAt, + updatedAt: updatedAt, + ); + } +} diff --git a/frontend/lib/domain/entities/folder_model.dart b/frontend/lib/domain/entities/folder_model.dart new file mode 100644 index 0000000..70f2996 --- /dev/null +++ b/frontend/lib/domain/entities/folder_model.dart @@ -0,0 +1,126 @@ +class FolderModel { + final int id; + final String name; + final int? parentId; + final int? studentId; + final String? category; + final int? createdBy; + final DateTime createdAt; + final DateTime? updatedAt; + + // Extra fields for display + final String? studentLrn; + final String? studentFirstName; + final String? studentLastName; + final String? createdByUsername; + final int? documentCount; + + // For student folder view + final StudentInfo? student; + final List? subfolders; + final List? physicalFolders; + final List? physicalFiles; + final String? folderPath; + + FolderModel({ + required this.id, + required this.name, + this.parentId, + this.studentId, + this.category, + this.createdBy, + required this.createdAt, + this.updatedAt, + this.studentLrn, + this.studentFirstName, + this.studentLastName, + this.createdByUsername, + this.documentCount, + this.student, + this.subfolders, + this.physicalFolders, + this.physicalFiles, + this.folderPath, + }); + + factory FolderModel.fromJson(Map json) { + return FolderModel( + id: json['id'] as int, + name: json['name'] as String, + parentId: json['parent_id'] as int?, + studentId: json['student_id'] as int?, + category: json['category'] as String?, + createdBy: json['created_by'] as int?, + createdAt: json['created_at'] != null + ? DateTime.parse(json['created_at']) + : DateTime.now(), + updatedAt: json['updated_at'] != null + ? DateTime.parse(json['updated_at']) + : null, + studentLrn: json['lrn'] as String?, + studentFirstName: json['first_name'] as String?, + studentLastName: json['last_name'] as String?, + createdByUsername: json['created_by_username'] as String?, + documentCount: json['document_count'] as int?, + student: json['student'] != null + ? StudentInfo.fromJson(json['student'] as Map) + : null, + subfolders: json['subfolders'] != null + ? (json['subfolders'] as List) + .map((f) => FolderModel.fromJson(f as Map)) + .toList() + : null, + physicalFolders: json['physicalFolders'] != null + ? (json['physicalFolders'] as List) + .map((e) => PhysicalEntry.fromJson(e as Map)) + .toList() + : null, + physicalFiles: json['physicalFiles'] != null + ? (json['physicalFiles'] as List) + .map((e) => PhysicalEntry.fromJson(e as Map)) + .toList() + : null, + folderPath: json['folderPath'] as String?, + ); + } +} + +class StudentInfo { + final int id; + final String lrn; + final String firstName; + final String lastName; + + StudentInfo({ + required this.id, + required this.lrn, + required this.firstName, + required this.lastName, + }); + + factory StudentInfo.fromJson(Map json) { + return StudentInfo( + id: json['id'] as int, + lrn: json['lrn'] as String, + firstName: json['firstName'] as String? ?? json['first_name'] as String? ?? '', + lastName: json['lastName'] as String? ?? json['last_name'] as String? ?? '', + ); + } +} + +class PhysicalEntry { + final String name; + final bool isDirectory; + + PhysicalEntry({ + required this.name, + required this.isDirectory, + }); + + factory PhysicalEntry.fromJson(Map json) { + return PhysicalEntry( + name: json['name'] as String, + isDirectory: json['isDirectory'] as bool? ?? false, + ); + } +} \ No newline at end of file diff --git a/frontend/lib/domain/entities/report_models.dart b/frontend/lib/domain/entities/report_models.dart new file mode 100644 index 0000000..4a1c189 --- /dev/null +++ b/frontend/lib/domain/entities/report_models.dart @@ -0,0 +1,154 @@ +/// Represents one academic year record from the DB. +class AcademicYear { + final int id; + final String yearRange; + final String status; + + const AcademicYear({required this.id, required this.yearRange, required this.status}); + + factory AcademicYear.fromJson(Map j) => AcademicYear( + id: j['id'] as int, + yearRange: j['year_range'] as String, + status: j['status'] as String? ?? 'active', + ); +} + +/// KPI summary numbers for the Reports screen. +class ReportStats { + final int totalStudents; + final int pendingDocs; + final int verifiedDocs; + final int printQueueCount; + final int verificationRate; // 0-100 % + + const ReportStats({ + required this.totalStudents, + required this.pendingDocs, + required this.verifiedDocs, + required this.printQueueCount, + required this.verificationRate, + }); + + factory ReportStats.fromJson(Map j) => ReportStats( + totalStudents: (j['totalStudents'] as num).toInt(), + pendingDocs: (j['pendingDocs'] as num).toInt(), + verifiedDocs: (j['verifiedDocs'] as num).toInt(), + printQueueCount: (j['printQueueCount'] as num).toInt(), + verificationRate: (j['verificationRate'] as num).toInt(), + ); +} + +/// One bar in the "Enrollment by Grade" chart. +class GradeEnrollment { + final int gradeLevel; + final int count; + + const GradeEnrollment({required this.gradeLevel, required this.count}); + + factory GradeEnrollment.fromJson(Map j) => GradeEnrollment( + gradeLevel: (j['grade_level'] as num).toInt(), + count: (j['count'] as num).toInt(), + ); + + String get label => gradeLevel <= 10 ? 'G$gradeLevel' : 'G$gradeLevel'; + String get fullLabel => 'Grade $gradeLevel'; +} + +/// Document verification status breakdown. +class DocumentStatus { + final int pending; + final int verified; + final int draft; + final int archived; + + const DocumentStatus({ + required this.pending, + required this.verified, + required this.draft, + required this.archived, + }); + + int get total => pending + verified + draft + archived; + double get verificationRate => total > 0 ? verified / total : 0.0; + double get pendingRate => total > 0 ? pending / total : 0.0; + + factory DocumentStatus.fromJson(Map j) => DocumentStatus( + pending: (j['Pending'] as num?)?.toInt() ?? 0, + verified: (j['Verified'] as num?)?.toInt() ?? 0, + draft: (j['Draft'] as num?)?.toInt() ?? 0, + archived: (j['Archived'] as num?)?.toInt() ?? 0, + ); +} + +/// One student row for the Excel export detail sheet. +class ReportStudent { + final String lrn; + final String firstName; + final String lastName; + final String sex; + final int? gradeLevel; + final int verifiedDocs; + final int pendingDocs; + + const ReportStudent({ + required this.lrn, + required this.firstName, + required this.lastName, + required this.sex, + this.gradeLevel, + required this.verifiedDocs, + required this.pendingDocs, + }); + + factory ReportStudent.fromJson(Map j) => ReportStudent( + lrn: j['lrn'] as String? ?? '', + firstName: j['first_name'] as String? ?? '', + lastName: j['last_name'] as String? ?? '', + sex: j['sex'] as String? ?? '', + gradeLevel: (j['grade_level'] as num?)?.toInt(), + verifiedDocs: (j['verified_docs'] as num?)?.toInt() ?? 0, + pendingDocs: (j['pending_docs'] as num?)?.toInt() ?? 0, + ); +} + +/// Grade-level summary row for the Excel export. +class GradeExportRow { + final int gradeLevel; + final int totalStudents; + final String yearRange; + + const GradeExportRow({ + required this.gradeLevel, + required this.totalStudents, + required this.yearRange, + }); + + factory GradeExportRow.fromJson(Map j) => GradeExportRow( + gradeLevel: (j['grade_level'] as num).toInt(), + totalStudents: (j['total_students'] as num).toInt(), + yearRange: j['year_range'] as String? ?? 'All Years', + ); +} + +/// Full export payload from /api/reports/export-data. +class ReportExportData { + final List enrollmentByGrade; + final DocumentStatus documentStatus; + final List students; + + const ReportExportData({ + required this.enrollmentByGrade, + required this.documentStatus, + required this.students, + }); + + factory ReportExportData.fromJson(Map j) => ReportExportData( + enrollmentByGrade: (j['enrollmentByGrade'] as List) + .map((e) => GradeExportRow.fromJson(e as Map)) + .toList(), + documentStatus: DocumentStatus.fromJson(j['documentStatus'] as Map), + students: (j['students'] as List) + .map((e) => ReportStudent.fromJson(e as Map)) + .toList(), + ); +} diff --git a/frontend/lib/domain/entities/student_model.dart b/frontend/lib/domain/entities/student_model.dart new file mode 100644 index 0000000..69a2e2d --- /dev/null +++ b/frontend/lib/domain/entities/student_model.dart @@ -0,0 +1,161 @@ +class StudentModel { + final int id; + final String lrn; + final String firstName; + final String? middleName; + final String lastName; + final String? extension; + final String sex; + final DateTime birthDate; + final String status; // 'Enrolled', 'Graduated', 'Transferred Out', 'Dropped' + final int missingDocumentsCount; + final int? latestGradeLevel; + final String? latestSection; + final List? enrollments; + + StudentModel({ + required this.id, + required this.lrn, + required this.firstName, + this.middleName, + required this.lastName, + this.extension, + required this.sex, + required this.birthDate, + this.status = 'Enrolled', + this.missingDocumentsCount = 0, + this.latestGradeLevel, + this.latestSection, + this.enrollments, + }); + + /// Display name: "De La Cruz, Juan Jr. M." + String get fullName { + final ext = extension != null && extension!.isNotEmpty ? ' ${extension!}' : ''; + final mi = middleName != null && middleName!.isNotEmpty ? ' ${middleName![0]}.' : ''; + return '$lastName, $firstName$ext$mi'.trim(); + } + + /// e.g. "Grade 10 – Sec A" + String get gradeSection { + if (latestGradeLevel == null) return '—'; + final section = latestSection?.isNotEmpty == true ? ' — ${latestSection!}' : ''; + return 'Grade $latestGradeLevel$section'; + } + + factory StudentModel.fromJson(Map json) { + return StudentModel( + id: json['id'] as int, + lrn: json['lrn'] as String, + firstName: json['first_name'] as String, + middleName: json['middle_name'] as String?, + lastName: json['last_name'] as String, + extension: json['extension'] as String?, + sex: json['sex'] as String, + birthDate: DateTime.parse(json['birth_date'] as String), + status: json['status'] as String? ?? 'Enrolled', + missingDocumentsCount: (json['missingDocumentsCount'] as num?)?.toInt() ?? 0, + latestGradeLevel: (json['latest_grade_level'] as num?)?.toInt(), + latestSection: json['latest_section'] as String?, + enrollments: json['enrollments'] != null + ? (json['enrollments'] as List) + .map((e) => EnrollmentModel.fromJson(e as Map)) + .toList() + : null, + ); + } + + Map toJson() { + return { + 'id': id, + 'lrn': lrn, + 'first_name': firstName, + 'middle_name': middleName, + 'last_name': lastName, + 'extension': extension, + 'sex': sex, + 'birth_date': birthDate.toIso8601String().split('T').first, + 'status': status, + }; + } + + /// Used when submitting the create/update form + Map toRequestBody() { + return { + 'lrn': lrn, + 'firstName': firstName, + 'middleName': middleName, + 'lastName': lastName, + 'extension': extension, + 'sex': sex, + 'birthDate': birthDate.toIso8601String().split('T').first, + 'status': status, + }; + } + + StudentModel copyWith({ + int? id, + String? lrn, + String? firstName, + String? middleName, + String? lastName, + String? extension, + String? sex, + DateTime? birthDate, + String? status, + int? missingDocumentsCount, + int? latestGradeLevel, + String? latestSection, + }) { + return StudentModel( + id: id ?? this.id, + lrn: lrn ?? this.lrn, + firstName: firstName ?? this.firstName, + middleName: middleName ?? this.middleName, + lastName: lastName ?? this.lastName, + extension: extension ?? this.extension, + sex: sex ?? this.sex, + birthDate: birthDate ?? this.birthDate, + status: status ?? this.status, + missingDocumentsCount: missingDocumentsCount ?? this.missingDocumentsCount, + latestGradeLevel: latestGradeLevel ?? this.latestGradeLevel, + latestSection: latestSection ?? this.latestSection, + enrollments: enrollments ?? this.enrollments, + ); + } +} + +class EnrollmentModel { + final int id; + final int studentId; + final int academicYearId; + final int sectionId; + final int gradeLevel; + final String? trackStrand; + final String? yearRange; + final String? sectionName; + + EnrollmentModel({ + required this.id, + required this.studentId, + required this.academicYearId, + required this.sectionId, + required this.gradeLevel, + this.trackStrand, + this.yearRange, + this.sectionName, + }); + + factory EnrollmentModel.fromJson(Map json) { + return EnrollmentModel( + id: json['id'] as int, + studentId: json['student_id'] as int, + academicYearId: json['academic_year_id'] as int, + sectionId: json['section_id'] as int, + gradeLevel: json['grade_level'] as int, + trackStrand: json['track_strand'] as String?, + yearRange: json['year_range'] as String?, + sectionName: json['section_name'] as String?, + ); + } +} \ No newline at end of file diff --git a/frontend/lib/domain/entities/system_user.dart b/frontend/lib/domain/entities/system_user.dart new file mode 100644 index 0000000..c95734f --- /dev/null +++ b/frontend/lib/domain/entities/system_user.dart @@ -0,0 +1,52 @@ +class SystemUser { + final int id; + final String username; + final String firstName; + final String? middleName; + final String lastName; + final String? extension; + final String role; + final String? email; + final String? phone; + final String? createdAt; + + SystemUser({ + required this.id, + required this.username, + required this.firstName, + this.middleName, + required this.lastName, + this.extension, + required this.role, + this.email, + this.phone, + this.createdAt, + }); + + String get fullName { + final mid = middleName != null && middleName!.isNotEmpty ? '${middleName![0]}. ' : ''; + final ext = extension != null && extension!.isNotEmpty ? ' $extension' : ''; + return '$firstName $mid$lastName$ext'.trim(); + } + + String get initials { + final f = firstName.isNotEmpty ? firstName[0] : ''; + final l = lastName.isNotEmpty ? lastName[0] : ''; + return '$f$l'.toUpperCase(); + } + + factory SystemUser.fromJson(Map json) { + return SystemUser( + id: json['id'] as int, + username: json['username'] as String, + firstName: json['first_name'] as String, + middleName: json['middle_name'] as String?, + lastName: json['last_name'] as String, + extension: json['extension'] as String?, + role: json['role'] as String, + email: json['email'] as String?, + phone: json['phone'] as String?, + createdAt: json['created_at'] as String?, + ); + } +} diff --git a/frontend/lib/domain/entities/user_model.dart b/frontend/lib/domain/entities/user_model.dart new file mode 100644 index 0000000..09f8ec7 --- /dev/null +++ b/frontend/lib/domain/entities/user_model.dart @@ -0,0 +1,54 @@ +class UserModel { + final int id; + final String username; + final String firstName; + final String? middleName; + final String lastName; + final String? extension; + final String role; // 'super_admin', 'admin', 'teacher' + final String? email; + final String? phone; + + UserModel({ + required this.id, + required this.username, + required this.firstName, + this.middleName, + required this.lastName, + this.extension, + required this.role, + this.email, + this.phone, + }); + + // Helper to get full formatted name + String get fullName => '$firstName ${middleName != null ? '${middleName![0]}. ' : ''}$lastName ${extension ?? ''}'.trim(); + + factory UserModel.fromJson(Map json) { + return UserModel( + id: json['id'] as int, + username: json['username'] as String, + firstName: json['first_name'] as String, + middleName: json['middle_name'] as String?, + lastName: json['last_name'] as String, + extension: json['extension'] as String?, + role: json['role'] as String, + email: json['email'] as String?, + phone: json['phone'] as String?, + ); + } + + Map toJson() { + return { + 'id': id, + 'username': username, + 'first_name': firstName, + 'middle_name': middleName, + 'last_name': lastName, + 'extension': extension, + 'role': role, + 'email': email, + 'phone': phone, + }; + } +} \ No newline at end of file diff --git a/frontend/lib/domain/repositories/archive_repository.dart b/frontend/lib/domain/repositories/archive_repository.dart new file mode 100644 index 0000000..b76ee0a --- /dev/null +++ b/frontend/lib/domain/repositories/archive_repository.dart @@ -0,0 +1,88 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../core/network/api_constants.dart'; +import '../entities/archive_model.dart'; + +class ArchivePage { + final List archives; + final int total; + final int page; + final int limit; + final int totalPages; + + const ArchivePage({ + required this.archives, + required this.total, + required this.page, + required this.limit, + required this.totalPages, + }); + + factory ArchivePage.fromJson(Map json) { + final pagination = json['pagination'] as Map; + return ArchivePage( + archives: (json['archives'] as List) + .map((a) => ArchiveModel.fromJson(a as Map)) + .toList(), + total: (pagination['total'] as num).toInt(), + page: (pagination['page'] as num).toInt(), + limit: (pagination['limit'] as num).toInt(), + totalPages: (pagination['totalPages'] as num).toInt(), + ); + } +} + +class ArchiveRepository { + final Dio _dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); + final FlutterSecureStorage _storage = const FlutterSecureStorage(); + + Future _getAuthOptions() async { + final token = await _storage.read(key: 'jwt_token'); + return Options(headers: {'Authorization': 'Bearer $token'}); + } + + Future getArchives({ + String search = '', + int page = 1, + int limit = 10, + String status = 'All Statuses', + }) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get( + '/archives', + queryParameters: { + if (search.trim().isNotEmpty) 'search': search.trim(), + if (status.trim().isNotEmpty) 'status': status.trim(), + 'page': page, + 'limit': limit, + }, + options: options, + ); + return ArchivePage.fromJson(response.data as Map); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch archives.'; + throw Exception(msg); + } + } + + Future restoreArchive(int id) async { + try { + final options = await _getAuthOptions(); + await _dio.post('/archives/$id/restore', options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to restore archive.'; + throw Exception(msg); + } + } + + Future purgeArchive(int id) async { + try { + final options = await _getAuthOptions(); + await _dio.delete('/archives/$id', options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to purge archive.'; + throw Exception(msg); + } + } +} diff --git a/frontend/lib/domain/repositories/auth_repository.dart b/frontend/lib/domain/repositories/auth_repository.dart new file mode 100644 index 0000000..fda0702 --- /dev/null +++ b/frontend/lib/domain/repositories/auth_repository.dart @@ -0,0 +1,173 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../domain/entities/user_model.dart'; +import '../../core/network/api_constants.dart'; + +class AuthRepository { + final Dio _dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); + final FlutterSecureStorage _storage = const FlutterSecureStorage(); + + static const _tokenKey = 'jwt_token'; + static const _rememberMeKey = 'remember_me'; + + Future login(String username, String password, {bool rememberMe = false}) async { + try { + final response = await _dio.post('/auth/login', data: { + 'username': username, + 'password': password, + }); + + final token = response.data['token'] as String; + await _storage.write(key: _tokenKey, value: token); + await _storage.write(key: _rememberMeKey, value: rememberMe ? 'true' : 'false'); + + final userData = response.data['user']; + return UserModel( + id: userData['id'], + username: userData['username'], + firstName: userData['firstName'], + lastName: userData['lastName'], + role: userData['role'], + ); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to connect to the server.'; + throw Exception(errorMessage); + } + } + + /// Auto-login: returns user if a valid Remember Me token is stored, otherwise null. + Future tryAutoLogin() async { + final rememberMe = await _storage.read(key: _rememberMeKey); + if (rememberMe != 'true') return null; + + final token = await _storage.read(key: _tokenKey); + if (token == null) return null; + + try { + final options = Options(headers: {'Authorization': 'Bearer $token'}); + final response = await _dio.get('/auth/profile', options: options); + return UserModel.fromJson(response.data); + } on DioException { + // Token is invalid/expired — clear stored session + await logout(); + return null; + } + } + + Future getToken() async => await _storage.read(key: _tokenKey); + + Future logout() async { + await _storage.delete(key: _tokenKey); + await _storage.delete(key: _rememberMeKey); + } + + Future _getAuthOptions() async { + final token = await getToken(); + return Options(headers: {'Authorization': 'Bearer $token'}); + } + + Future getProfile() async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/auth/profile', options: options); + return UserModel.fromJson(response.data); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to fetch profile.'; + throw Exception(errorMessage); + } + } + + Future updateProfile({ + required String firstName, + String? middleName, + required String lastName, + String? extension, + String? phone, + String? email, + }) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/auth/profile', options: options, data: { + 'firstName': firstName, + 'middleName': middleName, + 'lastName': lastName, + 'extension': extension, + 'phone': phone, + 'email': email, + }); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to update profile.'; + throw Exception(errorMessage); + } + } + + Future changePassword({ + required String currentPassword, + required String newPassword, + required String confirmPassword, + }) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/auth/change-password', options: options, data: { + 'currentPassword': currentPassword, + 'newPassword': newPassword, + 'confirmPassword': confirmPassword, + }); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to change password.'; + throw Exception(errorMessage); + } + } + + /// Submits a forgot-password request (Admin/Teacher only, no auth required). + Future requestPasswordReset({ + required String username, + required String newPassword, + required String confirmPassword, + }) async { + try { + await _dio.post('/auth/forgot-password', data: { + 'username': username, + 'newPassword': newPassword, + 'confirmPassword': confirmPassword, + }); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to submit request.'; + throw Exception(errorMessage); + } + } + + /// Super Admin: get pending password reset requests. + Future>> getResetRequests() async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/auth/reset-requests', options: options); + return List>.from(response.data); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to fetch requests.'; + throw Exception(errorMessage); + } + } + + /// Super Admin: approve a password reset request. + Future approveResetRequest(int requestId) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/auth/reset-requests/$requestId/approve', options: options); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to approve.'; + throw Exception(errorMessage); + } + } + + /// Super Admin: reject a password reset request. + Future rejectResetRequest(int requestId) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/auth/reset-requests/$requestId/reject', options: options); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to reject.'; + throw Exception(errorMessage); + } + } +} \ No newline at end of file diff --git a/frontend/lib/domain/repositories/dashboard_repository.dart b/frontend/lib/domain/repositories/dashboard_repository.dart new file mode 100644 index 0000000..8dd5889 --- /dev/null +++ b/frontend/lib/domain/repositories/dashboard_repository.dart @@ -0,0 +1,44 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../core/network/api_constants.dart'; +import '../entities/dashboard_models.dart'; + +class DashboardRepository { + final Dio _dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); + final FlutterSecureStorage _storage = const FlutterSecureStorage(); + + Future _getAuthOptions() async { + final token = await _storage.read(key: 'jwt_token'); + return Options( + headers: { + 'Authorization': 'Bearer $token', + }, + ); + } + + Future getStats() async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/dashboard/stats', options: options); + return DashboardStats.fromJson(response.data); + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to fetch stats.'; + throw Exception(errorMessage); + } + } + + Future> getPendingTasks() async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/dashboard/pending-tasks', options: options); + + if (response.data is List) { + return (response.data as List).map((task) => PendingTask.fromJson(task)).toList(); + } + return []; + } on DioException catch (e) { + final errorMessage = e.response?.data['message'] ?? 'Failed to fetch pending tasks.'; + throw Exception(errorMessage); + } + } +} diff --git a/frontend/lib/domain/repositories/document_repository.dart b/frontend/lib/domain/repositories/document_repository.dart new file mode 100644 index 0000000..80bbb64 --- /dev/null +++ b/frontend/lib/domain/repositories/document_repository.dart @@ -0,0 +1,435 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../core/network/api_constants.dart'; +import '../entities/document_model.dart'; +import '../entities/document_requirement_model.dart'; +import '../entities/folder_model.dart'; + +class DocumentPage { + final List documents; + final int total; + final int page; + final int limit; + final int totalPages; + + const DocumentPage({ + required this.documents, + required this.total, + required this.page, + required this.limit, + required this.totalPages, + }); + + factory DocumentPage.fromJson(Map json) { + final pagination = json['pagination'] as Map; + return DocumentPage( + documents: (json['documents'] as List) + .map((d) => DocumentModel.fromJson(d as Map)) + .toList(), + total: (pagination['total'] as num).toInt(), + page: (pagination['page'] as num).toInt(), + limit: (pagination['limit'] as num).toInt(), + totalPages: (pagination['totalPages'] as num).toInt(), + ); + } +} + +class PrintQueueItem { + final int queueId; + final int documentId; + final String fileName; + final String filePath; + final String? documentType; + final String status; + final String? studentName; + final String? studentLrn; + final DateTime addedAt; + + const PrintQueueItem({ + required this.queueId, + required this.documentId, + required this.fileName, + required this.filePath, + this.documentType, + required this.status, + this.studentName, + this.studentLrn, + required this.addedAt, + }); + + factory PrintQueueItem.fromJson(Map json) { + return PrintQueueItem( + queueId: json['queue_id'] as int, + documentId: json['document_id'] as int, + fileName: json['file_name'] as String? ?? '', + filePath: json['file_path'] as String? ?? '', + documentType: json['document_type'] as String?, + status: json['status'] as String? ?? 'Pending', + studentName: json['student_name'] as String?, + studentLrn: json['student_lrn'] as String?, + addedAt: json['added_at'] != null + ? DateTime.parse(json['added_at'] as String) + : DateTime.now(), + ); + } +} + + + +class RequirementsSettings { + final List jhs; + final List shs; + final List documentTypes; + + RequirementsSettings({ + required this.jhs, + required this.shs, + required this.documentTypes, + }); + + factory RequirementsSettings.fromJson(Map json) { + return RequirementsSettings( + jhs: (json['jhs'] as List) + .map((r) => DocumentRequirementModel.fromJson(r as Map)) + .toList(), + shs: (json['shs'] as List) + .map((r) => DocumentRequirementModel.fromJson(r as Map)) + .toList(), + documentTypes: (json['documentTypes'] as List) + .map((t) => t as String) + .toList(), + ); + } +} + +class MissingRequirements { + final String category; + final int gradeLevel; + final List missing; + final List pending; + final List verified; + final int totalRequired; + final int totalVerified; + + MissingRequirements({ + required this.category, + required this.gradeLevel, + required this.missing, + required this.pending, + required this.verified, + required this.totalRequired, + required this.totalVerified, + }); + + factory MissingRequirements.fromJson(Map json) { + return MissingRequirements( + category: json['category'] as String, + gradeLevel: json['gradeLevel'] as int, + missing: (json['missing'] as List) + .map((r) => DocumentRequirementModel.fromJson(r as Map)) + .toList(), + pending: (json['pending'] as List) + .map((r) => DocumentRequirementModel.fromJson(r as Map)) + .toList(), + verified: (json['verified'] as List) + .map((r) => DocumentRequirementModel.fromJson(r as Map)) + .toList(), + totalRequired: json['totalRequired'] as int, + totalVerified: json['totalVerified'] as int, + ); + } +} + +class DocumentRepository { + final Dio _dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); + final FlutterSecureStorage _storage = const FlutterSecureStorage(); + + Future _getAuthOptions() async { + final token = await _storage.read(key: 'jwt_token'); + return Options(headers: {'Authorization': 'Bearer $token'}); + } + + // Documents + Future getDocuments({ + String search = '', + int page = 1, + int limit = 20, + String status = 'All Statuses', + String documentType = 'All Types', + String gradeLevel = '', + String schoolYear = '', + }) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get( + '/documents', + queryParameters: { + if (search.trim().isNotEmpty) 'search': search.trim(), + if (status.trim().isNotEmpty && status != 'All Statuses') 'status': status.trim(), + if (documentType.trim().isNotEmpty && documentType != 'All Types') 'documentType': documentType.trim(), + if (gradeLevel.trim().isNotEmpty) 'gradeLevel': gradeLevel.trim(), + if (schoolYear.trim().isNotEmpty) 'schoolYear': schoolYear.trim(), + 'page': page, + 'limit': limit, + }, + options: options, + ); + return DocumentPage.fromJson(response.data as Map); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch documents.'; + throw Exception(msg); + } + } + + Future updateDocumentStatus(int id, String status) async { + try { + final options = await _getAuthOptions(); + await _dio.patch('/documents/$id/status', data: {'status': status}, options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to update status.'; + throw Exception(msg); + } + } + + Future deleteDocument(int id) async { + try { + final options = await _getAuthOptions(); + await _dio.delete('/documents/$id', options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to delete document.'; + throw Exception(msg); + } + } + + Future> getDocumentsByStudent(int studentId) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get( + '/documents/student/$studentId', + options: options, + ); + return (response.data as List) + .map((d) => DocumentModel.fromJson(d as Map)) + .toList(); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch student documents.'; + throw Exception(msg); + } + } + + // Requirements + Future> getRequirements({ + String? category, + bool? isEnabled, + String search = '', + }) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get( + '/requirements', + queryParameters: { + if (category != null) 'category': category, + if (isEnabled != null) 'isEnabled': isEnabled.toString(), + if (search.trim().isNotEmpty) 'search': search.trim(), + }, + options: options, + ); + return (response.data as List) + .map((r) => DocumentRequirementModel.fromJson(r as Map)) + .toList(); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch requirements.'; + throw Exception(msg); + } + } + + Future getRequirementsSettings() async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/requirements/settings', options: options); + return RequirementsSettings.fromJson(response.data as Map); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch requirements settings.'; + throw Exception(msg); + } + } + + Future getMissingRequirements(int studentId) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/requirements/missing/$studentId', options: options); + return MissingRequirements.fromJson(response.data as Map); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch missing requirements.'; + throw Exception(msg); + } + } + + Future createRequirement(DocumentRequirementModel requirement) async { + try { + final options = await _getAuthOptions(); + await _dio.post('/requirements', data: requirement.toJson(), options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to create requirement.'; + throw Exception(msg); + } + } + + Future updateRequirement(DocumentRequirementModel requirement) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/requirements/${requirement.id}', data: requirement.toJson(), options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to update requirement.'; + throw Exception(msg); + } + } + + Future deleteRequirement(int id) async { + try { + final options = await _getAuthOptions(); + await _dio.delete('/requirements/$id', options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to delete requirement.'; + throw Exception(msg); + } + } + + Future bulkUpdateRequirements(List> requirements) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/requirements/bulk', data: {'requirements': requirements}, options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to bulk update requirements.'; + throw Exception(msg); + } + } + + // Folders + Future> getFolders({int? studentId, int? parentId, String search = ''}) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get( + '/folders', + queryParameters: { + if (studentId != null) 'studentId': studentId, + if (parentId != null) 'parentId': parentId.toString(), + if (search.trim().isNotEmpty) 'search': search.trim(), + }, + options: options, + ); + return (response.data as List) + .map((f) => FolderModel.fromJson(f as Map)) + .toList(); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch folders.'; + throw Exception(msg); + } + } + + Future getStudentFolder(int studentId) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/folders/student/$studentId', options: options); + return FolderModel.fromJson(response.data as Map); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch student folder.'; + throw Exception(msg); + } + } + + Future createFolder({required String name, int? parentId, int? studentId, String? category}) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.post( + '/folders', + data: { + 'name': name, + if (parentId != null) 'parentId': parentId, + if (studentId != null) 'studentId': studentId, + if (category != null) 'category': category, + }, + options: options, + ); + return response.data['id'] as int; + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to create folder.'; + throw Exception(msg); + } + } + + Future renameFolder(int id, String name) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/folders/$id', data: {'name': name}, options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to rename folder.'; + throw Exception(msg); + } + } + + Future deleteFolder(int id) async { + try { + final options = await _getAuthOptions(); + await _dio.delete('/folders/$id', options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to delete folder.'; + throw Exception(msg); + } + } + + Future syncFolders(int studentId) async { + try { + final options = await _getAuthOptions(); + await _dio.post('/folders/sync', data: {'studentId': studentId}, options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to sync folders.'; + throw Exception(msg); + } + } + + // Print Queue + Future> getPrintQueue() async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/documents/print-queue', options: options); + return (response.data as List) + .map((i) => PrintQueueItem.fromJson(i as Map)) + .toList(); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch print queue.'; + throw Exception(msg); + } + } + + Future addToPrintQueue(int documentId) async { + try { + final options = await _getAuthOptions(); + await _dio.post('/documents/print-queue', data: {'documentId': documentId}, options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to add to print queue.'; + throw Exception(msg); + } + } + + Future removeFromPrintQueue(int queueId) async { + try { + final options = await _getAuthOptions(); + await _dio.delete('/documents/print-queue/$queueId', options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to remove from print queue.'; + throw Exception(msg); + } + } + + Future clearPrintQueue() async { + try { + final options = await _getAuthOptions(); + await _dio.delete('/documents/print-queue/clear', options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to clear print queue.'; + throw Exception(msg); + } + } +} + diff --git a/frontend/lib/domain/repositories/report_repository.dart b/frontend/lib/domain/repositories/report_repository.dart new file mode 100644 index 0000000..6de2b34 --- /dev/null +++ b/frontend/lib/domain/repositories/report_repository.dart @@ -0,0 +1,71 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../core/network/api_constants.dart'; +import '../entities/report_models.dart'; + +class ReportRepository { + final Dio _dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); + final FlutterSecureStorage _storage = const FlutterSecureStorage(); + + Future _authOptions() async { + final token = await _storage.read(key: 'jwt_token'); + return Options(headers: {'Authorization': 'Bearer $token'}); + } + + Future> getAcademicYears() async { + try { + final res = await _dio.get('/reports/academic-years', options: await _authOptions()); + return (res.data as List).map((e) => AcademicYear.fromJson(e as Map)).toList(); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to fetch academic years.'); + } + } + + Future getStats({int? academicYearId}) async { + try { + final res = await _dio.get( + '/reports/stats', + queryParameters: academicYearId != null ? {'academicYearId': academicYearId} : null, + options: await _authOptions(), + ); + return ReportStats.fromJson(res.data as Map); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to fetch stats.'); + } + } + + Future> getEnrollmentByGrade({int? academicYearId}) async { + try { + final res = await _dio.get( + '/reports/enrollment-by-grade', + queryParameters: academicYearId != null ? {'academicYearId': academicYearId} : null, + options: await _authOptions(), + ); + return (res.data as List).map((e) => GradeEnrollment.fromJson(e as Map)).toList(); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to fetch enrollment data.'); + } + } + + Future getDocumentStatus() async { + try { + final res = await _dio.get('/reports/document-status', options: await _authOptions()); + return DocumentStatus.fromJson(res.data as Map); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to fetch document status.'); + } + } + + Future getExportData({int? academicYearId}) async { + try { + final res = await _dio.get( + '/reports/export-data', + queryParameters: academicYearId != null ? {'academicYearId': academicYearId} : null, + options: await _authOptions(), + ); + return ReportExportData.fromJson(res.data as Map); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to fetch export data.'); + } + } +} diff --git a/frontend/lib/domain/repositories/student_repository.dart b/frontend/lib/domain/repositories/student_repository.dart new file mode 100644 index 0000000..ab62517 --- /dev/null +++ b/frontend/lib/domain/repositories/student_repository.dart @@ -0,0 +1,171 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../core/network/api_constants.dart'; +import '../entities/student_model.dart'; + +/// Paginated student list returned from the API. +class StudentPage { + final List students; + final int total; + final int page; + final int limit; + final int totalPages; + + const StudentPage({ + required this.students, + required this.total, + required this.page, + required this.limit, + required this.totalPages, + }); + + factory StudentPage.fromJson(Map json) { + final pagination = json['pagination'] as Map; + return StudentPage( + students: (json['students'] as List) + .map((s) => StudentModel.fromJson(s as Map)) + .toList(), + total: (pagination['total'] as num).toInt(), + page: (pagination['page'] as num).toInt(), + limit: (pagination['limit'] as num).toInt(), + totalPages: (pagination['totalPages'] as num).toInt(), + ); + } +} + +class StudentRepository { + final Dio _dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); + final FlutterSecureStorage _storage = const FlutterSecureStorage(); + + Future _getAuthOptions() async { + final token = await _storage.read(key: 'jwt_token'); + return Options(headers: {'Authorization': 'Bearer $token'}); + } + + // ---------------------------------------------------------------- + // Fetch paginated students with optional search + filters + // ---------------------------------------------------------------- + Future getStudents({ + String search = '', + int page = 1, + int limit = 10, + String gradeLevel = '', + String status = '', + }) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get( + '/students', + queryParameters: { + if (search.trim().isNotEmpty) 'search': search.trim(), + if (gradeLevel.trim().isNotEmpty) 'gradeLevel': gradeLevel.trim(), + if (status.trim().isNotEmpty) 'status': status.trim(), + 'page': page, + 'limit': limit, + }, + options: options, + ); + return StudentPage.fromJson(response.data as Map); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch students.'; + throw Exception(msg); + } + } + + // ---------------------------------------------------------------- + // Get single student by ID + // ---------------------------------------------------------------- + Future getStudentById(int id) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/students/$id', options: options); + return StudentModel.fromJson(response.data as Map); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to fetch student.'; + throw Exception(msg); + } + } + + // ---------------------------------------------------------------- + // Create student — returns the newly created ID + // ---------------------------------------------------------------- + Future createStudent({ + required String lrn, + required String firstName, + String? middleName, + required String lastName, + String? extension, + required String sex, + required DateTime birthDate, + }) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.post( + '/students', + data: { + 'lrn': lrn.trim(), + 'firstName': firstName.trim(), + 'middleName': middleName?.trim(), + 'lastName': lastName.trim(), + 'extension': extension?.trim(), + 'sex': sex, + 'birthDate': '${birthDate.year}-${birthDate.month.toString().padLeft(2, '0')}-${birthDate.day.toString().padLeft(2, '0')}', + }, + options: options, + ); + return (response.data['id'] as num).toInt(); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to create student.'; + throw Exception(msg); + } + } + + // ---------------------------------------------------------------- + // Update student + // ---------------------------------------------------------------- + Future updateStudent({ + required int id, + required String lrn, + required String firstName, + String? middleName, + required String lastName, + String? extension, + required String sex, + required DateTime birthDate, + String status = 'Enrolled', + }) async { + try { + final options = await _getAuthOptions(); + await _dio.put( + '/students/$id', + data: { + 'lrn': lrn.trim(), + 'firstName': firstName.trim(), + 'middleName': middleName?.trim(), + 'lastName': lastName.trim(), + 'extension': extension?.trim(), + 'sex': sex, + 'birthDate': '${birthDate.year}-${birthDate.month.toString().padLeft(2, '0')}-${birthDate.day.toString().padLeft(2, '0')}', + 'status': status, + }, + options: options, + ); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to update student.'; + throw Exception(msg); + } + } + + // ---------------------------------------------------------------- + // Delete student + // ---------------------------------------------------------------- + Future deleteStudent(int id) async { + try { + final options = await _getAuthOptions(); + await _dio.delete('/students/$id', options: options); + } on DioException catch (e) { + final msg = e.response?.data?['message'] ?? 'Failed to delete student.'; + throw Exception(msg); + } + } +} diff --git a/frontend/lib/domain/repositories/user_repository.dart b/frontend/lib/domain/repositories/user_repository.dart new file mode 100644 index 0000000..f089f28 --- /dev/null +++ b/frontend/lib/domain/repositories/user_repository.dart @@ -0,0 +1,101 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../core/network/api_constants.dart'; +import '../entities/system_user.dart'; + +class UserRepository { + final Dio _dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); + final FlutterSecureStorage _storage = const FlutterSecureStorage(); + + Future _getAuthOptions() async { + final token = await _storage.read(key: 'jwt_token'); + return Options(headers: {'Authorization': 'Bearer $token'}); + } + + Future> getUsers() async { + try { + final options = await _getAuthOptions(); + final response = await _dio.get('/users', options: options); + return (response.data as List).map((u) => SystemUser.fromJson(u)).toList(); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to fetch users.'); + } + } + + /// Creates a user and returns the temporary plaintext password (shown once only). + Future createUser({ + required String username, + String? password, // optional — backend auto-generates if omitted + required String firstName, + String? middleName, + required String lastName, + String? extension, + required String role, + String? email, + String? phone, + }) async { + try { + final options = await _getAuthOptions(); + final response = await _dio.post('/users', options: options, data: { + 'username': username, + if (password != null && password.isNotEmpty) 'password': password, + 'firstName': firstName, + 'middleName': middleName, + 'lastName': lastName, + 'extension': extension, + 'role': role, + 'email': email, + 'phone': phone, + }); + final tempPass = response.data['temporaryPassword']; + if (tempPass == null) throw Exception('No temporary password in response.'); + return tempPass as String; + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to create user.'); + } + } + + Future updateUser({ + required int id, + required String firstName, + String? middleName, + required String lastName, + String? extension, + required String role, + String? email, + String? phone, + }) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/users/$id', options: options, data: { + 'firstName': firstName, + 'middleName': middleName, + 'lastName': lastName, + 'extension': extension, + 'role': role, + 'email': email, + 'phone': phone, + }); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to update user.'); + } + } + + Future resetPassword(int id) async { + try { + final options = await _getAuthOptions(); + await _dio.put('/users/$id/reset-password', options: options); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to reset password.'); + } + } + + Future deleteUser(int id) async { + try { + final options = await _getAuthOptions(); + await _dio.delete('/users/$id', options: options); + } on DioException catch (e) { + throw Exception(e.response?.data['message'] ?? 'Failed to delete user.'); + } + } +} diff --git a/frontend/lib/main.dart b/frontend/lib/main.dart new file mode 100644 index 0000000..93d1739 --- /dev/null +++ b/frontend/lib/main.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +// UI Imports +import 'ui/screens/splash/splash_screen.dart'; +// Core Imports +import 'core/theme/app_theme.dart'; // Add this import + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + await SystemChrome.setPreferredOrientations([ + DeviceOrientation.portraitUp, + DeviceOrientation.portraitDown, + ]); + runApp(const ProviderScope(child: TisRmsApp())); +} + +class TisRmsApp extends StatelessWidget { + const TisRmsApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'TIS RMS', + debugShowCheckedModeBanner: false, + + // Clean, centralized theme reference! + theme: AppTheme.lightTheme, + + home: const SplashScreen(), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/layouts/android_bottom_nav_layout.dart b/frontend/lib/ui/layouts/android_bottom_nav_layout.dart new file mode 100644 index 0000000..f011122 --- /dev/null +++ b/frontend/lib/ui/layouts/android_bottom_nav_layout.dart @@ -0,0 +1,203 @@ +import 'package:flutter/material.dart'; +import '../../core/constants/app_colors.dart'; +import '../../core/constants/app_sizes.dart'; +import '../screens/dashboard/dashboard_screen.dart'; +import '../screens/settings/settings_screen.dart'; +import '../screens/students/students_screen.dart'; +import '../screens/documents/documents_screen.dart'; +import '../screens/archives/archives_screen.dart'; +import '../screens/reports/reports_screen.dart'; +import '../screens/users/users_screen.dart'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; // Import Riverpod +import '../providers/auth_provider.dart'; // Import your Auth Provider +import '../screens/login/login_screen.dart'; // Import the Login Screen + +// Dummy screen for placeholders +class PlaceholderScreen extends StatelessWidget { + final String title; + const PlaceholderScreen(this.title, {super.key}); + @override + Widget build(BuildContext context) => Center(child: Text(title, style: const TextStyle(fontSize: 24))); +} + +class AndroidBottomNavLayout extends ConsumerStatefulWidget { + final String userRole; + + const AndroidBottomNavLayout({super.key, required this.userRole}); + + @override + ConsumerState createState() => _AndroidBottomNavLayoutState(); +} + +class _AndroidBottomNavLayoutState extends ConsumerState { + int _selectedBottomNavIndex = 0; + int _activeStackIndex = 0; + + void _onNavTapped(int index, List> allowedPrimary, List> allowedSecondary) { + if (index < allowedPrimary.length) { + setState(() { + _selectedBottomNavIndex = index; + _activeStackIndex = index; + }); + } else { + _showMoreBottomSheet(allowedPrimary, allowedSecondary); + } + } + + void _showMoreBottomSheet(List> allowedPrimary, List> allowedSecondary) { + showModalBottomSheet( + context: context, + backgroundColor: AppColors.surfaceWhite, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(AppSizes.radiusLarge)), + ), + builder: (context) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: AppSizes.p12), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Drag Handle + Container( + width: 40, + height: 5, + margin: const EdgeInsets.only(bottom: AppSizes.p16), + decoration: BoxDecoration( + color: Colors.grey.shade300, + borderRadius: BorderRadius.circular(AppSizes.radiusSmall), + ), + ), + // Build Secondary Tabs + ...allowedSecondary.asMap().entries.map((entry) { + int secondaryIndex = entry.key; + var tab = entry.value; + + return ListTile( + leading: Container( + padding: const EdgeInsets.all(AppSizes.p8), + decoration: BoxDecoration( + color: AppColors.primaryGreen.withOpacity(0.1), + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + child: Icon(tab['icon'] as IconData, color: AppColors.primaryGreen), + ), + title: Text( + tab['label'] as String, + style: const TextStyle(fontWeight: FontWeight.w600, color: AppColors.textPrimary), + ), + trailing: const Icon(Icons.chevron_right, color: AppColors.textMuted), + onTap: () { + Navigator.pop(context); + setState(() { + _selectedBottomNavIndex = allowedPrimary.length; + _activeStackIndex = allowedPrimary.length + secondaryIndex; + }); + }, + ); + }), + const Divider(), + // Logout Option in the More Menu + ListTile( + leading: const Padding( + padding: EdgeInsets.all(AppSizes.p8), + child: Icon(Icons.logout, color: AppColors.error), + ), + title: const Text( + 'Logout', + style: TextStyle(fontWeight: FontWeight.w600, color: AppColors.error), + ), + onTap: () { + _handleLogout(); + }, + ), + ], + ), + ), + ); + }, + ); + } + + void _handleLogout() async { + // Close the Bottom Sheet modal first + Navigator.pop(context); + + // Clear state + await ref.read(authProvider.notifier).logout(); + + if (!mounted) return; + + // Route to Login + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => const LoginScreen()), + (route) => false, + ); + } + + @override + Widget build(BuildContext context) { + final primaryTabsConfig = [ + {'label': 'Dashboard', 'icon': Icons.dashboard, 'screen': const DashboardScreen(), 'roles': ['super_admin', 'admin', 'teacher']}, + {'label': 'Students', 'icon': Icons.people_outline, 'screen': StudentsScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin', 'teacher']}, + {'label': 'Documents', 'icon': Icons.folder_outlined, 'screen': DocumentsScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin', 'teacher']}, + {'label': 'Archives', 'icon': Icons.archive_outlined, 'screen': ArchivesScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin']}, + ]; + final secondaryTabsConfig = [ + {'label': 'Reports', 'icon': Icons.bar_chart_outlined, 'screen': ReportsScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin']}, + {'label': 'Users', 'icon': Icons.manage_accounts_outlined, 'screen': const UsersScreen(), 'roles': ['super_admin']}, + {'label': 'Settings', 'icon': Icons.settings_outlined, 'screen': SettingsScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin', 'teacher']}, + ]; + final allowedPrimary = primaryTabsConfig.where((t) => (t['roles'] as List).contains(widget.userRole)).toList(); + final allowedSecondary = secondaryTabsConfig.where((t) => (t['roles'] as List).contains(widget.userRole)).toList(); + final allAllowedTabs = [...allowedPrimary, ...allowedSecondary]; + + List bottomNavItems = allowedPrimary.map((tab) { + return BottomNavigationBarItem( + icon: Icon(tab['icon'] as IconData), + label: tab['label'] as String, + ); + }).toList(); + + if (allowedSecondary.isNotEmpty) { + bottomNavItems.add( + const BottomNavigationBarItem( + icon: Icon(Icons.more_horiz), + label: 'More', + ), + ); + } + + return Scaffold( + backgroundColor: AppColors.pageBackground, + body: IndexedStack( + index: _activeStackIndex, + children: allAllowedTabs.map((t) => t['screen'] as Widget).toList(), + ), + bottomNavigationBar: Container( + decoration: BoxDecoration( + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.1), + blurRadius: 10, + offset: const Offset(0, -5), + ), + ], + ), + child: BottomNavigationBar( + currentIndex: _selectedBottomNavIndex, + onTap: (i) => _onNavTapped(i, allowedPrimary, allowedSecondary), + backgroundColor: AppColors.primaryGreen, + selectedItemColor: Colors.white, + unselectedItemColor: Colors.white70, + showUnselectedLabels: true, + type: BottomNavigationBarType.fixed, + selectedLabelStyle: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12), + unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w500, fontSize: 11), + items: bottomNavItems, + ), + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/layouts/responsive_layout.dart b/frontend/lib/ui/layouts/responsive_layout.dart new file mode 100644 index 0000000..d196742 --- /dev/null +++ b/frontend/lib/ui/layouts/responsive_layout.dart @@ -0,0 +1,25 @@ +import 'package:flutter/material.dart'; +import 'android_bottom_nav_layout.dart'; +import 'windows_sidebar_layout.dart'; + +class ResponsiveLayout extends StatelessWidget { + final String userRole; // Keep passing this from your Auth State + + const ResponsiveLayout({super.key, required this.userRole}); + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) { + // Breakpoint: If width is less than 800px, serve Mobile/Android UI + if (constraints.maxWidth < 800) { + return AndroidBottomNavLayout(userRole: userRole); + } + // Breakpoint: If width is 800px or larger, serve Desktop/Windows UI + else { + return WindowsSidebarLayout(userRole: userRole); + } + }, + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/layouts/windows_sidebar_layout.dart b/frontend/lib/ui/layouts/windows_sidebar_layout.dart new file mode 100644 index 0000000..02c2ef3 --- /dev/null +++ b/frontend/lib/ui/layouts/windows_sidebar_layout.dart @@ -0,0 +1,183 @@ +import 'package:flutter/material.dart'; +import '../../core/constants/app_colors.dart'; +import '../../core/constants/app_sizes.dart'; +import '../screens/dashboard/dashboard_screen.dart'; +import '../screens/settings/settings_screen.dart'; +import '../screens/students/students_screen.dart'; +import '../screens/documents/documents_screen.dart'; +import '../screens/archives/archives_screen.dart'; +import '../screens/reports/reports_screen.dart'; +import '../screens/users/users_screen.dart'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; // Import Riverpod +import '../providers/auth_provider.dart'; // Import your Auth Provider +import '../screens/login/login_screen.dart'; // Import the Login Screen + +// Dummy screen for placeholders +class PlaceholderScreen extends StatelessWidget { + final String title; + const PlaceholderScreen(this.title, {super.key}); + @override + Widget build(BuildContext context) => Center(child: Text(title, style: const TextStyle(fontSize: 24))); +} + +class WindowsSidebarLayout extends ConsumerStatefulWidget { + final String userRole; + + const WindowsSidebarLayout({super.key, required this.userRole}); + + @override + ConsumerState createState() => _WindowsSidebarLayoutState(); +} + +class _WindowsSidebarLayoutState extends ConsumerState { + int _currentIndex = 0; + + void _handleLogout() async { + await ref.read(authProvider.notifier).logout(); + if (!mounted) return; + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => const LoginScreen()), + (route) => false, + ); + } + + @override + Widget build(BuildContext context) { + final allTabs = [ + {'label': 'Dashboard', 'icon': Icons.dashboard_outlined, 'activeIcon': Icons.dashboard, 'screen': const DashboardScreen(), 'roles': ['super_admin', 'admin', 'teacher']}, + {'label': 'Students', 'icon': Icons.people_outline, 'activeIcon': Icons.people, 'screen': StudentsScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin', 'teacher']}, + {'label': 'Documents', 'icon': Icons.folder_outlined, 'activeIcon': Icons.folder, 'screen': DocumentsScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin', 'teacher']}, + {'label': 'Archives', 'icon': Icons.archive_outlined, 'activeIcon': Icons.archive, 'screen': ArchivesScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin']}, + {'label': 'Reports', 'icon': Icons.bar_chart_outlined, 'activeIcon': Icons.bar_chart, 'screen': ReportsScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin']}, + {'label': 'Users', 'icon': Icons.manage_accounts_outlined, 'activeIcon': Icons.manage_accounts, 'screen': const UsersScreen(), 'roles': ['super_admin']}, + {'label': 'Settings', 'icon': Icons.settings_outlined, 'activeIcon': Icons.settings, 'screen': SettingsScreen(userRole: widget.userRole), 'roles': ['super_admin', 'admin', 'teacher']}, + ]; + final tabs = allTabs.where((tab) => (tab['roles'] as List).contains(widget.userRole)).toList(); + + return Scaffold( + backgroundColor: AppColors.pageBackground, // Solid Off-white beige + body: Row( + children: [ + // ========================================== + // WINDOWS SIDEBAR (Fixed Width: 260px) + // ========================================== + Container( + width: 260, + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [AppColors.darkGreen, AppColors.primaryGreen], + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.15), + blurRadius: 10, + offset: const Offset(3, 0), + ) + ], + ), + child: Column( + children: [ + // Branding Header + Padding( + padding: const EdgeInsets.symmetric( + vertical: AppSizes.p32, + horizontal: AppSizes.p24 + ), + child: Row( + children: [ + Image.asset('assets/images/logo.png', width: 42, height: 42), + const SizedBox(width: AppSizes.p12), + const Expanded( + child: Text( + 'TIS RMS', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: Colors.white, + letterSpacing: 1.0, + ), + ), + ), + ], + ), + ), + + // Navigation Items + Expanded( + child: ListView.builder( + padding: const EdgeInsets.symmetric(horizontal: AppSizes.p12), + itemCount: tabs.length, + itemBuilder: (context, index) { + final tab = tabs[index]; + final isSelected = _currentIndex == index; + + return Padding( + padding: const EdgeInsets.only(bottom: AppSizes.p8), + child: Material( + color: Colors.transparent, + child: ListTile( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + selected: isSelected, + selectedTileColor: Colors.white.withOpacity(0.15), // Soft highlight + leading: Icon( + (isSelected ? tab['activeIcon'] ?? tab['icon'] : tab['icon']) as IconData, + color: isSelected ? Colors.white : Colors.white70, + ), + title: Text( + tab['label'] as String, + style: TextStyle( + fontWeight: isSelected ? FontWeight.bold : FontWeight.w500, + color: isSelected ? Colors.white : Colors.white70, + fontSize: 15, + ), + ), + onTap: () => setState(() => _currentIndex = index), + ), + ), + ); + }, + ), + ), + + // Bottom Section: Logout + Divider(height: 1, color: Colors.white24), + Padding( + padding: const EdgeInsets.all(AppSizes.p16), + child: ListTile( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + leading: Icon(Icons.logout, color: Colors.redAccent.shade100), + title: Text( + 'Logout', + style: TextStyle(color: Colors.redAccent.shade100, fontWeight: FontWeight.bold), + ), + hoverColor: Colors.white.withOpacity(0.05), + onTap: () { + _handleLogout(); + }, + ), + ), + ], + ), + ), + + // ========================================== + // MAIN CONTENT AREA + // ========================================== + Expanded( + child: IndexedStack( + index: _currentIndex, + children: tabs.map((t) => t['screen'] as Widget).toList(), + ), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/providers/archives_provider.dart b/frontend/lib/ui/providers/archives_provider.dart new file mode 100644 index 0000000..c7fe808 --- /dev/null +++ b/frontend/lib/ui/providers/archives_provider.dart @@ -0,0 +1,93 @@ +import 'dart:async'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../domain/repositories/archive_repository.dart'; + +final archiveRepositoryProvider = Provider((ref) { + return ArchiveRepository(); +}); + +class ArchiveQueryParams { + final String search; + final int page; + final int limit; + final String status; + + const ArchiveQueryParams({ + this.search = '', + this.page = 1, + this.limit = 10, + this.status = 'All Statuses', + }); + + ArchiveQueryParams copyWith({ + String? search, + int? page, + int? limit, + String? status, + }) { + return ArchiveQueryParams( + search: search ?? this.search, + page: page ?? this.page, + limit: limit ?? this.limit, + status: status ?? this.status, + ); + } +} + +final archiveQueryProvider = NotifierProvider(ArchiveQueryNotifier.new); + +class ArchiveQueryNotifier extends Notifier { + @override + ArchiveQueryParams build() => const ArchiveQueryParams(); + + void setSearch(String value) => state = state.copyWith(search: value, page: 1); + void setPage(int page) => state = state.copyWith(page: page); + void setLimit(int limit) => state = state.copyWith(limit: limit, page: 1); + void setStatus(String status) => state = state.copyWith(status: status, page: 1); + void reset() => state = const ArchiveQueryParams(); +} + +final archivePageProvider = FutureProvider.autoDispose((ref) async { + final query = ref.watch(archiveQueryProvider); + final repo = ref.read(archiveRepositoryProvider); + + return repo.getArchives( + search: query.search, + page: query.page, + limit: query.limit, + status: query.status, + ); +}); + +final archiveMutationProvider = AsyncNotifierProvider(ArchiveMutationNotifier.new); + +class ArchiveMutationNotifier extends AsyncNotifier { + @override + FutureOr build() {} + + Future restoreArchive(int id) async { + state = const AsyncLoading(); + try { + final repo = ref.read(archiveRepositoryProvider); + await repo.restoreArchive(id); + state = const AsyncData(null); + ref.invalidate(archivePageProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future purgeArchive(int id) async { + state = const AsyncLoading(); + try { + final repo = ref.read(archiveRepositoryProvider); + await repo.purgeArchive(id); + state = const AsyncData(null); + ref.invalidate(archivePageProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } +} diff --git a/frontend/lib/ui/providers/auth_provider.dart b/frontend/lib/ui/providers/auth_provider.dart new file mode 100644 index 0000000..7a293aa --- /dev/null +++ b/frontend/lib/ui/providers/auth_provider.dart @@ -0,0 +1,62 @@ +import 'dart:async'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../domain/repositories/auth_repository.dart'; +import '../../domain/entities/user_model.dart'; + +final authRepositoryProvider = Provider((ref) => AuthRepository()); + +final authProvider = AsyncNotifierProvider(() { + return AuthNotifier(); +}); + +class AuthNotifier extends AsyncNotifier { + @override + FutureOr build() { + return null; // Always starts null; auto-login handled in SplashScreen + } + + Future login(String username, String password, {bool rememberMe = false}) async { + state = const AsyncLoading(); + try { + final repository = ref.read(authRepositoryProvider); + final user = await repository.login(username, password, rememberMe: rememberMe); + state = AsyncData(user); + return true; + } catch (e, st) { + state = AsyncError(e, st); + return false; + } + } + + /// Called from SplashScreen — tries to auto-login from stored token. + Future tryAutoLogin() async { + try { + final repository = ref.read(authRepositoryProvider); + final user = await repository.tryAutoLogin(); + if (user != null) { + state = AsyncData(user); + } + return user; + } catch (_) { + return null; + } + } + + Future logout() async { + final repository = ref.read(authRepositoryProvider); + await repository.logout(); + state = const AsyncData(null); + } +} + +// Full profile data provider +final profileProvider = FutureProvider.autoDispose((ref) async { + final repository = ref.read(authRepositoryProvider); + return await repository.getProfile(); +}); + +// Super Admin: pending password reset requests +final resetRequestsProvider = FutureProvider.autoDispose>>((ref) async { + final repository = ref.read(authRepositoryProvider); + return await repository.getResetRequests(); +}); \ No newline at end of file diff --git a/frontend/lib/ui/providers/dashboard_provider.dart b/frontend/lib/ui/providers/dashboard_provider.dart new file mode 100644 index 0000000..af404a3 --- /dev/null +++ b/frontend/lib/ui/providers/dashboard_provider.dart @@ -0,0 +1,23 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../domain/repositories/dashboard_repository.dart'; +import '../../domain/entities/dashboard_models.dart'; + +final dashboardRepositoryProvider = Provider((ref) { + return DashboardRepository(); +}); + +class DashboardData { + final DashboardStats stats; + final List pendingTasks; + + DashboardData({required this.stats, required this.pendingTasks}); +} + +final dashboardDataProvider = FutureProvider.autoDispose((ref) async { + final repository = ref.read(dashboardRepositoryProvider); + + final stats = await repository.getStats(); + final tasks = await repository.getPendingTasks(); + + return DashboardData(stats: stats, pendingTasks: tasks); +}); diff --git a/frontend/lib/ui/providers/document_provider.dart b/frontend/lib/ui/providers/document_provider.dart new file mode 100644 index 0000000..6f63e8f --- /dev/null +++ b/frontend/lib/ui/providers/document_provider.dart @@ -0,0 +1,424 @@ +import 'dart:async'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../domain/repositories/document_repository.dart'; +import '../../domain/entities/document_requirement_model.dart'; +import '../../domain/entities/folder_model.dart'; + +final documentRepositoryProvider = Provider((ref) { + return DocumentRepository(); +}); + +// ============================================================ +// Query params for documents +// ============================================================ +class DocumentQueryParams { + final String search; + final int page; + final int limit; + final String status; + final String documentType; + final String gradeLevel; + final String schoolYear; + // Optional: filter by specific student (for "Open Documents Folder" redirect) + final int? studentId; + + const DocumentQueryParams({ + this.search = '', + this.page = 1, + this.limit = 20, + this.status = 'All Statuses', + this.documentType = 'All Types', + this.gradeLevel = '', + this.schoolYear = '', + this.studentId, + }); + + DocumentQueryParams copyWith({ + String? search, + int? page, + int? limit, + String? status, + String? documentType, + String? gradeLevel, + String? schoolYear, + int? studentId, + bool clearStudentId = false, + }) { + return DocumentQueryParams( + search: search ?? this.search, + page: page ?? this.page, + limit: limit ?? this.limit, + status: status ?? this.status, + documentType: documentType ?? this.documentType, + gradeLevel: gradeLevel ?? this.gradeLevel, + schoolYear: schoolYear ?? this.schoolYear, + studentId: clearStudentId ? null : (studentId ?? this.studentId), + ); + } +} + +final documentQueryProvider = + NotifierProvider( + DocumentQueryNotifier.new); + +class DocumentQueryNotifier extends Notifier { + @override + DocumentQueryParams build() => const DocumentQueryParams(); + + void setSearch(String value) => state = state.copyWith(search: value, page: 1); + void setPage(int page) => state = state.copyWith(page: page); + void setLimit(int limit) => state = state.copyWith(limit: limit, page: 1); + void setStatus(String status) => state = state.copyWith(status: status, page: 1); + void setDocumentType(String type) => state = state.copyWith(documentType: type, page: 1); + void setGradeLevel(String gradeLevel) => state = state.copyWith(gradeLevel: gradeLevel, page: 1); + void setSchoolYear(String schoolYear) => state = state.copyWith(schoolYear: schoolYear, page: 1); + + /// Navigate to a specific student's documents + void setStudentId(int? studentId) { + state = state.copyWith( + studentId: studentId, + clearStudentId: studentId == null, + page: 1, + search: '', + ); + } + + void reset() => state = const DocumentQueryParams(); +} + +// ============================================================ +// Document page provider — fetches from /documents with all filters +// OR from /documents/student/:id when studentId is specified +// ============================================================ +final documentPageProvider = + FutureProvider.autoDispose((ref) async { + final query = ref.watch(documentQueryProvider); + final repo = ref.read(documentRepositoryProvider); + + // If filtering by a specific student, use the student-specific endpoint + if (query.studentId != null) { + final docs = await repo.getDocumentsByStudent(query.studentId!); + return DocumentPage( + documents: docs, + total: docs.length, + page: 1, + limit: docs.length, + totalPages: 1, + ); + } + + return repo.getDocuments( + search: query.search, + page: query.page, + limit: query.limit, + status: query.status, + documentType: query.documentType, + gradeLevel: query.gradeLevel, + schoolYear: query.schoolYear, + ); +}); + + +// ============================================================ +// Student-specific documents provider +// ============================================================ +final studentDocumentsProvider = + FutureProvider.family.autoDispose, int>((ref, studentId) async { + final repo = ref.read(documentRepositoryProvider); + return repo.getDocumentsByStudent(studentId); +}); + +// ============================================================ +// Folders for all students — list of student root folders +// ============================================================ +final studentFoldersProvider = + FutureProvider.autoDispose>((ref) async { + final repo = ref.read(documentRepositoryProvider); + // Fetch top-level folders (no parentId filter = all root folders) + return repo.getFolders(); +}); + +// ============================================================ +// Requirements providers +// ============================================================ +final documentRequirementsProvider = + FutureProvider.autoDispose>((ref) async { + final repo = ref.read(documentRepositoryProvider); + return repo.getRequirements(); +}); + +final requirementsSettingsProvider = + FutureProvider.autoDispose((ref) async { + final repo = ref.read(documentRepositoryProvider); + return repo.getRequirementsSettings(); +}); + +final missingRequirementsProvider = + FutureProvider.family.autoDispose((ref, studentId) async { + final repo = ref.read(documentRepositoryProvider); + return repo.getMissingRequirements(studentId); +}); + +// ============================================================ +// Folder providers +// ============================================================ +final foldersProvider = + FutureProvider.autoDispose>((ref) async { + final repo = ref.read(documentRepositoryProvider); + return repo.getFolders(); +}); + +final studentFolderProvider = + FutureProvider.family.autoDispose((ref, studentId) async { + final repo = ref.read(documentRepositoryProvider); + return repo.getStudentFolder(studentId); +}); + +// ============================================================ +// Print Queue providers +// ============================================================ +final printQueueProvider = + FutureProvider.autoDispose>((ref) async { + final repo = ref.read(documentRepositoryProvider); + return repo.getPrintQueue(); +}); + +final printQueueMutationProvider = + AsyncNotifierProvider( + PrintQueueMutationNotifier.new); + +class PrintQueueMutationNotifier extends AsyncNotifier { + @override + FutureOr build() {} + + Future addToQueue(int documentId) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.addToPrintQueue(documentId); + state = const AsyncData(null); + ref.invalidate(printQueueProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future removeFromQueue(int queueId) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.removeFromPrintQueue(queueId); + state = const AsyncData(null); + ref.invalidate(printQueueProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future clearQueue() async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.clearPrintQueue(); + state = const AsyncData(null); + ref.invalidate(printQueueProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } +} + +// ============================================================ +// Document mutations +// ============================================================ +final documentMutationProvider = + AsyncNotifierProvider( + DocumentMutationNotifier.new); + +class DocumentMutationNotifier extends AsyncNotifier { + @override + FutureOr build() {} + + Future updateDocumentStatus(int id, String status) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.updateDocumentStatus(id, status); + state = const AsyncData(null); + ref.invalidate(documentPageProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future deleteDocument(int id) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.deleteDocument(id); + state = const AsyncData(null); + ref.invalidate(documentPageProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } +} + +// ============================================================ +// Requirement mutations +// ============================================================ +final requirementMutationProvider = + AsyncNotifierProvider( + RequirementMutationNotifier.new); + +class RequirementMutationNotifier extends AsyncNotifier { + @override + FutureOr build() {} + + Future createRequirement(DocumentRequirementModel requirement) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.createRequirement(requirement); + state = const AsyncData(null); + ref.invalidate(requirementsSettingsProvider); + ref.invalidate(documentRequirementsProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future updateRequirement(DocumentRequirementModel requirement) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.updateRequirement(requirement); + state = const AsyncData(null); + ref.invalidate(requirementsSettingsProvider); + ref.invalidate(documentRequirementsProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future deleteRequirement(int id) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.deleteRequirement(id); + state = const AsyncData(null); + ref.invalidate(requirementsSettingsProvider); + ref.invalidate(documentRequirementsProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future bulkUpdateRequirements( + List> requirements) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.bulkUpdateRequirements(requirements); + state = const AsyncData(null); + ref.invalidate(requirementsSettingsProvider); + ref.invalidate(documentRequirementsProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } +} + +// ============================================================ +// Folder mutations +// ============================================================ +final folderMutationProvider = + AsyncNotifierProvider( + FolderMutationNotifier.new); + +class FolderMutationNotifier extends AsyncNotifier { + @override + FutureOr build() {} + + Future createFolder( + {required String name, + int? parentId, + int? studentId, + String? category}) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + final id = await repo.createFolder( + name: name, + parentId: parentId, + studentId: studentId, + category: category, + ); + state = const AsyncData(null); + ref.invalidate(foldersProvider); + ref.invalidate(studentFoldersProvider); + if (studentId != null) { + ref.invalidate(studentFolderProvider(studentId)); + } + return id; + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future renameFolder(int id, String name) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.renameFolder(id, name); + state = const AsyncData(null); + ref.invalidate(foldersProvider); + ref.invalidate(studentFoldersProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future deleteFolder(int id, {int? studentId}) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.deleteFolder(id); + state = const AsyncData(null); + ref.invalidate(foldersProvider); + ref.invalidate(studentFoldersProvider); + if (studentId != null) { + ref.invalidate(studentFolderProvider(studentId)); + } + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future syncFolders(int studentId) async { + state = const AsyncLoading(); + try { + final repo = ref.read(documentRepositoryProvider); + await repo.syncFolders(studentId); + state = const AsyncData(null); + ref.invalidate(studentFolderProvider(studentId)); + ref.invalidate(foldersProvider); + ref.invalidate(studentFoldersProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } +} \ No newline at end of file diff --git a/frontend/lib/ui/providers/reports_provider.dart b/frontend/lib/ui/providers/reports_provider.dart new file mode 100644 index 0000000..f8f8b93 --- /dev/null +++ b/frontend/lib/ui/providers/reports_provider.dart @@ -0,0 +1,42 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../domain/repositories/report_repository.dart'; +import '../../domain/entities/report_models.dart'; + +// Repository provider +final reportRepositoryProvider = Provider((ref) => ReportRepository()); + +// Selected academic year (null = all years) +final selectedAcademicYearIdProvider = NotifierProvider(() => SelectedYearNotifier()); + +class SelectedYearNotifier extends Notifier { + @override + int? build() => null; + void select(int? id) => state = id; +} + +// Academic years list +final academicYearsProvider = FutureProvider>((ref) async { + return await ref.read(reportRepositoryProvider).getAcademicYears(); +}); + +// KPI stats — re-fetches when selected year changes +final reportStatsProvider = FutureProvider.autoDispose((ref) async { + final yearId = ref.watch(selectedAcademicYearIdProvider); + return await ref.read(reportRepositoryProvider).getStats(academicYearId: yearId); +}); + +// Enrollment by grade — re-fetches when selected year changes +final enrollmentByGradeProvider = FutureProvider.autoDispose>((ref) async { + final yearId = ref.watch(selectedAcademicYearIdProvider); + return await ref.read(reportRepositoryProvider).getEnrollmentByGrade(academicYearId: yearId); +}); + +// Document status (global, not filtered by year) +final documentStatusProvider = FutureProvider.autoDispose((ref) async { + return await ref.read(reportRepositoryProvider).getDocumentStatus(); +}); + +// Full export data — triggered manually, not auto-watched +final reportExportDataProvider = FutureProvider.autoDispose.family((ref, yearId) async { + return await ref.read(reportRepositoryProvider).getExportData(academicYearId: yearId); +}); diff --git a/frontend/lib/ui/providers/student_provider.dart b/frontend/lib/ui/providers/student_provider.dart new file mode 100644 index 0000000..1f40596 --- /dev/null +++ b/frontend/lib/ui/providers/student_provider.dart @@ -0,0 +1,233 @@ +import 'dart:async'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../core/network/api_constants.dart'; +import '../../domain/repositories/student_repository.dart'; +import '../../domain/entities/student_model.dart'; + + +// ============================================================ +// Academic Years Model +// ============================================================ +class AcademicYear { + final int id; + final String yearRange; + final String status; + + AcademicYear({required this.id, required this.yearRange, required this.status}); + + factory AcademicYear.fromJson(Map json) { + return AcademicYear( + id: json['id'] as int, + yearRange: json['year_range'] as String, + status: json['status'] as String? ?? 'active', + ); + } +} + +// ============================================================ +// Repository provider +// ============================================================ +final studentRepositoryProvider = Provider((ref) { + return StudentRepository(); +}); + +// ============================================================ +// Academic Years Provider +// ============================================================ +final academicYearsProvider = FutureProvider.autoDispose>((ref) async { + final storage = const FlutterSecureStorage(); + final token = await storage.read(key: 'jwt_token'); + final dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); + + try { + final response = await dio.get( + '/setup/academic-years', + options: Options(headers: {'Authorization': 'Bearer $token'}), + ); + return (response.data as List) + .map((y) => AcademicYear.fromJson(y as Map)) + .toList(); + } catch (e) { + return []; + } +}); + +// ============================================================ +// Student Detail Provider +// ============================================================ +final studentDetailProvider = FutureProvider.family.autoDispose((ref, studentId) async { + final repo = ref.read(studentRepositoryProvider); + return repo.getStudentById(studentId); +}); + +// ============================================================ +// Query params state — drives what the list shows +// ============================================================ +class StudentQueryParams { + final String search; + final int page; + final int limit; + final String gradeLevel; // '' = All + final String status; // '' = All + + const StudentQueryParams({ + this.search = '', + this.page = 1, + this.limit = 10, + this.gradeLevel = '', + this.status = '', + }); + + StudentQueryParams copyWith({ + String? search, + int? page, + int? limit, + String? gradeLevel, + String? status, + }) { + return StudentQueryParams( + search: search ?? this.search, + page: page ?? this.page, + limit: limit ?? this.limit, + gradeLevel: gradeLevel ?? this.gradeLevel, + status: status ?? this.status, + ); + } +} + +// ============================================================ +// Notifier — manages the live query state +// ============================================================ +final studentQueryProvider = + NotifierProvider( + StudentQueryNotifier.new, +); + +class StudentQueryNotifier extends Notifier { + @override + StudentQueryParams build() => const StudentQueryParams(); + + void setSearch(String value) { + // Reset to page 1 whenever search changes + state = state.copyWith(search: value, page: 1); + } + + void setPage(int page) => state = state.copyWith(page: page); + + void setLimit(int limit) => state = state.copyWith(limit: limit, page: 1); + + void setGradeLevel(String grade) => + state = state.copyWith(gradeLevel: grade, page: 1); + + void setStatus(String status) => + state = state.copyWith(status: status, page: 1); + + void reset() => state = const StudentQueryParams(); +} + +// ============================================================ +// Async data provider — re-fetches when query changes +// ============================================================ +final studentPageProvider = FutureProvider.autoDispose((ref) async { + final query = ref.watch(studentQueryProvider); + final repo = ref.read(studentRepositoryProvider); + + return repo.getStudents( + search: query.search, + page: query.page, + limit: query.limit, + gradeLevel: query.gradeLevel, + status: query.status, + ); +}); + +// ============================================================ +// Mutation notifier — handles Create / Update / Delete +// ============================================================ +final studentMutationProvider = + AsyncNotifierProvider( + StudentMutationNotifier.new, +); + +class StudentMutationNotifier extends AsyncNotifier { + @override + FutureOr build() {} + + Future createStudent({ + required String lrn, + required String firstName, + String? middleName, + required String lastName, + String? extension, + required String sex, + required DateTime birthDate, + }) async { + state = const AsyncLoading(); + try { + final repo = ref.read(studentRepositoryProvider); + await repo.createStudent( + lrn: lrn, + firstName: firstName, + middleName: middleName, + lastName: lastName, + extension: extension, + sex: sex, + birthDate: birthDate, + ); + state = const AsyncData(null); + // Invalidate to refresh the list + ref.invalidate(studentPageProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future updateStudent({ + required int id, + required String lrn, + required String firstName, + String? middleName, + required String lastName, + String? extension, + required String sex, + required DateTime birthDate, + String status = 'Enrolled', + }) async { + state = const AsyncLoading(); + try { + final repo = ref.read(studentRepositoryProvider); + await repo.updateStudent( + id: id, + lrn: lrn, + firstName: firstName, + middleName: middleName, + lastName: lastName, + extension: extension, + sex: sex, + birthDate: birthDate, + status: status, + ); + state = const AsyncData(null); + ref.invalidate(studentPageProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } + + Future deleteStudent(int id) async { + state = const AsyncLoading(); + try { + final repo = ref.read(studentRepositoryProvider); + await repo.deleteStudent(id); + state = const AsyncData(null); + ref.invalidate(studentPageProvider); + } catch (e, st) { + state = AsyncError(e, st); + rethrow; + } + } +} diff --git a/frontend/lib/ui/providers/users_provider.dart b/frontend/lib/ui/providers/users_provider.dart new file mode 100644 index 0000000..b8baccb --- /dev/null +++ b/frontend/lib/ui/providers/users_provider.dart @@ -0,0 +1,82 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../domain/repositories/user_repository.dart'; +import '../../domain/entities/system_user.dart'; + +final userRepositoryProvider = Provider((ref) => UserRepository()); + +final usersProvider = AsyncNotifierProvider>(() { + return UsersNotifier(); +}); + +class UsersNotifier extends AsyncNotifier> { + @override + Future> build() async { + return await ref.read(userRepositoryProvider).getUsers(); + } + + Future refresh() async { + state = const AsyncLoading(); + state = await AsyncValue.guard(() => ref.read(userRepositoryProvider).getUsers()); + } + + /// Returns the generated temporary password to display once. + Future createUser({ + required String username, + String? password, + required String firstName, + String? middleName, + required String lastName, + String? extension, + required String role, + String? email, + String? phone, + }) async { + try { + final tempPassword = await ref.read(userRepositoryProvider).createUser( + username: username, password: password, firstName: firstName, + middleName: middleName, lastName: lastName, extension: extension, + role: role, email: email, phone: phone, + ); + await refresh(); + return tempPassword; + } catch (e) { + rethrow; + } + } + + Future updateUser({ + required int id, required String firstName, String? middleName, + required String lastName, String? extension, required String role, + String? email, String? phone, + }) async { + try { + await ref.read(userRepositoryProvider).updateUser( + id: id, firstName: firstName, middleName: middleName, lastName: lastName, + extension: extension, role: role, email: email, phone: phone, + ); + await refresh(); + return true; + } catch (e) { + rethrow; + } + } + + Future resetPassword(int id) async { + try { + await ref.read(userRepositoryProvider).resetPassword(id); + return true; + } catch (e) { + rethrow; + } + } + + Future deleteUser(int id) async { + try { + await ref.read(userRepositoryProvider).deleteUser(id); + await refresh(); + return true; + } catch (e) { + rethrow; + } + } +} diff --git a/frontend/lib/ui/screens/archives/archives_screen.dart b/frontend/lib/ui/screens/archives/archives_screen.dart new file mode 100644 index 0000000..71ec07c --- /dev/null +++ b/frontend/lib/ui/screens/archives/archives_screen.dart @@ -0,0 +1,381 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../shared/inputs/custom_text_field.dart'; +import '../../providers/archives_provider.dart'; +import '../../../domain/entities/archive_model.dart'; + +class ArchivesScreen extends ConsumerStatefulWidget { + final String userRole; + + const ArchivesScreen({super.key, required this.userRole}); + + @override + ConsumerState createState() => _ArchivesScreenState(); +} + +class _ArchivesScreenState extends ConsumerState { + final TextEditingController _searchController = TextEditingController(); + Timer? _debounce; + + @override + void dispose() { + _searchController.dispose(); + _debounce?.cancel(); + super.dispose(); + } + + void _onSearchChanged(String query) { + if (_debounce?.isActive ?? false) _debounce!.cancel(); + _debounce = Timer(const Duration(milliseconds: 500), () { + ref.read(archiveQueryProvider.notifier).setSearch(query); + }); + } + + void _handleRestore(ArchiveModel archive) async { + try { + await ref.read(archiveMutationProvider.notifier).restoreArchive(archive.id); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('${archive.name} restored to active records.'), backgroundColor: AppColors.success), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to restore: $e'), backgroundColor: AppColors.error), + ); + } + } + + void _handlePermanentDelete(ArchiveModel archive) { + // RBAC Check just in case + if (widget.userRole != 'super_admin' && widget.userRole != 'admin') return; + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Confirm Permanent Purge', style: TextStyle(color: AppColors.error)), + content: Text('Are you sure you want to permanently delete ${archive.name}? This action cannot be undone and will purge all connected documents.'), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('CANCEL')), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: AppColors.error, foregroundColor: Colors.white), + onPressed: () async { + Navigator.pop(context); + try { + await ref.read(archiveMutationProvider.notifier).purgeArchive(archive.id); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('${archive.name} permanently deleted.'), backgroundColor: AppColors.error), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to purge: $e'), backgroundColor: AppColors.error), + ); + } + }, + child: const Text('PURGE RECORD'), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final archiveState = ref.watch(archivePageProvider); + final query = ref.watch(archiveQueryProvider); + + return Scaffold( + backgroundColor: Colors.transparent, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeaderControls(context, query), + const SizedBox(height: AppSizes.p24), + + // ========================================== + // RETENTION RULES BANNER + // ========================================== + Container( + width: double.infinity, + padding: const EdgeInsets.all(AppSizes.p16), + decoration: BoxDecoration( + color: Colors.blue.withOpacity(0.05), + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + border: Border.all(color: Colors.blue.withOpacity(0.2)), + ), + child: const Row( + children: [ + Icon(Icons.info_outline, color: Colors.blue), + SizedBox(width: AppSizes.p12), + Expanded( + child: Text( + 'Retention Engine Rules: Graduated (5 Yrs) • Transferred Out (5 Yrs) • Dropped (3 Yrs). Records marked in red have exceeded their retention period and are ready for permanent purging.', + style: TextStyle(color: Color(0xFF0D47A1), fontSize: 13), // Material Blue 900 + ), + ), + ], + ), + ), + const SizedBox(height: AppSizes.p24), + + // ========================================== + // RESPONSIVE DATA VIEW + // ========================================== + Expanded( + child: archiveState.when( + data: (pageData) { + if (pageData.archives.isEmpty) { + return const Center(child: Text('No archived records found.')); + } + return LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth > 800) { + return _buildDesktopTable(pageData.archives); + } else { + return _buildMobileCardList(pageData.archives); + } + }, + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (err, stack) => Center(child: Text('Error: $err', style: const TextStyle(color: AppColors.error))), + ), + ), + + if (archiveState.hasValue && archiveState.value!.totalPages > 1) + _buildPaginationControls(archiveState.value!.totalPages, query.page), + ], + ), + ), + ), + ); + } + + // ========================================== + // HEADER CONTROLS + // ========================================== + Widget _buildHeaderControls(BuildContext context, ArchiveQueryParams query) { + return LayoutBuilder( + builder: (context, constraints) { + bool isDesktop = constraints.maxWidth > 800; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'System Archives', + style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: AppColors.textPrimary), + ), + const SizedBox(height: AppSizes.p16), + Row( + children: [ + Expanded( + flex: 2, + child: CustomTextField( + hintText: 'Search archived records...', + prefixIcon: Icons.search, + controller: _searchController, + onChanged: _onSearchChanged, + ), + ), + const SizedBox(width: AppSizes.p16), + if (isDesktop) ...[ + Expanded( + flex: 1, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: AppSizes.p16), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.grey.shade300), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: query.status, + isExpanded: true, + items: ['All Statuses', 'Graduated', 'Transferred Out', 'Dropped'] + .map((String value) => DropdownMenuItem(value: value, child: Text(value))) + .toList(), + onChanged: (val) { + if (val != null) { + ref.read(archiveQueryProvider.notifier).setStatus(val); + } + }, + ), + ), + ), + ), + ], + ], + ), + ], + ); + }, + ); + } + + // ========================================== + // DESKTOP TABLE + // ========================================== + Widget _buildDesktopTable(List archives) { + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 10, offset: const Offset(0, 4))], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + headingRowColor: WidgetStateProperty.all(AppColors.primaryGreen.withOpacity(0.05)), + columns: const [ + DataColumn(label: Text('LRN', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Name', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Final Status', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Date Archived', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Retention Expiry', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Actions', style: TextStyle(fontWeight: FontWeight.bold))), + ], + rows: archives.map((archive) { + return DataRow(cells: [ + DataCell(Text(archive.lrn, style: const TextStyle(fontWeight: FontWeight.w500))), + DataCell(Text(archive.name)), + DataCell(_buildStatusChip(archive.status)), + DataCell(Text(archive.archivedDate, style: const TextStyle(color: AppColors.textSecondary))), + DataCell(Text( + archive.expiryDate, + style: TextStyle(color: archive.isExpired ? AppColors.error : AppColors.primaryGreen, fontWeight: archive.isExpired ? FontWeight.bold : FontWeight.normal), + )), + DataCell(_buildActionButtons(archive)), + ]); + }).toList(), + ), + ), + ), + ); + } + + // ========================================== + // MOBILE CARD LIST + // ========================================== + Widget _buildMobileCardList(List archives) { + return ListView.separated( + itemCount: archives.length, + separatorBuilder: (context, index) => const SizedBox(height: AppSizes.p12), + itemBuilder: (context, index) { + final archive = archives[index]; + + return Container( + padding: const EdgeInsets.all(AppSizes.p16), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + border: archive.isExpired ? Border.all(color: AppColors.error.withOpacity(0.3)) : null, + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 8, offset: const Offset(0, 2))], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(archive.lrn, style: const TextStyle(fontWeight: FontWeight.bold, color: AppColors.primaryGreen)), + _buildStatusChip(archive.status), + ], + ), + const SizedBox(height: AppSizes.p8), + Text(archive.name, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + const Padding( + padding: EdgeInsets.symmetric(vertical: AppSizes.p12), + child: Divider(height: 1), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Archived: ${archive.archivedDate}', style: const TextStyle(color: AppColors.textSecondary, fontSize: 12)), + Text( + 'Expires: ${archive.expiryDate}', + style: TextStyle(color: archive.isExpired ? AppColors.error : AppColors.primaryGreen, fontSize: 12, fontWeight: archive.isExpired ? FontWeight.bold : FontWeight.normal), + ), + ], + ), + _buildActionButtons(archive), + ], + ), + ], + ), + ); + }, + ); + } + + // ========================================== + // PAGINATION CONTROLS + // ========================================== + Widget _buildPaginationControls(int totalPages, int currentPage) { + return Padding( + padding: const EdgeInsets.only(top: AppSizes.p16), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: currentPage > 1 + ? () => ref.read(archiveQueryProvider.notifier).setPage(currentPage - 1) + : null, + ), + Text('Page $currentPage of $totalPages', style: const TextStyle(fontWeight: FontWeight.bold)), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: currentPage < totalPages + ? () => ref.read(archiveQueryProvider.notifier).setPage(currentPage + 1) + : null, + ), + ], + ), + ); + } + + // ========================================== + // HELPER COMPONENTS + // ========================================== + Widget _buildStatusChip(String status) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(20)), + child: Text(status, style: TextStyle(color: Colors.grey.shade800, fontWeight: FontWeight.w600, fontSize: 12)), + ); + } + + Widget _buildActionButtons(ArchiveModel archive) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.restore, color: AppColors.primaryGreen), + tooltip: 'Restore to Active', + onPressed: () => _handleRestore(archive), + ), + if (widget.userRole == 'super_admin' || widget.userRole == 'admin') // RBAC Protection + IconButton( + icon: Icon(Icons.delete_forever, color: archive.isExpired ? AppColors.error : Colors.grey.shade400), + tooltip: 'Permanently Purge', + onPressed: () => _handlePermanentDelete(archive), + ), + ], + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/dashboard/dashboard_screen.dart b/frontend/lib/ui/screens/dashboard/dashboard_screen.dart new file mode 100644 index 0000000..159f384 --- /dev/null +++ b/frontend/lib/ui/screens/dashboard/dashboard_screen.dart @@ -0,0 +1,251 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../shared/cards/stat_card.dart'; +import '../../providers/dashboard_provider.dart'; +import '../../providers/auth_provider.dart'; +import '../../../domain/entities/dashboard_models.dart'; +import '../../../domain/entities/user_model.dart'; + +class DashboardScreen extends ConsumerStatefulWidget { + const DashboardScreen({super.key}); + + @override + ConsumerState createState() => _DashboardScreenState(); +} + +class _DashboardScreenState extends ConsumerState { + Future _handleRefresh() async { + ref.invalidate(dashboardDataProvider); + // Wait for the new data to finish loading + await ref.read(dashboardDataProvider.future); + } + + @override + Widget build(BuildContext context) { + final dashboardAsync = ref.watch(dashboardDataProvider); + final user = ref.watch(authProvider).value; + + return Scaffold( + backgroundColor: Colors.transparent, + body: SafeArea( + child: dashboardAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, stackTrace) => Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.error_outline, color: Colors.red, size: 48), + const SizedBox(height: 12), + Text('$error', style: const TextStyle(color: Colors.red)), + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: _handleRefresh, + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + ), + ], + ), + ), + data: (data) => RefreshIndicator( + onRefresh: _handleRefresh, + child: SingleChildScrollView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildTopBar(user), + const SizedBox(height: 32), + const Text( + 'Dashboard Overview', + style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Text( + 'Welcome back, ${user?.firstName ?? 'Admin'}. Here is what is happening today.', + style: TextStyle(fontSize: 16, color: Colors.grey.shade600), + ), + const SizedBox(height: 24), + _buildStatGrid(data.stats), + const SizedBox(height: 32), + const Text( + 'Pending Tasks', + style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 16), + _buildPendingTasksList(data.pendingTasks), + const SizedBox(height: 48), + ], + ), + ), + ), + ), + ), + ); + } + + // ========================================== + // TOP BAR MODULE + // ========================================== + Widget _buildTopBar(UserModel? user) { + final String initials = user != null && user.firstName.isNotEmpty && user.lastName.isNotEmpty + ? '${user.firstName[0]}${user.lastName[0]}'.toUpperCase() + : 'SA'; + + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + // Dummy Search Bar (Expands on Desktop, fixed width on Mobile) + Expanded( + flex: 1, + child: Container( + constraints: const BoxConstraints(maxWidth: 400), + child: TextField( + decoration: InputDecoration( + hintText: 'Search students by LRN or Name...', + prefixIcon: const Icon(Icons.search), + filled: true, + fillColor: Colors.white, + contentPadding: const EdgeInsets.symmetric(vertical: 0), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8.0), + borderSide: BorderSide.none, + ), + ), + ), + ), + ), + const SizedBox(width: 16), + // Icons + Row( + children: [ + // Notification with Red Badge + Stack( + children: [ + IconButton( + icon: const Icon(Icons.notifications_outlined, size: 28), + onPressed: () { + // TODO: Open Notification Modal + }, + ), + Positioned( + right: 8, + top: 8, + child: Container( + padding: const EdgeInsets.all(4), + decoration: const BoxDecoration( + color: Colors.redAccent, + shape: BoxShape.circle, + ), + child: const Text( + '3', + style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold), + ), + ), + ), + ], + ), + const SizedBox(width: 16), + // User Profile Mockup + CircleAvatar( + backgroundColor: const Color(0xFF1C8248), + child: Text(initials, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), + ), + ], + ), + ], + ); + } + + // ========================================== + // RESPONSIVE STAT GRID + // ========================================== + Widget _buildStatGrid(DashboardStats stats) { + return LayoutBuilder( + builder: (context, constraints) { + // Breakpoint logic: >= 800px is Windows (4 columns), < 800px is Android (2 columns) + int crossAxisCount = constraints.maxWidth >= 800 ? 4 : 2; + + return GridView( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: crossAxisCount, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + // THE FIX: This forces the card to always be exactly 110 pixels tall, + // completely ignoring the width and preventing vertical squishing! + mainAxisExtent: 110, + ), + children: [ + StatCard(title: 'Total Students', value: stats.totalStudents.toString(), icon: Icons.school), + StatCard(title: 'Pending Docs', value: stats.pendingVerifications.toString(), icon: Icons.folder_shared, iconColor: Colors.orange), + StatCard(title: 'Print Queue', value: stats.printQueueCount.toString(), icon: Icons.print, iconColor: Colors.blue), + StatCard(title: 'Active Users', value: stats.activeUsers.toString(), icon: Icons.badge), // Super Admin specific stat + ], + ); + }, + ); + } + + // ========================================== + // PENDING TASKS LIST + // ========================================== + Widget _buildPendingTasksList(List tasks) { + if (tasks.isEmpty) { + return Container( + padding: const EdgeInsets.all(24.0), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12.0), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: const Center( + child: Text('No pending tasks at the moment.', style: TextStyle(color: Colors.grey)), + ), + ); + } + + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12.0), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: tasks.length, + separatorBuilder: (context, index) => Divider(height: 1, color: Colors.grey.shade200), + itemBuilder: (context, index) { + final task = tasks[index]; + return ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + leading: CircleAvatar( + backgroundColor: Colors.orange.withOpacity(0.1), + child: const Icon(Icons.folder_shared, color: Colors.orange), + ), + title: Text('Verify ${task.fileName} for ${task.firstName} ${task.lastName}', style: const TextStyle(fontWeight: FontWeight.w500)), + subtitle: Text('Submitted on ${task.createdAt.split('T').first}'), + trailing: const Icon(Icons.chevron_right, color: Colors.grey), + onTap: () { + // TODO: Navigate to specific task + }, + ); + }, + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/documents/documents_screen.dart b/frontend/lib/ui/screens/documents/documents_screen.dart new file mode 100644 index 0000000..29c3bf6 --- /dev/null +++ b/frontend/lib/ui/screens/documents/documents_screen.dart @@ -0,0 +1,952 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../shared/inputs/custom_text_field.dart'; +import '../../shared/buttons/primary_button.dart'; +import '../../providers/document_provider.dart'; +import '../../providers/student_provider.dart'; +import '../students/student_detail_screen.dart'; +import 'widgets/file_folder_card.dart'; +import 'widgets/upload_ocr_modal.dart'; +import 'widgets/print_queue_modal.dart'; + +class DocumentsScreen extends ConsumerStatefulWidget { + final String userRole; + /// When set, the screen auto-filters to this student's documents + final int? initialStudentId; + + const DocumentsScreen({ + super.key, + this.userRole = 'teacher', + this.initialStudentId, + }); + + @override + ConsumerState createState() => _DocumentsScreenState(); +} + +class _DocumentsScreenState extends ConsumerState + with SingleTickerProviderStateMixin { + final TextEditingController _searchController = TextEditingController(); + Timer? _debounce; + bool _isGridView = false; + bool _showFilters = false; + late final TabController _tabController; + + // Filter values — kept in sync with provider + String _selectedStatus = 'All Statuses'; + String _selectedDocumentType = 'All Types'; + String _selectedGradeLevel = 'All Grades'; + String _selectedSchoolYear = 'All Years'; + + @override + void initState() { + super.initState(); + // 2 tabs: 0=Folders, 1=Documents + _tabController = TabController(length: 2, vsync: this); + // If a specific student was passed, jump directly to Documents tab + if (widget.initialStudentId != null) { + _tabController.index = 1; + WidgetsBinding.instance.addPostFrameCallback((_) { + ref + .read(documentQueryProvider.notifier) + .setStudentId(widget.initialStudentId); + }); + } + } + + @override + void dispose() { + _tabController.dispose(); + _searchController.dispose(); + _debounce?.cancel(); + super.dispose(); + } + + void _onSearchChanged(String query) { + if (_debounce?.isActive ?? false) _debounce!.cancel(); + _debounce = Timer(const Duration(milliseconds: 500), () { + ref.read(documentQueryProvider.notifier).setSearch(query); + }); + } + + void _applyFilters() { + final n = ref.read(documentQueryProvider.notifier); + n.setStatus(_selectedStatus); + n.setDocumentType(_selectedDocumentType); + n.setGradeLevel( + _selectedGradeLevel == 'All Grades' ? '' : _selectedGradeLevel); + n.setSchoolYear( + _selectedSchoolYear == 'All Years' ? '' : _selectedSchoolYear); + } + + void _clearFilters() { + setState(() { + _selectedStatus = 'All Statuses'; + _selectedDocumentType = 'All Types'; + _selectedGradeLevel = 'All Grades'; + _selectedSchoolYear = 'All Years'; + _searchController.clear(); + }); + ref.read(documentQueryProvider.notifier).reset(); + } + + void _handleAction(String action, int documentId, int? studentId) async { + if (action == 'view_profile' && studentId != null) { + Navigator.of(context).push(MaterialPageRoute( + builder: (_) => + StudentDetailScreen(studentId: studentId, userRole: widget.userRole), + )); + } else if (action == 'delete') { + _confirmDelete(documentId); + } else if (action == 'queue') { + try { + await ref + .read(printQueueMutationProvider.notifier) + .addToQueue(documentId); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Added to Print Queue.'), + backgroundColor: AppColors.primaryGreen, + )); + } catch (e) { + if (!mounted) return; + final msg = e.toString().replaceFirst('Exception: ', ''); + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(msg), + backgroundColor: AppColors.warning, + )); + } + } else if (action == 'preview') { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Preview feature coming soon.'), + backgroundColor: Colors.blue, + )); + } else if (action == 'download') { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Download started.'), + backgroundColor: Colors.blue, + )); + } + } + + void _confirmDelete(int id) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + title: const Row(children: [ + Icon(Icons.warning_amber_rounded, color: AppColors.error), + SizedBox(width: 8), + Text('Delete Document', style: TextStyle(color: AppColors.error)), + ]), + content: + const Text('Are you sure you want to permanently delete this document?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), + child: const Text('CANCEL')), + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.error, + foregroundColor: Colors.white), + onPressed: () async { + Navigator.pop(ctx); + try { + await ref + .read(documentMutationProvider.notifier) + .deleteDocument(id); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Document deleted.'), + backgroundColor: AppColors.error, + )); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('Failed to delete: $e'), + backgroundColor: AppColors.error, + )); + } + }, + child: const Text('DELETE'), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final docState = ref.watch(documentPageProvider); + final query = ref.watch(documentQueryProvider); + final requirementsAsync = ref.watch(documentRequirementsProvider); + final academicYearsAsync = ref.watch(academicYearsProvider); + final foldersAsync = ref.watch(foldersProvider); + final screenW = MediaQuery.of(context).size.width; + final isMobile = screenW < 700; + final isStudentFiltered = query.studentId != null; + + return Scaffold( + backgroundColor: Colors.transparent, + floatingActionButton: isMobile + ? FloatingActionButton( + backgroundColor: AppColors.primaryGreen, + onPressed: () => showDialog( + context: context, + builder: (_) => const UploadOcrModal()), + child: const Icon(Icons.cloud_upload, color: Colors.white), + ) + : null, + body: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ── Top Header ── + _buildTopHeader(isMobile, isStudentFiltered, query), + + // ── TabBar ── + Container( + color: AppColors.surfaceWhite, + child: TabBar( + controller: _tabController, + labelColor: AppColors.primaryGreen, + unselectedLabelColor: AppColors.textSecondary, + indicatorColor: AppColors.primaryGreen, + indicatorWeight: 2.5, + labelStyle: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13), + tabs: const [ + Tab(icon: Icon(Icons.folder, size: 18), text: 'Student Folders'), + Tab(icon: Icon(Icons.description, size: 18), text: 'All Documents'), + ], + ), + ), + + // ── Filter Panel (Documents tab only) ── + if (_showFilters && _tabController.index == 1) + _buildFilterPanel(requirementsAsync, academicYearsAsync, isMobile), + + const Divider(height: 1), + + // ── Tab Body ── + Expanded( + child: TabBarView( + controller: _tabController, + children: [ + // Tab 0: Student Folders + _buildFoldersTab(foldersAsync, isMobile), + + // Tab 1: All Documents + Column( + children: [ + Expanded( + child: docState.when( + loading: () => const Center( + child: CircularProgressIndicator( + color: AppColors.primaryGreen)), + error: (e, _) => _buildErrorState(e.toString()), + data: (pageData) => pageData.documents.isEmpty + ? _buildEmptyState() + : _isGridView + ? _buildGridView(pageData.documents) + : _buildListView(pageData.documents), + ), + ), + // Pagination + docState.maybeWhen( + data: (p) => p.totalPages > 1 + ? _buildPagination(p.totalPages, query.page) + : const SizedBox.shrink(), + orElse: () => const SizedBox.shrink(), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ); + } + + // ══════════════════════════════════════════════════════════════ + // TOP HEADER + // ══════════════════════════════════════════════════════════════ + Widget _buildTopHeader( + bool isMobile, bool isStudentFiltered, DocumentQueryParams query) { + return Container( + color: AppColors.surfaceWhite, + padding: EdgeInsets.symmetric( + horizontal: isMobile ? 12 : 20, vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Title row + Row( + children: [ + const Icon(Icons.folder_open, + color: AppColors.primaryGreen, size: 26), + const SizedBox(width: 10), + Expanded( + child: Text( + isStudentFiltered + ? 'Student Documents' + : 'Document Manager', + style: TextStyle( + fontSize: isMobile ? 18 : 22, + fontWeight: FontWeight.bold, + color: AppColors.textPrimary, + ), + ), + ), + // Clear student filter badge + if (isStudentFiltered) + TextButton.icon( + onPressed: () { + ref + .read(documentQueryProvider.notifier) + .setStudentId(null); + }, + icon: const Icon(Icons.close, size: 16), + label: const Text('All Students', + style: TextStyle(fontSize: 12)), + style: TextButton.styleFrom( + foregroundColor: AppColors.primaryGreen), + ), + if (!isMobile) ...[ + const SizedBox(width: 8), + _buildPrintQueueButton(), + const SizedBox(width: 8), + SizedBox( + width: 130, + child: PrimaryButton( + label: 'UPLOAD', + onPressed: () => showDialog( + context: context, + builder: (_) => const UploadOcrModal()), + ), + ), + ], + ], + ), + + const SizedBox(height: 10), + + // Search + Controls row + Row( + children: [ + Expanded( + child: CustomTextField( + hintText: 'Search by name, LRN, file…', + prefixIcon: Icons.search, + controller: _searchController, + onChanged: _onSearchChanged, + ), + ), + const SizedBox(width: 8), + + // Filter toggle + _buildIconToggle( + icon: Icons.tune, + isActive: _showFilters, + tooltip: 'Toggle Filters', + onTap: () => setState(() => _showFilters = !_showFilters), + ), + const SizedBox(width: 6), + + // Grid/List toggle + _buildIconToggle( + icon: _isGridView ? Icons.view_list : Icons.grid_view, + isActive: false, + tooltip: _isGridView ? 'Switch to List' : 'Switch to Grid', + onTap: () => setState(() => _isGridView = !_isGridView), + ), + + if (isMobile) ...[ + const SizedBox(width: 6), + _buildPrintQueueButton(compact: true), + ], + ], + ), + + // Active filter chips + if (_hasActiveFilters()) + Padding( + padding: const EdgeInsets.only(top: 8), + child: _buildActiveFilterChips(), + ), + ], + ), + ); + } + + bool _hasActiveFilters() => + _selectedStatus != 'All Statuses' || + _selectedDocumentType != 'All Types' || + _selectedGradeLevel != 'All Grades' || + _selectedSchoolYear != 'All Years' || + _searchController.text.isNotEmpty; + + Widget _buildActiveFilterChips() { + final chips = []; + if (_selectedStatus != 'All Statuses') + chips.add(_filterChip('Status: $_selectedStatus')); + if (_selectedDocumentType != 'All Types') + chips.add(_filterChip('Type: $_selectedDocumentType')); + if (_selectedGradeLevel != 'All Grades') + chips.add(_filterChip('Grade: $_selectedGradeLevel')); + if (_selectedSchoolYear != 'All Years') + chips.add(_filterChip('Year: $_selectedSchoolYear')); + chips.add(TextButton( + onPressed: _clearFilters, + style: TextButton.styleFrom( + foregroundColor: AppColors.error, + padding: const EdgeInsets.symmetric(horizontal: 8)), + child: const Text('Clear All', style: TextStyle(fontSize: 12)), + )); + + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(children: chips), + ); + } + + Widget _filterChip(String label) => Container( + margin: const EdgeInsets.only(right: 6), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: AppColors.primaryGreen.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: AppColors.primaryGreen.withValues(alpha: 0.3)), + ), + child: Text(label, + style: const TextStyle( + fontSize: 11, + color: AppColors.primaryGreen, + fontWeight: FontWeight.w500)), + ); + + Widget _buildIconToggle({ + required IconData icon, + required bool isActive, + required String tooltip, + required VoidCallback onTap, + }) { + return Tooltip( + message: tooltip, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: isActive + ? AppColors.primaryGreen.withValues(alpha: 0.1) + : AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: isActive + ? AppColors.primaryGreen + : Colors.grey.shade300, + ), + ), + child: Icon(icon, + size: 20, + color: isActive ? AppColors.primaryGreen : AppColors.textSecondary), + ), + ), + ); + } + + Widget _buildPrintQueueButton({bool compact = false}) { + return Tooltip( + message: 'Print Queue', + child: OutlinedButton.icon( + onPressed: () => showDialog( + context: context, builder: (_) => const PrintQueueModal()), + icon: const Icon(Icons.print, size: 18), + label: compact + ? const SizedBox.shrink() + : const Text('Print Queue'), + style: OutlinedButton.styleFrom( + foregroundColor: AppColors.textPrimary, + side: BorderSide(color: Colors.grey.shade300), + padding: compact + ? const EdgeInsets.all(10) + : const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8)), + ), + ), + ); + } + + // ══════════════════════════════════════════════════════════════ + // FILTER PANEL + // ══════════════════════════════════════════════════════════════ + Widget _buildFilterPanel( + AsyncValue> requirementsAsync, + AsyncValue> academicYearsAsync, + bool isMobile, + ) { + final docTypes = requirementsAsync.when( + data: (reqs) => + ['All Types', ...reqs.map((r) => r.name as String).toSet().toList()..sort()], + loading: () => ['All Types'], + error: (_, __) => ['All Types'], + ); + final years = academicYearsAsync.when( + data: (y) => ['All Years', ...y.map((ay) => ay.yearRange as String)], + loading: () => ['All Years'], + error: (_, __) => ['All Years'], + ); + + return Container( + color: Colors.grey.shade50, + padding: EdgeInsets.symmetric( + horizontal: isMobile ? 12 : 20, vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Filters', + style: + TextStyle(fontWeight: FontWeight.w600, fontSize: 13, color: AppColors.textSecondary)), + const SizedBox(height: 10), + Wrap( + spacing: 10, + runSpacing: 10, + children: [ + _buildDropdown( + label: 'Status', + value: _selectedStatus, + items: const [ + 'All Statuses','Pending','Verified','Draft','Archived','Rejected' + ], + onChanged: (v) { + setState(() => _selectedStatus = v!); + _applyFilters(); + }, + ), + _buildDropdown( + label: 'Document Type', + value: _selectedDocumentType, + items: docTypes, + onChanged: (v) { + setState(() => _selectedDocumentType = v!); + _applyFilters(); + }, + ), + _buildDropdown( + label: 'Grade Level', + value: _selectedGradeLevel, + items: const [ + 'All Grades','7','8','9','10','11','12' + ], + onChanged: (v) { + setState(() => _selectedGradeLevel = v!); + _applyFilters(); + }, + ), + _buildDropdown( + label: 'School Year', + value: _selectedSchoolYear, + items: years, + onChanged: (v) { + setState(() => _selectedSchoolYear = v!); + _applyFilters(); + }, + ), + ], + ), + const SizedBox(height: 8), + Row(mainAxisAlignment: MainAxisAlignment.end, children: [ + TextButton( + onPressed: _clearFilters, + child: const Text('Clear All', + style: TextStyle(color: AppColors.error))), + const SizedBox(width: 8), + SizedBox( + width: 120, + child: PrimaryButton(label: 'Apply', onPressed: _applyFilters), + ), + ]), + ], + ), + ); + } + + Widget _buildDropdown({ + required String label, + required String value, + required List items, + required ValueChanged onChanged, + }) { + // Guard: if value is not in items, use first item + final safeValue = items.contains(value) ? value : items.first; + return Container( + constraints: const BoxConstraints(minWidth: 150), + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey.shade300), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: safeValue, + hint: Text(label, style: const TextStyle(fontSize: 13)), + isExpanded: false, + isDense: true, + items: items + .map((i) => DropdownMenuItem( + value: i, + child: Text(i, style: const TextStyle(fontSize: 13)))) + .toList(), + onChanged: onChanged, + ), + ), + ); + } + + // ══════════════════════════════════════════════════════════════ + // FOLDERS TAB + // ══════════════════════════════════════════════════════════════ + Widget _buildFoldersTab(AsyncValue> foldersAsync, bool isMobile) { + return foldersAsync.when( + loading: () => const Center( + child: CircularProgressIndicator(color: AppColors.primaryGreen)), + error: (e, _) => _buildErrorState(e.toString()), + data: (folders) { + if (folders.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.folder_off_outlined, + size: 64, color: Colors.grey.shade300), + const SizedBox(height: 16), + const Text('No Student Folders', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: AppColors.textSecondary)), + const SizedBox(height: 8), + const Text('Student folders are created automatically.', + style: TextStyle(color: AppColors.textMuted)), + ], + ), + ); + } + + return LayoutBuilder(builder: (ctx, c) { + int cols = (c.maxWidth / 200).floor().clamp(2, 6); + return GridView.builder( + padding: const EdgeInsets.all(16), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: cols, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + childAspectRatio: 1.1, + ), + itemCount: folders.length, + itemBuilder: (ctx, i) { + final folder = folders[i]; + return InkWell( + onTap: () { + if (folder.studentId != null) { + _tabController.index = 1; + ref + .read(documentQueryProvider.notifier) + .setStudentId(folder.studentId); + } + }, + borderRadius: BorderRadius.circular(12), + child: Container( + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.grey.shade200), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.04), + blurRadius: 8, + offset: const Offset(0, 2), + ) + ], + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.folder, + size: 48, color: Colors.orange), + const SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Text( + folder.name, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + color: AppColors.textPrimary), + ), + ), + const SizedBox(height: 4), + Text( + '${folder.documentCount ?? 0} Documents', + style: const TextStyle( + fontSize: 11, color: AppColors.textSecondary), + ), + ], + ), + ), + ); + }, + ); + }); + }, + ); + } + + + // ══════════════════════════════════════════════════════════════ + // GRID VIEW + // ══════════════════════════════════════════════════════════════ + Widget _buildGridView(List documents) { + return LayoutBuilder(builder: (ctx, c) { + int cols = (c.maxWidth / 180).floor().clamp(2, 6); + return GridView.builder( + padding: const EdgeInsets.all(16), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: cols, + crossAxisSpacing: 12, + mainAxisSpacing: 12, + childAspectRatio: 1.0, + ), + itemCount: documents.length, + itemBuilder: (ctx, i) => FileFolderCard( + document: documents[i], + isGrid: true, + userRole: widget.userRole, + onTap: () {}, + onActionSelected: (a) => + _handleAction(a, documents[i].id, documents[i].studentId), + onViewProfile: (sid) => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => + StudentDetailScreen(studentId: sid, userRole: widget.userRole), + )), + ), + ); + }); + } + + // ══════════════════════════════════════════════════════════════ + // LIST VIEW + // ══════════════════════════════════════════════════════════════ + Widget _buildListView(List documents) { + return Container( + margin: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.04), + blurRadius: 10, + offset: const Offset(0, 2)), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Column( + children: [ + // Table header + Container( + padding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + color: AppColors.primaryGreen.withValues(alpha: 0.06), + child: const Row( + children: [ + SizedBox(width: 44), + Expanded( + flex: 3, + child: Text('File Name', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 12, + color: AppColors.textSecondary))), + Expanded( + flex: 2, + child: Text('Student', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 12, + color: AppColors.textSecondary))), + Expanded( + flex: 2, + child: Text('Doc Type', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 12, + color: AppColors.textSecondary))), + Expanded( + child: Text('Status', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 12, + color: AppColors.textSecondary))), + SizedBox(width: 40), + ], + ), + ), + Expanded( + child: ListView.separated( + itemCount: documents.length, + separatorBuilder: (_, __) => + Divider(height: 1, color: Colors.grey.shade100), + itemBuilder: (ctx, i) => FileFolderCard( + document: documents[i], + isGrid: false, + userRole: widget.userRole, + onTap: () {}, + onActionSelected: (a) => + _handleAction(a, documents[i].id, documents[i].studentId), + onViewProfile: (sid) => + Navigator.of(context).push(MaterialPageRoute( + builder: (_) => StudentDetailScreen( + studentId: sid, userRole: widget.userRole), + )), + ), + ), + ), + ], + ), + ), + ); + } + + // ══════════════════════════════════════════════════════════════ + // EMPTY / ERROR STATES + // ══════════════════════════════════════════════════════════════ + Widget _buildEmptyState() { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.folder_off_outlined, size: 72, color: Colors.grey.shade300), + const SizedBox(height: 16), + const Text('No documents found', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary)), + const SizedBox(height: 8), + const Text('Upload a document or adjust your filters', + style: TextStyle(color: AppColors.textSecondary)), + if (_hasActiveFilters()) ...[ + const SizedBox(height: 16), + TextButton.icon( + onPressed: _clearFilters, + icon: const Icon(Icons.clear_all), + label: const Text('Clear Filters')), + ], + ], + ), + ); + } + + Widget _buildErrorState(String message) { + final clean = message.startsWith('Exception: ') + ? message.substring(11) + : message; + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.wifi_off_rounded, size: 56, color: AppColors.error), + const SizedBox(height: 16), + Text(clean, + textAlign: TextAlign.center, + style: const TextStyle(color: AppColors.error)), + const SizedBox(height: 16), + ElevatedButton.icon( + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + onPressed: () => ref.invalidate(documentPageProvider), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primaryGreen, + foregroundColor: Colors.white), + ), + ], + ), + ); + } + + // ══════════════════════════════════════════════════════════════ + // PAGINATION + // ══════════════════════════════════════════════════════════════ + Widget _buildPagination(int totalPages, int currentPage) { + return Container( + color: AppColors.surfaceWhite, + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: currentPage > 1 + ? () => ref + .read(documentQueryProvider.notifier) + .setPage(currentPage - 1) + : null, + ), + ...List.generate(totalPages, (i) => i + 1) + .where((p) => (p - currentPage).abs() <= 2) + .map((p) { + final isActive = p == currentPage; + return GestureDetector( + onTap: () => + ref.read(documentQueryProvider.notifier).setPage(p), + child: Container( + width: 32, + height: 32, + margin: const EdgeInsets.symmetric(horizontal: 2), + decoration: BoxDecoration( + color: isActive ? AppColors.primaryGreen : Colors.transparent, + borderRadius: BorderRadius.circular(6), + border: isActive + ? null + : Border.all(color: Colors.grey.shade300), + ), + child: Center( + child: Text('$p', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: isActive + ? Colors.white + : AppColors.textSecondary)), + ), + ), + ); + }), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: currentPage < totalPages + ? () => ref + .read(documentQueryProvider.notifier) + .setPage(currentPage + 1) + : null, + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/documents/widgets/file_folder_card.dart b/frontend/lib/ui/screens/documents/widgets/file_folder_card.dart new file mode 100644 index 0000000..b3dc07a --- /dev/null +++ b/frontend/lib/ui/screens/documents/widgets/file_folder_card.dart @@ -0,0 +1,287 @@ +import 'package:flutter/material.dart'; +import '../../../../core/constants/app_colors.dart'; +import '../../../../core/constants/app_sizes.dart'; +import '../../../../domain/entities/document_model.dart'; + +class FileFolderCard extends StatelessWidget { + final DocumentModel document; + final bool isGrid; + final String userRole; + final VoidCallback onTap; + final void Function(String)? onActionSelected; + final void Function(int studentId)? onViewProfile; + + const FileFolderCard({ + super.key, + required this.document, + required this.isGrid, + required this.userRole, + required this.onTap, + this.onActionSelected, + this.onViewProfile, + }); + + IconData get _fileIcon { + final name = document.fileName.toLowerCase(); + if (name.endsWith('.pdf')) return Icons.picture_as_pdf; + if (name.endsWith('.png') || + name.endsWith('.jpg') || + name.endsWith('.jpeg')) return Icons.image; + return Icons.insert_drive_file; + } + + Color get _fileColor { + final name = document.fileName.toLowerCase(); + if (name.endsWith('.pdf')) return Colors.redAccent; + if (name.endsWith('.png') || + name.endsWith('.jpg') || + name.endsWith('.jpeg')) return Colors.blueAccent; + return AppColors.primaryGreen; + } + + Color get _statusColor { + switch (document.status) { + case 'Verified': + return AppColors.success; + case 'Pending': + return Colors.orange; + case 'Draft': + return Colors.grey; + case 'Archived': + return Colors.blue; + case 'Rejected': + return AppColors.error; + default: + return Colors.grey; + } + } + + List> _buildMenuItems() { + final items = >[ + const PopupMenuItem( + value: 'preview', + child: ListTile( + dense: true, + leading: Icon(Icons.visibility, size: 18), + title: Text('Preview', style: TextStyle(fontSize: 14)))), + const PopupMenuItem( + value: 'queue', + child: ListTile( + dense: true, + leading: Icon(Icons.print, size: 18), + title: Text('Add to Print Queue', + style: TextStyle(fontSize: 14)))), + const PopupMenuItem( + value: 'download', + child: ListTile( + dense: true, + leading: Icon(Icons.download, size: 18), + title: Text('Download', style: TextStyle(fontSize: 14)))), + const PopupMenuDivider(), + const PopupMenuItem( + value: 'view_profile', + child: ListTile( + dense: true, + leading: + Icon(Icons.person, size: 18, color: AppColors.primaryGreen), + title: Text('View Student Profile', + style: TextStyle(fontSize: 14)))), + ]; + + if (userRole != 'teacher') { + items.add(const PopupMenuDivider()); + items.add(const PopupMenuItem( + value: 'delete', + child: ListTile( + dense: true, + leading: + Icon(Icons.delete_outline, size: 18, color: AppColors.error), + title: Text('Delete', + style: + TextStyle(fontSize: 14, color: AppColors.error))))); + } + return items; + } + + @override + Widget build(BuildContext context) { + if (isGrid) return _buildGridCard(); + return _buildListRow(); + } + + // ════════════════════════════════════════ + // GRID CARD + // ════════════════════════════════════════ + Widget _buildGridCard() { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + child: Container( + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + border: Border.all(color: Colors.grey.shade200), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.03), + blurRadius: 6, + offset: const Offset(0, 2)), + ], + ), + child: Stack( + children: [ + Padding( + padding: const EdgeInsets.all(12), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: _fileColor.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(_fileIcon, size: 40, color: _fileColor), + ), + const SizedBox(height: 10), + Text( + document.fileName, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 12, + color: AppColors.textPrimary), + ), + const SizedBox(height: 4), + Text( + document.studentName ?? document.studentLrn ?? 'Unknown', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 11, color: AppColors.textSecondary), + ), + const SizedBox(height: 6), + _buildStatusBadge(small: true), + ], + ), + ), + Positioned( + top: 2, + right: 2, + child: PopupMenuButton( + icon: const Icon(Icons.more_vert, + color: AppColors.textSecondary, size: 18), + onSelected: onActionSelected, + itemBuilder: (_) => _buildMenuItems(), + ), + ), + ], + ), + ), + ); + } + + // ════════════════════════════════════════ + // LIST ROW — matches the table header columns + // ════════════════════════════════════════ + Widget _buildListRow() { + return InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + child: Row( + children: [ + // File icon + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: _fileColor.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: Icon(_fileIcon, size: 18, color: _fileColor), + ), + const SizedBox(width: 8), + + // File name + Expanded( + flex: 3, + child: Text( + document.fileName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 13, + color: AppColors.textPrimary), + ), + ), + + // Student + Expanded( + flex: 2, + child: Text( + document.studentName ?? + (document.studentLrn != null + ? 'LRN: ${document.studentLrn}' + : '—'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12, color: AppColors.textSecondary), + ), + ), + + // Doc type + Expanded( + flex: 2, + child: Text( + document.documentType ?? '—', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12, color: AppColors.textSecondary), + ), + ), + + // Status + Expanded(child: _buildStatusBadge()), + + // Actions + SizedBox( + width: 40, + child: PopupMenuButton( + icon: const Icon(Icons.more_vert, + size: 18, color: AppColors.textSecondary), + onSelected: onActionSelected, + itemBuilder: (_) => _buildMenuItems(), + ), + ), + ], + ), + ), + ); + } + + Widget _buildStatusBadge({bool small = false}) { + return Container( + padding: EdgeInsets.symmetric( + horizontal: small ? 6 : 8, vertical: small ? 2 : 3), + decoration: BoxDecoration( + color: _statusColor.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + border: + Border.all(color: _statusColor.withValues(alpha: 0.3)), + ), + child: Text( + document.status, + style: TextStyle( + fontSize: small ? 10 : 11, + color: _statusColor, + fontWeight: FontWeight.w600), + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/documents/widgets/print_queue_modal.dart b/frontend/lib/ui/screens/documents/widgets/print_queue_modal.dart new file mode 100644 index 0000000..ede016f --- /dev/null +++ b/frontend/lib/ui/screens/documents/widgets/print_queue_modal.dart @@ -0,0 +1,317 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../../core/constants/app_colors.dart'; +import '../../../../core/constants/app_sizes.dart'; +import '../../../../domain/repositories/document_repository.dart' + show PrintQueueItem; +import '../../../shared/buttons/primary_button.dart'; +import '../../../providers/document_provider.dart'; + +class PrintQueueModal extends ConsumerStatefulWidget { + const PrintQueueModal({super.key}); + + @override + ConsumerState createState() => _PrintQueueModalState(); +} + +class _PrintQueueModalState extends ConsumerState { + bool _isPrinting = false; + + Future _handlePrintAll(List items) async { + if (items.isEmpty) return; + setState(() => _isPrinting = true); + + // Simulate sending batch to printer (replace with real print service when available) + await Future.delayed(const Duration(seconds: 2)); + + if (!mounted) return; + setState(() => _isPrinting = false); + Navigator.of(context).pop(); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Batch sent to printer successfully!'), + backgroundColor: AppColors.success, + ), + ); + } + + Future _removeItem(int queueId) async { + try { + await ref + .read(printQueueMutationProvider.notifier) + .removeFromQueue(queueId); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('Failed to remove: $e'), + backgroundColor: AppColors.error, + )); + } + } + + Future _clearAll() async { + try { + await ref.read(printQueueMutationProvider.notifier).clearQueue(); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('Failed to clear queue: $e'), + backgroundColor: AppColors.error, + )); + } + } + + @override + Widget build(BuildContext context) { + final queueAsync = ref.watch(printQueueProvider); + + return Dialog( + backgroundColor: AppColors.surfaceWhite, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusLarge)), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520, maxHeight: 620), + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ── Header ── + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: AppColors.primaryGreen.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: const Icon(Icons.print, + color: AppColors.primaryGreen, size: 22), + ), + const SizedBox(width: AppSizes.p12), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Print Queue', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: AppColors.textPrimary)), + Text('Documents staged for batch printing', + style: TextStyle( + fontSize: 12, + color: AppColors.textSecondary)), + ], + ), + ), + IconButton( + icon: const Icon(Icons.close, + color: AppColors.textSecondary), + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + const Divider(height: AppSizes.p32), + + // ── Queue Content ── + Expanded( + child: queueAsync.when( + loading: () => const Center( + child: CircularProgressIndicator( + color: AppColors.primaryGreen)), + error: (e, _) => _buildErrorState(e.toString()), + data: (items) => items.isEmpty + ? _buildEmptyState() + : _buildQueueList(items), + ), + ), + + // ── Footer ── + queueAsync.maybeWhen( + data: (items) => items.isNotEmpty + ? _buildFooter(items) + : const SizedBox.shrink(), + orElse: () => const SizedBox.shrink(), + ), + ], + ), + ), + ), + ); + } + + Widget _buildQueueList(List items) { + return ListView.separated( + itemCount: items.length, + separatorBuilder: (_, __) => + Divider(height: 1, color: Colors.grey.shade100), + itemBuilder: (ctx, i) { + final item = items[i]; + final isPdf = item.fileName.toLowerCase().endsWith('.pdf'); + return ListTile( + contentPadding: + const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + leading: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: (isPdf ? Colors.red : Colors.blue) + .withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: Icon( + isPdf ? Icons.picture_as_pdf : Icons.image, + color: isPdf ? Colors.redAccent : Colors.blueAccent, + size: 20, + ), + ), + title: Text( + item.fileName, + style: const TextStyle( + fontWeight: FontWeight.w600, fontSize: 13), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (item.studentName != null) + Text(item.studentName!, + style: const TextStyle( + fontSize: 11, color: AppColors.textSecondary)), + if (item.documentType != null) + Text(item.documentType!, + style: const TextStyle( + fontSize: 11, color: AppColors.textMuted)), + ], + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _buildStatusChip(item.status), + IconButton( + icon: const Icon(Icons.remove_circle_outline, + color: AppColors.error, size: 20), + tooltip: 'Remove from Queue', + onPressed: () => _removeItem(item.queueId), + ), + ], + ), + ); + }, + ); + } + + Widget _buildStatusChip(String status) { + Color color; + switch (status) { + case 'Verified': + color = AppColors.success; + break; + case 'Pending': + color = Colors.orange; + break; + default: + color = Colors.grey; + } + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + border: Border.all(color: color.withValues(alpha: 0.3)), + ), + child: Text(status, + style: TextStyle( + fontSize: 10, color: color, fontWeight: FontWeight.w600)), + ); + } + + Widget _buildFooter(List items) { + return Column( + children: [ + const Divider(height: AppSizes.p32), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${items.length} document${items.length > 1 ? 's' : ''}', + style: const TextStyle( + fontWeight: FontWeight.bold, + color: AppColors.textPrimary)), + const Text('Ready for batch print', + style: TextStyle( + color: AppColors.textSecondary, fontSize: 12)), + ], + ), + Row( + children: [ + TextButton( + onPressed: _isPrinting ? null : _clearAll, + child: const Text('CLEAR ALL', + style: TextStyle( + color: AppColors.textSecondary, + fontWeight: FontWeight.bold)), + ), + const SizedBox(width: AppSizes.p8), + SizedBox( + width: 130, + child: PrimaryButton( + label: 'PRINT ALL', + isLoading: _isPrinting, + onPressed: () => _handlePrintAll(items), + ), + ), + ], + ), + ], + ), + ], + ); + } + + Widget _buildEmptyState() { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.print_disabled, size: 64, color: Colors.grey.shade300), + const SizedBox(height: AppSizes.p16), + const Text('Queue is empty', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: AppColors.textSecondary)), + const SizedBox(height: AppSizes.p8), + const Text( + 'Open a document\'s menu and select\n"Add to Print Queue" to batch print.', + textAlign: TextAlign.center, + style: TextStyle(color: AppColors.textMuted, fontSize: 13), + ), + ], + ), + ); + } + + Widget _buildErrorState(String message) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.error_outline, size: 48, color: AppColors.error), + const SizedBox(height: 12), + const Text('Failed to load print queue', + style: TextStyle(color: AppColors.error)), + const SizedBox(height: 8), + TextButton( + onPressed: () => ref.invalidate(printQueueProvider), + child: const Text('Retry'), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/documents/widgets/requirements_settings_modal.dart b/frontend/lib/ui/screens/documents/widgets/requirements_settings_modal.dart new file mode 100644 index 0000000..e3936f8 --- /dev/null +++ b/frontend/lib/ui/screens/documents/widgets/requirements_settings_modal.dart @@ -0,0 +1,177 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../../core/constants/app_colors.dart'; +import '../../../../core/constants/app_sizes.dart'; +import '../../../providers/document_provider.dart'; +import '../../../shared/buttons/primary_button.dart'; +import '../../../../domain/entities/document_requirement_model.dart'; + +class RequirementsSettingsModal extends ConsumerStatefulWidget { + const RequirementsSettingsModal({super.key}); + + @override + ConsumerState createState() => _RequirementsSettingsModalState(); +} + +class _RequirementsSettingsModalState extends ConsumerState { + @override + Widget build(BuildContext context) { + final settingsAsync = ref.watch(documentRequirementsSettingsProvider); + + return Dialog( + backgroundColor: AppColors.surfaceWhite, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusLarge)), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 800, maxHeight: 700), + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Row( + children: [ + Icon(Icons.settings, color: AppColors.primaryGreen, size: 28), + SizedBox(width: AppSizes.p12), + Text( + 'Document Requirements Settings', + style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: AppColors.textPrimary), + ), + ], + ), + IconButton( + icon: const Icon(Icons.close, color: AppColors.textSecondary), + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + const Divider(height: AppSizes.p32), + + // Content + Expanded( + child: settingsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, _) => Center(child: Text('Error: $e', style: const TextStyle(color: AppColors.error))), + data: (settings) => SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildCategorySection('Junior High School (JHS)', settings.jhs), + const SizedBox(height: AppSizes.p24), + _buildCategorySection('Senior High School (SHS)', settings.shs), + ], + ), + ), + ), + ), + + // Footer + const Divider(height: AppSizes.p32), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + OutlinedButton.icon( + onPressed: _addNewRequirement, + icon: const Icon(Icons.add), + label: const Text('Add New Requirement'), + ), + PrimaryButton( + label: 'DONE', + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + ], + ), + ), + ), + ); + } + + Widget _buildCategorySection(String title, List requirements) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: AppSizes.p16), + if (requirements.isEmpty) + const Text('No requirements configured.', style: TextStyle(color: AppColors.textSecondary)) + else + ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: requirements.length, + itemBuilder: (context, index) { + final req = requirements[index]; + return Card( + margin: const EdgeInsets.only(bottom: AppSizes.p8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusMedium)), + child: ListTile( + title: Text(req.name, style: const TextStyle(fontWeight: FontWeight.w600)), + subtitle: Text( + '${req.description ?? "No description"} | Mandatory: ${req.isMandatory ? "Yes" : "No"}', + style: const TextStyle(fontSize: 12), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Switch( + value: req.isEnabled ?? true, + activeColor: AppColors.primaryGreen, + onChanged: (val) { + _toggleRequirement(req, val); + }, + ), + IconButton( + icon: const Icon(Icons.delete, color: AppColors.error), + onPressed: () => _deleteRequirement(req.id), + ), + ], + ), + ), + ); + }, + ), + ], + ); + } + + void _addNewRequirement() { + // Show dialog to add a new requirement + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Add requirement form coming soon'))); + } + + void _toggleRequirement(DocumentRequirementModel req, bool isEnabled) async { + try { + final updatedReq = DocumentRequirementModel( + id: req.id, + name: req.name, + description: req.description, + category: req.category, + isMandatory: req.isMandatory, + isEnabled: isEnabled, + dueDate: req.dueDate, + acceptedFileTypes: req.acceptedFileTypes, + schoolLevels: req.schoolLevels, + ); + await ref.read(documentRequirementsMutationProvider.notifier).updateRequirement(updatedReq); + ref.invalidate(documentRequirementsSettingsProvider); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Error: $e'))); + } + } + + void _deleteRequirement(int id) async { + try { + await ref.read(documentRequirementsMutationProvider.notifier).deleteRequirement(id); + ref.invalidate(documentRequirementsSettingsProvider); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Error: $e'))); + } + } +} diff --git a/frontend/lib/ui/screens/documents/widgets/upload_ocr_modal.dart b/frontend/lib/ui/screens/documents/widgets/upload_ocr_modal.dart new file mode 100644 index 0000000..d2cb346 --- /dev/null +++ b/frontend/lib/ui/screens/documents/widgets/upload_ocr_modal.dart @@ -0,0 +1,393 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../../../core/constants/app_colors.dart'; +import '../../../../core/constants/app_sizes.dart'; +import '../../../../core/network/api_constants.dart'; +import '../../../shared/inputs/custom_text_field.dart'; +import '../../../shared/buttons/primary_button.dart'; +import '../../../providers/document_provider.dart'; + +class UploadOcrModal extends ConsumerStatefulWidget { + const UploadOcrModal({super.key}); + + @override + ConsumerState createState() => _UploadOcrModalState(); +} + +class _UploadOcrModalState extends ConsumerState { + int _currentStep = 0; + + File? _selectedFile; + String? _fileName; + String? _fileSize; + + final TextEditingController _lrnController = TextEditingController(); + final TextEditingController _remarksController = TextEditingController(); + + String? _selectedDocumentType; + int? _selectedRequirementId; + int? _matchedStudentId; + + bool _isSubmitting = false; + bool _isValidating = false; + String? _errorMessage; + + @override + void dispose() { + _lrnController.dispose(); + _remarksController.dispose(); + super.dispose(); + } + + void _pickFile() async { + FilePickerResult? result = await FilePicker.pickFiles( + type: FileType.custom, + allowedExtensions: ['pdf', 'jpg', 'png', 'jpeg'], + ); + + if (result != null) { + final file = File(result.files.single.path!); + final size = (file.lengthSync() / (1024 * 1024)).toStringAsFixed(2); + + setState(() { + _selectedFile = file; + _fileName = result.files.single.name; + _fileSize = '$size MB'; + _currentStep = 1; + }); + + _processOCR(); + } + } + + void _processOCR() async { + // Simulate OCR delay + await Future.delayed(const Duration(milliseconds: 1500)); + if (!mounted) return; + setState(() { + _currentStep = 2; + }); + } + + Future _validateAndUpload() async { + setState(() { + _errorMessage = null; + }); + + final lrn = _lrnController.text.trim(); + if (lrn.isEmpty || lrn.length != 12) { + setState(() => _errorMessage = 'Valid 12-digit LRN is required.'); + return; + } + if (_selectedDocumentType == null) { + setState(() => _errorMessage = 'Please select a Document Type.'); + return; + } + if (_selectedFile == null) { + setState(() => _errorMessage = 'No file selected.'); + return; + } + + setState(() => _isSubmitting = true); + + try { + final storage = const FlutterSecureStorage(); + final token = await storage.read(key: 'jwt_token'); + final dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl, headers: {'Authorization': 'Bearer $token'})); + + // 1. Validate LRN and get Student ID + final studentsRes = await dio.get('/students', queryParameters: {'search': lrn}); + final students = studentsRes.data['students'] as List; + if (students.isEmpty) { + setState(() { + _errorMessage = 'Student with LRN $lrn not found.'; + _isSubmitting = false; + }); + return; + } + final studentId = students[0]['id']; + + // 2. Upload Document + final formData = FormData.fromMap({ + 'studentId': studentId, + 'documentType': _selectedDocumentType, + 'requirementId': _selectedRequirementId, + 'remarks': _remarksController.text.trim(), + 'document': await MultipartFile.fromFile(_selectedFile!.path, filename: _fileName), + }); + + await dio.post('/documents/upload', data: formData); + + if (!mounted) return; + ref.invalidate(documentPageProvider); // Refresh list + Navigator.of(context).pop(); + + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Document uploaded successfully.'), + backgroundColor: AppColors.success, + ), + ); + + } on DioException catch (e) { + setState(() { + _errorMessage = e.response?.data?['message'] ?? 'Failed to upload document.'; + _isSubmitting = false; + }); + } catch (e) { + setState(() { + _errorMessage = 'An unexpected error occurred.'; + _isSubmitting = false; + }); + } + } + + @override + Widget build(BuildContext context) { + return Dialog( + backgroundColor: AppColors.surfaceWhite, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusLarge)), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 600, minHeight: 400), + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Upload & Scan Document', + style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: AppColors.primaryGreen), + ), + IconButton( + icon: const Icon(Icons.close, color: AppColors.textSecondary), + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + const Divider(height: 32), + + if (_errorMessage != null) + Container( + padding: const EdgeInsets.all(AppSizes.p12), + margin: const EdgeInsets.only(bottom: AppSizes.p16), + color: AppColors.error.withOpacity(0.1), + child: Row( + children: [ + const Icon(Icons.error_outline, color: AppColors.error), + const SizedBox(width: AppSizes.p8), + Expanded(child: Text(_errorMessage!, style: const TextStyle(color: AppColors.error))), + ], + ), + ), + + Expanded( + flex: _currentStep == 2 ? 1 : 0, + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + child: _buildCurrentStep(), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildCurrentStep() { + switch (_currentStep) { + case 0: return _buildStep0Upload(); + case 1: return _buildStep1Processing(); + case 2: return _buildStep2Review(); + default: return const SizedBox.shrink(); + } + } + + Widget _buildStep0Upload() { + return InkWell( + onTap: _pickFile, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + child: Container( + width: double.infinity, + height: 250, + decoration: BoxDecoration( + color: AppColors.primaryGreen.withOpacity(0.05), + border: Border.all(color: AppColors.primaryGreen.withOpacity(0.3), width: 2), + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + padding: const EdgeInsets.all(AppSizes.p16), + decoration: BoxDecoration( + color: AppColors.primaryGreen.withOpacity(0.1), + shape: BoxShape.circle, + ), + child: const Icon(Icons.cloud_upload_outlined, size: 64, color: AppColors.primaryGreen), + ), + const SizedBox(height: AppSizes.p16), + const Text( + 'Click to browse or drag file here', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: AppColors.textPrimary), + ), + const SizedBox(height: AppSizes.p8), + const Text( + 'Supports PDF, JPG, PNG (Max 10MB)', + style: TextStyle(color: AppColors.textSecondary), + ), + const SizedBox(height: AppSizes.p24), + ElevatedButton( + onPressed: _pickFile, + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primaryGreen, + foregroundColor: Colors.white, + elevation: 0, + ), + child: const Text('Select Document'), + ), + ], + ), + ), + ); + } + + Widget _buildStep1Processing() { + return SizedBox( + width: double.infinity, + height: 250, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const CircularProgressIndicator(color: AppColors.primaryGreen), + const SizedBox(height: AppSizes.p24), + const Text( + 'Running OCR Engine...', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: AppSizes.p8), + Text( + 'Analyzing $_fileName', + style: const TextStyle(color: AppColors.textSecondary), + ), + ], + ), + ); + } + + Widget _buildStep2Review() { + final requirementsAsync = ref.watch(documentRequirementsProvider); + + return SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.all(AppSizes.p12), + decoration: BoxDecoration( + color: Colors.blue.withOpacity(0.1), + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.blue.shade200), + ), + child: Row( + children: [ + const Icon(Icons.info_outline, color: Colors.blue), + const SizedBox(width: AppSizes.p12), + Expanded( + child: Text( + 'File: $_fileName ($_fileSize). Please select the document type and enter the student LRN.', + style: const TextStyle(color: Color(0xFF0D47A1), fontSize: 13), + ), + ), + ], + ), + ), + const SizedBox(height: AppSizes.p24), + + CustomTextField( + hintText: 'Student LRN (12 Digits)', + prefixIcon: Icons.pin_outlined, + controller: _lrnController, + ), + const SizedBox(height: AppSizes.p16), + + requirementsAsync.when( + data: (requirements) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: AppSizes.p16), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.grey.shade300), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: _selectedDocumentType, + hint: const Text('Select Document Type'), + isExpanded: true, + items: requirements.map((req) { + return DropdownMenuItem( + value: req.name, + child: Text('${req.name} (${req.category})'), + ); + }).toList(), + onChanged: (val) { + setState(() { + _selectedDocumentType = val; + final reqMatch = requirements.firstWhere((r) => r.name == val); + _selectedRequirementId = reqMatch.id; + }); + }, + ), + ), + ); + }, + loading: () => const CircularProgressIndicator(), + error: (e, st) => Text('Failed to load types: $e', style: const TextStyle(color: AppColors.error)), + ), + + const SizedBox(height: AppSizes.p16), + CustomTextField( + hintText: 'Remarks (Optional)', + prefixIcon: Icons.comment_outlined, + controller: _remarksController, + ), + + const SizedBox(height: AppSizes.p32), + + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () { + setState(() { + _currentStep = 0; + _selectedFile = null; + }); + }, + child: const Text('RE-UPLOAD', style: TextStyle(color: AppColors.textSecondary, fontWeight: FontWeight.bold)), + ), + const SizedBox(width: AppSizes.p16), + SizedBox( + width: 200, + child: PrimaryButton( + label: 'UPLOAD DOCUMENT', + isLoading: _isSubmitting, + onPressed: _validateAndUpload, + ), + ), + ], + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/login/login_screen.dart b/frontend/lib/ui/screens/login/login_screen.dart new file mode 100644 index 0000000..a126969 --- /dev/null +++ b/frontend/lib/ui/screens/login/login_screen.dart @@ -0,0 +1,366 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../shared/inputs/custom_text_field.dart'; +import '../../shared/buttons/primary_button.dart'; +import '../../layouts/windows_sidebar_layout.dart'; +import '../../layouts/android_bottom_nav_layout.dart'; +import '../../providers/auth_provider.dart'; + +class LoginScreen extends ConsumerStatefulWidget { + const LoginScreen({super.key}); + + @override + ConsumerState createState() => _LoginScreenState(); +} + +class _LoginScreenState extends ConsumerState { + final TextEditingController _usernameController = TextEditingController(); + final TextEditingController _passwordController = TextEditingController(); + bool _obscurePassword = true; + bool _rememberMe = false; + + @override + void dispose() { + _usernameController.dispose(); + _passwordController.dispose(); + super.dispose(); + } + + void _handleLogin() async { + if (_usernameController.text.trim().isEmpty || _passwordController.text.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Please enter both username and password.')), + ); + return; + } + + FocusScope.of(context).unfocus(); + + final success = await ref.read(authProvider.notifier).login( + _usernameController.text.trim(), + _passwordController.text, + rememberMe: _rememberMe, + ); + + if (!mounted) return; + + if (success) { + final user = ref.read(authProvider).value; + final isDesktop = MediaQuery.of(context).size.width >= 800; + Navigator.of(context).pushReplacement( + MaterialPageRoute( + builder: (_) => isDesktop + ? WindowsSidebarLayout(userRole: user!.role) + : AndroidBottomNavLayout(userRole: user!.role), + ), + ); + } else { + final error = ref.read(authProvider).error.toString(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error.replaceAll('Exception: ', '')), + backgroundColor: AppColors.error, + ), + ); + } + } + + void _showForgotPasswordDialog() { + showDialog( + context: context, + builder: (ctx) => _ForgotPasswordDialog( + onSuccess: (msg) { + Navigator.pop(ctx); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg), backgroundColor: AppColors.success), + ); + }, + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.pageBackground, + body: LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth >= 800) { + // Desktop: Split Layout + return Row( + children: [ + Expanded( + flex: 5, + child: Container( + color: AppColors.primaryGreen, + padding: const EdgeInsets.all(AppSizes.p48), + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Image.asset('assets/images/logo.png', width: 220, height: 220), + const SizedBox(height: AppSizes.p24), + const Text('TIS RMS', style: TextStyle(fontSize: 42, fontWeight: FontWeight.bold, color: Colors.white, letterSpacing: 2.0)), + const Text('Tiaong, Quezon', style: TextStyle(fontSize: 18, color: Colors.white70, letterSpacing: 1.0)), + const SizedBox(height: AppSizes.p32), + const Text('Record Management System', style: TextStyle(fontSize: 20, color: Colors.white, fontWeight: FontWeight.w600)), + const SizedBox(height: AppSizes.p8), + const Text('Secure Academic Records Database System', textAlign: TextAlign.center, style: TextStyle(fontSize: 15, color: Colors.white70)), + ], + ), + ), + ), + ), + Expanded( + flex: 4, + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: _buildLoginForm(), + ), + ), + ), + ], + ); + } else { + // Mobile: Stacked Layout + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(AppSizes.p24), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Image.asset('assets/images/logo.png', width: 120, height: 120), + const SizedBox(height: AppSizes.p24), + const Text('Welcome Back', style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: AppColors.primaryGreen)), + const SizedBox(height: AppSizes.p8), + const Text('Login to your account', style: TextStyle(fontSize: 16, color: AppColors.textSecondary)), + const SizedBox(height: AppSizes.p48), + _buildLoginForm(), + ], + ), + ), + ), + ); + } + }, + ), + ); + } + + Widget _buildLoginForm() { + final authState = ref.watch(authProvider); + final isLoading = authState.isLoading; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + CustomTextField( + hintText: 'Username', + prefixIcon: Icons.person_outline, + controller: _usernameController, + ), + const SizedBox(height: AppSizes.p16), + CustomTextField( + hintText: 'Password', + prefixIcon: Icons.lock_outline, + controller: _passwordController, + isPassword: true, + obscureText: _obscurePassword, + onToggleVisibility: () => setState(() => _obscurePassword = !_obscurePassword), + ), + const SizedBox(height: AppSizes.p8), + + // Remember Me + Forgot Password row + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Checkbox( + value: _rememberMe, + activeColor: AppColors.primaryGreen, + onChanged: (val) => setState(() => _rememberMe = val ?? false), + ), + const Text('Remember Me', style: TextStyle(fontSize: 13, color: AppColors.textSecondary)), + ], + ), + TextButton( + onPressed: _showForgotPasswordDialog, + child: const Text('Forgot Password?', style: TextStyle(color: AppColors.primaryGreen, fontWeight: FontWeight.w600)), + ), + ], + ), + + const SizedBox(height: AppSizes.p16), + PrimaryButton( + label: 'LOGIN', + isLoading: isLoading, + onPressed: _handleLogin, + ), + ], + ); + } +} + +// ================================================================ +// FORGOT PASSWORD DIALOG +// ================================================================ +class _ForgotPasswordDialog extends ConsumerStatefulWidget { + final void Function(String message) onSuccess; + const _ForgotPasswordDialog({required this.onSuccess}); + + @override + ConsumerState<_ForgotPasswordDialog> createState() => _ForgotPasswordDialogState(); +} + +class _ForgotPasswordDialogState extends ConsumerState<_ForgotPasswordDialog> { + final _usernameCtrl = TextEditingController(); + final _newPassCtrl = TextEditingController(); + final _confirmPassCtrl = TextEditingController(); + bool _obscureNew = true; + bool _obscureConfirm = true; + bool _isLoading = false; + String? _error; + + @override + void dispose() { + _usernameCtrl.dispose(); + _newPassCtrl.dispose(); + _confirmPassCtrl.dispose(); + super.dispose(); + } + + Future _handleSubmit() async { + final username = _usernameCtrl.text.trim(); + final newPass = _newPassCtrl.text; + final confirmPass = _confirmPassCtrl.text; + + if (username.isEmpty || newPass.isEmpty || confirmPass.isEmpty) { + setState(() => _error = 'All fields are required.'); + return; + } + if (newPass != confirmPass) { + setState(() => _error = 'Passwords do not match.'); + return; + } + if (newPass.length < 6) { + setState(() => _error = 'Password must be at least 6 characters.'); + return; + } + + setState(() { _isLoading = true; _error = null; }); + + try { + final repo = ref.read(authRepositoryProvider); + await repo.requestPasswordReset( + username: username, + newPassword: newPass, + confirmPassword: confirmPass, + ); + if (mounted) { + widget.onSuccess('Reset request submitted. Awaiting Super Admin approval.'); + } + } catch (e) { + if (mounted) { + setState(() => _error = e.toString().replaceAll('Exception: ', '')); + } + } finally { + if (mounted) setState(() => _isLoading = false); + } + } + + @override + Widget build(BuildContext context) { + return Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusLarge)), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.lock_reset, color: AppColors.primaryGreen), + const SizedBox(width: 10), + const Expanded( + child: Text('Forgot Password', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), + ), + IconButton(icon: const Icon(Icons.close), onPressed: () => Navigator.pop(context)), + ], + ), + const SizedBox(height: 8), + const Text( + 'Admin and Teacher accounts only. Your request will be reviewed by the Super Admin.', + style: TextStyle(fontSize: 13, color: AppColors.textSecondary), + ), + const Divider(height: 28), + + CustomTextField(hintText: 'Your Username', prefixIcon: Icons.person_outline, controller: _usernameCtrl), + const SizedBox(height: AppSizes.p12), + CustomTextField( + hintText: 'New Password', + prefixIcon: Icons.lock_outline, + controller: _newPassCtrl, + isPassword: true, + obscureText: _obscureNew, + onToggleVisibility: () => setState(() => _obscureNew = !_obscureNew), + ), + const SizedBox(height: AppSizes.p12), + CustomTextField( + hintText: 'Confirm New Password', + prefixIcon: Icons.lock_outline, + controller: _confirmPassCtrl, + isPassword: true, + obscureText: _obscureConfirm, + onToggleVisibility: () => setState(() => _obscureConfirm = !_obscureConfirm), + ), + + if (_error != null) ...[ + const SizedBox(height: 12), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.red.shade50, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.red.shade200), + ), + child: Row(children: [ + Icon(Icons.error_outline, color: Colors.red.shade600, size: 16), + const SizedBox(width: 8), + Expanded(child: Text(_error!, style: TextStyle(color: Colors.red.shade700, fontSize: 13))), + ]), + ), + ], + + const SizedBox(height: AppSizes.p24), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('CANCEL')), + const SizedBox(width: 12), + SizedBox( + width: 140, + child: PrimaryButton( + label: 'SUBMIT REQUEST', + isLoading: _isLoading, + onPressed: _handleSubmit, + ), + ), + ], + ), + ], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/reports/reports_screen.dart b/frontend/lib/ui/screens/reports/reports_screen.dart new file mode 100644 index 0000000..6be771f --- /dev/null +++ b/frontend/lib/ui/screens/reports/reports_screen.dart @@ -0,0 +1,589 @@ +import 'dart:io'; +import 'package:excel/excel.dart' hide Border; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../../domain/entities/report_models.dart'; +import '../../shared/buttons/primary_button.dart'; +import '../../shared/cards/stat_card.dart'; +import '../../providers/reports_provider.dart'; + +class ReportsScreen extends ConsumerStatefulWidget { + final String userRole; + const ReportsScreen({super.key, required this.userRole}); + + @override + ConsumerState createState() => _ReportsScreenState(); +} + +class _ReportsScreenState extends ConsumerState { + bool _isExporting = false; + + // ── Excel Export ───────────────────────────────────────────────────────────── + Future _handleExportExcel() async { + setState(() => _isExporting = true); + try { + final yearId = ref.read(selectedAcademicYearIdProvider); + final data = await ref.read(reportRepositoryProvider).getExportData(academicYearId: yearId); + + final years = ref.read(academicYearsProvider).asData?.value ?? []; + final yearLabel = yearId != null + ? years.firstWhere((y) => y.id == yearId, orElse: () => AcademicYear(id: 0, yearRange: 'Selected', status: '')).yearRange + : 'All Years'; + + final bytes = _buildExcel(data, yearLabel); + final defaultFileName = 'TIS_RMS_Report_${yearLabel.replaceAll('-', '_')}_${DateTime.now().millisecondsSinceEpoch}.xlsx'; + + String? savePath; + + if (Platform.isAndroid) { + // Request permissions + var storageStatus = await Permission.storage.status; + var manageStatus = await Permission.manageExternalStorage.status; + + if (!storageStatus.isGranted && !manageStatus.isGranted) { + await [Permission.storage, Permission.manageExternalStorage].request(); + storageStatus = await Permission.storage.status; + manageStatus = await Permission.manageExternalStorage.status; + } + + if (!storageStatus.isGranted && !manageStatus.isGranted) { + if (!mounted) return; + final retry = await _showPermissionDeniedDialog(); + if (retry == true) { + await openAppSettings(); + // Ask user to confirm after returning from settings + if (!mounted) return; + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Confirm Permission'), + content: const Text('Did you grant the storage permission in settings?'), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('No')), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: AppColors.primaryGreen, foregroundColor: Colors.white), + onPressed: () => Navigator.pop(ctx, true), + child: const Text('Yes') + ), + ], + ), + ); + + if (confirmed == true) { + storageStatus = await Permission.storage.status; + manageStatus = await Permission.manageExternalStorage.status; + if (!storageStatus.isGranted && !manageStatus.isGranted) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Storage permission is still denied. Cannot export.'), + backgroundColor: Colors.red, + )); + setState(() => _isExporting = false); + } + return; + } + } else { + setState(() => _isExporting = false); + return; + } + } else { + setState(() => _isExporting = false); + return; + } + } + + final selectedDirectory = await FilePicker.getDirectoryPath( + dialogTitle: 'Select folder to save report', + ); + + if (selectedDirectory == null) { + setState(() => _isExporting = false); + return; + } + savePath = '$selectedDirectory/$defaultFileName'; + } else if (Platform.isWindows) { + savePath = await FilePicker.saveFile( + dialogTitle: 'Save Report As...', + fileName: defaultFileName, + type: FileType.custom, + allowedExtensions: ['xlsx'], + ); + + if (savePath == null) { + setState(() => _isExporting = false); + return; + } + } else { + final dir = await getApplicationDocumentsDirectory(); + savePath = '${dir.path}/$defaultFileName'; + } + + final file = File(savePath); + await file.writeAsBytes(bytes); + + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('✅ Saved successfully: ${file.path}'), + backgroundColor: AppColors.success, + duration: const Duration(seconds: 5), + )); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('Export failed: $e'), + backgroundColor: Colors.red, + duration: const Duration(seconds: 5), + )); + } finally { + if (mounted) setState(() => _isExporting = false); + } + } + + Future _showPermissionDeniedDialog() { + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Permission Denied'), + content: const Text('Storage permission is required to save the exported Excel file. Would you like to open app settings to grant the permission?'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: AppColors.primaryGreen, foregroundColor: Colors.white), + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Open Settings'), + ), + ], + ), + ); + } + + + List _buildExcel(ReportExportData data, String yearLabel) { + final excel = Excel.createExcel(); + excel.delete('Sheet1'); // Remove default sheet + + // ── Sheet 1: Summary ──────────────────────────────────────────────────── + final summary = excel['Summary']; + _excelTitle(summary, 'A1', 'TIAONG INTEGRATED SCHOOL — TIS RMS', 7); + _excelTitle(summary, 'A2', 'Annual Report: $yearLabel', 7); + _excelTitle(summary, 'A3', 'Generated: ${DateTime.now().toString().substring(0, 19)}', 7); + + summary.cell(CellIndex.indexByString('A5')).value = TextCellValue('KEY METRICS'); + _boldCell(summary, 'A5'); + _header(summary, 'A6', 'Metric'); _header(summary, 'B6', 'Value'); + final stats = [ + ['Total Students Enrolled', data.students.length.toString()], + ['Verified Documents', data.documentStatus.verified.toString()], + ['Pending Documents', data.documentStatus.pending.toString()], + ['Archived Documents', data.documentStatus.archived.toString()], + ]; + for (int i = 0; i < stats.length; i++) { + summary.cell(CellIndex.indexByString('A${7 + i}')).value = TextCellValue(stats[i][0]); + summary.cell(CellIndex.indexByString('B${7 + i}')).value = TextCellValue(stats[i][1]); + } + + summary.cell(CellIndex.indexByString('A13')).value = TextCellValue('ENROLLMENT BY GRADE LEVEL'); + _boldCell(summary, 'A13'); + _header(summary, 'A14', 'Grade Level'); _header(summary, 'B14', 'Total Students'); + for (int i = 0; i < data.enrollmentByGrade.length; i++) { + final row = data.enrollmentByGrade[i]; + summary.cell(CellIndex.indexByString('A${15 + i}')).value = TextCellValue('Grade ${row.gradeLevel}'); + summary.cell(CellIndex.indexByString('B${15 + i}')).value = IntCellValue(row.totalStudents); + } + + summary.setColumnWidth(0, 32); + summary.setColumnWidth(1, 20); + + // ── Sheet 2: Student List ──────────────────────────────────────────────── + final students = excel['Student List']; + _excelTitle(students, 'A1', 'STUDENT DOCUMENT COMPLIANCE REPORT — $yearLabel', 7); + final headers = ['#', 'LRN', 'Last Name', 'First Name', 'Sex', 'Grade Level', 'Verified Docs', 'Pending Docs', 'Status']; + for (int c = 0; c < headers.length; c++) { + final cell = students.cell(CellIndex.indexByColumnRow(columnIndex: c, rowIndex: 2)); + cell.value = TextCellValue(headers[c]); + cell.cellStyle = CellStyle(bold: true, backgroundColorHex: ExcelColor.fromHexString('#1C8248'), fontColorHex: ExcelColor.fromHexString('#FFFFFF')); + } + for (int r = 0; r < data.students.length; r++) { + final s = data.students[r]; + final row = [ + (r + 1).toString(), + s.lrn, + s.lastName, + s.firstName, + s.sex, + s.gradeLevel != null ? 'Grade ${s.gradeLevel}' : 'N/A', + s.verifiedDocs.toString(), + s.pendingDocs.toString(), + s.pendingDocs == 0 ? 'Complete' : 'Incomplete', + ]; + for (int c = 0; c < row.length; c++) { + final cell = students.cell(CellIndex.indexByColumnRow(columnIndex: c, rowIndex: r + 3)); + cell.value = TextCellValue(row[c]); + if (row[c] == 'Incomplete') { + cell.cellStyle = CellStyle(fontColorHex: ExcelColor.fromHexString('#C62828')); + } else if (row[c] == 'Complete') { + cell.cellStyle = CellStyle(fontColorHex: ExcelColor.fromHexString('#1C8248')); + } + } + } + students.setColumnWidth(0, 6); students.setColumnWidth(1, 18); + students.setColumnWidth(2, 20); students.setColumnWidth(3, 20); + students.setColumnWidth(4, 8); students.setColumnWidth(5, 14); + students.setColumnWidth(6, 15); students.setColumnWidth(7, 15); + students.setColumnWidth(8, 12); + + return excel.encode()!; + } + + void _excelTitle(Sheet sheet, String addr, String text, int span) { + final cell = sheet.cell(CellIndex.indexByString(addr)); + cell.value = TextCellValue(text); + cell.cellStyle = CellStyle(bold: true, fontSize: 14, fontColorHex: ExcelColor.fromHexString('#1C8248')); + } + + void _boldCell(Sheet sheet, String addr) { + sheet.cell(CellIndex.indexByString(addr)).cellStyle = CellStyle(bold: true, fontSize: 11); + } + + void _header(Sheet sheet, String addr, String text) { + final cell = sheet.cell(CellIndex.indexByString(addr)); + cell.value = TextCellValue(text); + cell.cellStyle = CellStyle(bold: true, backgroundColorHex: ExcelColor.fromHexString('#E8F5E9')); + } + + // ── Build ───────────────────────────────────────────────────────────────── + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.transparent, + body: SafeArea( + child: RefreshIndicator( + onRefresh: () async { + ref.invalidate(reportStatsProvider); + ref.invalidate(enrollmentByGradeProvider); + ref.invalidate(documentStatusProvider); + }, + child: SingleChildScrollView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeader(context), + const SizedBox(height: AppSizes.p24), + _buildMetricsGrid(), + const SizedBox(height: AppSizes.p24), + LayoutBuilder(builder: (ctx, constraints) { + if (constraints.maxWidth > 800) { + return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(flex: 3, child: _buildEnrollmentChart()), + const SizedBox(width: AppSizes.p24), + Expanded(flex: 2, child: _buildDocumentStatusCard()), + ]); + } + return Column(children: [ + _buildEnrollmentChart(), + const SizedBox(height: AppSizes.p24), + _buildDocumentStatusCard(), + ]); + }), + const SizedBox(height: AppSizes.p48), + ], + ), + ), + ), + ), + ); + } + + // ── Header + Filters ────────────────────────────────────────────────────── + Widget _buildHeader(BuildContext context) { + final yearsAsync = ref.watch(academicYearsProvider); + final selectedYearId = ref.watch(selectedAcademicYearIdProvider); + final isDesktop = MediaQuery.of(context).size.width > 600; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('System Reports & Analytics', + style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: AppColors.textPrimary)), + const SizedBox(height: AppSizes.p8), + Text('Live data from the TIS RMS database.', + style: TextStyle(fontSize: 16, color: Colors.grey.shade600)), + ], + ), + ), + if (isDesktop) ...[ + // School Year Dropdown + yearsAsync.when( + loading: () => const SizedBox(width: 160, child: LinearProgressIndicator()), + error: (e, st) => const SizedBox.shrink(), + data: (years) => Container( + padding: const EdgeInsets.symmetric(horizontal: AppSizes.p16), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.grey.shade300), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: selectedYearId, + hint: const Text('All Years', style: TextStyle(fontWeight: FontWeight.bold)), + items: [ + const DropdownMenuItem(value: null, child: Text('All Years', style: TextStyle(fontWeight: FontWeight.bold))), + ...years.map((y) => DropdownMenuItem( + value: y.id, + child: Text(y.yearRange, style: const TextStyle(fontWeight: FontWeight.bold)), + )), + ], + onChanged: (val) => ref.read(selectedAcademicYearIdProvider.notifier).select(val), + ), + ), + ), + ), + const SizedBox(width: AppSizes.p16), + SizedBox( + width: 190, + child: PrimaryButton( + label: 'EXPORT TO EXCEL', + isLoading: _isExporting, + onPressed: _handleExportExcel, + ), + ), + ], + ], + ), + // Mobile controls + if (!isDesktop) ...[ + const SizedBox(height: AppSizes.p16), + yearsAsync.when( + loading: () => const LinearProgressIndicator(), + error: (e, st) => const SizedBox.shrink(), + data: (years) => DropdownButtonFormField( + initialValue: selectedYearId, + decoration: InputDecoration( + labelText: 'School Year', + border: OutlineInputBorder(borderRadius: BorderRadius.circular(AppSizes.radiusMedium)), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + items: [ + const DropdownMenuItem(value: null, child: Text('All Years')), + ...years.map((y) => DropdownMenuItem(value: y.id, child: Text(y.yearRange))), + ], + onChanged: (val) => ref.read(selectedAcademicYearIdProvider.notifier).select(val), + ), + ), + const SizedBox(height: AppSizes.p12), + PrimaryButton(label: 'EXPORT TO EXCEL', isLoading: _isExporting, onPressed: _handleExportExcel), + ], + ], + ); + } + + // ── KPI Cards ──────────────────────────────────────────────────────────── + Widget _buildMetricsGrid() { + final statsAsync = ref.watch(reportStatsProvider); + return statsAsync.when( + loading: () => const SizedBox(height: 110, child: Center(child: CircularProgressIndicator())), + error: (err, _) => _errorWidget('Failed to load stats: $err'), + data: (stats) => LayoutBuilder( + builder: (ctx, constraints) { + final cols = constraints.maxWidth >= 800 ? 4 : (constraints.maxWidth >= 500 ? 2 : 1); + return GridView( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: cols, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + mainAxisExtent: 110, + ), + children: [ + StatCard(title: 'Total Enrollees', value: stats.totalStudents.toString(), icon: Icons.people, iconColor: AppColors.primaryGreen), + StatCard(title: 'Verified Documents', value: stats.verifiedDocs.toString(), icon: Icons.verified, iconColor: Colors.blue), + StatCard(title: 'Verification Rate', value: '${stats.verificationRate}%', icon: Icons.verified_user, iconColor: Colors.teal), + StatCard(title: 'Pending Print Queue', value: stats.printQueueCount.toString(), icon: Icons.print, iconColor: Colors.orange), + ], + ); + }, + ), + ); + } + + // ── Enrollment Bar Chart ───────────────────────────────────────────────── + Widget _buildEnrollmentChart() { + final enrollAsync = ref.watch(enrollmentByGradeProvider); + final selectedYearId = ref.watch(selectedAcademicYearIdProvider); + final years = ref.watch(academicYearsProvider).asData?.value ?? []; + final yearLabel = selectedYearId != null + ? years.firstWhere((y) => y.id == selectedYearId, orElse: () => AcademicYear(id: 0, yearRange: 'Selected', status: '')).yearRange + : 'All Years'; + + return Container( + padding: const EdgeInsets.all(AppSizes.p24), + decoration: _cardDecoration(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Enrollment by Grade Level', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 4), + Text('School Year: $yearLabel', style: const TextStyle(color: AppColors.textSecondary, fontSize: 13)), + const SizedBox(height: AppSizes.p24), + enrollAsync.when( + loading: () => const SizedBox(height: 200, child: Center(child: CircularProgressIndicator())), + error: (err, _) => _errorWidget('$err'), + data: (grades) { + if (grades.isEmpty) return _emptyWidget('No enrollment data for selected year.'); + final maxCount = grades.map((g) => g.count).reduce((a, b) => a > b ? a : b); + return SizedBox( + height: 220, + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: grades.map((grade) { + final pct = maxCount > 0 ? grade.count / maxCount : 0.0; + return Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Text(grade.count.toString(), style: const TextStyle(fontWeight: FontWeight.bold, color: AppColors.primaryGreen, fontSize: 12)), + const SizedBox(height: 4), + AnimatedContainer( + duration: const Duration(milliseconds: 700), + curve: Curves.easeOutQuart, + margin: const EdgeInsets.symmetric(horizontal: 4), + height: 170 * pct, + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [AppColors.primaryGreen, AppColors.primaryGreen.withValues(alpha: 0.55)], + begin: Alignment.topCenter, end: Alignment.bottomCenter, + ), + borderRadius: const BorderRadius.vertical(top: Radius.circular(6)), + ), + ), + const SizedBox(height: 8), + Text(grade.label, style: const TextStyle(color: AppColors.textSecondary, fontSize: 11)), + ], + ), + ); + }).toList(), + ), + ); + }, + ), + ], + ), + ); + } + + // ── Document Status Card ───────────────────────────────────────────────── + Widget _buildDocumentStatusCard() { + final docAsync = ref.watch(documentStatusProvider); + return Container( + padding: const EdgeInsets.all(AppSizes.p24), + decoration: _cardDecoration(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Document Status', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 4), + const Text('Overall document verification health', style: TextStyle(color: AppColors.textSecondary, fontSize: 13)), + const SizedBox(height: AppSizes.p24), + docAsync.when( + loading: () => const SizedBox(height: 160, child: Center(child: CircularProgressIndicator())), + error: (err, _) => _errorWidget('$err'), + data: (doc) { + final verRate = doc.verificationRate; + return Column(children: [ + Center( + child: Stack(alignment: Alignment.center, children: [ + SizedBox( + width: 140, height: 140, + child: CircularProgressIndicator( + value: verRate, + strokeWidth: 14, + backgroundColor: Colors.grey.shade200, + valueColor: AlwaysStoppedAnimation( + verRate >= 0.8 ? AppColors.primaryGreen : verRate >= 0.5 ? Colors.orange : Colors.red, + ), + ), + ), + Column(mainAxisSize: MainAxisSize.min, children: [ + Text('${(verRate * 100).round()}%', style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold)), + const Text('Verified', style: TextStyle(color: AppColors.textSecondary, fontSize: 12)), + ]), + ]), + ), + const SizedBox(height: AppSizes.p24), + const Divider(), + const SizedBox(height: AppSizes.p12), + _legendRow('Verified', AppColors.primaryGreen, doc.verified), + const SizedBox(height: 8), + _legendRow('Pending', Colors.orange, doc.pending), + const SizedBox(height: 8), + _legendRow('Draft', Colors.blue, doc.draft), + const SizedBox(height: 8), + _legendRow('Archived', Colors.grey, doc.archived), + ]); + }, + ), + ], + ), + ); + } + + // ── Helpers ────────────────────────────────────────────────────────────── + Widget _legendRow(String label, Color color, int count) => Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row(children: [ + Container(width: 12, height: 12, decoration: BoxDecoration(color: color, shape: BoxShape.circle)), + const SizedBox(width: 8), + Text(label, style: const TextStyle(fontWeight: FontWeight.w500)), + ]), + Text(count.toString(), style: TextStyle(fontWeight: FontWeight.bold, color: color)), + ], + ); + + Widget _errorWidget(String msg) => Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration(color: Colors.red.shade50, borderRadius: BorderRadius.circular(8)), + child: Row(children: [ + const Icon(Icons.error_outline, color: Colors.red), + const SizedBox(width: 8), + Expanded(child: Text(msg, style: const TextStyle(color: Colors.red))), + ]), + ); + + Widget _emptyWidget(String msg) => Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Icon(Icons.bar_chart, size: 48, color: Colors.grey.shade400), + const SizedBox(height: 12), + Text(msg, style: TextStyle(color: Colors.grey.shade500)), + ]), + ), + ); + + BoxDecoration _cardDecoration() => BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 10, offset: const Offset(0, 4))], + ); +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/settings/requirements_settings_screen.dart b/frontend/lib/ui/screens/settings/requirements_settings_screen.dart new file mode 100644 index 0000000..0f45804 --- /dev/null +++ b/frontend/lib/ui/screens/settings/requirements_settings_screen.dart @@ -0,0 +1,552 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../shared/inputs/custom_text_field.dart'; +import '../../shared/buttons/primary_button.dart'; +import '../../providers/document_provider.dart'; +import '../../../domain/entities/document_requirement_model.dart'; + +class RequirementsSettingsScreen extends ConsumerStatefulWidget { + const RequirementsSettingsScreen({super.key}); + + @override + ConsumerState createState() => _RequirementsSettingsScreenState(); +} + +class _RequirementsSettingsScreenState extends ConsumerState + with SingleTickerProviderStateMixin { + late TabController _tabController; + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 2, vsync: this); + } + + @override + void dispose() { + _tabController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final settingsAsync = ref.watch(requirementsSettingsProvider); + + return Scaffold( + backgroundColor: Colors.transparent, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeader(), + const SizedBox(height: AppSizes.p24), + Container( + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + child: TabBar( + controller: _tabController, + labelColor: AppColors.primaryGreen, + unselectedLabelColor: AppColors.textSecondary, + indicatorColor: AppColors.primaryGreen, + tabs: const [ + Tab(text: 'JHS Requirements'), + Tab(text: 'SHS Requirements'), + ], + ), + ), + const SizedBox(height: AppSizes.p16), + Expanded( + child: settingsAsync.when( + data: (settings) => TabBarView( + controller: _tabController, + children: [ + _buildRequirementsList(settings.jhs), + _buildRequirementsList(settings.shs), + ], + ), + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, st) => Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.error_outline, size: 48, color: AppColors.error), + const SizedBox(height: AppSizes.p16), + Text('Error: $e', style: const TextStyle(color: AppColors.error)), + const SizedBox(height: AppSizes.p16), + PrimaryButton( + label: 'Retry', + onPressed: () => ref.invalidate(requirementsSettingsProvider), + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + floatingActionButton: FloatingActionButton.extended( + backgroundColor: AppColors.primaryGreen, + onPressed: () => _showAddRequirementModal(context), + icon: const Icon(Icons.add, color: Colors.white), + label: const Text('Add Document Type', style: TextStyle(color: Colors.white)), + ), + ); + } + + Widget _buildHeader() { + return Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.of(context).pop(), + ), + const SizedBox(width: AppSizes.p8), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Document Requirements', + style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: AppColors.textPrimary), + ), + Text( + 'Configure required documents for JHS and SHS students', + style: TextStyle(fontSize: 14, color: AppColors.textSecondary), + ), + ], + ), + ), + ], + ); + } + + Widget _buildRequirementsList(List requirements) { + if (requirements.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.folder_off_outlined, size: 64, color: Colors.grey.shade400), + const SizedBox(height: AppSizes.p16), + const Text('No requirements configured', style: TextStyle(color: AppColors.textSecondary)), + const SizedBox(height: AppSizes.p8), + const Text( + 'Click the button below to add document requirements', + style: TextStyle(color: AppColors.textSecondary, fontSize: 12), + ), + ], + ), + ); + } + + return ListView.builder( + padding: const EdgeInsets.only(bottom: 80), + itemCount: requirements.length, + itemBuilder: (context, index) { + final req = requirements[index]; + return _buildRequirementCard(req); + }, + ); + } + + Widget _buildRequirementCard(DocumentRequirementModel req) { + return Container( + margin: const EdgeInsets.only(bottom: AppSizes.p12), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.grey.shade200), + ), + child: ExpansionTile( + tilePadding: const EdgeInsets.symmetric(horizontal: AppSizes.p16, vertical: AppSizes.p8), + childrenPadding: const EdgeInsets.all(AppSizes.p16), + leading: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: req.isMandatory + ? AppColors.error.withValues(alpha: 0.1) + : AppColors.primaryGreen.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: Icon( + req.isMandatory ? Icons.warning_amber : Icons.check_circle_outline, + color: req.isMandatory ? AppColors.error : AppColors.primaryGreen, + ), + ), + title: Text( + req.name, + style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 16), + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 4), + Row( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: req.category == 'JHS' + ? Colors.blue.withValues(alpha: 0.1) + : Colors.purple.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + req.category, + style: TextStyle( + fontSize: 12, + color: req.category == 'JHS' ? Colors.blue : Colors.purple, + fontWeight: FontWeight.w500, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: req.isMandatory + ? AppColors.error.withValues(alpha: 0.1) + : Colors.grey.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + req.isMandatory ? 'Mandatory' : 'Optional', + style: TextStyle( + fontSize: 12, + color: req.isMandatory ? AppColors.error : Colors.grey, + fontWeight: FontWeight.w500, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: req.isEnabled + ? AppColors.success.withValues(alpha: 0.1) + : Colors.grey.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + req.isEnabled ? 'Enabled' : 'Disabled', + style: TextStyle( + fontSize: 12, + color: req.isEnabled ? AppColors.success : Colors.grey, + fontWeight: FontWeight.w500, + ), + ), + ), + ], + ), + if (req.dueDate != null) ...[ + const SizedBox(height: 4), + Text( + 'Due: ${_formatDate(req.dueDate!)}', + style: const TextStyle(fontSize: 12, color: AppColors.textSecondary), + ), + ], + ], + ), + children: [ + if (req.description != null && req.description!.isNotEmpty) ...[ + Text(req.description!, style: const TextStyle(color: AppColors.textSecondary)), + const SizedBox(height: AppSizes.p12), + ], + _buildDetailRow('Accepted File Types', req.acceptedFileTypes), + _buildDetailRow('School Levels', req.schoolLevels), + const SizedBox(height: AppSizes.p16), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton.icon( + onPressed: () => _showEditRequirementModal(context, req), + icon: const Icon(Icons.edit, size: 18), + label: const Text('Edit'), + ), + const SizedBox(width: AppSizes.p8), + TextButton.icon( + onPressed: () => _confirmDelete(req), + icon: const Icon(Icons.delete, size: 18, color: AppColors.error), + label: const Text('Delete', style: TextStyle(color: AppColors.error)), + ), + ], + ), + ], + ), + ); + } + + Widget _buildDetailRow(String label, String value) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 140, + child: Text(label, style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 13)), + ), + Expanded( + child: Text(value, style: const TextStyle(fontSize: 13)), + ), + ], + ), + ); + } + + String _formatDate(DateTime date) { + return '${date.month}/${date.day}/${date.year}'; + } + + void _showAddRequirementModal(BuildContext context) { + showDialog( + context: context, + builder: (context) => RequirementFormModal( + category: _tabController.index == 0 ? 'JHS' : 'SHS', + ), + ); + } + + void _showEditRequirementModal(BuildContext context, DocumentRequirementModel req) { + showDialog( + context: context, + builder: (context) => RequirementFormModal( + requirement: req, + category: req.category, + ), + ); + } + + void _confirmDelete(DocumentRequirementModel req) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Delete Requirement', style: TextStyle(color: AppColors.error)), + content: Text('Are you sure you want to delete "${req.name}"?'), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('CANCEL')), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: AppColors.error, foregroundColor: Colors.white), + onPressed: () async { + Navigator.pop(context); + try { + await ref.read(requirementMutationProvider.notifier).deleteRequirement(req.id); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Requirement deleted'), backgroundColor: AppColors.success), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed: $e'), backgroundColor: AppColors.error), + ); + } + }, + child: const Text('DELETE'), + ), + ], + ), + ); + } +} + +class RequirementFormModal extends ConsumerStatefulWidget { + final DocumentRequirementModel? requirement; + final String category; + + const RequirementFormModal({ + super.key, + this.requirement, + required this.category, + }); + + @override + ConsumerState createState() => _RequirementFormModalState(); +} + +class _RequirementFormModalState extends ConsumerState { + final _formKey = GlobalKey(); + late TextEditingController _nameController; + late TextEditingController _descController; + late TextEditingController _dueDateController; + + late String _category; + late bool _isMandatory; + late bool _isEnabled; + late String _acceptedFileTypes; + + bool _isLoading = false; + + @override + void initState() { + super.initState(); + final req = widget.requirement; + _nameController = TextEditingController(text: req?.name ?? ''); + _descController = TextEditingController(text: req?.description ?? ''); + _dueDateController = TextEditingController( + text: req?.dueDate != null ? '${req!.dueDate!.month}/${req.dueDate!.day}/${req.dueDate!.year}' : '', + ); + _category = req?.category ?? widget.category; + _isMandatory = req?.isMandatory ?? true; + _isEnabled = req?.isEnabled ?? true; + _acceptedFileTypes = req?.acceptedFileTypes ?? 'pdf,jpg,jpeg,png'; + } + + @override + void dispose() { + _nameController.dispose(); + _descController.dispose(); + _dueDateController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final isEditing = widget.requirement != null; + + return AlertDialog( + title: Text(isEditing ? 'Edit Document Type' : 'Add Document Type'), + content: SizedBox( + width: 400, + child: Form( + key: _formKey, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CustomTextField( + hintText: 'Document Name', + controller: _nameController, + prefixIcon: Icons.description, + validator: (v) => v?.trim().isEmpty == true ? 'Name is required' : null, + ), + const SizedBox(height: AppSizes.p12), + CustomTextField( + hintText: 'Description', + controller: _descController, + prefixIcon: Icons.notes, + maxLines: 2, + ), + const SizedBox(height: AppSizes.p12), + DropdownButtonFormField( + value: _category, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.school), + border: OutlineInputBorder(), + ), + items: ['JHS', 'SHS'].map((c) => DropdownMenuItem(value: c, child: Text(c))).toList(), + onChanged: (v) => setState(() => _category = v!), + ), + const SizedBox(height: AppSizes.p12), + CustomTextField( + hintText: 'Due Date (MM/DD/YYYY)', + controller: _dueDateController, + prefixIcon: Icons.calendar_today, + ), + const SizedBox(height: AppSizes.p12), + DropdownButtonFormField( + value: _acceptedFileTypes, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.attach_file), + border: OutlineInputBorder(), + ), + items: const [ + DropdownMenuItem(value: 'pdf', child: Text('PDF only')), + DropdownMenuItem(value: 'pdf,jpg,jpeg,png', child: Text('PDF, JPG, PNG')), + DropdownMenuItem(value: 'pdf,doc,docx', child: Text('PDF, Word')), + DropdownMenuItem(value: 'pdf,jpg,jpeg,png,doc,docx', child: Text('All')), + ], + onChanged: (v) => setState(() => _acceptedFileTypes = v!), + ), + const SizedBox(height: AppSizes.p16), + SwitchListTile( + title: const Text('Mandatory'), + value: _isMandatory, + onChanged: (v) => setState(() => _isMandatory = v), + activeColor: AppColors.error, + ), + SwitchListTile( + title: const Text('Enabled'), + value: _isEnabled, + onChanged: (v) => setState(() => _isEnabled = v), + activeColor: AppColors.success, + ), + ], + ), + ), + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('CANCEL')), + PrimaryButton( + label: isEditing ? 'UPDATE' : 'CREATE', + isLoading: _isLoading, + onPressed: _handleSubmit, + ), + ], + ); + } + + Future _handleSubmit() async { + if (!_formKey.currentState!.validate()) return; + + setState(() => _isLoading = true); + + try { + DateTime? dueDate; + if (_dueDateController.text.trim().isNotEmpty) { + final parts = _dueDateController.text.trim().split('/'); + if (parts.length == 3) { + dueDate = DateTime( + int.parse(parts[2]), + int.parse(parts[0]), + int.parse(parts[1]), + ); + } + } + + final requirement = DocumentRequirementModel( + id: widget.requirement?.id ?? 0, + name: _nameController.text.trim(), + description: _descController.text.trim().isEmpty ? null : _descController.text.trim(), + category: _category, + isMandatory: _isMandatory, + isEnabled: _isEnabled, + dueDate: dueDate, + acceptedFileTypes: _acceptedFileTypes, + schoolLevels: 'JHS,SHS', + ); + + if (widget.requirement != null) { + await ref.read(requirementMutationProvider.notifier).updateRequirement(requirement); + } else { + await ref.read(requirementMutationProvider.notifier).createRequirement(requirement); + } + + if (!mounted) return; + Navigator.pop(context); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(widget.requirement != null ? 'Requirement updated' : 'Requirement created'), + backgroundColor: AppColors.success, + ), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed: $e'), backgroundColor: AppColors.error), + ); + } finally { + if (mounted) setState(() => _isLoading = false); + } + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/settings/settings_screen.dart b/frontend/lib/ui/screens/settings/settings_screen.dart new file mode 100644 index 0000000..b5e949c --- /dev/null +++ b/frontend/lib/ui/screens/settings/settings_screen.dart @@ -0,0 +1,343 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../shared/inputs/custom_text_field.dart'; +import '../../shared/buttons/primary_button.dart'; +import '../../providers/auth_provider.dart'; +import 'requirements_settings_screen.dart'; + +class SettingsScreen extends ConsumerStatefulWidget { + final String? userRole; + const SettingsScreen({super.key, this.userRole}); + + @override + ConsumerState createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends ConsumerState { + // Profile controllers + final _firstNameCtrl = TextEditingController(); + final _middleNameCtrl = TextEditingController(); + final _lastNameCtrl = TextEditingController(); + final _extCtrl = TextEditingController(); + final _phoneCtrl = TextEditingController(); + final _emailCtrl = TextEditingController(); + + // Password controllers + final _currentPassCtrl = TextEditingController(); + final _newPassCtrl = TextEditingController(); + final _confirmPassCtrl = TextEditingController(); + bool _obscureCurrent = true; + bool _obscureNew = true; + bool _obscureConfirm = true; + + bool _isInitialized = false; + bool _isProfileLoading = false; + bool _isPasswordLoading = false; + + @override + void dispose() { + _firstNameCtrl.dispose(); + _middleNameCtrl.dispose(); + _lastNameCtrl.dispose(); + _extCtrl.dispose(); + _phoneCtrl.dispose(); + _emailCtrl.dispose(); + _currentPassCtrl.dispose(); + _newPassCtrl.dispose(); + _confirmPassCtrl.dispose(); + super.dispose(); + } + + Future _handleUpdateProfile() async { + setState(() => _isProfileLoading = true); + try { + final repo = ref.read(authRepositoryProvider); + await repo.updateProfile( + firstName: _firstNameCtrl.text.trim(), + middleName: _middleNameCtrl.text.trim(), + lastName: _lastNameCtrl.text.trim(), + extension: _extCtrl.text.trim(), + phone: _phoneCtrl.text.trim(), + email: _emailCtrl.text.trim(), + ); + ref.invalidate(profileProvider); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Profile updated successfully!'), backgroundColor: AppColors.success), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed: $e'), backgroundColor: Colors.red), + ); + } finally { + if (mounted) setState(() => _isProfileLoading = false); + } + } + + Future _handleChangePassword() async { + final current = _currentPassCtrl.text; + final newPass = _newPassCtrl.text; + final confirm = _confirmPassCtrl.text; + + if (current.isEmpty || newPass.isEmpty || confirm.isEmpty) { + _showSnack('All password fields are required.', isError: true); + return; + } + if (newPass != confirm) { + _showSnack('New passwords do not match.', isError: true); + return; + } + if (newPass.length < 6) { + _showSnack('New password must be at least 6 characters.', isError: true); + return; + } + + setState(() => _isPasswordLoading = true); + try { + final repo = ref.read(authRepositoryProvider); + await repo.changePassword( + currentPassword: current, + newPassword: newPass, + confirmPassword: confirm, + ); + _currentPassCtrl.clear(); + _newPassCtrl.clear(); + _confirmPassCtrl.clear(); + if (!mounted) return; + _showSnack('Password changed successfully!'); + } catch (e) { + if (!mounted) return; + _showSnack(e.toString().replaceAll('Exception: ', ''), isError: true); + } finally { + if (mounted) setState(() => _isPasswordLoading = false); + } + } + + void _showSnack(String msg, {bool isError = false}) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(msg), + backgroundColor: isError ? Colors.red : AppColors.success, + )); + } + + @override + Widget build(BuildContext context) { + final profileAsync = ref.watch(profileProvider); + + return Scaffold( + backgroundColor: Colors.transparent, + body: SafeArea( + child: profileAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (err, _) => Center(child: Text('Error: $err')), + data: (user) { + if (!_isInitialized) { + Future.microtask(() { + if (mounted && !_isInitialized) { + _firstNameCtrl.text = user.firstName; + _middleNameCtrl.text = user.middleName ?? ''; + _lastNameCtrl.text = user.lastName; + _extCtrl.text = user.extension ?? ''; + _phoneCtrl.text = user.phone ?? ''; + _emailCtrl.text = user.email ?? ''; + setState(() => _isInitialized = true); + } + }); + } + + return SingleChildScrollView( + padding: const EdgeInsets.all(AppSizes.p24), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 700), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header + const Text('Account Settings', style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: AppColors.textPrimary)), + const SizedBox(height: AppSizes.p8), + const Text('Manage your profile information and security settings.', style: TextStyle(fontSize: 16, color: AppColors.textSecondary)), + const SizedBox(height: AppSizes.p32), + + // ── Profile Card ────────────────────────────────────── + _buildCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(children: [ + const CircleAvatar( + radius: 30, + backgroundColor: AppColors.primaryGreen, + child: Icon(Icons.person, size: 30, color: Colors.white), + ), + const SizedBox(width: AppSizes.p16), + Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + const Text('Profile Details', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + Text('Role: ${user.role.toUpperCase().replaceAll('_', ' ')}', + style: const TextStyle(color: AppColors.primaryGreen, fontWeight: FontWeight.w600)), + ]), + ]), + const Padding(padding: EdgeInsets.symmetric(vertical: AppSizes.p24), child: Divider()), + + LayoutBuilder(builder: (ctx, constraints) { + final wide = constraints.maxWidth > 500; + final spacing = AppSizes.p16; + if (wide) { + return Column(children: [ + Row(children: [ + Expanded(child: CustomTextField(hintText: 'First Name', prefixIcon: Icons.badge_outlined, controller: _firstNameCtrl)), + SizedBox(width: spacing), + Expanded(child: CustomTextField(hintText: 'Middle Name', prefixIcon: Icons.badge_outlined, controller: _middleNameCtrl)), + ]), + SizedBox(height: spacing), + Row(children: [ + Expanded(flex: 3, child: CustomTextField(hintText: 'Last Name', prefixIcon: Icons.badge_outlined, controller: _lastNameCtrl)), + SizedBox(width: spacing), + Expanded(child: CustomTextField(hintText: 'Ext. (Jr)', prefixIcon: Icons.text_format, controller: _extCtrl)), + ]), + SizedBox(height: spacing), + Row(children: [ + Expanded(child: CustomTextField(hintText: 'Phone Number', prefixIcon: Icons.phone_outlined, controller: _phoneCtrl)), + SizedBox(width: spacing), + Expanded(child: CustomTextField(hintText: 'Email Address', prefixIcon: Icons.email_outlined, controller: _emailCtrl)), + ]), + ]); + } else { + return Column(children: [ + CustomTextField(hintText: 'First Name', prefixIcon: Icons.badge_outlined, controller: _firstNameCtrl), + SizedBox(height: spacing), + CustomTextField(hintText: 'Middle Name', prefixIcon: Icons.badge_outlined, controller: _middleNameCtrl), + SizedBox(height: spacing), + CustomTextField(hintText: 'Last Name', prefixIcon: Icons.badge_outlined, controller: _lastNameCtrl), + SizedBox(height: spacing), + CustomTextField(hintText: 'Ext. (Jr)', prefixIcon: Icons.text_format, controller: _extCtrl), + SizedBox(height: spacing), + CustomTextField(hintText: 'Phone Number', prefixIcon: Icons.phone_outlined, controller: _phoneCtrl), + SizedBox(height: spacing), + CustomTextField(hintText: 'Email Address', prefixIcon: Icons.email_outlined, controller: _emailCtrl), + ]); + } + }), + const SizedBox(height: AppSizes.p32), + Align( + alignment: Alignment.centerRight, + child: SizedBox( + width: 200, + child: PrimaryButton(label: 'SAVE CHANGES', isLoading: _isProfileLoading, onPressed: _handleUpdateProfile), + ), + ), + ], + ), + ), + + const SizedBox(height: AppSizes.p24), + + // ── Document Requirements Settings (Super Admin Only) ── + if (widget.userRole == 'super_admin') ...[ + _buildCard( + child: InkWell( + onTap: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => const RequirementsSettingsScreen(), + ), + ); + }, + child: const Row(children: [ + Icon(Icons.folder_copy_outlined, color: AppColors.primaryGreen), + SizedBox(width: AppSizes.p8), + Expanded(child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Document Requirements', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + Text('Configure required documents for JHS and SHS', style: TextStyle(fontSize: 13, color: AppColors.textSecondary)), + ], + )), + Icon(Icons.chevron_right, color: AppColors.textSecondary), + ]), + ), + ), + const SizedBox(height: AppSizes.p24), + ], + + // ── Change Password Card ────────────────────────────── + _buildCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Row(children: [ + Icon(Icons.lock_outline, color: AppColors.textPrimary), + SizedBox(width: AppSizes.p8), + Text('Change Password', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + ]), + const SizedBox(height: 6), + const Text('Enter your current password before setting a new one.', style: TextStyle(fontSize: 13, color: AppColors.textSecondary)), + const Divider(height: 28), + + CustomTextField( + hintText: 'Current Password', + prefixIcon: Icons.lock_open_outlined, + controller: _currentPassCtrl, + isPassword: true, + obscureText: _obscureCurrent, + onToggleVisibility: () => setState(() => _obscureCurrent = !_obscureCurrent), + ), + const SizedBox(height: AppSizes.p12), + CustomTextField( + hintText: 'New Password', + prefixIcon: Icons.lock_outline, + controller: _newPassCtrl, + isPassword: true, + obscureText: _obscureNew, + onToggleVisibility: () => setState(() => _obscureNew = !_obscureNew), + ), + const SizedBox(height: AppSizes.p12), + CustomTextField( + hintText: 'Confirm New Password', + prefixIcon: Icons.lock_outline, + controller: _confirmPassCtrl, + isPassword: true, + obscureText: _obscureConfirm, + onToggleVisibility: () => setState(() => _obscureConfirm = !_obscureConfirm), + ), + const SizedBox(height: AppSizes.p24), + Align( + alignment: Alignment.centerRight, + child: SizedBox( + width: 200, + child: PrimaryButton(label: 'UPDATE PASSWORD', isLoading: _isPasswordLoading, onPressed: _handleChangePassword), + ), + ), + ], + ), + ), + + const SizedBox(height: AppSizes.p48), + ], + ), + ), + ), + ); + }, + ), + ), + ); + } + + Widget _buildCard({required Widget child}) { + return Container( + width: double.infinity, + padding: const EdgeInsets.all(AppSizes.p24), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 10, offset: const Offset(0, 4))], + border: Border.all(color: Colors.grey.shade200), + ), + child: child, + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/splash/splash_screen.dart b/frontend/lib/ui/screens/splash/splash_screen.dart new file mode 100644 index 0000000..3ce5d52 --- /dev/null +++ b/frontend/lib/ui/screens/splash/splash_screen.dart @@ -0,0 +1,80 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../login/login_screen.dart'; +import '../../layouts/windows_sidebar_layout.dart'; +import '../../layouts/android_bottom_nav_layout.dart'; +import '../../providers/auth_provider.dart'; + +class SplashScreen extends ConsumerStatefulWidget { + const SplashScreen({super.key}); + + @override + ConsumerState createState() => _SplashScreenState(); +} + +class _SplashScreenState extends ConsumerState { + @override + void initState() { + super.initState(); + _initializeApp(); + } + + Future _initializeApp() async { + await Future.delayed(const Duration(milliseconds: 1800)); + if (!mounted) return; + + // Try to auto-login if Remember Me was enabled + final user = await ref.read(authProvider.notifier).tryAutoLogin(); + + if (!mounted) return; + + if (user != null) { + final isDesktop = MediaQuery.of(context).size.width >= 800; + Navigator.of(context).pushReplacement( + MaterialPageRoute( + builder: (_) => isDesktop + ? WindowsSidebarLayout(userRole: user.role) + : AndroidBottomNavLayout(userRole: user.role), + ), + ); + } else { + Navigator.of(context).pushReplacement( + MaterialPageRoute(builder: (_) => const LoginScreen()), + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF9F9F9), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Image.asset('assets/images/logo.png', width: 150, height: 150), + const SizedBox(height: 24), + const Text( + 'TIS RMS', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Color(0xFF1C8248), + letterSpacing: 1.2, + ), + ), + const SizedBox(height: 8), + const Text( + 'Record Management System', + style: TextStyle(fontSize: 14, color: Colors.grey), + ), + const SizedBox(height: 48), + const CircularProgressIndicator( + valueColor: AlwaysStoppedAnimation(Color(0xFF1C8248)), + ), + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/students/student_detail_screen.dart b/frontend/lib/ui/screens/students/student_detail_screen.dart new file mode 100644 index 0000000..3e6a3b9 --- /dev/null +++ b/frontend/lib/ui/screens/students/student_detail_screen.dart @@ -0,0 +1,337 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../../domain/repositories/document_repository.dart' show MissingRequirements; +import '../../providers/student_provider.dart'; +import '../../providers/document_provider.dart'; + +class StudentDetailScreen extends ConsumerWidget { + final int studentId; + final String userRole; + + const StudentDetailScreen({ + super.key, + required this.studentId, + required this.userRole, + }); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final studentAsync = ref.watch(studentDetailProvider(studentId)); + final missingReqsAsync = ref.watch(missingRequirementsProvider(studentId)); + + return Scaffold( + backgroundColor: AppColors.pageBackground, + appBar: AppBar( + backgroundColor: AppColors.primaryGreen, + foregroundColor: Colors.white, + title: const Text('Student Profile'), + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.of(context).pop(), + ), + ), + body: studentAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, st) => Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.error_outline, size: 48, color: AppColors.error), + const SizedBox(height: AppSizes.p16), + Text('Error: $e', style: const TextStyle(color: AppColors.error)), + ], + ), + ), + data: (student) => SingleChildScrollView( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Student Info Card + _buildInfoCard(student), + const SizedBox(height: AppSizes.p24), + + // Enrollments + if (student.enrollments != null && student.enrollments!.isNotEmpty) ...[ + const Text('Enrollments', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: AppSizes.p12), + ...student.enrollments!.map((e) => _buildEnrollmentCard(e)).toList(), + const SizedBox(height: AppSizes.p24), + ], + + // Document Requirements Status + const Text('Document Requirements', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: AppSizes.p12), + missingReqsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, _) => Text('Error loading requirements: $e', style: const TextStyle(color: AppColors.error)), + data: (missing) => _buildRequirementsStatus(missing), + ), + ], + ), + ), + ), + ); + } + + Widget _buildInfoCard(dynamic student) { + return Container( + padding: const EdgeInsets.all(AppSizes.p20), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + boxShadow: [ + BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 10, offset: const Offset(0, 4)), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 36, + backgroundColor: AppColors.primaryGreen, + child: Text( + '${student.firstName?[0] ?? ''}${student.lastName?[0] ?? ''}', + style: const TextStyle(fontSize: 24, color: Colors.white, fontWeight: FontWeight.bold), + ), + ), + const SizedBox(width: AppSizes.p16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${student.firstName} ${student.middleName != null ? student.middleName + ' ' : ''}${student.lastName} ${student.extension ?? ''}', + style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + ), + Text( + 'LRN: ${student.lrn}', + style: const TextStyle(color: AppColors.textSecondary, fontSize: 14), + ), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: _getStatusColor(student.status).withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + student.status ?? 'Enrolled', + style: TextStyle( + color: _getStatusColor(student.status), + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + const Divider(height: 32), + Row( + children: [ + _buildInfoItem('Sex', student.sex), + const SizedBox(width: AppSizes.p24), + _buildInfoItem('Birth Date', _formatDate(student.birthDate)), + ], + ), + ], + ), + ); + } + + Widget _buildInfoItem(String label, String value) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: const TextStyle(color: AppColors.textSecondary, fontSize: 12)), + Text(value, style: const TextStyle(fontWeight: FontWeight.w600)), + ], + ); + } + + Widget _buildEnrollmentCard(dynamic enrollment) { + return Container( + margin: const EdgeInsets.only(bottom: AppSizes.p8), + padding: const EdgeInsets.all(AppSizes.p12), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.grey.shade200), + ), + child: Row( + children: [ + Container( + width: 48, + height: 48, + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: const Icon(Icons.school, color: Colors.blue), + ), + const SizedBox(width: AppSizes.p12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Grade ${enrollment.gradeLevel}', + style: const TextStyle(fontWeight: FontWeight.w600), + ), + Text( + '${enrollment.sectionName ?? 'N/A'} - ${enrollment.yearRange ?? 'N/A'}', + style: const TextStyle(color: AppColors.textSecondary, fontSize: 13), + ), + if (enrollment.trackStrand != null) + Text( + 'Track: ${enrollment.trackStrand}', + style: const TextStyle(color: AppColors.textSecondary, fontSize: 12), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildRequirementsStatus(MissingRequirements missing) { + return Container( + padding: const EdgeInsets.all(AppSizes.p16), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.grey.shade200), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Summary + Row( + children: [ + _buildStatusChip( + 'Total Required', + '${missing.totalRequired}', + AppColors.primaryGreen, + ), + const SizedBox(width: AppSizes.p8), + _buildStatusChip( + 'Verified', + '${missing.totalVerified}', + AppColors.success, + ), + const SizedBox(width: AppSizes.p8), + _buildStatusChip( + 'Missing', + '${missing.totalRequired - missing.totalVerified}', + missing.totalRequired - missing.totalVerified > 0 + ? AppColors.error + : AppColors.success, + ), + ], + ), + const SizedBox(height: AppSizes.p16), + + // Missing Documents + if (missing.missing.isNotEmpty) ...[ + const Text('Missing Documents', style: TextStyle(fontWeight: FontWeight.w600, color: AppColors.error)), + const SizedBox(height: AppSizes.p8), + ...missing.missing.map((req) => _buildRequirementItem(req.name, 'Missing', AppColors.error)), + const SizedBox(height: AppSizes.p12), + ], + + // Pending Documents + if (missing.pending.isNotEmpty) ...[ + const Text('Pending Documents', style: TextStyle(fontWeight: FontWeight.w600, color: Colors.orange)), + const SizedBox(height: AppSizes.p8), + ...missing.pending.map((req) => _buildRequirementItem( + req.name, + 'Pending', + Colors.orange, + )), + const SizedBox(height: AppSizes.p12), + ], + + // Verified Documents + if (missing.verified.isNotEmpty) ...[ + const Text('Verified Documents', style: TextStyle(fontWeight: FontWeight.w600, color: AppColors.success)), + const SizedBox(height: AppSizes.p8), + ...missing.verified.map((req) => _buildRequirementItem(req.name, 'Verified', AppColors.success)), + ], + + if (missing.missing.isEmpty && missing.pending.isEmpty && missing.verified.isEmpty) + const Center( + child: Padding( + padding: EdgeInsets.all(AppSizes.p24), + child: Text('No document requirements for this student', style: TextStyle(color: AppColors.textSecondary)), + ), + ), + ], + ), + ); + } + + Widget _buildStatusChip(String label, String value, Color color) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(value, style: TextStyle(fontWeight: FontWeight.bold, color: color)), + const SizedBox(width: 4), + Text(label, style: TextStyle(fontSize: 12, color: color)), + ], + ), + ); + } + + Widget _buildRequirementItem(String name, String status, Color color) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row( + children: [ + Icon( + status == 'Verified' ? Icons.check_circle : Icons.warning, + size: 16, + color: color, + ), + const SizedBox(width: 8), + Expanded(child: Text(name)), + Text(status, style: TextStyle(color: color, fontSize: 12, fontWeight: FontWeight.w500)), + ], + ), + ); + } + + Color _getStatusColor(String? status) { + switch (status) { + case 'Enrolled': + return AppColors.success; + case 'Graduated': + return Colors.blue; + case 'Transferred Out': + return Colors.orange; + case 'Dropped': + return AppColors.error; + default: + return Colors.grey; + } + } + + String _formatDate(dynamic date) { + if (date == null) return 'N/A'; + if (date is DateTime) { + return '${date.month}/${date.day}/${date.year}'; + } + return date.toString(); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/students/students_screen.dart b/frontend/lib/ui/screens/students/students_screen.dart new file mode 100644 index 0000000..823f174 --- /dev/null +++ b/frontend/lib/ui/screens/students/students_screen.dart @@ -0,0 +1,748 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../../domain/entities/student_model.dart'; +import '../../shared/buttons/primary_button.dart'; +import '../../providers/student_provider.dart'; +import '../documents/documents_screen.dart'; +import '../students/student_detail_screen.dart'; +import 'widgets/add_edit_student_modal.dart'; + +class StudentsScreen extends ConsumerStatefulWidget { + final String userRole; + const StudentsScreen({super.key, this.userRole = 'teacher'}); + + @override + ConsumerState createState() => _StudentsScreenState(); +} + +class _StudentsScreenState extends ConsumerState { + final TextEditingController _searchController = TextEditingController(); + Timer? _debounce; + + static const _gradeLevels = ['All Grades', '7', '8', '9', '10', '11', '12']; + static const _statusItems = ['All Status', 'Enrolled', 'Graduated', 'Transferred Out', 'Dropped']; + static const _pageSizes = [10, 20, 50]; + + @override + void initState() { + super.initState(); + // Listen for text changes and debounce search + _searchController.addListener(_onSearchChanged); + } + + @override + void dispose() { + _debounce?.cancel(); + _searchController.removeListener(_onSearchChanged); + _searchController.dispose(); + super.dispose(); + } + + void _onSearchChanged() { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 500), () { + ref.read(studentQueryProvider.notifier).setSearch(_searchController.text); + }); + } + + // ---------------------------------------------------------------- + // SHOW ADD / EDIT MODAL + // ---------------------------------------------------------------- + void _openModal({StudentModel? student}) async { + final result = await showDialog( + context: context, + barrierDismissible: false, + builder: (_) => AddEditStudentModal(student: student), + ); + // result == true means success — list already refreshed by provider + if (result == true && mounted) { + // Provider already invalidated inside mutation notifier + } + } + + // ---------------------------------------------------------------- + // DELETE CONFIRM + // ---------------------------------------------------------------- + Future _confirmDelete(StudentModel student) async { + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Delete Student?'), + content: Text( + 'Are you sure you want to permanently delete ' + '"${student.fullName}"? This cannot be undone.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(false), + child: const Text('CANCEL'), + ), + TextButton( + onPressed: () => Navigator.of(ctx).pop(true), + style: TextButton.styleFrom(foregroundColor: AppColors.error), + child: const Text('DELETE'), + ), + ], + ), + ); + + if (confirmed == true && mounted) { + try { + await ref.read(studentMutationProvider.notifier).deleteStudent(student.id); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Student deleted successfully.'), + backgroundColor: AppColors.success, + ), + ); + } + } catch (e) { + if (mounted) { + final raw = e.toString(); + final msg = raw.startsWith('Exception: ') ? raw.substring(11) : raw; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg), backgroundColor: AppColors.error), + ); + } + } + } + } + + // ---------------------------------------------------------------- + // NAVIGATION HELPERS + // ---------------------------------------------------------------- + void _viewProfile(int studentId) { + Navigator.of(context).push(MaterialPageRoute( + builder: (_) => StudentDetailScreen( + studentId: studentId, + userRole: widget.userRole, + ), + )); + } + + void _openDocumentsFolder(int studentId) { + Navigator.of(context).push(MaterialPageRoute( + builder: (_) => DocumentsScreen( + userRole: widget.userRole, + initialStudentId: studentId, + ), + )); + } + + // ================================================================ + // BUILD + // ================================================================ + @override + Widget build(BuildContext context) { + final query = ref.watch(studentQueryProvider); + final pageAsync = ref.watch(studentPageProvider); + + return Scaffold( + backgroundColor: Colors.transparent, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ── Header + Controls ── + _buildHeaderControls(context, query), + const SizedBox(height: AppSizes.p24), + + // ── Data Table / Cards ── + Expanded( + child: pageAsync.when( + loading: () => const Center( + child: CircularProgressIndicator(color: AppColors.primaryGreen), + ), + error: (err, _) => _buildError(err.toString()), + data: (page) => LayoutBuilder( + builder: (ctx, c) => c.maxWidth > 800 + ? _buildDesktopTable(page.students) + : _buildMobileCardList(page.students), + ), + ), + ), + + // ── Pagination ── + const SizedBox(height: AppSizes.p16), + pageAsync.maybeWhen( + data: (page) => _buildPagination(query, page), + orElse: () => const SizedBox.shrink(), + ), + ], + ), + ), + ), + ); + } + + // ================================================================ + // HEADER + CONTROLS + // ================================================================ + Widget _buildHeaderControls(BuildContext context, StudentQueryParams query) { + final gradeValue = query.gradeLevel.isEmpty ? 'All Grades' : query.gradeLevel; + final statusValue = query.status.isEmpty ? 'All Status' : query.status; + + return LayoutBuilder(builder: (_, c) { + final isDesktop = c.maxWidth > 800; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Title row + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Students Directory', + style: TextStyle( + fontSize: 28, + fontWeight: FontWeight.bold, + color: AppColors.textPrimary, + ), + ), + // Add Student Button + if (widget.userRole != 'teacher') + SizedBox( + width: isDesktop ? 180 : 50, + child: isDesktop + ? PrimaryButton( + label: '+ ADD STUDENT', + onPressed: () => _openModal(), + ) + : ElevatedButton( + onPressed: () => _openModal(), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primaryGreen, + foregroundColor: Colors.white, + padding: const EdgeInsets.all(14), + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.circular(AppSizes.radiusMedium), + ), + ), + child: const Icon(Icons.add), + ), + ), + ], + ), + const SizedBox(height: AppSizes.p16), + + // Search + Filters row + Wrap( + spacing: AppSizes.p12, + runSpacing: AppSizes.p12, + children: [ + // Search field + SizedBox( + width: isDesktop ? 300 : double.infinity, + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: 'Search by LRN or name…', + prefixIcon: const Icon(Icons.search, color: AppColors.textSecondary), + filled: true, + fillColor: AppColors.surfaceWhite, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + borderSide: BorderSide(color: Colors.grey.shade300), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + borderSide: BorderSide(color: Colors.grey.shade300), + ), + suffixIcon: _searchController.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.close, size: 18), + onPressed: () { + _searchController.clear(); + ref.read(studentQueryProvider.notifier).setSearch(''); + }, + ) + : null, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + ), + ), + ), + + // Grade Level filter + _FilterDropdown( + value: gradeValue, + items: _gradeLevels, + icon: Icons.school_outlined, + onChanged: (v) { + ref.read(studentQueryProvider.notifier) + .setGradeLevel(v == 'All Grades' ? '' : v); + }, + ), + + // Status filter + _FilterDropdown( + value: statusValue, + items: _statusItems, + icon: Icons.flag_outlined, + onChanged: (v) { + ref.read(studentQueryProvider.notifier) + .setStatus(v == 'All Status' ? '' : v); + }, + ), + + // Page size selector + _FilterDropdown( + value: '${query.limit} / page', + items: _pageSizes.map((n) => '$n / page').toList(), + icon: Icons.format_list_numbered, + onChanged: (v) { + final n = int.tryParse(v.split(' ').first) ?? 10; + ref.read(studentQueryProvider.notifier).setLimit(n); + }, + ), + ], + ), + ], + ); + }); + } + + // ================================================================ + // DESKTOP DATA TABLE + // ================================================================ + Widget _buildDesktopTable(List students) { + if (students.isEmpty) return _buildEmptyState(); + + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.04), + blurRadius: 12, + offset: const Offset(0, 4), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + headingRowColor: WidgetStateProperty.all( + AppColors.primaryGreen.withValues(alpha: 0.06), + ), + dataRowMaxHeight: 56, + columns: const [ + DataColumn(label: Text('LRN', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Name', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Grade & Sec.', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Status', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Missing Docs', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Actions', style: TextStyle(fontWeight: FontWeight.bold))), + ], + rows: students.map((student) { + return DataRow(cells: [ + DataCell(Text(student.lrn, style: const TextStyle(fontWeight: FontWeight.w600))), + DataCell(Text(student.fullName)), + DataCell(Text(student.gradeSection)), + DataCell(_StatusChip(status: student.status)), + DataCell(_MissingDocsBadge(count: student.missingDocumentsCount)), + DataCell(_ActionButtons( + student: student, + userRole: widget.userRole, + onEdit: () => _openModal(student: student), + onDelete: () => _confirmDelete(student), + onViewProfile: () => _viewProfile(student.id), + onOpenDocuments: () => _openDocumentsFolder(student.id), + )), + ]); + }).toList(), + ), + ), + ), + ), + ); + } + + // ================================================================ + // MOBILE CARD LIST + // ================================================================ + Widget _buildMobileCardList(List students) { + if (students.isEmpty) return _buildEmptyState(); + + return ListView.separated( + itemCount: students.length, + separatorBuilder: (ctx, index) => const SizedBox(height: AppSizes.p12), + itemBuilder: (_, i) { + final s = students[i]; + return Container( + padding: const EdgeInsets.all(AppSizes.p16), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.04), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + s.lrn, + style: const TextStyle( + fontWeight: FontWeight.bold, + color: AppColors.primaryGreen, + ), + ), + _StatusChip(status: s.status), + ], + ), + const SizedBox(height: AppSizes.p8), + Text(s.fullName, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold)), + Text(s.gradeSection, style: const TextStyle(color: AppColors.textSecondary)), + const Padding( + padding: EdgeInsets.symmetric(vertical: AppSizes.p12), + child: Divider(height: 1), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row(children: [ + const Text('Missing Docs: ', style: TextStyle(color: AppColors.textSecondary)), + _MissingDocsBadge(count: s.missingDocumentsCount), + ]), + _ActionButtons( + student: s, + userRole: widget.userRole, + onEdit: () => _openModal(student: s), + onDelete: () => _confirmDelete(s), + onViewProfile: () => _viewProfile(s.id), + onOpenDocuments: () => _openDocumentsFolder(s.id), + ), + ], + ), + ], + ), + ); + }, + ); + } + + // ================================================================ + // PAGINATION CONTROLS + // ================================================================ + Widget _buildPagination(StudentQueryParams query, dynamic page) { + final total = page.total as int; + final totalPages = page.totalPages as int; + final current = query.page; + + final from = total == 0 ? 0 : ((current - 1) * query.limit) + 1; + final to = (current * query.limit).clamp(0, total); + + return Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Text( + 'Showing $from–$to of $total', + style: const TextStyle(color: AppColors.textSecondary, fontSize: 13), + ), + const SizedBox(width: AppSizes.p12), + + // First page + _PaginationButton( + icon: Icons.first_page, + enabled: current > 1, + onTap: () => ref.read(studentQueryProvider.notifier).setPage(1), + ), + // Prev + _PaginationButton( + icon: Icons.chevron_left, + enabled: current > 1, + onTap: () => ref.read(studentQueryProvider.notifier).setPage(current - 1), + ), + + // Page number chips + ...List.generate(totalPages, (i) => i + 1) + .where((p) => (p - current).abs() <= 2) + .map((p) => _PageChip( + page: p, + current: current, + onTap: () => ref.read(studentQueryProvider.notifier).setPage(p), + )), + + // Next + _PaginationButton( + icon: Icons.chevron_right, + enabled: current < totalPages, + onTap: () => ref.read(studentQueryProvider.notifier).setPage(current + 1), + ), + // Last page + _PaginationButton( + icon: Icons.last_page, + enabled: current < totalPages, + onTap: () => ref.read(studentQueryProvider.notifier).setPage(totalPages), + ), + ], + ); + } + + Widget _buildEmptyState() { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.people_outline, size: 64, color: Colors.grey.shade300), + const SizedBox(height: 16), + Text( + 'No students found.', + style: TextStyle(color: AppColors.textSecondary, fontSize: 16), + ), + const SizedBox(height: 8), + Text( + 'Try adjusting your search or filters.', + style: TextStyle(color: AppColors.textMuted, fontSize: 13), + ), + ], + ), + ); + } + + Widget _buildError(String message) { + final clean = message.startsWith('Exception: ') ? message.substring(11) : message; + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.wifi_off_rounded, size: 56, color: AppColors.error), + const SizedBox(height: 16), + Text( + clean, + textAlign: TextAlign.center, + style: const TextStyle(color: AppColors.error), + ), + const SizedBox(height: 16), + ElevatedButton.icon( + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + onPressed: () => ref.invalidate(studentPageProvider), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primaryGreen, + foregroundColor: Colors.white, + ), + ), + ], + ), + ); + } +} + +// ================================================================ +// EXTRACTED COMPONENTS +// ================================================================ + +class _FilterDropdown extends StatelessWidget { + final String value; + final List items; + final IconData icon; + final ValueChanged onChanged; + + const _FilterDropdown({ + required this.value, + required this.items, + required this.icon, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.grey.shade300), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: value, + icon: const Icon(Icons.expand_more, size: 18), + isDense: true, + items: items.map((i) => DropdownMenuItem(value: i, child: Text(i, style: const TextStyle(fontSize: 13)))).toList(), + onChanged: (v) => onChanged(v!), + ), + ), + ); + } +} + +class _StatusChip extends StatelessWidget { + final String status; + const _StatusChip({required this.status}); + + Color get _bg { + return switch (status) { + 'Enrolled' => AppColors.primaryGreen.withValues(alpha: 0.10), + 'Graduated' => Colors.blue.withValues(alpha: 0.10), + 'Transferred Out' => Colors.orange.withValues(alpha: 0.10), + 'Dropped' => Colors.red.withValues(alpha: 0.10), + _ => Colors.grey.shade200, + }; + } + + Color get _text { + return switch (status) { + 'Enrolled' => AppColors.primaryGreen, + 'Graduated' => Colors.blue.shade700, + 'Transferred Out' => Colors.orange.shade800, + 'Dropped' => Colors.red.shade700, + _ => Colors.grey.shade700, + }; + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration(color: _bg, borderRadius: BorderRadius.circular(20)), + child: Text(status, style: TextStyle(color: _text, fontWeight: FontWeight.w600, fontSize: 12)), + ); + } +} + +class _MissingDocsBadge extends StatelessWidget { + final int count; + const _MissingDocsBadge({required this.count}); + + @override + Widget build(BuildContext context) { + if (count == 0) return const Icon(Icons.check_circle, color: AppColors.primaryGreen, size: 22); + return Container( + padding: const EdgeInsets.all(6), + decoration: const BoxDecoration(color: AppColors.error, shape: BoxShape.circle), + child: Text( + count > 99 ? '99+' : count.toString(), + style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.bold), + ), + ); + } +} + +class _ActionButtons extends StatelessWidget { + final StudentModel student; + final String userRole; + final VoidCallback onEdit; + final VoidCallback onDelete; + final VoidCallback onViewProfile; + final VoidCallback onOpenDocuments; + + const _ActionButtons({ + required this.student, + required this.userRole, + required this.onEdit, + required this.onDelete, + required this.onViewProfile, + required this.onOpenDocuments, + }); + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Tooltip( + message: 'View Profile', + child: IconButton( + icon: const Icon(Icons.person_outline, color: AppColors.primaryGreen), + onPressed: onViewProfile, + ), + ), + Tooltip( + message: 'Open Documents Folder', + child: IconButton( + icon: const Icon(Icons.folder_open, color: Colors.orange), + onPressed: onOpenDocuments, + ), + ), + if (userRole != 'teacher') ...[ + Tooltip( + message: 'Edit Student', + child: IconButton( + icon: const Icon(Icons.edit_outlined, color: Colors.blueAccent), + onPressed: onEdit, + ), + ), + Tooltip( + message: 'Delete Student', + child: IconButton( + icon: const Icon(Icons.delete_outline, color: AppColors.error), + onPressed: onDelete, + ), + ), + ], + ], + ); + } +} + +class _PaginationButton extends StatelessWidget { + final IconData icon; + final bool enabled; + final VoidCallback onTap; + const _PaginationButton({required this.icon, required this.enabled, required this.onTap}); + + @override + Widget build(BuildContext context) { + return IconButton( + icon: Icon(icon, size: 20, color: enabled ? AppColors.primaryGreen : Colors.grey.shade300), + onPressed: enabled ? onTap : null, + ); + } +} + +class _PageChip extends StatelessWidget { + final int page; + final int current; + final VoidCallback onTap; + const _PageChip({required this.page, required this.current, required this.onTap}); + + @override + Widget build(BuildContext context) { + final isActive = page == current; + return GestureDetector( + onTap: onTap, + child: Container( + width: 34, + height: 34, + margin: const EdgeInsets.symmetric(horizontal: 2), + decoration: BoxDecoration( + color: isActive ? AppColors.primaryGreen : Colors.transparent, + borderRadius: BorderRadius.circular(8), + border: isActive ? null : Border.all(color: Colors.grey.shade300), + ), + child: Center( + child: Text( + '$page', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: isActive ? Colors.white : AppColors.textSecondary, + ), + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/students/widgets/add_edit_student_modal.dart b/frontend/lib/ui/screens/students/widgets/add_edit_student_modal.dart new file mode 100644 index 0000000..228a0cc --- /dev/null +++ b/frontend/lib/ui/screens/students/widgets/add_edit_student_modal.dart @@ -0,0 +1,460 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../../core/constants/app_colors.dart'; +import '../../../../core/constants/app_sizes.dart'; +import '../../../../domain/entities/student_model.dart'; + +import '../../../shared/buttons/primary_button.dart'; +import '../../../providers/student_provider.dart'; + +class AddEditStudentModal extends ConsumerStatefulWidget { + final StudentModel? student; // null → Add mode, non-null → Edit mode + + const AddEditStudentModal({super.key, this.student}); + + @override + ConsumerState createState() => _AddEditStudentModalState(); +} + +class _AddEditStudentModalState extends ConsumerState { + final _formKey = GlobalKey(); + + late TextEditingController _lrnController; + late TextEditingController _firstNameController; + late TextEditingController _middleNameController; + late TextEditingController _lastNameController; + late TextEditingController _extController; + + String _selectedSex = 'Male'; + String _selectedStatus = 'Enrolled'; + DateTime? _selectedDob; + bool _isLoading = false; + String? _errorMessage; + + static const _statuses = ['Enrolled', 'Graduated', 'Transferred Out', 'Dropped']; + + @override + void initState() { + super.initState(); + final s = widget.student; + _lrnController = TextEditingController(text: s?.lrn ?? ''); + _firstNameController = TextEditingController(text: s?.firstName ?? ''); + _middleNameController = TextEditingController(text: s?.middleName ?? ''); + _lastNameController = TextEditingController(text: s?.lastName ?? ''); + _extController = TextEditingController(text: s?.extension ?? ''); + if (s != null) { + _selectedSex = s.sex; + _selectedDob = s.birthDate; + _selectedStatus = s.status; + } + } + + @override + void dispose() { + _lrnController.dispose(); + _firstNameController.dispose(); + _middleNameController.dispose(); + _lastNameController.dispose(); + _extController.dispose(); + super.dispose(); + } + + // ---------------------------------------------------------------- + // VALIDATION HELPERS + // ---------------------------------------------------------------- + String? _validateLRN(String? value) { + if (value == null || value.trim().isEmpty) return 'LRN is required.'; + if (!RegExp(r'^\d{12}$').hasMatch(value.trim())) { + return 'LRN must be exactly 12 digits (numbers only).'; + } + return null; + } + + String? _validateRequired(String? value, String fieldName) { + if (value == null || value.trim().isEmpty) return '$fieldName is required.'; + if (value.trim().length < 2) return '$fieldName must be at least 2 characters.'; + return null; + } + + Future _selectDate() async { + final picked = await showDatePicker( + context: context, + initialDate: _selectedDob ?? DateTime(2010), + firstDate: DateTime(1980), + lastDate: DateTime.now(), + builder: (ctx, child) => Theme( + data: Theme.of(ctx).copyWith( + colorScheme: const ColorScheme.light( + primary: AppColors.primaryGreen, + onPrimary: Colors.white, + onSurface: AppColors.textPrimary, + ), + ), + child: child!, + ), + ); + if (picked != null) setState(() => _selectedDob = picked); + } + + // ---------------------------------------------------------------- + // SUBMIT + // ---------------------------------------------------------------- + Future _handleSave() async { + setState(() => _errorMessage = null); + + // 1. Form validation + if (!_formKey.currentState!.validate()) return; + + // 2. DOB required check + if (_selectedDob == null) { + setState(() => _errorMessage = 'Please select a Date of Birth.'); + return; + } + + setState(() => _isLoading = true); + + try { + final notifier = ref.read(studentMutationProvider.notifier); + + if (widget.student == null) { + // ---- CREATE ---- + await notifier.createStudent( + lrn: _lrnController.text.trim(), + firstName: _firstNameController.text.trim(), + middleName: _middleNameController.text.trim().isEmpty + ? null + : _middleNameController.text.trim(), + lastName: _lastNameController.text.trim(), + extension: _extController.text.trim().isEmpty + ? null + : _extController.text.trim(), + sex: _selectedSex, + birthDate: _selectedDob!, + ); + } else { + // ---- UPDATE ---- + await notifier.updateStudent( + id: widget.student!.id, + lrn: _lrnController.text.trim(), + firstName: _firstNameController.text.trim(), + middleName: _middleNameController.text.trim().isEmpty + ? null + : _middleNameController.text.trim(), + lastName: _lastNameController.text.trim(), + extension: _extController.text.trim().isEmpty + ? null + : _extController.text.trim(), + sex: _selectedSex, + birthDate: _selectedDob!, + status: _selectedStatus, + ); + } + + if (!mounted) return; + Navigator.of(context).pop(true); + _showSuccessSnack(); + } catch (e) { + if (!mounted) return; + // Extract clean message from "Exception: ..." string + final raw = e.toString(); + final msg = raw.startsWith('Exception: ') ? raw.substring(11) : raw; + setState(() { + _isLoading = false; + _errorMessage = msg; + }); + } + } + + void _showSuccessSnack() { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + widget.student == null + ? 'Student added successfully!' + : 'Student updated successfully!', + ), + backgroundColor: AppColors.success, + ), + ); + } + + // ---------------------------------------------------------------- + // BUILD + // ---------------------------------------------------------------- + @override + Widget build(BuildContext context) { + final isEdit = widget.student != null; + + return Dialog( + backgroundColor: AppColors.surfaceWhite, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + ), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 620), + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Form( + key: _formKey, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ---- Header ---- + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + isEdit ? 'Update Student Record' : 'Add New Student', + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: AppColors.primaryGreen, + ), + ), + IconButton( + icon: const Icon(Icons.close, color: AppColors.textSecondary), + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + const Divider(height: 32), + + // ---- Error Banner ---- + if (_errorMessage != null) ...[ + _ErrorBanner(message: _errorMessage!), + const SizedBox(height: AppSizes.p16), + ], + + // ---- LRN ---- + TextFormField( + controller: _lrnController, + keyboardType: TextInputType.number, + maxLength: 12, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + validator: _validateLRN, + decoration: const InputDecoration( + labelText: 'LRN (Learner Reference Number)', + hintText: '12-digit number', + prefixIcon: Icon(Icons.pin_outlined), + counterText: '', + ), + ), + const SizedBox(height: AppSizes.p16), + + // ---- Name fields ---- + LayoutBuilder(builder: (ctx, c) { + final wide = c.maxWidth > 400; + if (wide) { + return Column(children: [ + Row(children: [ + Expanded( + child: TextFormField( + controller: _firstNameController, + validator: (v) => _validateRequired(v, 'First name'), + decoration: const InputDecoration( + labelText: 'First Name', + prefixIcon: Icon(Icons.badge_outlined), + ), + ), + ), + const SizedBox(width: AppSizes.p16), + Expanded( + child: TextFormField( + controller: _middleNameController, + decoration: const InputDecoration( + labelText: 'Middle Name (optional)', + prefixIcon: Icon(Icons.badge_outlined), + ), + ), + ), + ]), + const SizedBox(height: AppSizes.p16), + Row(children: [ + Expanded( + flex: 3, + child: TextFormField( + controller: _lastNameController, + validator: (v) => _validateRequired(v, 'Last name'), + decoration: const InputDecoration( + labelText: 'Last Name', + prefixIcon: Icon(Icons.badge_outlined), + ), + ), + ), + const SizedBox(width: AppSizes.p16), + Expanded( + flex: 1, + child: TextFormField( + controller: _extController, + decoration: const InputDecoration( + labelText: 'Ext.', + hintText: 'Jr / III', + prefixIcon: Icon(Icons.text_format), + ), + ), + ), + ]), + ]); + } else { + return Column(children: [ + TextFormField( + controller: _firstNameController, + validator: (v) => _validateRequired(v, 'First name'), + decoration: const InputDecoration(labelText: 'First Name'), + ), + const SizedBox(height: AppSizes.p12), + TextFormField( + controller: _middleNameController, + decoration: const InputDecoration(labelText: 'Middle Name'), + ), + const SizedBox(height: AppSizes.p12), + TextFormField( + controller: _lastNameController, + validator: (v) => _validateRequired(v, 'Last name'), + decoration: const InputDecoration(labelText: 'Last Name'), + ), + const SizedBox(height: AppSizes.p12), + TextFormField( + controller: _extController, + decoration: const InputDecoration(labelText: 'Extension (Jr / III)'), + ), + ]); + } + }), + const SizedBox(height: AppSizes.p16), + + // ---- Sex + DOB ---- + Row(children: [ + Expanded( + child: DropdownButtonFormField( + initialValue: _selectedSex, + validator: (v) => v == null ? 'Please select sex.' : null, + decoration: const InputDecoration( + labelText: 'Sex', + prefixIcon: Icon(Icons.wc), + ), + items: ['Male', 'Female'] + .map((s) => DropdownMenuItem(value: s, child: Text(s))) + .toList(), + onChanged: (v) => setState(() => _selectedSex = v!), + ), + ), + const SizedBox(width: AppSizes.p16), + Expanded( + child: GestureDetector( + onTap: _selectDate, + child: InputDecorator( + decoration: InputDecoration( + labelText: 'Date of Birth', + prefixIcon: const Icon(Icons.calendar_today, color: AppColors.textSecondary), + errorText: (_isLoading == false && _errorMessage != null && _selectedDob == null) + ? '' : null, + ), + child: Text( + _selectedDob == null + ? 'Select date…' + : '${_selectedDob!.year}-' + '${_selectedDob!.month.toString().padLeft(2, '0')}-' + '${_selectedDob!.day.toString().padLeft(2, '0')}', + style: TextStyle( + color: _selectedDob == null + ? AppColors.textMuted + : AppColors.textPrimary, + fontSize: 16, + ), + ), + ), + ), + ), + ]), + const SizedBox(height: AppSizes.p16), + + // ---- Status (edit only) ---- + if (isEdit) ...[ + DropdownButtonFormField( + initialValue: _selectedStatus, + decoration: const InputDecoration( + labelText: 'Status', + prefixIcon: Icon(Icons.info_outline), + ), + items: _statuses + .map((s) => DropdownMenuItem(value: s, child: Text(s))) + .toList(), + onChanged: (v) => setState(() => _selectedStatus = v!), + ), + const SizedBox(height: AppSizes.p16), + ], + + const SizedBox(height: AppSizes.p16), + + // ---- Actions ---- + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: _isLoading ? null : () => Navigator.of(context).pop(), + child: const Text( + 'CANCEL', + style: TextStyle( + color: AppColors.textSecondary, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(width: AppSizes.p16), + SizedBox( + width: 180, + child: PrimaryButton( + label: isEdit ? 'UPDATE RECORD' : 'SAVE STUDENT', + isLoading: _isLoading, + onPressed: _handleSave, + ), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ); + } +} + +/// A clean inline error banner +class _ErrorBanner extends StatelessWidget { + final String message; + const _ErrorBanner({required this.message}); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: AppColors.error.withValues(alpha: 0.08), + border: Border.all(color: AppColors.error.withValues(alpha: 0.4)), + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.error_outline, color: AppColors.error, size: 20), + const SizedBox(width: 8), + Expanded( + child: Text( + message, + style: const TextStyle( + color: AppColors.error, + fontSize: 14, + ), + ), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/users/users_screen.dart b/frontend/lib/ui/screens/users/users_screen.dart new file mode 100644 index 0000000..4e8153f --- /dev/null +++ b/frontend/lib/ui/screens/users/users_screen.dart @@ -0,0 +1,851 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/constants/app_colors.dart'; +import '../../../core/constants/app_sizes.dart'; +import '../../../domain/entities/system_user.dart'; +import '../../shared/inputs/custom_text_field.dart'; +import '../../shared/buttons/primary_button.dart'; +import '../../providers/users_provider.dart'; +import '../../providers/auth_provider.dart'; + +class UsersScreen extends ConsumerStatefulWidget { + const UsersScreen({super.key}); + + @override + ConsumerState createState() => _UsersScreenState(); +} + +class _UsersScreenState extends ConsumerState { + final TextEditingController _searchController = TextEditingController(); + String _searchQuery = ''; + String _roleFilter = 'all'; // 'all', 'super_admin', 'admin', 'teacher' + + @override + void initState() { + super.initState(); + _searchController.addListener(() { + setState(() => _searchQuery = _searchController.text.toLowerCase()); + }); + } + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + List _filter(List users) { + var result = users; + // Apply role filter first + if (_roleFilter != 'all') { + result = result.where((u) => u.role == _roleFilter).toList(); + } + // Then apply search filter + if (_searchQuery.isNotEmpty) { + result = result.where((u) => + u.username.toLowerCase().contains(_searchQuery) || + u.fullName.toLowerCase().contains(_searchQuery) || + u.role.toLowerCase().contains(_searchQuery) + ).toList(); + } + return result; + } + + Future _handleRefresh() async { + await ref.read(usersProvider.notifier).refresh(); + } + + Future _confirmResetPassword(SystemUser user) async { + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusLarge)), + title: const Row(children: [ + Icon(Icons.lock_reset, color: Colors.orange), + SizedBox(width: 8), + Text('Reset Password'), + ]), + content: Text( + 'Reset the password for "${user.username}"?\n\nTheir new password will be: changeme123', + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('CANCEL')), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: Colors.orange, foregroundColor: Colors.white), + onPressed: () => Navigator.pop(ctx, true), + child: const Text('RESET'), + ), + ], + ), + ); + if (confirmed != true || !mounted) return; + + try { + await ref.read(usersProvider.notifier).resetPassword(user.id); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Password for "${user.username}" reset to "changeme123".'), backgroundColor: AppColors.success), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: $e'), backgroundColor: Colors.red), + ); + } + } + + Future _confirmDelete(SystemUser user) async { + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusLarge)), + title: const Row(children: [ + Icon(Icons.delete_outline, color: Colors.red), + SizedBox(width: 8), + Text('Delete User'), + ]), + content: Text('Are you sure you want to permanently delete "${user.username}"? This action cannot be undone.'), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('CANCEL')), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: Colors.red, foregroundColor: Colors.white), + onPressed: () => Navigator.pop(ctx, true), + child: const Text('DELETE'), + ), + ], + ), + ); + if (confirmed != true || !mounted) return; + + try { + await ref.read(usersProvider.notifier).deleteUser(user.id); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('User "${user.username}" deleted.'), backgroundColor: AppColors.success), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: $e'), backgroundColor: Colors.red), + ); + } + } + + void _openModal({SystemUser? user}) { + showDialog( + context: context, + builder: (ctx) => AddEditUserModal(user: user), + ); + } + + @override + Widget build(BuildContext context) { + final usersAsync = ref.watch(usersProvider); + + return Scaffold( + backgroundColor: Colors.transparent, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeader(context), + const SizedBox(height: AppSizes.p16), + // Reset requests panel (super_admin only) + _buildResetRequestsPanel(), + const SizedBox(height: AppSizes.p8), + Expanded( + child: usersAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (err, _) => Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.error_outline, color: Colors.red, size: 48), + const SizedBox(height: 16), + Text('$err', style: const TextStyle(color: Colors.red)), + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: _handleRefresh, + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + ), + ], + ), + ), + data: (users) { + final filtered = _filter(users); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Role filter chips + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + _buildFilterChip('All', 'all', users.length, Colors.grey), + const SizedBox(width: 8), + _buildFilterChip('Super Admin', 'super_admin', + users.where((u) => u.role == 'super_admin').length, Colors.purple), + const SizedBox(width: 8), + _buildFilterChip('Admin', 'admin', + users.where((u) => u.role == 'admin').length, Colors.blue), + const SizedBox(width: 8), + _buildFilterChip('Teacher', 'teacher', + users.where((u) => u.role == 'teacher').length, AppColors.primaryGreen), + ], + ), + ), + const SizedBox(height: AppSizes.p16), + Expanded( + child: RefreshIndicator( + onRefresh: _handleRefresh, + child: LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth > 800) { + return _buildDesktopTable(filtered); + } else { + return _buildMobileList(filtered); + } + }, + ), + ), + ), + ], + ); + }, + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildResetRequestsPanel() { + final requestsAsync = ref.watch(resetRequestsProvider); + final currentUser = ref.watch(authProvider).value; + if (currentUser?.role != 'super_admin') return const SizedBox.shrink(); + + return requestsAsync.when( + loading: () => const SizedBox.shrink(), + error: (_, __) => const SizedBox.shrink(), + data: (requests) { + if (requests.isEmpty) return const SizedBox.shrink(); + return Container( + margin: const EdgeInsets.only(bottom: AppSizes.p8), + decoration: BoxDecoration( + color: Colors.orange.shade50, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + border: Border.all(color: Colors.orange.shade200), + ), + child: ExpansionTile( + leading: const Icon(Icons.lock_clock, color: Colors.orange), + title: Text( + '${requests.length} Pending Password Reset Request${requests.length > 1 ? 's' : ''}', + style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.orange), + ), + children: requests.map((req) { + return ListTile( + title: Text('${req['first_name']} ${req['last_name']} (@${req['username']})'), + subtitle: Text('Role: ${(req['role'] as String).toUpperCase().replaceAll('_', ' ')} • Requested: ${(req['requested_at'] as String).split('T').first}'), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + TextButton.icon( + icon: const Icon(Icons.check_circle, color: AppColors.success), + label: const Text('Approve', style: TextStyle(color: AppColors.success)), + onPressed: () async { + try { + final repo = ref.read(authRepositoryProvider); + await repo.approveResetRequest(req['id'] as int); + ref.invalidate(resetRequestsProvider); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Password reset approved.'), backgroundColor: AppColors.success, + )); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e'), backgroundColor: Colors.red)); + } + }, + ), + TextButton.icon( + icon: const Icon(Icons.cancel, color: Colors.red), + label: const Text('Reject', style: TextStyle(color: Colors.red)), + onPressed: () async { + try { + final repo = ref.read(authRepositoryProvider); + await repo.rejectResetRequest(req['id'] as int); + ref.invalidate(resetRequestsProvider); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Request rejected.'), backgroundColor: Colors.grey, + )); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e'), backgroundColor: Colors.red)); + } + }, + ), + ], + ), + ); + }).toList(), + ), + ); + }, + ); + } + + Widget _buildHeader(BuildContext context) { + final isDesktop = MediaQuery.of(context).size.width > 800; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('User Management', + style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: AppColors.textPrimary)), + const SizedBox(height: 4), + const Text('Manage system accounts and access roles.', + style: TextStyle(fontSize: 14, color: AppColors.textSecondary)), + const SizedBox(height: AppSizes.p16), + Row( + children: [ + Expanded( + flex: 2, + child: CustomTextField( + hintText: 'Search by username, name or role...', + prefixIcon: Icons.search, + controller: _searchController, + ), + ), + const SizedBox(width: AppSizes.p16), + SizedBox( + width: isDesktop ? 180 : 50, + child: isDesktop + ? PrimaryButton(label: '+ NEW USER', onPressed: () => _openModal()) + : ElevatedButton( + onPressed: () => _openModal(), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primaryGreen, + foregroundColor: Colors.white, + padding: const EdgeInsets.all(14), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusMedium)), + ), + child: const Icon(Icons.add), + ), + ), + ], + ), + ], + ); + } + + Widget _buildFilterChip(String label, String filterKey, int count, Color color) { + final isActive = _roleFilter == filterKey; + return GestureDetector( + onTap: () => setState(() => _roleFilter = filterKey), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7), + decoration: BoxDecoration( + color: isActive ? color : color.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(20), + border: Border.all(color: isActive ? color : color.withValues(alpha: 0.3), width: isActive ? 2 : 1), + boxShadow: isActive ? [BoxShadow(color: color.withValues(alpha: 0.3), blurRadius: 6, offset: const Offset(0, 2))] : [], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isActive) ...[ + Icon(Icons.check, color: Colors.white, size: 13), + const SizedBox(width: 4), + ], + Text( + '$label ($count)', + style: TextStyle( + color: isActive ? Colors.white : color, + fontWeight: FontWeight.w700, + fontSize: 12, + ), + ), + ], + ), + ), + ); + } + + Widget _buildDesktopTable(List users) { + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 10, offset: const Offset(0, 4))], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + child: SingleChildScrollView( + child: DataTable( + headingRowColor: WidgetStateProperty.all(AppColors.primaryGreen.withValues(alpha: 0.05)), + columnSpacing: 24, + columns: const [ + DataColumn(label: Text('User', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Username', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Access Role', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Contact', style: TextStyle(fontWeight: FontWeight.bold))), + DataColumn(label: Text('Actions', style: TextStyle(fontWeight: FontWeight.bold))), + ], + rows: users.isEmpty + ? [const DataRow(cells: [ + DataCell(Text('No users found.')), DataCell(Text('')), + DataCell(Text('')), DataCell(Text('')), DataCell(Text('')), + ])] + : users.map((user) => DataRow(cells: [ + DataCell(Row(children: [ + CircleAvatar( + radius: 16, + backgroundColor: _roleColor(user.role).withValues(alpha: 0.15), + child: Text(user.initials, style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold, color: _roleColor(user.role))), + ), + const SizedBox(width: 10), + Text(user.fullName, style: const TextStyle(fontWeight: FontWeight.w600)), + ])), + DataCell(Text('@${user.username}', style: const TextStyle(color: AppColors.textSecondary))), + DataCell(_buildRoleChip(user.role)), + DataCell(Text(user.email ?? user.phone ?? '—', style: const TextStyle(color: AppColors.textSecondary, fontSize: 13))), + DataCell(_buildActions(user)), + ])).toList(), + ), + ), + ), + ); + } + + Widget _buildMobileList(List users) { + if (users.isEmpty) { + return const Center(child: Text('No users found.', style: TextStyle(color: AppColors.textSecondary))); + } + return ListView.separated( + itemCount: users.length, + separatorBuilder: (_, __) => const SizedBox(height: AppSizes.p12), + itemBuilder: (context, index) { + final user = users[index]; + return Container( + padding: const EdgeInsets.all(AppSizes.p16), + decoration: BoxDecoration( + color: AppColors.surfaceWhite, + borderRadius: BorderRadius.circular(AppSizes.radiusLarge), + boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 8)], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 20, + backgroundColor: _roleColor(user.role).withValues(alpha: 0.15), + child: Text(user.initials, style: TextStyle(fontWeight: FontWeight.bold, color: _roleColor(user.role))), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(user.fullName, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15)), + Text('@${user.username}', style: const TextStyle(color: AppColors.textSecondary, fontSize: 13)), + ], + ), + ), + _buildRoleChip(user.role), + ], + ), + if (user.email != null || user.phone != null) ...[ + const SizedBox(height: 8), + Text( + [if (user.email != null) user.email!, if (user.phone != null) user.phone!].join(' · '), + style: const TextStyle(fontSize: 12, color: AppColors.textSecondary), + ), + ], + const Divider(height: 20), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [_buildActions(user)], + ), + ], + ), + ); + }, + ); + } + + Widget _buildRoleChip(String role) { + final color = _roleColor(role); + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration(color: color.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(20)), + child: Text(role.toUpperCase().replaceAll('_', ' '), + style: TextStyle(color: color, fontWeight: FontWeight.bold, fontSize: 11)), + ); + } + + Color _roleColor(String role) { + if (role == 'super_admin') return Colors.purple; + if (role == 'admin') return Colors.blue; + return AppColors.primaryGreen; + } + + Widget _buildActions(SystemUser user) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.lock_reset, color: Colors.orange), + tooltip: 'Reset Password to "changeme123"', + onPressed: () => _confirmResetPassword(user), + ), + IconButton( + icon: const Icon(Icons.edit, color: AppColors.primaryGreen), + tooltip: 'Edit User', + onPressed: () => _openModal(user: user), + ), + if (user.role != 'super_admin') + IconButton( + icon: const Icon(Icons.delete_outline, color: Colors.red), + tooltip: 'Delete User', + onPressed: () => _confirmDelete(user), + ), + ], + ); + } +} + +// ============================================================ +// ADD / EDIT MODAL (moved inline for clean imports) +// ============================================================ +class AddEditUserModal extends ConsumerStatefulWidget { + final SystemUser? user; + const AddEditUserModal({super.key, this.user}); + + @override + ConsumerState createState() => _AddEditUserModalState(); +} + +class _AddEditUserModalState extends ConsumerState { + final _formKey = GlobalKey(); + late TextEditingController _usernameCtrl; + late TextEditingController _firstNameCtrl; + late TextEditingController _middleNameCtrl; + late TextEditingController _lastNameCtrl; + late TextEditingController _extCtrl; + late TextEditingController _emailCtrl; + late TextEditingController _phoneCtrl; + String _selectedRole = 'teacher'; + bool _isLoading = false; + + bool get _isEdit => widget.user != null; + + @override + void initState() { + super.initState(); + final u = widget.user; + _usernameCtrl = TextEditingController(text: u?.username ?? ''); + _firstNameCtrl = TextEditingController(text: u?.firstName ?? ''); + _middleNameCtrl = TextEditingController(text: u?.middleName ?? ''); + _lastNameCtrl = TextEditingController(text: u?.lastName ?? ''); + _extCtrl = TextEditingController(text: u?.extension ?? ''); + _emailCtrl = TextEditingController(text: u?.email ?? ''); + _phoneCtrl = TextEditingController(text: u?.phone ?? ''); + if (u != null) _selectedRole = u.role; + } + + @override + void dispose() { + for (final c in [_usernameCtrl, _firstNameCtrl, _middleNameCtrl, _lastNameCtrl, _extCtrl, _emailCtrl, _phoneCtrl]) { + c.dispose(); + } + super.dispose(); + } + + Future _handleSave() async { + if (!_formKey.currentState!.validate()) return; + setState(() => _isLoading = true); + + try { + final notifier = ref.read(usersProvider.notifier); + if (_isEdit) { + await notifier.updateUser( + id: widget.user!.id, + firstName: _firstNameCtrl.text.trim(), + middleName: _middleNameCtrl.text.trim(), + lastName: _lastNameCtrl.text.trim(), + extension: _extCtrl.text.trim(), + role: _selectedRole, + email: _emailCtrl.text.trim(), + phone: _phoneCtrl.text.trim(), + ); + if (!mounted) return; + Navigator.of(context).pop(); + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('User updated successfully!'), + backgroundColor: AppColors.success, + )); + } else { + // Create — backend auto-generates a temporary password + final username = _usernameCtrl.text.trim(); + final tempPassword = await notifier.createUser( + username: username, + firstName: _firstNameCtrl.text.trim(), + middleName: _middleNameCtrl.text.trim(), + lastName: _lastNameCtrl.text.trim(), + extension: _extCtrl.text.trim(), + role: _selectedRole, + email: _emailCtrl.text.trim(), + phone: _phoneCtrl.text.trim(), + ); + if (!mounted) return; + // Close create modal first + Navigator.of(context).pop(); + // Show one-time credentials dialog + _showCredentialsDialog(context, username: username, tempPassword: tempPassword); + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('Error: ${e.toString().replaceAll('Exception: ', '')}'), + backgroundColor: Colors.red, + )); + } finally { + if (mounted) setState(() => _isLoading = false); + } + } + + void _showCredentialsDialog(BuildContext ctx, {required String username, required String tempPassword}) { + bool copied = false; + showDialog( + context: ctx, + barrierDismissible: false, // Must explicitly dismiss + builder: (dialogCtx) => StatefulBuilder( + builder: (dialogCtx, setDialogState) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusLarge)), + icon: const Icon(Icons.check_circle, color: AppColors.success, size: 48), + title: const Text('User Created!', textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.bold)), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '⚠️ Copy and share these credentials now. The temporary password will not be shown again.', + style: TextStyle(fontSize: 13, color: Colors.orange, fontWeight: FontWeight.w600), + textAlign: TextAlign.center, + ), + const SizedBox(height: 20), + _credentialRow('Username', username), + const SizedBox(height: 10), + _credentialRow('Temp. Password', tempPassword, highlight: true), + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + icon: Icon(copied ? Icons.check : Icons.copy, size: 18), + label: Text(copied ? 'Copied!' : 'Copy Credentials'), + style: OutlinedButton.styleFrom( + foregroundColor: copied ? AppColors.success : AppColors.primaryGreen, + side: BorderSide(color: copied ? AppColors.success : AppColors.primaryGreen), + ), + onPressed: () { + Clipboard.setData(ClipboardData( + text: 'Username: $username\nTemporary Password: $tempPassword', + )); + setDialogState(() => copied = true); + }, + ), + ), + ], + ), + actions: [ + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: AppColors.primaryGreen, foregroundColor: Colors.white), + onPressed: () => Navigator.of(dialogCtx).pop(), + child: const Text('DONE'), + ), + ], + ), + ), + ); + } + + Widget _credentialRow(String label, String value, {bool highlight = false}) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: highlight ? AppColors.primaryGreen.withValues(alpha: 0.07) : Colors.grey.shade50, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: highlight ? AppColors.primaryGreen.withValues(alpha: 0.3) : Colors.grey.shade200), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: const TextStyle(fontSize: 11, color: Colors.grey, fontWeight: FontWeight.w500)), + const SizedBox(height: 2), + Text(value, style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold, color: highlight ? AppColors.primaryGreen : AppColors.textPrimary, letterSpacing: 0.5)), + ], + ), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return Dialog( + backgroundColor: AppColors.surfaceWhite, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppSizes.radiusLarge)), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 560), + child: Padding( + padding: const EdgeInsets.all(AppSizes.p24), + child: Form( + key: _formKey, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row(children: [ + Icon(_isEdit ? Icons.edit : Icons.person_add, color: AppColors.primaryGreen), + const SizedBox(width: 8), + Text( + _isEdit ? 'Edit System User' : 'Create New User', + style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: AppColors.textPrimary), + ), + ]), + IconButton(icon: const Icon(Icons.close), onPressed: () => Navigator.of(context).pop()), + ], + ), + const Divider(height: 28), + + // Name row + Row(children: [ + Expanded(child: _field('First Name', Icons.badge_outlined, _firstNameCtrl, required: true)), + const SizedBox(width: 12), + Expanded(child: _field('Middle Name', Icons.badge_outlined, _middleNameCtrl)), + ]), + const SizedBox(height: AppSizes.p12), + Row(children: [ + Expanded(flex: 3, child: _field('Last Name', Icons.badge_outlined, _lastNameCtrl, required: true)), + const SizedBox(width: 12), + Expanded(flex: 1, child: _field('Ext.', Icons.text_format, _extCtrl)), + ]), + const SizedBox(height: AppSizes.p12), + + // Username (locked on edit) + _field('Username', Icons.person_outline, _usernameCtrl, required: !_isEdit, readOnly: _isEdit), + const SizedBox(height: AppSizes.p12), + + // Role dropdown — locked for super_admin + if (_isEdit && widget.user?.role == 'super_admin') + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14), + decoration: BoxDecoration( + color: Colors.grey.shade100, + borderRadius: BorderRadius.circular(AppSizes.radiusMedium), + border: Border.all(color: Colors.grey.shade300), + ), + child: const Row(children: [ + Icon(Icons.shield, color: Colors.purple, size: 20), + SizedBox(width: 12), + Text('Super Admin', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.purple)), + SizedBox(width: 8), + Icon(Icons.lock, color: Colors.grey, size: 14), + SizedBox(width: 4), + Text('(Role cannot be changed)', style: TextStyle(fontSize: 12, color: Colors.grey)), + ]), + ) + else + DropdownButtonFormField( + value: _selectedRole, + decoration: const InputDecoration(prefixIcon: Icon(Icons.shield_outlined, color: AppColors.textSecondary)), + items: const [ + DropdownMenuItem(value: 'teacher', child: Text('Teacher')), + DropdownMenuItem(value: 'admin', child: Text('Admin')), + ], + onChanged: (val) => setState(() => _selectedRole = val!), + ), + const SizedBox(height: AppSizes.p12), + + // Email & Phone + Row(children: [ + Expanded(child: _field('Email', Icons.email_outlined, _emailCtrl)), + const SizedBox(width: 12), + Expanded(child: _field('Phone', Icons.phone_outlined, _phoneCtrl)), + ]), + const SizedBox(height: AppSizes.p12), + + // Auto-generate notice (create only) + if (!_isEdit) + Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: AppColors.primaryGreen.withValues(alpha: 0.07), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: AppColors.primaryGreen.withValues(alpha: 0.3)), + ), + child: const Row(children: [ + Icon(Icons.auto_awesome, color: AppColors.primaryGreen, size: 16), + SizedBox(width: 8), + Expanded( + child: Text( + 'A secure temporary password will be auto-generated and shown once after creation.', + style: TextStyle(fontSize: 12, color: AppColors.primaryGreen, fontWeight: FontWeight.w600), + ), + ), + ]), + ), + + const SizedBox(height: AppSizes.p12), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('CANCEL')), + const SizedBox(width: AppSizes.p16), + SizedBox( + width: 150, + child: PrimaryButton( + label: _isEdit ? 'UPDATE' : 'CREATE', + isLoading: _isLoading, + onPressed: _handleSave, + ), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ); + } + + Widget _field(String hint, IconData icon, TextEditingController ctrl, {bool required = false, bool readOnly = false}) { + return CustomTextField( + hintText: hint, + prefixIcon: icon, + controller: ctrl, + readOnly: readOnly, + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/screens/users/widgets/add_edit_user_modal.dart b/frontend/lib/ui/screens/users/widgets/add_edit_user_modal.dart new file mode 100644 index 0000000..980acdb --- /dev/null +++ b/frontend/lib/ui/screens/users/widgets/add_edit_user_modal.dart @@ -0,0 +1,3 @@ +// This file is kept for backward compatibility. +// The AddEditUserModal is now defined in users_screen.dart. +export '../users_screen.dart' show AddEditUserModal; \ No newline at end of file diff --git a/frontend/lib/ui/shared/buttons/primary_button.dart b/frontend/lib/ui/shared/buttons/primary_button.dart new file mode 100644 index 0000000..7d8103a --- /dev/null +++ b/frontend/lib/ui/shared/buttons/primary_button.dart @@ -0,0 +1,50 @@ +import 'package:flutter/material.dart'; + +class PrimaryButton extends StatelessWidget { + final String label; + final VoidCallback onPressed; + final bool isLoading; + + const PrimaryButton({ + super.key, + required this.label, + required this.onPressed, + this.isLoading = false, + }); + + @override + Widget build(BuildContext context) { + return SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: isLoading ? null : onPressed, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF1C8248), // Primary Green + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8.0), + ), + elevation: 0, + ), + child: isLoading + ? const SizedBox( + height: 24, + width: 24, + child: CircularProgressIndicator( + color: Colors.white, + strokeWidth: 2.5, + ), + ) + : Text( + label, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + letterSpacing: 0.5, + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/shared/cards/stat_card.dart b/frontend/lib/ui/shared/cards/stat_card.dart new file mode 100644 index 0000000..d3f3781 --- /dev/null +++ b/frontend/lib/ui/shared/cards/stat_card.dart @@ -0,0 +1,85 @@ +import 'package:flutter/material.dart'; + +class StatCard extends StatelessWidget { + final String title; + final String value; + final IconData icon; + final Color? iconColor; + + const StatCard({ + super.key, + required this.title, + required this.value, + required this.icon, + this.iconColor, + }); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(20.0), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12.0), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: Row( + children: [ + // Icon Container + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: (iconColor ?? const Color(0xFF1C8248)).withOpacity(0.1), + borderRadius: BorderRadius.circular(10), + ), + child: Icon( + icon, + size: 28, + color: iconColor ?? const Color(0xFF1C8248), + ), + ), + const SizedBox(width: 16), + // Text Details + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + title, + maxLines: 1, // Prevent title from wrapping to two lines + overflow: TextOverflow.ellipsis, // Add '...' if title is too long + style: TextStyle( + fontSize: 14, + color: Colors.grey.shade600, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 4), + // FittedBox shrinks the text dynamically if the number gets too massive + FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: Text( + value, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + ), + ), + ], + ), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/ui/shared/inputs/custom_text_field.dart b/frontend/lib/ui/shared/inputs/custom_text_field.dart new file mode 100644 index 0000000..92f882c --- /dev/null +++ b/frontend/lib/ui/shared/inputs/custom_text_field.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; + +class CustomTextField extends StatelessWidget { + final String hintText; + final IconData prefixIcon; + final bool isPassword; + final bool obscureText; + final VoidCallback? onToggleVisibility; + final TextEditingController? controller; + final bool readOnly; + final void Function(String)? onChanged; + final String? Function(String?)? validator; + final int? maxLines; + final TextInputType? keyboardType; + + const CustomTextField({ + super.key, + required this.hintText, + required this.prefixIcon, + this.isPassword = false, + this.obscureText = false, + this.onToggleVisibility, + this.controller, + this.readOnly = false, + this.onChanged, + this.validator, + this.maxLines = 1, + this.keyboardType, + }); + + @override + Widget build(BuildContext context) { + return TextFormField( + controller: controller, + obscureText: obscureText, + readOnly: readOnly, + onChanged: onChanged, + validator: validator, + maxLines: maxLines, + keyboardType: keyboardType, + decoration: InputDecoration( + hintText: hintText, + prefixIcon: Icon(prefixIcon, color: Colors.grey.shade600), + border: const OutlineInputBorder(), + // Suffix icon only shows if it's a password field + suffixIcon: isPassword + ? IconButton( + icon: Icon( + obscureText ? Icons.visibility_off : Icons.visibility, + color: Colors.grey.shade600, + ), + onPressed: onToggleVisibility, + ) + : null, + ), + ); + } +} \ No newline at end of file diff --git a/frontend/pubspec.lock b/frontend/pubspec.lock new file mode 100644 index 0000000..d8bddee --- /dev/null +++ b/frontend/pubspec.lock @@ -0,0 +1,946 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d" + url: "https://pub.dev" + source: hosted + version: "93.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b + url: "https://pub.dev" + source: hosted + version: "10.0.1" + ansicolor: + dependency: transitive + description: + name: ansicolor + sha256: "50e982d500bc863e1d703448afdbf9e5a72eb48840a4f766fa361ffd6877055f" + url: "https://pub.dev" + source: hosted + version: "2.0.3" + archive: + dependency: transitive + description: + name: archive + sha256: cb6a278ef2dbb298455e1a713bda08524a175630ec643a242c399c932a0a1f7d + url: "https://pub.dev" + source: hosted + version: "3.6.1" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + change_app_package_name: + dependency: "direct dev" + description: + name: change_app_package_name + sha256: "8e43b754fe960426904d77ed4c62fa8c9834deaf6e293ae40963fa447482c4c5" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_config: + dependency: transitive + description: + name: cli_config + sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec + url: "https://pub.dev" + source: hosted + version: "0.2.0" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + coverage: + dependency: transitive + description: + name: coverage + sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d" + url: "https://pub.dev" + source: hosted + version: "1.15.0" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + dbus: + dependency: transitive + description: + name: dbus + sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 + url: "https://pub.dev" + source: hosted + version: "0.7.12" + dio: + dependency: "direct main" + description: + name: dio + sha256: aff32c08f92787a557dd5c0145ac91536481831a01b4648136373cddb0e64f8c + url: "https://pub.dev" + source: hosted + version: "5.9.2" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "2f9e64323a7c3c7ef69567d5c800424a11f8337b8b228bad02524c9fb3c1f340" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + equatable: + dependency: transitive + description: + name: equatable + sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b" + url: "https://pub.dev" + source: hosted + version: "2.0.8" + excel: + dependency: "direct main" + description: + name: excel + sha256: "1a15327dcad260d5db21d1f6e04f04838109b39a2f6a84ea486ceda36e468780" + url: "https://pub.dev" + source: hosted + version: "4.0.6" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: f13a03000d942e476bc1ff0a736d2e9de711d2f89a95cd4c1d88f861c3348387 + url: "https://pub.dev" + source: hosted + version: "11.0.2" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7" + url: "https://pub.dev" + source: hosted + version: "0.14.4" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_native_splash: + dependency: "direct main" + description: + name: flutter_native_splash + sha256: "7062602e0dbd29141fb8eb19220b5871ca650be5197ab9c1f193a28b17537bc7" + url: "https://pub.dev" + source: hosted + version: "2.4.4" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" + url: "https://pub.dev" + source: hosted + version: "2.0.34" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "4e166be88e1dbbaa34a280bdb744aeae73b7ef25fdf8db7a3bb776760a3648e2" + url: "https://pub.dev" + source: hosted + version: "3.3.1" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: "8b302d17096ba88f911b7eb317c71d5e691da60a259549f42b38c658d1776d87" + url: "https://pub.dev" + source: hosted + version: "10.1.0" + flutter_secure_storage_darwin: + dependency: transitive + description: + name: flutter_secure_storage_darwin + sha256: "3af15a3cb2bf5b8b776832bd01776f8018766aece55623176e28b406481fb320" + url: "https://pub.dev" + source: hosted + version: "0.3.0" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: "2b5c76dce569ab752d55a1cee6a2242bcc11fdba927078fb88c503f150767cda" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: "8ceea1223bee3c6ac1a22dabd8feefc550e4729b3675de4b5900f55afcb435d6" + url: "https://pub.dev" + source: hosted + version: "2.0.1" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + google_fonts: + dependency: "direct main" + description: + name: google_fonts + sha256: "4e9391085e524954a51e3625b7c9c7e9851dc3f376603208bb45c24b9a66255d" + url: "https://pub.dev" + source: hosted + version: "8.1.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: "025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e" + url: "https://pub.dev" + source: hosted + version: "1.0.3" + html: + dependency: transitive + description: + name: html + sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602" + url: "https://pub.dev" + source: hosted + version: "0.15.6" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: f31d52537dc417fdcde36088fdf11d191026fd5e4fae742491ebd40e5a8bea7d + url: "https://pub.dev" + source: hosted + version: "4.3.0" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + jni: + dependency: transitive + description: + name: jni + sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f + url: "https://pub.dev" + source: hosted + version: "1.0.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: cb09e7dac6210041fad964ed7fbee004f14258b4eca4040f72d1234062ace4c8 + url: "https://pub.dev" + source: hosted + version: "4.11.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "6ba77bb18063eebe9de401f5e6437e95e1438af0a87a3a39084fbd37c90df572" + url: "https://pub.dev" + source: hosted + version: "0.17.6" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + url: "https://pub.dev" + source: hosted + version: "9.3.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + permission_handler: + dependency: "direct main" + description: + name: permission_handler + sha256: bc917da36261b00137bbc8896bf1482169cd76f866282368948f032c8c1caae1 + url: "https://pub.dev" + source: hosted + version: "12.0.1" + permission_handler_android: + dependency: transitive + description: + name: permission_handler_android + sha256: "1e3bc410ca1bf84662104b100eb126e066cb55791b7451307f9708d4007350e6" + url: "https://pub.dev" + source: hosted + version: "13.0.1" + permission_handler_apple: + dependency: transitive + description: + name: permission_handler_apple + sha256: f000131e755c54cf4d84a5d8bd6e4149e262cc31c5a8b1d698de1ac85fa41023 + url: "https://pub.dev" + source: hosted + version: "9.4.7" + permission_handler_html: + dependency: transitive + description: + name: permission_handler_html + sha256: "38f000e83355abb3392140f6bc3030660cfaef189e1f87824facb76300b4ff24" + url: "https://pub.dev" + source: hosted + version: "0.1.3+5" + permission_handler_platform_interface: + dependency: transitive + description: + name: permission_handler_platform_interface + sha256: eb99b295153abce5d683cac8c02e22faab63e50679b937fa1bf67d58bb282878 + url: "https://pub.dev" + source: hosted + version: "4.3.0" + permission_handler_windows: + dependency: transitive + description: + name: permission_handler_windows + sha256: "1a790728016f79a41216d88672dbc5df30e686e811ad4e698bfc51f76ad91f1e" + url: "https://pub.dev" + source: hosted + version: "0.2.1" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + url: "https://pub.dev" + source: hosted + version: "1.5.2" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "8c22216be8ad3ef2b44af3a329693558c98eca7b8bd4ef495c92db0bba279f83" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 + url: "https://pub.dev" + source: hosted + version: "1.1.3" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b + url: "https://pub.dev" + source: hosted + version: "2.1.2" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812" + url: "https://pub.dev" + source: hosted + version: "0.10.13" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test: + dependency: transitive + description: + name: test + sha256: "280d6d890011ca966ad08df7e8a4ddfab0fb3aa49f96ed6de56e3521347a9ae7" + url: "https://pub.dev" + source: hosted + version: "1.30.0" + test_api: + dependency: transitive + description: + name: test_api + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + url: "https://pub.dev" + source: hosted + version: "0.7.10" + test_core: + dependency: transitive + description: + name: test_core + sha256: "0381bd1585d1a924763c308100f2138205252fb90c9d4eeaf28489ee65ccde51" + url: "https://pub.dev" + source: hosted + version: "0.6.16" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + universal_io: + dependency: transitive + description: + name: universal_io + sha256: f63cbc48103236abf48e345e07a03ce5757ea86285ed313a6a032596ed9301e2 + url: "https://pub.dev" + source: hosted + version: "2.3.1" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.11.5 <4.0.0" + flutter: ">=3.38.4" diff --git a/frontend/pubspec.yaml b/frontend/pubspec.yaml new file mode 100644 index 0000000..a4fcd28 --- /dev/null +++ b/frontend/pubspec.yaml @@ -0,0 +1,118 @@ +name: frontend +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.11.5 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + flutter_native_splash: 2.4.4 + flutter_riverpod: ^3.3.1 + dio: ^5.9.2 + flutter_secure_storage: ^10.1.0 + google_fonts: ^8.1.0 + excel: ^4.0.6 + path_provider: ^2.1.5 + file_picker: ^11.0.2 + permission_handler: ^12.0.1 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_launcher_icons: ^0.14.4 + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + change_app_package_name: ^1.5.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + assets: + - assets/images/logo.png + - assets/templates/School-Form-10-JHS.xlsx + - assets/templates/SSHS-SF-10-v2026_corrected.xlsx + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package + +flutter_launcher_icons: + android: true + ios: false # Set to true only if you plan to support iOS later + windows: + generate: true + image_path: "assets/images/logo.png" + icon_size: 256 # Standard optimal size for Windows .ico + image_path: "assets/images/logo.png" + min_sdk_android: 21 # Ensures compatibility with older Android devices + +flutter_native_splash: + color: "#F9F9F9" # Off-white page background + image: "assets/images/logo.png" + android_12: + image: "assets/images/logo.png" + icon_background_color: "#F9F9F9" diff --git a/frontend/test/widget_test.dart b/frontend/test/widget_test.dart new file mode 100644 index 0000000..157176f --- /dev/null +++ b/frontend/test/widget_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// Use a relative import to reliably find your main.dart file +import '../lib/main.dart'; + +void main() { + testWidgets('App boots up and displays the Splash Screen', (WidgetTester tester) async { + // 1. Build our app and trigger a frame. + await tester.pumpWidget(const TisRmsApp()); + + // 2. Verify that our branding text is present on the Splash Screen + expect(find.text('TIS RMS'), findsOneWidget); + expect(find.text('Record Management System'), findsOneWidget); + + // 3. Verify that the loading spinner is present + expect(find.byType(CircularProgressIndicator), findsOneWidget); + + // Note: We don't pump the timer here because the test environment + // shouldn't wait for the 2.5 second simulated delay. We just want + // to ensure the initial widget tree renders without crashing. + }); +} \ No newline at end of file diff --git a/frontend/windows/.gitignore b/frontend/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/frontend/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/frontend/windows/CMakeLists.txt b/frontend/windows/CMakeLists.txt new file mode 100644 index 0000000..c826e18 --- /dev/null +++ b/frontend/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(frontend LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "frontend") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/frontend/windows/flutter/CMakeLists.txt b/frontend/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/frontend/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/frontend/windows/flutter/generated_plugin_registrant.cc b/frontend/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8883006 --- /dev/null +++ b/frontend/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterSecureStorageWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); + PermissionHandlerWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); +} diff --git a/frontend/windows/flutter/generated_plugin_registrant.h b/frontend/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/frontend/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/frontend/windows/flutter/generated_plugins.cmake b/frontend/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..d1aac24 --- /dev/null +++ b/frontend/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_windows + permission_handler_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/frontend/windows/runner/CMakeLists.txt b/frontend/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/frontend/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/frontend/windows/runner/Runner.rc b/frontend/windows/runner/Runner.rc new file mode 100644 index 0000000..5f107b0 --- /dev/null +++ b/frontend/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "TeamSB", "TIS Academic Institution" "\0" + VALUE "FileDescription", "TIS Record Management System" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "tis_rms" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "tis_rms.exe" "\0" + VALUE "ProductName", "TIS RMS" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/frontend/windows/runner/flutter_window.cpp b/frontend/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/frontend/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/frontend/windows/runner/flutter_window.h b/frontend/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/frontend/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/frontend/windows/runner/main.cpp b/frontend/windows/runner/main.cpp new file mode 100644 index 0000000..8aff516 --- /dev/null +++ b/frontend/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"TIS Record Management System", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/frontend/windows/runner/resource.h b/frontend/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/frontend/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/frontend/windows/runner/resources/app_icon.ico b/frontend/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..50e6ae7 Binary files /dev/null and b/frontend/windows/runner/resources/app_icon.ico differ diff --git a/frontend/windows/runner/runner.exe.manifest b/frontend/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/frontend/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/frontend/windows/runner/utils.cpp b/frontend/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/frontend/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/frontend/windows/runner/utils.h b/frontend/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/frontend/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/frontend/windows/runner/win32_window.cpp b/frontend/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/frontend/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/frontend/windows/runner/win32_window.h b/frontend/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/frontend/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_