feat(admin): connect admin pages to live APIs and expand content tooling
Wire team, user, persona, FAQ, and ratings flows to backend endpoints; rebuild profile and user detail views with learning activity and subscriptions; fetch Vimeo lesson duration on module cards; add shared filters, permissions helpers, and notification UX improvements. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
035d73889e
commit
2966bdb180
174
package-lock.json
generated
174
package-lock.json
generated
|
|
@ -29,6 +29,7 @@
|
||||||
"resend": "^6.12.3",
|
"resend": "^6.12.3",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.4.0",
|
"tailwind-merge": "^3.4.0",
|
||||||
|
"tus-js-client": "^4.3.1",
|
||||||
"zustand": "^5.0.9"
|
"zustand": "^5.0.9"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
@ -3403,6 +3404,12 @@
|
||||||
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"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/call-bind-apply-helpers": {
|
"node_modules/call-bind-apply-helpers": {
|
||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||||
|
|
@ -3553,6 +3560,15 @@
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/combine-errors": {
|
||||||
|
"version": "3.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/combine-errors/-/combine-errors-3.0.3.tgz",
|
||||||
|
"integrity": "sha512-C8ikRNRMygCwaTx+Ek3Yr+OuZzgZjduCOfSQBjbM8V3MfgcjSTeto/GXP6PAwKvJz/v15b7GHZvx5rOlczFw/Q==",
|
||||||
|
"dependencies": {
|
||||||
|
"custom-error-instance": "2.1.1",
|
||||||
|
"lodash.uniqby": "4.5.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/combined-stream": {
|
"node_modules/combined-stream": {
|
||||||
"version": "1.0.8",
|
"version": "1.0.8",
|
||||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||||
|
|
@ -3637,6 +3653,12 @@
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/custom-error-instance": {
|
||||||
|
"version": "2.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/custom-error-instance/-/custom-error-instance-2.1.1.tgz",
|
||||||
|
"integrity": "sha512-p6JFxJc3M4OTD2li2qaHkDCw9SfMw82Ldr6OC9Je1aXiGfhx2W8p3GaoeaGrPJTUN9NirTM/KTxHWMUdR1rsUg==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
"node_modules/d3-array": {
|
"node_modules/d3-array": {
|
||||||
"version": "3.2.4",
|
"version": "3.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
|
||||||
|
|
@ -4467,6 +4489,12 @@
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/graceful-fs": {
|
||||||
|
"version": "4.2.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||||
|
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
"node_modules/has-flag": {
|
"node_modules/has-flag": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
|
||||||
|
|
@ -4651,6 +4679,18 @@
|
||||||
"node": ">=0.12.0"
|
"node": ">=0.12.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/is-stream": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/isexe": {
|
"node_modules/isexe": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||||
|
|
@ -4668,6 +4708,12 @@
|
||||||
"jiti": "bin/jiti.js"
|
"jiti": "bin/jiti.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/js-base64": {
|
||||||
|
"version": "3.7.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.8.tgz",
|
||||||
|
"integrity": "sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==",
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
"node_modules/js-tokens": {
|
"node_modules/js-tokens": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||||
|
|
@ -4795,6 +4841,52 @@
|
||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/lodash._baseiteratee": {
|
||||||
|
"version": "4.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash._baseiteratee/-/lodash._baseiteratee-4.7.0.tgz",
|
||||||
|
"integrity": "sha512-nqB9M+wITz0BX/Q2xg6fQ8mLkyfF7MU7eE+MNBNjTHFKeKaZAPEzEg+E8LWxKWf1DQVflNEn9N49yAuqKh2mWQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"lodash._stringtopath": "~4.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/lodash._basetostring": {
|
||||||
|
"version": "4.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-4.12.0.tgz",
|
||||||
|
"integrity": "sha512-SwcRIbyxnN6CFEEK4K1y+zuApvWdpQdBHM/swxP962s8HIxPO3alBH5t3m/dl+f4CMUug6sJb7Pww8d13/9WSw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/lodash._baseuniq": {
|
||||||
|
"version": "4.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash._baseuniq/-/lodash._baseuniq-4.6.0.tgz",
|
||||||
|
"integrity": "sha512-Ja1YevpHZctlI5beLA7oc5KNDhGcPixFhcqSiORHNsp/1QTv7amAXzw+gu4YOvErqVlMVyIJGgtzeepCnnur0A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"lodash._createset": "~4.0.0",
|
||||||
|
"lodash._root": "~3.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/lodash._createset": {
|
||||||
|
"version": "4.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash._createset/-/lodash._createset-4.0.3.tgz",
|
||||||
|
"integrity": "sha512-GTkC6YMprrJZCYU3zcqZj+jkXkrXzq3IPBcF/fIPpNEAB4hZEtXU8zp/RwKOvZl43NUmwDbyRk3+ZTbeRdEBXA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/lodash._root": {
|
||||||
|
"version": "3.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz",
|
||||||
|
"integrity": "sha512-O0pWuFSK6x4EXhM1dhZ8gchNtG7JMqBtrHdoUFUWXD7dJnNSUze1GuyQr5sOs0aCvgGeI3o/OJW8f4ca7FDxmQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/lodash._stringtopath": {
|
||||||
|
"version": "4.8.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash._stringtopath/-/lodash._stringtopath-4.8.0.tgz",
|
||||||
|
"integrity": "sha512-SXL66C731p0xPDC5LZg4wI5H+dJo/EO4KTqOMwLYCH3+FmmfAKJEZCm6ohGpI+T1xwsDsJCfL4OnhorllvlTPQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"lodash._basetostring": "~4.12.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/lodash.merge": {
|
"node_modules/lodash.merge": {
|
||||||
"version": "4.6.2",
|
"version": "4.6.2",
|
||||||
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
|
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
|
||||||
|
|
@ -4802,6 +4894,22 @@
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/lodash.throttle": {
|
||||||
|
"version": "4.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash.throttle/-/lodash.throttle-4.1.1.tgz",
|
||||||
|
"integrity": "sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/lodash.uniqby": {
|
||||||
|
"version": "4.5.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash.uniqby/-/lodash.uniqby-4.5.0.tgz",
|
||||||
|
"integrity": "sha512-IRt7cfTtHy6f1aRVA5n7kT8rgN3N1nH6MOWLcHfpWG2SH19E3JksLK38MktLxZDhlAjCP9jpIXkOnRXlu6oByQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"lodash._baseiteratee": "~4.7.0",
|
||||||
|
"lodash._baseuniq": "~4.6.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/lru-cache": {
|
"node_modules/lru-cache": {
|
||||||
"version": "5.1.1",
|
"version": "5.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
|
||||||
|
|
@ -5287,6 +5395,17 @@
|
||||||
"node": ">= 0.8.0"
|
"node": ">= 0.8.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/proper-lockfile": {
|
||||||
|
"version": "4.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
|
||||||
|
"integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"graceful-fs": "^4.2.4",
|
||||||
|
"retry": "^0.12.0",
|
||||||
|
"signal-exit": "^3.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/proxy-from-env": {
|
"node_modules/proxy-from-env": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||||
|
|
@ -5303,6 +5422,12 @@
|
||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/querystringify": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/queue-microtask": {
|
"node_modules/queue-microtask": {
|
||||||
"version": "1.2.3",
|
"version": "1.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||||
|
|
@ -5577,6 +5702,12 @@
|
||||||
"redux": "^5.0.0"
|
"redux": "^5.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/requires-port": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/reselect": {
|
"node_modules/reselect": {
|
||||||
"version": "5.1.1",
|
"version": "5.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
|
||||||
|
|
@ -5635,6 +5766,15 @@
|
||||||
"node": ">=4"
|
"node": ">=4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/retry": {
|
||||||
|
"version": "0.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
|
||||||
|
"integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/reusify": {
|
"node_modules/reusify": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
|
||||||
|
|
@ -5757,6 +5897,12 @@
|
||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/signal-exit": {
|
||||||
|
"version": "3.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
|
||||||
|
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
"node_modules/sonner": {
|
"node_modules/sonner": {
|
||||||
"version": "2.0.7",
|
"version": "2.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz",
|
||||||
|
|
@ -5991,6 +6137,24 @@
|
||||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
"license": "0BSD"
|
"license": "0BSD"
|
||||||
},
|
},
|
||||||
|
"node_modules/tus-js-client": {
|
||||||
|
"version": "4.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/tus-js-client/-/tus-js-client-4.3.1.tgz",
|
||||||
|
"integrity": "sha512-ZLeYmjrkaU1fUsKbIi8JML52uAocjEZtBx4DKjRrqzrZa0O4MYwT6db+oqePlspV+FxXJAyFBc/L5gwUi2OFsg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"buffer-from": "^1.1.2",
|
||||||
|
"combine-errors": "^3.0.3",
|
||||||
|
"is-stream": "^2.0.0",
|
||||||
|
"js-base64": "^3.7.2",
|
||||||
|
"lodash.throttle": "^4.1.1",
|
||||||
|
"proper-lockfile": "^4.1.2",
|
||||||
|
"url-parse": "^1.5.7"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/type-check": {
|
"node_modules/type-check": {
|
||||||
"version": "0.4.0",
|
"version": "0.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||||
|
|
@ -6091,6 +6255,16 @@
|
||||||
"punycode": "^2.1.0"
|
"punycode": "^2.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/url-parse": {
|
||||||
|
"version": "1.5.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
|
||||||
|
"integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"querystringify": "^2.1.1",
|
||||||
|
"requires-port": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/use-callback-ref": {
|
"node_modules/use-callback-ref": {
|
||||||
"version": "1.3.3",
|
"version": "1.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@
|
||||||
"resend": "^6.12.3",
|
"resend": "^6.12.3",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.4.0",
|
"tailwind-merge": "^3.4.0",
|
||||||
|
"tus-js-client": "^4.3.1",
|
||||||
"zustand": "^5.0.9"
|
"zustand": "^5.0.9"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
|
||||||
|
|
@ -63,9 +63,9 @@ import type {
|
||||||
GetSubCourseEntryAssessmentResponse,
|
GetSubCourseEntryAssessmentResponse,
|
||||||
ReorderItem,
|
ReorderItem,
|
||||||
ReorderOrderedIdsRequest,
|
ReorderOrderedIdsRequest,
|
||||||
GetRatingsResponse,
|
|
||||||
GetRatingsParams,
|
|
||||||
GetVimeoSampleResponse,
|
GetVimeoSampleResponse,
|
||||||
|
GetVimeoVideoResponse,
|
||||||
|
VimeoSampleVideo,
|
||||||
CreateCourseVideoRequest,
|
CreateCourseVideoRequest,
|
||||||
GetLearningProgramsResponse,
|
GetLearningProgramsResponse,
|
||||||
UpdateLearningProgramRequest,
|
UpdateLearningProgramRequest,
|
||||||
|
|
@ -1394,12 +1394,52 @@ export const reorderVideos = reorderNotYetSupported
|
||||||
|
|
||||||
export const reorderPractices = reorderNotYetSupported
|
export const reorderPractices = reorderNotYetSupported
|
||||||
|
|
||||||
// Ratings
|
// Ratings — see ratings.api.ts
|
||||||
export const getRatings = (params: GetRatingsParams) =>
|
export { getRatings } from "./ratings.api"
|
||||||
http.get<GetRatingsResponse>("/ratings", { params })
|
|
||||||
|
|
||||||
// Vimeo Sample Video
|
// Vimeo Sample Video
|
||||||
export const getVimeoSample = (videoId: string, width = 640, height = 360) =>
|
export const getVimeoSample = (videoId: string, width = 640, height = 360) =>
|
||||||
http.get<GetVimeoSampleResponse>("/vimeo/sample", {
|
http.get<GetVimeoSampleResponse>("/vimeo/sample", {
|
||||||
params: { video_id: videoId, width, height },
|
params: { video_id: videoId, width, height },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function readString(raw: Record<string, unknown>, ...keys: string[]): string {
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = raw[key]
|
||||||
|
if (value == null) continue
|
||||||
|
const text = String(value).trim()
|
||||||
|
if (text) return text
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeVimeoVideoDetails(raw: unknown): VimeoSampleVideo {
|
||||||
|
if (!isRecord(raw)) throw new Error("Invalid Vimeo video response")
|
||||||
|
|
||||||
|
return {
|
||||||
|
vimeo_id: readString(raw, "vimeo_id", "VimeoID"),
|
||||||
|
uri: readString(raw, "uri", "URI"),
|
||||||
|
name: readString(raw, "name", "Name"),
|
||||||
|
description: readString(raw, "description", "Description"),
|
||||||
|
duration: Number(raw.duration ?? raw.Duration) || 0,
|
||||||
|
width: Number(raw.width ?? raw.Width) || 0,
|
||||||
|
height: Number(raw.height ?? raw.Height) || 0,
|
||||||
|
link: readString(raw, "link", "Link"),
|
||||||
|
embed_url: readString(raw, "embed_url", "EmbedURL", "EmbedUrl"),
|
||||||
|
embed_html: readString(raw, "embed_html", "EmbedHTML", "EmbedHtml"),
|
||||||
|
thumbnail_url: readString(raw, "thumbnail_url", "ThumbnailURL", "ThumbnailUrl"),
|
||||||
|
status: readString(raw, "status", "Status"),
|
||||||
|
transcode_status: readString(raw, "transcode_status", "TranscodeStatus"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getVimeoVideo(videoId: string): Promise<VimeoSampleVideo> {
|
||||||
|
const res = await http.get<GetVimeoVideoResponse>(
|
||||||
|
`/vimeo/videos/${encodeURIComponent(videoId.trim())}`,
|
||||||
|
)
|
||||||
|
return normalizeVimeoVideoDetails(res.data.data)
|
||||||
|
}
|
||||||
|
|
|
||||||
163
src/api/faq.api.ts
Normal file
163
src/api/faq.api.ts
Normal file
|
|
@ -0,0 +1,163 @@
|
||||||
|
import http from "./http"
|
||||||
|
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||||
|
import type {
|
||||||
|
CreateFAQRequest,
|
||||||
|
CreateFAQResponse,
|
||||||
|
DeleteFAQResponse,
|
||||||
|
FAQ,
|
||||||
|
FAQFilters,
|
||||||
|
FAQListData,
|
||||||
|
GetFAQResponse,
|
||||||
|
GetFAQsResponse,
|
||||||
|
UpdateFAQRequest,
|
||||||
|
UpdateFAQResponse,
|
||||||
|
} from "../types/faq.types"
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFAQ(raw: unknown): FAQ | null {
|
||||||
|
if (!isRecord(raw)) return null
|
||||||
|
const id = Number(raw.id)
|
||||||
|
if (!Number.isFinite(id)) return null
|
||||||
|
|
||||||
|
const status = String(raw.status ?? "ACTIVE").toUpperCase()
|
||||||
|
const category = raw.category
|
||||||
|
const normalizedCategory =
|
||||||
|
category == null || String(category).trim() === "" ? null : String(category)
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
question: String(raw.question ?? ""),
|
||||||
|
answer: String(raw.answer ?? ""),
|
||||||
|
category: normalizedCategory,
|
||||||
|
display_order: Number(raw.display_order ?? 0),
|
||||||
|
status: status === "INACTIVE" ? "INACTIVE" : "ACTIVE",
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
updated_at:
|
||||||
|
raw.updated_at == null || String(raw.updated_at).trim() === ""
|
||||||
|
? null
|
||||||
|
: String(raw.updated_at),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseFAQsList(body: unknown): FAQListData {
|
||||||
|
const empty: FAQListData = { faqs: [], total_count: 0 }
|
||||||
|
|
||||||
|
if (isRecord(body)) {
|
||||||
|
const data = body.data
|
||||||
|
if (isRecord(data) && Array.isArray(data.faqs)) {
|
||||||
|
const faqs = data.faqs
|
||||||
|
.map(normalizeFAQ)
|
||||||
|
.filter((row): row is FAQ => row !== null)
|
||||||
|
const total_count = Number(data.total_count ?? faqs.length)
|
||||||
|
return {
|
||||||
|
faqs,
|
||||||
|
total_count: Number.isFinite(total_count) ? total_count : faqs.length,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
const faqs = data.map(normalizeFAQ).filter((row): row is FAQ => row !== null)
|
||||||
|
return { faqs, total_count: faqs.length }
|
||||||
|
}
|
||||||
|
if (Array.isArray(body.faqs)) {
|
||||||
|
const faqs = body.faqs
|
||||||
|
.map(normalizeFAQ)
|
||||||
|
.filter((row): row is FAQ => row !== null)
|
||||||
|
const total_count = Number(body.total_count ?? faqs.length)
|
||||||
|
return {
|
||||||
|
faqs,
|
||||||
|
total_count: Number.isFinite(total_count) ? total_count : faqs.length,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(body)) {
|
||||||
|
const faqs = body.map(normalizeFAQ).filter((row): row is FAQ => row !== null)
|
||||||
|
return { faqs, total_count: faqs.length }
|
||||||
|
}
|
||||||
|
|
||||||
|
return empty
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseFAQMutation(body: unknown): FAQ | null {
|
||||||
|
if (isRecord(body) && body.data != null) {
|
||||||
|
return normalizeFAQ(body.data)
|
||||||
|
}
|
||||||
|
return normalizeFAQ(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFAQQuery(filters: FAQFilters = {}): Record<string, string | number> {
|
||||||
|
const params: Record<string, string | number> = {}
|
||||||
|
if (filters.status) params.status = filters.status
|
||||||
|
if (filters.category?.trim()) params.category = filters.category.trim()
|
||||||
|
params.limit = filters.limit ?? DEFAULT_TABLE_PAGE_SIZE
|
||||||
|
params.offset = filters.offset ?? 0
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /admin/faqs — list FAQs (all statuses). */
|
||||||
|
export const getFAQs = (filters: FAQFilters = {}) =>
|
||||||
|
http
|
||||||
|
.get<GetFAQsResponse>("/admin/faqs", { params: buildFAQQuery(filters) })
|
||||||
|
.then((res) => {
|
||||||
|
const parsed = parseFAQsList(res.data)
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: parsed,
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
/** GET /admin/faqs/:id — get one FAQ for editing. */
|
||||||
|
export const getFAQById = (id: number) =>
|
||||||
|
http.get<GetFAQResponse>(`/admin/faqs/${id}`).then((res) => ({
|
||||||
|
...res,
|
||||||
|
data: parseFAQMutation(res.data),
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
/** POST /admin/faqs — create FAQ. */
|
||||||
|
export const createFAQ = (payload: CreateFAQRequest) =>
|
||||||
|
http.post<CreateFAQResponse>("/admin/faqs", payload).then((res) => ({
|
||||||
|
...res,
|
||||||
|
data: parseFAQMutation(res.data),
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
/** PUT /admin/faqs/:id — update FAQ. */
|
||||||
|
export const updateFAQ = (id: number, payload: UpdateFAQRequest) =>
|
||||||
|
http.put<UpdateFAQResponse>(`/admin/faqs/${id}`, payload).then((res) => ({
|
||||||
|
...res,
|
||||||
|
data: parseFAQMutation(res.data),
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
/** DELETE /admin/faqs/:id — hard delete FAQ. */
|
||||||
|
export const deleteFAQ = (id: number) =>
|
||||||
|
http.delete<DeleteFAQResponse>(`/admin/faqs/${id}`).then((res) => ({
|
||||||
|
...res,
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
/** GET /faqs/:id — public detail (preview only, ACTIVE FAQs). */
|
||||||
|
export const getPublicFAQById = (id: number) =>
|
||||||
|
http.get<GetFAQResponse>(`/faqs/${id}`).then((res) => ({
|
||||||
|
...res,
|
||||||
|
data: parseFAQMutation(res.data),
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
/** GET /faqs — public list (preview only, ACTIVE FAQs). */
|
||||||
|
export const getPublicFAQs = (filters: Pick<FAQFilters, "category" | "limit" | "offset"> = {}) =>
|
||||||
|
http
|
||||||
|
.get<GetFAQsResponse>("/faqs", { params: buildFAQQuery(filters) })
|
||||||
|
.then((res) => {
|
||||||
|
const parsed = parseFAQsList(res.data)
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: parsed,
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
@ -118,6 +118,13 @@ export const markAllRead = () =>
|
||||||
export const markAllUnread = () =>
|
export const markAllUnread = () =>
|
||||||
http.post("/notifications/mark-all-unread")
|
http.post("/notifications/mark-all-unread")
|
||||||
|
|
||||||
|
/** DELETE /notifications/:id — remove an in-app notification. */
|
||||||
|
export const deleteNotification = (id: string) =>
|
||||||
|
http.delete<unknown>(`/notifications/${id}`).then((res) => ({
|
||||||
|
...res,
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
export type BulkSendApiResult =
|
export type BulkSendApiResult =
|
||||||
| { kind: "immediate"; data: BulkSendResult; message: string }
|
| { kind: "immediate"; data: BulkSendResult; message: string }
|
||||||
| { kind: "scheduled"; data: ScheduledNotification; message: string }
|
| { kind: "scheduled"; data: ScheduledNotification; message: string }
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,162 @@
|
||||||
import http from "./http"
|
import http from "./http"
|
||||||
import type { GetPersonasParams, GetPersonasResponse } from "../types/persona.types"
|
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||||
|
import type {
|
||||||
|
CreatePersonaInput,
|
||||||
|
DeletePersonaResponse,
|
||||||
|
GetPersonaResponse,
|
||||||
|
GetPersonasResponse,
|
||||||
|
ListPersonasParams,
|
||||||
|
LmsPersona,
|
||||||
|
MutatePersonaResponse,
|
||||||
|
PersonaListData,
|
||||||
|
UpdatePersonaInput,
|
||||||
|
} from "../types/persona.types"
|
||||||
|
|
||||||
/** GET /personas — list personas (filter active client-side when needed). */
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
export const getPersonas = (params?: GetPersonasParams) =>
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
http.get<GetPersonasResponse>("/personas", { params })
|
}
|
||||||
|
|
||||||
|
function normalizePersona(raw: unknown): LmsPersona | null {
|
||||||
|
if (!isRecord(raw)) return null
|
||||||
|
const id = Number(raw.id)
|
||||||
|
if (!Number.isFinite(id)) return null
|
||||||
|
|
||||||
|
const name = String(raw.name ?? "").trim()
|
||||||
|
if (!name) return null
|
||||||
|
|
||||||
|
const descriptionRaw = raw.description
|
||||||
|
const description =
|
||||||
|
descriptionRaw == null || String(descriptionRaw).trim() === ""
|
||||||
|
? null
|
||||||
|
: String(descriptionRaw)
|
||||||
|
|
||||||
|
const profilePictureRaw = raw.profile_picture
|
||||||
|
const profile_picture =
|
||||||
|
profilePictureRaw == null || String(profilePictureRaw).trim() === ""
|
||||||
|
? null
|
||||||
|
: String(profilePictureRaw)
|
||||||
|
|
||||||
|
const genderRaw = raw.gender
|
||||||
|
const gender =
|
||||||
|
genderRaw == null || String(genderRaw).trim() === "" ? null : String(genderRaw)
|
||||||
|
|
||||||
|
const updatedAtRaw = raw.updated_at
|
||||||
|
const updated_at =
|
||||||
|
updatedAtRaw == null || String(updatedAtRaw).trim() === ""
|
||||||
|
? null
|
||||||
|
: String(updatedAtRaw)
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
profile_picture,
|
||||||
|
gender,
|
||||||
|
is_active: raw.is_active !== false,
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
updated_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parsePersonasList(body: unknown): PersonaListData {
|
||||||
|
const empty: PersonaListData = {
|
||||||
|
personas: [],
|
||||||
|
total_count: 0,
|
||||||
|
limit: DEFAULT_TABLE_PAGE_SIZE,
|
||||||
|
offset: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isRecord(body)) {
|
||||||
|
const data = body.data ?? body.Data
|
||||||
|
if (isRecord(data) && Array.isArray(data.personas)) {
|
||||||
|
const personas = data.personas
|
||||||
|
.map(normalizePersona)
|
||||||
|
.filter((row): row is LmsPersona => row !== null)
|
||||||
|
const total_count = Number(data.total_count ?? personas.length)
|
||||||
|
const limit = Number(data.limit ?? DEFAULT_TABLE_PAGE_SIZE)
|
||||||
|
const offset = Number(data.offset ?? 0)
|
||||||
|
return {
|
||||||
|
personas,
|
||||||
|
total_count: Number.isFinite(total_count) ? total_count : personas.length,
|
||||||
|
limit: Number.isFinite(limit) ? limit : DEFAULT_TABLE_PAGE_SIZE,
|
||||||
|
offset: Number.isFinite(offset) ? offset : 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return empty
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parsePersonaMutation(body: unknown): LmsPersona | null {
|
||||||
|
if (isRecord(body) && body.data != null) {
|
||||||
|
return normalizePersona(body.data)
|
||||||
|
}
|
||||||
|
return normalizePersona(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPersonasQuery(params: ListPersonasParams = {}): Record<string, string | number | boolean> {
|
||||||
|
return {
|
||||||
|
active_only: params.active_only !== false,
|
||||||
|
limit: params.limit ?? DEFAULT_TABLE_PAGE_SIZE,
|
||||||
|
offset: params.offset ?? 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /personas — list persona catalog (paginated). */
|
||||||
|
export function listPersonas(params: ListPersonasParams = {}) {
|
||||||
|
return http
|
||||||
|
.get<GetPersonasResponse>("/personas", { params: buildPersonasQuery(params) })
|
||||||
|
.then((res) => {
|
||||||
|
const parsed = parsePersonasList(res.data)
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: parsed,
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /personas — legacy axios response for practice picker callers. */
|
||||||
|
export const getPersonas = (params?: ListPersonasParams) =>
|
||||||
|
http.get<GetPersonasResponse>("/personas", { params: buildPersonasQuery(params ?? {}) })
|
||||||
|
|
||||||
|
/** GET /personas/:id */
|
||||||
|
export function getPersonaById(id: number) {
|
||||||
|
return http.get<GetPersonaResponse>(`/personas/${id}`).then((res) => ({
|
||||||
|
...res,
|
||||||
|
data: parsePersonaMutation(res.data),
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /personas */
|
||||||
|
export function createPersona(payload: CreatePersonaInput) {
|
||||||
|
return http.post<MutatePersonaResponse>("/personas", payload).then((res) => ({
|
||||||
|
...res,
|
||||||
|
data: parsePersonaMutation(res.data),
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PUT /personas/:id */
|
||||||
|
export function updatePersona(id: number, payload: UpdatePersonaInput) {
|
||||||
|
return http.put<MutatePersonaResponse>(`/personas/${id}`, payload).then((res) => ({
|
||||||
|
...res,
|
||||||
|
data: parsePersonaMutation(res.data),
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** DELETE /personas/:id */
|
||||||
|
export function deletePersona(id: number) {
|
||||||
|
return http.delete<DeletePersonaResponse>(`/personas/${id}`).then((res) => ({
|
||||||
|
...res,
|
||||||
|
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Active personas for practice editor dropdown. */
|
||||||
|
export async function listActivePersonasForPicker(limit = 200): Promise<LmsPersona[]> {
|
||||||
|
const res = await listPersonas({ active_only: true, limit, offset: 0 })
|
||||||
|
return res.data.personas
|
||||||
|
}
|
||||||
|
|
|
||||||
144
src/api/ratings.api.ts
Normal file
144
src/api/ratings.api.ts
Normal file
|
|
@ -0,0 +1,144 @@
|
||||||
|
import http from "./http"
|
||||||
|
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||||
|
import type {
|
||||||
|
AppReviewsPageData,
|
||||||
|
GetRatingSummaryResponse,
|
||||||
|
GetRatingsResponse,
|
||||||
|
ListRatingsParams,
|
||||||
|
Rating,
|
||||||
|
RatingSummary,
|
||||||
|
RatingSummaryParams,
|
||||||
|
RatingTargetType,
|
||||||
|
} from "../types/ratings.types"
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTargetId(targetType: RatingTargetType, targetId?: number): number {
|
||||||
|
if (targetType === "app") return 0
|
||||||
|
const id = Number(targetId ?? 0)
|
||||||
|
return Number.isFinite(id) ? id : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeRating(raw: unknown): Rating | null {
|
||||||
|
if (!isRecord(raw)) return null
|
||||||
|
const id = Number(raw.id)
|
||||||
|
const user_id = Number(raw.user_id)
|
||||||
|
if (!Number.isFinite(id) || !Number.isFinite(user_id)) return null
|
||||||
|
|
||||||
|
const target_type = String(raw.target_type ?? "app") as RatingTargetType
|
||||||
|
const stars = Number(raw.stars)
|
||||||
|
if (!Number.isFinite(stars) || stars < 1 || stars > 5) return null
|
||||||
|
|
||||||
|
const reviewRaw = raw.review
|
||||||
|
const review =
|
||||||
|
reviewRaw == null || String(reviewRaw).trim() === "" ? null : String(reviewRaw)
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
user_id,
|
||||||
|
target_type,
|
||||||
|
target_id: Number(raw.target_id ?? 0),
|
||||||
|
stars,
|
||||||
|
review,
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
updated_at: String(raw.updated_at ?? ""),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRatingsList(body: unknown): Rating[] {
|
||||||
|
if (isRecord(body) && Array.isArray(body.data)) {
|
||||||
|
return body.data.map(normalizeRating).filter((row): row is Rating => row !== null)
|
||||||
|
}
|
||||||
|
if (Array.isArray(body)) {
|
||||||
|
return body.map(normalizeRating).filter((row): row is Rating => row !== null)
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRatingSummary(body: unknown): RatingSummary {
|
||||||
|
const fallback: RatingSummary = { total_count: 0, average_stars: 0 }
|
||||||
|
if (!isRecord(body)) return fallback
|
||||||
|
|
||||||
|
const data = body.data
|
||||||
|
if (!isRecord(data)) return fallback
|
||||||
|
|
||||||
|
const total_count = Number(data.total_count ?? 0)
|
||||||
|
const average_stars = Number(data.average_stars ?? 0)
|
||||||
|
|
||||||
|
return {
|
||||||
|
total_count: Number.isFinite(total_count) ? total_count : 0,
|
||||||
|
average_stars: Number.isFinite(average_stars) ? average_stars : 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRatingsQuery(params: ListRatingsParams): Record<string, string | number> {
|
||||||
|
const targetId = normalizeTargetId(params.target_type, params.target_id)
|
||||||
|
return {
|
||||||
|
target_type: params.target_type,
|
||||||
|
target_id: targetId,
|
||||||
|
limit: params.limit ?? DEFAULT_TABLE_PAGE_SIZE,
|
||||||
|
offset: params.offset ?? 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRatingSummary(params: RatingSummaryParams) {
|
||||||
|
const targetId = normalizeTargetId(params.target_type, params.target_id)
|
||||||
|
return http
|
||||||
|
.get<GetRatingSummaryResponse>("/ratings/summary", {
|
||||||
|
params: { target_type: params.target_type, target_id: targetId },
|
||||||
|
})
|
||||||
|
.then((res) => parseRatingSummary(res.data))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listRatingsByTarget(params: ListRatingsParams) {
|
||||||
|
return http
|
||||||
|
.get<GetRatingsResponse>("/ratings", { params: buildRatingsQuery(params) })
|
||||||
|
.then((res) => parseRatingsList(res.data))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Load summary + paginated reviews in parallel (recommended admin pattern). */
|
||||||
|
export async function loadRatingsPage(
|
||||||
|
targetType: RatingTargetType,
|
||||||
|
page: number,
|
||||||
|
pageSize: number,
|
||||||
|
targetId?: number,
|
||||||
|
): Promise<AppReviewsPageData> {
|
||||||
|
const offset = (page - 1) * pageSize
|
||||||
|
const normalizedTargetId = normalizeTargetId(targetType, targetId)
|
||||||
|
|
||||||
|
const [summary, reviews] = await Promise.all([
|
||||||
|
getRatingSummary({ target_type: targetType, target_id: normalizedTargetId }),
|
||||||
|
listRatingsByTarget({
|
||||||
|
target_type: targetType,
|
||||||
|
target_id: normalizedTargetId,
|
||||||
|
limit: pageSize,
|
||||||
|
offset,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
return { summary, reviews }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @deprecated Use listRatingsByTarget — kept for legacy callers. */
|
||||||
|
export function getRatings(params: {
|
||||||
|
target_type: string
|
||||||
|
target_id: number
|
||||||
|
limit?: number
|
||||||
|
offset?: number
|
||||||
|
}) {
|
||||||
|
return listRatingsByTarget({
|
||||||
|
target_type: params.target_type as RatingTargetType,
|
||||||
|
target_id: params.target_id,
|
||||||
|
limit: params.limit,
|
||||||
|
offset: params.offset,
|
||||||
|
}).then((reviews) => ({
|
||||||
|
data: {
|
||||||
|
message: "Ratings retrieved successfully",
|
||||||
|
data: reviews,
|
||||||
|
success: true,
|
||||||
|
status_code: 200,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
@ -30,6 +30,10 @@ export const setRolePermissions = (roleId: number, data: SetRolePermissionsReque
|
||||||
export const getAllPermissions = () =>
|
export const getAllPermissions = () =>
|
||||||
http.get<GetPermissionsResponse>("/rbac/permissions")
|
http.get<GetPermissionsResponse>("/rbac/permissions")
|
||||||
|
|
||||||
|
/** POST /rbac/permissions/sync — upsert permission definitions and default role links. */
|
||||||
|
export const syncRbacPermissions = () =>
|
||||||
|
http.post<{ message?: string }>("/rbac/permissions/sync")
|
||||||
|
|
||||||
export const deleteRole = (roleId: number) =>
|
export const deleteRole = (roleId: number) =>
|
||||||
http.delete<DeleteRoleResponse>(`/rbac/roles/${roleId}`)
|
http.delete<DeleteRoleResponse>(`/rbac/roles/${roleId}`)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,12 +9,79 @@ import type {
|
||||||
import type {
|
import type {
|
||||||
ChangeTeamMemberPasswordRequest,
|
ChangeTeamMemberPasswordRequest,
|
||||||
ChangeTeamMemberPasswordResponse,
|
ChangeTeamMemberPasswordResponse,
|
||||||
|
GetTeamMeResponse,
|
||||||
GetTeamMembersResponse,
|
GetTeamMembersResponse,
|
||||||
GetTeamMemberResponse,
|
GetTeamMemberResponse,
|
||||||
CreateTeamMemberRequest,
|
CreateTeamMemberRequest,
|
||||||
UpdateTeamMemberRequest,
|
UpdateTeamMemberRequest,
|
||||||
|
UpdateTeamMeRequest,
|
||||||
|
TeamMember,
|
||||||
|
TeamMemberDetail,
|
||||||
} from "../types/team.types"
|
} from "../types/team.types"
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function optionalString(value: unknown): string | null {
|
||||||
|
if (value == null) return null
|
||||||
|
const text = String(value).trim()
|
||||||
|
return text ? text : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeTeamMemberDetail(raw: unknown): TeamMemberDetail | null {
|
||||||
|
if (!isRecord(raw)) return null
|
||||||
|
const id = Number(raw.id)
|
||||||
|
if (!Number.isFinite(id)) return null
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
first_name: String(raw.first_name ?? ""),
|
||||||
|
last_name: String(raw.last_name ?? ""),
|
||||||
|
email: String(raw.email ?? ""),
|
||||||
|
phone_number: String(raw.phone_number ?? ""),
|
||||||
|
team_role: String(raw.team_role ?? ""),
|
||||||
|
department: String(raw.department ?? ""),
|
||||||
|
job_title: String(raw.job_title ?? ""),
|
||||||
|
bio: optionalString(raw.bio),
|
||||||
|
status: String(raw.status ?? ""),
|
||||||
|
email_verified: raw.email_verified === true,
|
||||||
|
last_login: optionalString(raw.last_login),
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
updated_at: optionalString(raw.updated_at),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeTeamMember(raw: unknown): TeamMember | null {
|
||||||
|
if (!isRecord(raw)) return null
|
||||||
|
const id = Number(raw.id)
|
||||||
|
if (!Number.isFinite(id)) return null
|
||||||
|
|
||||||
|
const permissionsRaw = raw.permissions
|
||||||
|
const permissions = Array.isArray(permissionsRaw)
|
||||||
|
? permissionsRaw.map((entry) => String(entry))
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
first_name: String(raw.first_name ?? ""),
|
||||||
|
last_name: String(raw.last_name ?? ""),
|
||||||
|
email: String(raw.email ?? ""),
|
||||||
|
phone_number: String(raw.phone_number ?? ""),
|
||||||
|
team_role: String(raw.team_role ?? ""),
|
||||||
|
department: String(raw.department ?? ""),
|
||||||
|
job_title: String(raw.job_title ?? ""),
|
||||||
|
employment_type: optionalString(raw.employment_type) ?? undefined,
|
||||||
|
hire_date: optionalString(raw.hire_date) ?? undefined,
|
||||||
|
bio: optionalString(raw.bio) ?? undefined,
|
||||||
|
status: String(raw.status ?? ""),
|
||||||
|
email_verified: raw.email_verified === true,
|
||||||
|
permissions,
|
||||||
|
last_login: optionalString(raw.last_login),
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const getTeamMembers = (page?: number, pageSize?: number) =>
|
export const getTeamMembers = (page?: number, pageSize?: number) =>
|
||||||
http.get<GetTeamMembersResponse>("/team/members", {
|
http.get<GetTeamMembersResponse>("/team/members", {
|
||||||
params: {
|
params: {
|
||||||
|
|
@ -24,7 +91,27 @@ export const getTeamMembers = (page?: number, pageSize?: number) =>
|
||||||
})
|
})
|
||||||
|
|
||||||
export const getTeamMemberById = (id: number) =>
|
export const getTeamMemberById = (id: number) =>
|
||||||
http.get<GetTeamMemberResponse>(`/team/members/${id}`)
|
http.get<GetTeamMemberResponse>(`/team/members/${id}`).then((res) => {
|
||||||
|
const body = res.data
|
||||||
|
const member = normalizeTeamMemberDetail(body?.data)
|
||||||
|
if (!member) {
|
||||||
|
throw new Error("Invalid team member response")
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: {
|
||||||
|
...body,
|
||||||
|
data: member,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
/** GET /team/me — signed-in team member profile */
|
||||||
|
export const getTeamMe = () => http.get<GetTeamMeResponse>("/team/me")
|
||||||
|
|
||||||
|
/** PUT /team/me — update signed-in team member profile */
|
||||||
|
export const updateTeamMe = (data: UpdateTeamMeRequest) =>
|
||||||
|
http.put<GetTeamMeResponse>("/team/me", data)
|
||||||
|
|
||||||
export const createTeamMember = (data: CreateTeamMemberRequest) =>
|
export const createTeamMember = (data: CreateTeamMemberRequest) =>
|
||||||
http.post("/team/register", data)
|
http.post("/team/register", data)
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,399 @@
|
||||||
import http from "./http";
|
import http from "./http";
|
||||||
|
import type { GetTeamMeResponse } from "../types/team.types";
|
||||||
import {
|
import {
|
||||||
type UserProfileResponse,
|
|
||||||
type GetUsersResponse,
|
type GetUsersResponse,
|
||||||
type UpdateProfileRequest,
|
type UpdateProfileRequest,
|
||||||
|
type UserProfileData,
|
||||||
|
type UserProfileResponse,
|
||||||
type UserSummaryResponse,
|
type UserSummaryResponse,
|
||||||
type GetDeletionRequestsParams,
|
type GetDeletionRequestsParams,
|
||||||
type GetDeletionRequestsResponse,
|
type GetDeletionRequestsResponse,
|
||||||
type UserRecentActivityResponse,
|
type UserRecentActivityResponse,
|
||||||
|
type UserRecentActivityItem,
|
||||||
|
type UserRecentActivityData,
|
||||||
} from "../types/user.types";
|
} from "../types/user.types";
|
||||||
|
import type {
|
||||||
|
LearningActivityAccess,
|
||||||
|
LearningActivityCompletedIds,
|
||||||
|
LearningActivityCourse,
|
||||||
|
LearningActivityLesson,
|
||||||
|
LearningActivityModule,
|
||||||
|
LearningActivityProgram,
|
||||||
|
LearningActivityUnit,
|
||||||
|
UserLearningActivityData,
|
||||||
|
UserLearningActivityResponse,
|
||||||
|
UserSubscriptionPayment,
|
||||||
|
UserSubscriptionRecord,
|
||||||
|
UserSubscriptionsData,
|
||||||
|
UserSubscriptionsResponse,
|
||||||
|
} from "../types/userAdmin.types";
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function optionalString(value: unknown): string | null {
|
||||||
|
if (value == null) return null;
|
||||||
|
const text = String(value).trim();
|
||||||
|
return text ? text : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeUserProfile(raw: unknown): UserProfileData | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = Number(raw.id);
|
||||||
|
if (!Number.isFinite(id)) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
first_name: String(raw.first_name ?? ""),
|
||||||
|
last_name: String(raw.last_name ?? ""),
|
||||||
|
gender: String(raw.gender ?? ""),
|
||||||
|
birth_day: optionalString(raw.birth_day),
|
||||||
|
email: String(raw.email ?? ""),
|
||||||
|
role: String(raw.role ?? ""),
|
||||||
|
age_group: String(raw.age_group ?? ""),
|
||||||
|
education_level: String(raw.education_level ?? ""),
|
||||||
|
country: String(raw.country ?? ""),
|
||||||
|
region: String(raw.region ?? ""),
|
||||||
|
nick_name: String(raw.nick_name ?? ""),
|
||||||
|
occupation: String(raw.occupation ?? ""),
|
||||||
|
learning_goal: String(raw.learning_goal ?? ""),
|
||||||
|
language_goal: String(raw.language_goal ?? ""),
|
||||||
|
language_challange: String(raw.language_challange ?? ""),
|
||||||
|
favoutite_topic: String(raw.favoutite_topic ?? ""),
|
||||||
|
email_verified: raw.email_verified === true,
|
||||||
|
phone_verified: raw.phone_verified === true,
|
||||||
|
status: String(raw.status ?? ""),
|
||||||
|
last_login: optionalString(raw.last_login),
|
||||||
|
profile_completed: raw.profile_completed === true,
|
||||||
|
profile_completion_percentage: Number(raw.profile_completion_percentage) || 0,
|
||||||
|
profile_picture_url: String(raw.profile_picture_url ?? ""),
|
||||||
|
preferred_language: String(raw.preferred_language ?? ""),
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
subscription_status: String(raw.subscription_status ?? ""),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeUserRecentActivityItem(raw: unknown): UserRecentActivityItem | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = String(raw.id ?? "").trim();
|
||||||
|
if (!id) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
kind: String(raw.kind ?? ""),
|
||||||
|
occurred_at: String(raw.occurred_at ?? ""),
|
||||||
|
headline: String(raw.headline ?? ""),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeUserRecentActivity(raw: unknown): UserRecentActivityData | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const userId = Number(raw.user_id);
|
||||||
|
if (!Number.isFinite(userId)) return null;
|
||||||
|
|
||||||
|
const itemsRaw = raw.items;
|
||||||
|
const items = Array.isArray(itemsRaw)
|
||||||
|
? itemsRaw
|
||||||
|
.map((entry) => normalizeUserRecentActivityItem(entry))
|
||||||
|
.filter((entry): entry is UserRecentActivityItem => entry !== null)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return { user_id: userId, items };
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLearningActivityAccess(raw: unknown): LearningActivityAccess {
|
||||||
|
if (!isRecord(raw)) {
|
||||||
|
return {
|
||||||
|
is_accessible: false,
|
||||||
|
is_completed: false,
|
||||||
|
completed_count: 0,
|
||||||
|
total_count: 0,
|
||||||
|
progress_percent: 0,
|
||||||
|
progress_percent_precise: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const reason = optionalString(raw.reason);
|
||||||
|
return {
|
||||||
|
is_accessible: raw.is_accessible === true,
|
||||||
|
is_completed: raw.is_completed === true,
|
||||||
|
reason: reason ?? undefined,
|
||||||
|
completed_count: Number(raw.completed_count) || 0,
|
||||||
|
total_count: Number(raw.total_count) || 0,
|
||||||
|
progress_percent: Number(raw.progress_percent) || 0,
|
||||||
|
progress_percent_precise: Number(raw.progress_percent_precise) || 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLearningActivityLesson(raw: unknown): LearningActivityLesson | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = Number(raw.id);
|
||||||
|
const moduleId = Number(raw.module_id);
|
||||||
|
if (!Number.isFinite(id) || !Number.isFinite(moduleId)) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
module_id: moduleId,
|
||||||
|
title: String(raw.title ?? ""),
|
||||||
|
access: normalizeLearningActivityAccess(raw.access),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLearningActivityModule(raw: unknown): LearningActivityModule | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = Number(raw.id);
|
||||||
|
if (!Number.isFinite(id)) return null;
|
||||||
|
|
||||||
|
const lessonsRaw = raw.lessons;
|
||||||
|
const lessons = Array.isArray(lessonsRaw)
|
||||||
|
? lessonsRaw
|
||||||
|
.map((entry) => normalizeLearningActivityLesson(entry))
|
||||||
|
.filter((entry): entry is LearningActivityLesson => entry !== null)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const programId = Number(raw.program_id);
|
||||||
|
const courseId = Number(raw.course_id);
|
||||||
|
const unitId = Number(raw.unit_id);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
program_id: Number.isFinite(programId) ? programId : undefined,
|
||||||
|
course_id: Number.isFinite(courseId) ? courseId : undefined,
|
||||||
|
unit_id: Number.isFinite(unitId) ? unitId : undefined,
|
||||||
|
name: String(raw.name ?? ""),
|
||||||
|
access: normalizeLearningActivityAccess(raw.access),
|
||||||
|
lessons,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLearningActivityUnit(raw: unknown): LearningActivityUnit | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = Number(raw.id);
|
||||||
|
const catalogCourseId = Number(raw.catalog_course_id);
|
||||||
|
if (!Number.isFinite(id) || !Number.isFinite(catalogCourseId)) return null;
|
||||||
|
|
||||||
|
const modulesRaw = raw.modules;
|
||||||
|
const modules = Array.isArray(modulesRaw)
|
||||||
|
? modulesRaw
|
||||||
|
.map((entry) => normalizeLearningActivityModule(entry))
|
||||||
|
.filter((entry): entry is LearningActivityModule => entry !== null)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
catalog_course_id: catalogCourseId,
|
||||||
|
name: String(raw.name ?? ""),
|
||||||
|
access: normalizeLearningActivityAccess(raw.access),
|
||||||
|
modules,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLearningActivityCourse(raw: unknown): LearningActivityCourse | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = Number(raw.id);
|
||||||
|
if (!Number.isFinite(id)) return null;
|
||||||
|
|
||||||
|
const modulesRaw = raw.modules;
|
||||||
|
const modules = Array.isArray(modulesRaw)
|
||||||
|
? modulesRaw
|
||||||
|
.map((entry) => normalizeLearningActivityModule(entry))
|
||||||
|
.filter((entry): entry is LearningActivityModule => entry !== null)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const unitsRaw = raw.units;
|
||||||
|
const units = Array.isArray(unitsRaw)
|
||||||
|
? unitsRaw
|
||||||
|
.map((entry) => normalizeLearningActivityUnit(entry))
|
||||||
|
.filter((entry): entry is LearningActivityUnit => entry !== null)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const programId = Number(raw.program_id);
|
||||||
|
const catalogCourseId = Number(raw.catalog_course_id);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
program_id: Number.isFinite(programId) ? programId : undefined,
|
||||||
|
catalog_course_id: Number.isFinite(catalogCourseId) ? catalogCourseId : undefined,
|
||||||
|
name: String(raw.name ?? ""),
|
||||||
|
access: normalizeLearningActivityAccess(raw.access),
|
||||||
|
modules,
|
||||||
|
units,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLearningActivityProgram(raw: unknown): LearningActivityProgram | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = Number(raw.id);
|
||||||
|
if (!Number.isFinite(id)) return null;
|
||||||
|
|
||||||
|
const coursesRaw = raw.courses;
|
||||||
|
const courses = Array.isArray(coursesRaw)
|
||||||
|
? coursesRaw
|
||||||
|
.map((entry) => normalizeLearningActivityCourse(entry))
|
||||||
|
.filter((entry): entry is LearningActivityCourse => entry !== null)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: String(raw.name ?? ""),
|
||||||
|
access: normalizeLearningActivityAccess(raw.access),
|
||||||
|
courses,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCompletedIds(raw: unknown): LearningActivityCompletedIds {
|
||||||
|
if (!isRecord(raw)) {
|
||||||
|
return { lesson_ids: [], module_ids: [], course_ids: [], program_ids: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const toIds = (value: unknown) =>
|
||||||
|
Array.isArray(value)
|
||||||
|
? value.map((entry) => Number(entry)).filter((entry) => Number.isFinite(entry))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
lesson_ids: toIds(raw.lesson_ids),
|
||||||
|
module_ids: toIds(raw.module_ids),
|
||||||
|
course_ids: toIds(raw.course_ids),
|
||||||
|
program_ids: toIds(raw.program_ids),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeUserLearningActivity(raw: unknown): UserLearningActivityData | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const userId = Number(raw.user_id);
|
||||||
|
if (!Number.isFinite(userId)) return null;
|
||||||
|
|
||||||
|
const lmsRaw = isRecord(raw.lms) ? raw.lms : {};
|
||||||
|
const lmsProgressRaw = isRecord(lmsRaw.progress) ? lmsRaw.progress : {};
|
||||||
|
const programsRaw = lmsProgressRaw.programs;
|
||||||
|
const programs = Array.isArray(programsRaw)
|
||||||
|
? programsRaw
|
||||||
|
.map((entry) => normalizeLearningActivityProgram(entry))
|
||||||
|
.filter((entry): entry is LearningActivityProgram => entry !== null)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const examPrepRaw = isRecord(raw.exam_prep) ? raw.exam_prep : {};
|
||||||
|
const examProgressRaw = isRecord(examPrepRaw.progress) ? examPrepRaw.progress : {};
|
||||||
|
const catalogCoursesRaw = examProgressRaw.catalog_courses;
|
||||||
|
const catalogCourses = Array.isArray(catalogCoursesRaw)
|
||||||
|
? catalogCoursesRaw
|
||||||
|
.map((entry) => normalizeLearningActivityCourse(entry))
|
||||||
|
.filter((entry): entry is LearningActivityCourse => entry !== null)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const lmsCompletionsRaw = isRecord(lmsRaw.completions) ? lmsRaw.completions : {};
|
||||||
|
const examCompletionsRaw = isRecord(examPrepRaw.completions) ? examPrepRaw.completions : {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
user_id: userId,
|
||||||
|
lms: {
|
||||||
|
completed_ids: normalizeCompletedIds(lmsRaw.completed_ids),
|
||||||
|
progress: { programs },
|
||||||
|
completions: {
|
||||||
|
user_id: Number(lmsCompletionsRaw.user_id) || userId,
|
||||||
|
programs: Array.isArray(lmsCompletionsRaw.programs) ? lmsCompletionsRaw.programs : [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
exam_prep: {
|
||||||
|
progress: { catalog_courses: catalogCourses },
|
||||||
|
completions: {
|
||||||
|
user_id: Number(examCompletionsRaw.user_id) || userId,
|
||||||
|
catalog_courses: Array.isArray(examCompletionsRaw.catalog_courses)
|
||||||
|
? examCompletionsRaw.catalog_courses
|
||||||
|
: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
recent_activity: normalizeUserRecentActivity(raw.recent_activity) ?? undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeUserSubscriptionRecord(raw: unknown): UserSubscriptionRecord | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = Number(raw.id);
|
||||||
|
const userId = Number(raw.user_id);
|
||||||
|
const planId = Number(raw.plan_id);
|
||||||
|
if (!Number.isFinite(id) || !Number.isFinite(userId) || !Number.isFinite(planId)) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
user_id: userId,
|
||||||
|
plan_id: planId,
|
||||||
|
plan_name: String(raw.plan_name ?? ""),
|
||||||
|
plan_category: String(raw.plan_category ?? ""),
|
||||||
|
starts_at: String(raw.starts_at ?? ""),
|
||||||
|
expires_at: String(raw.expires_at ?? ""),
|
||||||
|
status: String(raw.status ?? ""),
|
||||||
|
payment_reference: String(raw.payment_reference ?? ""),
|
||||||
|
payment_method: String(raw.payment_method ?? ""),
|
||||||
|
auto_renew: raw.auto_renew === true,
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
duration_value: Number(raw.duration_value) || 0,
|
||||||
|
duration_unit: String(raw.duration_unit ?? ""),
|
||||||
|
price: Number(raw.price) || 0,
|
||||||
|
currency: String(raw.currency ?? ""),
|
||||||
|
is_currently_active: raw.is_currently_active === true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeUserSubscriptionPayment(raw: unknown): UserSubscriptionPayment | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const id = Number(raw.id);
|
||||||
|
if (!Number.isFinite(id)) return null;
|
||||||
|
|
||||||
|
const planId = Number(raw.plan_id);
|
||||||
|
const subscriptionId = Number(raw.subscription_id);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
plan_id: Number.isFinite(planId) ? planId : undefined,
|
||||||
|
plan_name: optionalString(raw.plan_name) ?? undefined,
|
||||||
|
subscription_id: Number.isFinite(subscriptionId) ? subscriptionId : undefined,
|
||||||
|
amount: Number(raw.amount) || 0,
|
||||||
|
currency: String(raw.currency ?? ""),
|
||||||
|
payment_method: optionalString(raw.payment_method) ?? undefined,
|
||||||
|
status: String(raw.status ?? ""),
|
||||||
|
paid_at: optionalString(raw.paid_at),
|
||||||
|
expires_at: optionalString(raw.expires_at),
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeUserSubscriptions(raw: unknown): UserSubscriptionsData | null {
|
||||||
|
if (!isRecord(raw)) return null;
|
||||||
|
const userId = Number(raw.user_id);
|
||||||
|
if (!Number.isFinite(userId)) return null;
|
||||||
|
|
||||||
|
const activeByCategoryRaw = isRecord(raw.active_by_category) ? raw.active_by_category : {};
|
||||||
|
const active_by_category: Record<string, boolean> = {};
|
||||||
|
for (const [key, value] of Object.entries(activeByCategoryRaw)) {
|
||||||
|
active_by_category[key] = value === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mapSubscriptions = (value: unknown) =>
|
||||||
|
Array.isArray(value)
|
||||||
|
? value
|
||||||
|
.map((entry) => normalizeUserSubscriptionRecord(entry))
|
||||||
|
.filter((entry): entry is UserSubscriptionRecord => entry !== null)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const payments = Array.isArray(raw.payments)
|
||||||
|
? raw.payments
|
||||||
|
.map((entry) => normalizeUserSubscriptionPayment(entry))
|
||||||
|
.filter((entry): entry is UserSubscriptionPayment => entry !== null)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
user_id: userId,
|
||||||
|
display_status: String(raw.display_status ?? ""),
|
||||||
|
has_active_subscription: raw.has_active_subscription === true,
|
||||||
|
active_by_category,
|
||||||
|
active_subscriptions: mapSubscriptions(raw.active_subscriptions),
|
||||||
|
subscriptions: mapSubscriptions(raw.subscriptions),
|
||||||
|
payments,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/** Query params for GET /users (RFC3339 for created_*; subscription_status: ACTIVE | PENDING | Unsubscribed). */
|
/** Query params for GET /users (RFC3339 for created_*; subscription_status: ACTIVE | PENDING | Unsubscribed). */
|
||||||
export interface GetUsersParams {
|
export interface GetUsersParams {
|
||||||
|
|
@ -59,13 +445,71 @@ export const updateUserStatus = (payload: UpdateUserStatusRequest) =>
|
||||||
http.patch("/user/status", payload);
|
http.patch("/user/status", payload);
|
||||||
|
|
||||||
export const getUserById = (id: number) =>
|
export const getUserById = (id: number) =>
|
||||||
http.get<UserProfileResponse>(`/user/single/${id}`);
|
http.get<UserProfileResponse>(`/user/single/${id}`).then((res) => {
|
||||||
|
const body = res.data;
|
||||||
|
const user = normalizeUserProfile(body?.data);
|
||||||
|
if (!user) {
|
||||||
|
throw new Error("Invalid user profile response");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: {
|
||||||
|
...body,
|
||||||
|
data: user,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
export const getUserRecentActivity = (userId: number) =>
|
export const getUserRecentActivity = (userId: number) =>
|
||||||
http.get<UserRecentActivityResponse>(`/admin/users/${userId}/recent-activity`);
|
http.get<UserRecentActivityResponse>(`/admin/users/${userId}/recent-activity`).then((res) => {
|
||||||
|
const body = res.data;
|
||||||
|
const activity = normalizeUserRecentActivity(body?.data);
|
||||||
|
if (!activity) {
|
||||||
|
throw new Error("Invalid recent activity response");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: {
|
||||||
|
...body,
|
||||||
|
data: activity,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getUserLearningActivity = (userId: number) =>
|
||||||
|
http.get<UserLearningActivityResponse>(`/admin/users/${userId}/learning-activity`).then((res) => {
|
||||||
|
const body = res.data;
|
||||||
|
const activity = normalizeUserLearningActivity(body?.data);
|
||||||
|
if (!activity) {
|
||||||
|
throw new Error("Invalid learning activity response");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: {
|
||||||
|
...body,
|
||||||
|
data: activity,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getUserSubscriptions = (userId: number) =>
|
||||||
|
http.get<UserSubscriptionsResponse>(`/admin/users/${userId}/subscriptions`).then((res) => {
|
||||||
|
const body = res.data;
|
||||||
|
const subscriptions = normalizeUserSubscriptions(body?.data);
|
||||||
|
if (!subscriptions) {
|
||||||
|
throw new Error("Invalid user subscriptions response");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: {
|
||||||
|
...body,
|
||||||
|
data: subscriptions,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
export const getMyProfile = () =>
|
export const getMyProfile = () =>
|
||||||
http.get<UserProfileResponse>("/team/me");
|
http.get<GetTeamMeResponse>("/team/me");
|
||||||
|
|
||||||
// Best-guess API for creating a new user (admin-side).
|
// Best-guess API for creating a new user (admin-side).
|
||||||
// Adjust payload shape or endpoint if backend differs.
|
// Adjust payload shape or endpoint if backend differs.
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,10 @@ import { AboutPage } from "../pages/AboutPage";
|
||||||
import { TermsPage } from "../pages/TermsPage";
|
import { TermsPage } from "../pages/TermsPage";
|
||||||
import { PrivacyPage } from "../pages/PrivacyPage";
|
import { PrivacyPage } from "../pages/PrivacyPage";
|
||||||
import { AccountDeletionPage } from "../pages/AccountDeletionPage";
|
import { AccountDeletionPage } from "../pages/AccountDeletionPage";
|
||||||
|
import { FaqsPage } from "../pages/faqs/FaqsPage";
|
||||||
|
import { EditFaqPage } from "../pages/faqs/EditFaqPage";
|
||||||
|
import { AppReviewsPage } from "../pages/ratings/AppReviewsPage";
|
||||||
|
import { PersonasPage } from "../pages/personas/PersonasPage";
|
||||||
|
|
||||||
export function AppRoutes() {
|
export function AppRoutes() {
|
||||||
return (
|
return (
|
||||||
|
|
@ -287,6 +291,14 @@ export function AppRoutes() {
|
||||||
<Route path="/payments" element={<PaymentsPage />} />
|
<Route path="/payments" element={<PaymentsPage />} />
|
||||||
<Route path="/user-log" element={<UserLogPage />} />
|
<Route path="/user-log" element={<UserLogPage />} />
|
||||||
<Route path="/issues" element={<IssuesPage />} />
|
<Route path="/issues" element={<IssuesPage />} />
|
||||||
|
<Route path="/help/faqs" element={<FaqsPage />} />
|
||||||
|
<Route path="/help/faqs/:id/edit" element={<EditFaqPage />} />
|
||||||
|
<Route path="/app-reviews" element={<AppReviewsPage />} />
|
||||||
|
<Route path="/admin/app-reviews" element={<AppReviewsPage />} />
|
||||||
|
<Route path="/operations/app-reviews" element={<AppReviewsPage />} />
|
||||||
|
<Route path="/ratings" element={<AppReviewsPage />} />
|
||||||
|
<Route path="/personas" element={<PersonasPage />} />
|
||||||
|
<Route path="/admin/personas" element={<PersonasPage />} />
|
||||||
<Route path="/analytics" element={<AnalyticsPage />} />
|
<Route path="/analytics" element={<AnalyticsPage />} />
|
||||||
|
|
||||||
<Route path="/team" element={<TeamManagementPage />} />
|
<Route path="/team" element={<TeamManagementPage />} />
|
||||||
|
|
|
||||||
102
src/components/filters/AdminFiltersPanel.tsx
Normal file
102
src/components/filters/AdminFiltersPanel.tsx
Normal file
|
|
@ -0,0 +1,102 @@
|
||||||
|
import { useEffect, useState, type ReactNode } from "react"
|
||||||
|
import { ChevronDown, SlidersHorizontal, X } from "lucide-react"
|
||||||
|
import { Badge } from "../ui/badge"
|
||||||
|
import { Button } from "../ui/button"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
|
||||||
|
export type AdminFiltersPanelProps = {
|
||||||
|
search?: ReactNode
|
||||||
|
children?: ReactNode
|
||||||
|
/** Renders in place of the show/hide toggle; keeps filters always visible. */
|
||||||
|
actions?: ReactNode
|
||||||
|
activeFilterCount?: number
|
||||||
|
onClearFilters?: () => void
|
||||||
|
clearLabel?: string
|
||||||
|
defaultOpen?: boolean
|
||||||
|
className?: string
|
||||||
|
footer?: ReactNode
|
||||||
|
summary?: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AdminFiltersPanel({
|
||||||
|
search,
|
||||||
|
children,
|
||||||
|
actions,
|
||||||
|
activeFilterCount = 0,
|
||||||
|
onClearFilters,
|
||||||
|
clearLabel = "Clear filters",
|
||||||
|
defaultOpen = false,
|
||||||
|
className,
|
||||||
|
footer,
|
||||||
|
summary,
|
||||||
|
}: AdminFiltersPanelProps) {
|
||||||
|
const [open, setOpen] = useState(defaultOpen || activeFilterCount > 0)
|
||||||
|
const inlineActions = Boolean(actions)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!inlineActions && activeFilterCount > 0) {
|
||||||
|
setOpen(true)
|
||||||
|
}
|
||||||
|
}, [activeFilterCount, inlineActions])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"rounded-xl border border-grayScale-100 bg-white shadow-none",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-3 p-4">
|
||||||
|
{search ? <div className="min-w-[200px] flex-1">{search}</div> : null}
|
||||||
|
{inlineActions ? (
|
||||||
|
<div className="h-9 shrink-0">{actions}</div>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-9 shrink-0 gap-2"
|
||||||
|
onClick={() => setOpen((prev) => !prev)}
|
||||||
|
aria-expanded={open}
|
||||||
|
>
|
||||||
|
<SlidersHorizontal className="h-4 w-4" />
|
||||||
|
{open ? "Hide filters" : "Show filters"}
|
||||||
|
{activeFilterCount > 0 ? (
|
||||||
|
<Badge variant="default" className="px-1.5 py-0 text-[10px]">
|
||||||
|
{activeFilterCount}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
<ChevronDown
|
||||||
|
className={cn("h-4 w-4 transition-transform", open && "rotate-180")}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{activeFilterCount > 0 && onClearFilters ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-9 shrink-0 gap-1 text-grayScale-500"
|
||||||
|
onClick={onClearFilters}
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
{clearLabel}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{summary ? <div className="ml-auto text-xs text-grayScale-500">{summary}</div> : null}
|
||||||
|
</div>
|
||||||
|
{inlineActions ? (
|
||||||
|
footer ? (
|
||||||
|
<div className="border-t border-grayScale-100 px-4 pb-3 pt-2 text-xs text-grayScale-400">
|
||||||
|
{footer}
|
||||||
|
</div>
|
||||||
|
) : null
|
||||||
|
) : open ? (
|
||||||
|
<div className="space-y-3 border-t border-grayScale-100 px-4 pb-4 pt-3">
|
||||||
|
{children}
|
||||||
|
{footer ? <div className="text-xs text-grayScale-400">{footer}</div> : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
96
src/components/notifications/NotificationDeleteDialog.tsx
Normal file
96
src/components/notifications/NotificationDeleteDialog.tsx
Normal file
|
|
@ -0,0 +1,96 @@
|
||||||
|
import { useState } from "react"
|
||||||
|
import { Trash2 } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { deleteNotification } from "../../api/notifications.api"
|
||||||
|
import { Button } from "../ui/button"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../ui/dialog"
|
||||||
|
import { getNotificationTitle, type Notification } from "../../types/notification.types"
|
||||||
|
|
||||||
|
type NotificationDeleteDialogProps = {
|
||||||
|
notification: Notification | null
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
onDeleted?: (id: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function NotificationDeleteDialog({
|
||||||
|
notification,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onDeleted,
|
||||||
|
}: NotificationDeleteDialogProps) {
|
||||||
|
const [deleting, setDeleting] = useState(false)
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next && !deleting) onOpenChange(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleConfirm = async () => {
|
||||||
|
if (!notification) return
|
||||||
|
|
||||||
|
setDeleting(true)
|
||||||
|
try {
|
||||||
|
const response = await deleteNotification(notification.id)
|
||||||
|
toast.success(response.message || "Notification deleted")
|
||||||
|
onOpenChange(false)
|
||||||
|
onDeleted?.(notification.id)
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const msg =
|
||||||
|
(e as { response?: { data?: { message?: string; error?: string } } })?.response
|
||||||
|
?.data?.error ??
|
||||||
|
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
|
||||||
|
"Failed to delete notification"
|
||||||
|
toast.error(msg)
|
||||||
|
} finally {
|
||||||
|
setDeleting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="max-w-md rounded-2xl border-grayScale-200 sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||||
|
<Trash2 className="h-5 w-5 shrink-0 text-destructive" aria-hidden />
|
||||||
|
Delete notification?
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-left text-grayScale-600">
|
||||||
|
This permanently removes the notification from your inbox.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{notification ? (
|
||||||
|
<div className="space-y-1 rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3">
|
||||||
|
<p className="line-clamp-2 text-sm font-semibold text-grayScale-900">
|
||||||
|
{getNotificationTitle(notification) || "Notification"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-grayScale-500">#{notification.id}</p>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<DialogFooter className="gap-2 sm:gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={deleting}
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
disabled={deleting || !notification}
|
||||||
|
onClick={() => void handleConfirm()}
|
||||||
|
>
|
||||||
|
{deleting ? "Deleting…" : "Delete"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -4,6 +4,7 @@ import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
DialogDescription,
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../ui/dialog"
|
} from "../ui/dialog"
|
||||||
|
|
@ -26,6 +27,7 @@ type NotificationDetailDialogProps = {
|
||||||
loading?: boolean
|
loading?: boolean
|
||||||
error?: boolean
|
error?: boolean
|
||||||
onRetry?: () => void
|
onRetry?: () => void
|
||||||
|
onDelete?: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NotificationDetailDialog({
|
export function NotificationDetailDialog({
|
||||||
|
|
@ -35,6 +37,7 @@ export function NotificationDetailDialog({
|
||||||
loading = false,
|
loading = false,
|
||||||
error = false,
|
error = false,
|
||||||
onRetry,
|
onRetry,
|
||||||
|
onDelete,
|
||||||
}: NotificationDetailDialogProps) {
|
}: NotificationDetailDialogProps) {
|
||||||
const config = notification
|
const config = notification
|
||||||
? NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
|
? NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
|
||||||
|
|
@ -161,6 +164,14 @@ export function NotificationDetailDialog({
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{onDelete ? (
|
||||||
|
<DialogFooter className="gap-2 sm:gap-2">
|
||||||
|
<Button variant="destructive" onClick={onDelete}>
|
||||||
|
Delete notification
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
) : null}
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|
|
||||||
132
src/components/profile/ProfileAvatarUpload.tsx
Normal file
132
src/components/profile/ProfileAvatarUpload.tsx
Normal file
|
|
@ -0,0 +1,132 @@
|
||||||
|
import { useCallback, useRef, useState, type ChangeEvent } from "react"
|
||||||
|
import { Camera } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { uploadImageFile } from "../../api/files.api"
|
||||||
|
import { updateTeamMe } from "../../api/team.api"
|
||||||
|
import { SpinnerIcon } from "../ui/spinner-icon"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
import type { TeamMeProfile } from "../../types/team.types"
|
||||||
|
|
||||||
|
const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||||
|
const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp"])
|
||||||
|
|
||||||
|
function isAllowedImageFile(file: File): boolean {
|
||||||
|
if (ALLOWED_IMAGE_TYPES.has(file.type)) return true
|
||||||
|
const name = file.name.toLowerCase()
|
||||||
|
return /\.(jpe?g|png|webp)$/.test(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProfileAvatarUploadProps = {
|
||||||
|
avatarUrl?: string | null
|
||||||
|
initials: string
|
||||||
|
onProfileUpdate: (profile: TeamMeProfile) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProfileAvatarUpload({
|
||||||
|
avatarUrl,
|
||||||
|
initials,
|
||||||
|
onProfileUpdate,
|
||||||
|
}: ProfileAvatarUploadProps) {
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
const [uploading, setUploading] = useState(false)
|
||||||
|
|
||||||
|
const processFile = useCallback(
|
||||||
|
async (file: File) => {
|
||||||
|
if (uploading) return
|
||||||
|
if (!isAllowedImageFile(file)) {
|
||||||
|
toast.error("Please use a JPG, PNG, or WEBP image.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (file.size > MAX_IMAGE_BYTES) {
|
||||||
|
toast.error("Image is too large", { description: "Maximum size is 5 MB." })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setUploading(true)
|
||||||
|
try {
|
||||||
|
const uploadRes = await uploadImageFile(file)
|
||||||
|
const uploadedUrl = uploadRes.data?.data?.url?.trim()
|
||||||
|
if (!uploadedUrl) throw new Error("Upload did not return a file URL")
|
||||||
|
|
||||||
|
const updateRes = await updateTeamMe({ profile_picture_url: uploadedUrl })
|
||||||
|
onProfileUpdate(updateRes.data.data)
|
||||||
|
toast.success(updateRes.data.message || "Profile picture updated")
|
||||||
|
} catch (err: unknown) {
|
||||||
|
console.error(err)
|
||||||
|
const uploadMsg =
|
||||||
|
(err as { response?: { data?: { message?: string } } })?.response?.data
|
||||||
|
?.message
|
||||||
|
toast.error(uploadMsg ?? "Failed to update profile picture")
|
||||||
|
} finally {
|
||||||
|
setUploading(false)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[onProfileUpdate, uploading],
|
||||||
|
)
|
||||||
|
|
||||||
|
const handleFileInputChange = (e: ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0]
|
||||||
|
e.target.value = ""
|
||||||
|
if (file) void processFile(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
const trimmedUrl = avatarUrl?.trim()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/jpeg,image/png,image/webp,.jpg,.jpeg,.png,.webp"
|
||||||
|
className="sr-only"
|
||||||
|
onChange={handleFileInputChange}
|
||||||
|
disabled={uploading}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Upload profile picture"
|
||||||
|
disabled={uploading}
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
className={cn(
|
||||||
|
"group relative h-24 w-24 shrink-0 overflow-hidden rounded-full border-4 border-white shadow-sm",
|
||||||
|
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2",
|
||||||
|
uploading && "cursor-wait",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{trimmedUrl ? (
|
||||||
|
<img
|
||||||
|
src={trimmedUrl}
|
||||||
|
alt=""
|
||||||
|
className="h-full w-full object-cover"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<span className="flex h-full w-full items-center justify-center bg-brand-100 text-2xl font-bold text-brand-700">
|
||||||
|
{initials || "?"}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"absolute inset-0 flex items-center justify-center rounded-full bg-black/45",
|
||||||
|
"opacity-0 transition-opacity duration-200 ease-out",
|
||||||
|
"group-hover:opacity-100 group-focus-visible:opacity-100",
|
||||||
|
uploading && "opacity-100",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<SpinnerIcon className="h-6 w-6 text-white" />
|
||||||
|
) : (
|
||||||
|
<Camera
|
||||||
|
className={cn(
|
||||||
|
"h-6 w-6 text-white",
|
||||||
|
"scale-75 opacity-0 transition-all duration-200 ease-out",
|
||||||
|
"group-hover:scale-100 group-hover:opacity-100",
|
||||||
|
"group-focus-visible:scale-100 group-focus-visible:opacity-100",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -5,13 +5,16 @@ import {
|
||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
CircleAlert,
|
CircleAlert,
|
||||||
|
CircleHelp,
|
||||||
ClipboardList,
|
ClipboardList,
|
||||||
CreditCard,
|
CreditCard,
|
||||||
LayoutDashboard,
|
LayoutDashboard,
|
||||||
LogOut,
|
LogOut,
|
||||||
UserCircle2,
|
UserCircle2,
|
||||||
Users,
|
Users,
|
||||||
|
UsersRound,
|
||||||
Settings,
|
Settings,
|
||||||
|
Star,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { type ComponentType, useEffect, useState } from "react";
|
import { type ComponentType, useEffect, useState } from "react";
|
||||||
|
|
@ -19,6 +22,10 @@ import { NavLink } from "react-router-dom";
|
||||||
import { cn } from "../../lib/utils";
|
import { cn } from "../../lib/utils";
|
||||||
import { BrandLogo } from "../brand/BrandLogo";
|
import { BrandLogo } from "../brand/BrandLogo";
|
||||||
import { getUnreadCount } from "../../api/notifications.api";
|
import { getUnreadCount } from "../../api/notifications.api";
|
||||||
|
import { useTeamPermissions } from "../../hooks/useTeamPermissions";
|
||||||
|
import { hasFaqPermission } from "../../lib/faqPermissions";
|
||||||
|
import { hasRatingsPermission } from "../../lib/ratingsPermissions";
|
||||||
|
import { hasPersonaPermission } from "../../lib/personasPermissions";
|
||||||
import { SidebarNavGroup } from "./SidebarNavGroup";
|
import { SidebarNavGroup } from "./SidebarNavGroup";
|
||||||
|
|
||||||
type NavLinkItem = {
|
type NavLinkItem = {
|
||||||
|
|
@ -26,6 +33,7 @@ type NavLinkItem = {
|
||||||
label: string;
|
label: string;
|
||||||
to: string;
|
to: string;
|
||||||
icon: ComponentType<{ className?: string }>;
|
icon: ComponentType<{ className?: string }>;
|
||||||
|
permission?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type NavGroupItem = {
|
type NavGroupItem = {
|
||||||
|
|
@ -77,6 +85,13 @@ const navEntries: NavEntry[] = [
|
||||||
{ label: "Question types", to: "/new-content/question-types" },
|
{ label: "Question types", to: "/new-content/question-types" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
kind: "link",
|
||||||
|
label: "Personas",
|
||||||
|
to: "/personas",
|
||||||
|
icon: UsersRound,
|
||||||
|
permission: "personas.list",
|
||||||
|
},
|
||||||
|
|
||||||
{ kind: "section", label: "Communications" },
|
{ kind: "section", label: "Communications" },
|
||||||
{
|
{
|
||||||
|
|
@ -96,6 +111,20 @@ const navEntries: NavEntry[] = [
|
||||||
{ kind: "link", label: "Payments", to: "/payments", icon: CreditCard },
|
{ kind: "link", label: "Payments", to: "/payments", icon: CreditCard },
|
||||||
{ kind: "link", label: "User activity log", to: "/user-log", icon: ClipboardList },
|
{ kind: "link", label: "User activity log", to: "/user-log", icon: ClipboardList },
|
||||||
{ kind: "link", label: "Issue reports", to: "/issues", icon: CircleAlert },
|
{ kind: "link", label: "Issue reports", to: "/issues", icon: CircleAlert },
|
||||||
|
{
|
||||||
|
kind: "link",
|
||||||
|
label: "FAQs",
|
||||||
|
to: "/help/faqs",
|
||||||
|
icon: CircleHelp,
|
||||||
|
permission: "faqs.list",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "link",
|
||||||
|
label: "App reviews",
|
||||||
|
to: "/app-reviews",
|
||||||
|
icon: Star,
|
||||||
|
permission: "ratings.list_by_target",
|
||||||
|
},
|
||||||
|
|
||||||
{ kind: "section", label: "Account" },
|
{ kind: "section", label: "Account" },
|
||||||
{ kind: "link", label: "Profile", to: "/profile", icon: UserCircle2 },
|
{ kind: "link", label: "Profile", to: "/profile", icon: UserCircle2 },
|
||||||
|
|
@ -115,6 +144,7 @@ export function Sidebar({
|
||||||
onToggleCollapse,
|
onToggleCollapse,
|
||||||
onClose,
|
onClose,
|
||||||
}: SidebarProps) {
|
}: SidebarProps) {
|
||||||
|
const { permissions, hasPermission, loading: permissionsLoading } = useTeamPermissions();
|
||||||
const [unreadCount, setUnreadCount] = useState(0);
|
const [unreadCount, setUnreadCount] = useState(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -226,6 +256,40 @@ export function Sidebar({
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (entry.kind === "link") {
|
||||||
|
if (
|
||||||
|
entry.permission === "faqs.list" &&
|
||||||
|
!permissionsLoading &&
|
||||||
|
!hasFaqPermission("faqs.list", permissions)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
entry.permission === "ratings.list_by_target" &&
|
||||||
|
!permissionsLoading &&
|
||||||
|
!hasRatingsPermission("ratings.list_by_target", permissions)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
entry.permission === "personas.list" &&
|
||||||
|
!permissionsLoading &&
|
||||||
|
!hasPersonaPermission("personas.list", permissions)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
entry.permission &&
|
||||||
|
entry.permission !== "faqs.list" &&
|
||||||
|
entry.permission !== "ratings.list_by_target" &&
|
||||||
|
entry.permission !== "personas.list" &&
|
||||||
|
!permissionsLoading &&
|
||||||
|
!hasPermission(entry.permission)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (entry.kind === "group") {
|
if (entry.kind === "group") {
|
||||||
const isNotifications = entry.basePath === "/notifications";
|
const isNotifications = entry.basePath === "/notifications";
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { useCallback, useEffect, useRef, useState } from "react"
|
import { useCallback, useEffect, useRef, useState } from "react"
|
||||||
import { useNavigate } from "react-router-dom"
|
import { useNavigate } from "react-router-dom"
|
||||||
import { Bell, BellOff, CheckCheck, Mail, MailOpen } from "lucide-react"
|
import { Bell, BellOff, CheckCheck, Mail, MailOpen, Trash2 } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { Badge } from "../ui/badge"
|
import { Badge } from "../ui/badge"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
|
|
@ -8,6 +8,7 @@ import { SpinnerIcon } from "../ui/spinner-icon"
|
||||||
import { getNotificationById } from "../../api/notifications.api"
|
import { getNotificationById } from "../../api/notifications.api"
|
||||||
import { useNotifications } from "../../hooks/useNotifications"
|
import { useNotifications } from "../../hooks/useNotifications"
|
||||||
import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog"
|
import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog"
|
||||||
|
import { NotificationDeleteDialog } from "../notifications/NotificationDeleteDialog"
|
||||||
import {
|
import {
|
||||||
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
||||||
formatNotificationTimestamp,
|
formatNotificationTimestamp,
|
||||||
|
|
@ -20,11 +21,13 @@ function NotificationItem({
|
||||||
onOpen,
|
onOpen,
|
||||||
onMarkRead,
|
onMarkRead,
|
||||||
onMarkUnread,
|
onMarkUnread,
|
||||||
|
onDelete,
|
||||||
}: {
|
}: {
|
||||||
notification: Notification
|
notification: Notification
|
||||||
onOpen: (notification: Notification) => void
|
onOpen: (notification: Notification) => void
|
||||||
onMarkRead: (id: string) => void
|
onMarkRead: (id: string) => void
|
||||||
onMarkUnread: (id: string) => void
|
onMarkUnread: (id: string) => void
|
||||||
|
onDelete: (notification: Notification) => void
|
||||||
}) {
|
}) {
|
||||||
const cfg = NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
|
const cfg = NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
|
||||||
const Icon = cfg.icon
|
const Icon = cfg.icon
|
||||||
|
|
@ -86,6 +89,17 @@ function NotificationItem({
|
||||||
<MailOpen className="h-4 w-4" />
|
<MailOpen className="h-4 w-4" />
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="hidden shrink-0 self-center rounded-md p-1.5 text-destructive hover:bg-destructive/10 group-hover:block"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
onDelete(notification)
|
||||||
|
}}
|
||||||
|
aria-label="Delete notification"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -97,6 +111,7 @@ export function NotificationDropdown() {
|
||||||
const [detailError, setDetailError] = useState(false)
|
const [detailError, setDetailError] = useState(false)
|
||||||
const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null)
|
const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null)
|
||||||
const [selectedNotificationId, setSelectedNotificationId] = useState<string | null>(null)
|
const [selectedNotificationId, setSelectedNotificationId] = useState<string | null>(null)
|
||||||
|
const [notificationPendingDelete, setNotificationPendingDelete] = useState<Notification | null>(null)
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
const containerRef = useRef<HTMLDivElement>(null)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const {
|
const {
|
||||||
|
|
@ -106,6 +121,7 @@ export function NotificationDropdown() {
|
||||||
markOneRead,
|
markOneRead,
|
||||||
markOneUnread,
|
markOneUnread,
|
||||||
markAllAsRead,
|
markAllAsRead,
|
||||||
|
refresh,
|
||||||
} = useNotifications()
|
} = useNotifications()
|
||||||
|
|
||||||
const loadNotificationDetail = useCallback(async (id: string, markReadIfNeeded: boolean) => {
|
const loadNotificationDetail = useCallback(async (id: string, markReadIfNeeded: boolean) => {
|
||||||
|
|
@ -142,6 +158,16 @@ export function NotificationDropdown() {
|
||||||
[loadNotificationDetail],
|
[loadNotificationDetail],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const handleNotificationDeleted = useCallback((id: string) => {
|
||||||
|
if (selectedNotificationId === id) {
|
||||||
|
setDetailOpen(false)
|
||||||
|
setSelectedNotification(null)
|
||||||
|
setSelectedNotificationId(null)
|
||||||
|
}
|
||||||
|
setNotificationPendingDelete(null)
|
||||||
|
refresh()
|
||||||
|
}, [selectedNotificationId, refresh])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
function handleMouseDown(e: MouseEvent) {
|
function handleMouseDown(e: MouseEvent) {
|
||||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||||
|
|
@ -213,6 +239,10 @@ export function NotificationDropdown() {
|
||||||
onOpen={handleOpenNotification}
|
onOpen={handleOpenNotification}
|
||||||
onMarkRead={markOneRead}
|
onMarkRead={markOneRead}
|
||||||
onMarkUnread={markOneUnread}
|
onMarkUnread={markOneUnread}
|
||||||
|
onDelete={(notification) => {
|
||||||
|
setOpen(false)
|
||||||
|
setNotificationPendingDelete(notification)
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -246,6 +276,20 @@ export function NotificationDropdown() {
|
||||||
? () => void loadNotificationDetail(selectedNotificationId, false)
|
? () => void loadNotificationDetail(selectedNotificationId, false)
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
|
onDelete={
|
||||||
|
selectedNotification
|
||||||
|
? () => setNotificationPendingDelete(selectedNotification)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<NotificationDeleteDialog
|
||||||
|
notification={notificationPendingDelete}
|
||||||
|
open={notificationPendingDelete !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setNotificationPendingDelete(null)
|
||||||
|
}}
|
||||||
|
onDeleted={handleNotificationDeleted}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
54
src/components/ui/toggle-switch.tsx
Normal file
54
src/components/ui/toggle-switch.tsx
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
|
||||||
|
export type ToggleSwitchProps = {
|
||||||
|
checked: boolean
|
||||||
|
onCheckedChange?: () => void
|
||||||
|
disabled?: boolean
|
||||||
|
"aria-label"?: string
|
||||||
|
className?: string
|
||||||
|
variant?: "brand" | "plain"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ToggleSwitch({
|
||||||
|
checked,
|
||||||
|
onCheckedChange,
|
||||||
|
disabled = false,
|
||||||
|
"aria-label": ariaLabel,
|
||||||
|
className,
|
||||||
|
variant = "brand",
|
||||||
|
}: ToggleSwitchProps) {
|
||||||
|
const isBrand = variant === "brand"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="switch"
|
||||||
|
aria-checked={checked}
|
||||||
|
aria-label={ariaLabel}
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={onCheckedChange}
|
||||||
|
className={cn(
|
||||||
|
"relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full transition-all duration-200",
|
||||||
|
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-1",
|
||||||
|
isBrand && "border p-0.5",
|
||||||
|
isBrand
|
||||||
|
? checked
|
||||||
|
? "border-brand-500 bg-brand-500 shadow-[0_4px_12px_rgba(168,85,247,0.3)]"
|
||||||
|
: "border-grayScale-300 bg-grayScale-200 hover:bg-grayScale-300/80"
|
||||||
|
: checked
|
||||||
|
? "bg-brand-500"
|
||||||
|
: "bg-grayScale-200",
|
||||||
|
disabled && "cursor-not-allowed opacity-60",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"pointer-events-none inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform duration-200 ease-out",
|
||||||
|
isBrand ? "shadow-md ring-0" : "shadow-sm",
|
||||||
|
checked ? "translate-x-4" : isBrand ? "translate-x-0" : "translate-x-0.5",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -1,18 +1,13 @@
|
||||||
import { useCallback, useEffect, useState } from "react"
|
import { useCallback, useEffect, useState } from "react"
|
||||||
import { getPersonas } from "../api/personas.api"
|
import { listActivePersonasForPicker } from "../api/personas.api"
|
||||||
import {
|
import { mapPersonaToCard, type PersonaCardModel } from "../lib/personaDisplay"
|
||||||
mapPersonaToCard,
|
|
||||||
unwrapPersonasList,
|
|
||||||
type PersonaCardModel,
|
|
||||||
} from "../lib/personaDisplay"
|
|
||||||
|
|
||||||
type UseActivePersonasOptions = {
|
type UseActivePersonasOptions = {
|
||||||
limit?: number
|
limit?: number
|
||||||
offset?: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useActivePersonas(options: UseActivePersonasOptions = {}) {
|
export function useActivePersonas(options: UseActivePersonasOptions = {}) {
|
||||||
const { limit = 50, offset = 0 } = options
|
const { limit = 200 } = options
|
||||||
const [personas, setPersonas] = useState<PersonaCardModel[]>([])
|
const [personas, setPersonas] = useState<PersonaCardModel[]>([])
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
@ -21,8 +16,7 @@ export function useActivePersonas(options: UseActivePersonasOptions = {}) {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
try {
|
try {
|
||||||
const res = await getPersonas({ limit, offset })
|
const list = await listActivePersonasForPicker(limit)
|
||||||
const list = unwrapPersonasList(res).filter((p) => p.is_active)
|
|
||||||
setPersonas(list.map(mapPersonaToCard))
|
setPersonas(list.map(mapPersonaToCard))
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const msg =
|
const msg =
|
||||||
|
|
@ -33,7 +27,7 @@ export function useActivePersonas(options: UseActivePersonasOptions = {}) {
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [limit, offset])
|
}, [limit])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load()
|
void load()
|
||||||
|
|
|
||||||
39
src/hooks/useFaqPermissions.ts
Normal file
39
src/hooks/useFaqPermissions.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { useMemo } from "react"
|
||||||
|
import { hasFaqPermission } from "../lib/faqPermissions"
|
||||||
|
import { useTeamPermissions } from "./useTeamPermissions"
|
||||||
|
|
||||||
|
export function useFaqPermissions() {
|
||||||
|
const { permissions, loading, reload } = useTeamPermissions()
|
||||||
|
|
||||||
|
const canList = useMemo(
|
||||||
|
() => hasFaqPermission("faqs.list", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canGet = useMemo(
|
||||||
|
() => hasFaqPermission("faqs.get", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canCreate = useMemo(
|
||||||
|
() => hasFaqPermission("faqs.create", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canUpdate = useMemo(
|
||||||
|
() => hasFaqPermission("faqs.update", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canDelete = useMemo(
|
||||||
|
() => hasFaqPermission("faqs.delete", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
permissions,
|
||||||
|
loading,
|
||||||
|
reload,
|
||||||
|
canList,
|
||||||
|
canGet,
|
||||||
|
canCreate,
|
||||||
|
canUpdate,
|
||||||
|
canDelete,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { useEffect, useState, useCallback, useRef } from "react"
|
import { useEffect, useState, useCallback, useRef } from "react"
|
||||||
import { getNotifications, getUnreadCount, markAsRead, markAsUnread, markAllRead } from "../api/notifications.api"
|
import { getNotifications, getUnreadCount, markAsRead, markAsUnread, markAllRead, deleteNotification } from "../api/notifications.api"
|
||||||
import type { Notification } from "../types/notification.types"
|
import type { Notification } from "../types/notification.types"
|
||||||
|
|
||||||
const MAX_DROPDOWN = 5
|
const MAX_DROPDOWN = 5
|
||||||
|
|
@ -167,6 +167,21 @@ export function useNotifications() {
|
||||||
}
|
}
|
||||||
}, [fetchData])
|
}, [fetchData])
|
||||||
|
|
||||||
|
const deleteOne = useCallback(async (id: string) => {
|
||||||
|
const removed = notifications.find((n) => n.id === id)
|
||||||
|
setNotifications((prev) => prev.filter((n) => n.id !== id))
|
||||||
|
if (removed && !removed.is_read) {
|
||||||
|
setUnreadCount((prev) => Math.max(0, prev - 1))
|
||||||
|
}
|
||||||
|
dispatchUpdate()
|
||||||
|
try {
|
||||||
|
await deleteNotification(id)
|
||||||
|
} catch {
|
||||||
|
await fetchData()
|
||||||
|
throw new Error("delete failed")
|
||||||
|
}
|
||||||
|
}, [notifications, fetchData])
|
||||||
|
|
||||||
const refresh = useCallback(() => {
|
const refresh = useCallback(() => {
|
||||||
fetchData()
|
fetchData()
|
||||||
}, [fetchData])
|
}, [fetchData])
|
||||||
|
|
@ -178,6 +193,7 @@ export function useNotifications() {
|
||||||
markOneRead,
|
markOneRead,
|
||||||
markOneUnread,
|
markOneUnread,
|
||||||
markAllAsRead,
|
markAllAsRead,
|
||||||
|
deleteOne,
|
||||||
refresh,
|
refresh,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
39
src/hooks/usePersonaPermissions.ts
Normal file
39
src/hooks/usePersonaPermissions.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { useMemo } from "react"
|
||||||
|
import { hasPersonaPermission } from "../lib/personasPermissions"
|
||||||
|
import { useTeamPermissions } from "./useTeamPermissions"
|
||||||
|
|
||||||
|
export function usePersonaPermissions() {
|
||||||
|
const { permissions, loading, reload } = useTeamPermissions()
|
||||||
|
|
||||||
|
const canList = useMemo(
|
||||||
|
() => hasPersonaPermission("personas.list", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canGet = useMemo(
|
||||||
|
() => hasPersonaPermission("personas.get", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canCreate = useMemo(
|
||||||
|
() => hasPersonaPermission("personas.create", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canUpdate = useMemo(
|
||||||
|
() => hasPersonaPermission("personas.update", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canDelete = useMemo(
|
||||||
|
() => hasPersonaPermission("personas.delete", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
permissions,
|
||||||
|
loading,
|
||||||
|
reload,
|
||||||
|
canList,
|
||||||
|
canGet,
|
||||||
|
canCreate,
|
||||||
|
canUpdate,
|
||||||
|
canDelete,
|
||||||
|
}
|
||||||
|
}
|
||||||
24
src/hooks/useRatingsPermissions.ts
Normal file
24
src/hooks/useRatingsPermissions.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { useMemo } from "react"
|
||||||
|
import { hasRatingsPermission } from "../lib/ratingsPermissions"
|
||||||
|
import { useTeamPermissions } from "./useTeamPermissions"
|
||||||
|
|
||||||
|
export function useRatingsPermissions() {
|
||||||
|
const { permissions, loading, reload } = useTeamPermissions()
|
||||||
|
|
||||||
|
const canList = useMemo(
|
||||||
|
() => hasRatingsPermission("ratings.list_by_target", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
const canSummary = useMemo(
|
||||||
|
() => hasRatingsPermission("ratings.summary", permissions),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
permissions,
|
||||||
|
loading,
|
||||||
|
reload,
|
||||||
|
canList,
|
||||||
|
canSummary,
|
||||||
|
}
|
||||||
|
}
|
||||||
32
src/hooks/useTeamPermissions.ts
Normal file
32
src/hooks/useTeamPermissions.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
import { useCallback, useEffect, useState } from "react"
|
||||||
|
import { getMyProfile } from "../api/users.api"
|
||||||
|
import type { TeamMeProfile } from "../types/team.types"
|
||||||
|
|
||||||
|
export function useTeamPermissions() {
|
||||||
|
const [permissions, setPermissions] = useState<string[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
const res = await getMyProfile()
|
||||||
|
const profile = res.data?.data as TeamMeProfile & { permissions?: string[] }
|
||||||
|
setPermissions(Array.isArray(profile?.permissions) ? profile.permissions : [])
|
||||||
|
} catch {
|
||||||
|
setPermissions([])
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
const hasPermission = useCallback(
|
||||||
|
(key: string) => permissions.includes(key),
|
||||||
|
[permissions],
|
||||||
|
)
|
||||||
|
|
||||||
|
return { permissions, loading, hasPermission, reload: load }
|
||||||
|
}
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { getTeamMemberById } from "../api/team.api"
|
import { getTeamMemberById } from "../api/team.api"
|
||||||
import { getUserById } from "../api/users.api"
|
import { getUserById } from "../api/users.api"
|
||||||
import { TEAM_ROLE_OPTIONS, formatTeamRoleLabel } from "./teamRoles"
|
import { TEAM_ROLE_OPTIONS, formatTeamRoleLabel } from "./teamRoles"
|
||||||
import type { TeamMember } from "../types/team.types"
|
import type { TeamMember, TeamMemberDetail } from "../types/team.types"
|
||||||
import type { UserProfileData } from "../types/user.types"
|
import type { UserProfileData } from "../types/user.types"
|
||||||
|
|
||||||
const TEAM_ROLE_VALUES = new Set(
|
const TEAM_ROLE_VALUES = new Set(
|
||||||
|
|
@ -51,7 +51,12 @@ export function resolveActorKind(actorRole: string | null | undefined): ActorPro
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
function teamMemberToProfile(member: TeamMember): ActorProfile {
|
function teamMemberToProfile(
|
||||||
|
member: Pick<
|
||||||
|
TeamMember | TeamMemberDetail,
|
||||||
|
"id" | "first_name" | "last_name" | "email" | "team_role" | "status" | "email_verified" | "created_at"
|
||||||
|
>,
|
||||||
|
): ActorProfile {
|
||||||
return {
|
return {
|
||||||
kind: "team",
|
kind: "team",
|
||||||
id: member.id,
|
id: member.id,
|
||||||
|
|
|
||||||
22
src/lib/adminFilterUtils.ts
Normal file
22
src/lib/adminFilterUtils.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
type FilterEntry = {
|
||||||
|
value: unknown
|
||||||
|
defaultValue?: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
function isActiveFilterValue(value: unknown, defaultValue: unknown): boolean {
|
||||||
|
if (value === defaultValue) return false
|
||||||
|
if (value == null) return false
|
||||||
|
if (typeof value === "string") {
|
||||||
|
const trimmed = value.trim()
|
||||||
|
if (!trimmed) return false
|
||||||
|
if (trimmed === "all" || trimmed === "All") return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Count how many filters differ from their default / empty state. */
|
||||||
|
export function countActiveFilters(entries: FilterEntry[]): number {
|
||||||
|
return entries.filter(({ value, defaultValue = "" }) =>
|
||||||
|
isActiveFilterValue(value, defaultValue),
|
||||||
|
).length
|
||||||
|
}
|
||||||
39
src/lib/faqDisplay.ts
Normal file
39
src/lib/faqDisplay.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
import type { FAQ, FAQStatus } from "../types/faq.types"
|
||||||
|
|
||||||
|
export function faqStatusBadgeVariant(status: string): "success" | "secondary" {
|
||||||
|
const normalized = status.toUpperCase()
|
||||||
|
if (normalized === "ACTIVE") return "success"
|
||||||
|
return "secondary"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function faqStatusLabel(status: FAQStatus | string): string {
|
||||||
|
const normalized = status.toUpperCase()
|
||||||
|
if (normalized === "ACTIVE") return "Published"
|
||||||
|
if (normalized === "INACTIVE") return "Draft"
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatFaqDate(raw: string | null | undefined): string {
|
||||||
|
if (raw == null || String(raw).trim() === "") {
|
||||||
|
return "—"
|
||||||
|
}
|
||||||
|
const text = String(raw)
|
||||||
|
const parsed = new Date(text)
|
||||||
|
if (Number.isNaN(parsed.getTime())) {
|
||||||
|
return text.split(" +")[0]?.trim() || text
|
||||||
|
}
|
||||||
|
return parsed.toLocaleString(undefined, {
|
||||||
|
dateStyle: "medium",
|
||||||
|
timeStyle: "short",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deriveFaqCategories(faqs: FAQ[]): string[] {
|
||||||
|
return [...new Set(faqs.map((f) => f.category).filter(Boolean) as string[])].sort()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function suggestNextDisplayOrder(faqs: FAQ[]): number {
|
||||||
|
if (faqs.length === 0) return 1
|
||||||
|
const max = Math.max(...faqs.map((f) => f.display_order ?? 0))
|
||||||
|
return max + 1
|
||||||
|
}
|
||||||
12
src/lib/faqErrors.ts
Normal file
12
src/lib/faqErrors.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
export function getFaqApiErrorMessage(error: unknown, fallback: string): string {
|
||||||
|
const data = (error as { response?: { data?: { message?: string; error?: string } } })
|
||||||
|
?.response?.data
|
||||||
|
return data?.error ?? data?.message ?? fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isFaqForbiddenError(error: unknown): boolean {
|
||||||
|
return (error as { response?: { status?: number } })?.response?.status === 403
|
||||||
|
}
|
||||||
|
|
||||||
|
export const FAQ_FORBIDDEN_MESSAGE =
|
||||||
|
"You don't have permission to access this resource"
|
||||||
26
src/lib/faqPermissions.ts
Normal file
26
src/lib/faqPermissions.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
/** Team roles whose JWT maps to ADMIN/SUPER_ADMIN and bypass FAQ permission checks. */
|
||||||
|
const FAQ_BYPASS_TEAM_ROLES = new Set([
|
||||||
|
"SUPER_ADMIN",
|
||||||
|
"ADMIN",
|
||||||
|
"CONTENT_MANAGER",
|
||||||
|
"FINANCE",
|
||||||
|
"HR",
|
||||||
|
"ANALYST",
|
||||||
|
])
|
||||||
|
|
||||||
|
export function getSessionTeamRole(): string {
|
||||||
|
return localStorage.getItem("role")?.trim() ?? ""
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasFaqRoleBypass(): boolean {
|
||||||
|
const role = getSessionTeamRole().toUpperCase()
|
||||||
|
return FAQ_BYPASS_TEAM_ROLES.has(role)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasFaqPermission(
|
||||||
|
permission: string,
|
||||||
|
permissions: string[],
|
||||||
|
): boolean {
|
||||||
|
if (hasFaqRoleBypass()) return true
|
||||||
|
return permissions.includes(permission)
|
||||||
|
}
|
||||||
|
|
@ -41,6 +41,26 @@ export function mapPersonaToCard(persona: PersonaListItem): PersonaCardModel {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function formatPersonaDate(dateStr: string | null | undefined): string {
|
||||||
|
if (!dateStr?.trim()) return "—"
|
||||||
|
const d = new Date(dateStr)
|
||||||
|
if (Number.isNaN(d.getTime())) return dateStr
|
||||||
|
return d.toLocaleDateString(undefined, {
|
||||||
|
year: "numeric",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function personaStatusLabel(isActive: boolean): string {
|
||||||
|
return isActive ? "Active" : "Inactive"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function personaGenderLabel(gender: string | null | undefined): string {
|
||||||
|
const value = gender?.trim()
|
||||||
|
return value ? value : "—"
|
||||||
|
}
|
||||||
|
|
||||||
export function unwrapPersonasList(
|
export function unwrapPersonasList(
|
||||||
res: { data?: GetPersonasResponse & { Data?: GetPersonasResponse["data"] } },
|
res: { data?: GetPersonasResponse & { Data?: GetPersonasResponse["data"] } },
|
||||||
): PersonaListItem[] {
|
): PersonaListItem[] {
|
||||||
|
|
|
||||||
12
src/lib/personasErrors.ts
Normal file
12
src/lib/personasErrors.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
export function getPersonaApiErrorMessage(error: unknown, fallback: string): string {
|
||||||
|
const data = (error as { response?: { data?: { message?: string; error?: string } } })
|
||||||
|
?.response?.data
|
||||||
|
return data?.error ?? data?.message ?? fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPersonaForbiddenError(error: unknown): boolean {
|
||||||
|
return (error as { response?: { status?: number } })?.response?.status === 403
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PERSONAS_FORBIDDEN_MESSAGE =
|
||||||
|
"You don't have permission to access the persona catalog"
|
||||||
18
src/lib/personasPermissions.ts
Normal file
18
src/lib/personasPermissions.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
const PERSONAS_BYPASS_TEAM_ROLES = new Set(["SUPER_ADMIN", "ADMIN"])
|
||||||
|
|
||||||
|
export function getSessionTeamRole(): string {
|
||||||
|
return localStorage.getItem("role")?.trim() ?? ""
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasPersonasRoleBypass(): boolean {
|
||||||
|
const role = getSessionTeamRole().toUpperCase()
|
||||||
|
return PERSONAS_BYPASS_TEAM_ROLES.has(role)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasPersonaPermission(
|
||||||
|
permission: string,
|
||||||
|
permissions: string[],
|
||||||
|
): boolean {
|
||||||
|
if (hasPersonasRoleBypass()) return true
|
||||||
|
return permissions.includes(permission)
|
||||||
|
}
|
||||||
54
src/lib/ratingUserCache.ts
Normal file
54
src/lib/ratingUserCache.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
import { getUserById } from "../api/users.api"
|
||||||
|
import { userDisplayName } from "./ratingsDisplay"
|
||||||
|
|
||||||
|
export type ReviewerProfile = {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const cache = new Map<number, ReviewerProfile | "error">()
|
||||||
|
|
||||||
|
export async function fetchReviewerProfile(userId: number): Promise<ReviewerProfile | null> {
|
||||||
|
const cached = cache.get(userId)
|
||||||
|
if (cached === "error") return null
|
||||||
|
if (cached) return cached
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await getUserById(userId)
|
||||||
|
const user = res.data.data
|
||||||
|
const profile: ReviewerProfile = {
|
||||||
|
id: user.id,
|
||||||
|
name: userDisplayName(user.first_name, user.last_name, user.id),
|
||||||
|
email: user.email || "",
|
||||||
|
}
|
||||||
|
cache.set(userId, profile)
|
||||||
|
return profile
|
||||||
|
} catch {
|
||||||
|
cache.set(userId, "error")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchReviewerProfiles(
|
||||||
|
userIds: number[],
|
||||||
|
concurrency = 5,
|
||||||
|
): Promise<Map<number, ReviewerProfile>> {
|
||||||
|
const unique = Array.from(new Set(userIds.filter((id) => Number.isFinite(id))))
|
||||||
|
const result = new Map<number, ReviewerProfile>()
|
||||||
|
|
||||||
|
for (let i = 0; i < unique.length; i += concurrency) {
|
||||||
|
const batch = unique.slice(i, i + concurrency)
|
||||||
|
const profiles = await Promise.all(batch.map((id) => fetchReviewerProfile(id)))
|
||||||
|
batch.forEach((id, index) => {
|
||||||
|
const profile = profiles[index]
|
||||||
|
if (profile) result.set(id, profile)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearReviewerProfileCache(): void {
|
||||||
|
cache.clear()
|
||||||
|
}
|
||||||
57
src/lib/ratingsDisplay.ts
Normal file
57
src/lib/ratingsDisplay.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
import type { RatingTargetType } from "../types/ratings.types"
|
||||||
|
|
||||||
|
export function formatAverageStars(value: number): string {
|
||||||
|
if (!Number.isFinite(value) || value <= 0) return "0.0"
|
||||||
|
return value.toFixed(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatRatingDate(dateStr: string): string {
|
||||||
|
const d = new Date(dateStr)
|
||||||
|
if (Number.isNaN(d.getTime())) return dateStr || "—"
|
||||||
|
return d.toLocaleDateString(undefined, {
|
||||||
|
year: "numeric",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatRatingDateTime(dateStr: string): string {
|
||||||
|
const d = new Date(dateStr)
|
||||||
|
if (Number.isNaN(d.getTime())) return dateStr || "—"
|
||||||
|
return d.toLocaleString(undefined, {
|
||||||
|
year: "numeric",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function targetTypeLabel(type: RatingTargetType): string {
|
||||||
|
switch (type) {
|
||||||
|
case "app":
|
||||||
|
return "App"
|
||||||
|
case "course":
|
||||||
|
return "Course"
|
||||||
|
case "sub_course":
|
||||||
|
return "Sub-course"
|
||||||
|
default:
|
||||||
|
return type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reviewTextOrPlaceholder(review: string | null | undefined): string {
|
||||||
|
const text = review?.trim()
|
||||||
|
return text ? text : "No written review"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function userDisplayName(
|
||||||
|
firstName?: string | null,
|
||||||
|
lastName?: string | null,
|
||||||
|
userId?: number,
|
||||||
|
): string {
|
||||||
|
const name = [firstName, lastName].filter(Boolean).join(" ").trim()
|
||||||
|
if (name) return name
|
||||||
|
if (userId != null) return `User #${userId}`
|
||||||
|
return "Unknown user"
|
||||||
|
}
|
||||||
12
src/lib/ratingsErrors.ts
Normal file
12
src/lib/ratingsErrors.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
export function getRatingsApiErrorMessage(error: unknown, fallback: string): string {
|
||||||
|
const data = (error as { response?: { data?: { message?: string; error?: string } } })
|
||||||
|
?.response?.data
|
||||||
|
return data?.error ?? data?.message ?? fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isRatingsForbiddenError(error: unknown): boolean {
|
||||||
|
return (error as { response?: { status?: number } })?.response?.status === 403
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RATINGS_FORBIDDEN_MESSAGE =
|
||||||
|
"You don't have permission to access ratings and app reviews"
|
||||||
19
src/lib/ratingsPermissions.ts
Normal file
19
src/lib/ratingsPermissions.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
/** Roles that bypass RBAC permission checks per ratings integration guide. */
|
||||||
|
const RATINGS_BYPASS_TEAM_ROLES = new Set(["SUPER_ADMIN", "ADMIN"])
|
||||||
|
|
||||||
|
export function getSessionTeamRole(): string {
|
||||||
|
return localStorage.getItem("role")?.trim() ?? ""
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasRatingsRoleBypass(): boolean {
|
||||||
|
const role = getSessionTeamRole().toUpperCase()
|
||||||
|
return RATINGS_BYPASS_TEAM_ROLES.has(role)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasRatingsPermission(
|
||||||
|
permission: string,
|
||||||
|
permissions: string[],
|
||||||
|
): boolean {
|
||||||
|
if (hasRatingsRoleBypass()) return true
|
||||||
|
return permissions.includes(permission)
|
||||||
|
}
|
||||||
|
|
@ -10,9 +10,9 @@ export function toVimeoEmbedUrl(rawUrl: string): string | null {
|
||||||
if (host.includes("player.vimeo.com") && parsed.pathname.includes("/video/")) {
|
if (host.includes("player.vimeo.com") && parsed.pathname.includes("/video/")) {
|
||||||
return parsed.toString();
|
return parsed.toString();
|
||||||
}
|
}
|
||||||
const segments = parsed.pathname.split("/").filter(Boolean);
|
const videoId = extractVimeoVideoId(rawUrl);
|
||||||
const videoId = segments.find((segment) => /^\d+$/.test(segment));
|
|
||||||
if (!videoId) return null;
|
if (!videoId) return null;
|
||||||
|
const segments = parsed.pathname.split("/").filter(Boolean);
|
||||||
// Vimeo private/unlisted links often come as /<videoId>/<hash> instead of ?h=<hash>.
|
// Vimeo private/unlisted links often come as /<videoId>/<hash> instead of ?h=<hash>.
|
||||||
const hashFromPath = (() => {
|
const hashFromPath = (() => {
|
||||||
const videoIdx = segments.findIndex((segment) => segment === videoId);
|
const videoIdx = segments.findIndex((segment) => segment === videoId);
|
||||||
|
|
@ -30,6 +30,23 @@ export function toVimeoEmbedUrl(rawUrl: string): string | null {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Numeric Vimeo video id from vimeo.com or player.vimeo.com URLs. */
|
||||||
|
export function extractVimeoVideoId(rawUrl: string): string | null {
|
||||||
|
try {
|
||||||
|
const parsed = new URL(rawUrl.trim());
|
||||||
|
const host = parsed.hostname.toLowerCase();
|
||||||
|
if (!host.includes("vimeo.com")) return null;
|
||||||
|
if (host.includes("player.vimeo.com")) {
|
||||||
|
const match = parsed.pathname.match(/\/video\/(\d+)/);
|
||||||
|
return match?.[1] ?? null;
|
||||||
|
}
|
||||||
|
const segments = parsed.pathname.split("/").filter(Boolean);
|
||||||
|
return segments.find((segment) => /^\d+$/.test(segment)) ?? null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function toYoutubeEmbedUrl(rawUrl: string): string | null {
|
export function toYoutubeEmbedUrl(rawUrl: string): string | null {
|
||||||
try {
|
try {
|
||||||
const u = new URL(rawUrl.trim());
|
const u = new URL(rawUrl.trim());
|
||||||
|
|
|
||||||
38
src/lib/vimeoVideoCache.ts
Normal file
38
src/lib/vimeoVideoCache.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { getVimeoVideo } from "../api/courses.api"
|
||||||
|
|
||||||
|
const durationCache = new Map<string, number | null>()
|
||||||
|
const inflight = new Map<string, Promise<number | null>>()
|
||||||
|
|
||||||
|
export function fetchVimeoDurationSeconds(vimeoId: string): Promise<number | null> {
|
||||||
|
const id = vimeoId.trim()
|
||||||
|
if (!id) return Promise.resolve(null)
|
||||||
|
|
||||||
|
if (durationCache.has(id)) {
|
||||||
|
return Promise.resolve(durationCache.get(id) ?? null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = inflight.get(id)
|
||||||
|
if (pending) return pending
|
||||||
|
|
||||||
|
const request = getVimeoVideo(id)
|
||||||
|
.then((video) => {
|
||||||
|
const seconds =
|
||||||
|
typeof video.duration === "number" &&
|
||||||
|
Number.isFinite(video.duration) &&
|
||||||
|
video.duration > 0
|
||||||
|
? video.duration
|
||||||
|
: null
|
||||||
|
durationCache.set(id, seconds)
|
||||||
|
return seconds
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
durationCache.set(id, null)
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
inflight.delete(id)
|
||||||
|
})
|
||||||
|
|
||||||
|
inflight.set(id, request)
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
|
@ -37,8 +37,9 @@ import { cn } from "../lib/utils"
|
||||||
import { getTeamMemberById } from "../api/team.api"
|
import { getTeamMemberById } from "../api/team.api"
|
||||||
import { getDashboard } from "../api/analytics.api"
|
import { getDashboard } from "../api/analytics.api"
|
||||||
import { getSubscriptionPlans } from "../api/subscription-plans.api"
|
import { getSubscriptionPlans } from "../api/subscription-plans.api"
|
||||||
import { getRatings } from "../api/courses.api"
|
import { getRatingSummary, listRatingsByTarget } from "../api/ratings.api"
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
|
import { Link } from "react-router-dom"
|
||||||
import { AnalyticsTimeRangeFilter } from "../components/analytics/AnalyticsTimeRangeFilter"
|
import { AnalyticsTimeRangeFilter } from "../components/analytics/AnalyticsTimeRangeFilter"
|
||||||
import {
|
import {
|
||||||
getPrimaryQuestionTypeSummary,
|
getPrimaryQuestionTypeSummary,
|
||||||
|
|
@ -47,9 +48,10 @@ import {
|
||||||
getVideoLessonsSummary,
|
getVideoLessonsSummary,
|
||||||
} from "../lib/analytics"
|
} from "../lib/analytics"
|
||||||
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
|
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
|
||||||
|
import { formatAverageStars } from "../lib/ratingsDisplay"
|
||||||
import { formatPlanDuration } from "../lib/subscriptionPlans"
|
import { formatPlanDuration } from "../lib/subscriptionPlans"
|
||||||
import type { SubscriptionPlan } from "../types/subscription.types"
|
import type { SubscriptionPlan } from "../types/subscription.types"
|
||||||
import type { Rating } from "../types/course.types"
|
import type { Rating, RatingSummary } from "../types/ratings.types"
|
||||||
|
|
||||||
const PIE_COLORS = ["#9E2891", "#FFD23F", "#1DE9B6", "#C26FC0", "#6366F1", "#F97316", "#14B8A6", "#EF4444"]
|
const PIE_COLORS = ["#9E2891", "#FFD23F", "#1DE9B6", "#C26FC0", "#6366F1", "#F97316", "#14B8A6", "#EF4444"]
|
||||||
|
|
||||||
|
|
@ -66,6 +68,10 @@ export function DashboardPage() {
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [activeStatTab, setActiveStatTab] = useState<"primary" | "secondary">("primary")
|
const [activeStatTab, setActiveStatTab] = useState<"primary" | "secondary">("primary")
|
||||||
const [appRatings, setAppRatings] = useState<Rating[]>([])
|
const [appRatings, setAppRatings] = useState<Rating[]>([])
|
||||||
|
const [appRatingsSummary, setAppRatingsSummary] = useState<RatingSummary>({
|
||||||
|
total_count: 0,
|
||||||
|
average_stars: 0,
|
||||||
|
})
|
||||||
const [appRatingsLoading, setAppRatingsLoading] = useState(true)
|
const [appRatingsLoading, setAppRatingsLoading] = useState(true)
|
||||||
const [filters, setFilters] = useState<DashboardFilters>(DEFAULT_FILTERS)
|
const [filters, setFilters] = useState<DashboardFilters>(DEFAULT_FILTERS)
|
||||||
const [subscriptionPlans, setSubscriptionPlans] = useState<SubscriptionPlan[]>([])
|
const [subscriptionPlans, setSubscriptionPlans] = useState<SubscriptionPlan[]>([])
|
||||||
|
|
@ -93,8 +99,12 @@ export function DashboardPage() {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchAppRatings = async () => {
|
const fetchAppRatings = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await getRatings({ target_type: "app", target_id: 1, limit: 5 })
|
const [summary, reviews] = await Promise.all([
|
||||||
setAppRatings(res.data.data)
|
getRatingSummary({ target_type: "app", target_id: 0 }),
|
||||||
|
listRatingsByTarget({ target_type: "app", target_id: 0, limit: 5, offset: 0 }),
|
||||||
|
])
|
||||||
|
setAppRatingsSummary(summary)
|
||||||
|
setAppRatings(reviews)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -496,17 +506,25 @@ export function DashboardPage() {
|
||||||
{/* App Ratings */}
|
{/* App Ratings */}
|
||||||
<Card className="shadow-none">
|
<Card className="shadow-none">
|
||||||
<CardHeader className="pb-2">
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<MessageSquare className="h-5 w-5 text-brand-500" />
|
<MessageSquare className="h-5 w-5 text-brand-500" />
|
||||||
<CardTitle>Recent App Reviews</CardTitle>
|
<CardTitle>Recent App Reviews</CardTitle>
|
||||||
</div>
|
</div>
|
||||||
|
<Link
|
||||||
|
to="/app-reviews"
|
||||||
|
className="text-xs font-medium text-brand-600 hover:underline"
|
||||||
|
>
|
||||||
|
View all
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="p-6 pt-2">
|
<CardContent className="p-6 pt-2">
|
||||||
{appRatingsLoading ? (
|
{appRatingsLoading ? (
|
||||||
<div className="flex items-center justify-center py-10">
|
<div className="flex items-center justify-center py-10">
|
||||||
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
|
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
|
||||||
</div>
|
</div>
|
||||||
) : appRatings.length === 0 ? (
|
) : appRatingsSummary.total_count === 0 ? (
|
||||||
<div className="flex items-center justify-center py-10 text-sm text-grayScale-400">
|
<div className="flex items-center justify-center py-10 text-sm text-grayScale-400">
|
||||||
No app reviews yet
|
No app reviews yet
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -519,10 +537,7 @@ export function DashboardPage() {
|
||||||
key={i}
|
key={i}
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-4 w-4",
|
"h-4 w-4",
|
||||||
i <
|
i < Math.round(appRatingsSummary.average_stars)
|
||||||
Math.round(
|
|
||||||
appRatings.reduce((sum, r) => sum + r.stars, 0) / appRatings.length,
|
|
||||||
)
|
|
||||||
? "fill-amber-400 text-amber-400"
|
? "fill-amber-400 text-amber-400"
|
||||||
: "fill-grayScale-200 text-grayScale-200",
|
: "fill-grayScale-200 text-grayScale-200",
|
||||||
)}
|
)}
|
||||||
|
|
@ -530,10 +545,11 @@ export function DashboardPage() {
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<span className="text-sm font-semibold text-grayScale-600">
|
<span className="text-sm font-semibold text-grayScale-600">
|
||||||
{(appRatings.reduce((sum, r) => sum + r.stars, 0) / appRatings.length).toFixed(1)}
|
{formatAverageStars(appRatingsSummary.average_stars)}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs text-grayScale-400">
|
<span className="text-xs text-grayScale-400">
|
||||||
({appRatings.length} {appRatings.length === 1 ? "review" : "reviews"})
|
({appRatingsSummary.total_count}{" "}
|
||||||
|
{appRatingsSummary.total_count === 1 ? "review" : "reviews"})
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,433 +1,491 @@
|
||||||
import { useEffect, useState, type ChangeEvent } from "react";
|
import { useEffect, useState } from "react"
|
||||||
import { BadgeCheck, Briefcase, CalendarDays, Mail, Phone, Shield, User } from "lucide-react";
|
import {
|
||||||
import { Badge } from "../components/ui/badge";
|
BadgeCheck,
|
||||||
import { Button } from "../components/ui/button";
|
CalendarDays,
|
||||||
import { Card, CardContent } from "../components/ui/card";
|
Clock3,
|
||||||
|
Mail,
|
||||||
|
Phone,
|
||||||
|
Shield,
|
||||||
|
User,
|
||||||
|
} from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { getTeamMe, updateTeamMe } from "../api/team.api"
|
||||||
|
import { Badge } from "../components/ui/badge"
|
||||||
|
import { Button } from "../components/ui/button"
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../components/ui/dialog";
|
} from "../components/ui/dialog"
|
||||||
import { Input } from "../components/ui/input";
|
import { Input } from "../components/ui/input"
|
||||||
import { Textarea } from "../components/ui/textarea";
|
import { SpinnerIcon } from "../components/ui/spinner-icon"
|
||||||
import { FileUpload } from "../components/ui/file-upload";
|
import { Textarea } from "../components/ui/textarea"
|
||||||
import { getMyProfile } from "../api/users.api";
|
import { cn } from "../lib/utils"
|
||||||
import { updateTeamMember } from "../api/team.api";
|
import type { TeamMeProfile } from "../types/team.types"
|
||||||
import { uploadImageFile } from "../api/files.api";
|
import { ProfileAvatarUpload } from "../components/profile/ProfileAvatarUpload"
|
||||||
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
import { PersonaProfilePictureUploadField } from "./personas/components/PersonaProfilePictureUploadField"
|
||||||
import type { UpdateTeamMemberRequest } from "../types/team.types";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
|
|
||||||
function formatDate(dateStr: string | null | undefined): string {
|
function formatDate(dateStr: string | null | undefined): string {
|
||||||
if (!dateStr) return "—";
|
if (!dateStr) return "—"
|
||||||
return new Date(dateStr).toLocaleDateString("en-US", {
|
const date = new Date(dateStr)
|
||||||
|
if (Number.isNaN(date.getTime())) return dateStr
|
||||||
|
return date.toLocaleDateString(undefined, {
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
month: "long",
|
month: "long",
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDateTime(dateStr: string | null | undefined): string {
|
function formatDateTime(dateStr: string | null | undefined): string {
|
||||||
if (!dateStr) return "—";
|
if (!dateStr) return "—"
|
||||||
return new Date(dateStr).toLocaleString("en-US", {
|
const date = new Date(dateStr)
|
||||||
|
if (Number.isNaN(date.getTime())) return dateStr
|
||||||
|
return date.toLocaleString(undefined, {
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
month: "long",
|
month: "short",
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TeamMeProfile {
|
function formatRoleLabel(role: string): string {
|
||||||
id: number
|
const value = role.trim()
|
||||||
first_name: string
|
if (!value) return "—"
|
||||||
last_name: string
|
return value
|
||||||
email: string
|
.split("_")
|
||||||
phone_number: string
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||||
team_role: string
|
.join(" ")
|
||||||
department: string
|
}
|
||||||
job_title: string
|
|
||||||
employment_type: string
|
function formatStatusLabel(status: string): string {
|
||||||
hire_date: string
|
const value = status.trim()
|
||||||
bio: string
|
if (!value) return "—"
|
||||||
status: string
|
return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase()
|
||||||
email_verified: boolean
|
}
|
||||||
permissions: string[]
|
|
||||||
last_login: string | null
|
function displayValue(value: string | null | undefined): string {
|
||||||
created_at: string
|
const trimmed = value?.trim()
|
||||||
emergency_contact?: string
|
return trimmed ? trimmed : "—"
|
||||||
work_phone?: string
|
}
|
||||||
profile_picture_url?: string
|
|
||||||
|
function ReadOnlyField({ label, value }: { label: string; value: string }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p className="mb-1 text-xs font-medium text-grayScale-500">{label}</p>
|
||||||
|
<p className="text-sm font-medium text-grayScale-700">{value}</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function LoadingSkeleton() {
|
function LoadingSkeleton() {
|
||||||
return (
|
return (
|
||||||
<div className="w-full space-y-8 py-10">
|
<div className="mx-auto w-full max-w-5xl space-y-6 py-8">
|
||||||
<div className="animate-pulse space-y-8">
|
<div className="h-8 w-48 animate-pulse rounded-lg bg-grayScale-100" />
|
||||||
<div className="overflow-hidden rounded-2xl border border-grayScale-100">
|
<div className="h-40 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
<div className="h-40 bg-gradient-to-r from-grayScale-100 via-grayScale-200/60 to-grayScale-100" />
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
<div className="flex flex-col items-center px-8 pb-8">
|
{[1, 2].map((item) => (
|
||||||
<div className="-mt-14 h-28 w-28 rounded-full bg-grayScale-100 ring-4 ring-white" />
|
<div key={item} className="h-56 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
<div className="mt-4 h-6 w-48 rounded-lg bg-grayScale-100" />
|
|
||||||
<div className="mt-3 h-5 w-24 rounded-full bg-grayScale-100" />
|
|
||||||
<div className="mt-5 flex gap-3">
|
|
||||||
<div className="h-7 w-20 rounded-full bg-grayScale-100" />
|
|
||||||
<div className="h-7 w-28 rounded-full bg-grayScale-100" />
|
|
||||||
<div className="h-7 w-28 rounded-full bg-grayScale-100" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="grid gap-6 md:grid-cols-3">
|
|
||||||
{[1, 2, 3].map((i) => (
|
|
||||||
<div key={i} className="rounded-2xl border border-grayScale-100 p-6">
|
|
||||||
<div className="mb-5 h-5 w-40 rounded bg-grayScale-100" />
|
|
||||||
<div className="space-y-4">
|
|
||||||
{[1, 2, 3, 4].map((j) => (
|
|
||||||
<div key={j} className="flex items-center justify-between">
|
|
||||||
<div className="h-4 w-20 rounded bg-grayScale-100" />
|
|
||||||
<div className="h-4 w-28 rounded bg-grayScale-100" />
|
|
||||||
</div>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
)
|
||||||
</div>
|
}
|
||||||
</div>
|
|
||||||
</div>
|
type EditFormState = {
|
||||||
);
|
first_name: string
|
||||||
|
last_name: string
|
||||||
|
phone_number: string
|
||||||
|
department: string
|
||||||
|
job_title: string
|
||||||
|
profile_picture_url: string
|
||||||
|
bio: string
|
||||||
|
work_phone: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function profileToEditForm(profile: TeamMeProfile): EditFormState {
|
||||||
|
return {
|
||||||
|
first_name: profile.first_name,
|
||||||
|
last_name: profile.last_name,
|
||||||
|
phone_number: profile.phone_number,
|
||||||
|
department: profile.department ?? "",
|
||||||
|
job_title: profile.job_title ?? "",
|
||||||
|
profile_picture_url: profile.profile_picture_url ?? "",
|
||||||
|
bio: profile.bio ?? "",
|
||||||
|
work_phone: profile.work_phone ?? "",
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ProfilePage() {
|
export function ProfilePage() {
|
||||||
const [profile, setProfile] = useState<TeamMeProfile | null>(null);
|
const [profile, setProfile] = useState<TeamMeProfile | null>(null)
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [editing, setEditing] = useState(false);
|
const [editing, setEditing] = useState(false)
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false)
|
||||||
const [profilePictureFile, setProfilePictureFile] = useState<File | null>(null);
|
const [uploadingPicture, setUploadingPicture] = useState(false)
|
||||||
const [editForm, setEditForm] = useState<UpdateTeamMemberRequest>({
|
const [editForm, setEditForm] = useState<EditFormState>({
|
||||||
first_name: "",
|
first_name: "",
|
||||||
last_name: "",
|
last_name: "",
|
||||||
phone_number: "",
|
phone_number: "",
|
||||||
|
department: "",
|
||||||
|
job_title: "",
|
||||||
profile_picture_url: "",
|
profile_picture_url: "",
|
||||||
bio: "",
|
bio: "",
|
||||||
});
|
work_phone: "",
|
||||||
|
})
|
||||||
|
|
||||||
|
const busy = saving || uploadingPicture
|
||||||
|
|
||||||
|
const loadProfile = async () => {
|
||||||
|
setLoading(true)
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
const res = await getTeamMe()
|
||||||
|
setProfile(res.data.data)
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to fetch profile", err)
|
||||||
|
setProfile(null)
|
||||||
|
setError("Failed to load profile. Please try again later.")
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchProfile = async () => {
|
void loadProfile()
|
||||||
try {
|
}, [])
|
||||||
const res = await getMyProfile();
|
|
||||||
setProfile((res.data?.data ?? null) as unknown as TeamMeProfile | null);
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to fetch profile", err);
|
|
||||||
setError("Failed to load profile. Please try again later.");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
fetchProfile();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const startEditing = () => {
|
const startEditing = () => {
|
||||||
if (!profile) return;
|
if (!profile) return
|
||||||
const nextForm: UpdateTeamMemberRequest = {
|
setEditForm(profileToEditForm(profile))
|
||||||
first_name: profile.first_name ?? "",
|
setUploadingPicture(false)
|
||||||
last_name: profile.last_name ?? "",
|
setEditing(true)
|
||||||
phone_number: profile.phone_number ?? "",
|
}
|
||||||
profile_picture_url: profile.profile_picture_url ?? "",
|
|
||||||
bio: profile.bio ?? "",
|
|
||||||
};
|
|
||||||
setEditForm(nextForm);
|
|
||||||
setProfilePictureFile(null);
|
|
||||||
setEditing(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelEditing = () => {
|
|
||||||
setProfilePictureFile(null);
|
|
||||||
setEditing(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateField = (field: keyof UpdateTeamMemberRequest, value: string) => {
|
|
||||||
setEditForm((prev) => ({ ...prev, [field]: value }));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
if (!profile) return;
|
if (!profile) return
|
||||||
|
|
||||||
let nextProfilePictureUrl = editForm.profile_picture_url ?? "";
|
const firstName = editForm.first_name.trim()
|
||||||
if (profilePictureFile) {
|
const lastName = editForm.last_name.trim()
|
||||||
try {
|
|
||||||
const uploadRes = await uploadImageFile(profilePictureFile);
|
if (!firstName || !lastName) {
|
||||||
const uploadedUrl = uploadRes.data?.data?.url?.trim();
|
toast.error("First name and last name are required")
|
||||||
if (!uploadedUrl) throw new Error("Missing uploaded image url");
|
return
|
||||||
nextProfilePictureUrl = uploadedUrl;
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to upload profile picture:", err);
|
|
||||||
toast.error("Failed to upload profile picture");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload: UpdateTeamMemberRequest = {
|
setSaving(true)
|
||||||
bio: editForm.bio ?? "",
|
|
||||||
first_name: editForm.first_name ?? "",
|
|
||||||
last_name: editForm.last_name ?? "",
|
|
||||||
phone_number: editForm.phone_number ?? "",
|
|
||||||
profile_picture_url: nextProfilePictureUrl,
|
|
||||||
};
|
|
||||||
|
|
||||||
setSaving(true);
|
|
||||||
try {
|
try {
|
||||||
await updateTeamMember(profile.id, payload);
|
const res = await updateTeamMe({
|
||||||
const refreshed = await getMyProfile();
|
first_name: firstName,
|
||||||
setProfile((refreshed.data?.data ?? null) as unknown as TeamMeProfile | null);
|
last_name: lastName,
|
||||||
setEditing(false);
|
phone_number: editForm.phone_number.trim(),
|
||||||
setProfilePictureFile(null);
|
department: editForm.department.trim(),
|
||||||
toast.success("Profile updated successfully");
|
job_title: editForm.job_title.trim(),
|
||||||
|
profile_picture_url: editForm.profile_picture_url.trim(),
|
||||||
|
bio: editForm.bio.trim(),
|
||||||
|
work_phone: editForm.work_phone.trim(),
|
||||||
|
})
|
||||||
|
setProfile(res.data.data)
|
||||||
|
setEditing(false)
|
||||||
|
toast.success(res.data.message || "Profile updated successfully")
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to update team member profile", err);
|
console.error("Failed to update profile", err)
|
||||||
toast.error("Failed to update profile");
|
const message =
|
||||||
|
(err as { response?: { data?: { message?: string } } })?.response?.data
|
||||||
|
?.message ?? "Failed to update profile"
|
||||||
|
toast.error(message)
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
if (loading) return <LoadingSkeleton />;
|
if (loading) return <LoadingSkeleton />
|
||||||
|
|
||||||
if (error || !profile) {
|
if (error || !profile) {
|
||||||
return (
|
return (
|
||||||
<div className="w-full py-16">
|
<div className="mx-auto w-full max-w-5xl py-16">
|
||||||
<Card className="border-dashed">
|
<Card className="border-dashed">
|
||||||
<CardContent className="flex flex-col items-center gap-5 p-12">
|
<CardContent className="flex flex-col items-center gap-5 p-12">
|
||||||
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-grayScale-100">
|
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-grayScale-100">
|
||||||
<User className="h-10 w-10 text-grayScale-300" />
|
<User className="h-10 w-10 text-grayScale-300" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<p className="text-lg font-semibold tracking-tight text-grayScale-600">
|
<p className="text-lg font-semibold text-grayScale-700">
|
||||||
{error || "Profile not available"}
|
{error || "Profile not available"}
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-1 text-sm text-grayScale-400">
|
<p className="mt-1 text-sm text-grayScale-500">
|
||||||
Please check your connection and try again.
|
Please check your connection and try again.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<Button variant="outline" onClick={() => void loadProfile()}>
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const fullName = `${profile.first_name} ${profile.last_name}`;
|
const fullName = `${profile.first_name} ${profile.last_name}`.trim()
|
||||||
const initials = `${profile.first_name?.[0] ?? ""}${profile.last_name?.[0] ?? ""}`.toUpperCase();
|
const initials = `${profile.first_name?.[0] ?? ""}${profile.last_name?.[0] ?? ""}`.toUpperCase()
|
||||||
|
const isActive = profile.status.toLowerCase() === "active"
|
||||||
|
|
||||||
|
const handleProfileUpdate = (nextProfile: TeamMeProfile) => {
|
||||||
|
setProfile(nextProfile)
|
||||||
|
setEditForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
profile_picture_url: nextProfile.profile_picture_url ?? "",
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-7xl rounded-2xl bg-[#f7f1f8] p-4 pb-8 sm:p-6">
|
<div className="mx-auto w-full max-w-5xl space-y-6">
|
||||||
<div className="overflow-hidden rounded-2xl border border-[#d9bddb] bg-white">
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
<div className="h-40 w-full bg-gradient-to-r from-[#d6aed6] via-[#e4cce4] to-[#cba0cd]" />
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-grayScale-500">Account</p>
|
||||||
<div className="grid gap-0 lg:grid-cols-[280px_minmax(0,1fr)]">
|
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">My profile</h1>
|
||||||
<aside className="border-r border-[#eadbea] bg-white px-5 pb-6">
|
<p className="mt-1 text-sm text-grayScale-500">
|
||||||
<div className="-mt-16">
|
Your team account details from the admin directory.
|
||||||
<div className="flex h-28 w-28 items-center justify-center rounded-full border-4 border-white bg-[#d6aed6] text-2xl font-bold text-[#6f2aa8]">
|
</p>
|
||||||
{initials}
|
|
||||||
</div>
|
</div>
|
||||||
<h2 className="mt-3 text-2xl font-bold text-grayScale-700">{fullName}</h2>
|
<Button className="bg-brand-500 text-white hover:bg-brand-600" onClick={startEditing}>
|
||||||
<p className="text-sm text-grayScale-400">{profile.job_title || "Team Member"}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-4">
|
|
||||||
<div className="flex w-full items-center justify-between rounded-lg border border-[#d9bddb] bg-[#f4e8f4] px-3 py-2">
|
|
||||||
<span className="text-sm font-medium text-[#6f2aa8]">Account Status</span>
|
|
||||||
<span className="text-sm font-semibold uppercase text-[#5e2390]">{profile.status}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-5 space-y-5 text-sm">
|
|
||||||
<section>
|
|
||||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-grayScale-400">About</p>
|
|
||||||
<div className="space-y-2 text-grayScale-600">
|
|
||||||
<div className="flex items-center gap-2"><Briefcase className="h-4 w-4 text-[#6f2aa8]" />{profile.job_title || "Job title not set"}</div>
|
|
||||||
<div className="flex items-center gap-2"><Shield className="h-4 w-4 text-[#6f2aa8]" />{profile.team_role || "Role not set"}</div>
|
|
||||||
<div className="flex items-center gap-2"><CalendarDays className="h-4 w-4 text-[#6f2aa8]" />Hire date: {formatDate(profile.hire_date)}</div>
|
|
||||||
<div className="flex items-center gap-2"><BadgeCheck className="h-4 w-4 text-[#6f2aa8]" />{profile.department || "Department not set"}</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section>
|
|
||||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-grayScale-400">Contact</p>
|
|
||||||
<div className="space-y-2 text-grayScale-600">
|
|
||||||
<div className="flex items-center gap-2"><Mail className="h-4 w-4 text-[#6f2aa8]" />{profile.email}</div>
|
|
||||||
<div className="flex items-center gap-2"><Phone className="h-4 w-4 text-[#6f2aa8]" />{profile.phone_number || "—"}</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section>
|
|
||||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-grayScale-400">Access</p>
|
|
||||||
<p className="text-xs text-grayScale-500">Permissions from `/team/me`</p>
|
|
||||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
|
||||||
{(profile.permissions ?? []).length === 0 ? (
|
|
||||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">No permissions listed</Badge>
|
|
||||||
) : (
|
|
||||||
profile.permissions.map((permission) => (
|
|
||||||
<Badge key={permission} className="bg-[#ecd9ec] text-[#6f2aa8]">
|
|
||||||
{permission}
|
|
||||||
</Badge>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
<main className="bg-[#fdf8fd] px-5 py-6 sm:px-7">
|
|
||||||
<div className="space-y-5">
|
|
||||||
<Card className="border-[#d9bddb] bg-white shadow-none">
|
|
||||||
<CardContent className="p-5">
|
|
||||||
<div className="mb-3 flex items-center justify-between">
|
|
||||||
<h3 className="text-base font-semibold text-grayScale-700">Summary</h3>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={startEditing}
|
|
||||||
className="inline-flex items-center rounded-md border border-[#d9bddb] bg-[#f4e8f4] px-3 py-1.5 text-sm font-medium text-[#6f2aa8] transition-colors hover:bg-[#ecd9ec] hover:text-[#5e2390] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#c39bd4]"
|
|
||||||
>
|
|
||||||
Edit profile
|
Edit profile
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2 text-sm text-grayScale-600">
|
|
||||||
<div className="flex items-center gap-2"><Briefcase className="h-4 w-4 text-[#6f2aa8]" />{profile.job_title || "Role-focused work item"}</div>
|
<Card className="overflow-hidden border-grayScale-100 shadow-soft">
|
||||||
<div className="flex items-center gap-2"><Shield className="h-4 w-4 text-[#6f2aa8]" />{profile.team_role || "Team responsibility"}</div>
|
<div className="h-28 bg-gradient-to-r from-brand-500/20 via-brand-300/20 to-brand-100/40" />
|
||||||
<div className="flex items-center gap-2"><Mail className="h-4 w-4 text-[#6f2aa8]" />{profile.email}</div>
|
<CardContent className="relative px-6 pb-6 pt-0">
|
||||||
<div className="flex items-center gap-2"><Phone className="h-4 w-4 text-[#6f2aa8]" />{profile.phone_number || "No phone number"}</div>
|
<div className="-mt-12 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
|
||||||
|
<div className="flex items-end gap-4">
|
||||||
|
<ProfileAvatarUpload
|
||||||
|
avatarUrl={profile.profile_picture_url}
|
||||||
|
initials={initials}
|
||||||
|
onProfileUpdate={handleProfileUpdate}
|
||||||
|
/>
|
||||||
|
<div className="pb-1">
|
||||||
|
<h2 className="text-2xl font-semibold text-grayScale-800">{fullName}</h2>
|
||||||
|
<p className="text-sm text-grayScale-500">{displayValue(profile.job_title)}</p>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2 pb-1">
|
||||||
|
<Badge variant={isActive ? "default" : "secondary"}>
|
||||||
|
{formatStatusLabel(profile.status)}
|
||||||
|
</Badge>
|
||||||
|
<Badge variant={profile.email_verified ? "default" : "outline"}>
|
||||||
|
{profile.email_verified ? "Email verified" : "Email not verified"}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{profile.bio?.trim() ? (
|
||||||
|
<p className="mt-4 text-sm leading-relaxed text-grayScale-600">{profile.bio.trim()}</p>
|
||||||
|
) : null}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="border-[#d9bddb] bg-white shadow-none">
|
<div className="grid gap-6 lg:grid-cols-2">
|
||||||
<CardContent className="p-5">
|
<Card className="shadow-soft">
|
||||||
<h3 className="mb-3 text-base font-semibold text-grayScale-700">Employment</h3>
|
<CardHeader>
|
||||||
<div className="rounded-lg border border-[#dcc3df] bg-[#f4e8f4] p-3">
|
<CardTitle className="text-base">Work details</CardTitle>
|
||||||
<p className="text-sm font-medium text-grayScale-700">{profile.department || "Department not set"}</p>
|
</CardHeader>
|
||||||
<p className="text-xs text-grayScale-500">Employment type: {profile.employment_type || "—"}</p>
|
<CardContent className="grid gap-4 sm:grid-cols-2">
|
||||||
</div>
|
<ReadOnlyField label="Team role" value={formatRoleLabel(profile.team_role)} />
|
||||||
|
<ReadOnlyField label="Department" value={displayValue(profile.department)} />
|
||||||
|
<ReadOnlyField label="Job title" value={displayValue(profile.job_title)} />
|
||||||
|
<ReadOnlyField label="Member ID" value={String(profile.id)} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="border-[#d9bddb] bg-white shadow-none">
|
<Card className="shadow-soft">
|
||||||
<CardContent className="p-5">
|
<CardHeader>
|
||||||
<h3 className="mb-3 text-base font-semibold text-grayScale-700">More about me</h3>
|
<CardTitle className="text-base">Contact</CardTitle>
|
||||||
<div className="flex flex-wrap gap-2">
|
</CardHeader>
|
||||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">Status {profile.status}</Badge>
|
<CardContent className="space-y-4">
|
||||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">Email {profile.email_verified ? "verified" : "not verified"}</Badge>
|
<div className="flex items-center gap-3 text-sm text-grayScale-700">
|
||||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">Joined {formatDate(profile.created_at)}</Badge>
|
<Mail className="h-4 w-4 text-brand-600" />
|
||||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">Last login {formatDateTime(profile.last_login)}</Badge>
|
<span>{displayValue(profile.email)}</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center gap-3 text-sm text-grayScale-700">
|
||||||
|
<Phone className="h-4 w-4 text-brand-600" />
|
||||||
|
<span>{displayValue(profile.phone_number)}</span>
|
||||||
|
</div>
|
||||||
|
{profile.work_phone?.trim() ? (
|
||||||
|
<div className="flex items-center gap-3 text-sm text-grayScale-700">
|
||||||
|
<Phone className="h-4 w-4 text-brand-600" />
|
||||||
|
<span>
|
||||||
|
<span className="text-grayScale-500">Work: </span>
|
||||||
|
{profile.work_phone.trim()}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="border-[#d9bddb] bg-white shadow-none">
|
<Card className="shadow-soft lg:col-span-2">
|
||||||
<CardContent className="grid gap-3 p-5 sm:grid-cols-2">
|
<CardHeader>
|
||||||
<div>
|
<CardTitle className="text-base">Account activity</CardTitle>
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">First Name</p>
|
</CardHeader>
|
||||||
<p className="text-sm font-medium text-grayScale-700">{profile.first_name}</p>
|
<CardContent className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<CalendarDays className="mt-0.5 h-4 w-4 text-brand-600" />
|
||||||
|
<ReadOnlyField label="Joined" value={formatDate(profile.created_at)} />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div className="flex items-start gap-3">
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Last Name</p>
|
<Clock3 className="mt-0.5 h-4 w-4 text-brand-600" />
|
||||||
<p className="text-sm font-medium text-grayScale-700">{profile.last_name}</p>
|
<ReadOnlyField label="Last login" value={formatDateTime(profile.last_login)} />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div className="flex items-start gap-3">
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Department</p>
|
<BadgeCheck className="mt-0.5 h-4 w-4 text-brand-600" />
|
||||||
<p className="text-sm font-medium text-grayScale-700">{profile.department || "—"}</p>
|
<ReadOnlyField
|
||||||
|
label="Email verification"
|
||||||
|
value={profile.email_verified ? "Verified" : "Not verified"}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div className="flex items-start gap-3">
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Team Role</p>
|
<Shield className="mt-0.5 h-4 w-4 text-brand-600" />
|
||||||
<p className="text-sm font-medium text-grayScale-700">{profile.team_role || "—"}</p>
|
<ReadOnlyField label="Last updated" value={formatDate(profile.updated_at)} />
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Job Title</p>
|
|
||||||
<p className="text-sm font-medium text-grayScale-700">{profile.job_title || "—"}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Hire Date</p>
|
|
||||||
<p className="text-sm font-medium text-grayScale-700">{formatDate(profile.hire_date) || "—"}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Phone Number</p>
|
|
||||||
<p className="text-sm font-medium text-grayScale-700">{profile.phone_number || "—"}</p>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
|
||||||
</div>
|
<Dialog open={editing} onOpenChange={(open) => !busy && setEditing(open)}>
|
||||||
</div>
|
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||||
<Dialog open={editing} onOpenChange={(open) => !saving && setEditing(open)}>
|
|
||||||
<DialogContent className="max-h-[88vh] overflow-y-auto border-[#d9bddb] bg-[#fdf8fd] sm:max-w-3xl">
|
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle className="text-[#6f2aa8]">Edit profile</DialogTitle>
|
<DialogTitle>Edit profile</DialogTitle>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="grid gap-3 sm:grid-cols-2">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
<div>
|
<div className="space-y-1.5">
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">First Name</p>
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-first-name">
|
||||||
<Input value={editForm.first_name ?? ""} onChange={(e) => updateField("first_name", e.target.value)} />
|
First name
|
||||||
</div>
|
</label>
|
||||||
<div>
|
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Last Name</p>
|
|
||||||
<Input value={editForm.last_name ?? ""} onChange={(e) => updateField("last_name", e.target.value)} />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Phone Number</p>
|
|
||||||
<Input value={editForm.phone_number ?? ""} onChange={(e) => updateField("phone_number", e.target.value)} />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Profile Picture</p>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<FileUpload
|
|
||||||
accept="image/*"
|
|
||||||
onFileSelect={setProfilePictureFile}
|
|
||||||
label="Upload profile picture"
|
|
||||||
description="JPEG, PNG, WEBP"
|
|
||||||
className="min-h-[90px] rounded-lg border-2 border-dashed border-grayScale-200 transition-colors hover:border-brand-400 hover:bg-brand-50/30"
|
|
||||||
/>
|
|
||||||
<Input
|
<Input
|
||||||
value={editForm.profile_picture_url ?? ""}
|
id="profile-first-name"
|
||||||
onChange={(e) => updateField("profile_picture_url", e.target.value)}
|
value={editForm.first_name}
|
||||||
placeholder="Or paste image URL (https://...)"
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm((prev) => ({ ...prev, first_name: e.target.value }))
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-last-name">
|
||||||
|
Last name
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="profile-last-name"
|
||||||
|
value={editForm.last_name}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm((prev) => ({ ...prev, last_name: e.target.value }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="sm:col-span-2">
|
<div className="space-y-1.5">
|
||||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Bio</p>
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-phone">
|
||||||
|
Phone number
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="profile-phone"
|
||||||
|
value={editForm.phone_number}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm((prev) => ({ ...prev, phone_number: e.target.value }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-work-phone">
|
||||||
|
Work phone
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="profile-work-phone"
|
||||||
|
value={editForm.work_phone}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm((prev) => ({ ...prev, work_phone: e.target.value }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-department">
|
||||||
|
Department
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="profile-department"
|
||||||
|
value={editForm.department}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm((prev) => ({ ...prev, department: e.target.value }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-job-title">
|
||||||
|
Job title
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="profile-job-title"
|
||||||
|
value={editForm.job_title}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm((prev) => ({ ...prev, job_title: e.target.value }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5 sm:col-span-2">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700">Email</label>
|
||||||
|
<Input value={profile.email} disabled />
|
||||||
|
<p className="text-xs text-grayScale-500">Email is managed by your administrator.</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5 sm:col-span-2">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-picture">
|
||||||
|
Profile picture
|
||||||
|
</label>
|
||||||
|
<PersonaProfilePictureUploadField
|
||||||
|
value={editForm.profile_picture_url}
|
||||||
|
disabled={busy}
|
||||||
|
onUploadBusyChange={setUploadingPicture}
|
||||||
|
onChange={(profile_picture_url) =>
|
||||||
|
setEditForm((prev) => ({ ...prev, profile_picture_url }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5 sm:col-span-2">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-bio">
|
||||||
|
Bio
|
||||||
|
</label>
|
||||||
<Textarea
|
<Textarea
|
||||||
value={editForm.bio ?? ""}
|
id="profile-bio"
|
||||||
onChange={(e: ChangeEvent<HTMLTextAreaElement>) => updateField("bio", e.target.value)}
|
value={editForm.bio}
|
||||||
|
disabled={busy}
|
||||||
rows={4}
|
rows={4}
|
||||||
|
placeholder="A short introduction about your role and background."
|
||||||
|
onChange={(e) => setEditForm((prev) => ({ ...prev, bio: e.target.value }))}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DialogFooter className="mt-2">
|
<DialogFooter>
|
||||||
<Button
|
<Button type="button" variant="outline" onClick={() => setEditing(false)} disabled={busy}>
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
className="border-[#d9bddb] text-[#6f2aa8]"
|
|
||||||
onClick={cancelEditing}
|
|
||||||
disabled={saving}
|
|
||||||
>
|
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
className="bg-[#6f2aa8] text-white hover:bg-[#5e2390]"
|
className={cn("bg-brand-500 text-white hover:bg-brand-600")}
|
||||||
onClick={handleSave}
|
onClick={() => void handleSave()}
|
||||||
disabled={saving}
|
disabled={busy}
|
||||||
>
|
>
|
||||||
{saving ? <SpinnerIcon className="mr-1 h-4 w-4" /> : null}
|
{saving ? <SpinnerIcon className="mr-2 h-4 w-4" /> : null}
|
||||||
{saving ? "Saving..." : "Save changes"}
|
{saving ? "Saving…" : "Save changes"}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ import {
|
||||||
Lock,
|
Lock,
|
||||||
Moon,
|
Moon,
|
||||||
Palette,
|
Palette,
|
||||||
Save,
|
|
||||||
Shield,
|
Shield,
|
||||||
Sun,
|
Sun,
|
||||||
User,
|
User,
|
||||||
|
|
@ -21,13 +20,12 @@ import {
|
||||||
} from "../components/ui/card";
|
} from "../components/ui/card";
|
||||||
import { Input } from "../components/ui/input";
|
import { Input } from "../components/ui/input";
|
||||||
import { Button } from "../components/ui/button";
|
import { Button } from "../components/ui/button";
|
||||||
import { Select } from "../components/ui/select";
|
|
||||||
import { cn } from "../lib/utils";
|
import { cn } from "../lib/utils";
|
||||||
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
||||||
import { changeTeamMemberPassword } from "../api/team.api";
|
import { changeTeamMemberPassword } from "../api/team.api";
|
||||||
import { logoutToLogin } from "../lib/auth";
|
import { logoutToLogin } from "../lib/auth";
|
||||||
import { getMyProfile, updateProfile } from "../api/users.api";
|
import { getMyProfile } from "../api/users.api";
|
||||||
import type { UserProfileData } from "../types/user.types";
|
import type { TeamMeProfile } from "../types/team.types";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { AppVersionsTab } from "./settings/AppVersionsTab";
|
import { AppVersionsTab } from "./settings/AppVersionsTab";
|
||||||
import { SubscriptionPlansTab } from "./settings/SubscriptionPlansTab";
|
import { SubscriptionPlansTab } from "./settings/SubscriptionPlansTab";
|
||||||
|
|
@ -37,133 +35,16 @@ import { useTheme } from "../contexts/ThemeContext";
|
||||||
type SettingsTab =
|
type SettingsTab =
|
||||||
| "subscription"
|
| "subscription"
|
||||||
| "app-versions"
|
| "app-versions"
|
||||||
| "profile"
|
|
||||||
| "security"
|
| "security"
|
||||||
| "appearance";
|
| "appearance";
|
||||||
|
|
||||||
const tabs: { id: SettingsTab; label: string; icon: typeof User }[] = [
|
const tabs: { id: SettingsTab; label: string; icon: typeof Shield }[] = [
|
||||||
{ id: "subscription", label: "Subscription packages", icon: CreditCard },
|
{ id: "subscription", label: "Subscription packages", icon: CreditCard },
|
||||||
{ id: "app-versions", label: "App versions", icon: Smartphone },
|
{ id: "app-versions", label: "App versions", icon: Smartphone },
|
||||||
{ id: "profile", label: "Profile", icon: User },
|
|
||||||
{ id: "security", label: "Security", icon: Shield },
|
{ id: "security", label: "Security", icon: Shield },
|
||||||
{ id: "appearance", label: "Appearance", icon: Palette },
|
{ id: "appearance", label: "Appearance", icon: Palette },
|
||||||
];
|
];
|
||||||
|
|
||||||
function ProfileTab({ profile }: { profile: UserProfileData }) {
|
|
||||||
const [firstName, setFirstName] = useState(profile.first_name);
|
|
||||||
const [lastName, setLastName] = useState(profile.last_name);
|
|
||||||
const [nickName, setNickName] = useState(profile.nick_name || "");
|
|
||||||
const [language, setLanguage] = useState(profile.preferred_language || "en");
|
|
||||||
const [saving, setSaving] = useState(false);
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
setSaving(true);
|
|
||||||
try {
|
|
||||||
await updateProfile({
|
|
||||||
first_name: firstName,
|
|
||||||
last_name: lastName,
|
|
||||||
nick_name: nickName,
|
|
||||||
preferred_language: language,
|
|
||||||
});
|
|
||||||
toast.success("Profile settings saved");
|
|
||||||
} catch {
|
|
||||||
toast.error("Failed to save profile settings.");
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
|
|
||||||
<Card className="border border-grayScale-100 rounded-[6px] overflow-hidden">
|
|
||||||
<div className="h-1 w-full bg-brand-500" />
|
|
||||||
<CardHeader className="pb-3 border-b border-grayScale-50">
|
|
||||||
<CardTitle className="text-sm font-bold text-grayScale-900">
|
|
||||||
Personal Information
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-5 pb-6">
|
|
||||||
<div className="grid gap-5 sm:grid-cols-2">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
|
||||||
First Name
|
|
||||||
</label>
|
|
||||||
<Input
|
|
||||||
value={firstName}
|
|
||||||
onChange={(e) => setFirstName(e.target.value)}
|
|
||||||
className="rounded-[6px]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
|
||||||
Last Name
|
|
||||||
</label>
|
|
||||||
<Input
|
|
||||||
value={lastName}
|
|
||||||
onChange={(e) => setLastName(e.target.value)}
|
|
||||||
className="rounded-[6px]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
|
||||||
Nickname
|
|
||||||
</label>
|
|
||||||
<Input
|
|
||||||
value={nickName}
|
|
||||||
onChange={(e) => setNickName(e.target.value)}
|
|
||||||
className="rounded-[6px]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card className="border border-grayScale-100 rounded-[6px] overflow-hidden">
|
|
||||||
<div className="h-1 w-full bg-brand-400" />
|
|
||||||
<CardHeader className="pb-3 border-b border-grayScale-50">
|
|
||||||
<CardTitle className="text-sm font-bold text-grayScale-900">
|
|
||||||
Preferences
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-5 pb-6">
|
|
||||||
<div className="grid gap-5 sm:grid-cols-2">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
|
||||||
Preferred Language
|
|
||||||
</label>
|
|
||||||
<Select
|
|
||||||
value={language}
|
|
||||||
onChange={(e) => setLanguage(e.target.value)}
|
|
||||||
className="rounded-[6px]"
|
|
||||||
>
|
|
||||||
<option value="en">English</option>
|
|
||||||
<option value="am">Amharic</option>
|
|
||||||
<option value="or">Afan Oromo</option>
|
|
||||||
<option value="ti">Tigrinya</option>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<div className="flex justify-end">
|
|
||||||
<Button
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={saving}
|
|
||||||
className="min-w-[140px] rounded-[6px] font-bold"
|
|
||||||
>
|
|
||||||
{saving ? (
|
|
||||||
<SpinnerIcon className="h-4 w-4" />
|
|
||||||
) : (
|
|
||||||
<Save className="h-4 w-4 mr-2" />
|
|
||||||
)}
|
|
||||||
{saving ? "Saving…" : "Save Changes"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SecurityTab({ memberId }: { memberId: number }) {
|
function SecurityTab({ memberId }: { memberId: number }) {
|
||||||
const [currentPassword, setCurrentPassword] = useState("");
|
const [currentPassword, setCurrentPassword] = useState("");
|
||||||
const [newPassword, setNewPassword] = useState("");
|
const [newPassword, setNewPassword] = useState("");
|
||||||
|
|
@ -474,7 +355,7 @@ function AppearanceTab() {
|
||||||
|
|
||||||
export function SettingsPage() {
|
export function SettingsPage() {
|
||||||
const [activeTab, setActiveTab] = useState<SettingsTab>("subscription");
|
const [activeTab, setActiveTab] = useState<SettingsTab>("subscription");
|
||||||
const [profile, setProfile] = useState<UserProfileData | null>(null);
|
const [profile, setProfile] = useState<TeamMeProfile | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
|
@ -535,8 +416,8 @@ export function SettingsPage() {
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex min-w-0 flex-col gap-8 lg:flex-row lg:items-start">
|
<div className="space-y-6">
|
||||||
<nav className="flex shrink-0 flex-row gap-1 overflow-x-auto rounded-[8px] border border-grayScale-100 bg-white p-1 lg:w-56 lg:flex-col">
|
<nav className="flex gap-1 overflow-x-auto border-b border-grayScale-100 pb-px">
|
||||||
{tabs.map((tab) => {
|
{tabs.map((tab) => {
|
||||||
const Icon = tab.icon;
|
const Icon = tab.icon;
|
||||||
const active = activeTab === tab.id;
|
const active = activeTab === tab.id;
|
||||||
|
|
@ -546,10 +427,10 @@ export function SettingsPage() {
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setActiveTab(tab.id)}
|
onClick={() => setActiveTab(tab.id)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center gap-2.5 whitespace-nowrap rounded-[6px] px-3 py-2.5 text-left text-sm font-medium transition-colors",
|
"flex shrink-0 items-center gap-2 whitespace-nowrap border-b-2 px-4 py-3 text-sm font-medium transition-colors",
|
||||||
active
|
active
|
||||||
? "bg-brand-50 text-brand-600"
|
? "border-brand-500 text-brand-600"
|
||||||
: "text-grayScale-600 hover:bg-grayScale-50",
|
: "border-transparent text-grayScale-500 hover:border-grayScale-200 hover:text-grayScale-700",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Icon className="h-4 w-4 shrink-0" />
|
<Icon className="h-4 w-4 shrink-0" />
|
||||||
|
|
@ -559,10 +440,9 @@ export function SettingsPage() {
|
||||||
})}
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<main className="min-h-[400px] min-w-0 w-full flex-1">
|
<main className="min-h-[400px] min-w-0 w-full">
|
||||||
{activeTab === "subscription" && <SubscriptionPlansTab />}
|
{activeTab === "subscription" && <SubscriptionPlansTab />}
|
||||||
{activeTab === "app-versions" && <AppVersionsTab />}
|
{activeTab === "app-versions" && <AppVersionsTab />}
|
||||||
{activeTab === "profile" && <ProfileTab profile={profile} />}
|
|
||||||
{activeTab === "security" && <SecurityTab memberId={profile.id} />}
|
{activeTab === "security" && <SecurityTab memberId={profile.id} />}
|
||||||
{activeTab === "appearance" && <AppearanceTab />}
|
{activeTab === "appearance" && <AppearanceTab />}
|
||||||
</main>
|
</main>
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ import { toast } from "sonner";
|
||||||
import { Card } from "../../components/ui/card";
|
import { Card } from "../../components/ui/card";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { Input } from "../../components/ui/input";
|
import { Input } from "../../components/ui/input";
|
||||||
|
import { ToggleSwitch } from "../../components/ui/toggle-switch";
|
||||||
import { PracticeQuestionEditorFields } from "../../components/content-management/PracticeQuestionEditorFields";
|
import { PracticeQuestionEditorFields } from "../../components/content-management/PracticeQuestionEditorFields";
|
||||||
import { AddNewPracticeReviewStep } from "./components/AddNewPracticeReviewStep";
|
import { AddNewPracticeReviewStep } from "./components/AddNewPracticeReviewStep";
|
||||||
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
||||||
|
|
@ -713,19 +714,12 @@ export function AddNewPracticePage() {
|
||||||
<label className="text-sm font-medium text-grayScale-700">
|
<label className="text-sm font-medium text-grayScale-700">
|
||||||
Shuffle questions
|
Shuffle questions
|
||||||
</label>
|
</label>
|
||||||
<button
|
<ToggleSwitch
|
||||||
type="button"
|
variant="plain"
|
||||||
onClick={() => setShuffleQuestions(!shuffleQuestions)}
|
checked={shuffleQuestions}
|
||||||
className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out ${
|
aria-label="Shuffle questions"
|
||||||
shuffleQuestions ? "bg-brand-500" : "bg-grayScale-300"
|
onCheckedChange={() => setShuffleQuestions(!shuffleQuestions)}
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-md ring-0 transition-transform duration-200 ease-in-out ${
|
|
||||||
shuffleQuestions ? "translate-x-5" : "translate-x-0"
|
|
||||||
}`}
|
|
||||||
/>
|
/>
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ import { useEffect, useState } from "react"
|
||||||
import { useNavigate } from "react-router-dom"
|
import { useNavigate } from "react-router-dom"
|
||||||
import { Search, Plus, RefreshCw, Edit2, ToggleLeft, ToggleRight, BookOpen, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react"
|
import { Search, Plus, RefreshCw, Edit2, ToggleLeft, ToggleRight, BookOpen, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { Select } from "../../components/ui/select"
|
import { Select } from "../../components/ui/select"
|
||||||
|
|
@ -27,6 +28,7 @@ import {
|
||||||
} from "../../components/ui/dialog"
|
} from "../../components/ui/dialog"
|
||||||
import { Textarea } from "../../components/ui/textarea"
|
import { Textarea } from "../../components/ui/textarea"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||||
|
|
@ -228,6 +230,15 @@ export function AllCoursesPage() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setCategoryFilter("all")
|
||||||
|
setPage(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: categoryFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center justify-center py-32">
|
<div className="flex flex-col items-center justify-center py-32">
|
||||||
|
|
@ -275,9 +286,13 @@ export function AllCoursesPage() {
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-5 pt-5">
|
<CardContent className="space-y-5 pt-5">
|
||||||
{/* Search / Filters */}
|
<AdminFiltersPanel
|
||||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center">
|
className="border-0 shadow-none"
|
||||||
<div className="relative flex-1">
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
summary={`Showing ${filteredCourses.length} of ${courses.length} courses`}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||||
<Input
|
<Input
|
||||||
placeholder="Search by title, description, or category…"
|
placeholder="Search by title, description, or category…"
|
||||||
|
|
@ -289,7 +304,8 @@ export function AllCoursesPage() {
|
||||||
className="pl-10 transition-colors focus:border-brand-300 focus:ring-brand-200"
|
className="pl-10 transition-colors focus:border-brand-300 focus:ring-brand-200"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
}
|
||||||
|
>
|
||||||
<Select
|
<Select
|
||||||
value={categoryFilter}
|
value={categoryFilter}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
|
|
@ -304,12 +320,7 @@ export function AllCoursesPage() {
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="text-xs font-medium text-grayScale-400">
|
|
||||||
Showing {filteredCourses.length} of {courses.length} courses
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Courses Table */}
|
{/* Courses Table */}
|
||||||
{filteredCourses.length > 0 ? (
|
{filteredCourses.length > 0 ? (
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { Link } from "react-router-dom"
|
||||||
import { BookOpen, ChevronDown, ChevronRight, FolderTree, Languages, Pencil, Plus, Trash2 } from "lucide-react"
|
import { BookOpen, ChevronDown, ChevronRight, FolderTree, Languages, Pencil, Plus, Trash2 } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../../components/ui/dialog"
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../../components/ui/dialog"
|
||||||
|
|
@ -18,6 +19,7 @@ import {
|
||||||
updateModule,
|
updateModule,
|
||||||
} from "../../api/courses.api"
|
} from "../../api/courses.api"
|
||||||
import { uploadImageFile } from "../../api/files.api"
|
import { uploadImageFile } from "../../api/files.api"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import type { CourseHierarchyRow, HumanLanguageHierarchyFlatRow, Practice } from "../../types/course.types"
|
import type { CourseHierarchyRow, HumanLanguageHierarchyFlatRow, Practice } from "../../types/course.types"
|
||||||
|
|
||||||
type IdFilterValue = number | "ALL"
|
type IdFilterValue = number | "ALL"
|
||||||
|
|
@ -650,6 +652,18 @@ export function HumanLanguageHierarchyPage() {
|
||||||
window.sessionStorage.setItem(HUMAN_LANGUAGE_RETURN_STATE_KEY, JSON.stringify(payload))
|
window.sessionStorage.setItem(HUMAN_LANGUAGE_RETURN_STATE_KEY, JSON.stringify(payload))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setSelectedSubCategoryId("ALL")
|
||||||
|
setSelectedCourseId("ALL")
|
||||||
|
setSelectedLevelId("ALL")
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: selectedSubCategoryId, defaultValue: "ALL" },
|
||||||
|
{ value: selectedCourseId, defaultValue: "ALL" },
|
||||||
|
{ value: selectedLevelId, defaultValue: "ALL" },
|
||||||
|
])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto max-w-6xl space-y-6">
|
<div className="mx-auto max-w-6xl space-y-6">
|
||||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
|
@ -667,11 +681,11 @@ export function HumanLanguageHierarchyPage() {
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card className="border border-grayScale-200 shadow-sm">
|
<AdminFiltersPanel
|
||||||
<CardHeader className="pb-3">
|
activeFilterCount={activeFilterCount}
|
||||||
<CardTitle className="text-lg">Filters</CardTitle>
|
onClearFilters={clearFilters}
|
||||||
</CardHeader>
|
defaultOpen={activeFilterCount > 0}
|
||||||
<CardContent className="space-y-6">
|
>
|
||||||
<div className="grid gap-4 md:grid-cols-3">
|
<div className="grid gap-4 md:grid-cols-3">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label htmlFor="hl-subcategory-filter" className="text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
<label htmlFor="hl-subcategory-filter" className="text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||||
|
|
@ -764,8 +778,7 @@ export function HumanLanguageHierarchyPage() {
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</AdminFiltersPanel>
|
||||||
</Card>
|
|
||||||
|
|
||||||
{selectedSubCategoryId !== "ALL" ? (
|
{selectedSubCategoryId !== "ALL" ? (
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { Link, useLocation, useNavigate, useParams } from "react-router-dom"
|
||||||
import { ArrowLeft, BookOpen, Eye, FileText, Plus, Search, Trophy, Video } from "lucide-react"
|
import { ArrowLeft, BookOpen, Eye, FileText, Plus, Search, Trophy, Video } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { Card } from "../../components/ui/card"
|
import { Card } from "../../components/ui/card"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../../components/ui/dialog"
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../../components/ui/dialog"
|
||||||
|
|
@ -12,6 +13,7 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
import { Textarea } from "../../components/ui/textarea"
|
import { Textarea } from "../../components/ui/textarea"
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import {
|
import {
|
||||||
getLessonsBySubModule,
|
getLessonsBySubModule,
|
||||||
getQuestionSetsByOwner,
|
getQuestionSetsByOwner,
|
||||||
|
|
@ -347,6 +349,17 @@ export function HumanLanguageSubModulePage() {
|
||||||
() => filterLessons(lessons, lessonSearch, lessonActiveFilter),
|
() => filterLessons(lessons, lessonSearch, lessonActiveFilter),
|
||||||
[lessons, lessonSearch, lessonActiveFilter],
|
[lessons, lessonSearch, lessonActiveFilter],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const practiceActiveFilterCount = countActiveFilters([
|
||||||
|
{ value: practiceStatusFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
const lessonActiveFilterCount = countActiveFilters([
|
||||||
|
{ value: lessonActiveFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
const capstoneActiveFilterCount = countActiveFilters([
|
||||||
|
{ value: capstoneStatusFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
const subModuleLabel = useMemo(() => {
|
const subModuleLabel = useMemo(() => {
|
||||||
const rawTitle = subCourse?.title?.trim()
|
const rawTitle = subCourse?.title?.trim()
|
||||||
if (!rawTitle) return "Sub-module"
|
if (!rawTitle) return "Sub-module"
|
||||||
|
|
@ -797,8 +810,11 @@ export function HumanLanguageSubModulePage() {
|
||||||
|
|
||||||
{activeTab === "practices" ? (
|
{activeTab === "practices" ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
<AdminFiltersPanel
|
||||||
<div className="relative min-w-[200px] flex-1">
|
activeFilterCount={practiceActiveFilterCount}
|
||||||
|
onClearFilters={() => setPracticeStatusFilter("all")}
|
||||||
|
search={
|
||||||
|
<div className="relative min-w-[200px] w-full">
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
className="pl-9"
|
className="pl-9"
|
||||||
|
|
@ -808,8 +824,10 @@ export function HumanLanguageSubModulePage() {
|
||||||
aria-label="Search practices"
|
aria-label="Search practices"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
<Select
|
<Select
|
||||||
className="w-full sm:w-48 sm:shrink-0"
|
className="w-full sm:w-48"
|
||||||
value={practiceStatusFilter}
|
value={practiceStatusFilter}
|
||||||
onChange={(e) => setPracticeStatusFilter(e.target.value as "all" | QuestionSetStatus)}
|
onChange={(e) => setPracticeStatusFilter(e.target.value as "all" | QuestionSetStatus)}
|
||||||
aria-label="Filter practices by status"
|
aria-label="Filter practices by status"
|
||||||
|
|
@ -819,7 +837,7 @@ export function HumanLanguageSubModulePage() {
|
||||||
<option value="DRAFT">Draft</option>
|
<option value="DRAFT">Draft</option>
|
||||||
<option value="ARCHIVED">Archived</option>
|
<option value="ARCHIVED">Archived</option>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
{renderQuestionSetTable(
|
{renderQuestionSetTable(
|
||||||
filteredPractices,
|
filteredPractices,
|
||||||
practices,
|
practices,
|
||||||
|
|
@ -833,8 +851,11 @@ export function HumanLanguageSubModulePage() {
|
||||||
|
|
||||||
{activeTab === "lessons" ? (
|
{activeTab === "lessons" ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
<AdminFiltersPanel
|
||||||
<div className="relative min-w-[200px] flex-1">
|
activeFilterCount={lessonActiveFilterCount}
|
||||||
|
onClearFilters={() => setLessonActiveFilter("all")}
|
||||||
|
search={
|
||||||
|
<div className="relative min-w-[200px] w-full">
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
className="pl-9"
|
className="pl-9"
|
||||||
|
|
@ -844,8 +865,10 @@ export function HumanLanguageSubModulePage() {
|
||||||
aria-label="Search lessons"
|
aria-label="Search lessons"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
<Select
|
<Select
|
||||||
className="w-full sm:w-48 sm:shrink-0"
|
className="w-full sm:w-48"
|
||||||
value={lessonActiveFilter}
|
value={lessonActiveFilter}
|
||||||
onChange={(e) => setLessonActiveFilter(e.target.value as LessonActiveFilter)}
|
onChange={(e) => setLessonActiveFilter(e.target.value as LessonActiveFilter)}
|
||||||
aria-label="Filter lessons by status"
|
aria-label="Filter lessons by status"
|
||||||
|
|
@ -854,15 +877,18 @@ export function HumanLanguageSubModulePage() {
|
||||||
<option value="active">Active only</option>
|
<option value="active">Active only</option>
|
||||||
<option value="inactive">Inactive only</option>
|
<option value="inactive">Inactive only</option>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
{renderLessonsTable(filteredLessons, lessons)}
|
{renderLessonsTable(filteredLessons, lessons)}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{activeTab === "capstones" ? (
|
{activeTab === "capstones" ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
<AdminFiltersPanel
|
||||||
<div className="relative min-w-[200px] flex-1">
|
activeFilterCount={capstoneActiveFilterCount}
|
||||||
|
onClearFilters={() => setCapstoneStatusFilter("all")}
|
||||||
|
search={
|
||||||
|
<div className="relative min-w-[200px] w-full">
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
className="pl-9"
|
className="pl-9"
|
||||||
|
|
@ -872,8 +898,10 @@ export function HumanLanguageSubModulePage() {
|
||||||
aria-label="Search capstones"
|
aria-label="Search capstones"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
<Select
|
<Select
|
||||||
className="w-full sm:w-48 sm:shrink-0"
|
className="w-full sm:w-48"
|
||||||
value={capstoneStatusFilter}
|
value={capstoneStatusFilter}
|
||||||
onChange={(e) => setCapstoneStatusFilter(e.target.value as "all" | QuestionSetStatus)}
|
onChange={(e) => setCapstoneStatusFilter(e.target.value as "all" | QuestionSetStatus)}
|
||||||
aria-label="Filter capstones by status"
|
aria-label="Filter capstones by status"
|
||||||
|
|
@ -883,7 +911,7 @@ export function HumanLanguageSubModulePage() {
|
||||||
<option value="DRAFT">Draft</option>
|
<option value="DRAFT">Draft</option>
|
||||||
<option value="ARCHIVED">Archived</option>
|
<option value="ARCHIVED">Archived</option>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
{renderQuestionSetTable(
|
{renderQuestionSetTable(
|
||||||
filteredCapstones,
|
filteredCapstones,
|
||||||
capstones,
|
capstones,
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ import {
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import {
|
import {
|
||||||
|
|
@ -25,6 +26,7 @@ import {
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../../components/ui/dialog"
|
} from "../../components/ui/dialog"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import { QuestionTypeCard } from "./components/QuestionTypeCard"
|
import { QuestionTypeCard } from "./components/QuestionTypeCard"
|
||||||
|
|
@ -71,6 +73,11 @@ export function QuestionTypeLibraryPage() {
|
||||||
const hasActiveFilters =
|
const hasActiveFilters =
|
||||||
query.trim().length > 0 || statusFilter !== "All" || scopeFilter !== "all"
|
query.trim().length > 0 || statusFilter !== "All" || scopeFilter !== "all"
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: statusFilter, defaultValue: "All" },
|
||||||
|
{ value: scopeFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -236,7 +243,12 @@ export function QuestionTypeLibraryPage() {
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<div className="border-b border-grayScale-100 bg-grayScale-50/60 px-6 py-5 space-y-4">
|
<div className="border-b border-grayScale-100 bg-grayScale-50/60 px-6 py-5">
|
||||||
|
<AdminFiltersPanel
|
||||||
|
className="border-0 bg-transparent shadow-none"
|
||||||
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
search={
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Search className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
|
|
@ -256,8 +268,8 @@ export function QuestionTypeLibraryPage() {
|
||||||
</button>
|
</button>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
>
|
||||||
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
|
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||||
|
|
@ -297,20 +309,7 @@ export function QuestionTypeLibraryPage() {
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</AdminFiltersPanel>
|
||||||
{hasActiveFilters ? (
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-8 shrink-0 self-start rounded-[8px] px-3 text-xs font-semibold text-grayScale-500 hover:text-brand-600 lg:self-center"
|
|
||||||
disabled={loading}
|
|
||||||
onClick={clearFilters}
|
|
||||||
>
|
|
||||||
Clear filters
|
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { Link } from "react-router-dom"
|
||||||
import { Plus, Search, Edit, Trash2, HelpCircle, X, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react"
|
import { Plus, Search, Edit, Trash2, HelpCircle, X, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react"
|
||||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { Select } from "../../components/ui/select"
|
import { Select } from "../../components/ui/select"
|
||||||
|
|
@ -17,6 +18,7 @@ import {
|
||||||
} from "../../components/ui/table"
|
} from "../../components/ui/table"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { deleteQuestion, getQuestionById, getQuestions, updateQuestion } from "../../api/courses.api"
|
import { deleteQuestion, getQuestionById, getQuestions, updateQuestion } from "../../api/courses.api"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import type { QuestionDetail } from "../../types/course.types"
|
import type { QuestionDetail } from "../../types/course.types"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
|
|
@ -321,6 +323,19 @@ export function QuestionsPage() {
|
||||||
return pages
|
return pages
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setTypeFilter("all")
|
||||||
|
setDifficultyFilter("all")
|
||||||
|
setStatusFilter("all")
|
||||||
|
setPage(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: typeFilter, defaultValue: "all" },
|
||||||
|
{ value: difficultyFilter, defaultValue: "all" },
|
||||||
|
{ value: statusFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
{/* Page Header */}
|
{/* Page Header */}
|
||||||
|
|
@ -359,9 +374,13 @@ export function QuestionsPage() {
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-5 pt-5">
|
<CardContent className="space-y-5 pt-5">
|
||||||
{/* Search and Filters */}
|
<AdminFiltersPanel
|
||||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center">
|
className="border-0 shadow-none"
|
||||||
<div className="relative flex-1">
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
summary={`Showing ${paginatedQuestions.length} of ${totalCount} questions`}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||||
<Input
|
<Input
|
||||||
placeholder="Search questions..."
|
placeholder="Search questions..."
|
||||||
|
|
@ -370,12 +389,14 @@ export function QuestionsPage() {
|
||||||
className="pl-10 transition-colors focus:border-brand-300 focus:ring-brand-200"
|
className="pl-10 transition-colors focus:border-brand-300 focus:ring-brand-200"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<Select
|
<Select
|
||||||
value={typeFilter}
|
value={typeFilter}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setTypeFilter(e.target.value as QuestionTypeFilter)
|
setTypeFilter(e.target.value as QuestionTypeFilter)
|
||||||
|
setPage(1)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<option value="all">All Types</option>
|
<option value="all">All Types</option>
|
||||||
|
|
@ -388,6 +409,7 @@ export function QuestionsPage() {
|
||||||
value={difficultyFilter}
|
value={difficultyFilter}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setDifficultyFilter(e.target.value as DifficultyFilter)
|
setDifficultyFilter(e.target.value as DifficultyFilter)
|
||||||
|
setPage(1)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<option value="all">All Difficulties</option>
|
<option value="all">All Difficulties</option>
|
||||||
|
|
@ -399,6 +421,7 @@ export function QuestionsPage() {
|
||||||
value={statusFilter}
|
value={statusFilter}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setStatusFilter(e.target.value as StatusFilter)
|
setStatusFilter(e.target.value as StatusFilter)
|
||||||
|
setPage(1)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<option value="all">All Statuses</option>
|
<option value="all">All Statuses</option>
|
||||||
|
|
@ -407,12 +430,7 @@ export function QuestionsPage() {
|
||||||
<option value="INACTIVE">Inactive</option>
|
<option value="INACTIVE">Inactive</option>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
|
|
||||||
{/* Results count */}
|
|
||||||
<div className="text-xs font-medium text-grayScale-400">
|
|
||||||
Showing {paginatedQuestions.length} of {totalCount} questions
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="rounded-xl border bg-white">
|
<div className="rounded-xl border bg-white">
|
||||||
<Table>
|
<Table>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { type ChangeEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
|
import { type ChangeEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||||
import { ArrowLeft, ChevronDown, ChevronRight, Image as ImageIcon, Mic, Plus, Trash2, Upload } from "lucide-react"
|
import { ArrowLeft, ChevronDown, ChevronRight, Image as ImageIcon, Mic, Plus, Trash2, Upload } from "lucide-react"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { Textarea } from "../../components/ui/textarea"
|
import { Textarea } from "../../components/ui/textarea"
|
||||||
|
|
@ -30,6 +31,7 @@ import {
|
||||||
} from "../../components/ui/dropdown-menu"
|
} from "../../components/ui/dropdown-menu"
|
||||||
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
|
|
||||||
const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024
|
const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024
|
||||||
|
|
@ -1272,6 +1274,14 @@ export function SpeakingPage() {
|
||||||
return Array.from(groups.values())
|
return Array.from(groups.values())
|
||||||
}, [audioQuestions])
|
}, [audioQuestions])
|
||||||
|
|
||||||
|
const clearAudioFilters = () => {
|
||||||
|
setSelectedPracticeId("")
|
||||||
|
setPracticeFilterSearch("")
|
||||||
|
setAudioPage(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const audioActiveFilterCount = countActiveFilters([{ value: selectedPracticeId }])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-7xl space-y-6 pb-10 sm:space-y-8 sm:pb-12">
|
<div className="mx-auto w-full max-w-7xl space-y-6 pb-10 sm:space-y-8 sm:pb-12">
|
||||||
<div className="flex flex-col gap-4 border-b border-grayScale-100 pb-6 sm:flex-row sm:items-end sm:justify-between sm:pb-8">
|
<div className="flex flex-col gap-4 border-b border-grayScale-100 pb-6 sm:flex-row sm:items-end sm:justify-between sm:pb-8">
|
||||||
|
|
@ -1305,7 +1315,26 @@ export function SpeakingPage() {
|
||||||
<p className="mt-1 text-xs font-normal text-grayScale-500 sm:text-sm">
|
<p className="mt-1 text-xs font-normal text-grayScale-500 sm:text-sm">
|
||||||
Tap a row to view details. Speaking practices create AUDIO question sets linked to a sub-course.
|
Tap a row to view details. Speaking practices create AUDIO question sets linked to a sub-course.
|
||||||
</p>
|
</p>
|
||||||
<div className="mt-3 max-w-md space-y-1.5">
|
</CardHeader>
|
||||||
|
<div className="border-b border-grayScale-100 px-5 py-4 sm:px-6">
|
||||||
|
<AdminFiltersPanel
|
||||||
|
className="border-0 shadow-none"
|
||||||
|
activeFilterCount={audioActiveFilterCount}
|
||||||
|
onClearFilters={clearAudioFilters}
|
||||||
|
summary={`Showing page ${audioPage} of ${Math.max(1, Math.ceil(audioTotalCount / audioPageSize))} (${audioTotalCount} total)`}
|
||||||
|
search={
|
||||||
|
<Input
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSearchQuery(e.target.value)
|
||||||
|
setAudioPage(1)
|
||||||
|
}}
|
||||||
|
placeholder="Search question text, answer text, or practice..."
|
||||||
|
className="h-10"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="max-w-md space-y-1.5">
|
||||||
<label className="text-xs font-medium uppercase tracking-wide text-grayScale-500">
|
<label className="text-xs font-medium uppercase tracking-wide text-grayScale-500">
|
||||||
Filter by practice
|
Filter by practice
|
||||||
</label>
|
</label>
|
||||||
|
|
@ -1351,22 +1380,8 @@ export function SpeakingPage() {
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-3 max-w-md space-y-1.5">
|
</AdminFiltersPanel>
|
||||||
<label className="text-xs font-medium uppercase tracking-wide text-grayScale-500">Search</label>
|
|
||||||
<Input
|
|
||||||
value={searchQuery}
|
|
||||||
onChange={(e) => {
|
|
||||||
setSearchQuery(e.target.value)
|
|
||||||
setAudioPage(1)
|
|
||||||
}}
|
|
||||||
placeholder="Search question text, answer text, or practice..."
|
|
||||||
className="h-10"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 text-xs font-normal text-grayScale-400 sm:text-sm">
|
|
||||||
Showing page {audioPage} of {Math.max(1, Math.ceil(audioTotalCount / audioPageSize))} ({audioTotalCount} total)
|
|
||||||
</p>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="px-4 pb-6 pt-5 sm:px-6">
|
<CardContent className="px-4 pb-6 pt-5 sm:px-6">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex flex-col items-center gap-2 py-14 text-center text-sm text-grayScale-500">
|
<div className="flex flex-col items-center gap-2 py-14 text-center text-sm text-grayScale-500">
|
||||||
|
|
|
||||||
|
|
@ -16,19 +16,19 @@ import {
|
||||||
createCourseVideo,
|
createCourseVideo,
|
||||||
updateSubCourseVideo,
|
updateSubCourseVideo,
|
||||||
deleteSubCourseVideo,
|
deleteSubCourseVideo,
|
||||||
getRatings,
|
|
||||||
getVimeoSample,
|
getVimeoSample,
|
||||||
} from "../../api/courses.api"
|
} from "../../api/courses.api"
|
||||||
|
import { getRatings } from "../../api/ratings.api"
|
||||||
import { uploadVideoFile } from "../../api/files.api"
|
import { uploadVideoFile } from "../../api/files.api"
|
||||||
import type {
|
import type {
|
||||||
SubCourse,
|
SubCourse,
|
||||||
QuestionSet,
|
QuestionSet,
|
||||||
SubCourseVideo,
|
SubCourseVideo,
|
||||||
Rating,
|
|
||||||
VimeoSampleVideo,
|
VimeoSampleVideo,
|
||||||
VideoStatus,
|
VideoStatus,
|
||||||
VideoVisibility,
|
VideoVisibility,
|
||||||
} from "../../types/course.types"
|
} from "../../types/course.types"
|
||||||
|
import type { Rating } from "../../types/ratings.types"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
|
||||||
type TabType = "video" | "practice" | "ratings"
|
type TabType = "video" | "practice" | "ratings"
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
import { Search } from "lucide-react"
|
import { Search } from "lucide-react"
|
||||||
|
import { AdminFiltersPanel } from "../../../components/filters/AdminFiltersPanel"
|
||||||
import { Input } from "../../../components/ui/input"
|
import { Input } from "../../../components/ui/input"
|
||||||
import { Select } from "../../../components/ui/select"
|
import { Select } from "../../../components/ui/select"
|
||||||
|
import { countActiveFilters } from "../../../lib/adminFilterUtils"
|
||||||
import type { PublishStatusFilter } from "../../../lib/contentListFilters"
|
import type { PublishStatusFilter } from "../../../lib/contentListFilters"
|
||||||
import { cn } from "../../../lib/utils"
|
import { cn } from "../../../lib/utils"
|
||||||
|
|
||||||
|
|
@ -23,14 +25,17 @@ export function ContentListSearchFilterBar({
|
||||||
searchAriaLabel = "Search content",
|
searchAriaLabel = "Search content",
|
||||||
className,
|
className,
|
||||||
}: ContentListSearchFilterBarProps) {
|
}: ContentListSearchFilterBarProps) {
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: publishStatusFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<AdminFiltersPanel
|
||||||
className={cn(
|
className={cn("shadow-sm", className)}
|
||||||
"flex flex-wrap items-center gap-3 rounded-xl border border-grayScale-100 bg-white p-4 shadow-sm",
|
activeFilterCount={activeFilterCount}
|
||||||
className,
|
onClearFilters={() => onPublishStatusFilterChange("all")}
|
||||||
)}
|
search={
|
||||||
>
|
<div className="relative w-full">
|
||||||
<div className="relative min-w-[200px] flex-1">
|
|
||||||
<Search
|
<Search
|
||||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400"
|
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400"
|
||||||
aria-hidden
|
aria-hidden
|
||||||
|
|
@ -43,8 +48,10 @@ export function ContentListSearchFilterBar({
|
||||||
aria-label={searchAriaLabel}
|
aria-label={searchAriaLabel}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
<Select
|
<Select
|
||||||
className="w-full sm:w-48 sm:shrink-0"
|
className="w-full sm:w-48"
|
||||||
value={publishStatusFilter}
|
value={publishStatusFilter}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
onPublishStatusFilterChange(e.target.value as PublishStatusFilter)
|
onPublishStatusFilterChange(e.target.value as PublishStatusFilter)
|
||||||
|
|
@ -55,6 +62,6 @@ export function ContentListSearchFilterBar({
|
||||||
<option value="PUBLISHED">Published</option>
|
<option value="PUBLISHED">Published</option>
|
||||||
<option value="DRAFT">Draft</option>
|
<option value="DRAFT">Draft</option>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -20,11 +20,13 @@ import { cn } from "../../../lib/utils";
|
||||||
import {
|
import {
|
||||||
applyShortPreviewToEmbedUrl,
|
applyShortPreviewToEmbedUrl,
|
||||||
DEFAULT_PREVIEW_MAX_SECONDS,
|
DEFAULT_PREVIEW_MAX_SECONDS,
|
||||||
|
extractVimeoVideoId,
|
||||||
formatPreviewLength,
|
formatPreviewLength,
|
||||||
formatVideoDurationLabel,
|
formatVideoDurationLabel,
|
||||||
getVideoPreview,
|
getVideoPreview,
|
||||||
isDirectVideoFileUrl,
|
isDirectVideoFileUrl,
|
||||||
} from "../../../lib/videoPreview";
|
} from "../../../lib/videoPreview";
|
||||||
|
import { fetchVimeoDurationSeconds } from "../../../lib/vimeoVideoCache";
|
||||||
import { PreviewLimitedFileVideo } from "./PreviewLimitedFileVideo";
|
import { PreviewLimitedFileVideo } from "./PreviewLimitedFileVideo";
|
||||||
import type {
|
import type {
|
||||||
ContentAccessTier,
|
ContentAccessTier,
|
||||||
|
|
@ -121,6 +123,9 @@ export function VideoCard({
|
||||||
const [probedDurationSeconds, setProbedDurationSeconds] = useState<
|
const [probedDurationSeconds, setProbedDurationSeconds] = useState<
|
||||||
number | null
|
number | null
|
||||||
>(null);
|
>(null);
|
||||||
|
const [vimeoDurationSeconds, setVimeoDurationSeconds] = useState<
|
||||||
|
number | null
|
||||||
|
>(null);
|
||||||
const [previewOpen, setPreviewOpen] = useState(false);
|
const [previewOpen, setPreviewOpen] = useState(false);
|
||||||
/** Iframe players ignore URL limits in many cases — unmount after real time. */
|
/** Iframe players ignore URL limits in many cases — unmount after real time. */
|
||||||
const [iframeSessionDone, setIframeSessionDone] = useState(false);
|
const [iframeSessionDone, setIframeSessionDone] = useState(false);
|
||||||
|
|
@ -194,6 +199,34 @@ export function VideoCard({
|
||||||
};
|
};
|
||||||
}, [duration, durationSeconds, videoUrl]);
|
}, [duration, durationSeconds, videoUrl]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (duration?.trim()) {
|
||||||
|
setVimeoDurationSeconds(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
typeof durationSeconds === "number" &&
|
||||||
|
Number.isFinite(durationSeconds) &&
|
||||||
|
durationSeconds > 0
|
||||||
|
) {
|
||||||
|
setVimeoDurationSeconds(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const url = videoUrl?.trim() ?? "";
|
||||||
|
const vimeoId = extractVimeoVideoId(url);
|
||||||
|
if (!vimeoId) {
|
||||||
|
setVimeoDurationSeconds(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
void fetchVimeoDurationSeconds(vimeoId).then((seconds) => {
|
||||||
|
if (!cancelled) setVimeoDurationSeconds(seconds);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [duration, durationSeconds, videoUrl]);
|
||||||
|
|
||||||
const durationLabel = (() => {
|
const durationLabel = (() => {
|
||||||
const trimmed = duration?.trim();
|
const trimmed = duration?.trim();
|
||||||
if (trimmed) return trimmed;
|
if (trimmed) return trimmed;
|
||||||
|
|
@ -204,6 +237,13 @@ export function VideoCard({
|
||||||
? durationSeconds
|
? durationSeconds
|
||||||
: null;
|
: null;
|
||||||
if (fromApi != null) return formatVideoDurationLabel(fromApi);
|
if (fromApi != null) return formatVideoDurationLabel(fromApi);
|
||||||
|
if (
|
||||||
|
vimeoDurationSeconds != null &&
|
||||||
|
Number.isFinite(vimeoDurationSeconds) &&
|
||||||
|
vimeoDurationSeconds > 0
|
||||||
|
) {
|
||||||
|
return formatVideoDurationLabel(vimeoDurationSeconds);
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
probedDurationSeconds != null &&
|
probedDurationSeconds != null &&
|
||||||
Number.isFinite(probedDurationSeconds) &&
|
Number.isFinite(probedDurationSeconds) &&
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { Check, ArrowRight, Loader2 } from "lucide-react";
|
import { Check, ArrowRight, Loader2 } from "lucide-react";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
import { Button } from "../../../../components/ui/button";
|
import { Button } from "../../../../components/ui/button";
|
||||||
import {
|
import {
|
||||||
Avatar,
|
Avatar,
|
||||||
|
|
@ -67,7 +68,10 @@ export function PersonaStep({
|
||||||
No active personas available.
|
No active personas available.
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-1 text-sm text-grayScale-400">
|
<p className="mt-1 text-sm text-grayScale-400">
|
||||||
Add personas in the admin panel, then return here.
|
<Link to="/personas" className="font-medium text-brand-600 hover:underline">
|
||||||
|
Add personas
|
||||||
|
</Link>{" "}
|
||||||
|
in the admin panel, then return here.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|
|
||||||
185
src/pages/faqs/EditFaqPage.tsx
Normal file
185
src/pages/faqs/EditFaqPage.tsx
Normal file
|
|
@ -0,0 +1,185 @@
|
||||||
|
import { useCallback, useEffect, useState } from "react"
|
||||||
|
import { Link, useNavigate, useParams } from "react-router-dom"
|
||||||
|
import { ArrowLeft } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { getFAQById, getFAQs, updateFAQ } from "../../api/faq.api"
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { useFaqPermissions } from "../../hooks/useFaqPermissions"
|
||||||
|
import { deriveFaqCategories } from "../../lib/faqDisplay"
|
||||||
|
import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors"
|
||||||
|
import type { FAQ, FAQStatus } from "../../types/faq.types"
|
||||||
|
import { FaqAccessDenied } from "./components/FaqAccessDenied"
|
||||||
|
import {
|
||||||
|
draftToUpdatePayload,
|
||||||
|
FaqForm,
|
||||||
|
validateFaqDraft,
|
||||||
|
type FaqFormDraft,
|
||||||
|
} from "./components/FaqForm"
|
||||||
|
|
||||||
|
function faqToDraft(faq: FAQ): FaqFormDraft {
|
||||||
|
return {
|
||||||
|
question: faq.question,
|
||||||
|
answer: faq.answer,
|
||||||
|
category: faq.category ?? "",
|
||||||
|
display_order: String(faq.display_order ?? 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditFaqPage() {
|
||||||
|
const { id } = useParams<{ id: string }>()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const faqId = Number(id)
|
||||||
|
const { canGet, canUpdate, loading: permissionsLoading } = useFaqPermissions()
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [savingAction, setSavingAction] = useState<"draft" | "publish" | null>(null)
|
||||||
|
const [draft, setDraft] = useState<FaqFormDraft | null>(null)
|
||||||
|
const [currentStatus, setCurrentStatus] = useState<FAQStatus>("INACTIVE")
|
||||||
|
const [categories, setCategories] = useState<string[]>([])
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
if (!Number.isFinite(faqId) || faqId <= 0) {
|
||||||
|
toast.error("Invalid FAQ ID")
|
||||||
|
navigate("/help/faqs", { replace: true })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!canGet) {
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
setPermissionDenied(false)
|
||||||
|
try {
|
||||||
|
const [faqRes, listRes] = await Promise.all([
|
||||||
|
getFAQById(faqId),
|
||||||
|
getFAQs({ limit: 200, offset: 0 }),
|
||||||
|
])
|
||||||
|
|
||||||
|
if (!faqRes.data) {
|
||||||
|
toast.error("FAQ not found")
|
||||||
|
navigate("/help/faqs", { replace: true })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setDraft(faqToDraft(faqRes.data))
|
||||||
|
setCurrentStatus(faqRes.data.status)
|
||||||
|
setCategories(deriveFaqCategories(listRes.data.faqs))
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const status = (e as { response?: { status?: number } })?.response?.status
|
||||||
|
if (status === 404) {
|
||||||
|
toast.error("FAQ not found")
|
||||||
|
navigate("/help/faqs", { replace: true })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (isFaqForbiddenError(e)) {
|
||||||
|
setPermissionDenied(true)
|
||||||
|
toast.error(getFaqApiErrorMessage(e, "You do not have permission to view this FAQ"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
toast.error(getFaqApiErrorMessage(e, "Failed to load FAQ"))
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [faqId, canGet, navigate])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
const handleSave = async (status: FAQStatus) => {
|
||||||
|
if (!draft) return
|
||||||
|
if (!canUpdate) {
|
||||||
|
toast.error("You do not have permission to update FAQs")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const validationError = validateFaqDraft(draft)
|
||||||
|
if (validationError) {
|
||||||
|
toast.error(validationError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setSaving(true)
|
||||||
|
setSavingAction(status === "ACTIVE" ? "publish" : "draft")
|
||||||
|
try {
|
||||||
|
const response = await updateFAQ(faqId, draftToUpdatePayload(draft, status))
|
||||||
|
if (!response.data) {
|
||||||
|
throw new Error("Empty update response")
|
||||||
|
}
|
||||||
|
setDraft(faqToDraft(response.data))
|
||||||
|
setCurrentStatus(response.data.status)
|
||||||
|
toast.success(
|
||||||
|
status === "ACTIVE"
|
||||||
|
? response.message ?? "FAQ published successfully"
|
||||||
|
: response.message ?? "FAQ saved as draft",
|
||||||
|
)
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
toast.error(getFaqApiErrorMessage(e, "Failed to update FAQ"))
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
setSavingAction(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissionsLoading && !canGet) {
|
||||||
|
return <FaqAccessDenied />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissionsLoading && permissionDenied) {
|
||||||
|
return <FaqAccessDenied apiForbidden />
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-3xl space-y-6 pb-12">
|
||||||
|
<Link
|
||||||
|
to="/help/faqs"
|
||||||
|
className="group flex w-fit items-center gap-2 text-sm font-semibold text-grayScale-600 transition-colors hover:text-brand-500"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4 transition-transform group-hover:-translate-x-0.5" />
|
||||||
|
Back to FAQs
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-sm font-semibold text-grayScale-500">Help center</p>
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-900">
|
||||||
|
Edit FAQ
|
||||||
|
</h1>
|
||||||
|
<p className="max-w-2xl text-sm text-grayScale-500">
|
||||||
|
Update question, answer, category, or display order. Save as draft or publish when ready.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card className="border border-grayScale-100 shadow-none">
|
||||||
|
<CardHeader className="border-b border-grayScale-100 pb-4">
|
||||||
|
<CardTitle className="text-lg">FAQ details</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="p-6 sm:p-8">
|
||||||
|
{loading || !draft ? (
|
||||||
|
<div className="flex justify-center py-8">
|
||||||
|
<SpinnerIcon className="h-6 w-6" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<FaqForm
|
||||||
|
draft={draft}
|
||||||
|
saving={saving}
|
||||||
|
savingAction={savingAction}
|
||||||
|
categories={categories}
|
||||||
|
currentStatus={currentStatus}
|
||||||
|
onChange={(patch) => setDraft((prev) => (prev ? { ...prev, ...patch } : prev))}
|
||||||
|
onSaveDraft={() => void handleSave("INACTIVE")}
|
||||||
|
onPublish={() => void handleSave("ACTIVE")}
|
||||||
|
onCancel={() => navigate("/help/faqs")}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
465
src/pages/faqs/FaqsPage.tsx
Normal file
465
src/pages/faqs/FaqsPage.tsx
Normal file
|
|
@ -0,0 +1,465 @@
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||||
|
import { Link } from "react-router-dom"
|
||||||
|
import {
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
CircleHelp,
|
||||||
|
Eye,
|
||||||
|
EyeOff,
|
||||||
|
ExternalLink,
|
||||||
|
Pencil,
|
||||||
|
Plus,
|
||||||
|
RefreshCw,
|
||||||
|
Search,
|
||||||
|
Trash2,
|
||||||
|
} from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { getFAQs, updateFAQ } from "../../api/faq.api"
|
||||||
|
import { Badge } from "../../components/ui/badge"
|
||||||
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { Card, CardContent } from "../../components/ui/card"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "../../components/ui/table"
|
||||||
|
import { useFaqPermissions } from "../../hooks/useFaqPermissions"
|
||||||
|
import {
|
||||||
|
deriveFaqCategories,
|
||||||
|
faqStatusBadgeVariant,
|
||||||
|
faqStatusLabel,
|
||||||
|
formatFaqDate,
|
||||||
|
suggestNextDisplayOrder,
|
||||||
|
} from "../../lib/faqDisplay"
|
||||||
|
import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
import type { FAQ, FAQStatus } from "../../types/faq.types"
|
||||||
|
import { CreateFaqDialog } from "./components/CreateFaqDialog"
|
||||||
|
import { FaqDeleteDialog } from "./components/FaqDeleteDialog"
|
||||||
|
import { FaqAccessDenied } from "./components/FaqAccessDenied"
|
||||||
|
import { FaqPublicPreviewDialog } from "./components/FaqPublicPreviewDialog"
|
||||||
|
|
||||||
|
type StatusFilter = "all" | FAQStatus
|
||||||
|
|
||||||
|
export function FaqsPage() {
|
||||||
|
const { canList, canCreate, canUpdate, canDelete, canGet, loading: permissionsLoading } =
|
||||||
|
useFaqPermissions()
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState(false)
|
||||||
|
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||||
|
const [faqs, setFaqs] = useState<FAQ[]>([])
|
||||||
|
const [totalCount, setTotalCount] = useState(0)
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
|
const [query, setQuery] = useState("")
|
||||||
|
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all")
|
||||||
|
const [categoryFilter, setCategoryFilter] = useState("")
|
||||||
|
const [allCategories, setAllCategories] = useState<string[]>([])
|
||||||
|
const [faqPendingDelete, setFaqPendingDelete] = useState<FAQ | null>(null)
|
||||||
|
const [togglingId, setTogglingId] = useState<number | null>(null)
|
||||||
|
const [previewOpen, setPreviewOpen] = useState(false)
|
||||||
|
const [createOpen, setCreateOpen] = useState(false)
|
||||||
|
const [suggestedDisplayOrder, setSuggestedDisplayOrder] = useState(1)
|
||||||
|
|
||||||
|
const offset = (page - 1) * pageSize
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
if (!canList) {
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
setError(false)
|
||||||
|
setPermissionDenied(false)
|
||||||
|
try {
|
||||||
|
const res = await getFAQs({
|
||||||
|
status: statusFilter === "all" ? undefined : statusFilter,
|
||||||
|
category: categoryFilter || undefined,
|
||||||
|
limit: pageSize,
|
||||||
|
offset,
|
||||||
|
})
|
||||||
|
setFaqs(res.data.faqs)
|
||||||
|
setTotalCount(res.data.total_count)
|
||||||
|
|
||||||
|
const categoryRes = await getFAQs({ limit: 200, offset: 0 })
|
||||||
|
setAllCategories(deriveFaqCategories(categoryRes.data.faqs))
|
||||||
|
setSuggestedDisplayOrder(suggestNextDisplayOrder(categoryRes.data.faqs))
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
setError(true)
|
||||||
|
setFaqs([])
|
||||||
|
setTotalCount(0)
|
||||||
|
if (isFaqForbiddenError(e)) {
|
||||||
|
setPermissionDenied(true)
|
||||||
|
toast.error(getFaqApiErrorMessage(e, "You do not have permission to view FAQs"))
|
||||||
|
} else {
|
||||||
|
toast.error(getFaqApiErrorMessage(e, "Failed to load FAQs"))
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [canList, statusFilter, categoryFilter, pageSize, offset])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1)
|
||||||
|
}, [statusFilter, categoryFilter, pageSize])
|
||||||
|
|
||||||
|
const filtered = useMemo(() => {
|
||||||
|
const q = query.trim().toLowerCase()
|
||||||
|
if (!q) return faqs
|
||||||
|
return faqs.filter((faq) => {
|
||||||
|
const haystack = [faq.question, faq.answer, faq.category ?? ""]
|
||||||
|
.join(" ")
|
||||||
|
.toLowerCase()
|
||||||
|
return haystack.includes(q)
|
||||||
|
})
|
||||||
|
}, [faqs, query])
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||||
|
const pageStart = totalCount === 0 ? 0 : offset + 1
|
||||||
|
const pageEnd = Math.min(offset + faqs.length, totalCount)
|
||||||
|
const canPrev = page > 1
|
||||||
|
const canNext = page < totalPages
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: statusFilter, defaultValue: "all" },
|
||||||
|
{ value: categoryFilter },
|
||||||
|
])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setStatusFilter("all")
|
||||||
|
setCategoryFilter("")
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleStatus = async (faq: FAQ) => {
|
||||||
|
if (!canUpdate) {
|
||||||
|
toast.error("You do not have permission to update FAQs")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextStatus: FAQStatus = faq.status === "ACTIVE" ? "INACTIVE" : "ACTIVE"
|
||||||
|
setTogglingId(faq.id)
|
||||||
|
try {
|
||||||
|
const res = await updateFAQ(faq.id, { status: nextStatus })
|
||||||
|
if (res.data) {
|
||||||
|
setFaqs((prev) => prev.map((row) => (row.id === faq.id ? res.data! : row)))
|
||||||
|
}
|
||||||
|
toast.success(
|
||||||
|
nextStatus === "ACTIVE" ? "FAQ published" : "FAQ moved to draft",
|
||||||
|
)
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const msg = getFaqApiErrorMessage(e, "Failed to update FAQ status")
|
||||||
|
toast.error(msg)
|
||||||
|
} finally {
|
||||||
|
setTogglingId(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissionsLoading && !canList) {
|
||||||
|
return <FaqAccessDenied />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissionsLoading && permissionDenied) {
|
||||||
|
return <FaqAccessDenied apiForbidden />
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||||
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-grayScale-500">Help center</p>
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">
|
||||||
|
FAQs
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">
|
||||||
|
Manage frequently asked questions shown in the learner help center.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button variant="outline" className="shrink-0" onClick={() => setPreviewOpen(true)}>
|
||||||
|
<ExternalLink className="mr-2 h-4 w-4" />
|
||||||
|
Preview as learner
|
||||||
|
</Button>
|
||||||
|
{canCreate ? (
|
||||||
|
<Button
|
||||||
|
className="shrink-0 bg-brand-500 text-white hover:bg-brand-600"
|
||||||
|
onClick={() => setCreateOpen(true)}
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Add FAQ
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="shrink-0"
|
||||||
|
disabled={loading}
|
||||||
|
onClick={() => void load()}
|
||||||
|
>
|
||||||
|
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
|
||||||
|
Refresh
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AdminFiltersPanel
|
||||||
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
summary={
|
||||||
|
loading
|
||||||
|
? "Loading…"
|
||||||
|
: `${filtered.length} shown on page · ${totalCount} total`
|
||||||
|
}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
|
<Input
|
||||||
|
className="pl-9"
|
||||||
|
placeholder="Search question or answer…"
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{(["all", "ACTIVE", "INACTIVE"] as const).map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setStatusFilter(tab)}
|
||||||
|
className={cn(
|
||||||
|
"h-9 rounded-full px-3 text-xs font-semibold transition-colors",
|
||||||
|
statusFilter === tab
|
||||||
|
? "bg-brand-500 text-white"
|
||||||
|
: "bg-grayScale-100 text-grayScale-600 hover:bg-grayScale-200",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{tab === "all" ? "All" : tab === "ACTIVE" ? "Published" : "Draft"}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<label htmlFor="faq-category-filter" className="text-xs font-semibold text-grayScale-500">
|
||||||
|
Category
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="faq-category-filter"
|
||||||
|
value={categoryFilter}
|
||||||
|
onChange={(e) => setCategoryFilter(e.target.value)}
|
||||||
|
className="h-9 rounded-lg border border-grayScale-200 bg-white px-3 text-sm text-grayScale-800"
|
||||||
|
>
|
||||||
|
<option value="">All categories</option>
|
||||||
|
{allCategories.map((category) => (
|
||||||
|
<option key={category} value={category}>
|
||||||
|
{category}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</AdminFiltersPanel>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex justify-center py-16">
|
||||||
|
<SpinnerIcon className="h-6 w-6" />
|
||||||
|
</div>
|
||||||
|
) : error ? (
|
||||||
|
<Card className="border border-grayScale-100 shadow-none">
|
||||||
|
<CardContent className="flex flex-col items-center gap-3 py-16 text-center">
|
||||||
|
<p className="text-sm text-destructive">Could not load FAQs.</p>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => void load()}>
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : filtered.length === 0 ? (
|
||||||
|
<Card className="border border-grayScale-100 shadow-none">
|
||||||
|
<CardContent className="flex flex-col items-center gap-4 px-6 py-16 text-center">
|
||||||
|
<div className="grid h-14 w-14 place-items-center rounded-2xl bg-brand-100/50 text-brand-500">
|
||||||
|
<CircleHelp className="h-7 w-7" />
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-grayScale-500">
|
||||||
|
{faqs.length === 0
|
||||||
|
? "No FAQs yet. Create your first FAQ to populate the help center."
|
||||||
|
: "No FAQs match your search or filters."}
|
||||||
|
</p>
|
||||||
|
{canCreate && faqs.length === 0 ? (
|
||||||
|
<Button
|
||||||
|
className="bg-brand-500 text-white hover:bg-brand-600"
|
||||||
|
onClick={() => setCreateOpen(true)}
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Add FAQ
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<Card className="overflow-hidden border border-grayScale-100 shadow-none">
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Question</TableHead>
|
||||||
|
<TableHead>Category</TableHead>
|
||||||
|
<TableHead className="w-20 text-center">Order</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead>Updated</TableHead>
|
||||||
|
<TableHead className="text-right">Actions</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{filtered.map((faq) => (
|
||||||
|
<TableRow key={faq.id}>
|
||||||
|
<TableCell className="max-w-xs">
|
||||||
|
<p className="line-clamp-2 font-medium text-grayScale-900">
|
||||||
|
{faq.question}
|
||||||
|
</p>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{faq.category ? (
|
||||||
|
<Badge variant="secondary">{faq.category}</Badge>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-grayScale-400">—</span>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-center text-sm text-grayScale-600">
|
||||||
|
{faq.display_order}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={faqStatusBadgeVariant(faq.status)}>
|
||||||
|
{faqStatusLabel(faq.status)}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-grayScale-500">
|
||||||
|
{formatFaqDate(faq.updated_at || faq.created_at)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
{canUpdate ? (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={togglingId === faq.id}
|
||||||
|
onClick={() => void handleToggleStatus(faq)}
|
||||||
|
title={
|
||||||
|
faq.status === "ACTIVE" ? "Unpublish" : "Publish"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{faq.status === "ACTIVE" ? (
|
||||||
|
<EyeOff className="h-3.5 w-3.5" />
|
||||||
|
) : (
|
||||||
|
<Eye className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
<span className="sr-only">
|
||||||
|
{faq.status === "ACTIVE" ? "Unpublish" : "Publish"}
|
||||||
|
</span>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{canGet ? (
|
||||||
|
<Button variant="outline" size="sm" asChild>
|
||||||
|
<Link to={`/help/faqs/${faq.id}/edit`}>
|
||||||
|
<Pencil className="h-3.5 w-3.5" />
|
||||||
|
<span className="sr-only">Edit</span>
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{canDelete ? (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||||
|
onClick={() => setFaqPendingDelete(faq)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
<span className="sr-only">Delete</span>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && !error && totalCount > 0 ? (
|
||||||
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<p className="text-sm text-grayScale-500">
|
||||||
|
Showing {pageStart}–{pageEnd} of {totalCount}
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<select
|
||||||
|
value={pageSize}
|
||||||
|
onChange={(e) => setPageSize(Number(e.target.value))}
|
||||||
|
className="h-9 rounded-lg border border-grayScale-200 bg-white px-3 text-sm"
|
||||||
|
>
|
||||||
|
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||||
|
<option key={size} value={size}>
|
||||||
|
{size} per page
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={!canPrev}
|
||||||
|
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<span className="text-sm text-grayScale-600">
|
||||||
|
Page {page} of {totalPages}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={!canNext}
|
||||||
|
onClick={() => setPage((p) => p + 1)}
|
||||||
|
>
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<FaqPublicPreviewDialog open={previewOpen} onOpenChange={setPreviewOpen} />
|
||||||
|
|
||||||
|
<CreateFaqDialog
|
||||||
|
open={createOpen}
|
||||||
|
onOpenChange={setCreateOpen}
|
||||||
|
categories={allCategories}
|
||||||
|
suggestedDisplayOrder={suggestedDisplayOrder}
|
||||||
|
onCreated={() => void load()}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FaqDeleteDialog
|
||||||
|
faq={faqPendingDelete}
|
||||||
|
open={faqPendingDelete !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setFaqPendingDelete(null)
|
||||||
|
}}
|
||||||
|
onDeleted={() => {
|
||||||
|
setFaqPendingDelete(null)
|
||||||
|
void load()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
111
src/pages/faqs/components/CreateFaqDialog.tsx
Normal file
111
src/pages/faqs/components/CreateFaqDialog.tsx
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
import { useEffect, useState } from "react"
|
||||||
|
import { Plus } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { createFAQ } from "../../../api/faq.api"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../../../components/ui/dialog"
|
||||||
|
import { getFaqApiErrorMessage } from "../../../lib/faqErrors"
|
||||||
|
import {
|
||||||
|
draftToCreatePayload,
|
||||||
|
EMPTY_FAQ_FORM_DRAFT,
|
||||||
|
FaqForm,
|
||||||
|
validateFaqDraft,
|
||||||
|
type FaqFormDraft,
|
||||||
|
} from "./FaqForm"
|
||||||
|
import type { FAQStatus } from "../../../types/faq.types"
|
||||||
|
|
||||||
|
type CreateFaqDialogProps = {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
categories: string[]
|
||||||
|
suggestedDisplayOrder: number
|
||||||
|
onCreated?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CreateFaqDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
categories,
|
||||||
|
suggestedDisplayOrder,
|
||||||
|
onCreated,
|
||||||
|
}: CreateFaqDialogProps) {
|
||||||
|
const [draft, setDraft] = useState<FaqFormDraft>(EMPTY_FAQ_FORM_DRAFT)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [savingAction, setSavingAction] = useState<"draft" | "publish" | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
setDraft({
|
||||||
|
...EMPTY_FAQ_FORM_DRAFT,
|
||||||
|
display_order: String(suggestedDisplayOrder),
|
||||||
|
})
|
||||||
|
setSavingAction(null)
|
||||||
|
}
|
||||||
|
}, [open, suggestedDisplayOrder])
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next && !saving) onOpenChange(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCreate = async (status: FAQStatus) => {
|
||||||
|
const validationError = validateFaqDraft(draft)
|
||||||
|
if (validationError) {
|
||||||
|
toast.error(validationError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setSaving(true)
|
||||||
|
setSavingAction(status === "ACTIVE" ? "publish" : "draft")
|
||||||
|
try {
|
||||||
|
const response = await createFAQ(draftToCreatePayload(draft, status))
|
||||||
|
if (!response.data) {
|
||||||
|
throw new Error("Empty create response")
|
||||||
|
}
|
||||||
|
toast.success(
|
||||||
|
status === "ACTIVE"
|
||||||
|
? response.message ?? "FAQ published successfully"
|
||||||
|
: response.message ?? "FAQ saved as draft",
|
||||||
|
)
|
||||||
|
onOpenChange(false)
|
||||||
|
onCreated?.()
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
toast.error(getFaqApiErrorMessage(e, "Failed to create FAQ"))
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
setSavingAction(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="max-h-[90vh] max-w-lg overflow-y-auto">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<Plus className="h-5 w-5 text-brand-500" />
|
||||||
|
New FAQ
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Add a question and answer for the learner help center.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<FaqForm
|
||||||
|
draft={draft}
|
||||||
|
saving={saving}
|
||||||
|
savingAction={savingAction}
|
||||||
|
categories={categories}
|
||||||
|
onChange={(patch) => setDraft((prev) => ({ ...prev, ...patch }))}
|
||||||
|
onSaveDraft={() => void handleCreate("INACTIVE")}
|
||||||
|
onPublish={() => void handleCreate("ACTIVE")}
|
||||||
|
onCancel={() => onOpenChange(false)}
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
97
src/pages/faqs/components/FaqAccessDenied.tsx
Normal file
97
src/pages/faqs/components/FaqAccessDenied.tsx
Normal file
|
|
@ -0,0 +1,97 @@
|
||||||
|
import { useState } from "react"
|
||||||
|
import { Link } from "react-router-dom"
|
||||||
|
import { CircleHelp, LogOut, RefreshCw } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { syncRbacPermissions } from "../../../api/rbac.api"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import { Card, CardContent } from "../../../components/ui/card"
|
||||||
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
|
import { getSessionTeamRole, hasFaqRoleBypass } from "../../../lib/faqPermissions"
|
||||||
|
import { FAQ_FORBIDDEN_MESSAGE } from "../../../lib/faqErrors"
|
||||||
|
|
||||||
|
type FaqAccessDeniedProps = {
|
||||||
|
apiForbidden?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FaqAccessDenied({ apiForbidden = false }: FaqAccessDeniedProps) {
|
||||||
|
const [syncing, setSyncing] = useState(false)
|
||||||
|
const teamRole = getSessionTeamRole()
|
||||||
|
const canSync = hasFaqRoleBypass()
|
||||||
|
|
||||||
|
const handleSync = async () => {
|
||||||
|
setSyncing(true)
|
||||||
|
try {
|
||||||
|
const res = await syncRbacPermissions()
|
||||||
|
toast.success(res.data?.message ?? "RBAC permissions synced. Please sign in again.")
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const msg =
|
||||||
|
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
|
||||||
|
"Failed to sync RBAC permissions"
|
||||||
|
toast.error(msg)
|
||||||
|
} finally {
|
||||||
|
setSyncing(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-2xl space-y-6">
|
||||||
|
<Card className="border border-grayScale-100 shadow-none">
|
||||||
|
<CardContent className="flex flex-col items-center gap-4 px-6 py-16 text-center">
|
||||||
|
<CircleHelp className="h-10 w-10 text-grayScale-300" />
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h2 className="text-lg font-semibold text-grayScale-800">
|
||||||
|
{apiForbidden ? "FAQ access denied" : "No permission to view FAQs"}
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm text-grayScale-600">
|
||||||
|
{apiForbidden
|
||||||
|
? FAQ_FORBIDDEN_MESSAGE
|
||||||
|
: "Your account does not have the faqs.list permission."}
|
||||||
|
</p>
|
||||||
|
{teamRole ? (
|
||||||
|
<p className="text-xs text-grayScale-500">
|
||||||
|
Signed in as team role: <span className="font-medium">{teamRole}</span>
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full max-w-md rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3 text-left text-xs text-grayScale-600">
|
||||||
|
<p className="font-semibold text-grayScale-700">If you expect access:</p>
|
||||||
|
<ul className="mt-2 list-disc space-y-1 pl-4">
|
||||||
|
<li>Use a team account mapped to ADMIN, SUPER_ADMIN, or INSTRUCTOR with faqs.* permissions</li>
|
||||||
|
<li>Ensure migrations 000059 and 000084 are applied on the API database</li>
|
||||||
|
<li>After RBAC sync or deploy, sign out and sign in again for a fresh token</li>
|
||||||
|
<li>Custom roles need faqs.list, faqs.get, faqs.create, faqs.update, and faqs.delete assigned</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||||
|
{canSync ? (
|
||||||
|
<Button variant="outline" disabled={syncing} onClick={() => void handleSync()}>
|
||||||
|
{syncing ? (
|
||||||
|
<SpinnerIcon className="mr-2 h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<RefreshCw className="mr-2 h-4 w-4" />
|
||||||
|
)}
|
||||||
|
Sync RBAC permissions
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button variant="outline" asChild>
|
||||||
|
<Link to="/roles">Manage roles</Link>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
localStorage.clear()
|
||||||
|
window.location.href = "/login"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LogOut className="mr-2 h-4 w-4" />
|
||||||
|
Sign in again
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
91
src/pages/faqs/components/FaqDeleteDialog.tsx
Normal file
91
src/pages/faqs/components/FaqDeleteDialog.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
import { useState } from "react"
|
||||||
|
import { Trash2 } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { deleteFAQ } from "../../../api/faq.api"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import { getFaqApiErrorMessage } from "../../../lib/faqErrors"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../../../components/ui/dialog"
|
||||||
|
import type { FAQ } from "../../../types/faq.types"
|
||||||
|
|
||||||
|
type FaqDeleteDialogProps = {
|
||||||
|
faq: FAQ | null
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
onDeleted?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FaqDeleteDialog({
|
||||||
|
faq,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onDeleted,
|
||||||
|
}: FaqDeleteDialogProps) {
|
||||||
|
const [deleting, setDeleting] = useState(false)
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next && !deleting) onOpenChange(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleConfirm = async () => {
|
||||||
|
if (!faq) return
|
||||||
|
|
||||||
|
setDeleting(true)
|
||||||
|
try {
|
||||||
|
const response = await deleteFAQ(faq.id)
|
||||||
|
toast.success(response.message ?? "FAQ deleted successfully")
|
||||||
|
onOpenChange(false)
|
||||||
|
onDeleted?.()
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const msg = getFaqApiErrorMessage(e, "Failed to delete FAQ")
|
||||||
|
toast.error(msg)
|
||||||
|
} finally {
|
||||||
|
setDeleting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="max-w-md rounded-2xl border-grayScale-200 sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||||
|
<Trash2 className="h-5 w-5 shrink-0 text-destructive" aria-hidden />
|
||||||
|
Delete FAQ?
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-left text-grayScale-600">
|
||||||
|
This permanently removes the FAQ from the help center. This action cannot be undone.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{faq ? (
|
||||||
|
<div className="space-y-1 rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3">
|
||||||
|
<p className="text-sm font-semibold text-grayScale-900">{faq.question}</p>
|
||||||
|
<p className="text-xs text-grayScale-500">#{faq.id}</p>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<DialogFooter className="gap-2 sm:gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={deleting}
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
disabled={deleting || !faq}
|
||||||
|
onClick={() => void handleConfirm()}
|
||||||
|
>
|
||||||
|
{deleting ? "Deleting…" : "Delete FAQ"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
167
src/pages/faqs/components/FaqForm.tsx
Normal file
167
src/pages/faqs/components/FaqForm.tsx
Normal file
|
|
@ -0,0 +1,167 @@
|
||||||
|
import { Badge } from "../../../components/ui/badge"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import { Input } from "../../../components/ui/input"
|
||||||
|
import { Textarea } from "../../../components/ui/textarea"
|
||||||
|
import { faqStatusBadgeVariant, faqStatusLabel } from "../../../lib/faqDisplay"
|
||||||
|
import type { FAQStatus } from "../../../types/faq.types"
|
||||||
|
|
||||||
|
export type FaqFormDraft = {
|
||||||
|
question: string
|
||||||
|
answer: string
|
||||||
|
category: string
|
||||||
|
display_order: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EMPTY_FAQ_FORM_DRAFT: FaqFormDraft = {
|
||||||
|
question: "",
|
||||||
|
answer: "",
|
||||||
|
category: "",
|
||||||
|
display_order: "0",
|
||||||
|
}
|
||||||
|
|
||||||
|
type FaqFormProps = {
|
||||||
|
draft: FaqFormDraft
|
||||||
|
saving: boolean
|
||||||
|
savingAction?: "draft" | "publish" | null
|
||||||
|
categories: string[]
|
||||||
|
currentStatus?: FAQStatus
|
||||||
|
onChange: (patch: Partial<FaqFormDraft>) => void
|
||||||
|
onSaveDraft: () => void
|
||||||
|
onPublish: () => void
|
||||||
|
onCancel: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FaqForm({
|
||||||
|
draft,
|
||||||
|
saving,
|
||||||
|
savingAction = null,
|
||||||
|
categories,
|
||||||
|
currentStatus,
|
||||||
|
onChange,
|
||||||
|
onSaveDraft,
|
||||||
|
onPublish,
|
||||||
|
onCancel,
|
||||||
|
}: FaqFormProps) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-5">
|
||||||
|
<div>
|
||||||
|
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||||
|
Question
|
||||||
|
</p>
|
||||||
|
<Textarea
|
||||||
|
value={draft.question}
|
||||||
|
onChange={(e) => onChange({ question: e.target.value })}
|
||||||
|
placeholder="How do I reset my password?"
|
||||||
|
rows={2}
|
||||||
|
disabled={saving}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||||
|
Answer
|
||||||
|
</p>
|
||||||
|
<Textarea
|
||||||
|
value={draft.answer}
|
||||||
|
onChange={(e) => onChange({ answer: e.target.value })}
|
||||||
|
placeholder="Go to login and click 'Forgot Password'."
|
||||||
|
rows={6}
|
||||||
|
disabled={saving}
|
||||||
|
/>
|
||||||
|
<p className="mt-1 text-xs text-grayScale-400">Plain text only.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-5 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||||
|
Category
|
||||||
|
</p>
|
||||||
|
<Input
|
||||||
|
value={draft.category}
|
||||||
|
onChange={(e) => onChange({ category: e.target.value })}
|
||||||
|
placeholder="Account"
|
||||||
|
list="faq-category-suggestions"
|
||||||
|
disabled={saving}
|
||||||
|
/>
|
||||||
|
{categories.length > 0 ? (
|
||||||
|
<datalist id="faq-category-suggestions">
|
||||||
|
{categories.map((category) => (
|
||||||
|
<option key={category} value={category} />
|
||||||
|
))}
|
||||||
|
</datalist>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||||
|
Display order
|
||||||
|
</p>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
value={draft.display_order}
|
||||||
|
onChange={(e) => onChange({ display_order: e.target.value })}
|
||||||
|
disabled={saving}
|
||||||
|
/>
|
||||||
|
<p className="mt-1 text-xs text-grayScale-400">
|
||||||
|
Lower numbers appear first.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-grayScale-100 pt-5">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Button variant="outline" disabled={saving} onClick={onCancel}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
{currentStatus ? (
|
||||||
|
<Badge variant={faqStatusBadgeVariant(currentStatus)}>
|
||||||
|
Currently {faqStatusLabel(currentStatus)}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={saving}
|
||||||
|
onClick={onSaveDraft}
|
||||||
|
>
|
||||||
|
{saving && savingAction === "draft" ? "Saving draft…" : "Save as draft"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="bg-brand-500 text-white hover:bg-brand-600"
|
||||||
|
disabled={saving}
|
||||||
|
onClick={onPublish}
|
||||||
|
>
|
||||||
|
{saving && savingAction === "publish" ? "Publishing…" : "Publish FAQ"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateFaqDraft(draft: FaqFormDraft): string | null {
|
||||||
|
if (!draft.question.trim()) return "Question is required"
|
||||||
|
if (!draft.answer.trim()) return "Answer is required"
|
||||||
|
const order = Number(draft.display_order)
|
||||||
|
if (!Number.isFinite(order) || order < 0) {
|
||||||
|
return "Display order must be a non-negative number"
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function draftToCreatePayload(draft: FaqFormDraft, status: FAQStatus) {
|
||||||
|
const category = draft.category.trim()
|
||||||
|
return {
|
||||||
|
question: draft.question.trim(),
|
||||||
|
answer: draft.answer.trim(),
|
||||||
|
category: category || null,
|
||||||
|
display_order: Number(draft.display_order),
|
||||||
|
status,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function draftToUpdatePayload(draft: FaqFormDraft, status: FAQStatus) {
|
||||||
|
return draftToCreatePayload(draft, status)
|
||||||
|
}
|
||||||
136
src/pages/faqs/components/FaqPublicPreviewDialog.tsx
Normal file
136
src/pages/faqs/components/FaqPublicPreviewDialog.tsx
Normal file
|
|
@ -0,0 +1,136 @@
|
||||||
|
import { useCallback, useEffect, useState } from "react"
|
||||||
|
import { Eye } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { getPublicFAQs } from "../../../api/faq.api"
|
||||||
|
import { Badge } from "../../../components/ui/badge"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../../../components/ui/dialog"
|
||||||
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
|
import { deriveFaqCategories } from "../../../lib/faqDisplay"
|
||||||
|
import type { FAQ } from "../../../types/faq.types"
|
||||||
|
|
||||||
|
type FaqPublicPreviewDialogProps = {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FaqPublicPreviewDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
}: FaqPublicPreviewDialogProps) {
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [faqs, setFaqs] = useState<FAQ[]>([])
|
||||||
|
const [categoryFilter, setCategoryFilter] = useState("")
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
const res = await getPublicFAQs({ limit: 200, offset: 0 })
|
||||||
|
setFaqs(res.data.faqs)
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
setFaqs([])
|
||||||
|
toast.error("Failed to load public FAQ preview")
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
void load()
|
||||||
|
}
|
||||||
|
}, [open, load])
|
||||||
|
|
||||||
|
const categories = deriveFaqCategories(faqs)
|
||||||
|
const filtered = categoryFilter
|
||||||
|
? faqs.filter((faq) => faq.category === categoryFilter)
|
||||||
|
: faqs
|
||||||
|
|
||||||
|
const grouped = filtered.reduce<Record<string, FAQ[]>>((acc, faq) => {
|
||||||
|
const key = faq.category?.trim() || "General"
|
||||||
|
if (!acc[key]) acc[key] = []
|
||||||
|
acc[key].push(faq)
|
||||||
|
return acc
|
||||||
|
}, {})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<Eye className="h-5 w-5 text-brand-500" />
|
||||||
|
Preview as learner
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Published FAQs from GET /faqs (ACTIVE only, no authentication).
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<label htmlFor="preview-category" className="text-xs font-semibold text-grayScale-500">
|
||||||
|
Category
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="preview-category"
|
||||||
|
value={categoryFilter}
|
||||||
|
onChange={(e) => setCategoryFilter(e.target.value)}
|
||||||
|
className="h-9 rounded-lg border border-grayScale-200 bg-white px-3 text-sm"
|
||||||
|
>
|
||||||
|
<option value="">All categories</option>
|
||||||
|
{categories.map((category) => (
|
||||||
|
<option key={category} value={category}>
|
||||||
|
{category}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<Button variant="outline" size="sm" disabled={loading} onClick={() => void load()}>
|
||||||
|
Refresh
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="max-h-[55vh] space-y-4 overflow-y-auto pr-1">
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex justify-center py-12">
|
||||||
|
<SpinnerIcon className="h-6 w-6" />
|
||||||
|
</div>
|
||||||
|
) : filtered.length === 0 ? (
|
||||||
|
<p className="py-12 text-center text-sm text-grayScale-500">
|
||||||
|
No published FAQs are visible on the public help center.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
Object.entries(grouped).map(([category, rows]) => (
|
||||||
|
<div key={category} className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h3 className="text-sm font-semibold text-grayScale-800">{category}</h3>
|
||||||
|
<Badge variant="secondary" className="text-[10px]">
|
||||||
|
{rows.length}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{rows.map((faq) => (
|
||||||
|
<div
|
||||||
|
key={faq.id}
|
||||||
|
className="rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3"
|
||||||
|
>
|
||||||
|
<p className="text-sm font-semibold text-grayScale-900">{faq.question}</p>
|
||||||
|
<p className="mt-1 whitespace-pre-wrap text-sm text-grayScale-600">
|
||||||
|
{faq.answer}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -10,7 +10,6 @@ import {
|
||||||
Clock,
|
Clock,
|
||||||
User,
|
User,
|
||||||
Trash2,
|
Trash2,
|
||||||
X,
|
|
||||||
Info,
|
Info,
|
||||||
Bug,
|
Bug,
|
||||||
Video,
|
Video,
|
||||||
|
|
@ -22,8 +21,10 @@ import {
|
||||||
ArrowUpCircle,
|
ArrowUpCircle,
|
||||||
MessageCircle,
|
MessageCircle,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { Input } from "../../components/ui/input";
|
import { Input } from "../../components/ui/input";
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
|
|
@ -300,10 +301,12 @@ export function IssuesPage() {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasActiveFilters = statusFilter || typeFilter;
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: statusFilter },
|
||||||
|
{ value: typeFilter },
|
||||||
|
]);
|
||||||
|
|
||||||
const clearFilters = () => {
|
const clearFilters = () => {
|
||||||
setSearchQuery("");
|
|
||||||
setStatusFilter("");
|
setStatusFilter("");
|
||||||
setTypeFilter("");
|
setTypeFilter("");
|
||||||
setPage(1);
|
setPage(1);
|
||||||
|
|
@ -423,9 +426,16 @@ export function IssuesPage() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filters */}
|
<AdminFiltersPanel
|
||||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
activeFilterCount={activeFilterCount}
|
||||||
<div className="relative flex-1 min-w-[200px]">
|
onClearFilters={clearFilters}
|
||||||
|
summary={
|
||||||
|
loading
|
||||||
|
? "Loading…"
|
||||||
|
: `${filteredIssues.length} shown · ${totalCount} total`
|
||||||
|
}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
placeholder="Search by subject, description, or type..."
|
placeholder="Search by subject, description, or type..."
|
||||||
|
|
@ -434,7 +444,9 @@ export function IssuesPage() {
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<select
|
<select
|
||||||
value={statusFilter}
|
value={statusFilter}
|
||||||
|
|
@ -472,19 +484,8 @@ export function IssuesPage() {
|
||||||
</select>
|
</select>
|
||||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{hasActiveFilters && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={clearFilters}
|
|
||||||
className="gap-1 text-grayScale-400 hover:text-grayScale-600"
|
|
||||||
>
|
|
||||||
<X className="h-3.5 w-3.5" />
|
|
||||||
Clear
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
</AdminFiltersPanel>
|
||||||
|
|
||||||
{/* Table */}
|
{/* Table */}
|
||||||
<div className="rounded-xl border bg-white">
|
<div className="rounded-xl border bg-white">
|
||||||
|
|
@ -518,7 +519,7 @@ export function IssuesPage() {
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-medium text-grayScale-500">No issues found</p>
|
<p className="text-sm font-medium text-grayScale-500">No issues found</p>
|
||||||
<p className="text-xs text-grayScale-400 mt-1">
|
<p className="text-xs text-grayScale-400 mt-1">
|
||||||
{hasActiveFilters || searchQuery
|
{activeFilterCount > 0 || searchQuery
|
||||||
? "Try adjusting your filters or search query"
|
? "Try adjusting your filters or search query"
|
||||||
: "Reported issues will appear here"}
|
: "Reported issues will appear here"}
|
||||||
</p>
|
</p>
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,12 @@ import {
|
||||||
getEmailTemplates,
|
getEmailTemplates,
|
||||||
parseEmailTemplatesResponse,
|
parseEmailTemplatesResponse,
|
||||||
} from "../../api/emailTemplates.api"
|
} from "../../api/emailTemplates.api"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Card, CardContent } from "../../components/ui/card"
|
import { Card, CardContent } from "../../components/ui/card"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import {
|
import {
|
||||||
|
|
@ -69,6 +71,14 @@ export function EmailTemplatesPage() {
|
||||||
})
|
})
|
||||||
}, [templates, query, statusFilter])
|
}, [templates, query, statusFilter])
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: statusFilter, defaultValue: "All" },
|
||||||
|
])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setStatusFilter("All")
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-6xl space-y-6">
|
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
|
@ -101,10 +111,16 @@ export function EmailTemplatesPage() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card className="border border-grayScale-100 shadow-none">
|
<AdminFiltersPanel
|
||||||
<CardContent className="space-y-4 p-4 sm:p-6">
|
activeFilterCount={activeFilterCount}
|
||||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center">
|
onClearFilters={clearFilters}
|
||||||
<div className="relative flex-1">
|
summary={
|
||||||
|
loading
|
||||||
|
? "Loading…"
|
||||||
|
: `${filtered.length} shown · ${totalCount} total from API`
|
||||||
|
}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
className="pl-9"
|
className="pl-9"
|
||||||
|
|
@ -113,6 +129,8 @@ export function EmailTemplatesPage() {
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
{(["All", "ACTIVE", "INACTIVE"] as const).map((tab) => (
|
{(["All", "ACTIVE", "INACTIVE"] as const).map((tab) => (
|
||||||
<button
|
<button
|
||||||
|
|
@ -130,14 +148,7 @@ export function EmailTemplatesPage() {
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
<p className="text-xs text-grayScale-500">
|
|
||||||
{loading
|
|
||||||
? "Loading…"
|
|
||||||
: `${filtered.length} shown · ${totalCount} total from API`}
|
|
||||||
</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex justify-center py-16">
|
<div className="flex justify-center py-16">
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,9 @@ import {
|
||||||
MailX,
|
MailX,
|
||||||
Search,
|
Search,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
|
Trash2,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Card, CardContent } from "../../components/ui/card"
|
import { Card, CardContent } from "../../components/ui/card"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
|
|
@ -24,6 +26,7 @@ import {
|
||||||
DropdownMenuRadioItem,
|
DropdownMenuRadioItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "../../components/ui/dropdown-menu"
|
} from "../../components/ui/dropdown-menu"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
import { useNavigate } from "react-router-dom"
|
import { useNavigate } from "react-router-dom"
|
||||||
|
|
@ -37,6 +40,7 @@ import {
|
||||||
markAllUnread,
|
markAllUnread,
|
||||||
} from "../../api/notifications.api"
|
} from "../../api/notifications.api"
|
||||||
import { NotificationDetailDialog } from "../../components/notifications/NotificationDetailDialog"
|
import { NotificationDetailDialog } from "../../components/notifications/NotificationDetailDialog"
|
||||||
|
import { NotificationDeleteDialog } from "../../components/notifications/NotificationDeleteDialog"
|
||||||
import {
|
import {
|
||||||
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
||||||
formatNotificationTimestamp,
|
formatNotificationTimestamp,
|
||||||
|
|
@ -183,6 +187,7 @@ export function NotificationsPage() {
|
||||||
const [detailOpen, setDetailOpen] = useState(false)
|
const [detailOpen, setDetailOpen] = useState(false)
|
||||||
const [detailLoading, setDetailLoading] = useState(false)
|
const [detailLoading, setDetailLoading] = useState(false)
|
||||||
const [detailError, setDetailError] = useState(false)
|
const [detailError, setDetailError] = useState(false)
|
||||||
|
const [notificationPendingDelete, setNotificationPendingDelete] = useState<Notification | null>(null)
|
||||||
|
|
||||||
const [channelFilter, setChannelFilter] = useState<"all" | "push" | "sms">("all")
|
const [channelFilter, setChannelFilter] = useState<"all" | "push" | "sms">("all")
|
||||||
const [activeStatusTab, setActiveStatusTab] = useState<"all" | "read" | "unread">("all")
|
const [activeStatusTab, setActiveStatusTab] = useState<"all" | "read" | "unread">("all")
|
||||||
|
|
@ -303,6 +308,20 @@ export function NotificationsPage() {
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: activeStatusTab, defaultValue: "all" },
|
||||||
|
{ value: channelFilter, defaultValue: "all" },
|
||||||
|
{ value: typeFilter, defaultValue: "all" },
|
||||||
|
{ value: levelFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setActiveStatusTab("all")
|
||||||
|
setChannelFilter("all")
|
||||||
|
setTypeFilter("all")
|
||||||
|
setLevelFilter("all")
|
||||||
|
}
|
||||||
|
|
||||||
const loadNotificationDetail = useCallback(async (id: string) => {
|
const loadNotificationDetail = useCallback(async (id: string) => {
|
||||||
setDetailLoading(true)
|
setDetailLoading(true)
|
||||||
setDetailError(false)
|
setDetailError(false)
|
||||||
|
|
@ -341,6 +360,22 @@ export function NotificationsPage() {
|
||||||
void loadNotificationDetail(notification.id)
|
void loadNotificationDetail(notification.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleNotificationDeleted = useCallback((id: string) => {
|
||||||
|
const removed = notifications.find((n) => n.id === id)
|
||||||
|
setNotifications((prev) => prev.filter((n) => n.id !== id))
|
||||||
|
setTotalCount((prev) => Math.max(0, prev - 1))
|
||||||
|
if (removed && !removed.is_read) {
|
||||||
|
setGlobalUnread((prev) => Math.max(0, prev - 1))
|
||||||
|
}
|
||||||
|
if (selectedNotificationId === id) {
|
||||||
|
setDetailOpen(false)
|
||||||
|
setSelectedNotification(null)
|
||||||
|
setSelectedNotificationId(null)
|
||||||
|
}
|
||||||
|
setNotificationPendingDelete(null)
|
||||||
|
window.dispatchEvent(new Event("notifications-updated"))
|
||||||
|
}, [notifications, selectedNotificationId])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-6xl bg-grayScale-50/60 rounded-2xl px-3 py-4 sm:px-4 sm:py-5">
|
<div className="mx-auto w-full max-w-6xl bg-grayScale-50/60 rounded-2xl px-3 py-4 sm:px-4 sm:py-5">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
|
|
@ -485,8 +520,24 @@ export function NotificationsPage() {
|
||||||
{/* Filters + table */}
|
{/* Filters + table */}
|
||||||
{!loading && !error && notifications.length > 0 && (
|
{!loading && !error && notifications.length > 0 && (
|
||||||
<>
|
<>
|
||||||
{/* Status tabs */}
|
<AdminFiltersPanel
|
||||||
<div className="mb-2 border-b border-grayScale-200">
|
className="mb-3"
|
||||||
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
summary={`${filteredNotifications.length} shown · ${totalCount} total`}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
|
<Input
|
||||||
|
placeholder="Search by title, message, or type…"
|
||||||
|
className="pl-9"
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="border-b border-grayScale-200">
|
||||||
<div className="-mb-px flex gap-6">
|
<div className="-mb-px flex gap-6">
|
||||||
{(["all", "unread", "read"] as const).map((tab) => (
|
{(["all", "unread", "read"] as const).map((tab) => (
|
||||||
<button
|
<button
|
||||||
|
|
@ -508,20 +559,7 @@ export function NotificationsPage() {
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
{/* Filters */}
|
|
||||||
<Card className="mb-3 shadow-none">
|
|
||||||
<CardContent className="flex flex-wrap items-center gap-3 p-4">
|
|
||||||
<div className="relative flex-1 min-w-[180px] max-w-sm">
|
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
|
||||||
<Input
|
|
||||||
placeholder="Search by title, message, or type…"
|
|
||||||
className="pl-9"
|
|
||||||
value={searchTerm}
|
|
||||||
onChange={(e) => setSearchTerm(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-xs font-medium text-grayScale-500">Channel</span>
|
<span className="text-xs font-medium text-grayScale-500">Channel</span>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
|
|
@ -597,8 +635,7 @@ export function NotificationsPage() {
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</AdminFiltersPanel>
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card className="overflow-hidden rounded-xl border bg-white shadow-none">
|
<Card className="overflow-hidden rounded-xl border bg-white shadow-none">
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
|
|
@ -719,6 +756,15 @@ export function NotificationsPage() {
|
||||||
>
|
>
|
||||||
View
|
View
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||||
|
onClick={() => setNotificationPendingDelete(n)}
|
||||||
|
title="Delete notification"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
|
|
@ -815,6 +861,20 @@ export function NotificationsPage() {
|
||||||
? () => void loadNotificationDetail(selectedNotificationId)
|
? () => void loadNotificationDetail(selectedNotificationId)
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
|
onDelete={
|
||||||
|
selectedNotification
|
||||||
|
? () => setNotificationPendingDelete(selectedNotification)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<NotificationDeleteDialog
|
||||||
|
notification={notificationPendingDelete}
|
||||||
|
open={notificationPendingDelete !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setNotificationPendingDelete(null)
|
||||||
|
}}
|
||||||
|
onDeleted={handleNotificationDeleted}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ import {
|
||||||
cancelScheduledNotification,
|
cancelScheduledNotification,
|
||||||
getScheduledNotifications,
|
getScheduledNotifications,
|
||||||
} from "../../api/notifications.api"
|
} from "../../api/notifications.api"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Card, CardContent } from "../../components/ui/card"
|
import { Card, CardContent } from "../../components/ui/card"
|
||||||
|
|
@ -32,6 +33,7 @@ import {
|
||||||
formatScheduledAtLabel,
|
formatScheduledAtLabel,
|
||||||
scheduledStatusBadgeVariant,
|
scheduledStatusBadgeVariant,
|
||||||
} from "../../lib/notificationBulk"
|
} from "../../lib/notificationBulk"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination"
|
||||||
import type {
|
import type {
|
||||||
|
|
@ -133,6 +135,16 @@ export function ScheduledNotificationsPage() {
|
||||||
return "—"
|
return "—"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: statusFilter },
|
||||||
|
{ value: channelFilter },
|
||||||
|
])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setStatusFilter("")
|
||||||
|
setChannelFilter("")
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-6xl space-y-6">
|
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
|
@ -160,8 +172,15 @@ export function ScheduledNotificationsPage() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card className="border border-grayScale-100 shadow-none">
|
<AdminFiltersPanel
|
||||||
<CardContent className="space-y-4 p-4 sm:p-6">
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
summary={
|
||||||
|
loading
|
||||||
|
? "Loading…"
|
||||||
|
: `${totalCount} job${totalCount === 1 ? "" : "s"}`
|
||||||
|
}
|
||||||
|
>
|
||||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||||
<Select
|
<Select
|
||||||
value={statusFilter}
|
value={statusFilter}
|
||||||
|
|
@ -185,11 +204,11 @@ export function ScheduledNotificationsPage() {
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
<Badge variant="secondary" className="w-fit">
|
|
||||||
{totalCount} job{totalCount === 1 ? "" : "s"}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
</div>
|
||||||
|
</AdminFiltersPanel>
|
||||||
|
|
||||||
|
<Card className="border border-grayScale-100 shadow-none">
|
||||||
|
<CardContent className="space-y-4 p-4 sm:p-6">
|
||||||
{loading && (
|
{loading && (
|
||||||
<div className="flex items-center justify-center py-16 text-sm text-grayScale-500">
|
<div className="flex items-center justify-center py-16 text-sm text-grayScale-500">
|
||||||
<SpinnerIcon className="mr-2 h-5 w-5" alt="" />
|
<SpinnerIcon className="mr-2 h-5 w-5" alt="" />
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import {
|
||||||
import { Link } from "react-router-dom"
|
import { Link } from "react-router-dom"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { getPayments } from "../../api/payments.api"
|
import { getPayments } from "../../api/payments.api"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
|
|
@ -26,7 +27,9 @@ import {
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../../components/ui/dialog"
|
} from "../../components/ui/dialog"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { Select } from "../../components/ui/select"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import {
|
import {
|
||||||
formatPaymentAmount,
|
formatPaymentAmount,
|
||||||
|
|
@ -37,6 +40,7 @@ import {
|
||||||
paymentCustomerName,
|
paymentCustomerName,
|
||||||
paymentStatusBadgeVariant,
|
paymentStatusBadgeVariant,
|
||||||
} from "../../lib/payments"
|
} from "../../lib/payments"
|
||||||
|
import { SUBSCRIPTION_CURRENCIES } from "../../lib/subscriptionPlans"
|
||||||
import type {
|
import type {
|
||||||
Payment,
|
Payment,
|
||||||
PaymentPlanCategory,
|
PaymentPlanCategory,
|
||||||
|
|
@ -92,19 +96,11 @@ export function PaymentsPage() {
|
||||||
const [statusFilter, setStatusFilter] = useState<PaymentStatus | "">("")
|
const [statusFilter, setStatusFilter] = useState<PaymentStatus | "">("")
|
||||||
const [providerFilter, setProviderFilter] = useState<PaymentProvider | "">("")
|
const [providerFilter, setProviderFilter] = useState<PaymentProvider | "">("")
|
||||||
const [planCategoryFilter, setPlanCategoryFilter] = useState<PaymentPlanCategory | "">("")
|
const [planCategoryFilter, setPlanCategoryFilter] = useState<PaymentPlanCategory | "">("")
|
||||||
const [currencyInput, setCurrencyInput] = useState("")
|
|
||||||
const [referenceInput, setReferenceInput] = useState("")
|
|
||||||
const [currencyFilter, setCurrencyFilter] = useState("")
|
const [currencyFilter, setCurrencyFilter] = useState("")
|
||||||
|
const [referenceInput, setReferenceInput] = useState("")
|
||||||
const [referenceFilter, setReferenceFilter] = useState("")
|
const [referenceFilter, setReferenceFilter] = useState("")
|
||||||
const [selected, setSelected] = useState<Payment | null>(null)
|
const [selected, setSelected] = useState<Payment | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const timer = window.setTimeout(() => {
|
|
||||||
setCurrencyFilter(currencyInput.trim().toUpperCase())
|
|
||||||
}, TEXT_FILTER_DEBOUNCE_MS)
|
|
||||||
return () => window.clearTimeout(timer)
|
|
||||||
}, [currencyInput])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = window.setTimeout(() => {
|
const timer = window.setTimeout(() => {
|
||||||
setReferenceFilter(referenceInput.trim())
|
setReferenceFilter(referenceInput.trim())
|
||||||
|
|
@ -114,7 +110,7 @@ export function PaymentsPage() {
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setOffset(0)
|
setOffset(0)
|
||||||
}, [currencyFilter, referenceFilter])
|
}, [referenceFilter])
|
||||||
|
|
||||||
const listFilters: PaymentListFilters = {
|
const listFilters: PaymentListFilters = {
|
||||||
status: statusFilter,
|
status: statusFilter,
|
||||||
|
|
@ -124,13 +120,15 @@ export function PaymentsPage() {
|
||||||
reference: referenceFilter,
|
reference: referenceFilter,
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasActiveFilters = Boolean(
|
const activeFilterCount = countActiveFilters([
|
||||||
listFilters.status ||
|
{ value: statusFilter },
|
||||||
listFilters.provider ||
|
{ value: providerFilter },
|
||||||
listFilters.planCategory ||
|
{ value: planCategoryFilter },
|
||||||
listFilters.currency ||
|
{ value: currencyFilter },
|
||||||
listFilters.reference,
|
{ value: referenceFilter },
|
||||||
)
|
])
|
||||||
|
|
||||||
|
const hasActiveFilters = activeFilterCount > 0
|
||||||
|
|
||||||
const fetchPayments = useCallback(
|
const fetchPayments = useCallback(
|
||||||
async (nextOffset: number, limit: number, filters: PaymentListFilters) => {
|
async (nextOffset: number, limit: number, filters: PaymentListFilters) => {
|
||||||
|
|
@ -193,9 +191,8 @@ export function PaymentsPage() {
|
||||||
setStatusFilter("")
|
setStatusFilter("")
|
||||||
setProviderFilter("")
|
setProviderFilter("")
|
||||||
setPlanCategoryFilter("")
|
setPlanCategoryFilter("")
|
||||||
setCurrencyInput("")
|
|
||||||
setReferenceInput("")
|
|
||||||
setCurrencyFilter("")
|
setCurrencyFilter("")
|
||||||
|
setReferenceInput("")
|
||||||
setReferenceFilter("")
|
setReferenceFilter("")
|
||||||
setOffset(0)
|
setOffset(0)
|
||||||
}
|
}
|
||||||
|
|
@ -282,7 +279,10 @@ export function PaymentsPage() {
|
||||||
<CardTitle className="text-sm font-bold text-grayScale-900">Transaction history</CardTitle>
|
<CardTitle className="text-sm font-bold text-grayScale-900">Transaction history</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
||||||
<div className="flex flex-col gap-3 rounded-[8px] border border-grayScale-100 bg-grayScale-50/40 p-3 sm:p-4">
|
<AdminFiltersPanel
|
||||||
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
>
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||||
Status
|
Status
|
||||||
|
|
@ -333,27 +333,23 @@ export function PaymentsPage() {
|
||||||
>
|
>
|
||||||
Currency
|
Currency
|
||||||
</label>
|
</label>
|
||||||
<div className="relative">
|
<Select
|
||||||
<Input
|
|
||||||
id="payments-currency-filter"
|
id="payments-currency-filter"
|
||||||
value={currencyInput}
|
value={currencyFilter}
|
||||||
onChange={(e) => setCurrencyInput(e.target.value)}
|
onChange={(e) => {
|
||||||
placeholder="e.g. ETB"
|
setCurrencyFilter(e.target.value)
|
||||||
|
setOffset(0)
|
||||||
|
}}
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
className="h-9 rounded-[6px] border-grayScale-200 pr-8 text-sm uppercase"
|
className="h-9 rounded-[6px] text-sm"
|
||||||
/>
|
|
||||||
{currencyInput ? (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
aria-label="Clear currency filter"
|
|
||||||
disabled={loading}
|
|
||||||
onClick={() => setCurrencyInput("")}
|
|
||||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-grayScale-400 hover:text-grayScale-600"
|
|
||||||
>
|
>
|
||||||
<X className="h-3.5 w-3.5" />
|
<option value="">All currencies</option>
|
||||||
</button>
|
{SUBSCRIPTION_CURRENCIES.map((currency) => (
|
||||||
) : null}
|
<option key={currency} value={currency}>
|
||||||
</div>
|
{currency}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<label
|
<label
|
||||||
|
|
@ -389,21 +385,7 @@ export function PaymentsPage() {
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{hasActiveFilters ? (
|
</AdminFiltersPanel>
|
||||||
<div className="flex justify-end border-t border-grayScale-100 pt-2">
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-7 rounded-[6px] px-2 text-xs text-grayScale-500"
|
|
||||||
disabled={loading}
|
|
||||||
onClick={clearFilters}
|
|
||||||
>
|
|
||||||
Clear all filters
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
||||||
|
|
|
||||||
441
src/pages/personas/PersonasPage.tsx
Normal file
441
src/pages/personas/PersonasPage.tsx
Normal file
|
|
@ -0,0 +1,441 @@
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||||
|
import {
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
Pencil,
|
||||||
|
Plus,
|
||||||
|
RefreshCw,
|
||||||
|
Search,
|
||||||
|
Trash2,
|
||||||
|
UserCircle2,
|
||||||
|
} from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { listPersonas, updatePersona } from "../../api/personas.api"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
|
import { Badge } from "../../components/ui/badge"
|
||||||
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { Card, CardContent } from "../../components/ui/card"
|
||||||
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { Select } from "../../components/ui/select"
|
||||||
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { ToggleSwitch } from "../../components/ui/toggle-switch"
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "../../components/ui/table"
|
||||||
|
import { usePersonaPermissions } from "../../hooks/usePersonaPermissions"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import {
|
||||||
|
formatPersonaDate,
|
||||||
|
personaAvatarUrl,
|
||||||
|
personaGenderLabel,
|
||||||
|
personaStatusLabel,
|
||||||
|
} from "../../lib/personaDisplay"
|
||||||
|
import {
|
||||||
|
getPersonaApiErrorMessage,
|
||||||
|
isPersonaForbiddenError,
|
||||||
|
} from "../../lib/personasErrors"
|
||||||
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
|
import type { LmsPersona } from "../../types/persona.types"
|
||||||
|
import { CreatePersonaDialog } from "./components/CreatePersonaDialog"
|
||||||
|
import { EditPersonaDialog } from "./components/EditPersonaDialog"
|
||||||
|
import { PersonaAccessDenied } from "./components/PersonaAccessDenied"
|
||||||
|
import { PersonaDeleteDialog } from "./components/PersonaDeleteDialog"
|
||||||
|
|
||||||
|
type PersonaStatusFilter = "all" | "active" | "inactive"
|
||||||
|
|
||||||
|
export function PersonasPage() {
|
||||||
|
const {
|
||||||
|
canList,
|
||||||
|
canCreate,
|
||||||
|
canUpdate,
|
||||||
|
canDelete,
|
||||||
|
loading: permissionsLoading,
|
||||||
|
} = usePersonaPermissions()
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState(false)
|
||||||
|
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||||
|
const [personas, setPersonas] = useState<LmsPersona[]>([])
|
||||||
|
const [totalCount, setTotalCount] = useState(0)
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
|
const [query, setQuery] = useState("")
|
||||||
|
const [statusFilter, setStatusFilter] = useState<PersonaStatusFilter>("all")
|
||||||
|
const [createOpen, setCreateOpen] = useState(false)
|
||||||
|
const [personaPendingEdit, setPersonaPendingEdit] = useState<LmsPersona | null>(null)
|
||||||
|
const [personaPendingDelete, setPersonaPendingDelete] = useState<LmsPersona | null>(null)
|
||||||
|
const [togglingId, setTogglingId] = useState<number | null>(null)
|
||||||
|
|
||||||
|
const offset = (page - 1) * pageSize
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
if (!canList) {
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
setError(false)
|
||||||
|
setPermissionDenied(false)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await listPersonas({
|
||||||
|
active_only: statusFilter === "active",
|
||||||
|
limit: pageSize,
|
||||||
|
offset,
|
||||||
|
})
|
||||||
|
setPersonas(res.data.personas)
|
||||||
|
setTotalCount(res.data.total_count)
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
setError(true)
|
||||||
|
setPersonas([])
|
||||||
|
setTotalCount(0)
|
||||||
|
if (isPersonaForbiddenError(e)) {
|
||||||
|
setPermissionDenied(true)
|
||||||
|
toast.error(getPersonaApiErrorMessage(e, "You do not have permission to view personas"))
|
||||||
|
} else {
|
||||||
|
toast.error(getPersonaApiErrorMessage(e, "Failed to load personas"))
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [canList, statusFilter, pageSize, offset])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1)
|
||||||
|
}, [statusFilter, pageSize])
|
||||||
|
|
||||||
|
const filtered = useMemo(() => {
|
||||||
|
let rows = personas
|
||||||
|
if (statusFilter === "inactive") {
|
||||||
|
rows = rows.filter((persona) => !persona.is_active)
|
||||||
|
}
|
||||||
|
|
||||||
|
const q = query.trim().toLowerCase()
|
||||||
|
if (!q) return rows
|
||||||
|
return rows.filter((persona) => {
|
||||||
|
const haystack = [
|
||||||
|
persona.name,
|
||||||
|
persona.description ?? "",
|
||||||
|
persona.gender ?? "",
|
||||||
|
String(persona.id),
|
||||||
|
]
|
||||||
|
.join(" ")
|
||||||
|
.toLowerCase()
|
||||||
|
return haystack.includes(q)
|
||||||
|
})
|
||||||
|
}, [personas, query, statusFilter])
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: statusFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setStatusFilter("all")
|
||||||
|
setPage(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||||
|
const safePage = Math.min(page, totalPages)
|
||||||
|
const startEntry = totalCount === 0 ? 0 : offset + 1
|
||||||
|
const endEntry = Math.min(offset + personas.length, totalCount)
|
||||||
|
|
||||||
|
const handleToggleActive = async (persona: LmsPersona) => {
|
||||||
|
if (!canUpdate) {
|
||||||
|
toast.error("You do not have permission to update personas")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setTogglingId(persona.id)
|
||||||
|
try {
|
||||||
|
const res = await updatePersona(persona.id, { is_active: !persona.is_active })
|
||||||
|
if (res.data) {
|
||||||
|
setPersonas((prev) => prev.map((row) => (row.id === persona.id ? res.data! : row)))
|
||||||
|
}
|
||||||
|
toast.success(res.data?.is_active ? "Persona activated" : "Persona deactivated")
|
||||||
|
if (statusFilter === "active" && res.data && !res.data.is_active) {
|
||||||
|
void load()
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
toast.error(getPersonaApiErrorMessage(e, "Failed to update persona status"))
|
||||||
|
} finally {
|
||||||
|
setTogglingId(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissionsLoading && !canList) {
|
||||||
|
return <PersonaAccessDenied />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissionsLoading && permissionDenied) {
|
||||||
|
return <PersonaAccessDenied apiForbidden />
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||||
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-grayScale-500">Learning content</p>
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">Personas</h1>
|
||||||
|
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">
|
||||||
|
Manage coach and character profiles linked to practice shells in Learn English and
|
||||||
|
exam-prep content.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button variant="outline" className="shrink-0" disabled={loading} onClick={() => void load()}>
|
||||||
|
{loading ? <SpinnerIcon className="mr-2 h-4 w-4" /> : <RefreshCw className="mr-2 h-4 w-4" />}
|
||||||
|
Refresh
|
||||||
|
</Button>
|
||||||
|
{canCreate ? (
|
||||||
|
<Button
|
||||||
|
className="shrink-0 bg-brand-500 text-white hover:bg-brand-600"
|
||||||
|
onClick={() => setCreateOpen(true)}
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
New persona
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card className="shadow-soft">
|
||||||
|
<CardContent className="space-y-5 pt-5">
|
||||||
|
<AdminFiltersPanel
|
||||||
|
className="border-0 shadow-none"
|
||||||
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
summary={
|
||||||
|
totalCount > 0
|
||||||
|
? `Showing ${startEntry}–${endEntry} of ${totalCount}`
|
||||||
|
: "No personas"
|
||||||
|
}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
|
<Input
|
||||||
|
placeholder="Search by name, description, gender, or ID…"
|
||||||
|
className="pl-9"
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
actions={
|
||||||
|
<Select
|
||||||
|
value={statusFilter}
|
||||||
|
onChange={(e) => setStatusFilter(e.target.value as PersonaStatusFilter)}
|
||||||
|
className="h-9 w-[11rem] rounded-md text-sm"
|
||||||
|
aria-label="Filter by status"
|
||||||
|
>
|
||||||
|
<option value="all">All statuses</option>
|
||||||
|
<option value="active">Active</option>
|
||||||
|
<option value="inactive">Inactive</option>
|
||||||
|
</Select>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="rounded-xl border bg-white">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead className="w-[72px]">Avatar</TableHead>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead className="hidden md:table-cell">Gender</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead className="hidden lg:table-cell">Updated</TableHead>
|
||||||
|
<TableHead className="text-right">Actions</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{loading ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={6} className="py-12 text-center">
|
||||||
|
<div className="flex flex-col items-center gap-3">
|
||||||
|
<SpinnerIcon className="h-6 w-6 text-brand-500" />
|
||||||
|
<span className="text-sm text-grayScale-400">Loading personas…</span>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : error ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={6} className="py-12 text-center text-sm text-grayScale-500">
|
||||||
|
Failed to load personas. Try refreshing.
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : filtered.length === 0 ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={6} className="py-12 text-center">
|
||||||
|
<div className="flex flex-col items-center gap-2">
|
||||||
|
<UserCircle2 className="h-8 w-8 text-grayScale-200" />
|
||||||
|
<p className="text-sm font-medium text-grayScale-500">
|
||||||
|
{totalCount === 0 ? "No personas yet" : "No personas match your search"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-grayScale-400">
|
||||||
|
{canCreate
|
||||||
|
? "Create a persona to use in practice authoring."
|
||||||
|
: "Ask an admin to create personas for your team."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : (
|
||||||
|
filtered.map((persona) => (
|
||||||
|
<TableRow key={persona.id}>
|
||||||
|
<TableCell className="py-3.5">
|
||||||
|
<img
|
||||||
|
src={personaAvatarUrl(
|
||||||
|
persona.profile_picture,
|
||||||
|
persona.name,
|
||||||
|
persona.id,
|
||||||
|
)}
|
||||||
|
alt=""
|
||||||
|
className="h-10 w-10 rounded-full border border-grayScale-200 bg-grayScale-50 object-cover"
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="py-3.5">
|
||||||
|
<p className="text-sm font-semibold text-grayScale-700">{persona.name}</p>
|
||||||
|
{persona.description ? (
|
||||||
|
<p className="mt-0.5 line-clamp-2 text-xs text-grayScale-500">
|
||||||
|
{persona.description}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="hidden py-3.5 text-sm text-grayScale-500 md:table-cell">
|
||||||
|
{personaGenderLabel(persona.gender)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="py-3.5">
|
||||||
|
{canUpdate ? (
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={persona.is_active}
|
||||||
|
disabled={togglingId === persona.id}
|
||||||
|
aria-label={
|
||||||
|
persona.is_active ? "Deactivate persona" : "Activate persona"
|
||||||
|
}
|
||||||
|
onCheckedChange={() => void handleToggleActive(persona)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Badge variant={persona.is_active ? "default" : "outline"}>
|
||||||
|
{personaStatusLabel(persona.is_active)}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="hidden py-3.5 text-sm text-grayScale-500 lg:table-cell">
|
||||||
|
{formatPersonaDate(persona.updated_at ?? persona.created_at)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="py-3.5">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
{canUpdate ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 px-2"
|
||||||
|
onClick={() => setPersonaPendingEdit(persona)}
|
||||||
|
>
|
||||||
|
<Pencil className="mr-1 h-3.5 w-3.5" />
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{canDelete ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 px-2 text-destructive hover:text-destructive"
|
||||||
|
onClick={() => setPersonaPendingDelete(persona)}
|
||||||
|
>
|
||||||
|
<Trash2 className="mr-1 h-3.5 w-3.5" />
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{totalCount > 0 ? (
|
||||||
|
<div className="flex flex-col gap-3 border-t border-grayScale-100 pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div className="flex items-center gap-2 text-sm text-grayScale-500">
|
||||||
|
<span>Rows per page</span>
|
||||||
|
<select
|
||||||
|
value={pageSize}
|
||||||
|
onChange={(e) => setPageSize(Number(e.target.value))}
|
||||||
|
className="h-8 rounded-md border border-grayScale-200 bg-white px-2 text-sm"
|
||||||
|
>
|
||||||
|
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||||
|
<option key={size} value={size}>
|
||||||
|
{size}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={safePage <= 1 || loading}
|
||||||
|
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
Prev
|
||||||
|
</Button>
|
||||||
|
<span className="text-sm text-grayScale-500">
|
||||||
|
Page {safePage} of {totalPages}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={safePage >= totalPages || loading}
|
||||||
|
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
||||||
|
>
|
||||||
|
Next
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<CreatePersonaDialog
|
||||||
|
open={createOpen}
|
||||||
|
onOpenChange={setCreateOpen}
|
||||||
|
onCreated={() => void load()}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<EditPersonaDialog
|
||||||
|
persona={personaPendingEdit}
|
||||||
|
open={personaPendingEdit != null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setPersonaPendingEdit(null)
|
||||||
|
}}
|
||||||
|
onUpdated={() => void load()}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<PersonaDeleteDialog
|
||||||
|
persona={personaPendingDelete}
|
||||||
|
open={personaPendingDelete != null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setPersonaPendingDelete(null)
|
||||||
|
}}
|
||||||
|
onDeleted={() => void load()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
99
src/pages/personas/components/CreatePersonaDialog.tsx
Normal file
99
src/pages/personas/components/CreatePersonaDialog.tsx
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
import { useEffect, useState } from "react"
|
||||||
|
import { Plus } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { createPersona } from "../../../api/personas.api"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../../../components/ui/dialog"
|
||||||
|
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
|
||||||
|
import {
|
||||||
|
draftToCreatePayload,
|
||||||
|
EMPTY_PERSONA_FORM_DRAFT,
|
||||||
|
PersonaForm,
|
||||||
|
PersonaFormActions,
|
||||||
|
validatePersonaDraft,
|
||||||
|
type PersonaFormDraft,
|
||||||
|
} from "./PersonaForm"
|
||||||
|
|
||||||
|
type CreatePersonaDialogProps = {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
onCreated?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CreatePersonaDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onCreated,
|
||||||
|
}: CreatePersonaDialogProps) {
|
||||||
|
const [draft, setDraft] = useState<PersonaFormDraft>(EMPTY_PERSONA_FORM_DRAFT)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [uploadingPicture, setUploadingPicture] = useState(false)
|
||||||
|
const busy = saving || uploadingPicture
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
setDraft(EMPTY_PERSONA_FORM_DRAFT)
|
||||||
|
setUploadingPicture(false)
|
||||||
|
}
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next && !busy) onOpenChange(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCreate = async () => {
|
||||||
|
const validationError = validatePersonaDraft(draft)
|
||||||
|
if (validationError) {
|
||||||
|
toast.error(validationError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const response = await createPersona(draftToCreatePayload(draft))
|
||||||
|
if (!response.data) throw new Error("Empty create response")
|
||||||
|
toast.success(response.message ?? "Persona created successfully")
|
||||||
|
onOpenChange(false)
|
||||||
|
onCreated?.()
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
toast.error(getPersonaApiErrorMessage(e, "Failed to create persona"))
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="max-h-[90vh] overflow-y-auto rounded-2xl border-grayScale-200 sm:max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||||
|
<Plus className="h-5 w-5 text-brand-600" />
|
||||||
|
New persona
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Create a coach/character profile for linking to practice shells.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<PersonaForm
|
||||||
|
draft={draft}
|
||||||
|
onChange={setDraft}
|
||||||
|
disabled={busy}
|
||||||
|
onUploadBusyChange={setUploadingPicture}
|
||||||
|
/>
|
||||||
|
<PersonaFormActions
|
||||||
|
saving={busy}
|
||||||
|
onCancel={() => onOpenChange(false)}
|
||||||
|
onSave={() => void handleCreate()}
|
||||||
|
saveLabel="Create persona"
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
142
src/pages/personas/components/EditPersonaDialog.tsx
Normal file
142
src/pages/personas/components/EditPersonaDialog.tsx
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
import { useCallback, useEffect, useState } from "react"
|
||||||
|
import { Pencil } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { getPersonaById, updatePersona } from "../../../api/personas.api"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../../../components/ui/dialog"
|
||||||
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
|
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
|
||||||
|
import type { LmsPersona } from "../../../types/persona.types"
|
||||||
|
import {
|
||||||
|
draftToUpdatePayload,
|
||||||
|
PersonaForm,
|
||||||
|
PersonaFormActions,
|
||||||
|
personaToDraft,
|
||||||
|
validatePersonaDraft,
|
||||||
|
type PersonaFormDraft,
|
||||||
|
} from "./PersonaForm"
|
||||||
|
|
||||||
|
type EditPersonaDialogProps = {
|
||||||
|
persona: LmsPersona | null
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
onUpdated?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditPersonaDialog({
|
||||||
|
persona,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onUpdated,
|
||||||
|
}: EditPersonaDialogProps) {
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [uploadingPicture, setUploadingPicture] = useState(false)
|
||||||
|
const [draft, setDraft] = useState<PersonaFormDraft | null>(null)
|
||||||
|
const busy = saving || uploadingPicture
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
if (!persona) return
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
const res = await getPersonaById(persona.id)
|
||||||
|
if (!res.data) throw new Error("Persona not found")
|
||||||
|
setDraft(personaToDraft(res.data))
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const status = (e as { response?: { status?: number } })?.response?.status
|
||||||
|
if (status === 404) {
|
||||||
|
toast.error("Persona not found")
|
||||||
|
} else {
|
||||||
|
toast.error(getPersonaApiErrorMessage(e, "Failed to load persona"))
|
||||||
|
}
|
||||||
|
onOpenChange(false)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [persona, onOpenChange])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open && persona) {
|
||||||
|
void load()
|
||||||
|
} else if (!open) {
|
||||||
|
setDraft(null)
|
||||||
|
setLoading(false)
|
||||||
|
setSaving(false)
|
||||||
|
setUploadingPicture(false)
|
||||||
|
}
|
||||||
|
}, [open, persona, load])
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next && !busy && !loading) onOpenChange(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!persona || !draft) return
|
||||||
|
|
||||||
|
const validationError = validatePersonaDraft(draft)
|
||||||
|
if (validationError) {
|
||||||
|
toast.error(validationError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const res = await updatePersona(persona.id, draftToUpdatePayload(draft))
|
||||||
|
if (!res.data) throw new Error("Empty update response")
|
||||||
|
toast.success(res.message ?? "Persona updated successfully")
|
||||||
|
onOpenChange(false)
|
||||||
|
onUpdated?.()
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
toast.error(getPersonaApiErrorMessage(e, "Failed to update persona"))
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="max-h-[90vh] overflow-y-auto rounded-2xl border-grayScale-200 sm:max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||||
|
<Pencil className="h-5 w-5 text-brand-600" />
|
||||||
|
Edit persona
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{persona ? `Update coach profile #${persona.id}` : "Update persona details"}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{loading || !draft ? (
|
||||||
|
<div className="flex flex-col items-center justify-center gap-3 py-12">
|
||||||
|
<SpinnerIcon className="h-6 w-6 text-brand-500" />
|
||||||
|
<p className="text-sm text-grayScale-500">Loading persona…</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<PersonaForm
|
||||||
|
draft={draft}
|
||||||
|
onChange={setDraft}
|
||||||
|
disabled={busy}
|
||||||
|
previewId={persona?.id}
|
||||||
|
onUploadBusyChange={setUploadingPicture}
|
||||||
|
/>
|
||||||
|
<PersonaFormActions
|
||||||
|
saving={busy}
|
||||||
|
onCancel={() => onOpenChange(false)}
|
||||||
|
onSave={() => void handleSave()}
|
||||||
|
saveLabel="Save changes"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
100
src/pages/personas/components/PersonaAccessDenied.tsx
Normal file
100
src/pages/personas/components/PersonaAccessDenied.tsx
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
import { useState } from "react"
|
||||||
|
import { Link } from "react-router-dom"
|
||||||
|
import { LogOut, RefreshCw, UserCircle2 } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { syncRbacPermissions } from "../../../api/rbac.api"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import { Card, CardContent } from "../../../components/ui/card"
|
||||||
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
|
import { PERSONAS_FORBIDDEN_MESSAGE } from "../../../lib/personasErrors"
|
||||||
|
import {
|
||||||
|
getSessionTeamRole,
|
||||||
|
hasPersonasRoleBypass,
|
||||||
|
} from "../../../lib/personasPermissions"
|
||||||
|
|
||||||
|
type PersonaAccessDeniedProps = {
|
||||||
|
apiForbidden?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PersonaAccessDenied({ apiForbidden = false }: PersonaAccessDeniedProps) {
|
||||||
|
const [syncing, setSyncing] = useState(false)
|
||||||
|
const teamRole = getSessionTeamRole()
|
||||||
|
const canSync = hasPersonasRoleBypass()
|
||||||
|
|
||||||
|
const handleSync = async () => {
|
||||||
|
setSyncing(true)
|
||||||
|
try {
|
||||||
|
const res = await syncRbacPermissions()
|
||||||
|
toast.success(res.data?.message ?? "RBAC permissions synced. Please sign in again.")
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const msg =
|
||||||
|
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
|
||||||
|
"Failed to sync RBAC permissions"
|
||||||
|
toast.error(msg)
|
||||||
|
} finally {
|
||||||
|
setSyncing(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-2xl space-y-6">
|
||||||
|
<Card className="border border-grayScale-100 shadow-none">
|
||||||
|
<CardContent className="flex flex-col items-center gap-4 px-6 py-16 text-center">
|
||||||
|
<UserCircle2 className="h-10 w-10 text-grayScale-300" />
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h2 className="text-lg font-semibold text-grayScale-800">
|
||||||
|
{apiForbidden ? "Persona access denied" : "No permission to view personas"}
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm text-grayScale-600">
|
||||||
|
{apiForbidden
|
||||||
|
? PERSONAS_FORBIDDEN_MESSAGE
|
||||||
|
: "Your account does not have the personas.list permission."}
|
||||||
|
</p>
|
||||||
|
{teamRole ? (
|
||||||
|
<p className="text-xs text-grayScale-500">
|
||||||
|
Signed in as team role: <span className="font-medium">{teamRole}</span>
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full max-w-md rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3 text-left text-xs text-grayScale-600">
|
||||||
|
<p className="font-semibold text-grayScale-700">If you expect access:</p>
|
||||||
|
<ul className="mt-2 list-disc space-y-1 pl-4">
|
||||||
|
<li>Use ADMIN, SUPER_ADMIN, or INSTRUCTOR with personas.* permissions</li>
|
||||||
|
<li>Ensure migrations 000063–000065 are applied on the API database</li>
|
||||||
|
<li>Run RBAC sync, then sign out and sign in again</li>
|
||||||
|
<li>SUPPORT has read-only access (list/get)</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||||
|
{canSync ? (
|
||||||
|
<Button variant="outline" disabled={syncing} onClick={() => void handleSync()}>
|
||||||
|
{syncing ? (
|
||||||
|
<SpinnerIcon className="mr-2 h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<RefreshCw className="mr-2 h-4 w-4" />
|
||||||
|
)}
|
||||||
|
Sync RBAC permissions
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button variant="outline" asChild>
|
||||||
|
<Link to="/roles">Manage roles</Link>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
localStorage.clear()
|
||||||
|
window.location.href = "/login"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LogOut className="mr-2 h-4 w-4" />
|
||||||
|
Sign in again
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
87
src/pages/personas/components/PersonaDeleteDialog.tsx
Normal file
87
src/pages/personas/components/PersonaDeleteDialog.tsx
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
import { useState } from "react"
|
||||||
|
import { Trash2 } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { deletePersona } from "../../../api/personas.api"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../../../components/ui/dialog"
|
||||||
|
import type { LmsPersona } from "../../../types/persona.types"
|
||||||
|
|
||||||
|
type PersonaDeleteDialogProps = {
|
||||||
|
persona: LmsPersona | null
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
onDeleted?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PersonaDeleteDialog({
|
||||||
|
persona,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onDeleted,
|
||||||
|
}: PersonaDeleteDialogProps) {
|
||||||
|
const [deleting, setDeleting] = useState(false)
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next && !deleting) onOpenChange(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleConfirm = async () => {
|
||||||
|
if (!persona) return
|
||||||
|
|
||||||
|
setDeleting(true)
|
||||||
|
try {
|
||||||
|
const response = await deletePersona(persona.id)
|
||||||
|
toast.success(response.message ?? "Persona deleted successfully")
|
||||||
|
onOpenChange(false)
|
||||||
|
onDeleted?.()
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
toast.error(getPersonaApiErrorMessage(e, "Failed to delete persona"))
|
||||||
|
} finally {
|
||||||
|
setDeleting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="max-w-md rounded-2xl border-grayScale-200 sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||||
|
<Trash2 className="h-5 w-5 shrink-0 text-destructive" aria-hidden />
|
||||||
|
Delete persona?
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-left text-grayScale-600">
|
||||||
|
This permanently removes the persona from the catalog. Practices that referenced it
|
||||||
|
will have their persona assignment cleared automatically.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{persona ? (
|
||||||
|
<div className="space-y-1 rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3">
|
||||||
|
<p className="text-sm font-semibold text-grayScale-900">{persona.name}</p>
|
||||||
|
<p className="text-xs text-grayScale-500">#{persona.id}</p>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<DialogFooter className="gap-2 sm:gap-2">
|
||||||
|
<Button variant="outline" disabled={deleting} onClick={() => onOpenChange(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
disabled={deleting || !persona}
|
||||||
|
onClick={() => void handleConfirm()}
|
||||||
|
>
|
||||||
|
{deleting ? "Deleting…" : "Delete persona"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
209
src/pages/personas/components/PersonaForm.tsx
Normal file
209
src/pages/personas/components/PersonaForm.tsx
Normal file
|
|
@ -0,0 +1,209 @@
|
||||||
|
import type {
|
||||||
|
CreatePersonaInput,
|
||||||
|
LmsPersona,
|
||||||
|
UpdatePersonaInput,
|
||||||
|
} from "../../../types/persona.types"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import { Input } from "../../../components/ui/input"
|
||||||
|
import { Select } from "../../../components/ui/select"
|
||||||
|
import { Textarea } from "../../../components/ui/textarea"
|
||||||
|
import { personaAvatarUrl } from "../../../lib/personaDisplay"
|
||||||
|
import { PersonaProfilePictureUploadField } from "./PersonaProfilePictureUploadField"
|
||||||
|
|
||||||
|
const PERSONA_GENDER_OPTIONS = [
|
||||||
|
{ value: "female", label: "Female" },
|
||||||
|
{ value: "male", label: "Male" },
|
||||||
|
{ value: "neutral", label: "Neutral" },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export type PersonaFormDraft = {
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
profile_picture: string
|
||||||
|
gender: string
|
||||||
|
is_active: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EMPTY_PERSONA_FORM_DRAFT: PersonaFormDraft = {
|
||||||
|
name: "",
|
||||||
|
description: "",
|
||||||
|
profile_picture: "",
|
||||||
|
gender: "",
|
||||||
|
is_active: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validatePersonaDraft(draft: PersonaFormDraft): string | null {
|
||||||
|
if (!draft.name.trim()) return "Name is required"
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function draftToCreatePayload(draft: PersonaFormDraft): CreatePersonaInput {
|
||||||
|
return {
|
||||||
|
name: draft.name.trim(),
|
||||||
|
description: draft.description.trim() || null,
|
||||||
|
profile_picture: draft.profile_picture.trim() || null,
|
||||||
|
gender: draft.gender.trim() || null,
|
||||||
|
is_active: draft.is_active,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function draftToUpdatePayload(draft: PersonaFormDraft): UpdatePersonaInput {
|
||||||
|
return {
|
||||||
|
name: draft.name.trim(),
|
||||||
|
description: draft.description.trim(),
|
||||||
|
profile_picture: draft.profile_picture.trim(),
|
||||||
|
gender: draft.gender.trim(),
|
||||||
|
is_active: draft.is_active,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function personaToDraft(persona: LmsPersona): PersonaFormDraft {
|
||||||
|
return {
|
||||||
|
name: persona.name,
|
||||||
|
description: persona.description ?? "",
|
||||||
|
profile_picture: persona.profile_picture ?? "",
|
||||||
|
gender: persona.gender ?? "",
|
||||||
|
is_active: persona.is_active,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type PersonaFormProps = {
|
||||||
|
draft: PersonaFormDraft
|
||||||
|
onChange: (draft: PersonaFormDraft) => void
|
||||||
|
disabled?: boolean
|
||||||
|
previewId?: number
|
||||||
|
onUploadBusyChange?: (busy: boolean) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PersonaForm({
|
||||||
|
draft,
|
||||||
|
onChange,
|
||||||
|
disabled = false,
|
||||||
|
previewId,
|
||||||
|
onUploadBusyChange,
|
||||||
|
}: PersonaFormProps) {
|
||||||
|
const previewUrl = personaAvatarUrl(
|
||||||
|
draft.profile_picture.trim() || null,
|
||||||
|
draft.name.trim() || "Persona",
|
||||||
|
previewId,
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<img
|
||||||
|
src={previewUrl}
|
||||||
|
alt=""
|
||||||
|
className="h-16 w-16 rounded-full border border-grayScale-200 bg-grayScale-50 object-cover"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-grayScale-500">
|
||||||
|
Upload an image from your computer, paste a URL, or leave empty for a generated
|
||||||
|
placeholder.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="persona-name">
|
||||||
|
Name <span className="text-destructive">*</span>
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="persona-name"
|
||||||
|
value={draft.name}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder="Friendly Coach"
|
||||||
|
onChange={(e) => onChange({ ...draft, name: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="persona-description">
|
||||||
|
Description
|
||||||
|
</label>
|
||||||
|
<Textarea
|
||||||
|
id="persona-description"
|
||||||
|
value={draft.description}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder="Warm, encouraging tutor for everyday conversational practice."
|
||||||
|
rows={4}
|
||||||
|
onChange={(e) => onChange({ ...draft, description: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="persona-profile-picture">
|
||||||
|
Profile picture
|
||||||
|
</label>
|
||||||
|
<PersonaProfilePictureUploadField
|
||||||
|
value={draft.profile_picture}
|
||||||
|
onChange={(profile_picture) => onChange({ ...draft, profile_picture })}
|
||||||
|
disabled={disabled}
|
||||||
|
onUploadBusyChange={onUploadBusyChange}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium text-grayScale-700" htmlFor="persona-gender">
|
||||||
|
Gender
|
||||||
|
</label>
|
||||||
|
<Select
|
||||||
|
id="persona-gender"
|
||||||
|
value={draft.gender}
|
||||||
|
disabled={disabled}
|
||||||
|
onChange={(e) => onChange({ ...draft, gender: e.target.value })}
|
||||||
|
>
|
||||||
|
<option value="">Select gender</option>
|
||||||
|
{PERSONA_GENDER_OPTIONS.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
{draft.gender &&
|
||||||
|
!PERSONA_GENDER_OPTIONS.some((option) => option.value === draft.gender) ? (
|
||||||
|
<option value={draft.gender}>{draft.gender}</option>
|
||||||
|
) : null}
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label className="flex items-center gap-2 text-sm text-grayScale-700">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={draft.is_active}
|
||||||
|
disabled={disabled}
|
||||||
|
className="h-4 w-4 rounded border-grayScale-300"
|
||||||
|
onChange={(e) => onChange({ ...draft, is_active: e.target.checked })}
|
||||||
|
/>
|
||||||
|
Active (visible in practice persona picker)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PersonaFormActionsProps = {
|
||||||
|
saving: boolean
|
||||||
|
onCancel: () => void
|
||||||
|
onSave: () => void
|
||||||
|
saveLabel?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PersonaFormActions({
|
||||||
|
saving,
|
||||||
|
onCancel,
|
||||||
|
onSave,
|
||||||
|
saveLabel = "Save persona",
|
||||||
|
}: PersonaFormActionsProps) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap justify-end gap-2">
|
||||||
|
<Button type="button" variant="outline" disabled={saving} onClick={onCancel}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="bg-brand-500 text-white hover:bg-brand-600"
|
||||||
|
disabled={saving}
|
||||||
|
onClick={onSave}
|
||||||
|
>
|
||||||
|
{saving ? "Saving…" : saveLabel}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,156 @@
|
||||||
|
import { useCallback, useRef, useState, type ChangeEvent, type DragEvent } from "react"
|
||||||
|
import { CloudUpload } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { uploadImageFile } from "../../../api/files.api"
|
||||||
|
import { Input } from "../../../components/ui/input"
|
||||||
|
import { cn } from "../../../lib/utils"
|
||||||
|
|
||||||
|
const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||||
|
const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp"])
|
||||||
|
|
||||||
|
function isAllowedImageFile(file: File): boolean {
|
||||||
|
if (ALLOWED_IMAGE_TYPES.has(file.type)) return true
|
||||||
|
const name = file.name.toLowerCase()
|
||||||
|
return /\.(jpe?g|png|webp)$/.test(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PersonaProfilePictureUploadFieldProps = {
|
||||||
|
value: string
|
||||||
|
onChange: (url: string) => void
|
||||||
|
disabled?: boolean
|
||||||
|
onUploadBusyChange?: (busy: boolean) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PersonaProfilePictureUploadField({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
disabled = false,
|
||||||
|
onUploadBusyChange,
|
||||||
|
}: PersonaProfilePictureUploadFieldProps) {
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
const [uploading, setUploading] = useState(false)
|
||||||
|
const [dragActive, setDragActive] = useState(false)
|
||||||
|
|
||||||
|
const setBusy = useCallback(
|
||||||
|
(next: boolean) => {
|
||||||
|
setUploading(next)
|
||||||
|
onUploadBusyChange?.(next)
|
||||||
|
},
|
||||||
|
[onUploadBusyChange],
|
||||||
|
)
|
||||||
|
|
||||||
|
const processFile = useCallback(
|
||||||
|
async (file: File) => {
|
||||||
|
if (disabled || uploading) return
|
||||||
|
if (!isAllowedImageFile(file)) {
|
||||||
|
toast.error("Please use a JPG, PNG, or WEBP image.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (file.size > MAX_IMAGE_BYTES) {
|
||||||
|
toast.error("Image is too large", {
|
||||||
|
description: "Maximum size is 5 MB.",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
const res = await uploadImageFile(file)
|
||||||
|
const url = res.data?.data?.url?.trim()
|
||||||
|
if (!url) throw new Error("Upload did not return a file URL")
|
||||||
|
onChange(url)
|
||||||
|
toast.success("Profile picture uploaded")
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const msg =
|
||||||
|
(e as { response?: { data?: { message?: string } } })?.response?.data
|
||||||
|
?.message ?? "Failed to upload profile picture"
|
||||||
|
toast.error(msg)
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[disabled, uploading, onChange, setBusy],
|
||||||
|
)
|
||||||
|
|
||||||
|
const handleFileInputChange = (e: ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0]
|
||||||
|
e.target.value = ""
|
||||||
|
if (file) void processFile(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDragOver = (e: DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
if (!disabled && !uploading) setDragActive(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDragLeave = (e: DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
setDragActive(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDrop = (e: DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
setDragActive(false)
|
||||||
|
if (disabled || uploading) return
|
||||||
|
const file = e.dataTransfer.files?.[0]
|
||||||
|
if (file) void processFile(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
const zoneDisabled = disabled || uploading
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/jpeg,image/png,image/webp,.jpg,.jpeg,.png,.webp"
|
||||||
|
className="sr-only"
|
||||||
|
onChange={handleFileInputChange}
|
||||||
|
disabled={zoneDisabled}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={zoneDisabled}
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
className={cn(
|
||||||
|
"flex w-full cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed border-brand-200 bg-white p-6 text-center transition-colors",
|
||||||
|
"hover:border-brand-300 hover:bg-grayScale-50/40",
|
||||||
|
dragActive && "border-brand-400 bg-brand-50/40",
|
||||||
|
zoneDisabled && "cursor-not-allowed opacity-60",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<p className="text-sm font-medium text-grayScale-600">Uploading…</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<CloudUpload
|
||||||
|
className="mb-2 h-8 w-8 text-brand-600"
|
||||||
|
strokeWidth={1.5}
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
<p className="text-sm">
|
||||||
|
<span className="font-semibold text-brand-600">Click to upload</span>{" "}
|
||||||
|
<span className="text-grayScale-500">or drag and drop</span>
|
||||||
|
</p>
|
||||||
|
<p className="mt-1 text-xs text-grayScale-400">JPG, PNG, WEBP (max 5 MB)</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<Input
|
||||||
|
id="persona-profile-picture"
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
placeholder="Or paste image URL (https://…)"
|
||||||
|
disabled={zoneDisabled}
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
395
src/pages/ratings/AppReviewsPage.tsx
Normal file
395
src/pages/ratings/AppReviewsPage.tsx
Normal file
|
|
@ -0,0 +1,395 @@
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||||
|
import { Link } from "react-router-dom"
|
||||||
|
import {
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
ExternalLink,
|
||||||
|
MessageSquare,
|
||||||
|
RefreshCw,
|
||||||
|
Search,
|
||||||
|
Star,
|
||||||
|
} from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { loadRatingsPage } from "../../api/ratings.api"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
|
import { Badge } from "../../components/ui/badge"
|
||||||
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { Card, CardContent } from "../../components/ui/card"
|
||||||
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { Select } from "../../components/ui/select"
|
||||||
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "../../components/ui/table"
|
||||||
|
import { useRatingsPermissions } from "../../hooks/useRatingsPermissions"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import {
|
||||||
|
fetchReviewerProfiles,
|
||||||
|
type ReviewerProfile,
|
||||||
|
} from "../../lib/ratingUserCache"
|
||||||
|
import {
|
||||||
|
formatAverageStars,
|
||||||
|
formatRatingDate,
|
||||||
|
reviewTextOrPlaceholder,
|
||||||
|
} from "../../lib/ratingsDisplay"
|
||||||
|
import {
|
||||||
|
getRatingsApiErrorMessage,
|
||||||
|
isRatingsForbiddenError,
|
||||||
|
} from "../../lib/ratingsErrors"
|
||||||
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
import type { Rating, RatingSummary } from "../../types/ratings.types"
|
||||||
|
import { RatingsAccessDenied } from "./components/RatingsAccessDenied"
|
||||||
|
import { StarRating } from "./components/StarRating"
|
||||||
|
|
||||||
|
type StarsFilter = "all" | "1" | "2" | "3" | "4" | "5"
|
||||||
|
|
||||||
|
const APP_TARGET_TYPE = "app" as const
|
||||||
|
const APP_TARGET_ID = 0
|
||||||
|
|
||||||
|
export function AppReviewsPage() {
|
||||||
|
const { canList, loading: permissionsLoading } = useRatingsPermissions()
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState(false)
|
||||||
|
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||||
|
const [reviews, setReviews] = useState<Rating[]>([])
|
||||||
|
const [summary, setSummary] = useState<RatingSummary>({ total_count: 0, average_stars: 0 })
|
||||||
|
const [reviewerProfiles, setReviewerProfiles] = useState<Map<number, ReviewerProfile>>(new Map())
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
|
const [query, setQuery] = useState("")
|
||||||
|
const [starsFilter, setStarsFilter] = useState<StarsFilter>("all")
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
if (!canList) {
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
setError(false)
|
||||||
|
setPermissionDenied(false)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await loadRatingsPage(APP_TARGET_TYPE, page, pageSize, APP_TARGET_ID)
|
||||||
|
setSummary(data.summary)
|
||||||
|
setReviews(data.reviews)
|
||||||
|
|
||||||
|
const profiles = await fetchReviewerProfiles(data.reviews.map((r) => r.user_id))
|
||||||
|
setReviewerProfiles(profiles)
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
setError(true)
|
||||||
|
setReviews([])
|
||||||
|
setSummary({ total_count: 0, average_stars: 0 })
|
||||||
|
setReviewerProfiles(new Map())
|
||||||
|
if (isRatingsForbiddenError(e)) {
|
||||||
|
setPermissionDenied(true)
|
||||||
|
toast.error(getRatingsApiErrorMessage(e, "You do not have permission to view app reviews"))
|
||||||
|
} else {
|
||||||
|
toast.error(getRatingsApiErrorMessage(e, "Failed to load app reviews"))
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [canList, page, pageSize])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1)
|
||||||
|
}, [pageSize, starsFilter])
|
||||||
|
|
||||||
|
const filteredReviews = useMemo(() => {
|
||||||
|
const q = query.trim().toLowerCase()
|
||||||
|
return reviews.filter((rating) => {
|
||||||
|
if (starsFilter !== "all" && rating.stars !== Number(starsFilter)) return false
|
||||||
|
if (!q) return true
|
||||||
|
|
||||||
|
const profile = reviewerProfiles.get(rating.user_id)
|
||||||
|
const haystack = [
|
||||||
|
rating.review ?? "",
|
||||||
|
String(rating.user_id),
|
||||||
|
profile?.name ?? "",
|
||||||
|
profile?.email ?? "",
|
||||||
|
]
|
||||||
|
.join(" ")
|
||||||
|
.toLowerCase()
|
||||||
|
return haystack.includes(q)
|
||||||
|
})
|
||||||
|
}, [reviews, query, starsFilter, reviewerProfiles])
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([{ value: starsFilter, defaultValue: "all" }])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setStarsFilter("all")
|
||||||
|
setPage(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalCount = summary.total_count
|
||||||
|
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||||
|
const safePage = Math.min(page, totalPages)
|
||||||
|
const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1
|
||||||
|
const endEntry = Math.min(safePage * pageSize, totalCount)
|
||||||
|
|
||||||
|
const writtenOnPage = reviews.filter((r) => r.review?.trim()).length
|
||||||
|
|
||||||
|
if (!permissionsLoading && !canList) {
|
||||||
|
return <RatingsAccessDenied />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (permissionDenied) {
|
||||||
|
return <RatingsAccessDenied apiForbidden />
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-grayScale-600">App Reviews</h1>
|
||||||
|
<p className="mt-1 text-sm text-grayScale-400">
|
||||||
|
Monitor learner star ratings and written feedback submitted from the app.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="gap-2"
|
||||||
|
disabled={loading || !canList}
|
||||||
|
onClick={() => void load()}
|
||||||
|
>
|
||||||
|
{loading ? <SpinnerIcon className="h-4 w-4" /> : <RefreshCw className="h-4 w-4" />}
|
||||||
|
Refresh
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
|
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
|
||||||
|
<div className="grid h-10 w-10 place-items-center rounded-lg bg-amber-100 text-amber-600">
|
||||||
|
<Star className="h-5 w-5 fill-amber-500" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="text-2xl font-bold text-grayScale-600">
|
||||||
|
{formatAverageStars(summary.average_stars)}
|
||||||
|
</p>
|
||||||
|
<StarRating stars={summary.average_stars} size="sm" />
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-grayScale-400">Average rating</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
|
||||||
|
<div className="grid h-10 w-10 place-items-center rounded-lg bg-brand-100 text-brand-600">
|
||||||
|
<MessageSquare className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-2xl font-bold text-grayScale-600">{totalCount}</p>
|
||||||
|
<p className="text-xs text-grayScale-400">Total reviews</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
|
||||||
|
<div className="grid h-10 w-10 place-items-center rounded-lg bg-emerald-100 text-emerald-600">
|
||||||
|
<MessageSquare className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-2xl font-bold text-grayScale-600">{writtenOnPage}</p>
|
||||||
|
<p className="text-xs text-grayScale-400">With written review (this page)</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card className="shadow-soft">
|
||||||
|
<CardContent className="space-y-5 pt-5">
|
||||||
|
<AdminFiltersPanel
|
||||||
|
className="border-0 shadow-none"
|
||||||
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
footer="Star and text filters apply to the current page only. Server-side search is not available yet."
|
||||||
|
summary={
|
||||||
|
totalCount > 0
|
||||||
|
? `Showing ${startEntry}–${endEntry} of ${totalCount}`
|
||||||
|
: "No reviews"
|
||||||
|
}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
|
<Input
|
||||||
|
placeholder="Search review text, user name, email, or ID…"
|
||||||
|
className="pl-9"
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
actions={
|
||||||
|
<Select
|
||||||
|
value={starsFilter}
|
||||||
|
onChange={(e) => setStarsFilter(e.target.value as StarsFilter)}
|
||||||
|
className="h-9 w-full min-w-[140px] sm:w-40"
|
||||||
|
aria-label="Filter by stars"
|
||||||
|
>
|
||||||
|
<option value="all">All stars</option>
|
||||||
|
<option value="5">5 stars</option>
|
||||||
|
<option value="4">4 stars</option>
|
||||||
|
<option value="3">3 stars</option>
|
||||||
|
<option value="2">2 stars</option>
|
||||||
|
<option value="1">1 star</option>
|
||||||
|
</Select>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="rounded-xl border bg-white">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead className="w-[120px]">Stars</TableHead>
|
||||||
|
<TableHead>Review</TableHead>
|
||||||
|
<TableHead className="w-[200px]">User</TableHead>
|
||||||
|
<TableHead className="w-[140px]">Submitted</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{loading ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={4} className="py-12 text-center">
|
||||||
|
<div className="flex flex-col items-center gap-3">
|
||||||
|
<SpinnerIcon className="h-6 w-6 text-brand-500" />
|
||||||
|
<span className="text-sm text-grayScale-400">Loading reviews…</span>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : error ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={4} className="py-12 text-center text-sm text-grayScale-500">
|
||||||
|
Failed to load reviews. Try refreshing.
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : filteredReviews.length === 0 ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={4} className="py-12 text-center">
|
||||||
|
<div className="flex flex-col items-center gap-2">
|
||||||
|
<Star className="h-8 w-8 text-grayScale-200" />
|
||||||
|
<p className="text-sm font-medium text-grayScale-500">
|
||||||
|
{totalCount === 0
|
||||||
|
? "No reviews yet"
|
||||||
|
: "No reviews match your filters on this page"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-grayScale-400">
|
||||||
|
{totalCount === 0
|
||||||
|
? "Learners can submit ratings from the mobile or web app."
|
||||||
|
: "Try different filters or go to another page."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : (
|
||||||
|
filteredReviews.map((rating) => {
|
||||||
|
const profile = reviewerProfiles.get(rating.user_id)
|
||||||
|
return (
|
||||||
|
<TableRow key={rating.id}>
|
||||||
|
<TableCell className="py-3.5">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<StarRating stars={rating.stars} />
|
||||||
|
<Badge variant="outline" className="text-xs">
|
||||||
|
{rating.stars}/5
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="max-w-md py-3.5">
|
||||||
|
<p
|
||||||
|
className={cn(
|
||||||
|
"text-sm",
|
||||||
|
rating.review?.trim()
|
||||||
|
? "text-grayScale-600"
|
||||||
|
: "italic text-grayScale-400",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{reviewTextOrPlaceholder(rating.review)}
|
||||||
|
</p>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="py-3.5">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-brand-50 text-xs font-semibold text-brand-600">
|
||||||
|
{(profile?.name ?? `U${rating.user_id}`).charAt(0).toUpperCase()}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<Link
|
||||||
|
to={`/users/${rating.user_id}`}
|
||||||
|
className="inline-flex items-center gap-1 text-sm font-medium text-brand-600 hover:underline"
|
||||||
|
>
|
||||||
|
{profile?.name ?? `User #${rating.user_id}`}
|
||||||
|
<ExternalLink className="h-3 w-3" />
|
||||||
|
</Link>
|
||||||
|
{profile?.email ? (
|
||||||
|
<p className="truncate text-xs text-grayScale-400">{profile.email}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="py-3.5 text-sm text-grayScale-500">
|
||||||
|
{formatRatingDate(rating.created_at)}
|
||||||
|
{rating.updated_at !== rating.created_at ? (
|
||||||
|
<p className="text-xs text-grayScale-400">Updated</p>
|
||||||
|
) : null}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{canList && totalCount > 0 ? (
|
||||||
|
<div className="flex flex-col gap-3 border-t border-grayScale-100 pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div className="flex items-center gap-2 text-sm text-grayScale-500">
|
||||||
|
<span>Rows per page</span>
|
||||||
|
<select
|
||||||
|
value={pageSize}
|
||||||
|
onChange={(e) => setPageSize(Number(e.target.value))}
|
||||||
|
className="h-8 rounded-md border border-grayScale-200 bg-white px-2 text-sm"
|
||||||
|
>
|
||||||
|
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||||
|
<option key={size} value={size}>
|
||||||
|
{size}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={safePage <= 1 || loading}
|
||||||
|
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
Prev
|
||||||
|
</Button>
|
||||||
|
<span className="text-sm text-grayScale-500">
|
||||||
|
Page {safePage} of {totalPages}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={safePage >= totalPages || loading}
|
||||||
|
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
||||||
|
>
|
||||||
|
Next
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
97
src/pages/ratings/components/RatingsAccessDenied.tsx
Normal file
97
src/pages/ratings/components/RatingsAccessDenied.tsx
Normal file
|
|
@ -0,0 +1,97 @@
|
||||||
|
import { useState } from "react"
|
||||||
|
import { Link } from "react-router-dom"
|
||||||
|
import { LogOut, RefreshCw, Star } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { syncRbacPermissions } from "../../../api/rbac.api"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import { Card, CardContent } from "../../../components/ui/card"
|
||||||
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
|
import { getSessionTeamRole, hasRatingsRoleBypass } from "../../../lib/ratingsPermissions"
|
||||||
|
import { RATINGS_FORBIDDEN_MESSAGE } from "../../../lib/ratingsErrors"
|
||||||
|
|
||||||
|
type RatingsAccessDeniedProps = {
|
||||||
|
apiForbidden?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RatingsAccessDenied({ apiForbidden = false }: RatingsAccessDeniedProps) {
|
||||||
|
const [syncing, setSyncing] = useState(false)
|
||||||
|
const teamRole = getSessionTeamRole()
|
||||||
|
const canSync = hasRatingsRoleBypass()
|
||||||
|
|
||||||
|
const handleSync = async () => {
|
||||||
|
setSyncing(true)
|
||||||
|
try {
|
||||||
|
const res = await syncRbacPermissions()
|
||||||
|
toast.success(res.data?.message ?? "RBAC permissions synced. Please sign in again.")
|
||||||
|
} catch (e: unknown) {
|
||||||
|
console.error(e)
|
||||||
|
const msg =
|
||||||
|
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
|
||||||
|
"Failed to sync RBAC permissions"
|
||||||
|
toast.error(msg)
|
||||||
|
} finally {
|
||||||
|
setSyncing(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-2xl space-y-6">
|
||||||
|
<Card className="border border-grayScale-100 shadow-none">
|
||||||
|
<CardContent className="flex flex-col items-center gap-4 px-6 py-16 text-center">
|
||||||
|
<Star className="h-10 w-10 text-grayScale-300" />
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h2 className="text-lg font-semibold text-grayScale-800">
|
||||||
|
{apiForbidden ? "App reviews access denied" : "No permission to view app reviews"}
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm text-grayScale-600">
|
||||||
|
{apiForbidden
|
||||||
|
? RATINGS_FORBIDDEN_MESSAGE
|
||||||
|
: "Your account does not have the ratings.list_by_target permission."}
|
||||||
|
</p>
|
||||||
|
{teamRole ? (
|
||||||
|
<p className="text-xs text-grayScale-500">
|
||||||
|
Signed in as team role: <span className="font-medium">{teamRole}</span>
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full max-w-md rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3 text-left text-xs text-grayScale-600">
|
||||||
|
<p className="font-semibold text-grayScale-700">If you expect access:</p>
|
||||||
|
<ul className="mt-2 list-disc space-y-1 pl-4">
|
||||||
|
<li>Use a team account with ADMIN or SUPER_ADMIN, or explicit ratings permissions</li>
|
||||||
|
<li>Ensure migration 000017_ratings is applied on the API database</li>
|
||||||
|
<li>Run RBAC sync, then sign out and sign in again for a fresh token</li>
|
||||||
|
<li>Custom roles need ratings.list_by_target and ratings.summary assigned</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||||
|
{canSync ? (
|
||||||
|
<Button variant="outline" disabled={syncing} onClick={() => void handleSync()}>
|
||||||
|
{syncing ? (
|
||||||
|
<SpinnerIcon className="mr-2 h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<RefreshCw className="mr-2 h-4 w-4" />
|
||||||
|
)}
|
||||||
|
Sync RBAC permissions
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button variant="outline" asChild>
|
||||||
|
<Link to="/roles">Manage roles</Link>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
localStorage.clear()
|
||||||
|
window.location.href = "/login"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LogOut className="mr-2 h-4 w-4" />
|
||||||
|
Sign in again
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
30
src/pages/ratings/components/StarRating.tsx
Normal file
30
src/pages/ratings/components/StarRating.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { Star } from "lucide-react"
|
||||||
|
import { cn } from "../../../lib/utils"
|
||||||
|
|
||||||
|
type StarRatingProps = {
|
||||||
|
stars: number
|
||||||
|
max?: number
|
||||||
|
size?: "sm" | "md"
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StarRating({ stars, max = 5, size = "md", className }: StarRatingProps) {
|
||||||
|
const iconClass = size === "sm" ? "h-3.5 w-3.5" : "h-4 w-4"
|
||||||
|
const safeStars = Math.max(0, Math.min(max, Math.round(stars)))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("flex items-center gap-0.5", className)} aria-label={`${safeStars} out of ${max} stars`}>
|
||||||
|
{Array.from({ length: max }).map((_, i) => (
|
||||||
|
<Star
|
||||||
|
key={i}
|
||||||
|
className={cn(
|
||||||
|
iconClass,
|
||||||
|
i < safeStars
|
||||||
|
? "fill-amber-400 text-amber-400"
|
||||||
|
: "fill-grayScale-200 text-grayScale-200",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -17,11 +17,13 @@ import {
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { getAppVersions } from "../../api/app-versions.api"
|
import { getAppVersions } from "../../api/app-versions.api"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import {
|
import {
|
||||||
|
|
@ -147,6 +149,16 @@ export function AppVersionsTab() {
|
||||||
setTotalCount((c) => Math.max(0, c - 1))
|
setTotalCount((c) => Math.max(0, c - 1))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: platformFilter, defaultValue: "all" },
|
||||||
|
{ value: statusFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setPlatformFilter("all")
|
||||||
|
setStatusFilter("all")
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="animate-in fade-in slide-in-from-bottom-2 min-w-0 w-full max-w-full space-y-6 duration-300">
|
<div className="animate-in fade-in slide-in-from-bottom-2 min-w-0 w-full max-w-full space-y-6 duration-300">
|
||||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
|
@ -237,7 +249,10 @@ export function AppVersionsTab() {
|
||||||
<CardTitle className="text-sm font-bold text-grayScale-900">Release history</CardTitle>
|
<CardTitle className="text-sm font-bold text-grayScale-900">Release history</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
||||||
<div className="flex min-w-0 flex-col gap-4">
|
<AdminFiltersPanel
|
||||||
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
search={
|
||||||
<div className="relative w-full min-w-0">
|
<div className="relative w-full min-w-0">
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
|
|
@ -247,6 +262,8 @@ export function AppVersionsTab() {
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
<div className="flex min-w-0 flex-wrap gap-2">
|
<div className="flex min-w-0 flex-wrap gap-2">
|
||||||
{(
|
{(
|
||||||
[
|
[
|
||||||
|
|
@ -294,7 +311,7 @@ export function AppVersionsTab() {
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
||||||
|
|
|
||||||
|
|
@ -12,11 +12,13 @@ import {
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { getSubscriptionPlans } from "../../api/subscription-plans.api"
|
import { getSubscriptionPlans } from "../../api/subscription-plans.api"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import {
|
import {
|
||||||
formatPlanCategory,
|
formatPlanCategory,
|
||||||
|
|
@ -91,6 +93,14 @@ export function SubscriptionPlansTab() {
|
||||||
setPlans((prev) => prev.filter((p) => p.id !== id))
|
setPlans((prev) => prev.filter((p) => p.id !== id))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: statusFilter, defaultValue: "all" },
|
||||||
|
])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setStatusFilter("all")
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="animate-in fade-in slide-in-from-bottom-2 min-w-0 w-full max-w-full space-y-6 duration-300">
|
<div className="animate-in fade-in slide-in-from-bottom-2 min-w-0 w-full max-w-full space-y-6 duration-300">
|
||||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
|
@ -168,7 +178,10 @@ export function SubscriptionPlansTab() {
|
||||||
<CardTitle className="text-sm font-bold text-grayScale-900">All packages</CardTitle>
|
<CardTitle className="text-sm font-bold text-grayScale-900">All packages</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
||||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center">
|
<AdminFiltersPanel
|
||||||
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
search={
|
||||||
<div className="relative flex-1">
|
<div className="relative flex-1">
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
|
|
@ -178,6 +191,8 @@ export function SubscriptionPlansTab() {
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{(
|
{(
|
||||||
[
|
[
|
||||||
|
|
@ -201,7 +216,7 @@ export function SubscriptionPlansTab() {
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import { Input } from "../../../components/ui/input"
|
||||||
import { Select } from "../../../components/ui/select"
|
import { Select } from "../../../components/ui/select"
|
||||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
import { Textarea } from "../../../components/ui/textarea"
|
import { Textarea } from "../../../components/ui/textarea"
|
||||||
|
import { ToggleSwitch } from "../../../components/ui/toggle-switch"
|
||||||
import { cn } from "../../../lib/utils"
|
import { cn } from "../../../lib/utils"
|
||||||
import {
|
import {
|
||||||
SUBSCRIPTION_CURRENCIES,
|
SUBSCRIPTION_CURRENCIES,
|
||||||
|
|
@ -257,23 +258,12 @@ export function CreateSubscriptionPlanDialog({
|
||||||
Inactive plans stay in the catalog but are hidden from checkout
|
Inactive plans stay in the catalog but are hidden from checkout
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<ToggleSwitch
|
||||||
type="button"
|
variant="plain"
|
||||||
role="switch"
|
checked={draft.is_active}
|
||||||
aria-checked={draft.is_active}
|
aria-label="Active package"
|
||||||
onClick={() => setDraft((d) => ({ ...d, is_active: !d.is_active }))}
|
onCheckedChange={() => setDraft((d) => ({ ...d, is_active: !d.is_active }))}
|
||||||
className={cn(
|
|
||||||
"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors",
|
|
||||||
draft.is_active ? "bg-brand-500" : "bg-grayScale-200",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm transition-transform",
|
|
||||||
draft.is_active ? "translate-x-5" : "translate-x-0.5",
|
|
||||||
)}
|
|
||||||
/>
|
/>
|
||||||
</button>
|
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ import { Input } from "../../../components/ui/input"
|
||||||
import { Select } from "../../../components/ui/select"
|
import { Select } from "../../../components/ui/select"
|
||||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
import { Textarea } from "../../../components/ui/textarea"
|
import { Textarea } from "../../../components/ui/textarea"
|
||||||
|
import { ToggleSwitch } from "../../../components/ui/toggle-switch"
|
||||||
import { cn } from "../../../lib/utils"
|
import { cn } from "../../../lib/utils"
|
||||||
import {
|
import {
|
||||||
formatPlanCategory,
|
formatPlanCategory,
|
||||||
|
|
@ -265,23 +266,12 @@ export function EditSubscriptionPlanDialog({
|
||||||
Inactive plans stay in the catalog but are hidden from checkout
|
Inactive plans stay in the catalog but are hidden from checkout
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<ToggleSwitch
|
||||||
type="button"
|
variant="plain"
|
||||||
role="switch"
|
checked={draft.is_active}
|
||||||
aria-checked={draft.is_active}
|
aria-label="Active package"
|
||||||
onClick={() => setDraft((d) => d && { ...d, is_active: !d.is_active })}
|
onCheckedChange={() => setDraft((d) => d && { ...d, is_active: !d.is_active })}
|
||||||
className={cn(
|
|
||||||
"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors",
|
|
||||||
draft.is_active ? "bg-brand-500" : "bg-grayScale-200",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm transition-transform",
|
|
||||||
draft.is_active ? "translate-x-5" : "translate-x-0.5",
|
|
||||||
)}
|
|
||||||
/>
|
/>
|
||||||
</button>
|
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import {
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { Input } from "../../components/ui/input";
|
import { Input } from "../../components/ui/input";
|
||||||
import {
|
import {
|
||||||
|
|
@ -19,6 +20,8 @@ import {
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "../../components/ui/table";
|
} from "../../components/ui/table";
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar";
|
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar";
|
||||||
|
import { ToggleSwitch } from "../../components/ui/toggle-switch";
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
||||||
import { cn } from "../../lib/utils";
|
import { cn } from "../../lib/utils";
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
||||||
import { getTeamMembers, updateTeamMemberStatus } from "../../api/team.api";
|
import { getTeamMembers, updateTeamMemberStatus } from "../../api/team.api";
|
||||||
|
|
@ -215,6 +218,16 @@ export function TeamManagementPage() {
|
||||||
setConfirmDialog(null);
|
setConfirmDialog(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: roleFilter },
|
||||||
|
{ value: statusFilter },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setRoleFilter("");
|
||||||
|
setStatusFilter("");
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
|
@ -233,8 +246,11 @@ export function TeamManagementPage() {
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-3 rounded-lg border bg-white p-3">
|
<AdminFiltersPanel
|
||||||
<div className="relative w-full sm:flex-1 sm:w-auto">
|
activeFilterCount={activeFilterCount}
|
||||||
|
onClearFilters={clearFilters}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
placeholder="Search by name or email address..."
|
placeholder="Search by name or email address..."
|
||||||
|
|
@ -243,12 +259,14 @@ export function TeamManagementPage() {
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap gap-3">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<select
|
<select
|
||||||
value={roleFilter}
|
value={roleFilter}
|
||||||
onChange={(e) => setRoleFilter(e.target.value)}
|
onChange={(e) => setRoleFilter(e.target.value)}
|
||||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
className="h-9 appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||||
>
|
>
|
||||||
<option value="">Role: All</option>
|
<option value="">Role: All</option>
|
||||||
<option value="super_admin">Super Admin</option>
|
<option value="super_admin">Super Admin</option>
|
||||||
|
|
@ -262,12 +280,11 @@ export function TeamManagementPage() {
|
||||||
</select>
|
</select>
|
||||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<select
|
<select
|
||||||
value={statusFilter}
|
value={statusFilter}
|
||||||
onChange={(e) => setStatusFilter(e.target.value)}
|
onChange={(e) => setStatusFilter(e.target.value)}
|
||||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
className="h-9 appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||||
>
|
>
|
||||||
<option value="">Status: All</option>
|
<option value="">Status: All</option>
|
||||||
<option value="active">Active</option>
|
<option value="active">Active</option>
|
||||||
|
|
@ -275,8 +292,8 @@ export function TeamManagementPage() {
|
||||||
</select>
|
</select>
|
||||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
</AdminFiltersPanel>
|
||||||
|
|
||||||
<div className="rounded-xl border bg-white">
|
<div className="rounded-xl border bg-white">
|
||||||
<Table>
|
<Table>
|
||||||
|
|
@ -371,24 +388,10 @@ export function TeamManagementPage() {
|
||||||
)}
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||||
<button
|
<ToggleSwitch
|
||||||
type="button"
|
checked={isActive}
|
||||||
onClick={() => handleToggle(member.id)}
|
onCheckedChange={() => handleToggle(member.id)}
|
||||||
className={cn(
|
|
||||||
"relative inline-flex h-7 w-12 shrink-0 cursor-pointer items-center rounded-full border p-0.5 transition-all duration-200",
|
|
||||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-1",
|
|
||||||
isActive
|
|
||||||
? "border-brand-500 bg-brand-500 shadow-[0_6px_16px_rgba(168,85,247,0.35)]"
|
|
||||||
: "border-grayScale-300 bg-grayScale-200 hover:bg-grayScale-300/80"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-md ring-0 transition-transform duration-200 ease-out",
|
|
||||||
isActive ? "translate-x-5" : "translate-x-0"
|
|
||||||
)}
|
|
||||||
/>
|
/>
|
||||||
</button>
|
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,112 +1,190 @@
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react"
|
||||||
import { Link, useParams } from "react-router-dom";
|
import { Link, useParams } from "react-router-dom"
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
KeyRound,
|
BadgeCheck,
|
||||||
MessageCircle,
|
Briefcase,
|
||||||
|
Building2,
|
||||||
|
CalendarDays,
|
||||||
|
Clock3,
|
||||||
|
Hash,
|
||||||
|
Mail,
|
||||||
|
Phone,
|
||||||
Shield,
|
Shield,
|
||||||
User,
|
User,
|
||||||
} from "lucide-react";
|
UserCircle2,
|
||||||
import { Badge } from "../../components/ui/badge";
|
} from "lucide-react"
|
||||||
import { Button } from "../../components/ui/button";
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar";
|
import { Avatar, AvatarFallback } from "../../components/ui/avatar"
|
||||||
import { cn } from "../../lib/utils";
|
import { Separator } from "../../components/ui/separator"
|
||||||
import { getTeamMemberById } from "../../api/team.api";
|
import { cn } from "../../lib/utils"
|
||||||
import type { TeamMember } from "../../types/team.types";
|
import { getTeamMemberById } from "../../api/team.api"
|
||||||
|
import type { TeamMemberDetail } from "../../types/team.types"
|
||||||
|
|
||||||
function formatRoleLabel(role: string): string {
|
function formatRoleLabel(role: string): string {
|
||||||
return role
|
const value = role.trim()
|
||||||
|
if (!value) return "—"
|
||||||
|
return value
|
||||||
.split("_")
|
.split("_")
|
||||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||||
.join(" ");
|
.join(" ")
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatEmploymentType(type: string): string {
|
function formatStatusLabel(status: string): string {
|
||||||
return type
|
const value = status.trim()
|
||||||
.split("_")
|
if (!value) return "—"
|
||||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase()
|
||||||
.join(" ");
|
}
|
||||||
|
|
||||||
|
function formatDate(dateStr: string | null | undefined): string {
|
||||||
|
if (!dateStr?.trim()) return "—"
|
||||||
|
const date = new Date(dateStr)
|
||||||
|
if (Number.isNaN(date.getTime())) return dateStr
|
||||||
|
return date.toLocaleDateString(undefined, {
|
||||||
|
year: "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateTime(dateStr: string | null | undefined): string {
|
||||||
|
if (!dateStr?.trim()) return "—"
|
||||||
|
const date = new Date(dateStr)
|
||||||
|
if (Number.isNaN(date.getTime())) return dateStr
|
||||||
|
return date.toLocaleString(undefined, {
|
||||||
|
year: "numeric",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function displayValue(value: string | null | undefined): string {
|
||||||
|
const trimmed = value?.trim()
|
||||||
|
return trimmed ? trimmed : "—"
|
||||||
}
|
}
|
||||||
|
|
||||||
function getRoleBadgeClasses(role: string): string {
|
function getRoleBadgeClasses(role: string): string {
|
||||||
switch (role) {
|
const normalized = role.trim().toLowerCase()
|
||||||
|
switch (normalized) {
|
||||||
case "super_admin":
|
case "super_admin":
|
||||||
return "bg-brand-500/15 text-brand-600 border border-brand-500/25";
|
return "bg-brand-500/15 text-brand-600 border border-brand-500/25"
|
||||||
case "admin":
|
case "admin":
|
||||||
return "bg-brand-100 text-brand-600 border border-brand-200";
|
return "bg-brand-100 text-brand-600 border border-brand-200"
|
||||||
case "content_manager":
|
case "content_manager":
|
||||||
return "bg-mint-100 text-mint-500 border border-mint-300/40";
|
return "bg-mint-100 text-mint-500 border border-mint-300/40"
|
||||||
case "instructor":
|
case "instructor":
|
||||||
return "bg-gold-100 text-gold-600 border border-gold-300/40";
|
return "bg-gold-100 text-gold-600 border border-gold-300/40"
|
||||||
case "support_agent":
|
case "support_agent":
|
||||||
return "bg-orange-100 text-orange-600 border border-orange-200";
|
return "bg-orange-100 text-orange-600 border border-orange-200"
|
||||||
case "finance":
|
case "finance":
|
||||||
return "bg-sky-100 text-sky-600 border border-sky-200";
|
return "bg-sky-100 text-sky-600 border border-sky-200"
|
||||||
case "hr":
|
case "hr":
|
||||||
return "bg-pink-100 text-pink-600 border border-pink-200";
|
return "bg-pink-100 text-pink-600 border border-pink-200"
|
||||||
case "analyst":
|
case "analyst":
|
||||||
return "bg-violet-100 text-violet-600 border border-violet-200";
|
return "bg-violet-100 text-violet-600 border border-violet-200"
|
||||||
default:
|
default:
|
||||||
return "bg-grayScale-100 text-grayScale-600 border border-grayScale-200";
|
return "bg-grayScale-100 text-grayScale-600 border border-grayScale-200"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function ReadOnlyField({ label, value }: { label: string; value: string }) {
|
function DetailRow({
|
||||||
|
icon: Icon,
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
}: {
|
||||||
|
icon: React.ComponentType<{ className?: string }>
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="flex items-start gap-3 py-3.5">
|
||||||
<label className="mb-1 block text-xs font-medium text-grayScale-400">
|
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-50">
|
||||||
{label}
|
<Icon className="h-4 w-4 text-grayScale-500" />
|
||||||
</label>
|
</div>
|
||||||
<div className="rounded-lg border border-grayScale-200 bg-grayScale-50 px-3 py-2.5 text-sm text-grayScale-600">
|
<div className="min-w-0 flex-1">
|
||||||
{value || "—"}
|
<p className="text-xs font-medium uppercase tracking-wide text-grayScale-400">{label}</p>
|
||||||
|
<p className="mt-0.5 break-words text-sm font-medium text-grayScale-800">{value}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatTile({
|
||||||
|
icon: Icon,
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
}: {
|
||||||
|
icon: React.ComponentType<{ className?: string }>
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-grayScale-100 bg-white px-4 py-3.5 shadow-soft">
|
||||||
|
<div className="flex items-center gap-2 text-grayScale-500">
|
||||||
|
<Icon className="h-3.5 w-3.5" />
|
||||||
|
<span className="text-xs font-medium">{label}</span>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1.5 text-sm font-semibold text-grayScale-800">{value}</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function LoadingSkeleton() {
|
function LoadingSkeleton() {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="mx-auto w-full max-w-4xl space-y-5">
|
||||||
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
|
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
|
||||||
<div className="animate-pulse">
|
<div className="h-8 w-56 animate-pulse rounded-lg bg-grayScale-100" />
|
||||||
<div className="rounded-2xl bg-grayScale-100 h-[200px]" />
|
<div className="h-24 animate-pulse rounded-xl bg-grayScale-100" />
|
||||||
<div className="mt-6 grid gap-6 lg:grid-cols-3">
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
<div className="lg:col-span-2 rounded-2xl bg-grayScale-100 h-96" />
|
{[1, 2, 3, 4].map((item) => (
|
||||||
<div className="rounded-2xl bg-grayScale-100 h-96" />
|
<div key={item} className="h-20 animate-pulse rounded-xl bg-grayScale-100" />
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="h-72 animate-pulse rounded-xl bg-grayScale-100" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TeamMemberDetailPage() {
|
export function TeamMemberDetailPage() {
|
||||||
const { id } = useParams();
|
const { id } = useParams()
|
||||||
const [member, setMember] = useState<TeamMember | null>(null);
|
const [member, setMember] = useState<TeamMemberDetail | null>(null)
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!id) return;
|
const memberId = Number(id)
|
||||||
const fetchMember = async () => {
|
if (!Number.isFinite(memberId) || memberId <= 0) {
|
||||||
try {
|
setError("Invalid team member ID.")
|
||||||
const res = await getTeamMemberById(Number(id));
|
setLoading(false)
|
||||||
setMember(res.data.data);
|
return
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to fetch team member", err);
|
|
||||||
setError("Team member not found.");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
fetchMember();
|
|
||||||
}, [id]);
|
|
||||||
|
|
||||||
if (loading) return <LoadingSkeleton />;
|
const fetchMember = async () => {
|
||||||
|
setLoading(true)
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
const res = await getTeamMemberById(memberId)
|
||||||
|
setMember(res.data.data)
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to fetch team member", err)
|
||||||
|
setMember(null)
|
||||||
|
setError("Team member not found.")
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void fetchMember()
|
||||||
|
}, [id])
|
||||||
|
|
||||||
|
if (loading) return <LoadingSkeleton />
|
||||||
|
|
||||||
if (error || !member) {
|
if (error || !member) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="mx-auto w-full max-w-4xl space-y-5">
|
||||||
<Link
|
<Link
|
||||||
to="/team"
|
to="/team"
|
||||||
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||||
|
|
@ -116,23 +194,24 @@ export function TeamMemberDetailPage() {
|
||||||
</Link>
|
</Link>
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent className="flex flex-col items-center gap-4 p-10">
|
<CardContent className="flex flex-col items-center gap-4 p-10">
|
||||||
<div className="h-16 w-16 rounded-full bg-grayScale-100 flex items-center justify-center">
|
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-grayScale-100">
|
||||||
<User className="h-8 w-8 text-grayScale-300" />
|
<User className="h-8 w-8 text-grayScale-300" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-lg font-semibold text-grayScale-600">
|
<p className="text-lg font-semibold text-grayScale-600">
|
||||||
{error || "Member not found"}
|
{error || "Member not found"}
|
||||||
</div>
|
</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const fullName = `${member.first_name} ${member.last_name}`;
|
const fullName = `${member.first_name} ${member.last_name}`.trim()
|
||||||
const initials = `${member.first_name?.[0] ?? ""}${member.last_name?.[0] ?? ""}`.toUpperCase();
|
const initials = `${member.first_name?.[0] ?? ""}${member.last_name?.[0] ?? ""}`.toUpperCase()
|
||||||
|
const isActive = member.status.trim().toLowerCase() === "active"
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="mx-auto w-full max-w-4xl space-y-5">
|
||||||
<Link
|
<Link
|
||||||
to="/team"
|
to="/team"
|
||||||
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||||
|
|
@ -141,178 +220,102 @@ export function TeamMemberDetailPage() {
|
||||||
Back to Team
|
Back to Team
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
{/* Hero Banner */}
|
<div>
|
||||||
<div className="relative overflow-hidden rounded-2xl bg-gradient-to-r from-[#1a1f4e] via-[#2d2b6b] to-[#3b3480] px-6 py-12 sm:px-10 sm:py-14">
|
<p className="text-sm font-semibold text-grayScale-500">Team directory</p>
|
||||||
<div className="relative z-10 max-w-2xl">
|
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">{fullName}</h1>
|
||||||
<h1 className="text-3xl font-bold text-white sm:text-4xl">
|
<p className="mt-1 text-sm text-grayScale-500">
|
||||||
Hello {member.first_name}
|
Member #{member.id} · {displayValue(member.department)}
|
||||||
</h1>
|
|
||||||
<p className="mt-3 text-sm leading-relaxed text-white/70">
|
|
||||||
This is the profile page. You can see the progress made with their
|
|
||||||
work and manage their projects or assigned tasks
|
|
||||||
</p>
|
</p>
|
||||||
<Button className="mt-5 rounded-full bg-brand-600 px-6 hover:bg-brand-500">
|
|
||||||
Edit profile
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{/* Decorative circles */}
|
|
||||||
<div className="pointer-events-none absolute -right-10 -top-10 h-52 w-52 rounded-full bg-white/5" />
|
|
||||||
<div className="pointer-events-none absolute -bottom-16 right-20 h-40 w-40 rounded-full bg-white/5" />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Two-column layout */}
|
<Card className="border-grayScale-100 shadow-soft">
|
||||||
<div className="grid gap-6 lg:grid-cols-3">
|
<CardContent className="flex flex-col gap-4 p-5 sm:flex-row sm:items-center">
|
||||||
{/* Left: My Account Card */}
|
<Avatar className="h-14 w-14 shrink-0">
|
||||||
<Card className="lg:col-span-2">
|
<AvatarFallback className="bg-grayScale-100 text-base font-semibold text-grayScale-600">
|
||||||
<CardHeader className="flex-row items-center justify-between space-y-0">
|
{initials || "?"}
|
||||||
<CardTitle className="text-lg">My account</CardTitle>
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
className="rounded-full bg-brand-600 px-5 hover:bg-brand-500"
|
|
||||||
>
|
|
||||||
Settings
|
|
||||||
</Button>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-6">
|
|
||||||
{/* User Information */}
|
|
||||||
<div>
|
|
||||||
<h4 className="mb-4 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
|
|
||||||
User Information
|
|
||||||
</h4>
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
|
||||||
<ReadOnlyField label="Username" value={member.email} />
|
|
||||||
<ReadOnlyField label="Email address" value={member.email} />
|
|
||||||
<ReadOnlyField label="First name" value={member.first_name} />
|
|
||||||
<ReadOnlyField label="Last name" value={member.last_name} />
|
|
||||||
<ReadOnlyField label="Job Title" value={member.job_title} />
|
|
||||||
<ReadOnlyField label="Department" value={member.department} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Contact Information */}
|
|
||||||
<div>
|
|
||||||
<h4 className="mb-4 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
|
|
||||||
Contact Information
|
|
||||||
</h4>
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
|
||||||
<ReadOnlyField label="Phone" value={member.phone_number} />
|
|
||||||
<ReadOnlyField
|
|
||||||
label="Employment Type"
|
|
||||||
value={formatEmploymentType(member.employment_type)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* About Me */}
|
|
||||||
<div>
|
|
||||||
<h4 className="mb-4 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
|
|
||||||
About Me
|
|
||||||
</h4>
|
|
||||||
<div className="rounded-lg border border-grayScale-200 bg-grayScale-50 px-3 py-3 text-sm leading-relaxed text-grayScale-600">
|
|
||||||
{member.bio || "—"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Permissions */}
|
|
||||||
{member.permissions.length > 0 && (
|
|
||||||
<div>
|
|
||||||
<h4 className="mb-4 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
|
|
||||||
<KeyRound className="h-3.5 w-3.5" />
|
|
||||||
Permissions
|
|
||||||
</h4>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{member.permissions.map((perm) => (
|
|
||||||
<Badge
|
|
||||||
key={perm}
|
|
||||||
className="bg-grayScale-100 text-grayScale-600 border border-grayScale-200 font-mono text-xs"
|
|
||||||
>
|
|
||||||
{perm}
|
|
||||||
</Badge>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Right: Profile Card */}
|
|
||||||
<Card>
|
|
||||||
<CardContent className="flex flex-col items-center p-6">
|
|
||||||
{/* Avatar with gradient ring */}
|
|
||||||
<div className="relative mt-2">
|
|
||||||
<div className="rounded-full bg-gradient-to-br from-brand-400 via-brand-600 to-mint-500 p-1">
|
|
||||||
<Avatar className="h-28 w-28 ring-4 ring-white">
|
|
||||||
<AvatarImage src={undefined} alt={fullName} />
|
|
||||||
<AvatarFallback className="bg-brand-100 text-brand-600 text-3xl font-bold">
|
|
||||||
{initials}
|
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
</div>
|
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-lg font-semibold text-grayScale-800">{fullName}</p>
|
||||||
|
<p className="text-sm text-grayScale-500">{displayValue(member.job_title)}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h3 className="mt-4 text-lg font-bold text-grayScale-600">
|
<div className="flex flex-wrap items-center gap-2 sm:justify-end">
|
||||||
{fullName}
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm text-grayScale-400">{member.job_title}</p>
|
|
||||||
|
|
||||||
{/* Action buttons */}
|
|
||||||
<div className="mt-5 flex w-full gap-3">
|
|
||||||
<Button className="flex-1 rounded-full bg-mint-500 text-white hover:bg-mint-300">
|
|
||||||
Connect
|
|
||||||
</Button>
|
|
||||||
<Button className="flex-1 rounded-full bg-grayScale-600 text-white hover:bg-grayScale-500">
|
|
||||||
<MessageCircle className="h-4 w-4" />
|
|
||||||
Message
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Stats row */}
|
|
||||||
<div className="mt-6 grid w-full grid-cols-3 divide-x divide-grayScale-200 text-center">
|
|
||||||
<div className="px-2">
|
|
||||||
<p className="text-xs font-medium text-grayScale-400">Role</p>
|
|
||||||
<p className="mt-1">
|
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold",
|
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium",
|
||||||
getRoleBadgeClasses(member.team_role)
|
getRoleBadgeClasses(member.team_role),
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Shield className="h-3 w-3" />
|
<Shield className="mr-1 h-3 w-3" />
|
||||||
{formatRoleLabel(member.team_role)}
|
{formatRoleLabel(member.team_role)}
|
||||||
</span>
|
</span>
|
||||||
</p>
|
<Badge variant={isActive ? "default" : "secondary"}>
|
||||||
|
{formatStatusLabel(member.status)}
|
||||||
|
</Badge>
|
||||||
|
<Badge variant={member.email_verified ? "default" : "outline"}>
|
||||||
|
{member.email_verified ? "Verified" : "Unverified"}
|
||||||
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<div className="px-2">
|
</CardContent>
|
||||||
<p className="text-xs font-medium text-grayScale-400">Status</p>
|
</Card>
|
||||||
<p className="mt-1">
|
|
||||||
<span
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
className={cn(
|
<StatTile icon={CalendarDays} label="Joined" value={formatDate(member.created_at)} />
|
||||||
"inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium",
|
<StatTile icon={Clock3} label="Last login" value={formatDateTime(member.last_login)} />
|
||||||
member.status === "active"
|
<StatTile
|
||||||
? "bg-mint-100 text-mint-500"
|
icon={BadgeCheck}
|
||||||
: "bg-destructive/10 text-destructive"
|
label="Email status"
|
||||||
)}
|
value={member.email_verified ? "Verified" : "Not verified"}
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"h-1.5 w-1.5 rounded-full",
|
|
||||||
member.status === "active" ? "bg-mint-500" : "bg-destructive"
|
|
||||||
)}
|
|
||||||
/>
|
/>
|
||||||
{member.status === "active" ? "Active" : "Inactive"}
|
<StatTile icon={Clock3} label="Last updated" value={formatDateTime(member.updated_at)} />
|
||||||
</span>
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="px-2">
|
|
||||||
<p className="text-xs font-medium text-grayScale-400">Type</p>
|
<Card className="border-grayScale-100 shadow-soft">
|
||||||
<p className="mt-1 text-xs font-medium text-grayScale-600">
|
<CardHeader className="pb-2">
|
||||||
{formatEmploymentType(member.employment_type)}
|
<CardTitle className="text-base">Member record</CardTitle>
|
||||||
</p>
|
</CardHeader>
|
||||||
|
<CardContent className="pt-0">
|
||||||
|
{member.bio ? (
|
||||||
|
<div className="mb-4 rounded-lg border border-grayScale-100 bg-grayScale-50/60 px-4 py-3">
|
||||||
|
<p className="text-xs font-medium uppercase tracking-wide text-grayScale-400">Bio</p>
|
||||||
|
<p className="mt-1 text-sm leading-relaxed text-grayScale-700">{member.bio}</p>
|
||||||
</div>
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="grid gap-0 md:grid-cols-2 md:gap-x-8">
|
||||||
|
<div>
|
||||||
|
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-400">
|
||||||
|
Contact
|
||||||
|
</p>
|
||||||
|
<DetailRow icon={Mail} label="Email" value={displayValue(member.email)} />
|
||||||
|
<Separator />
|
||||||
|
<DetailRow icon={Phone} label="Phone" value={displayValue(member.phone_number)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-400">
|
||||||
|
Role & organization
|
||||||
|
</p>
|
||||||
|
<DetailRow icon={Shield} label="Team role" value={formatRoleLabel(member.team_role)} />
|
||||||
|
<Separator />
|
||||||
|
<DetailRow icon={Building2} label="Department" value={displayValue(member.department)} />
|
||||||
|
<Separator />
|
||||||
|
<DetailRow icon={Briefcase} label="Job title" value={displayValue(member.job_title)} />
|
||||||
|
<Separator />
|
||||||
|
<DetailRow icon={Hash} label="Member ID" value={String(member.id)} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator className="my-4" />
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 text-xs text-grayScale-400">
|
||||||
|
<UserCircle2 className="h-3.5 w-3.5" />
|
||||||
|
<span>Read-only team directory record</span>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,10 +13,10 @@ import {
|
||||||
Globe,
|
Globe,
|
||||||
Monitor,
|
Monitor,
|
||||||
FileText,
|
FileText,
|
||||||
X,
|
|
||||||
Info,
|
Info,
|
||||||
Shield,
|
Shield,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { Input } from "../../components/ui/input";
|
import { Input } from "../../components/ui/input";
|
||||||
import {
|
import {
|
||||||
|
|
@ -35,6 +35,7 @@ import {
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
DialogDescription,
|
DialogDescription,
|
||||||
} from "../../components/ui/dialog";
|
} from "../../components/ui/dialog";
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
||||||
import { cn } from "../../lib/utils";
|
import { cn } from "../../lib/utils";
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
||||||
import { getActivityLogs, getActivityLogById } from "../../api/activity-logs.api";
|
import { getActivityLogs, getActivityLogById } from "../../api/activity-logs.api";
|
||||||
|
|
@ -193,13 +194,18 @@ export function UserLogPage() {
|
||||||
|
|
||||||
const clearFilters = () => {
|
const clearFilters = () => {
|
||||||
setActionFilter("");
|
setActionFilter("");
|
||||||
setSearchQuery("");
|
|
||||||
setDateAfter("");
|
setDateAfter("");
|
||||||
setDateBefore("");
|
setDateBefore("");
|
||||||
setPage(1);
|
setPage(1);
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasActiveFilters = actionFilter || dateAfter || dateBefore;
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: actionFilter },
|
||||||
|
{ value: dateAfter },
|
||||||
|
{ value: dateBefore },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim());
|
||||||
|
|
||||||
// Pagination
|
// Pagination
|
||||||
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize));
|
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize));
|
||||||
|
|
@ -291,9 +297,11 @@ export function UserLogPage() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filters */}
|
<AdminFiltersPanel
|
||||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
activeFilterCount={activeFilterCount}
|
||||||
<div className="relative flex-1 min-w-[200px]">
|
onClearFilters={clearFilters}
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
placeholder="Search by message, action, or role..."
|
placeholder="Search by message, action, or role..."
|
||||||
|
|
@ -302,7 +310,9 @@ export function UserLogPage() {
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<select
|
<select
|
||||||
value={actionFilter}
|
value={actionFilter}
|
||||||
|
|
@ -310,7 +320,7 @@ export function UserLogPage() {
|
||||||
setActionFilter(e.target.value);
|
setActionFilter(e.target.value);
|
||||||
setPage(1);
|
setPage(1);
|
||||||
}}
|
}}
|
||||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
className="h-9 appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||||
>
|
>
|
||||||
<option value="">Action: All</option>
|
<option value="">Action: All</option>
|
||||||
{ACTION_TYPES.map((action) => (
|
{ACTION_TYPES.map((action) => (
|
||||||
|
|
@ -321,7 +331,6 @@ export function UserLogPage() {
|
||||||
</select>
|
</select>
|
||||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<label className="text-xs font-medium text-grayScale-400">From</label>
|
<label className="text-xs font-medium text-grayScale-400">From</label>
|
||||||
<input
|
<input
|
||||||
|
|
@ -331,10 +340,9 @@ export function UserLogPage() {
|
||||||
setDateAfter(e.target.value);
|
setDateAfter(e.target.value);
|
||||||
setPage(1);
|
setPage(1);
|
||||||
}}
|
}}
|
||||||
className="h-10 rounded-lg border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
className="h-9 rounded-md border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<label className="text-xs font-medium text-grayScale-400">To</label>
|
<label className="text-xs font-medium text-grayScale-400">To</label>
|
||||||
<input
|
<input
|
||||||
|
|
@ -344,22 +352,11 @@ export function UserLogPage() {
|
||||||
setDateBefore(e.target.value);
|
setDateBefore(e.target.value);
|
||||||
setPage(1);
|
setPage(1);
|
||||||
}}
|
}}
|
||||||
className="h-10 rounded-lg border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
className="h-9 rounded-md border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{hasActiveFilters && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={clearFilters}
|
|
||||||
className="gap-1 text-grayScale-400 hover:text-grayScale-600"
|
|
||||||
>
|
|
||||||
<X className="h-3.5 w-3.5" />
|
|
||||||
Clear
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
</AdminFiltersPanel>
|
||||||
|
|
||||||
{/* Table */}
|
{/* Table */}
|
||||||
<div className="rounded-xl border bg-white">
|
<div className="rounded-xl border bg-white">
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||||
import { CalendarDays, ChevronDown, ChevronLeft, ChevronRight, Search, SlidersHorizontal } from "lucide-react"
|
import { CalendarDays, ChevronDown, ChevronLeft, ChevronRight, Search } from "lucide-react"
|
||||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
|
|
@ -15,6 +16,7 @@ import {
|
||||||
} from "../../components/ui/table"
|
} from "../../components/ui/table"
|
||||||
import { getDeletionRequests } from "../../api/users.api"
|
import { getDeletionRequests } from "../../api/users.api"
|
||||||
import { getRoles } from "../../api/rbac.api"
|
import { getRoles } from "../../api/rbac.api"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import type {
|
import type {
|
||||||
|
|
@ -236,6 +238,16 @@ export function DeletionRequestsPage() {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: role },
|
||||||
|
{ value: status },
|
||||||
|
{ value: state },
|
||||||
|
{ value: requestedAfter },
|
||||||
|
{ value: requestedBefore },
|
||||||
|
{ value: scheduledAfter },
|
||||||
|
{ value: scheduledBefore },
|
||||||
|
])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -245,16 +257,14 @@ export function DeletionRequestsPage() {
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card className="overflow-visible rounded-2xl border border-brand-100/70 bg-white shadow-soft">
|
<AdminFiltersPanel
|
||||||
<CardHeader className="border-b border-brand-100/70 bg-gradient-to-r from-brand-100/50 via-white to-brand-100/25 pb-4">
|
className="overflow-visible rounded-2xl border border-brand-100/70 shadow-soft"
|
||||||
<CardTitle className="flex items-center gap-2 text-base font-semibold text-grayScale-700">
|
activeFilterCount={activeFilterCount}
|
||||||
<SlidersHorizontal className="h-4 w-4 text-brand-600" />
|
onClearFilters={resetFilters}
|
||||||
Filters
|
clearLabel="Clear filters"
|
||||||
</CardTitle>
|
summary={`${total} request${total === 1 ? "" : "s"}`}
|
||||||
</CardHeader>
|
search={
|
||||||
<CardContent className="space-y-5 bg-gradient-to-b from-white to-brand-100/10 pt-5">
|
<div className="relative">
|
||||||
<div className="grid grid-cols-1 gap-3 lg:grid-cols-4">
|
|
||||||
<div className="relative lg:col-span-2">
|
|
||||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||||
<Input
|
<Input
|
||||||
value={query}
|
value={query}
|
||||||
|
|
@ -266,6 +276,9 @@ export function DeletionRequestsPage() {
|
||||||
className="h-11 rounded-xl border-grayScale-200 bg-white pl-10 shadow-sm transition focus-visible:border-brand-400 focus-visible:ring-brand-200"
|
className="h-11 rounded-xl border-grayScale-200 bg-white pl-10 shadow-sm transition focus-visible:border-brand-400 focus-visible:ring-brand-200"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
|
||||||
<div className="relative" ref={roleMenuRef}>
|
<div className="relative" ref={roleMenuRef}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|
@ -478,18 +491,8 @@ export function DeletionRequestsPage() {
|
||||||
}}
|
}}
|
||||||
placeholder={`Scheduled before (${DATE_PLACEHOLDER})`}
|
placeholder={`Scheduled before (${DATE_PLACEHOLDER})`}
|
||||||
/>
|
/>
|
||||||
<div className="flex justify-end lg:col-start-4 lg:col-span-1">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="h-11 rounded-xl border-brand-200 px-5 text-brand-700 hover:bg-brand-100/40"
|
|
||||||
onClick={resetFilters}
|
|
||||||
>
|
|
||||||
Clear Filters
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</AdminFiltersPanel>
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card className="shadow-soft">
|
<Card className="shadow-soft">
|
||||||
<CardHeader className="border-b border-grayScale-200 pb-4">
|
<CardHeader className="border-b border-grayScale-200 pb-4">
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,13 @@
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
BarChart3,
|
|
||||||
BookOpen,
|
BookOpen,
|
||||||
Calendar,
|
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
Globe,
|
Globe,
|
||||||
GraduationCap,
|
GraduationCap,
|
||||||
Lock,
|
|
||||||
Mail,
|
Mail,
|
||||||
MapPin,
|
MapPin,
|
||||||
Phone,
|
|
||||||
PlayCircle,
|
PlayCircle,
|
||||||
RefreshCw,
|
|
||||||
Target,
|
Target,
|
||||||
UserPlus,
|
UserPlus,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
@ -23,26 +18,17 @@ import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/ca
|
||||||
import { Separator } from "../../components/ui/separator";
|
import { Separator } from "../../components/ui/separator";
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar";
|
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar";
|
||||||
import { cn } from "../../lib/utils";
|
import { cn } from "../../lib/utils";
|
||||||
import { useUsersStore } from "../../zustand/userStore";
|
|
||||||
import { getUserById, getUserRecentActivity } from "../../api/users.api";
|
|
||||||
import { getCourseCategories, getCoursesByCategory } from "../../api/courses.api";
|
|
||||||
import {
|
import {
|
||||||
getAdminLearnerCourseProgress,
|
getUserById,
|
||||||
getAdminLearnerCourseProgressSummary,
|
getUserLearningActivity,
|
||||||
} from "../../api/progress.api";
|
getUserRecentActivity,
|
||||||
import {
|
getUserSubscriptions,
|
||||||
Table,
|
} from "../../api/users.api";
|
||||||
TableBody,
|
|
||||||
TableCell,
|
|
||||||
TableHead,
|
|
||||||
TableHeader,
|
|
||||||
TableRow,
|
|
||||||
} from "../../components/ui/table";
|
|
||||||
import { Select } from "../../components/ui/select";
|
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon";
|
import { SpinnerIcon } from "../../components/ui/spinner-icon";
|
||||||
import type { LearnerCourseProgressItem, LearnerCourseProgressSummary } from "../../types/progress.types";
|
import type { UserProfileData, UserRecentActivityItem } from "../../types/user.types";
|
||||||
import type { Course } from "../../types/course.types";
|
import type { UserLearningActivityData, UserSubscriptionsData } from "../../types/userAdmin.types";
|
||||||
import type { UserRecentActivityItem } from "../../types/user.types";
|
import { UserLearningActivitySection } from "./components/UserLearningActivitySection";
|
||||||
|
import { UserSubscriptionsSection } from "./components/UserSubscriptionsSection";
|
||||||
|
|
||||||
const activityIcons = {
|
const activityIcons = {
|
||||||
completed: CheckCircle2,
|
completed: CheckCircle2,
|
||||||
|
|
@ -59,7 +45,59 @@ function visualActivityKind(kind: string): keyof typeof activityIcons {
|
||||||
return "default";
|
return "default";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Matches Recent Activity mock: "Today, 10:27 AM" / "Yesterday, 3:45 PM" / "Jan 10, 2025". */
|
function displayValue(value: string | null | undefined): string {
|
||||||
|
const trimmed = value?.trim();
|
||||||
|
return trimmed ? trimmed : "—";
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRoleLabel(role: string): string {
|
||||||
|
const value = role.trim();
|
||||||
|
if (!value) return "—";
|
||||||
|
return value
|
||||||
|
.split("_")
|
||||||
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||||
|
.join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatStatusLabel(status: string): string {
|
||||||
|
const value = status.trim();
|
||||||
|
if (!value) return "—";
|
||||||
|
return value
|
||||||
|
.split("_")
|
||||||
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||||
|
.join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatAgeGroup(ageGroup: string): string {
|
||||||
|
const value = ageGroup.trim();
|
||||||
|
if (!value) return "—";
|
||||||
|
return value.replace(/_/g, "-");
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(dateStr: string | null | undefined): string {
|
||||||
|
if (!dateStr?.trim()) return "—";
|
||||||
|
const date = new Date(dateStr);
|
||||||
|
if (Number.isNaN(date.getTime())) return dateStr;
|
||||||
|
return date.toLocaleDateString(undefined, {
|
||||||
|
year: "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateTime(value?: string | null): string {
|
||||||
|
if (!value?.trim()) return "—";
|
||||||
|
const parsed = new Date(value);
|
||||||
|
if (Number.isNaN(parsed.getTime())) return "—";
|
||||||
|
return parsed.toLocaleString(undefined, {
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
year: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function formatActivityOccurredAt(iso: string): string {
|
function formatActivityOccurredAt(iso: string): string {
|
||||||
const d = new Date(iso);
|
const d = new Date(iso);
|
||||||
if (Number.isNaN(d.getTime())) return "—";
|
if (Number.isNaN(d.getTime())) return "—";
|
||||||
|
|
@ -69,7 +107,7 @@ function formatActivityOccurredAt(iso: string): string {
|
||||||
const startThat = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
const startThat = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||||
const dayDiff = Math.round((startToday - startThat) / 86_400_000);
|
const dayDiff = Math.round((startToday - startThat) / 86_400_000);
|
||||||
|
|
||||||
const timePart = d.toLocaleTimeString("en-US", {
|
const timePart = d.toLocaleTimeString(undefined, {
|
||||||
hour: "numeric",
|
hour: "numeric",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
hour12: true,
|
hour12: true,
|
||||||
|
|
@ -78,114 +116,131 @@ function formatActivityOccurredAt(iso: string): string {
|
||||||
if (dayDiff === 0) return `Today, ${timePart}`;
|
if (dayDiff === 0) return `Today, ${timePart}`;
|
||||||
if (dayDiff === 1) return `Yesterday, ${timePart}`;
|
if (dayDiff === 1) return `Yesterday, ${timePart}`;
|
||||||
|
|
||||||
return d.toLocaleDateString("en-US", {
|
return d.toLocaleDateString(undefined, {
|
||||||
month: "short",
|
month: "short",
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
type CourseOption = Course & { category_name: string };
|
function getAccountStatusClasses(status: string): string {
|
||||||
|
const normalized = status.trim().toUpperCase();
|
||||||
|
if (normalized === "ACTIVE") {
|
||||||
|
return "bg-mint-500/15 text-mint-500 border border-mint-500/25";
|
||||||
|
}
|
||||||
|
return "bg-destructive/15 text-destructive border border-destructive/25";
|
||||||
|
}
|
||||||
|
|
||||||
|
function LoadingSkeleton() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
|
||||||
|
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="h-80 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
|
<div className="h-64 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="h-56 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
|
<div className="h-72 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function UserDetailPage() {
|
export function UserDetailPage() {
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
const userProfile = useUsersStore((s) => s.userProfile);
|
const [user, setUser] = useState<UserProfileData | null>(null);
|
||||||
const setUserProfile = useUsersStore((s) => s.setUserProfile);
|
const [loadingUser, setLoadingUser] = useState(true);
|
||||||
const [courseOptions, setCourseOptions] = useState<CourseOption[]>([]);
|
const [userError, setUserError] = useState<string | null>(null);
|
||||||
const [loadingCourseOptions, setLoadingCourseOptions] = useState(false);
|
const [learningActivity, setLearningActivity] = useState<UserLearningActivityData | null>(null);
|
||||||
const [selectedProgressCourseId, setSelectedProgressCourseId] = useState<number | null>(null);
|
const [learningActivityLoading, setLearningActivityLoading] = useState(false);
|
||||||
const [progressItems, setProgressItems] = useState<LearnerCourseProgressItem[]>([]);
|
const [learningActivityError, setLearningActivityError] = useState<string | null>(null);
|
||||||
const [progressSummary, setProgressSummary] = useState<LearnerCourseProgressSummary | null>(null);
|
const [subscriptions, setSubscriptions] = useState<UserSubscriptionsData | null>(null);
|
||||||
const [loadingProgress, setLoadingProgress] = useState(false);
|
const [subscriptionsLoading, setSubscriptionsLoading] = useState(false);
|
||||||
const [progressError, setProgressError] = useState<string | null>(null);
|
const [subscriptionsError, setSubscriptionsError] = useState<string | null>(null);
|
||||||
const [recentActivityItems, setRecentActivityItems] = useState<UserRecentActivityItem[]>([]);
|
const [recentActivityItems, setRecentActivityItems] = useState<UserRecentActivityItem[]>([]);
|
||||||
const [recentActivityLoading, setRecentActivityLoading] = useState(false);
|
const [recentActivityLoading, setRecentActivityLoading] = useState(false);
|
||||||
|
const [recentActivityError, setRecentActivityError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const userId = Number(id);
|
||||||
|
if (!Number.isFinite(userId) || userId <= 0) {
|
||||||
|
setUserError("Invalid user ID.");
|
||||||
|
setLoadingUser(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchUser = async () => {
|
||||||
|
setLoadingUser(true);
|
||||||
|
setUserError(null);
|
||||||
|
try {
|
||||||
|
const res = await getUserById(userId);
|
||||||
|
setUser(res.data.data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to fetch user profile", err);
|
||||||
|
setUser(null);
|
||||||
|
setUserError("User not found.");
|
||||||
|
} finally {
|
||||||
|
setLoadingUser(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void fetchUser();
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
const fetchUser = async () => {
|
|
||||||
try {
|
|
||||||
const res = await getUserById(Number(id));
|
|
||||||
setUserProfile(res.data.data);
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to fetch user profile", err);
|
|
||||||
setUserProfile(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
fetchUser();
|
|
||||||
}, [id, setUserProfile]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const loadCourseOptions = async () => {
|
|
||||||
setLoadingCourseOptions(true);
|
|
||||||
try {
|
|
||||||
const categoriesRes = await getCourseCategories();
|
|
||||||
const categories = categoriesRes.data?.data?.categories ?? [];
|
|
||||||
const options: CourseOption[] = [];
|
|
||||||
|
|
||||||
for (const category of categories) {
|
|
||||||
const coursesRes = await getCoursesByCategory(category.id);
|
|
||||||
const courses = coursesRes.data?.data?.courses ?? [];
|
|
||||||
options.push(
|
|
||||||
...courses.map((course) => ({
|
|
||||||
...course,
|
|
||||||
category_name: category.name,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
setCourseOptions(options);
|
|
||||||
if (options.length > 0 && !selectedProgressCourseId) {
|
|
||||||
setSelectedProgressCourseId(options[0].id);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
setCourseOptions([]);
|
|
||||||
} finally {
|
|
||||||
setLoadingCourseOptions(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
loadCourseOptions();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!id || !selectedProgressCourseId) return;
|
|
||||||
|
|
||||||
const userId = Number(id);
|
const userId = Number(id);
|
||||||
if (Number.isNaN(userId)) return;
|
if (Number.isNaN(userId)) return;
|
||||||
|
|
||||||
const loadProgress = async () => {
|
const loadLearningActivity = async () => {
|
||||||
setLoadingProgress(true);
|
setLearningActivityLoading(true);
|
||||||
setProgressError(null);
|
setLearningActivityError(null);
|
||||||
try {
|
try {
|
||||||
const [summaryRes, detailRes] = await Promise.all([
|
const res = await getUserLearningActivity(userId);
|
||||||
getAdminLearnerCourseProgressSummary(userId, selectedProgressCourseId),
|
setLearningActivity(res.data.data);
|
||||||
getAdminLearnerCourseProgress(userId, selectedProgressCourseId),
|
} catch (err) {
|
||||||
]);
|
console.error("Failed to load learning activity", err);
|
||||||
|
setLearningActivity(null);
|
||||||
setProgressSummary(summaryRes.data?.data ?? null);
|
const message =
|
||||||
const ordered = [...(detailRes.data?.data ?? [])].sort(
|
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
|
||||||
(a, b) => a.display_order - b.display_order || a.sub_course_id - b.sub_course_id,
|
"Failed to load learning activity.";
|
||||||
);
|
setLearningActivityError(message);
|
||||||
setProgressItems(ordered);
|
|
||||||
} catch (err: any) {
|
|
||||||
setProgressSummary(null);
|
|
||||||
setProgressItems([]);
|
|
||||||
const status = err?.response?.status;
|
|
||||||
if (status === 403) {
|
|
||||||
setProgressError("Missing permission: progress.get_any_user");
|
|
||||||
} else if (status === 400) {
|
|
||||||
setProgressError("Invalid learner or course selection.");
|
|
||||||
} else {
|
|
||||||
setProgressError(err?.response?.data?.message || "Failed to load learner progress.");
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingProgress(false);
|
setLearningActivityLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
loadProgress();
|
void loadLearningActivity();
|
||||||
}, [id, selectedProgressCourseId]);
|
}, [id]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!id) return;
|
||||||
|
const userId = Number(id);
|
||||||
|
if (Number.isNaN(userId)) return;
|
||||||
|
|
||||||
|
const loadSubscriptions = async () => {
|
||||||
|
setSubscriptionsLoading(true);
|
||||||
|
setSubscriptionsError(null);
|
||||||
|
try {
|
||||||
|
const res = await getUserSubscriptions(userId);
|
||||||
|
setSubscriptions(res.data.data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to load subscriptions", err);
|
||||||
|
setSubscriptions(null);
|
||||||
|
const message =
|
||||||
|
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
|
||||||
|
"Failed to load subscriptions.";
|
||||||
|
setSubscriptionsError(message);
|
||||||
|
} finally {
|
||||||
|
setSubscriptionsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void loadSubscriptions();
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
|
|
@ -194,57 +249,46 @@ export function UserDetailPage() {
|
||||||
|
|
||||||
const loadRecent = async () => {
|
const loadRecent = async () => {
|
||||||
setRecentActivityLoading(true);
|
setRecentActivityLoading(true);
|
||||||
|
setRecentActivityError(null);
|
||||||
try {
|
try {
|
||||||
const res = await getUserRecentActivity(userId);
|
const res = await getUserRecentActivity(userId);
|
||||||
const items = res.data?.data?.items ?? [];
|
const items = [...(res.data.data.items ?? [])].sort(
|
||||||
|
(a, b) => new Date(b.occurred_at).getTime() - new Date(a.occurred_at).getTime(),
|
||||||
|
);
|
||||||
setRecentActivityItems(items);
|
setRecentActivityItems(items);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to load recent activity", err);
|
console.error("Failed to load recent activity", err);
|
||||||
setRecentActivityItems([]);
|
setRecentActivityItems([]);
|
||||||
|
const message =
|
||||||
|
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
|
||||||
|
"Failed to load recent activity.";
|
||||||
|
setRecentActivityError(message);
|
||||||
} finally {
|
} finally {
|
||||||
setRecentActivityLoading(false);
|
setRecentActivityLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
loadRecent();
|
void loadRecent();
|
||||||
}, [id]);
|
}, [id]);
|
||||||
|
|
||||||
const progressMetrics = useMemo(() => {
|
if (loadingUser) return <LoadingSkeleton />;
|
||||||
if (progressSummary) {
|
|
||||||
return {
|
|
||||||
total: progressSummary.total_sub_courses ?? 0,
|
|
||||||
completed: progressSummary.completed_sub_courses ?? 0,
|
|
||||||
inProgress: progressSummary.in_progress_sub_courses ?? 0,
|
|
||||||
locked: progressSummary.locked_sub_courses ?? 0,
|
|
||||||
averageProgress: Math.round(progressSummary.overall_progress_percentage ?? 0),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const total = progressItems.length;
|
if (userError || !user) {
|
||||||
const completed = progressItems.filter((item) => item.progress_status === "COMPLETED").length;
|
|
||||||
const inProgress = progressItems.filter((item) => item.progress_status === "IN_PROGRESS").length;
|
|
||||||
const locked = progressItems.filter((item) => item.is_locked).length;
|
|
||||||
const averageProgress =
|
|
||||||
total === 0
|
|
||||||
? 0
|
|
||||||
: Math.round(
|
|
||||||
progressItems.reduce((sum, item) => sum + Number(item.progress_percentage || 0), 0) / total,
|
|
||||||
);
|
|
||||||
|
|
||||||
return { total, completed, inProgress, locked, averageProgress };
|
|
||||||
}, [progressItems, progressSummary]);
|
|
||||||
|
|
||||||
if (!userProfile) {
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-3xl space-y-4 py-12">
|
<div className="mx-auto w-full max-w-3xl space-y-4 py-12">
|
||||||
|
<Link
|
||||||
|
to="/users/list"
|
||||||
|
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
Back to Users
|
||||||
|
</Link>
|
||||||
<Card className="shadow-soft">
|
<Card className="shadow-soft">
|
||||||
<CardContent className="flex flex-col items-center gap-4 p-10">
|
<CardContent className="flex flex-col items-center gap-4 p-10">
|
||||||
<div className="h-16 w-16 rounded-full bg-grayScale-100 flex items-center justify-center">
|
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-grayScale-100">
|
||||||
<Target className="h-8 w-8 text-grayScale-300" />
|
<Target className="h-8 w-8 text-grayScale-300" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-lg font-semibold text-grayScale-600">
|
<p className="text-lg font-semibold text-grayScale-600">{userError || "User not found"}</p>
|
||||||
User not found
|
|
||||||
</div>
|
|
||||||
<Button asChild variant="outline" className="mt-2">
|
<Button asChild variant="outline" className="mt-2">
|
||||||
<Link to="/users/list">Back to Users</Link>
|
<Link to="/users/list">Back to Users</Link>
|
||||||
</Button>
|
</Button>
|
||||||
|
|
@ -254,39 +298,18 @@ export function UserDetailPage() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = userProfile;
|
const fullName = `${user.first_name} ${user.last_name}`.trim();
|
||||||
const fullName = `${user.first_name} ${user.last_name}`;
|
|
||||||
const initials = `${user.first_name?.[0] ?? ""}${user.last_name?.[0] ?? ""}`.toUpperCase();
|
const initials = `${user.first_name?.[0] ?? ""}${user.last_name?.[0] ?? ""}`.toUpperCase();
|
||||||
|
const profilePicture = user.profile_picture_url?.trim() || undefined;
|
||||||
|
|
||||||
const infoFields = [
|
const contactFields = [
|
||||||
{ icon: Phone, label: "Phone", value: user.phone_number },
|
{ icon: Mail, label: "Email", value: displayValue(user.email) },
|
||||||
{ icon: Mail, label: "Email", value: user.email },
|
{ icon: Globe, label: "Country", value: displayValue(user.country) },
|
||||||
{ icon: Globe, label: "Country", value: user.country || "Ethiopia" },
|
{ icon: MapPin, label: "Region", value: displayValue(user.region) },
|
||||||
{ icon: MapPin, label: "Region", value: user.region },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
const statusVariant = (status: LearnerCourseProgressItem["progress_status"]) => {
|
|
||||||
if (status === "COMPLETED") return "success" as const;
|
|
||||||
if (status === "IN_PROGRESS") return "warning" as const;
|
|
||||||
return "secondary" as const;
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDateTime = (value?: string | null) => {
|
|
||||||
if (!value) return "—";
|
|
||||||
const parsed = new Date(value);
|
|
||||||
if (Number.isNaN(parsed.getTime())) return "—";
|
|
||||||
return parsed.toLocaleString("en-US", {
|
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
year: "numeric",
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<Link
|
<Link
|
||||||
to="/users/list"
|
to="/users/list"
|
||||||
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||||
|
|
@ -294,52 +317,55 @@ export function UserDetailPage() {
|
||||||
<ArrowLeft className="h-4 w-4" />
|
<ArrowLeft className="h-4 w-4" />
|
||||||
Back to Users
|
Back to Users
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-grayScale-500">Learners</p>
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">{fullName}</h1>
|
||||||
|
<p className="mt-1 text-sm text-grayScale-500">
|
||||||
|
User #{user.id} · {formatRoleLabel(user.role)}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
||||||
{/* ── Left column ── */}
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Profile card */}
|
<Card className="overflow-hidden shadow-soft">
|
||||||
<Card className="overflow-hidden">
|
<CardContent className="space-y-5 p-5">
|
||||||
<div className="h-24 bg-gradient-to-br from-brand-600 via-brand-500 to-brand-400" />
|
<div className="flex items-center gap-4">
|
||||||
<CardContent className="-mt-12 space-y-5 px-4 sm:px-6 pb-6 pt-0">
|
<Avatar className="h-16 w-16 shrink-0">
|
||||||
<div className="flex flex-col items-center text-center">
|
{profilePicture ? <AvatarImage src={profilePicture} alt={fullName} /> : null}
|
||||||
<Avatar className="h-20 w-20 ring-4 ring-white shadow-soft">
|
<AvatarFallback className="bg-brand-100 text-lg font-semibold text-brand-600">
|
||||||
<AvatarImage src={user.profile_picture_url ?? undefined} alt={fullName} />
|
{initials || "?"}
|
||||||
<AvatarFallback className="bg-brand-100 text-brand-600 text-xl">
|
|
||||||
{initials}
|
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
<h2 className="mt-3 text-lg font-semibold text-grayScale-600">
|
<div className="min-w-0">
|
||||||
{fullName}
|
<h2 className="truncate text-lg font-semibold text-grayScale-800">{fullName}</h2>
|
||||||
</h2>
|
{user.nick_name.trim() ? (
|
||||||
<Badge
|
<p className="text-sm text-grayScale-500">@{user.nick_name.trim()}</p>
|
||||||
className={cn(
|
) : null}
|
||||||
"mt-1.5",
|
<div className="mt-2 flex flex-wrap gap-2">
|
||||||
user.status === "ACTIVE"
|
<Badge className={cn(getAccountStatusClasses(user.status))}>
|
||||||
? "bg-mint-500/15 text-mint-500 border border-mint-500/25"
|
{formatStatusLabel(user.status)}
|
||||||
: "bg-destructive/15 text-destructive border border-destructive/25"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{user.status === "ACTIVE" ? "Active" : "Inactive"}
|
|
||||||
</Badge>
|
</Badge>
|
||||||
|
<Badge variant={user.email_verified ? "default" : "outline"}>
|
||||||
|
{user.email_verified ? "Email verified" : "Email unverified"}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{infoFields.map(({ icon: Icon, label, value }) => (
|
{contactFields.map(({ icon: Icon, label, value }) => (
|
||||||
<div key={label} className="flex items-center gap-3">
|
<div key={label} className="flex items-center gap-3">
|
||||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-100">
|
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-100">
|
||||||
<Icon className="h-4 w-4 text-grayScale-400" />
|
<Icon className="h-4 w-4 text-grayScale-400" />
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
<p className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||||
{label}
|
{label}
|
||||||
</div>
|
</p>
|
||||||
<div className="truncate text-sm text-grayScale-600">
|
<p className="truncate text-sm text-grayScale-700">{value}</p>
|
||||||
{value || "—"}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|
@ -347,275 +373,96 @@ export function UserDetailPage() {
|
||||||
|
|
||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="grid gap-3 text-sm">
|
||||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-100">
|
<InfoRow label="Joined" value={formatDate(user.created_at)} />
|
||||||
<Calendar className="h-4 w-4 text-grayScale-400" />
|
<InfoRow label="Last login" value={formatDateTime(user.last_login)} />
|
||||||
</div>
|
<InfoRow label="Gender" value={displayValue(user.gender)} />
|
||||||
<div className="min-w-0">
|
<InfoRow label="Birthday" value={formatDate(user.birth_day)} />
|
||||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
<InfoRow label="Occupation" value={displayValue(user.occupation)} />
|
||||||
Joined
|
|
||||||
</div>
|
|
||||||
<div className="text-sm text-grayScale-600">
|
|
||||||
{user.created_at
|
|
||||||
? new Date(user.created_at).toLocaleDateString("en-US", {
|
|
||||||
year: "numeric",
|
|
||||||
month: "long",
|
|
||||||
day: "numeric",
|
|
||||||
})
|
|
||||||
: "—"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Subscription card */}
|
<Card className="shadow-soft">
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-3">
|
<CardHeader className="pb-3">
|
||||||
<div className="flex items-center justify-between">
|
<CardTitle className="text-base">Account</CardTitle>
|
||||||
<CardTitle>Subscription</CardTitle>
|
|
||||||
<Badge
|
|
||||||
className={cn(
|
|
||||||
user.status === "ACTIVE"
|
|
||||||
? "bg-mint-500/15 text-mint-500 border border-mint-500/25"
|
|
||||||
: "bg-destructive/15 text-destructive border border-destructive/25"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{user.status === "ACTIVE" ? "Active" : "Inactive"}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<div className="rounded-xl bg-grayScale-100 p-4 space-y-3">
|
<InfoRow
|
||||||
<div className="flex items-center justify-between">
|
label="Phone verified"
|
||||||
<span className="text-xs font-medium uppercase tracking-wider text-grayScale-400">
|
value={user.phone_verified ? "Verified" : "Not verified"}
|
||||||
Plan
|
/>
|
||||||
</span>
|
<InfoRow
|
||||||
<span className="text-sm font-semibold text-grayScale-600">6-Month</span>
|
label="Profile completed"
|
||||||
</div>
|
value={user.profile_completed ? "Yes" : "No"}
|
||||||
<Separator />
|
/>
|
||||||
<div className="flex flex-wrap items-center justify-between gap-1">
|
<InfoRow
|
||||||
<span className="text-xs font-medium uppercase tracking-wider text-grayScale-400">
|
label="Profile completion"
|
||||||
Expires
|
value={`${user.profile_completion_percentage}%`}
|
||||||
</span>
|
/>
|
||||||
<div className="flex items-center gap-2">
|
<InfoRow
|
||||||
<span className="text-sm font-medium text-grayScale-600">Nov 13, 2025</span>
|
label="Preferred language"
|
||||||
<Badge className="bg-gold-100 text-gold-600 text-[10px] border border-gold-300">
|
value={displayValue(user.preferred_language)}
|
||||||
3 days left
|
/>
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button className="w-full bg-brand-600 hover:bg-brand-500 text-white transition-colors">
|
|
||||||
<RefreshCw className="h-4 w-4 mr-2" />
|
|
||||||
Extend Subscription
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
|
||||||
<Button variant="outline" className="w-full text-sm">
|
|
||||||
Mark as Paid
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="w-full text-sm text-destructive border-destructive/40 hover:bg-destructive/5"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<UserSubscriptionsSection
|
||||||
|
subscriptions={subscriptions}
|
||||||
|
loading={subscriptionsLoading}
|
||||||
|
error={subscriptionsError}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ── Right column ── */}
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Learning profile */}
|
<Card className="shadow-soft">
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-3">
|
<CardHeader className="pb-3">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-100/50">
|
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-100/50">
|
||||||
<GraduationCap className="h-4 w-4 text-brand-600" />
|
<GraduationCap className="h-4 w-4 text-brand-600" />
|
||||||
</div>
|
</div>
|
||||||
<CardTitle>Learning Profile</CardTitle>
|
<CardTitle className="text-base">Learning profile</CardTitle>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-5">
|
<CardContent className="space-y-5">
|
||||||
<div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3">
|
<div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3">
|
||||||
<InfoItem
|
<InfoItem label="Education level" value={displayValue(user.education_level)} />
|
||||||
label="Education Level"
|
<InfoItem label="Age group" value={formatAgeGroup(user.age_group)} />
|
||||||
value={user.education_level || "Undergraduate"}
|
<InfoItem label="Favorite topic" value={displayValue(user.favoutite_topic)} />
|
||||||
/>
|
<InfoItem label="Language goal" value={displayValue(user.language_goal)} />
|
||||||
<InfoItem
|
<InfoItem label="Challenge" value={displayValue(user.language_challange)} />
|
||||||
label="Age Group"
|
<InfoItem label="Role" value={formatRoleLabel(user.role)} />
|
||||||
value={user.age ? `${user.age} years` : "25-34"}
|
|
||||||
/>
|
|
||||||
<div>
|
|
||||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400 mb-1">
|
|
||||||
Proficiency
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm text-grayScale-600">Intermediate</span>
|
|
||||||
<span className="inline-flex h-5 items-center rounded-md bg-brand-100/60 px-1.5 text-[11px] font-semibold text-brand-600">
|
|
||||||
B1
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<InfoItem
|
|
||||||
label="Preferred Topic"
|
|
||||||
value={user.favoutite_topic || "Business"}
|
|
||||||
/>
|
|
||||||
<TagItem label="Learning Path" value={user.learning_goal || "Business English"} />
|
|
||||||
<TagItem label="Challenge" value={user.language_challange || "Speaking"} />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{user.learning_goal.trim() ? (
|
||||||
|
<>
|
||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400 mb-2">
|
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||||
Primary Goal
|
Learning goal
|
||||||
</div>
|
</p>
|
||||||
<div className="rounded-xl bg-grayScale-100 p-4 text-sm leading-relaxed text-grayScale-600">
|
<div className="rounded-xl bg-grayScale-100 p-4 text-sm leading-relaxed text-grayScale-700">
|
||||||
{user.learning_goal ||
|
{user.learning_goal.trim()}
|
||||||
"Improve business communication skills for professional advancement"}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Learner course progress */}
|
<UserLearningActivitySection
|
||||||
<Card>
|
activity={learningActivity}
|
||||||
<CardHeader className="pb-3">
|
loading={learningActivityLoading}
|
||||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
error={learningActivityError}
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-sky-100/70">
|
|
||||||
<BarChart3 className="h-4 w-4 text-sky-600" />
|
|
||||||
</div>
|
|
||||||
<CardTitle>Learner Course Progress</CardTitle>
|
|
||||||
</div>
|
|
||||||
<div className="w-full sm:w-72">
|
|
||||||
<Select
|
|
||||||
value={selectedProgressCourseId ? String(selectedProgressCourseId) : ""}
|
|
||||||
onChange={(e) =>
|
|
||||||
setSelectedProgressCourseId(e.target.value ? Number(e.target.value) : null)
|
|
||||||
}
|
|
||||||
disabled={loadingCourseOptions || courseOptions.length === 0}
|
|
||||||
>
|
|
||||||
<option value="">
|
|
||||||
{loadingCourseOptions ? "Loading course sub-categories..." : "Select course sub-category..."}
|
|
||||||
</option>
|
|
||||||
{courseOptions.map((course) => (
|
|
||||||
<option key={course.id} value={course.id}>
|
|
||||||
{course.title} ({course.category_name})
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5">
|
|
||||||
<Metric label="Total Sub-courses" value={progressMetrics.total} />
|
|
||||||
<Metric label="Completed" value={progressMetrics.completed} />
|
|
||||||
<Metric label="In Progress" value={progressMetrics.inProgress} />
|
|
||||||
<Metric label="Locked" value={progressMetrics.locked} />
|
|
||||||
<Metric label="Avg Progress" value={`${progressMetrics.averageProgress}%`} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{progressError && (
|
|
||||||
<div className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive">
|
|
||||||
{progressError}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!progressError && loadingProgress && (
|
|
||||||
<div className="flex items-center gap-2 rounded-lg border border-grayScale-200 bg-grayScale-100 px-3 py-2 text-xs text-grayScale-500">
|
|
||||||
<SpinnerIcon className="h-3.5 w-3.5" />
|
|
||||||
Loading learner progress...
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!progressError && !loadingProgress && selectedProgressCourseId && progressItems.length === 0 && (
|
|
||||||
<div className="rounded-lg border border-dashed border-grayScale-200 px-3 py-5 text-center text-xs text-grayScale-400">
|
|
||||||
No learner progress records found for this course sub-category.
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!progressError && !loadingProgress && progressItems.length > 0 && (
|
|
||||||
<div className="overflow-x-auto rounded-xl border bg-white">
|
|
||||||
<Table>
|
|
||||||
<TableHeader>
|
|
||||||
<TableRow>
|
|
||||||
<TableHead>Course</TableHead>
|
|
||||||
<TableHead>Level</TableHead>
|
|
||||||
<TableHead>Status</TableHead>
|
|
||||||
<TableHead>Progress</TableHead>
|
|
||||||
<TableHead>Started</TableHead>
|
|
||||||
<TableHead>Completed</TableHead>
|
|
||||||
</TableRow>
|
|
||||||
</TableHeader>
|
|
||||||
<TableBody>
|
|
||||||
{progressItems.map((item) => (
|
|
||||||
<TableRow key={item.sub_course_id}>
|
|
||||||
<TableCell className="min-w-[220px]">
|
|
||||||
<div className="flex items-start gap-2">
|
|
||||||
{item.is_locked && <Lock className="mt-0.5 h-3.5 w-3.5 text-gold-600" />}
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-grayScale-700">{item.title}</p>
|
|
||||||
{item.description && (
|
|
||||||
<p className="mt-0.5 line-clamp-1 text-xs text-grayScale-400">{item.description}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</TableCell>
|
|
||||||
<TableCell>
|
|
||||||
<Badge variant="secondary">{item.level}</Badge>
|
|
||||||
</TableCell>
|
|
||||||
<TableCell>
|
|
||||||
<Badge variant={statusVariant(item.progress_status)}>{item.progress_status}</Badge>
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="min-w-[170px]">
|
|
||||||
<div className="space-y-1">
|
|
||||||
<div className="h-2 w-full rounded-full bg-grayScale-200">
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"h-2 rounded-full transition-all",
|
|
||||||
item.progress_status === "COMPLETED"
|
|
||||||
? "bg-mint-500"
|
|
||||||
: item.progress_status === "IN_PROGRESS"
|
|
||||||
? "bg-gold-600"
|
|
||||||
: "bg-grayScale-300",
|
|
||||||
)}
|
|
||||||
style={{
|
|
||||||
width: `${Math.min(100, Math.max(0, item.progress_percentage || 0))}%`,
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
<p className="text-[11px] text-grayScale-500">{item.progress_percentage}%</p>
|
|
||||||
</div>
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="text-xs text-grayScale-500">
|
|
||||||
{formatDateTime(item.started_at)}
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="text-xs text-grayScale-500">
|
|
||||||
{formatDateTime(item.completed_at)}
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
))}
|
|
||||||
</TableBody>
|
|
||||||
</Table>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Recent activity */}
|
<Card className="shadow-soft">
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-3">
|
<CardHeader className="pb-3">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-gold-100/60">
|
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-gold-100/60">
|
||||||
<BookOpen className="h-4 w-4 text-gold-600" />
|
<BookOpen className="h-4 w-4 text-gold-600" />
|
||||||
</div>
|
</div>
|
||||||
<CardTitle>Recent Activity</CardTitle>
|
<CardTitle className="text-base">Recent activity</CardTitle>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
|
|
@ -624,6 +471,8 @@ export function UserDetailPage() {
|
||||||
<SpinnerIcon className="h-5 w-5" />
|
<SpinnerIcon className="h-5 w-5" />
|
||||||
Loading activity…
|
Loading activity…
|
||||||
</div>
|
</div>
|
||||||
|
) : recentActivityError ? (
|
||||||
|
<p className="py-8 text-center text-sm text-destructive">{recentActivityError}</p>
|
||||||
) : recentActivityItems.length === 0 ? (
|
) : recentActivityItems.length === 0 ? (
|
||||||
<p className="py-8 text-center text-sm text-grayScale-400">No recent activity yet.</p>
|
<p className="py-8 text-center text-sm text-grayScale-400">No recent activity yet.</p>
|
||||||
) : (
|
) : (
|
||||||
|
|
@ -634,9 +483,9 @@ export function UserDetailPage() {
|
||||||
const isLast = index === recentActivityItems.length - 1;
|
const isLast = index === recentActivityItems.length - 1;
|
||||||
return (
|
return (
|
||||||
<div key={item.id} className="relative flex gap-4 pb-5 last:pb-0">
|
<div key={item.id} className="relative flex gap-4 pb-5 last:pb-0">
|
||||||
{!isLast && (
|
{!isLast ? (
|
||||||
<div className="absolute bottom-0 left-[15px] top-8 w-px bg-grayScale-200" />
|
<div className="absolute bottom-0 left-[15px] top-8 w-px bg-grayScale-200" />
|
||||||
)}
|
) : null}
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative z-10 flex h-8 w-8 shrink-0 items-center justify-center rounded-full",
|
"relative z-10 flex h-8 w-8 shrink-0 items-center justify-center rounded-full",
|
||||||
|
|
@ -652,10 +501,10 @@ export function UserDetailPage() {
|
||||||
<Icon className="h-4 w-4" />
|
<Icon className="h-4 w-4" />
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 flex-1 pt-1">
|
<div className="min-w-0 flex-1 pt-1">
|
||||||
<div className="text-sm font-medium text-grayScale-600">{item.headline}</div>
|
<p className="text-sm font-medium text-grayScale-700">{item.headline}</p>
|
||||||
<div className="mt-0.5 text-xs text-grayScale-400">
|
<p className="mt-0.5 text-xs text-grayScale-400">
|
||||||
{formatActivityOccurredAt(item.occurred_at)}
|
{formatActivityOccurredAt(item.occurred_at)}
|
||||||
</div>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
@ -673,32 +522,17 @@ export function UserDetailPage() {
|
||||||
function InfoItem({ label, value }: { label: string; value: string }) {
|
function InfoItem({ label, value }: { label: string; value: string }) {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400 mb-1">
|
<p className="mb-1 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">{label}</p>
|
||||||
{label}
|
<p className="text-sm text-grayScale-700">{value}</p>
|
||||||
</div>
|
|
||||||
<div className="text-sm text-grayScale-600">{value}</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Metric({ label, value }: { label: string; value: string | number }) {
|
function InfoRow({ label, value }: { label: string; value: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border border-grayScale-200 bg-grayScale-50 px-3 py-2">
|
<div className="flex items-center justify-between gap-3">
|
||||||
<div className="text-[10px] font-semibold uppercase tracking-wide text-grayScale-400">{label}</div>
|
<span className="text-sm text-grayScale-500">{label}</span>
|
||||||
<div className="mt-1 text-sm font-semibold text-grayScale-700">{value}</div>
|
<span className="text-sm font-medium text-grayScale-700">{value}</span>
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TagItem({ label, value }: { label: string; value: string }) {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400 mb-1">
|
|
||||||
{label}
|
|
||||||
</div>
|
|
||||||
<span className="inline-block rounded-lg border border-grayScale-200 bg-grayScale-100 px-2.5 py-1 text-xs font-medium text-grayScale-600">
|
|
||||||
{value}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,15 @@ import { ChevronDown, ChevronLeft, ChevronRight, Search, TrendingUp, UserCheck,
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import { useNavigate } from "react-router-dom"
|
import { useNavigate } from "react-router-dom"
|
||||||
import * as DropdownMenu from "@radix-ui/react-dropdown-menu"
|
import * as DropdownMenu from "@radix-ui/react-dropdown-menu"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar"
|
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Card, CardContent } from "../../components/ui/card"
|
import { Card, CardContent } from "../../components/ui/card"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { ToggleSwitch } from "../../components/ui/toggle-switch"
|
||||||
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import { getDashboard } from "../../api/analytics.api"
|
import { getDashboard } from "../../api/analytics.api"
|
||||||
|
|
@ -310,7 +313,19 @@ export function UsersListPage() {
|
||||||
navigate(`/users/${userId}`)
|
navigate(`/users/${userId}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const clearExtraFilters = () => {
|
const activeFilterCount = countActiveFilters([
|
||||||
|
{ value: roleFilter },
|
||||||
|
{ value: statusFilter },
|
||||||
|
{ value: createdAfterLocal },
|
||||||
|
{ value: createdBeforeLocal },
|
||||||
|
{ value: countryFilter },
|
||||||
|
{ value: regionFilter },
|
||||||
|
{ value: subscriptionStatusFilter },
|
||||||
|
])
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
setRoleFilter("")
|
||||||
|
setStatusFilter("")
|
||||||
setCreatedAfterLocal("")
|
setCreatedAfterLocal("")
|
||||||
setCreatedBeforeLocal("")
|
setCreatedBeforeLocal("")
|
||||||
setCountryFilter("")
|
setCountryFilter("")
|
||||||
|
|
@ -405,10 +420,13 @@ export function UsersListPage() {
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white rounded-xl border">
|
<div className="bg-white rounded-xl border">
|
||||||
{/* Search & Filters */}
|
<AdminFiltersPanel
|
||||||
<div className="p-4 border-b">
|
className="border-0 border-b rounded-none shadow-none"
|
||||||
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
|
activeFilterCount={activeFilterCount}
|
||||||
<div className="relative w-full md:max-w-sm">
|
onClearFilters={clearFilters}
|
||||||
|
footer="Dates are sent as RFC3339 (UTC). Country and region filters use the lists above; the API matches case-insensitively."
|
||||||
|
search={
|
||||||
|
<div className="relative w-full">
|
||||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
placeholder="Search by name, phone number"
|
placeholder="Search by name, phone number"
|
||||||
|
|
@ -417,8 +435,9 @@ export function UsersListPage() {
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
<div className="flex flex-wrap items-center gap-3">
|
>
|
||||||
|
<div className="flex flex-wrap gap-3">
|
||||||
<div className="relative w-full sm:w-auto">
|
<div className="relative w-full sm:w-auto">
|
||||||
<select
|
<select
|
||||||
value={roleFilter}
|
value={roleFilter}
|
||||||
|
|
@ -435,7 +454,6 @@ export function UsersListPage() {
|
||||||
</select>
|
</select>
|
||||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="relative w-full sm:w-auto">
|
<div className="relative w-full sm:w-auto">
|
||||||
<select
|
<select
|
||||||
value={statusFilter}
|
value={statusFilter}
|
||||||
|
|
@ -454,9 +472,7 @@ export function UsersListPage() {
|
||||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
|
||||||
|
|
||||||
<div className="mt-4 grid gap-3 border-t border-grayScale-100 pt-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
|
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<label htmlFor="filter-created-after" className="text-xs font-medium text-grayScale-500">
|
<label htmlFor="filter-created-after" className="text-xs font-medium text-grayScale-500">
|
||||||
Created on or after
|
Created on or after
|
||||||
|
|
@ -532,20 +548,7 @@ export function UsersListPage() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-2">
|
</AdminFiltersPanel>
|
||||||
<p className="text-xs text-grayScale-400">
|
|
||||||
Dates are sent as RFC3339 (UTC). Country and region filters use the lists above; the API matches
|
|
||||||
case-insensitively.
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={clearExtraFilters}
|
|
||||||
className="shrink-0 text-sm font-medium text-brand-600 hover:text-brand-700"
|
|
||||||
>
|
|
||||||
Clear date, location & subscription filters
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Table */}
|
{/* Table */}
|
||||||
<Table>
|
<Table>
|
||||||
|
|
@ -642,26 +645,11 @@ export function UsersListPage() {
|
||||||
</span>
|
</span>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||||
<button
|
<ToggleSwitch
|
||||||
type="button"
|
checked={isActive}
|
||||||
onClick={() => handleToggle(u.id)}
|
|
||||||
disabled={isUpdatingStatus}
|
disabled={isUpdatingStatus}
|
||||||
className={cn(
|
onCheckedChange={() => handleToggle(u.id)}
|
||||||
"relative inline-flex h-7 w-12 shrink-0 cursor-pointer items-center rounded-full border p-0.5 transition-all duration-200",
|
|
||||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-1",
|
|
||||||
isActive
|
|
||||||
? "border-brand-500 bg-brand-500 shadow-[0_6px_16px_rgba(168,85,247,0.35)]"
|
|
||||||
: "border-grayScale-300 bg-grayScale-200 hover:bg-grayScale-300/80",
|
|
||||||
isUpdatingStatus && "cursor-not-allowed opacity-60",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-md ring-0 transition-transform duration-200 ease-out",
|
|
||||||
isActive ? "translate-x-5" : "translate-x-0"
|
|
||||||
)}
|
|
||||||
/>
|
/>
|
||||||
</button>
|
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,401 @@
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { BarChart3, CheckCircle2, ChevronDown, ChevronRight, Lock } from "lucide-react";
|
||||||
|
import { Badge } from "../../../components/ui/badge";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
|
||||||
|
import { Select } from "../../../components/ui/select";
|
||||||
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon";
|
||||||
|
import { cn } from "../../../lib/utils";
|
||||||
|
import type {
|
||||||
|
LearningActivityAccess,
|
||||||
|
LearningActivityCourse,
|
||||||
|
LearningActivityLesson,
|
||||||
|
LearningActivityModule,
|
||||||
|
LearningActivityProgram,
|
||||||
|
LearningActivityUnit,
|
||||||
|
UserLearningActivityData,
|
||||||
|
} from "../../../types/userAdmin.types";
|
||||||
|
|
||||||
|
type Track = "lms" | "exam_prep";
|
||||||
|
|
||||||
|
function ProgressBar({ access }: { access: LearningActivityAccess }) {
|
||||||
|
const percent = Math.min(100, Math.max(0, access.progress_percent));
|
||||||
|
return (
|
||||||
|
<div className="flex min-w-[120px] items-center gap-2">
|
||||||
|
<div className="h-1.5 flex-1 rounded-full bg-grayScale-200">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"h-1.5 rounded-full transition-all",
|
||||||
|
access.is_completed ? "bg-mint-500" : access.is_accessible ? "bg-brand-500" : "bg-grayScale-300",
|
||||||
|
)}
|
||||||
|
style={{ width: `${percent}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className="w-8 text-right text-[11px] text-grayScale-500">{percent}%</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccessStatusBadge({ access }: { access: LearningActivityAccess }) {
|
||||||
|
if (access.is_completed) {
|
||||||
|
return (
|
||||||
|
<Badge className="bg-mint-500/15 text-mint-600 border border-mint-500/25">
|
||||||
|
<CheckCircle2 className="mr-1 h-3 w-3" />
|
||||||
|
Completed
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!access.is_accessible) {
|
||||||
|
return (
|
||||||
|
<Badge variant="secondary">
|
||||||
|
<Lock className="mr-1 h-3 w-3" />
|
||||||
|
Locked
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return <Badge variant="warning">Accessible</Badge>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccessMeta({ access }: { access: LearningActivityAccess }) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<AccessStatusBadge access={access} />
|
||||||
|
<span className="text-xs text-grayScale-500">
|
||||||
|
{access.completed_count}/{access.total_count} completed
|
||||||
|
</span>
|
||||||
|
<ProgressBar access={access} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LessonRow({ lesson }: { lesson: LearningActivityLesson }) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-grayScale-100 bg-white px-3 py-2.5">
|
||||||
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<p className="text-sm text-grayScale-700">{lesson.title || `Lesson #${lesson.id}`}</p>
|
||||||
|
<AccessMeta access={lesson.access} />
|
||||||
|
</div>
|
||||||
|
{!lesson.access.is_accessible && lesson.access.reason ? (
|
||||||
|
<p className="mt-1.5 text-xs text-grayScale-400">{lesson.access.reason}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ModuleBlock({ module }: { module: LearningActivityModule }) {
|
||||||
|
const [open, setOpen] = useState(module.access.is_accessible || module.access.is_completed);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-grayScale-100 bg-grayScale-50/60">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex w-full items-start justify-between gap-3 px-3 py-3 text-left"
|
||||||
|
onClick={() => setOpen((prev) => !prev)}
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm font-medium text-grayScale-800">{module.name || `Module #${module.id}`}</p>
|
||||||
|
<div className="mt-2">
|
||||||
|
<AccessMeta access={module.access} />
|
||||||
|
</div>
|
||||||
|
{!module.access.is_accessible && module.access.reason ? (
|
||||||
|
<p className="mt-1.5 text-xs text-grayScale-400">{module.access.reason}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{open ? (
|
||||||
|
<ChevronDown className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||||
|
) : (
|
||||||
|
<ChevronRight className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
{open ? (
|
||||||
|
<div className="space-y-2 border-t border-grayScale-100 px-3 py-3">
|
||||||
|
{module.lessons.length === 0 ? (
|
||||||
|
<p className="text-xs text-grayScale-400">No lessons in this module.</p>
|
||||||
|
) : (
|
||||||
|
module.lessons.map((lesson) => <LessonRow key={lesson.id} lesson={lesson} />)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function UnitBlock({ unit }: { unit: LearningActivityUnit }) {
|
||||||
|
const [open, setOpen] = useState(unit.access.is_accessible || unit.access.is_completed);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-grayScale-100">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex w-full items-start justify-between gap-3 px-3 py-3 text-left"
|
||||||
|
onClick={() => setOpen((prev) => !prev)}
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm font-medium text-grayScale-800">{unit.name || `Unit #${unit.id}`}</p>
|
||||||
|
<div className="mt-2">
|
||||||
|
<AccessMeta access={unit.access} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{open ? (
|
||||||
|
<ChevronDown className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||||
|
) : (
|
||||||
|
<ChevronRight className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
{open ? (
|
||||||
|
<div className="space-y-3 border-t border-grayScale-100 px-3 py-3">
|
||||||
|
{unit.modules.length === 0 ? (
|
||||||
|
<p className="text-xs text-grayScale-400">No modules in this unit.</p>
|
||||||
|
) : (
|
||||||
|
unit.modules.map((module) => <ModuleBlock key={module.id} module={module} />)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CourseBlock({ course, examPrep }: { course: LearningActivityCourse; examPrep?: boolean }) {
|
||||||
|
const [open, setOpen] = useState(course.access.is_accessible || course.access.is_completed);
|
||||||
|
const children = examPrep ? (course.units ?? []) : (course.modules ?? []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-grayScale-200 bg-white">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex w-full items-start justify-between gap-3 px-4 py-3 text-left"
|
||||||
|
onClick={() => setOpen((prev) => !prev)}
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm font-semibold text-grayScale-800">{course.name || `Course #${course.id}`}</p>
|
||||||
|
<div className="mt-2">
|
||||||
|
<AccessMeta access={course.access} />
|
||||||
|
</div>
|
||||||
|
{!course.access.is_accessible && course.access.reason ? (
|
||||||
|
<p className="mt-1.5 text-xs text-grayScale-400">{course.access.reason}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{open ? (
|
||||||
|
<ChevronDown className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||||
|
) : (
|
||||||
|
<ChevronRight className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
{open ? (
|
||||||
|
<div className="space-y-3 border-t border-grayScale-100 px-4 py-3">
|
||||||
|
{children.length === 0 ? (
|
||||||
|
<p className="text-xs text-grayScale-400">No content available.</p>
|
||||||
|
) : examPrep ? (
|
||||||
|
(course.units ?? []).map((unit) => <UnitBlock key={unit.id} unit={unit} />)
|
||||||
|
) : (
|
||||||
|
(course.modules ?? []).map((module) => <ModuleBlock key={module.id} module={module} />)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Metric({ label, value }: { label: string; value: string | number }) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-grayScale-200 bg-grayScale-50 px-3 py-2">
|
||||||
|
<p className="text-[10px] font-semibold uppercase tracking-wide text-grayScale-400">{label}</p>
|
||||||
|
<p className="mt-1 text-sm font-semibold text-grayScale-700">{value}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UserLearningActivitySection({
|
||||||
|
activity,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
}: {
|
||||||
|
activity: UserLearningActivityData | null;
|
||||||
|
loading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
}) {
|
||||||
|
const [track, setTrack] = useState<Track>("lms");
|
||||||
|
const programs = activity?.lms.progress.programs ?? [];
|
||||||
|
const catalogCourses = activity?.exam_prep.progress.catalog_courses ?? [];
|
||||||
|
|
||||||
|
const [selectedProgramId, setSelectedProgramId] = useState<number | null>(null);
|
||||||
|
const [selectedCatalogCourseId, setSelectedCatalogCourseId] = useState<number | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (programs.length === 0) {
|
||||||
|
setSelectedProgramId(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!selectedProgramId || !programs.some((program) => program.id === selectedProgramId)) {
|
||||||
|
setSelectedProgramId(programs[0].id);
|
||||||
|
}
|
||||||
|
}, [programs, selectedProgramId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (catalogCourses.length === 0) {
|
||||||
|
setSelectedCatalogCourseId(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!selectedCatalogCourseId ||
|
||||||
|
!catalogCourses.some((course) => course.id === selectedCatalogCourseId)
|
||||||
|
) {
|
||||||
|
setSelectedCatalogCourseId(catalogCourses[0].id);
|
||||||
|
}
|
||||||
|
}, [catalogCourses, selectedCatalogCourseId]);
|
||||||
|
|
||||||
|
const selectedProgram = useMemo(
|
||||||
|
() => programs.find((program) => program.id === selectedProgramId) ?? null,
|
||||||
|
[programs, selectedProgramId],
|
||||||
|
);
|
||||||
|
|
||||||
|
const selectedCatalogCourse = useMemo(
|
||||||
|
() => catalogCourses.find((course) => course.id === selectedCatalogCourseId) ?? null,
|
||||||
|
[catalogCourses, selectedCatalogCourseId],
|
||||||
|
);
|
||||||
|
|
||||||
|
const completedIds = activity?.lms.completed_ids;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="shadow-soft">
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-sky-100/70">
|
||||||
|
<BarChart3 className="h-4 w-4 text-sky-600" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-base">Learning activity</CardTitle>
|
||||||
|
</div>
|
||||||
|
<div className="flex rounded-lg border border-grayScale-200 p-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
"rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
|
||||||
|
track === "lms" ? "bg-brand-500 text-white" : "text-grayScale-500 hover:text-grayScale-700",
|
||||||
|
)}
|
||||||
|
onClick={() => setTrack("lms")}
|
||||||
|
>
|
||||||
|
Learn English
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
"rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
|
||||||
|
track === "exam_prep"
|
||||||
|
? "bg-brand-500 text-white"
|
||||||
|
: "text-grayScale-500 hover:text-grayScale-700",
|
||||||
|
)}
|
||||||
|
onClick={() => setTrack("exam_prep")}
|
||||||
|
>
|
||||||
|
Exam prep
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center gap-2 rounded-lg border border-grayScale-200 bg-grayScale-100 px-3 py-2 text-xs text-grayScale-500">
|
||||||
|
<SpinnerIcon className="h-3.5 w-3.5" />
|
||||||
|
Loading learning activity...
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{error ? (
|
||||||
|
<div className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{!loading && !error && activity && track === "lms" ? (
|
||||||
|
<>
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<Metric label="Programs" value={programs.length} />
|
||||||
|
<Metric label="Completed programs" value={completedIds?.program_ids.length ?? 0} />
|
||||||
|
<Metric label="Completed courses" value={completedIds?.course_ids.length ?? 0} />
|
||||||
|
<Metric label="Completed lessons" value={completedIds?.lesson_ids.length ?? 0} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full sm:max-w-sm">
|
||||||
|
<Select
|
||||||
|
value={selectedProgramId ? String(selectedProgramId) : ""}
|
||||||
|
onChange={(e) => setSelectedProgramId(e.target.value ? Number(e.target.value) : null)}
|
||||||
|
disabled={programs.length === 0}
|
||||||
|
>
|
||||||
|
<option value="">{programs.length === 0 ? "No programs available" : "Select program..."}</option>
|
||||||
|
{programs.map((program: LearningActivityProgram) => (
|
||||||
|
<option key={program.id} value={program.id}>
|
||||||
|
{program.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedProgram ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="rounded-xl border border-brand-100 bg-brand-50/40 px-4 py-3">
|
||||||
|
<p className="text-sm font-semibold text-grayScale-800">{selectedProgram.name}</p>
|
||||||
|
<div className="mt-2">
|
||||||
|
<AccessMeta access={selectedProgram.access} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{selectedProgram.courses.length === 0 ? (
|
||||||
|
<p className="py-6 text-center text-sm text-grayScale-400">No courses in this program.</p>
|
||||||
|
) : (
|
||||||
|
selectedProgram.courses.map((course) => (
|
||||||
|
<CourseBlock key={course.id} course={course} />
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="py-6 text-center text-sm text-grayScale-400">No LMS learning activity yet.</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{!loading && !error && activity && track === "exam_prep" ? (
|
||||||
|
<>
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<Metric label="Exam prep courses" value={catalogCourses.length} />
|
||||||
|
<Metric
|
||||||
|
label="Accessible courses"
|
||||||
|
value={catalogCourses.filter((course) => course.access.is_accessible).length}
|
||||||
|
/>
|
||||||
|
<Metric
|
||||||
|
label="Completed courses"
|
||||||
|
value={catalogCourses.filter((course) => course.access.is_completed).length}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full sm:max-w-sm">
|
||||||
|
<Select
|
||||||
|
value={selectedCatalogCourseId ? String(selectedCatalogCourseId) : ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSelectedCatalogCourseId(e.target.value ? Number(e.target.value) : null)
|
||||||
|
}
|
||||||
|
disabled={catalogCourses.length === 0}
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
{catalogCourses.length === 0 ? "No exam prep courses" : "Select exam prep course..."}
|
||||||
|
</option>
|
||||||
|
{catalogCourses.map((course) => (
|
||||||
|
<option key={course.id} value={course.id}>
|
||||||
|
{course.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedCatalogCourse ? (
|
||||||
|
<CourseBlock course={selectedCatalogCourse} examPrep />
|
||||||
|
) : (
|
||||||
|
<p className="py-6 text-center text-sm text-grayScale-400">No exam prep activity yet.</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{!loading && !error && !activity ? (
|
||||||
|
<p className="py-6 text-center text-sm text-grayScale-400">No learning activity available.</p>
|
||||||
|
) : null}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,255 @@
|
||||||
|
import { CreditCard, RefreshCw } from "lucide-react";
|
||||||
|
import { Badge } from "../../../components/ui/badge";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
|
||||||
|
import { Separator } from "../../../components/ui/separator";
|
||||||
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "../../../components/ui/table";
|
||||||
|
import { cn } from "../../../lib/utils";
|
||||||
|
import type { UserSubscriptionsData } from "../../../types/userAdmin.types";
|
||||||
|
|
||||||
|
function formatStatusLabel(status: string): string {
|
||||||
|
const value = status.trim();
|
||||||
|
if (!value) return "—";
|
||||||
|
return value
|
||||||
|
.split("_")
|
||||||
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||||
|
.join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCategoryLabel(value: string): string {
|
||||||
|
return value
|
||||||
|
.split("_")
|
||||||
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||||
|
.join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateTime(value?: string | null): string {
|
||||||
|
if (!value?.trim()) return "—";
|
||||||
|
const parsed = new Date(value);
|
||||||
|
if (Number.isNaN(parsed.getTime())) return "—";
|
||||||
|
return parsed.toLocaleString(undefined, {
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
year: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSubscriptionStatusClasses(status: string): string {
|
||||||
|
const normalized = status.trim().toUpperCase();
|
||||||
|
if (normalized === "ACTIVE" || normalized === "SUCCESS") {
|
||||||
|
return "bg-mint-500/15 text-mint-500 border border-mint-500/25";
|
||||||
|
}
|
||||||
|
if (normalized === "PENDING") {
|
||||||
|
return "bg-gold-100 text-gold-600 border border-gold-300/40";
|
||||||
|
}
|
||||||
|
if (normalized === "FAILED" || normalized === "EXPIRED") {
|
||||||
|
return "bg-destructive/15 text-destructive border border-destructive/25";
|
||||||
|
}
|
||||||
|
return "bg-grayScale-100 text-grayScale-600 border border-grayScale-200";
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDuration(value: number, unit: string): string {
|
||||||
|
if (!value) return "—";
|
||||||
|
const label = unit.trim().toLowerCase();
|
||||||
|
const plural = value === 1 ? label.replace(/s$/, "") : label.endsWith("s") ? label : `${label}s`;
|
||||||
|
return `${value} ${plural}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMoney(amount: number, currency: string): string {
|
||||||
|
if (!Number.isFinite(amount)) return "—";
|
||||||
|
const code = currency.trim() || "ETB";
|
||||||
|
return `${amount.toLocaleString()} ${code}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UserSubscriptionsSection({
|
||||||
|
subscriptions,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
}: {
|
||||||
|
subscriptions: UserSubscriptionsData | null;
|
||||||
|
loading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
}) {
|
||||||
|
const recentPayments = subscriptions?.payments.slice(0, 8) ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="shadow-soft">
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-100/50">
|
||||||
|
<CreditCard className="h-4 w-4 text-brand-600" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-base">Subscriptions</CardTitle>
|
||||||
|
</div>
|
||||||
|
{subscriptions ? (
|
||||||
|
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
|
||||||
|
{formatStatusLabel(subscriptions.display_status)}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-grayScale-400">
|
||||||
|
<SpinnerIcon className="h-4 w-4" />
|
||||||
|
Loading subscriptions...
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
||||||
|
|
||||||
|
{!loading && !error && subscriptions ? (
|
||||||
|
<>
|
||||||
|
<div className="flex items-center justify-between gap-3 text-sm">
|
||||||
|
<span className="text-grayScale-500">Active subscription</span>
|
||||||
|
<span className="font-medium text-grayScale-700">
|
||||||
|
{subscriptions.has_active_subscription ? "Yes" : "No"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{Object.keys(subscriptions.active_by_category).length > 0 ? (
|
||||||
|
<>
|
||||||
|
<Separator />
|
||||||
|
<div>
|
||||||
|
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||||
|
Access by category
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{Object.entries(subscriptions.active_by_category).map(([category, active]) => (
|
||||||
|
<Badge
|
||||||
|
key={category}
|
||||||
|
variant={active ? "default" : "outline"}
|
||||||
|
className={cn(!active && "text-grayScale-500")}
|
||||||
|
>
|
||||||
|
{formatCategoryLabel(category)}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||||
|
Active plans
|
||||||
|
</p>
|
||||||
|
{subscriptions.active_subscriptions.length === 0 ? (
|
||||||
|
<p className="text-sm text-grayScale-400">No active subscriptions.</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{subscriptions.active_subscriptions.map((subscription) => (
|
||||||
|
<div
|
||||||
|
key={subscription.id}
|
||||||
|
className="rounded-xl border border-grayScale-100 bg-grayScale-50/60 p-3"
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-grayScale-800">{subscription.plan_name}</p>
|
||||||
|
<p className="text-xs text-grayScale-500">
|
||||||
|
{formatCategoryLabel(subscription.plan_category)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Badge className={cn(getSubscriptionStatusClasses(subscription.status))}>
|
||||||
|
{formatStatusLabel(subscription.status)}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 grid gap-2 text-xs text-grayScale-600 sm:grid-cols-2">
|
||||||
|
<p>
|
||||||
|
<span className="text-grayScale-400">Price: </span>
|
||||||
|
{formatMoney(subscription.price, subscription.currency)}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<span className="text-grayScale-400">Duration: </span>
|
||||||
|
{formatDuration(subscription.duration_value, subscription.duration_unit)}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<span className="text-grayScale-400">Starts: </span>
|
||||||
|
{formatDateTime(subscription.starts_at)}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<span className="text-grayScale-400">Expires: </span>
|
||||||
|
{formatDateTime(subscription.expires_at)}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<span className="text-grayScale-400">Payment: </span>
|
||||||
|
{subscription.payment_method || "—"}
|
||||||
|
</p>
|
||||||
|
<p className="inline-flex items-center gap-1">
|
||||||
|
<RefreshCw className="h-3 w-3 text-grayScale-400" />
|
||||||
|
Auto-renew: {subscription.auto_renew ? "On" : "Off"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{recentPayments.length > 0 ? (
|
||||||
|
<>
|
||||||
|
<Separator />
|
||||||
|
<div>
|
||||||
|
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||||
|
Recent payments
|
||||||
|
</p>
|
||||||
|
<div className="overflow-x-auto rounded-xl border">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Plan</TableHead>
|
||||||
|
<TableHead>Amount</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead>Method</TableHead>
|
||||||
|
<TableHead>Date</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{recentPayments.map((payment) => (
|
||||||
|
<TableRow key={payment.id}>
|
||||||
|
<TableCell className="text-sm text-grayScale-700">
|
||||||
|
{payment.plan_name || "—"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-grayScale-700">
|
||||||
|
{formatMoney(payment.amount, payment.currency)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge className={cn(getSubscriptionStatusClasses(payment.status))}>
|
||||||
|
{formatStatusLabel(payment.status)}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-xs text-grayScale-500">
|
||||||
|
{payment.payment_method || "—"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-xs text-grayScale-500">
|
||||||
|
{formatDateTime(payment.paid_at || payment.created_at)}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{!loading && !error && !subscriptions ? (
|
||||||
|
<p className="text-sm text-grayScale-400">No subscription data available.</p>
|
||||||
|
) : null}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -1814,6 +1814,14 @@ export interface VimeoSampleVideo {
|
||||||
transcode_status: string
|
transcode_status: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface GetVimeoVideoResponse {
|
||||||
|
message: string
|
||||||
|
data: VimeoSampleVideo
|
||||||
|
success: boolean
|
||||||
|
status_code: number
|
||||||
|
metadata: unknown
|
||||||
|
}
|
||||||
|
|
||||||
export interface GetVimeoSampleResponse {
|
export interface GetVimeoSampleResponse {
|
||||||
message: string
|
message: string
|
||||||
data: {
|
data: {
|
||||||
|
|
|
||||||
80
src/types/faq.types.ts
Normal file
80
src/types/faq.types.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
export type FAQStatus = "ACTIVE" | "INACTIVE"
|
||||||
|
|
||||||
|
export interface FAQ {
|
||||||
|
id: number
|
||||||
|
question: string
|
||||||
|
answer: string
|
||||||
|
category?: string | null
|
||||||
|
display_order: number
|
||||||
|
status: FAQStatus
|
||||||
|
created_at: string
|
||||||
|
updated_at?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FAQListData {
|
||||||
|
faqs: FAQ[]
|
||||||
|
total_count: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetFAQsResponse {
|
||||||
|
message: string
|
||||||
|
data: FAQListData
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
metadata?: unknown | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetFAQResponse {
|
||||||
|
message: string
|
||||||
|
data: FAQ
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
metadata?: unknown | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateFAQRequest {
|
||||||
|
question: string
|
||||||
|
answer: string
|
||||||
|
category?: string | null
|
||||||
|
display_order?: number
|
||||||
|
status?: FAQStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateFAQRequest {
|
||||||
|
question?: string
|
||||||
|
answer?: string
|
||||||
|
category?: string | null
|
||||||
|
display_order?: number
|
||||||
|
status?: FAQStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateFAQResponse {
|
||||||
|
message: string
|
||||||
|
data: FAQ
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
metadata?: unknown | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateFAQResponse {
|
||||||
|
message: string
|
||||||
|
data: FAQ
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
metadata?: unknown | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeleteFAQResponse {
|
||||||
|
message: string
|
||||||
|
data?: { id: number }
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
metadata?: unknown | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FAQFilters {
|
||||||
|
status?: FAQStatus
|
||||||
|
category?: string
|
||||||
|
limit?: number
|
||||||
|
offset?: number
|
||||||
|
}
|
||||||
|
|
@ -1,26 +1,73 @@
|
||||||
export interface PersonaListItem {
|
export interface LmsPersona {
|
||||||
id: number
|
id: number
|
||||||
name: string
|
name: string
|
||||||
description: string
|
description: string | null
|
||||||
profile_picture: string | null
|
profile_picture: string | null
|
||||||
|
gender: string | null
|
||||||
is_active: boolean
|
is_active: boolean
|
||||||
created_at: string
|
created_at: string
|
||||||
|
updated_at: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GetPersonasParams {
|
/** @deprecated Use LmsPersona — kept for practice picker compatibility */
|
||||||
limit?: number
|
export type PersonaListItem = LmsPersona
|
||||||
offset?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GetPersonasResponse {
|
export interface PersonaListData {
|
||||||
message: string
|
personas: LmsPersona[]
|
||||||
data: {
|
|
||||||
personas: PersonaListItem[]
|
|
||||||
total_count: number
|
total_count: number
|
||||||
limit: number
|
limit: number
|
||||||
offset: number
|
offset: number
|
||||||
}
|
}
|
||||||
success: boolean
|
|
||||||
status_code: number
|
export interface ListPersonasParams {
|
||||||
metadata: unknown | null
|
active_only?: boolean
|
||||||
|
limit?: number
|
||||||
|
offset?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CreatePersonaInput {
|
||||||
|
name: string
|
||||||
|
description?: string | null
|
||||||
|
profile_picture?: string | null
|
||||||
|
gender?: string | null
|
||||||
|
is_active?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdatePersonaInput {
|
||||||
|
name?: string
|
||||||
|
description?: string | null
|
||||||
|
profile_picture?: string | null
|
||||||
|
gender?: string | null
|
||||||
|
is_active?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetPersonasResponse {
|
||||||
|
message: string
|
||||||
|
data: PersonaListData
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
metadata?: unknown | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetPersonaResponse {
|
||||||
|
message: string
|
||||||
|
data: LmsPersona
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MutatePersonaResponse {
|
||||||
|
message: string
|
||||||
|
data: LmsPersona
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeletePersonaResponse {
|
||||||
|
message: string
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @deprecated Use ListPersonasParams */
|
||||||
|
export type GetPersonasParams = ListPersonasParams
|
||||||
|
|
|
||||||
48
src/types/ratings.types.ts
Normal file
48
src/types/ratings.types.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
export type RatingTargetType = "app" | "course" | "sub_course"
|
||||||
|
|
||||||
|
export interface Rating {
|
||||||
|
id: number
|
||||||
|
user_id: number
|
||||||
|
target_type: RatingTargetType
|
||||||
|
target_id: number
|
||||||
|
stars: number
|
||||||
|
review: string | null
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RatingSummary {
|
||||||
|
total_count: number
|
||||||
|
average_stars: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ListRatingsParams {
|
||||||
|
target_type: RatingTargetType
|
||||||
|
target_id?: number
|
||||||
|
limit?: number
|
||||||
|
offset?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RatingSummaryParams {
|
||||||
|
target_type: RatingTargetType
|
||||||
|
target_id?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetRatingsResponse {
|
||||||
|
message: string
|
||||||
|
data: Rating[]
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetRatingSummaryResponse {
|
||||||
|
message: string
|
||||||
|
data: RatingSummary
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AppReviewsPageData {
|
||||||
|
summary: RatingSummary
|
||||||
|
reviews: Rating[]
|
||||||
|
}
|
||||||
|
|
@ -7,16 +7,74 @@ export interface TeamMember {
|
||||||
team_role: string
|
team_role: string
|
||||||
department: string
|
department: string
|
||||||
job_title: string
|
job_title: string
|
||||||
employment_type: string
|
employment_type?: string
|
||||||
hire_date: string
|
hire_date?: string
|
||||||
bio: string
|
bio?: string
|
||||||
status: string
|
status: string
|
||||||
email_verified: boolean
|
email_verified: boolean
|
||||||
permissions: string[]
|
permissions?: string[]
|
||||||
last_login?: string | null
|
last_login?: string | null
|
||||||
created_at: string
|
created_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** GET /team/members/:id — single team member detail */
|
||||||
|
export interface TeamMemberDetail {
|
||||||
|
id: number
|
||||||
|
first_name: string
|
||||||
|
last_name: string
|
||||||
|
email: string
|
||||||
|
phone_number: string
|
||||||
|
team_role: string
|
||||||
|
department: string
|
||||||
|
job_title: string
|
||||||
|
bio: string | null
|
||||||
|
status: string
|
||||||
|
email_verified: boolean
|
||||||
|
last_login: string | null
|
||||||
|
created_at: string
|
||||||
|
updated_at: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /team/me — signed-in team member profile */
|
||||||
|
export interface TeamMeProfile {
|
||||||
|
id: number
|
||||||
|
first_name: string
|
||||||
|
last_name: string
|
||||||
|
email: string
|
||||||
|
phone_number: string
|
||||||
|
team_role: string
|
||||||
|
department: string
|
||||||
|
job_title: string
|
||||||
|
status: string
|
||||||
|
email_verified: boolean
|
||||||
|
last_login: string | null
|
||||||
|
created_at: string
|
||||||
|
updated_at: string | null
|
||||||
|
profile_picture_url?: string | null
|
||||||
|
bio?: string | null
|
||||||
|
work_phone?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetTeamMeResponse {
|
||||||
|
message: string
|
||||||
|
data: TeamMeProfile
|
||||||
|
success: boolean
|
||||||
|
status_code: number
|
||||||
|
metadata: unknown | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PUT /team/me — update signed-in team member profile */
|
||||||
|
export interface UpdateTeamMeRequest {
|
||||||
|
first_name?: string
|
||||||
|
last_name?: string
|
||||||
|
phone_number?: string
|
||||||
|
department?: string
|
||||||
|
job_title?: string
|
||||||
|
profile_picture_url?: string
|
||||||
|
bio?: string
|
||||||
|
work_phone?: string
|
||||||
|
}
|
||||||
|
|
||||||
export interface CreateTeamMemberRequest {
|
export interface CreateTeamMemberRequest {
|
||||||
first_name: string
|
first_name: string
|
||||||
last_name: string
|
last_name: string
|
||||||
|
|
@ -63,7 +121,7 @@ export interface GetTeamMembersResponse {
|
||||||
|
|
||||||
export interface GetTeamMemberResponse {
|
export interface GetTeamMemberResponse {
|
||||||
message: string
|
message: string
|
||||||
data: TeamMember
|
data: TeamMemberDetail
|
||||||
success: boolean
|
success: boolean
|
||||||
status_code: number
|
status_code: number
|
||||||
metadata: null
|
metadata: null
|
||||||
|
|
|
||||||
|
|
@ -81,41 +81,35 @@ export const mapUserApiToUser = (u: UserApiDTO): User => ({
|
||||||
createdAt: u.created_at ?? "",
|
createdAt: u.created_at ?? "",
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** GET /user/single/:id — single learner profile */
|
||||||
export interface UserProfileData {
|
export interface UserProfileData {
|
||||||
id: number
|
id: number
|
||||||
first_name: string
|
first_name: string
|
||||||
last_name: string
|
last_name: string
|
||||||
gender: string
|
gender: string
|
||||||
birth_day: string | null
|
birth_day: string | null
|
||||||
|
|
||||||
email: string
|
email: string
|
||||||
phone_number: string
|
|
||||||
role: string
|
role: string
|
||||||
age: number
|
age_group: string
|
||||||
education_level: string
|
education_level: string
|
||||||
country: string
|
country: string
|
||||||
region: string
|
region: string
|
||||||
|
|
||||||
nick_name: string
|
nick_name: string
|
||||||
occupation: string
|
occupation: string
|
||||||
learning_goal: string
|
learning_goal: string
|
||||||
language_goal: string
|
language_goal: string
|
||||||
language_challange: string
|
language_challange: string
|
||||||
favoutite_topic: string
|
favoutite_topic: string
|
||||||
|
|
||||||
email_verified: boolean
|
email_verified: boolean
|
||||||
phone_verified: boolean
|
phone_verified: boolean
|
||||||
status: string
|
status: string
|
||||||
|
|
||||||
last_login: string | null
|
last_login: string | null
|
||||||
profile_completed: boolean
|
profile_completed: boolean
|
||||||
preferred_language: string
|
profile_completion_percentage: number
|
||||||
profile_picture_url: string
|
profile_picture_url: string
|
||||||
|
preferred_language: string
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at?: string | null // optional
|
subscription_status: string
|
||||||
age_group?: string
|
|
||||||
profile_completion_percentage?: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserProfileResponse {
|
export interface UserProfileResponse {
|
||||||
|
|
@ -139,11 +133,11 @@ export interface UserRecentActivityData {
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserRecentActivityResponse {
|
export interface UserRecentActivityResponse {
|
||||||
message?: string
|
message: string
|
||||||
data?: UserRecentActivityData
|
data: UserRecentActivityData
|
||||||
success?: boolean
|
success: boolean
|
||||||
status_code?: number
|
status_code: number
|
||||||
metadata?: unknown
|
metadata: null
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserSummary {
|
export interface UserSummary {
|
||||||
|
|
|
||||||
145
src/types/userAdmin.types.ts
Normal file
145
src/types/userAdmin.types.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
||||||
|
import type { UserRecentActivityData } from "./user.types"
|
||||||
|
|
||||||
|
/** Shared access/progress block in learning-activity tree nodes */
|
||||||
|
export interface LearningActivityAccess {
|
||||||
|
is_accessible: boolean
|
||||||
|
is_completed: boolean
|
||||||
|
reason?: string
|
||||||
|
completed_count: number
|
||||||
|
total_count: number
|
||||||
|
progress_percent: number
|
||||||
|
progress_percent_precise: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LearningActivityLesson {
|
||||||
|
id: number
|
||||||
|
module_id: number
|
||||||
|
title: string
|
||||||
|
access: LearningActivityAccess
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LearningActivityModule {
|
||||||
|
id: number
|
||||||
|
program_id?: number
|
||||||
|
course_id?: number
|
||||||
|
unit_id?: number
|
||||||
|
name: string
|
||||||
|
access: LearningActivityAccess
|
||||||
|
lessons: LearningActivityLesson[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LearningActivityUnit {
|
||||||
|
id: number
|
||||||
|
catalog_course_id: number
|
||||||
|
name: string
|
||||||
|
access: LearningActivityAccess
|
||||||
|
modules: LearningActivityModule[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LearningActivityCourse {
|
||||||
|
id: number
|
||||||
|
program_id?: number
|
||||||
|
catalog_course_id?: number
|
||||||
|
name: string
|
||||||
|
access: LearningActivityAccess
|
||||||
|
modules?: LearningActivityModule[]
|
||||||
|
units?: LearningActivityUnit[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LearningActivityProgram {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
access: LearningActivityAccess
|
||||||
|
courses: LearningActivityCourse[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LearningActivityCompletedIds {
|
||||||
|
lesson_ids: number[]
|
||||||
|
module_ids: number[]
|
||||||
|
course_ids: number[]
|
||||||
|
program_ids: number[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserLearningActivityData {
|
||||||
|
user_id: number
|
||||||
|
lms: {
|
||||||
|
completed_ids: LearningActivityCompletedIds
|
||||||
|
progress: {
|
||||||
|
programs: LearningActivityProgram[]
|
||||||
|
}
|
||||||
|
completions: {
|
||||||
|
user_id: number
|
||||||
|
programs: unknown[]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exam_prep: {
|
||||||
|
progress: {
|
||||||
|
catalog_courses: LearningActivityCourse[]
|
||||||
|
}
|
||||||
|
completions: {
|
||||||
|
user_id: number
|
||||||
|
catalog_courses: unknown[]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
recent_activity?: UserRecentActivityData
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserLearningActivityResponse {
|
||||||
|
message: string
|
||||||
|
data: UserLearningActivityData
|
||||||
|
success: boolean
|
||||||
|
status_code: number
|
||||||
|
metadata: null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserSubscriptionRecord {
|
||||||
|
id: number
|
||||||
|
user_id: number
|
||||||
|
plan_id: number
|
||||||
|
plan_name: string
|
||||||
|
plan_category: string
|
||||||
|
starts_at: string
|
||||||
|
expires_at: string
|
||||||
|
status: string
|
||||||
|
payment_reference: string
|
||||||
|
payment_method: string
|
||||||
|
auto_renew: boolean
|
||||||
|
created_at: string
|
||||||
|
duration_value: number
|
||||||
|
duration_unit: string
|
||||||
|
price: number
|
||||||
|
currency: string
|
||||||
|
is_currently_active: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserSubscriptionPayment {
|
||||||
|
id: number
|
||||||
|
plan_id?: number
|
||||||
|
plan_name?: string
|
||||||
|
subscription_id?: number
|
||||||
|
amount: number
|
||||||
|
currency: string
|
||||||
|
payment_method?: string
|
||||||
|
status: string
|
||||||
|
paid_at?: string | null
|
||||||
|
expires_at?: string | null
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserSubscriptionsData {
|
||||||
|
user_id: number
|
||||||
|
display_status: string
|
||||||
|
has_active_subscription: boolean
|
||||||
|
active_by_category: Record<string, boolean>
|
||||||
|
active_subscriptions: UserSubscriptionRecord[]
|
||||||
|
subscriptions: UserSubscriptionRecord[]
|
||||||
|
payments: UserSubscriptionPayment[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserSubscriptionsResponse {
|
||||||
|
message: string
|
||||||
|
data: UserSubscriptionsData
|
||||||
|
success: boolean
|
||||||
|
status_code: number
|
||||||
|
metadata: null
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user