Compare commits

...

160 Commits

Author SHA1 Message Date
Sebastián Ramírez 2eb8f5b624 🔖 Release version 0.8.0 2025-02-19 13:18:57 +01:00
github-actions 558b466d43 📝 Update release notes
[skip ci]
2025-02-19 12:00:29 +00:00
Alejandra 496c7090b3 ♻️ Redirect the user to login if we get 401/403 (#1501) 2025-02-19 12:00:08 +00:00
github-actions 50d2a3bfe1 📝 Update release notes
[skip ci]
2025-02-19 07:37:36 +00:00
Alejandra 1523c20cae 🐛 Refactor reset password test to create normal user instead of using super user (#1499) 2025-02-19 08:37:16 +01:00
github-actions f8e35a5249 📝 Update release notes
[skip ci]
2025-02-18 16:54:48 +00:00
Joel Pérez 9f6f8f088b ♻️ Replace email types from str to EmailStr in config.py (#1492) 2025-02-18 17:53:38 +01:00
github-actions ff5079079b 📝 Update release notes
[skip ci]
2025-02-18 15:03:12 +00:00
Alejandra 7b05fc1f6d 🔧 Remove unused context from router creation (#1498) 2025-02-18 15:02:50 +00:00
github-actions 86ef743226 📝 Update release notes
[skip ci]
2025-02-17 19:55:39 +00:00
Alejandra ed34e5e170 🔧 Configure path alias for cleaner imports (#1497) 2025-02-17 20:55:20 +01:00
github-actions 322975dd6e 📝 Update release notes
[skip ci]
2025-02-17 19:33:16 +00:00
Alejandra 55df823739 🛂 Migrate to Chakra UI v3 (#1496)
Co-authored-by: github-actions <github-actions@github.com>
2025-02-17 20:33:00 +01:00
github-actions 74e2604faf 📝 Update release notes
[skip ci]
2025-02-17 18:04:07 +00:00
Chris Handy 631980a876 📝 Removing deprecated manual client SDK step (#1494) 2025-02-17 18:03:49 +00:00
github-actions f178e58bfe 📝 Update release notes
[skip ci]
2025-02-10 19:26:55 +00:00
Christopher Markus aee08490e5 📝 Update Frontend README.md (#1462)
Fix incorrect script name which was generate-frontend-client.sh and now is generate-client.sh
2025-02-10 19:26:37 +00:00
github-actions 42fd54e06b 📝 Update release notes
[skip ci]
2025-02-10 19:26:00 +00:00
dependabot[bot] 16997dabf0 Bump vite from 5.0.13 to 5.4.14 in /frontend (#1469)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 5.0.13 to 5.4.14.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.4.14/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.4.14/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-10 19:25:42 +00:00
github-actions 7cffa83649 📝 Update release notes
[skip ci]
2025-02-10 19:23:23 +00:00
Nauanbek 15f41f755b ♻️ Remove redundant item deletion code leveraging cascade delete (#1481) 2025-02-10 19:23:04 +00:00
github-actions f2eb1b5c5f 📝 Update release notes
[skip ci]
2025-02-10 15:14:40 +00:00
Robert (Jamie) Munro 6042eda4bc ✏️ Fix a couple of spelling mistakes (#1485) 2025-02-10 15:14:19 +00:00
github-actions ba1706b489 📝 Update release notes
[skip ci]
2025-01-06 11:33:15 +00:00
Boriss Jerjomkin c754a0058b 🧑‍🔧 Replace correct value for 'htmlFor' (#1456) 2025-01-06 11:32:57 +00:00
github-actions 2d553dda53 📝 Update release notes
[skip ci]
2025-01-05 14:58:03 +00:00
Alejandra 846dd9e81a ⬆️ Update Dockerfile to use uv version 0.5.11 (#1454) 2025-01-05 14:57:42 +00:00
github-actions d4df197c59 📝 Update release notes
[skip ci]
2024-12-21 11:01:03 +00:00
Ayoub Benaissa 87afb074a3 📝 Update frontend/README.md to also remove Playwright when removing Frontend (#1452) 2024-12-21 11:00:44 +00:00
github-actions 98a2d7ddcf 📝 Update release notes
[skip ci]
2024-12-21 10:59:48 +00:00
dependabot[bot] b95dea6d26 ⬆ Bump astral-sh/setup-uv from 4 to 5 (#1453)
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 4 to 5.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/v4...v5)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-21 10:59:31 +00:00
github-actions 88c83cc06c 📝 Update release notes
[skip ci]
2024-12-10 09:59:57 +00:00
dependabot[bot] 3e6ed0157e ⬆ Bump astral-sh/setup-uv from 3 to 4 (#1433)
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 3 to 4.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/v3...v4)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-10 09:59:36 +00:00
github-actions b0f6195827 📝 Update release notes
[skip ci]
2024-12-02 12:04:22 +00:00
Patrick Arminio 30832076f5 🎨 Move prefix and tags to routers (#1439) 2024-12-02 12:04:03 +00:00
github-actions aa71abedcc 📝 Update release notes
[skip ci]
2024-12-02 11:58:11 +00:00
Patrick Arminio 14129f7a50 ✨ Add private, local only, API for usage in E2E tests (#1429)
Co-authored-by: github-actions <github-actions@github.com>
2024-12-02 12:57:53 +01:00
github-actions 414864d848 📝 Update release notes
[skip ci]
2024-11-27 11:43:08 +00:00
Patrick Arminio 953e9e5416 ♻️ Remove modify id script in favor of openapi-ts config (#1434) 2024-11-27 12:42:44 +01:00
github-actions b7d2df2f81 📝 Update release notes
[skip ci]
2024-11-27 11:07:21 +00:00
Patrick Arminio a21c57ab2b ✨ Migrate to latest openapi-ts (#1430) 2024-11-27 12:06:59 +01:00
github-actions e34527325b 📝 Update release notes
[skip ci]
2024-11-08 22:02:26 +00:00
dependabot[bot] 19764d5307 ⬆ Bump tiangolo/latest-changes from 0.3.1 to 0.3.2 (#1418)
Bumps [tiangolo/latest-changes](https://github.com/tiangolo/latest-changes) from 0.3.1 to 0.3.2.
- [Release notes](https://github.com/tiangolo/latest-changes/releases)
- [Commits](https://github.com/tiangolo/latest-changes/compare/0.3.1...0.3.2)

---
updated-dependencies:
- dependency-name: tiangolo/latest-changes
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-08 22:02:06 +00:00
github-actions 3aad3fb877 📝 Update release notes 2024-11-01 15:29:47 +00:00
Sebastián Ramírez 61fa9431b7 📝 Update deployment.md, instructions to install GitHub Runner in non-root VMs (#1412) 2024-11-01 15:29:29 +00:00
github-actions 24c4f13629 📝 Update release notes 2024-10-25 21:56:53 +00:00
Sebastián Ramírez e684f3c8d6 👷 Improve Playwright CI speed: sharding (paralel runs), run in Docker to use cache, use env vars (#1405) 2024-10-25 21:56:34 +00:00
github-actions d3d370cad0 📝 Update release notes 2024-10-14 15:36:28 +00:00
Alejandra c23c91bd4e 👷 Update issue manager workflow (#1398) 2024-10-14 17:35:47 +02:00
github-actions 6768359244 📝 Update release notes 2024-10-12 13:55:29 +00:00
Sebastián Ramírez a2e3a8ae11 👷 Fix smokeshow, checkout files on CI (#1395) 2024-10-12 15:54:30 +02:00
github-actions f5612ed7cd 📝 Update release notes 2024-10-12 12:38:47 +00:00
Tobias 12a13b4108 📝 Add MailCatcher to development.md (#1387) 2024-10-12 14:38:29 +02:00
github-actions db7ea2cbbe 📝 Update release notes 2024-10-07 20:34:33 +00:00
Sebastián Ramírez 86d2fcc2e8 👷 Update labeler.yml (#1388) 2024-10-07 20:33:45 +00:00
github-actions 67e3f35491 📝 Update release notes 2024-10-03 18:35:51 +00:00
Justin Perdok 1c3e464acd 🔧 Add .auth playwright folder to .gitignore (#1383) 2024-10-03 20:35:15 +02:00
github-actions 372c9f8f91 📝 Update release notes 2024-10-03 18:33:05 +00:00
Saltie 8d52d018b4 ♻️ Add PaginationFooter component (#1381) 2024-10-03 20:32:46 +02:00
github-actions 88e1a607b0 📝 Update release notes 2024-09-30 13:39:42 +00:00
dependabot[bot] 6047623ad1 ⬆️ Bump rollup from 4.6.1 to 4.22.5 in /frontend (#1379)
Bumps [rollup](https://github.com/rollup/rollup) from 4.6.1 to 4.22.5.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.6.1...v4.22.5)

---
updated-dependencies:
- dependency-name: rollup
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-30 15:39:17 +02:00
github-actions 0a5f1025d6 📝 Update release notes 2024-09-27 16:42:55 +00:00
Muhammad Sameer Amin 172bfd9349 ♻️ Refactored code to use encryption algorithm name from settings for consistency (#1160)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 18:42:36 +02:00
github-actions 79883c879f 📝 Update release notes 2024-09-27 16:40:03 +00:00
github-actions 721a44ab2f 📝 Update release notes 2024-09-27 16:39:41 +00:00
Hmily ddb4235bfe 🔊 Enable logging for email utils by default (#1374)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 16:39:40 +00:00
dependabot[bot] 2939b7723b ⬆ Bump astral-sh/setup-uv from 2 to 3 (#1364)
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 2 to 3.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/v2...v3)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-27 18:39:19 +02:00
github-actions 4d5b0a065c 📝 Update release notes 2024-09-27 16:30:27 +00:00
Chris 3793150fe4 👷 Update pre-commit end-of-file-fixer hook to exclude email-templates (#1296)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 16:30:09 +00:00
github-actions ab0d1bb12f 📝 Update release notes 2024-09-27 16:28:02 +00:00
dependabot[bot] 3136437bcb ⬆ Bump tiangolo/issue-manager from 0.5.0 to 0.5.1 (#1332)
Bumps [tiangolo/issue-manager](https://github.com/tiangolo/issue-manager) from 0.5.0 to 0.5.1.
- [Release notes](https://github.com/tiangolo/issue-manager/releases)
- [Commits](https://github.com/tiangolo/issue-manager/compare/0.5.0...0.5.1)

---
updated-dependencies:
- dependency-name: tiangolo/issue-manager
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-27 18:27:40 +02:00
github-actions b9ec1943eb 📝 Update release notes 2024-09-27 16:11:18 +00:00
Sebastián Ramírez fe7f4f7949 🔧 Add ENV PYTHONUNBUFFERED=1 to log output directly to Docker (#1378) 2024-09-27 16:10:59 +00:00
github-actions b67fb44e5b 📝 Update release notes 2024-09-27 16:00:15 +00:00
Waket Zheng 945fbc7699 🔧 Run task by the same Python environment used to run Copier (#1157)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 17:59:54 +02:00
github-actions 109a7454c7 📝 Update release notes 2024-09-27 15:53:52 +00:00
Sebastián Ramírez 38843cbe28 👷 Tweak generate client to error out if there are errors (#1377) 2024-09-27 15:53:31 +00:00
github-actions 1030118247 📝 Update release notes 2024-09-27 15:41:36 +00:00
Hani Sabsoob 08dd87d0f2 💡 Remove unnecessary comment (#1260)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 17:41:17 +02:00
github-actions 6a8fc240b3 📝 Update release notes 2024-09-27 14:23:43 +00:00
Sebastián Ramírez c297e9ee9e 👷 Generate and commit client only on same repo PRs, on forks, show the error (#1376) 2024-09-27 16:23:23 +02:00
Sebastián Ramírez 7e5ca88dc2 🔖 Release version 0.7.1 2024-09-27 15:30:04 +02:00
github-actions 451c656fb0 📝 Update release notes 2024-09-24 09:53:03 +00:00
Sebastián Ramírez 911223516c 👷 Use uv cache on GitHub Actions (#1366) 2024-09-24 11:52:42 +02:00
github-actions 1f666c4907 📝 Update release notes 2024-09-23 22:29:32 +00:00
Sebastián Ramírez 32227c4020 👷 Update GitHub Actions format (#1363) 2024-09-24 00:29:10 +02:00
github-actions cdc7b50fec 📝 Update release notes 2024-09-23 22:05:47 +00:00
Sebastián Ramírez 284527b7bc 👷 Use uv for Python env to generate client (#1362) 2024-09-24 00:05:29 +02:00
github-actions 6ed7aee371 📝 Update release notes 2024-09-23 21:27:39 +00:00
Sebastián Ramírez 39325ad421 👷 Run tests from Python environment (with uv), not from Docker container (#1361) 2024-09-23 23:27:21 +02:00
github-actions b3a77946cb 📝 Update release notes 2024-09-23 20:36:34 +00:00
Sebastián Ramírez 9b2e5813ae 🔨 Update generate-client.sh script, make it fail on errors, fix generation (#1360) 2024-09-23 22:36:14 +02:00
github-actions 55ad3b21ee 📝 Update release notes 2024-09-23 20:09:35 +00:00
Sebastián Ramírez d2020c1a37 ♻️ Update settings to use top level .env file (#1359) 2024-09-23 22:09:11 +02:00
github-actions 6fc03d1bf4 📝 Update release notes 2024-09-23 19:35:36 +00:00
Sebastián Ramírez 0435937f8e 👷 Add GitHub Actions workflow to lint backend apart from tests (#1358) 2024-09-23 21:35:18 +02:00
github-actions 8d9af8cb80 📝 Update release notes 2024-09-23 16:53:28 +00:00
Sebastián Ramírez 4fc9610175 💡 Add comments to Dockerfile with uv references (#1357) 2024-09-23 16:53:08 +00:00
github-actions 4b6fb7c465 📝 Update release notes 2024-09-23 14:11:09 +00:00
Sebastián Ramírez 81048277c7 ⬆️ Migrate from Poetry to uv (#1356) 2024-09-23 16:10:46 +02:00
github-actions fa97b372b4 📝 Update release notes 2024-09-23 11:40:12 +00:00
Sebastián Ramírez c8104d8ced 🔥 Remove logic for development dependencies and Jupyter, it was never documented, and I no longer use that trick (#1355) 2024-09-23 13:39:54 +02:00
github-actions 7ed8694643 📝 Update release notes 2024-09-22 22:29:44 +00:00
Sebastián Ramírez 4cd67f3483 ♻️ Use Docker Compose watch (#1354) 2024-09-23 00:29:23 +02:00
github-actions b262c2053c 📝 Update release notes 2024-09-22 16:25:47 +00:00
Sebastián Ramírez 651643982b 🔧 Use plain base official Python Docker image (#1351) 2024-09-22 18:25:29 +02:00
github-actions 224d0e31a8 📝 Update release notes 2024-09-22 16:20:17 +00:00
Sebastián Ramírez 87254dd79e 🚚 Move location of scripts to simplify file structure (#1352) 2024-09-22 18:19:57 +02:00
github-actions 68a7fe0899 📝 Update release notes 2024-09-20 15:13:01 +00:00
Sebastián Ramírez 8fe66c1cc1 ♻️ Refactor prestart (migrations), move that to its own container (#1350) 2024-09-20 17:12:40 +02:00
github-actions d87b6391b5 📝 Update release notes 2024-09-20 12:53:11 +00:00
Sebastián Ramírez 889a9bf5bf ⬆️ Upgrade FastAPI (#1349) 2024-09-20 14:52:45 +02:00
github-actions 44ff5730b7 📝 Update release notes 2024-09-20 12:43:51 +00:00
Sebastián Ramírez e64c9100ec ♻️ Include FRONTEND_HOST in CORS origins by default (#1348) 2024-09-20 14:43:32 +02:00
github-actions a292dbe10d 📝 Update release notes 2024-09-19 18:11:52 +00:00
Sebastián Ramírez 79d240f5b7 ♻️ Simplify domains with api.example.com for API and dashboard.example.com for frontend, improve local development with localhost (#1344) 2024-09-19 18:11:33 +00:00
github-actions 110a59c71d 📝 Update release notes 2024-09-16 22:26:45 +00:00
Sebastián Ramírez 2062b5b671 🔥 Simplify Traefik, remove www-redirects that add complexity (#1343) 2024-09-17 00:26:26 +02:00
github-actions 07b568b4f6 📝 Update release notes 2024-09-16 19:52:57 +00:00
Sebastián Ramírez 8a8a90459d 🩺 Add DB healthcheck (#1342) 2024-09-16 21:52:33 +02:00
github-actions eb88b52ff8 📝 Update release notes 2024-09-16 19:43:09 +00:00
Sebastián Ramírez 18a5cb21db 🔥 Enable support for Arm Docker images in Mac, remove old patch (#1341) 2024-09-16 21:42:50 +02:00
github-actions 46ac6a3c6f 📝 Update release notes 2024-09-12 13:21:44 +00:00
Patrick Arminio 97d04cd7ff 👷 Improve playwright CI job (#1335) 2024-09-12 15:21:24 +02:00
github-actions b3a49ae32e 📝 Update release notes 2024-09-07 15:20:44 +00:00
Sebastián Ramírez 4af652aa73 👷 Update issue-manager.yml (#1329) 2024-09-07 17:20:24 +02:00
github-actions ad3580703c 📝 Update release notes 2024-09-02 20:48:36 +00:00
Sofie Van Landeghem 2241d75131 set include-hidden-files to true for actions/upload-artifact@v4 (#1327) 2024-09-02 22:48:18 +02:00
github-actions 33b379bd46 📝 Update release notes 2024-08-29 18:11:08 +00:00
Alejandra bbad34aa8d 👷🏻 Auto-generate frontend client (#1320) 2024-08-29 20:10:49 +02:00
github-actions e8c73ff614 📝 Update release notes 2024-08-29 15:46:18 +00:00
Alejandra 644de7f186 🐛 Fix in .github/labeler.yml (#1322) 2024-08-29 17:46:02 +02:00
github-actions 90e3e337cb 📝 Update release notes 2024-08-29 15:38:45 +00:00
Alejandra 2fb7354923 👷 Update .github/labeler.yml (#1321) 2024-08-29 15:38:22 +00:00
github-actions 05bc1412b3 📝 Update release notes 2024-08-26 02:18:04 +00:00
Sebastián Ramírez 375170c386 👷 Update latest-changes GitHub Action (#1315) 2024-08-26 02:17:32 +00:00
github-actions 5005e5a5c1 📝 Update release notes 2024-08-17 18:59:41 +00:00
Alejandra 77040adf86 📝 Add Email Templates to backend/README.md (#1311) 2024-08-17 13:59:22 -05:00
github-actions 65c66f2050 📝 Update release notes 2024-08-15 20:43:14 +00:00
Sebastián Ramírez 8187a5283f 👷 Update configs for labeler (#1308) 2024-08-15 15:42:54 -05:00
github-actions 66c4ff169d 📝 Update release notes 2024-08-15 18:49:23 +00:00
Sebastián Ramírez d7d245a108 👷 Do not sync labels as it overrides manually added labels (#1307) 2024-08-15 13:48:43 -05:00
github-actions 6eff776fc1 📝 Update release notes 2024-08-14 19:12:46 +00:00
Sebastián Ramírez de57a7bac1 👷 Update GitHub Action labeler to add only one label (#1304) 2024-08-14 14:12:29 -05:00
github-actions 0f082d1265 📝 Update release notes 2024-08-14 14:57:14 +00:00
dependabot[bot] 5a138697ec ⬆️ Bump axios from 1.6.2 to 1.7.4 in /frontend (#1301)
Bumps [axios](https://github.com/axios/axios) from 1.6.2 to 1.7.4.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.6.2...v1.7.4)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com>
2024-08-14 09:56:53 -05:00
github-actions 79ed422871 📝 Update release notes 2024-08-14 03:58:27 +00:00
Sebastián Ramírez d275c6224b 👷 Update GitHub Action labeler dependencies (#1302) 2024-08-13 22:57:33 -05:00
github-actions 972714512b 📝 Update release notes 2024-08-13 22:34:48 +00:00
Sebastián Ramírez 4b9285643a 👷 Update GitHub Action labeler permissions (#1300) 2024-08-13 17:34:30 -05:00
github-actions cdf9a6548e 📝 Update release notes 2024-08-13 05:36:01 +00:00
Sebastián Ramírez 10c6cc72eb 👷 Add GitHub Action label-checker (#1299) 2024-08-13 05:35:21 +00:00
github-actions 7351d21fae 📝 Update release notes 2024-08-13 03:58:49 +00:00
jjaakko 974340c8ff ♻️ Remove duplicated information in the ItemCreate model (#1287) 2024-08-12 22:58:31 -05:00
github-actions 572f513458 📝 Update release notes 2024-08-13 02:45:00 +00:00
Sebastián Ramírez b4c34c63d6 👷 Add GitHub Action labeler (#1298) 2024-08-13 02:44:18 +00:00
github-actions ee82165ec7 📝 Update release notes 2024-08-13 02:11:43 +00:00
Sebastián Ramírez e46ba68301 👷 Add GitHub Action add-to-project (#1297) 2024-08-13 02:11:24 +00:00
github-actions 7a6107ff41 📝 Update release notes 2024-08-03 19:24:01 +00:00
Sebastián Ramírez df94e73a5a 👷 Update issue-manager (#1288) 2024-08-03 19:23:42 +00:00
128 changed files with 9561 additions and 7826 deletions
+8
View File
@@ -1,6 +1,14 @@
# Domain # Domain
# This would be set to the production domain with an env var on deployment # This would be set to the production domain with an env var on deployment
# used by Traefik to transmit traffic and aqcuire TLS certificates
DOMAIN=localhost DOMAIN=localhost
# To test the local Traefik config
# DOMAIN=localhost.tiangolo.com
# Used by the backend to generate links in emails to the frontend
FRONTEND_HOST=http://localhost:5173
# In staging and production, set this env var to the frontend host, e.g.
# FRONTEND_HOST=https://dashboard.example.com
# Environment: local, staging, production # Environment: local, staging, production
ENVIRONMENT=local ENVIRONMENT=local
+6 -6
View File
@@ -1,16 +1,16 @@
version: 2 version: 2
updates: updates:
# GitHub Actions # GitHub Actions
- package-ecosystem: "github-actions" - package-ecosystem: github-actions
directory: "/" directory: /
schedule: schedule:
interval: "daily" interval: daily
commit-message: commit-message:
prefix: ⬆ prefix: ⬆
# Python # Python
- package-ecosystem: "pip" - package-ecosystem: pip
directory: "/" directory: /
schedule: schedule:
interval: "daily" interval: daily
commit-message: commit-message:
prefix: ⬆ prefix: ⬆
+25
View File
@@ -0,0 +1,25 @@
docs:
- all:
- changed-files:
- any-glob-to-any-file:
- '**/*.md'
- all-globs-to-all-files:
- '!frontend/**'
- '!backend/**'
- '!.github/**'
- '!scripts/**'
- '!.gitignore'
- '!.pre-commit-config.yaml'
internal:
- all:
- changed-files:
- any-glob-to-any-file:
- .github/**
- scripts/**
- .gitignore
- .pre-commit-config.yaml
- all-globs-to-all-files:
- '!./**/*.md'
- '!frontend/**'
- '!backend/**'
+18
View File
@@ -0,0 +1,18 @@
name: Add to Project
on:
pull_request_target:
issues:
types:
- opened
- reopened
jobs:
add-to-project:
name: Add to project
runs-on: ubuntu-latest
steps:
- uses: actions/add-to-project@v1.0.2
with:
project-url: https://github.com/orgs/fastapi/projects/2
github-token: ${{ secrets.PROJECTS_TOKEN }}
+61
View File
@@ -0,0 +1,61 @@
name: Generate Client
on:
pull_request:
types:
- opened
- synchronize
jobs:
generate-client:
permissions:
contents: write
runs-on: ubuntu-latest
steps:
# For PRs from forks
- uses: actions/checkout@v4
# For PRs from the same repo
- uses: actions/checkout@v4
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' )
with:
ref: ${{ github.head_ref }}
token: ${{ secrets.FULL_STACK_FASTAPI_TEMPLATE_REPO_TOKEN }}
- uses: actions/setup-node@v4
with:
node-version: lts/*
- uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
version: "0.4.15"
enable-cache: true
- name: Install dependencies
run: npm ci
working-directory: frontend
- run: uv sync
working-directory: backend
- run: uv run bash scripts/generate-client.sh
env:
VIRTUAL_ENV: backend/.venv
ENVIRONMENT: production
SECRET_KEY: just-for-generating-client
POSTGRES_PASSWORD: just-for-generating-client
FIRST_SUPERUSER_PASSWORD: just-for-generating-client
- name: Add changes to git
run: |
git config --local user.email "github-actions@github.com"
git config --local user.name "github-actions"
git add frontend/src/client
# Same repo PRs
- name: Push changes
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' )
run: |
git diff --staged --quiet || git commit -m "✨ Autogenerate frontend client"
git push
# Fork PRs
- name: Check changes
if: ( github.event_name == 'pull_request' && github.secret_source != 'Actions' )
run: |
git diff --staged --quiet || (echo "Changes detected in generated client, run scripts/generate-client.sh and commit the changes" && exit 1)
+21 -5
View File
@@ -2,30 +2,46 @@ name: Issue Manager
on: on:
schedule: schedule:
- cron: "0 0 * * *" - cron: "21 17 * * *"
issue_comment: issue_comment:
types: types:
- created - created
- edited
issues: issues:
types: types:
- labeled - labeled
pull_request_target:
types:
- labeled
workflow_dispatch:
permissions: permissions:
issues: write issues: write
pull-requests: write
jobs: jobs:
issue-manager: issue-manager:
if: github.repository_owner == 'fastapi'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: tiangolo/issue-manager@0.5.0 - name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: tiangolo/issue-manager@0.5.1
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
config: > config: >
{ {
"answered": { "answered": {
"users": ["tiangolo"],
"delay": 864000, "delay": 864000,
"message": "Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues." "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
},
"waiting": {
"delay": 2628000,
"message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR."
},
"invalid": {
"delay": 0,
"message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details."
} }
} }
+33
View File
@@ -0,0 +1,33 @@
name: Labels
on:
pull_request_target:
types:
- opened
- synchronize
- reopened
# For label-checker
- labeled
- unlabeled
jobs:
labeler:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@v5
if: ${{ github.event.action != 'labeled' && github.event.action != 'unlabeled' }}
- run: echo "Done adding labels"
# Run this after labeler applied labels
check-labels:
needs:
- labeler
permissions:
pull-requests: read
runs-on: ubuntu-latest
steps:
- uses: docker://agilepathway/pull-request-label-checker:latest
with:
one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal
repo_token: ${{ secrets.GITHUB_TOKEN }}
+6 -7
View File
@@ -12,9 +12,9 @@ on:
description: PR number description: PR number
required: true required: true
debug_enabled: debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)"
required: false required: false
default: 'false' default: "false"
jobs: jobs:
latest-changes: latest-changes:
@@ -30,12 +30,11 @@ jobs:
with: with:
# To allow latest-changes to commit to the main branch # To allow latest-changes to commit to the main branch
token: ${{ secrets.LATEST_CHANGES }} token: ${{ secrets.LATEST_CHANGES }}
- uses: docker://tiangolo/latest-changes:0.3.0 - uses: tiangolo/latest-changes@0.3.2
# - uses: tiangolo/latest-changes@main
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
latest_changes_file: ./release-notes.md latest_changes_file: ./release-notes.md
latest_changes_header: '## Latest Changes' latest_changes_header: "## Latest Changes"
end_regex: '^## ' end_regex: "^## "
debug_logs: true debug_logs: true
label_header_prefix: '### ' label_header_prefix: "### "
+28
View File
@@ -0,0 +1,28 @@
name: Lint Backend
on:
push:
branches:
- master
pull_request:
types:
- opened
- synchronize
jobs:
lint-backend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
version: "0.4.15"
enable-cache: true
- run: uv run bash scripts/lint.sh
working-directory: backend
+82 -17
View File
@@ -16,10 +16,36 @@ on:
default: 'false' default: 'false'
jobs: jobs:
changes:
runs-on: ubuntu-latest
# Set job outputs to values from filter step
outputs:
changed: ${{ steps.filter.outputs.changed }}
steps:
- uses: actions/checkout@v4
# For pull requests it's not necessary to checkout the code but for the main branch it is
- uses: dorny/paths-filter@v3
id: filter
with:
filters: |
changed:
- backend/**
- frontend/**
- .env
- docker-compose*.yml
- .github/workflows/playwright.yml
test: test-playwright:
needs:
- changes
if: ${{ needs.changes.outputs.changed == 'true' }}
timeout-minutes: 60 timeout-minutes: 60
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
shardIndex: [1, 2, 3, 4]
shardTotal: [4]
fail-fast: false
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
@@ -33,34 +59,73 @@ jobs:
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
with: with:
limit-access-to-actor: true limit-access-to-actor: true
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
version: "0.4.15"
enable-cache: true
- run: uv sync
working-directory: backend
- run: npm ci
working-directory: frontend
- run: uv run bash scripts/generate-client.sh
env:
VIRTUAL_ENV: backend/.venv
- run: docker compose build
- run: docker compose down -v --remove-orphans
- name: Run Playwright tests
run: docker compose run --rm playwright npx playwright test --fail-on-flaky-tests --trace=retain-on-failure --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
- run: docker compose down -v --remove-orphans
- name: Upload blob report to GitHub Actions Artifacts
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: blob-report-${{ matrix.shardIndex }}
path: frontend/blob-report
include-hidden-files: true
retention-days: 1
merge-playwright-reports:
needs:
- test-playwright
- changes
# Merge reports after playwright-tests, even if some shards have failed
if: ${{ !cancelled() && needs.changes.outputs.changed == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
working-directory: frontend working-directory: frontend
- name: Install Playwright Browsers - name: Download blob reports from GitHub Actions Artifacts
run: npx playwright install --with-deps uses: actions/download-artifact@v4
working-directory: frontend
- run: docker compose build
- run: docker compose down -v --remove-orphans
- run: docker compose up -d
- name: Run Playwright tests
run: npx playwright test
working-directory: frontend
- run: docker compose down -v --remove-orphans
- uses: actions/upload-artifact@v4
if: always()
with: with:
name: playwright-report path: frontend/all-blob-reports
path: frontend/playwright-report/ pattern: blob-report-*
merge-multiple: true
- name: Merge into HTML Report
run: npx playwright merge-reports --reporter html ./all-blob-reports
working-directory: frontend
- name: Upload HTML report
uses: actions/upload-artifact@v4
with:
name: html-report--attempt-${{ github.run_attempt }}
path: frontend/playwright-report
retention-days: 30 retention-days: 30
include-hidden-files: true
# https://github.com/marketplace/actions/alls-green#why # https://github.com/marketplace/actions/alls-green#why
e2e-alls-green: # This job does nothing and is only used for the branch protection alls-green-playwright: # This job does nothing and is only used for the branch protection
if: always() if: always()
needs: needs:
- test - test-playwright
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Decide whether the needed jobs succeeded or failed - name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@release/v1 uses: re-actors/alls-green@release/v1
with: with:
jobs: ${{ toJSON(needs) }} jobs: ${{ toJSON(needs) }}
allowed-skips: test-playwright
+3 -5
View File
@@ -2,7 +2,7 @@ name: Smokeshow
on: on:
workflow_run: workflow_run:
workflows: [Test] workflows: [Test Backend]
types: [completed] types: [completed]
jobs: jobs:
@@ -14,19 +14,17 @@ jobs:
statuses: write statuses: write
steps: steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
with: with:
python-version: '3.9' python-version: "3.10"
- run: pip install smokeshow - run: pip install smokeshow
- uses: actions/download-artifact@v4 - uses: actions/download-artifact@v4
with: with:
name: coverage-html name: coverage-html
path: backend/htmlcov path: backend/htmlcov
github-token: ${{ secrets.GITHUB_TOKEN }} github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ github.event.workflow_run.id }} run-id: ${{ github.event.workflow_run.id }}
- run: smokeshow upload backend/htmlcov - run: smokeshow upload backend/htmlcov
env: env:
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
+41
View File
@@ -0,0 +1,41 @@
name: Test Backend
on:
push:
branches:
- master
pull_request:
types:
- opened
- synchronize
jobs:
test-backend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
version: "0.4.15"
enable-cache: true
- run: docker compose down -v --remove-orphans
- run: docker compose up -d db mailcatcher
- name: Migrate DB
run: uv run bash scripts/prestart.sh
working-directory: backend
- name: Run tests
run: uv run bash scripts/tests-start.sh "Coverage for ${{ github.sha }}"
working-directory: backend
- run: docker compose down -v --remove-orphans
- name: Store coverage files
uses: actions/upload-artifact@v4
with:
name: coverage-html
path: backend/htmlcov
include-hidden-files: true
+26
View File
@@ -0,0 +1,26 @@
name: Test Docker Compose
on:
push:
branches:
- master
pull_request:
types:
- opened
- synchronize
jobs:
test-docker-compose:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- run: docker compose build
- run: docker compose down -v --remove-orphans
- run: docker compose up -d --wait backend frontend adminer
- name: Test backend is up
run: curl http://localhost:8000/api/v1/utils/health-check
- name: Test frontend is up
run: curl http://localhost:5173
- run: docker compose down -v --remove-orphans
-49
View File
@@ -1,49 +0,0 @@
name: Test
on:
push:
branches:
- master
pull_request:
types:
- opened
- synchronize
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
- run: docker compose build
- run: docker compose down -v --remove-orphans
- run: docker compose up -d
- name: Lint
run: docker compose exec -T backend bash /app/scripts/lint.sh
- name: Run tests
run: docker compose exec -T backend bash /app/tests-start.sh "Coverage for ${{ github.sha }}"
- run: docker compose down -v --remove-orphans
- name: Store coverage files
uses: actions/upload-artifact@v4
with:
name: coverage-html
path: backend/htmlcov
# https://github.com/marketplace/actions/alls-green#why
alls-green: # This job does nothing and is only used for the branch protection
if: always()
needs:
- test
runs-on: ubuntu-latest
steps:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@release/v1
with:
jobs: ${{ toJSON(needs) }}
+5 -1
View File
@@ -10,7 +10,11 @@ repos:
args: args:
- --unsafe - --unsafe
- id: end-of-file-fixer - id: end-of-file-fixer
exclude: ^frontend/src/client/.* exclude: |
(?x)^(
frontend/src/client/.*|
backend/app/email-templates/build/.*
)$
- id: trailing-whitespace - id: trailing-whitespace
exclude: ^frontend/src/client/.* exclude: ^frontend/src/client/.*
- repo: https://github.com/charliermarsh/ruff-pre-commit - repo: https://github.com/charliermarsh/ruff-pre-commit
+32 -17
View File
@@ -1,28 +1,43 @@
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.10 FROM python:3.10
ENV PYTHONUNBUFFERED=1
WORKDIR /app/ WORKDIR /app/
# Install Poetry # Install uv
RUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/opt/poetry python && \ # Ref: https://docs.astral.sh/uv/guides/integration/docker/#installing-uv
cd /usr/local/bin && \ COPY --from=ghcr.io/astral-sh/uv:0.5.11 /uv /uvx /bin/
ln -s /opt/poetry/bin/poetry && \
poetry config virtualenvs.create false
# Copy poetry.lock* in case it doesn't exist in the repo # Place executables in the environment at the front of the path
COPY ./pyproject.toml ./poetry.lock* /app/ # Ref: https://docs.astral.sh/uv/guides/integration/docker/#using-the-environment
ENV PATH="/app/.venv/bin:$PATH"
# Allow installing dev dependencies to run tests # Compile bytecode
ARG INSTALL_DEV=false # Ref: https://docs.astral.sh/uv/guides/integration/docker/#compiling-bytecode
RUN bash -c "if [ $INSTALL_DEV == 'true' ] ; then poetry install --no-root ; else poetry install --no-root --only main ; fi" ENV UV_COMPILE_BYTECODE=1
# uv Cache
# Ref: https://docs.astral.sh/uv/guides/integration/docker/#caching
ENV UV_LINK_MODE=copy
# Install dependencies
# Ref: https://docs.astral.sh/uv/guides/integration/docker/#intermediate-layers
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --frozen --no-install-project
ENV PYTHONPATH=/app ENV PYTHONPATH=/app
COPY ./scripts/ /app/ COPY ./scripts /app/scripts
COPY ./alembic.ini /app/ COPY ./pyproject.toml ./uv.lock ./alembic.ini /app/
COPY ./prestart.sh /app/
COPY ./tests-start.sh /app/
COPY ./app /app/app COPY ./app /app/app
# Sync the project
# Ref: https://docs.astral.sh/uv/guides/integration/docker/#intermediate-layers
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync
CMD ["fastapi", "run", "--workers", "4", "app/main.py"]
+35 -61
View File
@@ -3,84 +3,50 @@
## Requirements ## Requirements
* [Docker](https://www.docker.com/). * [Docker](https://www.docker.com/).
* [Poetry](https://python-poetry.org/) for Python package and environment management. * [uv](https://docs.astral.sh/uv/) for Python package and environment management.
## Local Development ## Docker Compose
* Start the stack with Docker Compose: Start the local development environment with Docker Compose following the guide in [../development.md](../development.md).
```bash ## General Workflow
docker compose up -d
```
* Now you can open your browser and interact with these URLs: By default, the dependencies are managed with [uv](https://docs.astral.sh/uv/), go there and install it.
Frontend, built with Docker, with routes handled based on the path: http://localhost
Backend, JSON based web API based on OpenAPI: http://localhost/api/
Automatic interactive documentation with Swagger UI (from the OpenAPI backend): http://localhost/docs
Adminer, database web administration: http://localhost:8080
Traefik UI, to see how the routes are being handled by the proxy: http://localhost:8090
**Note**: The first time you start your stack, it might take a minute for it to be ready. While the backend waits for the database to be ready and configures everything. You can check the logs to monitor it.
To check the logs, run:
```bash
docker compose logs
```
To check the logs of a specific service, add the name of the service, e.g.:
```bash
docker compose logs backend
```
If your Docker is not running in `localhost` (the URLs above wouldn't work) you would need to use the IP or domain where your Docker is running.
## Backend local development, additional details
### General workflow
By default, the dependencies are managed with [Poetry](https://python-poetry.org/), go there and install it.
From `./backend/` you can install all the dependencies with: From `./backend/` you can install all the dependencies with:
```console ```console
$ poetry install $ uv sync
``` ```
Then you can start a shell session with the new environment with: Then you can activate the virtual environment with:
```console ```console
$ poetry shell $ source .venv/bin/activate
``` ```
Make sure your editor is using the correct Python virtual environment. Make sure your editor is using the correct Python virtual environment, with the interpreter at `backend/.venv/bin/python`.
Modify or add SQLModel models for data and SQL tables in `./backend/app/models.py`, API endpoints in `./backend/app/api/`, CRUD (Create, Read, Update, Delete) utils in `./backend/app/crud.py`. Modify or add SQLModel models for data and SQL tables in `./backend/app/models.py`, API endpoints in `./backend/app/api/`, CRUD (Create, Read, Update, Delete) utils in `./backend/app/crud.py`.
### VS Code ## VS Code
There are already configurations in place to run the backend through the VS Code debugger, so that you can use breakpoints, pause and explore variables, etc. There are already configurations in place to run the backend through the VS Code debugger, so that you can use breakpoints, pause and explore variables, etc.
The setup is also already configured so you can run the tests through the VS Code Python tests tab. The setup is also already configured so you can run the tests through the VS Code Python tests tab.
### Docker Compose Override ## Docker Compose Override
During development, you can change Docker Compose settings that will only affect the local development environment in the file `docker-compose.override.yml`. During development, you can change Docker Compose settings that will only affect the local development environment in the file `docker-compose.override.yml`.
The changes to that file only affect the local development environment, not the production environment. So, you can add "temporary" changes that help the development workflow. The changes to that file only affect the local development environment, not the production environment. So, you can add "temporary" changes that help the development workflow.
For example, the directory with the backend code is mounted as a Docker "host volume", mapping the code you change live to the directory inside the container. That allows you to test your changes right away, without having to build the Docker image again. It should only be done during development, for production, you should build the Docker image with a recent version of the backend code. But during development, it allows you to iterate very fast. For example, the directory with the backend code is synchronized in the Docker container, copying the code you change live to the directory inside the container. That allows you to test your changes right away, without having to build the Docker image again. It should only be done during development, for production, you should build the Docker image with a recent version of the backend code. But during development, it allows you to iterate very fast.
There is also a command override that runs `/start-reload.sh` (included in the base image) instead of the default `/start.sh` (also included in the base image). It starts a single server process (instead of multiple, as would be for production) and reloads the process whenever the code changes. Have in mind that if you have a syntax error and save the Python file, it will break and exit, and the container will stop. After that, you can restart the container by fixing the error and running again: There is also a command override that runs `fastapi run --reload` instead of the default `fastapi run`. It starts a single server process (instead of multiple, as would be for production) and reloads the process whenever the code changes. Have in mind that if you have a syntax error and save the Python file, it will break and exit, and the container will stop. After that, you can restart the container by fixing the error and running again:
```console ```console
$ docker compose up -d $ docker compose watch
``` ```
There is also a commented out `command` override, you can uncomment it and comment the default one. It makes the backend container run a process that does "nothing", but keeps the container alive. That allows you to get inside your running container and execute commands inside, for example a Python interpreter to test installed dependencies, or start the development server that reloads when it detects changes. There is also a commented out `command` override, you can uncomment it and comment the default one. It makes the backend container run a process that does "nothing", but keeps the container alive. That allows you to get inside your running container and execute commands inside, for example a Python interpreter to test installed dependencies, or start the development server that reloads when it detects changes.
@@ -88,10 +54,10 @@ There is also a commented out `command` override, you can uncomment it and comme
To get inside the container with a `bash` session you can start the stack with: To get inside the container with a `bash` session you can start the stack with:
```console ```console
$ docker compose up -d $ docker compose watch
``` ```
and then `exec` inside the running container: and then in another terminal, `exec` inside the running container:
```console ```console
$ docker compose exec backend bash $ docker compose exec backend bash
@@ -105,16 +71,16 @@ root@7f2607af31c3:/app#
that means that you are in a `bash` session inside your container, as a `root` user, under the `/app` directory, this directory has another directory called "app" inside, that's where your code lives inside the container: `/app/app`. that means that you are in a `bash` session inside your container, as a `root` user, under the `/app` directory, this directory has another directory called "app" inside, that's where your code lives inside the container: `/app/app`.
There you can use the script `/start-reload.sh` to run the debug live reloading server. You can run that script from inside the container with: There you can use the `fastapi run --reload` command to run the debug live reloading server.
```console ```console
$ bash /start-reload.sh $ fastapi run --reload app/main.py
``` ```
...it will look like: ...it will look like:
```console ```console
root@7f2607af31c3:/app# bash /start-reload.sh root@7f2607af31c3:/app# fastapi run --reload app/main.py
``` ```
and then hit enter. That runs the live reloading server that auto reloads when it detects code changes. and then hit enter. That runs the live reloading server that auto reloads when it detects code changes.
@@ -123,7 +89,7 @@ Nevertheless, if it doesn't detect a change but a syntax error, it will just sto
...this previous detail is what makes it useful to have the container alive doing nothing and then, in a Bash session, make it run the live reload server. ...this previous detail is what makes it useful to have the container alive doing nothing and then, in a Bash session, make it run the live reload server.
### Backend tests ## Backend tests
To test the backend run: To test the backend run:
@@ -135,27 +101,27 @@ The tests run with Pytest, modify and add tests to `./backend/app/tests/`.
If you use GitHub Actions the tests will run automatically. If you use GitHub Actions the tests will run automatically.
#### Test running stack ### Test running stack
If your stack is already up and you just want to run the tests, you can use: If your stack is already up and you just want to run the tests, you can use:
```bash ```bash
docker compose exec backend bash /app/tests-start.sh docker compose exec backend bash scripts/tests-start.sh
``` ```
That `/app/tests-start.sh` script just calls `pytest` after making sure that the rest of the stack is running. If you need to pass extra arguments to `pytest`, you can pass them to that command and they will be forwarded. That `/app/scripts/tests-start.sh` script just calls `pytest` after making sure that the rest of the stack is running. If you need to pass extra arguments to `pytest`, you can pass them to that command and they will be forwarded.
For example, to stop on first error: For example, to stop on first error:
```bash ```bash
docker compose exec backend bash /app/tests-start.sh -x docker compose exec backend bash scripts/tests-start.sh -x
``` ```
#### Test Coverage ### Test Coverage
When the tests are run, a file `htmlcov/index.html` is generated, you can open it in your browser to see the coverage of the tests. When the tests are run, a file `htmlcov/index.html` is generated, you can open it in your browser to see the coverage of the tests.
### Migrations ## Migrations
As during local development your app directory is mounted as a volume inside the container, you can also run the migrations with `alembic` commands inside the container and the migration code will be in your app directory (instead of being only inside the container). So you can add it to your git repository. As during local development your app directory is mounted as a volume inside the container, you can also run the migrations with `alembic` commands inside the container and the migration code will be in your app directory (instead of being only inside the container). So you can add it to your git repository.
@@ -189,10 +155,18 @@ If you don't want to use migrations at all, uncomment the lines in the file at `
SQLModel.metadata.create_all(engine) SQLModel.metadata.create_all(engine)
``` ```
and comment the line in the file `prestart.sh` that contains: and comment the line in the file `scripts/prestart.sh` that contains:
```console ```console
$ alembic upgrade head $ alembic upgrade head
``` ```
If you don't want to start with the default models and want to remove them / modify them, from the beginning, without having any previous revision, you can remove the revision files (`.py` Python files) under `./backend/app/alembic/versions/`. And then create a first migration as described above. If you don't want to start with the default models and want to remove them / modify them, from the beginning, without having any previous revision, you can remove the revision files (`.py` Python files) under `./backend/app/alembic/versions/`. And then create a first migration as described above.
## Email Templates
The email templates are in `./backend/app/email-templates/`. Here, there are two directories: `build` and `src`. The `src` directory contains the source files that are used to build the final email templates. The `build` directory contains the final email templates that are used by the application.
Before continuing, ensure you have the [MJML extension](https://marketplace.visualstudio.com/items?itemName=attilabuti.vscode-mjml) installed in your VS Code.
Once you have the MJML extension installed, you can create a new email template in the `src` directory. After creating the new email template and with the `.mjml` file open in your editor, open the command palette with `Ctrl+Shift+P` and search for `MJML: Export to HTML`. This will convert the `.mjml` file to a `.html` file and now you can save it in the build directory.
+10 -5
View File
@@ -1,9 +1,14 @@
from fastapi import APIRouter from fastapi import APIRouter
from app.api.routes import items, login, users, utils from app.api.routes import items, login, private, users, utils
from app.core.config import settings
api_router = APIRouter() api_router = APIRouter()
api_router.include_router(login.router, tags=["login"]) api_router.include_router(login.router)
api_router.include_router(users.router, prefix="/users", tags=["users"]) api_router.include_router(users.router)
api_router.include_router(utils.router, prefix="/utils", tags=["utils"]) api_router.include_router(utils.router)
api_router.include_router(items.router, prefix="/items", tags=["items"]) api_router.include_router(items.router)
if settings.ENVIRONMENT == "local":
api_router.include_router(private.router)
+1 -1
View File
@@ -7,7 +7,7 @@ from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep from app.api.deps import CurrentUser, SessionDep
from app.models import Item, ItemCreate, ItemPublic, ItemsPublic, ItemUpdate, Message from app.models import Item, ItemCreate, ItemPublic, ItemsPublic, ItemUpdate, Message
router = APIRouter() router = APIRouter(prefix="/items", tags=["items"])
@router.get("/", response_model=ItemsPublic) @router.get("/", response_model=ItemsPublic)
+1 -1
View File
@@ -18,7 +18,7 @@ from app.utils import (
verify_password_reset_token, verify_password_reset_token,
) )
router = APIRouter() router = APIRouter(tags=["login"])
@router.post("/login/access-token") @router.post("/login/access-token")
+38
View File
@@ -0,0 +1,38 @@
from typing import Any
from fastapi import APIRouter
from pydantic import BaseModel
from app.api.deps import SessionDep
from app.core.security import get_password_hash
from app.models import (
User,
UserPublic,
)
router = APIRouter(tags=["private"], prefix="/private")
class PrivateUserCreate(BaseModel):
email: str
password: str
full_name: str
is_verified: bool = False
@router.post("/users/", response_model=UserPublic)
def create_user(user_in: PrivateUserCreate, session: SessionDep) -> Any:
"""
Create a new user.
"""
user = User(
email=user_in.email,
full_name=user_in.full_name,
hashed_password=get_password_hash(user_in.password),
)
session.add(user)
session.commit()
return user
+1 -3
View File
@@ -26,7 +26,7 @@ from app.models import (
) )
from app.utils import generate_new_account_email, send_email from app.utils import generate_new_account_email, send_email
router = APIRouter() router = APIRouter(prefix="/users", tags=["users"])
@router.get( @router.get(
@@ -134,8 +134,6 @@ def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
raise HTTPException( raise HTTPException(
status_code=403, detail="Super users are not allowed to delete themselves" status_code=403, detail="Super users are not allowed to delete themselves"
) )
statement = delete(Item).where(col(Item.owner_id) == current_user.id)
session.exec(statement) # type: ignore
session.delete(current_user) session.delete(current_user)
session.commit() session.commit()
return Message(message="User deleted successfully") return Message(message="User deleted successfully")
+6 -1
View File
@@ -5,7 +5,7 @@ from app.api.deps import get_current_active_superuser
from app.models import Message from app.models import Message
from app.utils import generate_test_email, send_email from app.utils import generate_test_email, send_email
router = APIRouter() router = APIRouter(prefix="/utils", tags=["utils"])
@router.post( @router.post(
@@ -24,3 +24,8 @@ def test_email(email_to: EmailStr) -> Message:
html_content=email_data.html_content, html_content=email_data.html_content,
) )
return Message(message="Test email sent") return Message(message="Test email sent")
@router.get("/health-check/")
async def health_check() -> bool:
return True
+17 -17
View File
@@ -5,6 +5,7 @@ from typing import Annotated, Any, Literal
from pydantic import ( from pydantic import (
AnyUrl, AnyUrl,
BeforeValidator, BeforeValidator,
EmailStr,
HttpUrl, HttpUrl,
PostgresDsn, PostgresDsn,
computed_field, computed_field,
@@ -25,27 +26,29 @@ def parse_cors(v: Any) -> list[str] | str:
class Settings(BaseSettings): class Settings(BaseSettings):
model_config = SettingsConfigDict( model_config = SettingsConfigDict(
env_file=".env", env_ignore_empty=True, extra="ignore" # Use top level .env file (one level above ./backend/)
env_file="../.env",
env_ignore_empty=True,
extra="ignore",
) )
API_V1_STR: str = "/api/v1" API_V1_STR: str = "/api/v1"
SECRET_KEY: str = secrets.token_urlsafe(32) SECRET_KEY: str = secrets.token_urlsafe(32)
# 60 minutes * 24 hours * 8 days = 8 days # 60 minutes * 24 hours * 8 days = 8 days
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
DOMAIN: str = "localhost" FRONTEND_HOST: str = "http://localhost:5173"
ENVIRONMENT: Literal["local", "staging", "production"] = "local" ENVIRONMENT: Literal["local", "staging", "production"] = "local"
@computed_field # type: ignore[prop-decorator]
@property
def server_host(self) -> str:
# Use HTTPS for anything other than local development
if self.ENVIRONMENT == "local":
return f"http://{self.DOMAIN}"
return f"https://{self.DOMAIN}"
BACKEND_CORS_ORIGINS: Annotated[ BACKEND_CORS_ORIGINS: Annotated[
list[AnyUrl] | str, BeforeValidator(parse_cors) list[AnyUrl] | str, BeforeValidator(parse_cors)
] = [] ] = []
@computed_field # type: ignore[prop-decorator]
@property
def all_cors_origins(self) -> list[str]:
return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [
self.FRONTEND_HOST
]
PROJECT_NAME: str PROJECT_NAME: str
SENTRY_DSN: HttpUrl | None = None SENTRY_DSN: HttpUrl | None = None
POSTGRES_SERVER: str POSTGRES_SERVER: str
@@ -72,9 +75,8 @@ class Settings(BaseSettings):
SMTP_HOST: str | None = None SMTP_HOST: str | None = None
SMTP_USER: str | None = None SMTP_USER: str | None = None
SMTP_PASSWORD: str | None = None SMTP_PASSWORD: str | None = None
# TODO: update type to EmailStr when sqlmodel supports it EMAILS_FROM_EMAIL: EmailStr | None = None
EMAILS_FROM_EMAIL: str | None = None EMAILS_FROM_NAME: EmailStr | None = None
EMAILS_FROM_NAME: str | None = None
@model_validator(mode="after") @model_validator(mode="after")
def _set_default_emails_from(self) -> Self: def _set_default_emails_from(self) -> Self:
@@ -89,10 +91,8 @@ class Settings(BaseSettings):
def emails_enabled(self) -> bool: def emails_enabled(self) -> bool:
return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL) return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL)
# TODO: update type to EmailStr when sqlmodel supports it EMAIL_TEST_USER: EmailStr = "test@example.com"
EMAIL_TEST_USER: str = "test@example.com" FIRST_SUPERUSER: EmailStr
# TODO: update type to EmailStr when sqlmodel supports it
FIRST_SUPERUSER: str
FIRST_SUPERUSER_PASSWORD: str FIRST_SUPERUSER_PASSWORD: str
def _check_default_secret(self, var_name: str, value: str | None) -> None: def _check_default_secret(self, var_name: str, value: str | None) -> None:
-1
View File
@@ -18,7 +18,6 @@ def init_db(session: Session) -> None:
# the tables un-commenting the next lines # the tables un-commenting the next lines
# from sqlmodel import SQLModel # from sqlmodel import SQLModel
# from app.core.engine import engine
# This works because the models are already imported and registered from app.models # This works because the models are already imported and registered from app.models
# SQLModel.metadata.create_all(engine) # SQLModel.metadata.create_all(engine)
+2 -4
View File
@@ -21,12 +21,10 @@ app = FastAPI(
) )
# Set all CORS enabled origins # Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS: if settings.all_cors_origins:
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=[ allow_origins=settings.all_cors_origins,
str(origin).strip("/") for origin in settings.BACKEND_CORS_ORIGINS
],
allow_credentials=True, allow_credentials=True,
allow_methods=["*"], allow_methods=["*"],
allow_headers=["*"], allow_headers=["*"],
+1 -1
View File
@@ -64,7 +64,7 @@ class ItemBase(SQLModel):
# Properties to receive on item creation # Properties to receive on item creation
class ItemCreate(ItemBase): class ItemCreate(ItemBase):
title: str = Field(min_length=1, max_length=255) pass
# Properties to receive on item update # Properties to receive on item update
+26 -12
View File
@@ -1,11 +1,14 @@
from unittest.mock import patch from unittest.mock import patch
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from sqlmodel import Session, select from sqlmodel import Session
from app.core.config import settings from app.core.config import settings
from app.core.security import verify_password from app.core.security import verify_password
from app.models import User from app.crud import create_user
from app.models import UserCreate
from app.tests.utils.user import user_authentication_headers
from app.tests.utils.utils import random_email, random_lower_string
from app.utils import generate_password_reset_token from app.utils import generate_password_reset_token
@@ -69,23 +72,34 @@ def test_recovery_password_user_not_exits(
assert r.status_code == 404 assert r.status_code == 404
def test_reset_password( def test_reset_password(client: TestClient, db: Session) -> None:
client: TestClient, superuser_token_headers: dict[str, str], db: Session email = random_email()
) -> None: password = random_lower_string()
token = generate_password_reset_token(email=settings.FIRST_SUPERUSER) new_password = random_lower_string()
data = {"new_password": "changethis", "token": token}
user_create = UserCreate(
email=email,
full_name="Test User",
password=password,
is_active=True,
is_superuser=False,
)
user = create_user(session=db, user_create=user_create)
token = generate_password_reset_token(email=email)
headers = user_authentication_headers(client=client, email=email, password=password)
data = {"new_password": new_password, "token": token}
r = client.post( r = client.post(
f"{settings.API_V1_STR}/reset-password/", f"{settings.API_V1_STR}/reset-password/",
headers=superuser_token_headers, headers=headers,
json=data, json=data,
) )
assert r.status_code == 200 assert r.status_code == 200
assert r.json() == {"message": "Password updated successfully"} assert r.json() == {"message": "Password updated successfully"}
user_query = select(User).where(User.email == settings.FIRST_SUPERUSER) db.refresh(user)
user = db.exec(user_query).first() assert verify_password(new_password, user.hashed_password)
assert user
assert verify_password(data["new_password"], user.hashed_password)
def test_reset_password_invalid_token( def test_reset_password_invalid_token(
@@ -0,0 +1,26 @@
from fastapi.testclient import TestClient
from sqlmodel import Session, select
from app.core.config import settings
from app.models import User
def test_create_user(client: TestClient, db: Session) -> None:
r = client.post(
f"{settings.API_V1_STR}/private/users/",
json={
"email": "pollo@listo.com",
"password": "password123",
"full_name": "Pollo Listo",
},
)
assert r.status_code == 200
data = r.json()
user = db.exec(select(User).where(User.id == data["id"])).first()
assert user
assert user.email == "pollo@listo.com"
assert user.full_name == "Pollo Listo"
+11 -5
View File
@@ -9,8 +9,12 @@ import jwt
from jinja2 import Template from jinja2 import Template
from jwt.exceptions import InvalidTokenError from jwt.exceptions import InvalidTokenError
from app.core import security
from app.core.config import settings from app.core.config import settings
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass @dataclass
class EmailData: class EmailData:
@@ -48,7 +52,7 @@ def send_email(
if settings.SMTP_PASSWORD: if settings.SMTP_PASSWORD:
smtp_options["password"] = settings.SMTP_PASSWORD smtp_options["password"] = settings.SMTP_PASSWORD
response = message.send(to=email_to, smtp=smtp_options) response = message.send(to=email_to, smtp=smtp_options)
logging.info(f"send email result: {response}") logger.info(f"send email result: {response}")
def generate_test_email(email_to: str) -> EmailData: def generate_test_email(email_to: str) -> EmailData:
@@ -64,7 +68,7 @@ def generate_test_email(email_to: str) -> EmailData:
def generate_reset_password_email(email_to: str, email: str, token: str) -> EmailData: def generate_reset_password_email(email_to: str, email: str, token: str) -> EmailData:
project_name = settings.PROJECT_NAME project_name = settings.PROJECT_NAME
subject = f"{project_name} - Password recovery for user {email}" subject = f"{project_name} - Password recovery for user {email}"
link = f"{settings.server_host}/reset-password?token={token}" link = f"{settings.FRONTEND_HOST}/reset-password?token={token}"
html_content = render_email_template( html_content = render_email_template(
template_name="reset_password.html", template_name="reset_password.html",
context={ context={
@@ -90,7 +94,7 @@ def generate_new_account_email(
"username": username, "username": username,
"password": password, "password": password,
"email": email_to, "email": email_to,
"link": settings.server_host, "link": settings.FRONTEND_HOST,
}, },
) )
return EmailData(html_content=html_content, subject=subject) return EmailData(html_content=html_content, subject=subject)
@@ -104,14 +108,16 @@ def generate_password_reset_token(email: str) -> str:
encoded_jwt = jwt.encode( encoded_jwt = jwt.encode(
{"exp": exp, "nbf": now, "sub": email}, {"exp": exp, "nbf": now, "sub": email},
settings.SECRET_KEY, settings.SECRET_KEY,
algorithm="HS256", algorithm=security.ALGORITHM,
) )
return encoded_jwt return encoded_jwt
def verify_password_reset_token(token: str) -> str | None: def verify_password_reset_token(token: str) -> str | None:
try: try:
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) decoded_token = jwt.decode(
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
)
return str(decoded_token["sub"]) return str(decoded_token["sub"])
except InvalidTokenError: except InvalidTokenError:
return None return None
-2084
View File
File diff suppressed because it is too large Load Diff
+32 -34
View File
@@ -1,43 +1,41 @@
[tool.poetry] [project]
name = "app" name = "app"
version = "0.1.0" version = "0.1.0"
description = "" description = ""
authors = ["Admin <admin@example.com>"] requires-python = ">=3.10,<4.0"
dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
"jinja2<4.0.0,>=3.1.4",
"alembic<2.0.0,>=1.12.1",
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.0.1",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
]
[tool.poetry.dependencies] [tool.uv]
python = "^3.10" dev-dependencies = [
uvicorn = {extras = ["standard"], version = "^0.24.0.post1"} "pytest<8.0.0,>=7.4.3",
fastapi = "^0.109.1" "mypy<2.0.0,>=1.8.0",
python-multipart = "^0.0.7" "ruff<1.0.0,>=0.2.2",
email-validator = "^2.1.0.post1" "pre-commit<4.0.0,>=3.6.2",
passlib = {extras = ["bcrypt"], version = "^1.7.4"} "types-passlib<2.0.0.0,>=1.7.7.20240106",
tenacity = "^8.2.3" "coverage<8.0.0,>=7.4.3",
pydantic = ">2.0" ]
emails = "^0.6"
gunicorn = "^22.0.0"
jinja2 = "^3.1.4"
alembic = "^1.12.1"
httpx = "^0.25.1"
psycopg = {extras = ["binary"], version = "^3.1.13"}
sqlmodel = "^0.0.21"
# Pin bcrypt until passlib supports the latest
bcrypt = "4.0.1"
pydantic-settings = "^2.2.1"
sentry-sdk = {extras = ["fastapi"], version = "^1.40.6"}
pyjwt = "^2.8.0"
[tool.poetry.group.dev.dependencies]
pytest = "^7.4.3"
mypy = "^1.8.0"
ruff = "^0.2.2"
pre-commit = "^3.6.2"
types-passlib = "^1.7.7.20240106"
coverage = "^7.4.3"
[build-system] [build-system]
requires = ["poetry>=0.12"] requires = ["hatchling"]
build-backend = "poetry.masonry.api" build-backend = "hatchling.build"
[tool.mypy] [tool.mypy]
strict = true strict = true
@@ -1,10 +1,13 @@
#! /usr/bin/env bash #! /usr/bin/env bash
set -e
set -x
# Let the DB start # Let the DB start
python /app/app/backend_pre_start.py python app/backend_pre_start.py
# Run migrations # Run migrations
alembic upgrade head alembic upgrade head
# Create initial data in DB # Create initial data in DB
python /app/app/initial_data.py python app/initial_data.py
+7
View File
@@ -0,0 +1,7 @@
#! /usr/bin/env bash
set -e
set -x
python app/tests_pre_start.py
bash scripts/test.sh "$@"
-7
View File
@@ -1,7 +0,0 @@
#! /usr/bin/env bash
set -e
set -x
python /app/app/tests_pre_start.py
bash ./scripts/test.sh "$@"
+1554
View File
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -63,7 +63,6 @@ _exclude:
# Global # Global
- .vscode - .vscode
- .mypy_cache - .mypy_cache
- poetry.lock
# Python # Python
- __pycache__ - __pycache__
- app.egg-info - app.egg-info
@@ -71,7 +70,6 @@ _exclude:
- .mypy_cache - .mypy_cache
- .coverage - .coverage
- htmlcov - htmlcov
- poetry.lock
- .cache - .cache
- .venv - .venv
# Frontend # Frontend
@@ -99,4 +97,4 @@ _exclude:
_answers_file: .copier/.copier-answers.yml _answers_file: .copier/.copier-answers.yml
_tasks: _tasks:
- "python .copier/update_dotenv.py" - ["{{ _copier_python }}", .copier/update_dotenv.py]
+19 -13
View File
@@ -12,7 +12,7 @@ But you have to configure a couple things first. 🤓
* Have a remote server ready and available. * Have a remote server ready and available.
* Configure the DNS records of your domain to point to the IP of the server you just created. * Configure the DNS records of your domain to point to the IP of the server you just created.
* Configure a wildcard subdomain for your domain, so that you can have multiple subdomains for different services, e.g. `*.fastapi-project.example.com`. This will be useful for accessing different components, like `traefik.fastapi-project.example.com`, `adminer.fastapi-project.example.com`, etc. And also for `staging`, like `staging.fastapi-project.example.com`, `staging.adminer.fastapi-project.example.com`, etc. * Configure a wildcard subdomain for your domain, so that you can have multiple subdomains for different services, e.g. `*.fastapi-project.example.com`. This will be useful for accessing different components, like `dashboard.fastapi-project.example.com`, `api.fastapi-project.example.com`, `traefik.fastapi-project.example.com`, `adminer.fastapi-project.example.com`, etc. And also for `staging`, like `dashboard.staging.fastapi-project.example.com`, `adminer.staging..fastapi-project.example.com`, etc.
* Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop). * Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop).
## Public Traefik ## Public Traefik
@@ -183,22 +183,22 @@ There are already two environments configured, `staging` and `production`. 🚀
### Install GitHub Actions Runner ### Install GitHub Actions Runner
* On your remote server, if you are running as the `root` user, create a user for your GitHub Actions: * On your remote server, create a user for your GitHub Actions:
```bash ```bash
adduser github sudo adduser github
``` ```
* Add Docker permissions to the `github` user: * Add Docker permissions to the `github` user:
```bash ```bash
usermod -aG docker github sudo usermod -aG docker github
``` ```
* Temporarily switch to the `github` user: * Temporarily switch to the `github` user:
```bash ```bash
su - github sudo su - github
``` ```
* Go to the `github` user's home directory: * Go to the `github` user's home directory:
@@ -219,9 +219,15 @@ To make sure it runs on startup and continues running, you can install it as a s
exit exit
``` ```
After you do it, you would be on the `root` user again. And you will be on the previous directory, belonging to the `root` user. After you do it, you will be on the previous user again. And you will be on the previous directory, belonging to that user.
* Go to the `actions-runner` directory inside of the `github` user's home directory: Before being able to go the `github` user directory, you need to become the `root` user (you might already be):
```bash
sudo su
```
* As the `root` user, go to the `actions-runner` directory inside of the `github` user's home directory:
```bash ```bash
cd /home/github/actions-runner cd /home/github/actions-runner
@@ -284,20 +290,20 @@ Traefik UI: `https://traefik.fastapi-project.example.com`
### Production ### Production
Frontend: `https://fastapi-project.example.com` Frontend: `https://dashboard.fastapi-project.example.com`
Backend API docs: `https://fastapi-project.example.com/docs` Backend API docs: `https://api.fastapi-project.example.com/docs`
Backend API base URL: `https://fastapi-project.example.com/api/` Backend API base URL: `https://api.fastapi-project.example.com`
Adminer: `https://adminer.fastapi-project.example.com` Adminer: `https://adminer.fastapi-project.example.com`
### Staging ### Staging
Frontend: `https://staging.fastapi-project.example.com` Frontend: `https://dashboard.staging.fastapi-project.example.com`
Backend API docs: `https://staging.fastapi-project.example.com/docs` Backend API docs: `https://api.staging.fastapi-project.example.com/docs`
Backend API base URL: `https://staging.fastapi-project.example.com/api/` Backend API base URL: `https://api.staging.fastapi-project.example.com`
Adminer: `https://adminer.staging.fastapi-project.example.com` Adminer: `https://adminer.staging.fastapi-project.example.com`
+95 -63
View File
@@ -1,78 +1,100 @@
# FastAPI Project - Development # FastAPI Project - Development
## Development in `localhost` with a custom domain ## Docker Compose
You might want to use something different than `localhost` as the domain. For example, if you are having problems with cookies that need a subdomain, and Chrome is not allowing you to use `localhost`. * Start the local stack with Docker Compose:
In that case, you have two options: you could use the instructions to modify your system `hosts` file with the instructions below in **Development with a custom IP** or you can just use `localhost.tiangolo.com`, it is set up to point to `localhost` (to the IP `127.0.0.1`) and all its subdomains too. And as it is an actual domain, the browsers will store the cookies you set during development, etc. ```bash
docker compose watch
If you used the default CORS enabled domains while generating the project, `localhost.tiangolo.com` was configured to be allowed. If you didn't, you will need to add it to the list in the variable `BACKEND_CORS_ORIGINS` in the `.env` file.
To configure it in your stack, follow the section **Change the development "domain"** below, using the domain `localhost.tiangolo.com`.
After performing those steps you should be able to open: http://localhost.tiangolo.com and it will be served by your stack in `localhost`.
Check all the corresponding available URLs in the section at the end.
## Development with a custom IP
If you are running Docker in an IP address different than `127.0.0.1` (`localhost`), you will need to perform some additional steps. That will be the case if you are running a custom Virtual Machine or your Docker is located in a different machine in your network.
In that case, you will need to use a fake local domain (`dev.example.com`) and make your computer think that the domain is served by the custom IP (e.g. `192.168.99.150`).
If you have a custom domain like that, you need to add it to the list in the variable `BACKEND_CORS_ORIGINS` in the `.env` file.
* Open your `hosts` file with administrative privileges using a text editor:
* **Note for Windows**: If you are in Windows, open the main Windows menu, search for "notepad", right click on it, and select the option "open as Administrator" or similar. Then click the "File" menu, "Open file", go to the directory `c:\Windows\System32\Drivers\etc\`, select the option to show "All files" instead of only "Text (.txt) files", and open the `hosts` file.
* **Note for Mac and Linux**: Your `hosts` file is probably located at `/etc/hosts`, you can edit it in a terminal running `sudo nano /etc/hosts`.
* Additional to the contents it might have, add a new line with the custom IP (e.g. `192.168.99.150`) a space character, and your fake local domain: `dev.example.com`.
The new line might look like:
```
192.168.99.150 dev.example.com
``` ```
* Save the file. * Now you can open your browser and interact with these URLs:
* **Note for Windows**: Make sure you save the file as "All files", without an extension of `.txt`. By default, Windows tries to add the extension. Make sure the file is saved as is, without extension.
...that will make your computer think that the fake local domain is served by that custom IP, and when you open that URL in your browser, it will talk directly to your locally running server when it is asked to go to `dev.example.com` and think that it is a remote server while it is actually running in your computer. Frontend, built with Docker, with routes handled based on the path: http://localhost:5173
To configure it in your stack, follow the section **Change the development "domain"** below, using the domain `dev.example.com`. Backend, JSON based web API based on OpenAPI: http://localhost:8000
After performing those steps you should be able to open: http://dev.example.com and it will be server by your stack in `192.168.99.150`. Automatic interactive documentation with Swagger UI (from the OpenAPI backend): http://localhost:8000/docs
Check all the corresponding available URLs in the section at the end. Adminer, database web administration: http://localhost:8080
## Change the development "domain" Traefik UI, to see how the routes are being handled by the proxy: http://localhost:8090
If you need to use your local stack with a different domain than `localhost`, you need to make sure the domain you use points to the IP where your stack is set up. **Note**: The first time you start your stack, it might take a minute for it to be ready. While the backend waits for the database to be ready and configures everything. You can check the logs to monitor it.
To simplify your Docker Compose setup, for example, so that the API docs (Swagger UI) knows where is your API, you should let it know you are using that domain for development. To check the logs, run (in another terminal):
* Open the file located at `./.env`. It would have a line like: ```bash
docker compose logs
```
DOMAIN=localhost
``` ```
* Change it to the domain you are going to use, e.g.: To check the logs of a specific service, add the name of the service, e.g.:
```bash
docker compose logs backend
``` ```
## Local Development
The Docker Compose files are configured so that each of the services is available in a different port in `localhost`.
For the backend and frontend, they use the same port that would be used by their local development server, so, the backend is at `http://localhost:8000` and the frontend at `http://localhost:5173`.
This way, you could turn off a Docker Compose service and start its local development service, and everything would keep working, because it all uses the same ports.
For example, you can stop that `frontend` service in the Docker Compose, in another terminal, run:
```bash
docker compose stop frontend
```
And then start the local frontend development server:
```bash
cd frontend
npm run dev
```
Or you could stop the `backend` Docker Compose service:
```bash
docker compose stop backend
```
And then you can run the local development server for the backend:
```bash
cd backend
fastapi dev app/main.py
```
## Docker Compose in `localhost.tiangolo.com`
When you start the Docker Compose stack, it uses `localhost` by default, with different ports for each service (backend, frontend, adminer, etc).
When you deploy it to production (or staging), it will deploy each service in a different subdomain, like `api.example.com` for the backend and `dashboard.example.com` for the frontend.
In the guide about [deployment](deployment.md) you can read about Traefik, the configured proxy. That's the component in charge of transmitting traffic to each service based on the subdomain.
If you want to test that it's all working locally, you can edit the local `.env` file, and change:
```dotenv
DOMAIN=localhost.tiangolo.com DOMAIN=localhost.tiangolo.com
``` ```
That variable will be used by the Docker Compose files. That will be used by the Docker Compose files to configure the base domain for the services.
After that, you can restart your stack with: Traefik will use this to transmit traffic at `api.localhost.tiangolo.com` to the backend, and traffic at `dashboard.localhost.tiangolo.com` to the frontend.
The domain `localhost.tiangolo.com` is a special domain that is configured (with all its subdomains) to point to `127.0.0.1`. This way you can use that for your local development.
After you update it, run again:
```bash ```bash
docker compose up -d docker compose watch
``` ```
and check all the corresponding available URLs in the section at the end. When deploying, for example in production, the main Traefik is configured outside of the Docker Compose files. For local development, there's an included Traefik in `docker-compose.override.yml`, just to let you test that the domains work as expected, for example with `api.localhost.tiangolo.com` and `dashboard.localhost.tiangolo.com`.
## Docker Compose files and env vars ## Docker Compose files and env vars
@@ -84,6 +106,12 @@ These Docker Compose files use the `.env` file containing configurations to be i
They also use some additional configurations taken from environment variables set in the scripts before calling the `docker compose` command. They also use some additional configurations taken from environment variables set in the scripts before calling the `docker compose` command.
After changing variables, make sure you restart the stack:
```bash
docker compose watch
```
## The .env file ## The .env file
The `.env` file is the one that contains all your configurations, generated keys and passwords, etc. The `.env` file is the one that contains all your configurations, generated keys and passwords, etc.
@@ -92,7 +120,7 @@ Depending on your workflow, you could want to exclude it from Git, for example i
One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file. One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file.
### Pre-commits and code linting ## Pre-commits and code linting
we are using a tool called [pre-commit](https://pre-commit.com/) for code linting and formatting. we are using a tool called [pre-commit](https://pre-commit.com/) for code linting and formatting.
@@ -106,10 +134,10 @@ You can find a file `.pre-commit-config.yaml` with configurations at the root of
After having the `pre-commit` tool installed and available, you need to "install" it in the local repository, so that it runs automatically before each commit. After having the `pre-commit` tool installed and available, you need to "install" it in the local repository, so that it runs automatically before each commit.
Using Poetry, you could do it with: Using `uv`, you could do it with:
```bash ```bash
❯ poetry run pre-commit install ❯ uv run pre-commit install
pre-commit installed at .git/hooks/pre-commit pre-commit installed at .git/hooks/pre-commit
``` ```
@@ -125,10 +153,10 @@ Then you can `git add` the modified/fixed files again and now you can commit.
#### Running pre-commit hooks manually #### Running pre-commit hooks manually
you can also run `pre-commit` manually on all the files, you can do it using Poetry with: you can also run `pre-commit` manually on all the files, you can do it using `uv` with:
```bash ```bash
❯ poetry run pre-commit run --all-files ❯ uv run pre-commit run --all-files
check for added large files..............................................Passed check for added large files..............................................Passed
check toml...............................................................Passed check toml...............................................................Passed
check yaml...............................................................Passed check yaml...............................................................Passed
@@ -146,30 +174,34 @@ The production or staging URLs would use these same paths, but with your own dom
Development URLs, for local development. Development URLs, for local development.
Frontend: http://localhost Frontend: http://localhost:5173
Backend: http://localhost/api/ Backend: http://localhost:8000
Automatic Interactive Docs (Swagger UI): http://localhost/docs Automatic Interactive Docs (Swagger UI): http://localhost:8000/docs
Automatic Alternative Docs (ReDoc): http://localhost/redoc Automatic Alternative Docs (ReDoc): http://localhost:8000/redoc
Adminer: http://localhost:8080 Adminer: http://localhost:8080
Traefik UI: http://localhost:8090 Traefik UI: http://localhost:8090
### Development in localhost with a custom domain URLs MailCatcher: http://localhost:1080
### Development URLs with `localhost.tiangolo.com` Configured
Development URLs, for local development. Development URLs, for local development.
Frontend: http://localhost.tiangolo.com Frontend: http://dashboard.localhost.tiangolo.com
Backend: http://localhost.tiangolo.com/api/ Backend: http://api.localhost.tiangolo.com
Automatic Interactive Docs (Swagger UI): http://localhost.tiangolo.com/docs Automatic Interactive Docs (Swagger UI): http://api.localhost.tiangolo.com/docs
Automatic Alternative Docs (ReDoc): http://localhost.tiangolo.com/redoc Automatic Alternative Docs (ReDoc): http://api.localhost.tiangolo.com/redoc
Adminer: http://localhost.tiangolo.com:8080 Adminer: http://localhost.tiangolo.com:8080
Traefik UI: http://localhost.tiangolo.com:8090 Traefik UI: http://localhost.tiangolo.com:8090
MailCatcher: http://localhost.tiangolo.com:1080
+52 -7
View File
@@ -1,5 +1,10 @@
services: services:
# Local services are available on their ports, but also available on:
# http://api.localhost.tiangolo.com: backend
# http://dashboard.localhost.tiangolo.com: frontend
# etc. To enable it, update .env, set:
# DOMAIN=localhost.tiangolo.com
proxy: proxy:
image: traefik:3.0 image: traefik:3.0
volumes: volumes:
@@ -53,15 +58,28 @@ services:
backend: backend:
restart: "no" restart: "no"
ports: ports:
- "8888:8888" - "8000:8000"
volumes:
- ./backend/:/app
build: build:
context: ./backend context: ./backend
args:
INSTALL_DEV: ${INSTALL_DEV-true}
# command: sleep infinity # Infinite loop to keep container alive doing nothing # command: sleep infinity # Infinite loop to keep container alive doing nothing
command: /start-reload.sh command:
- fastapi
- run
- --reload
- "app/main.py"
develop:
watch:
- path: ./backend
action: sync
target: /app
ignore:
- ./backend/.venv
- .venv
- path: ./backend/pyproject.toml
action: rebuild
# TODO: remove once coverage is done locally
volumes:
- ./backend/htmlcov:/app/htmlcov
environment: environment:
SMTP_HOST: "mailcatcher" SMTP_HOST: "mailcatcher"
SMTP_PORT: "1025" SMTP_PORT: "1025"
@@ -76,12 +94,39 @@ services:
frontend: frontend:
restart: "no" restart: "no"
ports:
- "5173:80"
build: build:
context: ./frontend context: ./frontend
args: args:
- VITE_API_URL=http://${DOMAIN?Variable not set} - VITE_API_URL=http://localhost:8000
- NODE_ENV=development - NODE_ENV=development
playwright:
build:
context: ./frontend
dockerfile: Dockerfile.playwright
args:
- VITE_API_URL=http://backend:8000
- NODE_ENV=production
ipc: host
depends_on:
- backend
- mailcatcher
env_file:
- .env
environment:
- VITE_API_URL=http://backend:8000
- MAILCATCHER_HOST=http://mailcatcher:1080
# For the reports when run locally
- PLAYWRIGHT_HTML_HOST=0.0.0.0
- CI=${CI}
volumes:
- ./frontend/blob-report:/app/blob-report
- ./frontend/test-results:/app/test-results
ports:
- 9323:9323
networks: networks:
traefik-public: traefik-public:
# For local dev, don't expect an external Traefik network # For local dev, don't expect an external Traefik network
+64 -23
View File
@@ -1,7 +1,14 @@
services: services:
db: db:
image: postgres:12 image: postgres:12
restart: always restart: always
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
retries: 5
start_period: 30s
timeout: 10s
volumes: volumes:
- app-db-data:/var/lib/postgresql/data/pgdata - app-db-data:/var/lib/postgresql/data/pgdata
env_file: env_file:
@@ -35,18 +42,23 @@ services:
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls.certresolver=le - traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls.certresolver=le
- traefik.http.services.${STACK_NAME?Variable not set}-adminer.loadbalancer.server.port=8080 - traefik.http.services.${STACK_NAME?Variable not set}-adminer.loadbalancer.server.port=8080
backend: prestart:
image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}' image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}'
restart: always build:
context: ./backend
networks: networks:
- traefik-public - traefik-public
- default - default
depends_on: depends_on:
- db db:
condition: service_healthy
restart: true
command: bash scripts/prestart.sh
env_file: env_file:
- .env - .env
environment: environment:
- DOMAIN=${DOMAIN} - DOMAIN=${DOMAIN}
- FRONTEND_HOST=${FRONTEND_HOST?Variable not set}
- ENVIRONMENT=${ENVIRONMENT} - ENVIRONMENT=${ENVIRONMENT}
- BACKEND_CORS_ORIGINS=${BACKEND_CORS_ORIGINS} - BACKEND_CORS_ORIGINS=${BACKEND_CORS_ORIGINS}
- SECRET_KEY=${SECRET_KEY?Variable not set} - SECRET_KEY=${SECRET_KEY?Variable not set}
@@ -63,34 +75,64 @@ services:
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set}
- SENTRY_DSN=${SENTRY_DSN} - SENTRY_DSN=${SENTRY_DSN}
backend:
image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}'
restart: always
networks:
- traefik-public
- default
depends_on:
db:
condition: service_healthy
restart: true
prestart:
condition: service_completed_successfully
env_file:
- .env
environment:
- DOMAIN=${DOMAIN}
- FRONTEND_HOST=${FRONTEND_HOST?Variable not set}
- ENVIRONMENT=${ENVIRONMENT}
- BACKEND_CORS_ORIGINS=${BACKEND_CORS_ORIGINS}
- SECRET_KEY=${SECRET_KEY?Variable not set}
- FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set}
- FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set}
- SMTP_HOST=${SMTP_HOST}
- SMTP_USER=${SMTP_USER}
- SMTP_PASSWORD=${SMTP_PASSWORD}
- EMAILS_FROM_EMAIL=${EMAILS_FROM_EMAIL}
- POSTGRES_SERVER=db
- POSTGRES_PORT=${POSTGRES_PORT}
- POSTGRES_DB=${POSTGRES_DB}
- POSTGRES_USER=${POSTGRES_USER?Variable not set}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set}
- SENTRY_DSN=${SENTRY_DSN}
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/api/v1/utils/health-check/"]
interval: 10s
timeout: 5s
retries: 5
build: build:
context: ./backend context: ./backend
args:
INSTALL_DEV: ${INSTALL_DEV-false}
platform: linux/amd64 # Patch for M1 Mac
labels: labels:
- traefik.enable=true - traefik.enable=true
- traefik.docker.network=traefik-public - traefik.docker.network=traefik-public
- traefik.constraint-label=traefik-public - traefik.constraint-label=traefik-public
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80 - traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=8000
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.rule=(Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)) && (PathPrefix(`/api`) || PathPrefix(`/docs`) || PathPrefix(`/redoc`)) - traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.rule=Host(`api.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.entrypoints=http - traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=(Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)) && (PathPrefix(`/api`) || PathPrefix(`/docs`) || PathPrefix(`/redoc`)) - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=Host(`api.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.entrypoints=https - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le
# Define Traefik Middleware to handle domain with and without "www" to redirect to only one # Enable redirection for HTTP and HTTPS
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.regex=^http(s)?://www.(${DOMAIN?Variable not set})/(.*) - traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect
# Redirect a domain with www to non-www
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.replacement=http$${1}://${DOMAIN?Variable not set}/$${3}
# Enable www redirection for HTTP and HTTPS
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
frontend: frontend:
image: '${DOCKER_IMAGE_FRONTEND?Variable not set}:${TAG-latest}' image: '${DOCKER_IMAGE_FRONTEND?Variable not set}:${TAG-latest}'
@@ -101,7 +143,7 @@ services:
build: build:
context: ./frontend context: ./frontend
args: args:
- VITE_API_URL=https://${DOMAIN?Variable not set} - VITE_API_URL=https://api.${DOMAIN?Variable not set}
- NODE_ENV=production - NODE_ENV=production
labels: labels:
- traefik.enable=true - traefik.enable=true
@@ -110,17 +152,16 @@ services:
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80 - traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`dashboard.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.entrypoints=http - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`dashboard.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.entrypoints=https - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le
# Enable www redirection for HTTP and HTTPS # Enable redirection for HTTP and HTTPS
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
volumes: volumes:
app-db-data: app-db-data:
+2 -1
View File
@@ -1 +1,2 @@
VITE_API_URL=http://localhost VITE_API_URL=http://localhost:8000
MAILCATCHER_HOST=http://localhost:1080
+1
View File
@@ -27,3 +27,4 @@ openapi.json
/playwright-report/ /playwright-report/
/blob-report/ /blob-report/
/playwright/.cache/ /playwright/.cache/
/playwright/.auth/
+13
View File
@@ -0,0 +1,13 @@
FROM node:20
WORKDIR /app
COPY package*.json /app/
RUN npm install
RUN npx -y playwright install --with-deps
COPY ./ /app/
ARG VITE_API_URL=${VITE_API_URL}
+19 -12
View File
@@ -4,7 +4,7 @@ The frontend is built with [Vite](https://vitejs.dev/), [React](https://reactjs.
## Frontend development ## Frontend development
Before you begin, ensure that you have either the Node Version Manager (nvm) or Fast Node Manager (fnm) installed on your system. Before you begin, ensure that you have either the Node Version Manager (nvm) or Fast Node Manager (fnm) installed on your system.
* To install fnm follow the [official fnm guide](https://github.com/Schniz/fnm#installation). If you prefer nvm, you can install it using the [official nvm guide](https://github.com/nvm-sh/nvm#installing-and-updating). * To install fnm follow the [official fnm guide](https://github.com/Schniz/fnm#installation). If you prefer nvm, you can install it using the [official nvm guide](https://github.com/nvm-sh/nvm#installing-and-updating).
@@ -27,7 +27,7 @@ nvm install
```bash ```bash
# If using fnm # If using fnm
fnm use fnm use
# If using nvm # If using nvm
nvm use nvm use
@@ -59,7 +59,7 @@ If you are developing an API-only app and want to remove the frontend, you can d
* In the `docker-compose.yml` file, remove the whole service / section `frontend`. * In the `docker-compose.yml` file, remove the whole service / section `frontend`.
* In the `docker-compose.override.yml` file, remove the whole service / section `frontend`. * In the `docker-compose.override.yml` file, remove the whole service / section `frontend` and `playwright`.
Done, you have a frontend-less (api-only) app. 🤓 Done, you have a frontend-less (api-only) app. 🤓
@@ -74,16 +74,23 @@ But it would be only to clean them up, leaving them won't really have any effect
## Generate Client ## Generate Client
### Automatically
* Activate the backend virtual environment.
* From the top level project directory, run the script:
```bash
./scripts/generate-client.sh
```
* Commit the changes.
### Manually
* Start the Docker Compose stack. * Start the Docker Compose stack.
* Download the OpenAPI JSON file from `http://localhost/api/v1/openapi.json` and copy it to a new file `openapi.json` at the root of the `frontend` directory. * Download the OpenAPI JSON file from `http://localhost/api/v1/openapi.json` and copy it to a new file `openapi.json` at the root of the `frontend` directory.
* To simplify the names in the generated frontend client code, modify the `openapi.json` file by running the following script:
```bash
node modify-openapi-operationids.js
```
* To generate the frontend client, run: * To generate the frontend client, run:
```bash ```bash
@@ -99,7 +106,7 @@ Notice that everytime the backend changes (changing the OpenAPI schema), you sho
If you want to use a remote API, you can set the environment variable `VITE_API_URL` to the URL of the remote API. For example, you can set it in the `frontend/.env` file: If you want to use a remote API, you can set the environment variable `VITE_API_URL` to the URL of the remote API. For example, you can set it in the `frontend/.env` file:
```env ```env
VITE_API_URL=https://my-remote-api.example.com VITE_API_URL=https://api.my-domain.example.com
``` ```
Then, when you run the frontend, it will use that URL as the base URL for the API. Then, when you run the frontend, it will use that URL as the base URL for the API.
@@ -121,7 +128,7 @@ The frontend code is structured as follows:
The frontend includes initial end-to-end tests using Playwright. To run the tests, you need to have the Docker Compose stack running. Start the stack with the following command: The frontend includes initial end-to-end tests using Playwright. To run the tests, you need to have the Docker Compose stack running. Start the stack with the following command:
```bash ```bash
docker compose up -d docker compose up -d --wait backend
``` ```
Then, you can run the tests with the following command: Then, you can run the tests with the following command:
@@ -144,4 +151,4 @@ docker compose down -v
To update the tests, navigate to the tests directory and modify the existing test files or add new ones as needed. To update the tests, navigate to the tests directory and modify the existing test files or add new ones as needed.
For more information on writing and running Playwright tests, refer to the official [Playwright documentation](https://playwright.dev/docs/intro). For more information on writing and running Playwright tests, refer to the official [Playwright documentation](https://playwright.dev/docs/intro).
-1
View File
@@ -6,7 +6,6 @@
"files": { "files": {
"ignore": [ "ignore": [
"node_modules", "node_modules",
"src/client/",
"src/routeTree.gen.ts", "src/routeTree.gen.ts",
"playwright.config.ts", "playwright.config.ts",
"playwright-report" "playwright-report"
-36
View File
@@ -1,36 +0,0 @@
import * as fs from "node:fs"
async function modifyOpenAPIFile(filePath) {
try {
const data = await fs.promises.readFile(filePath)
const openapiContent = JSON.parse(data)
const paths = openapiContent.paths
for (const pathKey of Object.keys(paths)) {
const pathData = paths[pathKey]
for (const method of Object.keys(pathData)) {
const operation = pathData[method]
if (operation.tags && operation.tags.length > 0) {
const tag = operation.tags[0]
const operationId = operation.operationId
const toRemove = `${tag}-`
if (operationId.startsWith(toRemove)) {
const newOperationId = operationId.substring(toRemove.length)
operation.operationId = newOperationId
}
}
}
}
await fs.promises.writeFile(
filePath,
JSON.stringify(openapiContent, null, 2),
)
console.log("File successfully modified")
} catch (err) {
console.error("Error:", err)
}
}
const filePath = "./openapi.json"
modifyOpenAPIFile(filePath)
+28
View File
@@ -0,0 +1,28 @@
import { defineConfig } from "@hey-api/openapi-ts"
export default defineConfig({
client: "legacy/axios",
input: "./openapi.json",
output: "./src/client",
// exportSchemas: true,
plugins: [
{
name: "@hey-api/sdk",
// NOTE: this doesn't allow tree-shaking
asClass: true,
operationId: true,
methodNameBuilder: (operation) => {
// @ts-ignore
let name: string = operation.name
// @ts-ignore
const service: string = operation.service
if (service && name.toLowerCase().startsWith(service.toLowerCase())) {
name = name.slice(service.length)
}
return name.charAt(0).toLowerCase() + name.slice(1)
},
},
],
})
+3408 -3154
View File
File diff suppressed because it is too large Load Diff
+9 -11
View File
@@ -5,31 +5,29 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc && vite build", "build": "tsc -p tsconfig.build.json && vite build",
"lint": "biome check --apply-unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./", "lint": "biome check --apply-unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./",
"preview": "vite preview", "preview": "vite preview",
"generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios --exportSchemas true && biome format --write ./src/client" "generate-client": "openapi-ts"
}, },
"dependencies": { "dependencies": {
"@chakra-ui/icons": "2.1.1", "@chakra-ui/react": "^3.8.0",
"@chakra-ui/react": "2.8.2", "@emotion/react": "^11.14.0",
"@emotion/react": "11.11.3",
"@emotion/styled": "11.11.0",
"@tanstack/react-query": "^5.28.14", "@tanstack/react-query": "^5.28.14",
"@tanstack/react-query-devtools": "^5.28.14", "@tanstack/react-query-devtools": "^5.28.14",
"@tanstack/react-router": "1.19.1", "@tanstack/react-router": "1.19.1",
"axios": "1.6.2", "axios": "1.7.4",
"form-data": "4.0.0", "form-data": "4.0.0",
"framer-motion": "10.16.16", "next-themes": "^0.4.4",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-error-boundary": "^4.0.13", "react-error-boundary": "^4.0.13",
"react-hook-form": "7.49.3", "react-hook-form": "7.49.3",
"react-icons": "5.0.1" "react-icons": "^5.4.0"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "1.6.1", "@biomejs/biome": "1.6.1",
"@hey-api/openapi-ts": "^0.34.1", "@hey-api/openapi-ts": "^0.57.0",
"@playwright/test": "^1.45.2", "@playwright/test": "^1.45.2",
"@tanstack/router-devtools": "1.19.1", "@tanstack/router-devtools": "1.19.1",
"@tanstack/router-vite-plugin": "1.19.0", "@tanstack/router-vite-plugin": "1.19.0",
@@ -39,6 +37,6 @@
"@vitejs/plugin-react-swc": "^3.5.0", "@vitejs/plugin-react-swc": "^3.5.0",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"typescript": "^5.2.2", "typescript": "^5.2.2",
"vite": "^5.0.13" "vite": "^5.4.14"
} }
} }
+2 -3
View File
@@ -1,11 +1,10 @@
import { defineConfig, devices } from '@playwright/test'; import { defineConfig, devices } from '@playwright/test';
import 'dotenv/config'
/** /**
* Read environment variables from file. * Read environment variables from file.
* https://github.com/motdotla/dotenv * https://github.com/motdotla/dotenv
*/ */
// require('dotenv').config();
/** /**
* See https://playwright.dev/docs/test-configuration. * See https://playwright.dev/docs/test-configuration.
@@ -21,7 +20,7 @@ export default defineConfig({
/* Opt out of parallel tests on CI. */ /* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined, workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */ /* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html', reporter: process.env.CI ? 'blob' : 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: { use: {
/* Base URL to use in actions like `await page.goto('/')`. */ /* Base URL to use in actions like `await page.goto('/')`. */
+17 -16
View File
@@ -1,20 +1,21 @@
export type ApiRequestOptions = { export type ApiRequestOptions<T = unknown> = {
readonly method:
| "GET"
| "PUT"
| "POST"
| "DELETE"
| "OPTIONS"
| "HEAD"
| "PATCH"
readonly url: string
readonly path?: Record<string, unknown>
readonly cookies?: Record<string, unknown>
readonly headers?: Record<string, unknown>
readonly query?: Record<string, unknown>
readonly formData?: Record<string, unknown>
readonly body?: any readonly body?: any
readonly cookies?: Record<string, unknown>
readonly errors?: Record<number | string, string>
readonly formData?: Record<string, unknown> | any[] | Blob | File
readonly headers?: Record<string, unknown>
readonly mediaType?: string readonly mediaType?: string
readonly method:
| "DELETE"
| "GET"
| "HEAD"
| "OPTIONS"
| "PATCH"
| "POST"
| "PUT"
readonly path?: Record<string, unknown>
readonly query?: Record<string, unknown>
readonly responseHeader?: string readonly responseHeader?: string
readonly errors?: Record<number, string> readonly responseTransformer?: (data: unknown) => Promise<T>
readonly url: string
} }
+7 -7
View File
@@ -1,10 +1,9 @@
import type { AxiosRequestConfig, AxiosResponse } from "axios" import type { AxiosRequestConfig, AxiosResponse } from "axios"
import type { ApiRequestOptions } from "./ApiRequestOptions" import type { ApiRequestOptions } from "./ApiRequestOptions"
import type { TResult } from "./types"
type Headers = Record<string, string> type Headers = Record<string, string>
type Middleware<T> = (value: T) => T | Promise<T> type Middleware<T> = (value: T) => T | Promise<T>
type Resolver<T> = (options: ApiRequestOptions) => Promise<T> type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>
export class Interceptors<T> { export class Interceptors<T> {
_fns: Middleware<T>[] _fns: Middleware<T>[]
@@ -13,14 +12,14 @@ export class Interceptors<T> {
this._fns = [] this._fns = []
} }
eject(fn: Middleware<T>) { eject(fn: Middleware<T>): void {
const index = this._fns.indexOf(fn) const index = this._fns.indexOf(fn)
if (index !== -1) { if (index !== -1) {
this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)] this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]
} }
} }
use(fn: Middleware<T>) { use(fn: Middleware<T>): void {
this._fns = [...this._fns, fn] this._fns = [...this._fns, fn]
} }
} }
@@ -31,7 +30,6 @@ export type OpenAPIConfig = {
ENCODE_PATH?: ((path: string) => string) | undefined ENCODE_PATH?: ((path: string) => string) | undefined
HEADERS?: Headers | Resolver<Headers> | undefined HEADERS?: Headers | Resolver<Headers> | undefined
PASSWORD?: string | Resolver<string> | undefined PASSWORD?: string | Resolver<string> | undefined
RESULT?: TResult
TOKEN?: string | Resolver<string> | undefined TOKEN?: string | Resolver<string> | undefined
USERNAME?: string | Resolver<string> | undefined USERNAME?: string | Resolver<string> | undefined
VERSION: string VERSION: string
@@ -48,10 +46,12 @@ export const OpenAPI: OpenAPIConfig = {
ENCODE_PATH: undefined, ENCODE_PATH: undefined,
HEADERS: undefined, HEADERS: undefined,
PASSWORD: undefined, PASSWORD: undefined,
RESULT: "body",
TOKEN: undefined, TOKEN: undefined,
USERNAME: undefined, USERNAME: undefined,
VERSION: "0.1.0", VERSION: "0.1.0",
WITH_CREDENTIALS: false, WITH_CREDENTIALS: false,
interceptors: { request: new Interceptors(), response: new Interceptors() }, interceptors: {
request: new Interceptors(),
response: new Interceptors(),
},
} }
+22 -11
View File
@@ -1,9 +1,9 @@
import axios from "axios" import axios from "axios"
import type { import type {
AxiosError, AxiosError,
AxiosInstance,
AxiosRequestConfig, AxiosRequestConfig,
AxiosResponse, AxiosResponse,
AxiosInstance,
} from "axios" } from "axios"
import { ApiError } from "./ApiError" import { ApiError } from "./ApiError"
@@ -54,7 +54,9 @@ export const getQueryString = (params: Record<string, unknown>): string => {
return return
} }
if (Array.isArray(value)) { if (value instanceof Date) {
append(key, value.toISOString())
} else if (Array.isArray(value)) {
value.forEach((v) => encodePair(key, v)) value.forEach((v) => encodePair(key, v))
} else if (typeof value === "object") { } else if (typeof value === "object") {
Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)) Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v))
@@ -113,10 +115,10 @@ export const getFormData = (
return undefined return undefined
} }
type Resolver<T> = (options: ApiRequestOptions) => Promise<T> type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>
export const resolve = async <T>( export const resolve = async <T>(
options: ApiRequestOptions, options: ApiRequestOptions<T>,
resolver?: T | Resolver<T>, resolver?: T | Resolver<T>,
): Promise<T | undefined> => { ): Promise<T | undefined> => {
if (typeof resolver === "function") { if (typeof resolver === "function") {
@@ -125,14 +127,18 @@ export const resolve = async <T>(
return resolver return resolver
} }
export const getHeaders = async ( export const getHeaders = async <T>(
config: OpenAPIConfig, config: OpenAPIConfig,
options: ApiRequestOptions, options: ApiRequestOptions<T>,
): Promise<Record<string, string>> => { ): Promise<Record<string, string>> => {
const [token, username, password, additionalHeaders] = await Promise.all([ const [token, username, password, additionalHeaders] = await Promise.all([
// @ts-ignore
resolve(options, config.TOKEN), resolve(options, config.TOKEN),
// @ts-ignore
resolve(options, config.USERNAME), resolve(options, config.USERNAME),
// @ts-ignore
resolve(options, config.PASSWORD), resolve(options, config.PASSWORD),
// @ts-ignore
resolve(options, config.HEADERS), resolve(options, config.HEADERS),
]) ])
@@ -151,12 +157,12 @@ export const getHeaders = async (
) )
if (isStringWithValue(token)) { if (isStringWithValue(token)) {
headers.Authorization = `Bearer ${token}` headers["Authorization"] = `Bearer ${token}`
} }
if (isStringWithValue(username) && isStringWithValue(password)) { if (isStringWithValue(username) && isStringWithValue(password)) {
const credentials = base64(`${username}:${password}`) const credentials = base64(`${username}:${password}`)
headers.Authorization = `Basic ${credentials}` headers["Authorization"] = `Basic ${credentials}`
} }
if (options.body !== undefined) { if (options.body !== undefined) {
@@ -187,7 +193,7 @@ export const getRequestBody = (options: ApiRequestOptions): unknown => {
export const sendRequest = async <T>( export const sendRequest = async <T>(
config: OpenAPIConfig, config: OpenAPIConfig,
options: ApiRequestOptions, options: ApiRequestOptions<T>,
url: string, url: string,
body: unknown, body: unknown,
formData: FormData | undefined, formData: FormData | undefined,
@@ -325,7 +331,7 @@ export const catchErrorCodes = (
*/ */
export const request = <T>( export const request = <T>(
config: OpenAPIConfig, config: OpenAPIConfig,
options: ApiRequestOptions, options: ApiRequestOptions<T>,
axiosClient: AxiosInstance = axios, axiosClient: AxiosInstance = axios,
): CancelablePromise<T> => { ): CancelablePromise<T> => {
return new CancelablePromise(async (resolve, reject, onCancel) => { return new CancelablePromise(async (resolve, reject, onCancel) => {
@@ -357,12 +363,17 @@ export const request = <T>(
options.responseHeader, options.responseHeader,
) )
let transformedBody = responseBody
if (options.responseTransformer && isSuccess(response.status)) {
transformedBody = await options.responseTransformer(responseBody)
}
const result: ApiResult = { const result: ApiResult = {
url, url,
ok: isSuccess(response.status), ok: isSuccess(response.status),
status: response.status, status: response.status,
statusText: response.statusText, statusText: response.statusText,
body: responseHeader ?? responseBody, body: responseHeader ?? transformedBody,
} }
catchErrorCodes(options, result) catchErrorCodes(options, result)
-14
View File
@@ -1,14 +0,0 @@
import type { ApiResult } from "./ApiResult"
export type TResult = "body" | "raw"
export type TApiResponse<T extends TResult, TData> = Exclude<
T,
"raw"
> extends never
? ApiResult<TData>
: ApiResult<TData>["body"]
export type TConfig<T extends TResult> = {
_result?: T
}
+4 -6
View File
@@ -1,8 +1,6 @@
// This file is auto-generated by @hey-api/openapi-ts
export { ApiError } from "./core/ApiError" export { ApiError } from "./core/ApiError"
export { CancelablePromise, CancelError } from "./core/CancelablePromise" export { CancelablePromise, CancelError } from "./core/CancelablePromise"
export { OpenAPI } from "./core/OpenAPI" export { OpenAPI, type OpenAPIConfig } from "./core/OpenAPI"
export type { OpenAPIConfig } from "./core/OpenAPI" export * from "./sdk.gen"
export * from "./types.gen"
export * from "./models"
export * from "./schemas"
export * from "./services"
-99
View File
@@ -1,99 +0,0 @@
export type Body_login_login_access_token = {
grant_type?: string | null
username: string
password: string
scope?: string
client_id?: string | null
client_secret?: string | null
}
export type HTTPValidationError = {
detail?: Array<ValidationError>
}
export type ItemCreate = {
title: string
description?: string | null
}
export type ItemPublic = {
title: string
description?: string | null
id: string
owner_id: string
}
export type ItemUpdate = {
title?: string | null
description?: string | null
}
export type ItemsPublic = {
data: Array<ItemPublic>
count: number
}
export type Message = {
message: string
}
export type NewPassword = {
token: string
new_password: string
}
export type Token = {
access_token: string
token_type?: string
}
export type UpdatePassword = {
current_password: string
new_password: string
}
export type UserCreate = {
email: string
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
password: string
}
export type UserPublic = {
email: string
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
id: string
}
export type UserRegister = {
email: string
password: string
full_name?: string | null
}
export type UserUpdate = {
email?: string | null
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
password?: string | null
}
export type UserUpdateMe = {
full_name?: string | null
email?: string | null
}
export type UsersPublic = {
data: Array<UserPublic>
count: number
}
export type ValidationError = {
loc: Array<string | number>
msg: string
type: string
}
@@ -1,8 +1,9 @@
export const $Body_login_login_access_token = { // This file is auto-generated by @hey-api/openapi-ts
export const Body_login_login_access_tokenSchema = {
properties: { properties: {
grant_type: { grant_type: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
pattern: "password", pattern: "password",
@@ -11,22 +12,23 @@ export const $Body_login_login_access_token = {
type: "null", type: "null",
}, },
], ],
title: "Grant Type",
}, },
username: { username: {
type: "string", type: "string",
isRequired: true, title: "Username",
}, },
password: { password: {
type: "string", type: "string",
isRequired: true, title: "Password",
}, },
scope: { scope: {
type: "string", type: "string",
title: "Scope",
default: "", default: "",
}, },
client_id: { client_id: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
}, },
@@ -34,10 +36,10 @@ export const $Body_login_login_access_token = {
type: "null", type: "null",
}, },
], ],
title: "Client Id",
}, },
client_secret: { client_secret: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
}, },
@@ -45,32 +47,38 @@ export const $Body_login_login_access_token = {
type: "null", type: "null",
}, },
], ],
title: "Client Secret",
}, },
}, },
type: "object",
required: ["username", "password"],
title: "Body_login-login_access_token",
} as const } as const
export const $HTTPValidationError = { export const HTTPValidationErrorSchema = {
properties: { properties: {
detail: { detail: {
type: "array", items: {
contains: { $ref: "#/components/schemas/ValidationError",
type: "ValidationError",
}, },
type: "array",
title: "Detail",
}, },
}, },
type: "object",
title: "HTTPValidationError",
} as const } as const
export const $ItemCreate = { export const ItemCreateSchema = {
properties: { properties: {
title: { title: {
type: "string", type: "string",
isRequired: true,
maxLength: 255, maxLength: 255,
minLength: 1, minLength: 1,
title: "Title",
}, },
description: { description: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -79,21 +87,24 @@ export const $ItemCreate = {
type: "null", type: "null",
}, },
], ],
title: "Description",
}, },
}, },
type: "object",
required: ["title"],
title: "ItemCreate",
} as const } as const
export const $ItemPublic = { export const ItemPublicSchema = {
properties: { properties: {
title: { title: {
type: "string", type: "string",
isRequired: true,
maxLength: 255, maxLength: 255,
minLength: 1, minLength: 1,
title: "Title",
}, },
description: { description: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -102,25 +113,28 @@ export const $ItemPublic = {
type: "null", type: "null",
}, },
], ],
title: "Description",
}, },
id: { id: {
type: "string", type: "string",
isRequired: true,
format: "uuid", format: "uuid",
title: "Id",
}, },
owner_id: { owner_id: {
type: "string", type: "string",
isRequired: true,
format: "uuid", format: "uuid",
title: "Owner Id",
}, },
}, },
type: "object",
required: ["title", "id", "owner_id"],
title: "ItemPublic",
} as const } as const
export const $ItemUpdate = { export const ItemUpdateSchema = {
properties: { properties: {
title: { title: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -130,10 +144,10 @@ export const $ItemUpdate = {
type: "null", type: "null",
}, },
], ],
title: "Title",
}, },
description: { description: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -142,99 +156,119 @@ export const $ItemUpdate = {
type: "null", type: "null",
}, },
], ],
title: "Description",
}, },
}, },
type: "object",
title: "ItemUpdate",
} as const } as const
export const $ItemsPublic = { export const ItemsPublicSchema = {
properties: { properties: {
data: { data: {
type: "array", items: {
contains: { $ref: "#/components/schemas/ItemPublic",
type: "ItemPublic",
}, },
isRequired: true, type: "array",
title: "Data",
}, },
count: { count: {
type: "number", type: "integer",
isRequired: true, title: "Count",
}, },
}, },
type: "object",
required: ["data", "count"],
title: "ItemsPublic",
} as const } as const
export const $Message = { export const MessageSchema = {
properties: { properties: {
message: { message: {
type: "string", type: "string",
isRequired: true, title: "Message",
}, },
}, },
type: "object",
required: ["message"],
title: "Message",
} as const } as const
export const $NewPassword = { export const NewPasswordSchema = {
properties: { properties: {
token: { token: {
type: "string", type: "string",
isRequired: true, title: "Token",
}, },
new_password: { new_password: {
type: "string", type: "string",
isRequired: true,
maxLength: 40, maxLength: 40,
minLength: 8, minLength: 8,
title: "New Password",
}, },
}, },
type: "object",
required: ["token", "new_password"],
title: "NewPassword",
} as const } as const
export const $Token = { export const TokenSchema = {
properties: { properties: {
access_token: { access_token: {
type: "string", type: "string",
isRequired: true, title: "Access Token",
}, },
token_type: { token_type: {
type: "string", type: "string",
title: "Token Type",
default: "bearer", default: "bearer",
}, },
}, },
type: "object",
required: ["access_token"],
title: "Token",
} as const } as const
export const $UpdatePassword = { export const UpdatePasswordSchema = {
properties: { properties: {
current_password: { current_password: {
type: "string", type: "string",
isRequired: true,
maxLength: 40, maxLength: 40,
minLength: 8, minLength: 8,
title: "Current Password",
}, },
new_password: { new_password: {
type: "string", type: "string",
isRequired: true,
maxLength: 40, maxLength: 40,
minLength: 8, minLength: 8,
title: "New Password",
}, },
}, },
type: "object",
required: ["current_password", "new_password"],
title: "UpdatePassword",
} as const } as const
export const $UserCreate = { export const UserCreateSchema = {
properties: { properties: {
email: { email: {
type: "string", type: "string",
isRequired: true,
format: "email",
maxLength: 255, maxLength: 255,
format: "email",
title: "Email",
}, },
is_active: { is_active: {
type: "boolean", type: "boolean",
title: "Is Active",
default: true, default: true,
}, },
is_superuser: { is_superuser: {
type: "boolean", type: "boolean",
title: "Is Superuser",
default: false, default: false,
}, },
full_name: { full_name: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -243,35 +277,40 @@ export const $UserCreate = {
type: "null", type: "null",
}, },
], ],
title: "Full Name",
}, },
password: { password: {
type: "string", type: "string",
isRequired: true,
maxLength: 40, maxLength: 40,
minLength: 8, minLength: 8,
title: "Password",
}, },
}, },
type: "object",
required: ["email", "password"],
title: "UserCreate",
} as const } as const
export const $UserPublic = { export const UserPublicSchema = {
properties: { properties: {
email: { email: {
type: "string", type: "string",
isRequired: true,
format: "email",
maxLength: 255, maxLength: 255,
format: "email",
title: "Email",
}, },
is_active: { is_active: {
type: "boolean", type: "boolean",
title: "Is Active",
default: true, default: true,
}, },
is_superuser: { is_superuser: {
type: "boolean", type: "boolean",
title: "Is Superuser",
default: false, default: false,
}, },
full_name: { full_name: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -280,32 +319,35 @@ export const $UserPublic = {
type: "null", type: "null",
}, },
], ],
title: "Full Name",
}, },
id: { id: {
type: "string", type: "string",
isRequired: true,
format: "uuid", format: "uuid",
title: "Id",
}, },
}, },
type: "object",
required: ["email", "id"],
title: "UserPublic",
} as const } as const
export const $UserRegister = { export const UserRegisterSchema = {
properties: { properties: {
email: { email: {
type: "string", type: "string",
isRequired: true,
format: "email",
maxLength: 255, maxLength: 255,
format: "email",
title: "Email",
}, },
password: { password: {
type: "string", type: "string",
isRequired: true,
maxLength: 40, maxLength: 40,
minLength: 8, minLength: 8,
title: "Password",
}, },
full_name: { full_name: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -314,36 +356,41 @@ export const $UserRegister = {
type: "null", type: "null",
}, },
], ],
title: "Full Name",
}, },
}, },
type: "object",
required: ["email", "password"],
title: "UserRegister",
} as const } as const
export const $UserUpdate = { export const UserUpdateSchema = {
properties: { properties: {
email: { email: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
format: "email",
maxLength: 255, maxLength: 255,
format: "email",
}, },
{ {
type: "null", type: "null",
}, },
], ],
title: "Email",
}, },
is_active: { is_active: {
type: "boolean", type: "boolean",
title: "Is Active",
default: true, default: true,
}, },
is_superuser: { is_superuser: {
type: "boolean", type: "boolean",
title: "Is Superuser",
default: false, default: false,
}, },
full_name: { full_name: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -352,10 +399,10 @@ export const $UserUpdate = {
type: "null", type: "null",
}, },
], ],
title: "Full Name",
}, },
password: { password: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 40, maxLength: 40,
@@ -365,15 +412,17 @@ export const $UserUpdate = {
type: "null", type: "null",
}, },
], ],
title: "Password",
}, },
}, },
type: "object",
title: "UserUpdate",
} as const } as const
export const $UserUpdateMe = { export const UserUpdateMeSchema = {
properties: { properties: {
full_name: { full_name: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
maxLength: 255, maxLength: 255,
@@ -382,63 +431,71 @@ export const $UserUpdateMe = {
type: "null", type: "null",
}, },
], ],
title: "Full Name",
}, },
email: { email: {
type: "any-of", anyOf: [
contains: [
{ {
type: "string", type: "string",
format: "email",
maxLength: 255, maxLength: 255,
format: "email",
}, },
{ {
type: "null", type: "null",
}, },
], ],
title: "Email",
}, },
}, },
type: "object",
title: "UserUpdateMe",
} as const } as const
export const $UsersPublic = { export const UsersPublicSchema = {
properties: { properties: {
data: { data: {
type: "array", items: {
contains: { $ref: "#/components/schemas/UserPublic",
type: "UserPublic",
}, },
isRequired: true, type: "array",
title: "Data",
}, },
count: { count: {
type: "number", type: "integer",
isRequired: true, title: "Count",
}, },
}, },
type: "object",
required: ["data", "count"],
title: "UsersPublic",
} as const } as const
export const $ValidationError = { export const ValidationErrorSchema = {
properties: { properties: {
loc: { loc: {
type: "array", items: {
contains: { anyOf: [
type: "any-of",
contains: [
{ {
type: "string", type: "string",
}, },
{ {
type: "number", type: "integer",
}, },
], ],
}, },
isRequired: true, type: "array",
title: "Location",
}, },
msg: { msg: {
type: "string", type: "string",
isRequired: true, title: "Message",
}, },
type: { type: {
type: "string", type: "string",
isRequired: true, title: "Error Type",
}, },
}, },
type: "object",
required: ["loc", "msg", "type"],
title: "ValidationError",
} as const } as const
@@ -1,53 +1,188 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { CancelablePromise } from "./core/CancelablePromise" import type { CancelablePromise } from "./core/CancelablePromise"
import { OpenAPI } from "./core/OpenAPI" import { OpenAPI } from "./core/OpenAPI"
import { request as __request } from "./core/request" import { request as __request } from "./core/request"
import type { import type {
Body_login_login_access_token, ItemsReadItemsData,
ItemCreate, ItemsReadItemsResponse,
ItemPublic, ItemsCreateItemData,
ItemUpdate, ItemsCreateItemResponse,
ItemsPublic, ItemsReadItemData,
Message, ItemsReadItemResponse,
NewPassword, ItemsUpdateItemData,
Token, ItemsUpdateItemResponse,
UpdatePassword, ItemsDeleteItemData,
UserCreate, ItemsDeleteItemResponse,
UserPublic, LoginLoginAccessTokenData,
UserRegister, LoginLoginAccessTokenResponse,
UserUpdate, LoginTestTokenResponse,
UserUpdateMe, LoginRecoverPasswordData,
UsersPublic, LoginRecoverPasswordResponse,
} from "./models" LoginResetPasswordData,
LoginResetPasswordResponse,
LoginRecoverPasswordHtmlContentData,
LoginRecoverPasswordHtmlContentResponse,
UsersReadUsersData,
UsersReadUsersResponse,
UsersCreateUserData,
UsersCreateUserResponse,
UsersReadUserMeResponse,
UsersDeleteUserMeResponse,
UsersUpdateUserMeData,
UsersUpdateUserMeResponse,
UsersUpdatePasswordMeData,
UsersUpdatePasswordMeResponse,
UsersRegisterUserData,
UsersRegisterUserResponse,
UsersReadUserByIdData,
UsersReadUserByIdResponse,
UsersUpdateUserData,
UsersUpdateUserResponse,
UsersDeleteUserData,
UsersDeleteUserResponse,
UtilsTestEmailData,
UtilsTestEmailResponse,
UtilsHealthCheckResponse,
} from "./types.gen"
export type TDataLoginAccessToken = { export class ItemsService {
formData: Body_login_login_access_token /**
} * Read Items
export type TDataRecoverPassword = { * Retrieve items.
email: string * @param data The data for the request.
} * @param data.skip
export type TDataResetPassword = { * @param data.limit
requestBody: NewPassword * @returns ItemsPublic Successful Response
} * @throws ApiError
export type TDataRecoverPasswordHtmlContent = { */
email: string public static readItems(
data: ItemsReadItemsData = {},
): CancelablePromise<ItemsReadItemsResponse> {
return __request(OpenAPI, {
method: "GET",
url: "/api/v1/items/",
query: {
skip: data.skip,
limit: data.limit,
},
errors: {
422: "Validation Error",
},
})
}
/**
* Create Item
* Create new item.
* @param data The data for the request.
* @param data.requestBody
* @returns ItemPublic Successful Response
* @throws ApiError
*/
public static createItem(
data: ItemsCreateItemData,
): CancelablePromise<ItemsCreateItemResponse> {
return __request(OpenAPI, {
method: "POST",
url: "/api/v1/items/",
body: data.requestBody,
mediaType: "application/json",
errors: {
422: "Validation Error",
},
})
}
/**
* Read Item
* Get item by ID.
* @param data The data for the request.
* @param data.id
* @returns ItemPublic Successful Response
* @throws ApiError
*/
public static readItem(
data: ItemsReadItemData,
): CancelablePromise<ItemsReadItemResponse> {
return __request(OpenAPI, {
method: "GET",
url: "/api/v1/items/{id}",
path: {
id: data.id,
},
errors: {
422: "Validation Error",
},
})
}
/**
* Update Item
* Update an item.
* @param data The data for the request.
* @param data.id
* @param data.requestBody
* @returns ItemPublic Successful Response
* @throws ApiError
*/
public static updateItem(
data: ItemsUpdateItemData,
): CancelablePromise<ItemsUpdateItemResponse> {
return __request(OpenAPI, {
method: "PUT",
url: "/api/v1/items/{id}",
path: {
id: data.id,
},
body: data.requestBody,
mediaType: "application/json",
errors: {
422: "Validation Error",
},
})
}
/**
* Delete Item
* Delete an item.
* @param data The data for the request.
* @param data.id
* @returns Message Successful Response
* @throws ApiError
*/
public static deleteItem(
data: ItemsDeleteItemData,
): CancelablePromise<ItemsDeleteItemResponse> {
return __request(OpenAPI, {
method: "DELETE",
url: "/api/v1/items/{id}",
path: {
id: data.id,
},
errors: {
422: "Validation Error",
},
})
}
} }
export class LoginService { export class LoginService {
/** /**
* Login Access Token * Login Access Token
* OAuth2 compatible token login, get an access token for future requests * OAuth2 compatible token login, get an access token for future requests
* @param data The data for the request.
* @param data.formData
* @returns Token Successful Response * @returns Token Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static loginAccessToken( public static loginAccessToken(
data: TDataLoginAccessToken, data: LoginLoginAccessTokenData,
): CancelablePromise<Token> { ): CancelablePromise<LoginLoginAccessTokenResponse> {
const { formData } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/login/access-token", url: "/api/v1/login/access-token",
formData: formData, formData: data.formData,
mediaType: "application/x-www-form-urlencoded", mediaType: "application/x-www-form-urlencoded",
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -61,7 +196,7 @@ export class LoginService {
* @returns UserPublic Successful Response * @returns UserPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static testToken(): CancelablePromise<UserPublic> { public static testToken(): CancelablePromise<LoginTestTokenResponse> {
return __request(OpenAPI, { return __request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/login/test-token", url: "/api/v1/login/test-token",
@@ -71,18 +206,19 @@ export class LoginService {
/** /**
* Recover Password * Recover Password
* Password Recovery * Password Recovery
* @param data The data for the request.
* @param data.email
* @returns Message Successful Response * @returns Message Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static recoverPassword( public static recoverPassword(
data: TDataRecoverPassword, data: LoginRecoverPasswordData,
): CancelablePromise<Message> { ): CancelablePromise<LoginRecoverPasswordResponse> {
const { email } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/password-recovery/{email}", url: "/api/v1/password-recovery/{email}",
path: { path: {
email, email: data.email,
}, },
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -93,17 +229,18 @@ export class LoginService {
/** /**
* Reset Password * Reset Password
* Reset password * Reset password
* @param data The data for the request.
* @param data.requestBody
* @returns Message Successful Response * @returns Message Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static resetPassword( public static resetPassword(
data: TDataResetPassword, data: LoginResetPasswordData,
): CancelablePromise<Message> { ): CancelablePromise<LoginResetPasswordResponse> {
const { requestBody } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/reset-password/", url: "/api/v1/reset-password/",
body: requestBody, body: data.requestBody,
mediaType: "application/json", mediaType: "application/json",
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -114,18 +251,19 @@ export class LoginService {
/** /**
* Recover Password Html Content * Recover Password Html Content
* HTML Content for Password Recovery * HTML Content for Password Recovery
* @param data The data for the request.
* @param data.email
* @returns string Successful Response * @returns string Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static recoverPasswordHtmlContent( public static recoverPasswordHtmlContent(
data: TDataRecoverPasswordHtmlContent, data: LoginRecoverPasswordHtmlContentData,
): CancelablePromise<string> { ): CancelablePromise<LoginRecoverPasswordHtmlContentResponse> {
const { email } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/password-recovery-html-content/{email}", url: "/api/v1/password-recovery-html-content/{email}",
path: { path: {
email, email: data.email,
}, },
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -134,50 +272,25 @@ export class LoginService {
} }
} }
export type TDataReadUsers = {
limit?: number
skip?: number
}
export type TDataCreateUser = {
requestBody: UserCreate
}
export type TDataUpdateUserMe = {
requestBody: UserUpdateMe
}
export type TDataUpdatePasswordMe = {
requestBody: UpdatePassword
}
export type TDataRegisterUser = {
requestBody: UserRegister
}
export type TDataReadUserById = {
userId: string
}
export type TDataUpdateUser = {
requestBody: UserUpdate
userId: string
}
export type TDataDeleteUser = {
userId: string
}
export class UsersService { export class UsersService {
/** /**
* Read Users * Read Users
* Retrieve users. * Retrieve users.
* @param data The data for the request.
* @param data.skip
* @param data.limit
* @returns UsersPublic Successful Response * @returns UsersPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static readUsers( public static readUsers(
data: TDataReadUsers = {}, data: UsersReadUsersData = {},
): CancelablePromise<UsersPublic> { ): CancelablePromise<UsersReadUsersResponse> {
const { limit = 100, skip = 0 } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "GET", method: "GET",
url: "/api/v1/users/", url: "/api/v1/users/",
query: { query: {
skip, skip: data.skip,
limit, limit: data.limit,
}, },
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -188,17 +301,18 @@ export class UsersService {
/** /**
* Create User * Create User
* Create new user. * Create new user.
* @param data The data for the request.
* @param data.requestBody
* @returns UserPublic Successful Response * @returns UserPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static createUser( public static createUser(
data: TDataCreateUser, data: UsersCreateUserData,
): CancelablePromise<UserPublic> { ): CancelablePromise<UsersCreateUserResponse> {
const { requestBody } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/users/", url: "/api/v1/users/",
body: requestBody, body: data.requestBody,
mediaType: "application/json", mediaType: "application/json",
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -212,7 +326,7 @@ export class UsersService {
* @returns UserPublic Successful Response * @returns UserPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static readUserMe(): CancelablePromise<UserPublic> { public static readUserMe(): CancelablePromise<UsersReadUserMeResponse> {
return __request(OpenAPI, { return __request(OpenAPI, {
method: "GET", method: "GET",
url: "/api/v1/users/me", url: "/api/v1/users/me",
@@ -225,7 +339,7 @@ export class UsersService {
* @returns Message Successful Response * @returns Message Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static deleteUserMe(): CancelablePromise<Message> { public static deleteUserMe(): CancelablePromise<UsersDeleteUserMeResponse> {
return __request(OpenAPI, { return __request(OpenAPI, {
method: "DELETE", method: "DELETE",
url: "/api/v1/users/me", url: "/api/v1/users/me",
@@ -235,17 +349,18 @@ export class UsersService {
/** /**
* Update User Me * Update User Me
* Update own user. * Update own user.
* @param data The data for the request.
* @param data.requestBody
* @returns UserPublic Successful Response * @returns UserPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static updateUserMe( public static updateUserMe(
data: TDataUpdateUserMe, data: UsersUpdateUserMeData,
): CancelablePromise<UserPublic> { ): CancelablePromise<UsersUpdateUserMeResponse> {
const { requestBody } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "PATCH", method: "PATCH",
url: "/api/v1/users/me", url: "/api/v1/users/me",
body: requestBody, body: data.requestBody,
mediaType: "application/json", mediaType: "application/json",
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -256,17 +371,18 @@ export class UsersService {
/** /**
* Update Password Me * Update Password Me
* Update own password. * Update own password.
* @param data The data for the request.
* @param data.requestBody
* @returns Message Successful Response * @returns Message Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static updatePasswordMe( public static updatePasswordMe(
data: TDataUpdatePasswordMe, data: UsersUpdatePasswordMeData,
): CancelablePromise<Message> { ): CancelablePromise<UsersUpdatePasswordMeResponse> {
const { requestBody } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "PATCH", method: "PATCH",
url: "/api/v1/users/me/password", url: "/api/v1/users/me/password",
body: requestBody, body: data.requestBody,
mediaType: "application/json", mediaType: "application/json",
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -277,17 +393,18 @@ export class UsersService {
/** /**
* Register User * Register User
* Create new user without the need to be logged in. * Create new user without the need to be logged in.
* @param data The data for the request.
* @param data.requestBody
* @returns UserPublic Successful Response * @returns UserPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static registerUser( public static registerUser(
data: TDataRegisterUser, data: UsersRegisterUserData,
): CancelablePromise<UserPublic> { ): CancelablePromise<UsersRegisterUserResponse> {
const { requestBody } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/users/signup", url: "/api/v1/users/signup",
body: requestBody, body: data.requestBody,
mediaType: "application/json", mediaType: "application/json",
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -298,18 +415,19 @@ export class UsersService {
/** /**
* Read User By Id * Read User By Id
* Get a specific user by id. * Get a specific user by id.
* @param data The data for the request.
* @param data.userId
* @returns UserPublic Successful Response * @returns UserPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static readUserById( public static readUserById(
data: TDataReadUserById, data: UsersReadUserByIdData,
): CancelablePromise<UserPublic> { ): CancelablePromise<UsersReadUserByIdResponse> {
const { userId } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "GET", method: "GET",
url: "/api/v1/users/{user_id}", url: "/api/v1/users/{user_id}",
path: { path: {
user_id: userId, user_id: data.userId,
}, },
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -320,20 +438,22 @@ export class UsersService {
/** /**
* Update User * Update User
* Update a user. * Update a user.
* @param data The data for the request.
* @param data.userId
* @param data.requestBody
* @returns UserPublic Successful Response * @returns UserPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static updateUser( public static updateUser(
data: TDataUpdateUser, data: UsersUpdateUserData,
): CancelablePromise<UserPublic> { ): CancelablePromise<UsersUpdateUserResponse> {
const { requestBody, userId } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "PATCH", method: "PATCH",
url: "/api/v1/users/{user_id}", url: "/api/v1/users/{user_id}",
path: { path: {
user_id: userId, user_id: data.userId,
}, },
body: requestBody, body: data.requestBody,
mediaType: "application/json", mediaType: "application/json",
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -344,16 +464,19 @@ export class UsersService {
/** /**
* Delete User * Delete User
* Delete a user. * Delete a user.
* @param data The data for the request.
* @param data.userId
* @returns Message Successful Response * @returns Message Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static deleteUser(data: TDataDeleteUser): CancelablePromise<Message> { public static deleteUser(
const { userId } = data data: UsersDeleteUserData,
): CancelablePromise<UsersDeleteUserResponse> {
return __request(OpenAPI, { return __request(OpenAPI, {
method: "DELETE", method: "DELETE",
url: "/api/v1/users/{user_id}", url: "/api/v1/users/{user_id}",
path: { path: {
user_id: userId, user_id: data.userId,
}, },
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
@@ -362,156 +485,39 @@ export class UsersService {
} }
} }
export type TDataTestEmail = {
emailTo: string
}
export class UtilsService { export class UtilsService {
/** /**
* Test Email * Test Email
* Test emails. * Test emails.
* @param data The data for the request.
* @param data.emailTo
* @returns Message Successful Response * @returns Message Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static testEmail(data: TDataTestEmail): CancelablePromise<Message> { public static testEmail(
const { emailTo } = data data: UtilsTestEmailData,
): CancelablePromise<UtilsTestEmailResponse> {
return __request(OpenAPI, { return __request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/utils/test-email/", url: "/api/v1/utils/test-email/",
query: { query: {
email_to: emailTo, email_to: data.emailTo,
}, },
errors: { errors: {
422: "Validation Error", 422: "Validation Error",
}, },
}) })
} }
}
export type TDataReadItems = {
limit?: number
skip?: number
}
export type TDataCreateItem = {
requestBody: ItemCreate
}
export type TDataReadItem = {
id: string
}
export type TDataUpdateItem = {
id: string
requestBody: ItemUpdate
}
export type TDataDeleteItem = {
id: string
}
export class ItemsService {
/** /**
* Read Items * Health Check
* Retrieve items. * @returns boolean Successful Response
* @returns ItemsPublic Successful Response
* @throws ApiError * @throws ApiError
*/ */
public static readItems( public static healthCheck(): CancelablePromise<UtilsHealthCheckResponse> {
data: TDataReadItems = {},
): CancelablePromise<ItemsPublic> {
const { limit = 100, skip = 0 } = data
return __request(OpenAPI, { return __request(OpenAPI, {
method: "GET", method: "GET",
url: "/api/v1/items/", url: "/api/v1/utils/health-check/",
query: {
skip,
limit,
},
errors: {
422: "Validation Error",
},
})
}
/**
* Create Item
* Create new item.
* @returns ItemPublic Successful Response
* @throws ApiError
*/
public static createItem(
data: TDataCreateItem,
): CancelablePromise<ItemPublic> {
const { requestBody } = data
return __request(OpenAPI, {
method: "POST",
url: "/api/v1/items/",
body: requestBody,
mediaType: "application/json",
errors: {
422: "Validation Error",
},
})
}
/**
* Read Item
* Get item by ID.
* @returns ItemPublic Successful Response
* @throws ApiError
*/
public static readItem(data: TDataReadItem): CancelablePromise<ItemPublic> {
const { id } = data
return __request(OpenAPI, {
method: "GET",
url: "/api/v1/items/{id}",
path: {
id,
},
errors: {
422: "Validation Error",
},
})
}
/**
* Update Item
* Update an item.
* @returns ItemPublic Successful Response
* @throws ApiError
*/
public static updateItem(
data: TDataUpdateItem,
): CancelablePromise<ItemPublic> {
const { id, requestBody } = data
return __request(OpenAPI, {
method: "PUT",
url: "/api/v1/items/{id}",
path: {
id,
},
body: requestBody,
mediaType: "application/json",
errors: {
422: "Validation Error",
},
})
}
/**
* Delete Item
* Delete an item.
* @returns Message Successful Response
* @throws ApiError
*/
public static deleteItem(data: TDataDeleteItem): CancelablePromise<Message> {
const { id } = data
return __request(OpenAPI, {
method: "DELETE",
url: "/api/v1/items/{id}",
path: {
id,
},
errors: {
422: "Validation Error",
},
}) })
} }
} }
+221
View File
@@ -0,0 +1,221 @@
// This file is auto-generated by @hey-api/openapi-ts
export type Body_login_login_access_token = {
grant_type?: string | null
username: string
password: string
scope?: string
client_id?: string | null
client_secret?: string | null
}
export type HTTPValidationError = {
detail?: Array<ValidationError>
}
export type ItemCreate = {
title: string
description?: string | null
}
export type ItemPublic = {
title: string
description?: string | null
id: string
owner_id: string
}
export type ItemsPublic = {
data: Array<ItemPublic>
count: number
}
export type ItemUpdate = {
title?: string | null
description?: string | null
}
export type Message = {
message: string
}
export type NewPassword = {
token: string
new_password: string
}
export type Token = {
access_token: string
token_type?: string
}
export type UpdatePassword = {
current_password: string
new_password: string
}
export type UserCreate = {
email: string
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
password: string
}
export type UserPublic = {
email: string
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
id: string
}
export type UserRegister = {
email: string
password: string
full_name?: string | null
}
export type UsersPublic = {
data: Array<UserPublic>
count: number
}
export type UserUpdate = {
email?: string | null
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
password?: string | null
}
export type UserUpdateMe = {
full_name?: string | null
email?: string | null
}
export type ValidationError = {
loc: Array<string | number>
msg: string
type: string
}
export type ItemsReadItemsData = {
limit?: number
skip?: number
}
export type ItemsReadItemsResponse = ItemsPublic
export type ItemsCreateItemData = {
requestBody: ItemCreate
}
export type ItemsCreateItemResponse = ItemPublic
export type ItemsReadItemData = {
id: string
}
export type ItemsReadItemResponse = ItemPublic
export type ItemsUpdateItemData = {
id: string
requestBody: ItemUpdate
}
export type ItemsUpdateItemResponse = ItemPublic
export type ItemsDeleteItemData = {
id: string
}
export type ItemsDeleteItemResponse = Message
export type LoginLoginAccessTokenData = {
formData: Body_login_login_access_token
}
export type LoginLoginAccessTokenResponse = Token
export type LoginTestTokenResponse = UserPublic
export type LoginRecoverPasswordData = {
email: string
}
export type LoginRecoverPasswordResponse = Message
export type LoginResetPasswordData = {
requestBody: NewPassword
}
export type LoginResetPasswordResponse = Message
export type LoginRecoverPasswordHtmlContentData = {
email: string
}
export type LoginRecoverPasswordHtmlContentResponse = string
export type UsersReadUsersData = {
limit?: number
skip?: number
}
export type UsersReadUsersResponse = UsersPublic
export type UsersCreateUserData = {
requestBody: UserCreate
}
export type UsersCreateUserResponse = UserPublic
export type UsersReadUserMeResponse = UserPublic
export type UsersDeleteUserMeResponse = Message
export type UsersUpdateUserMeData = {
requestBody: UserUpdateMe
}
export type UsersUpdateUserMeResponse = UserPublic
export type UsersUpdatePasswordMeData = {
requestBody: UpdatePassword
}
export type UsersUpdatePasswordMeResponse = Message
export type UsersRegisterUserData = {
requestBody: UserRegister
}
export type UsersRegisterUserResponse = UserPublic
export type UsersReadUserByIdData = {
userId: string
}
export type UsersReadUserByIdResponse = UserPublic
export type UsersUpdateUserData = {
requestBody: UserUpdate
userId: string
}
export type UsersUpdateUserResponse = UserPublic
export type UsersDeleteUserData = {
userId: string
}
export type UsersDeleteUserResponse = Message
export type UtilsTestEmailData = {
emailTo: string
}
export type UtilsTestEmailResponse = Message
export type UtilsHealthCheckResponse = boolean
+174 -126
View File
@@ -1,45 +1,48 @@
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { Controller, type SubmitHandler, useForm } from "react-hook-form"
import { type UserCreate, UsersService } from "@/client"
import type { ApiError } from "@/client/core/ApiError"
import useCustomToast from "@/hooks/useCustomToast"
import { emailPattern, handleError } from "@/utils"
import { import {
Button, Button,
Checkbox, DialogActionTrigger,
DialogTitle,
Flex, Flex,
FormControl,
FormErrorMessage,
FormLabel,
Input, Input,
Modal, Text,
ModalBody, VStack,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
} from "@chakra-ui/react" } from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query" import { useState } from "react"
import { type SubmitHandler, useForm } from "react-hook-form" import { FaPlus } from "react-icons/fa"
import { Checkbox } from "../ui/checkbox"
import { type UserCreate, UsersService } from "../../client" import {
import type { ApiError } from "../../client/core/ApiError" DialogBody,
import useCustomToast from "../../hooks/useCustomToast" DialogCloseTrigger,
import { emailPattern, handleError } from "../../utils" DialogContent,
DialogFooter,
interface AddUserProps { DialogHeader,
isOpen: boolean DialogRoot,
onClose: () => void DialogTrigger,
} } from "../ui/dialog"
import { Field } from "../ui/field"
interface UserCreateForm extends UserCreate { interface UserCreateForm extends UserCreate {
confirm_password: string confirm_password: string
} }
const AddUser = ({ isOpen, onClose }: AddUserProps) => { const AddUser = () => {
const [isOpen, setIsOpen] = useState(false)
const queryClient = useQueryClient() const queryClient = useQueryClient()
const showToast = useCustomToast() const { showSuccessToast } = useCustomToast()
const { const {
control,
register, register,
handleSubmit, handleSubmit,
reset, reset,
getValues, getValues,
formState: { errors, isSubmitting }, formState: { errors, isValid, isSubmitting },
} = useForm<UserCreateForm>({ } = useForm<UserCreateForm>({
mode: "onBlur", mode: "onBlur",
criteriaMode: "all", criteriaMode: "all",
@@ -57,12 +60,12 @@ const AddUser = ({ isOpen, onClose }: AddUserProps) => {
mutationFn: (data: UserCreate) => mutationFn: (data: UserCreate) =>
UsersService.createUser({ requestBody: data }), UsersService.createUser({ requestBody: data }),
onSuccess: () => { onSuccess: () => {
showToast("Success!", "User created successfully.", "success") showSuccessToast("User created successfully.")
reset() reset()
onClose() setIsOpen(false)
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
handleError(err, showToast) handleError(err)
}, },
onSettled: () => { onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["users"] }) queryClient.invalidateQueries({ queryKey: ["users"] })
@@ -74,108 +77,153 @@ const AddUser = ({ isOpen, onClose }: AddUserProps) => {
} }
return ( return (
<> <DialogRoot
<Modal size={{ base: "xs", md: "md" }}
isOpen={isOpen} placement="center"
onClose={onClose} open={isOpen}
size={{ base: "sm", md: "md" }} onOpenChange={({ open }) => setIsOpen(open)}
isCentered >
> <DialogTrigger asChild>
<ModalOverlay /> <Button value="add-user" my={4}>
<ModalContent as="form" onSubmit={handleSubmit(onSubmit)}> <FaPlus fontSize="16px" />
<ModalHeader>Add User</ModalHeader> Add User
<ModalCloseButton /> </Button>
<ModalBody pb={6}> </DialogTrigger>
<FormControl isRequired isInvalid={!!errors.email}> <DialogContent>
<FormLabel htmlFor="email">Email</FormLabel> <form onSubmit={handleSubmit(onSubmit)}>
<Input <DialogHeader>
id="email" <DialogTitle>Add User</DialogTitle>
{...register("email", { </DialogHeader>
required: "Email is required", <DialogBody>
pattern: emailPattern, <Text mb={4}>
})} Fill in the form below to add a new user to the system.
placeholder="Email" </Text>
type="email" <VStack gap={4}>
<Field
required
invalid={!!errors.email}
errorText={errors.email?.message}
label="Email"
>
<Input
id="email"
{...register("email", {
required: "Email is required",
pattern: emailPattern,
})}
placeholder="Email"
type="email"
/>
</Field>
<Field
invalid={!!errors.full_name}
errorText={errors.full_name?.message}
label="Full Name"
>
<Input
id="name"
{...register("full_name")}
placeholder="Full name"
type="text"
/>
</Field>
<Field
required
invalid={!!errors.password}
errorText={errors.password?.message}
label="Set Password"
>
<Input
id="password"
{...register("password", {
required: "Password is required",
minLength: {
value: 8,
message: "Password must be at least 8 characters",
},
})}
placeholder="Password"
type="password"
/>
</Field>
<Field
required
invalid={!!errors.confirm_password}
errorText={errors.confirm_password?.message}
label="Confirm Password"
>
<Input
id="confirm_password"
{...register("confirm_password", {
required: "Please confirm your password",
validate: (value) =>
value === getValues().password ||
"The passwords do not match",
})}
placeholder="Password"
type="password"
/>
</Field>
</VStack>
<Flex mt={4} direction="column" gap={4}>
<Controller
control={control}
name="is_superuser"
render={({ field }) => (
<Field disabled={field.disabled} colorPalette="teal">
<Checkbox
checked={field.value}
onCheckedChange={({ checked }) => field.onChange(checked)}
>
Is superuser?
</Checkbox>
</Field>
)}
/> />
{errors.email && ( <Controller
<FormErrorMessage>{errors.email.message}</FormErrorMessage> control={control}
)} name="is_active"
</FormControl> render={({ field }) => (
<FormControl mt={4} isInvalid={!!errors.full_name}> <Field disabled={field.disabled} colorPalette="teal">
<FormLabel htmlFor="name">Full name</FormLabel> <Checkbox
<Input checked={field.value}
id="name" onCheckedChange={({ checked }) => field.onChange(checked)}
{...register("full_name")} >
placeholder="Full name" Is active?
type="text" </Checkbox>
</Field>
)}
/> />
{errors.full_name && (
<FormErrorMessage>{errors.full_name.message}</FormErrorMessage>
)}
</FormControl>
<FormControl mt={4} isRequired isInvalid={!!errors.password}>
<FormLabel htmlFor="password">Set Password</FormLabel>
<Input
id="password"
{...register("password", {
required: "Password is required",
minLength: {
value: 8,
message: "Password must be at least 8 characters",
},
})}
placeholder="Password"
type="password"
/>
{errors.password && (
<FormErrorMessage>{errors.password.message}</FormErrorMessage>
)}
</FormControl>
<FormControl
mt={4}
isRequired
isInvalid={!!errors.confirm_password}
>
<FormLabel htmlFor="confirm_password">Confirm Password</FormLabel>
<Input
id="confirm_password"
{...register("confirm_password", {
required: "Please confirm your password",
validate: (value) =>
value === getValues().password ||
"The passwords do not match",
})}
placeholder="Password"
type="password"
/>
{errors.confirm_password && (
<FormErrorMessage>
{errors.confirm_password.message}
</FormErrorMessage>
)}
</FormControl>
<Flex mt={4}>
<FormControl>
<Checkbox {...register("is_superuser")} colorScheme="teal">
Is superuser?
</Checkbox>
</FormControl>
<FormControl>
<Checkbox {...register("is_active")} colorScheme="teal">
Is active?
</Checkbox>
</FormControl>
</Flex> </Flex>
</ModalBody> </DialogBody>
<ModalFooter gap={3}>
<Button variant="primary" type="submit" isLoading={isSubmitting}> <DialogFooter gap={2}>
<DialogActionTrigger asChild>
<Button
variant="subtle"
colorPalette="gray"
disabled={isSubmitting}
>
Cancel
</Button>
</DialogActionTrigger>
<Button
variant="solid"
type="submit"
disabled={!isValid}
loading={isSubmitting}
>
Save Save
</Button> </Button>
<Button onClick={onClose}>Cancel</Button> </DialogFooter>
</ModalFooter> </form>
</ModalContent> <DialogCloseTrigger />
</Modal> </DialogContent>
</> </DialogRoot>
) )
} }
@@ -0,0 +1,104 @@
import { Button, DialogTitle, Text } from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { useState } from "react"
import { useForm } from "react-hook-form"
import { FiTrash2 } from "react-icons/fi"
import { UsersService } from "@/client"
import {
DialogActionTrigger,
DialogBody,
DialogCloseTrigger,
DialogContent,
DialogFooter,
DialogHeader,
DialogRoot,
DialogTrigger,
} from "@/components/ui/dialog"
import useCustomToast from "@/hooks/useCustomToast"
const DeleteUser = ({ id }: { id: string }) => {
const [isOpen, setIsOpen] = useState(false)
const queryClient = useQueryClient()
const { showSuccessToast, showErrorToast } = useCustomToast()
const {
handleSubmit,
formState: { isSubmitting },
} = useForm()
const deleteUser = async (id: string) => {
await UsersService.deleteUser({ userId: id })
}
const mutation = useMutation({
mutationFn: deleteUser,
onSuccess: () => {
showSuccessToast("The user was deleted successfully")
setIsOpen(false)
},
onError: () => {
showErrorToast("An error occurred while deleting the user")
},
onSettled: () => {
queryClient.invalidateQueries()
},
})
const onSubmit = async () => {
mutation.mutate(id)
}
return (
<DialogRoot
size={{ base: "xs", md: "md" }}
placement="center"
role="alertdialog"
open={isOpen}
onOpenChange={({ open }) => setIsOpen(open)}
>
<DialogTrigger asChild>
<Button variant="ghost" size="sm" colorPalette="red">
<FiTrash2 fontSize="16px" />
Delete User
</Button>
</DialogTrigger>
<DialogContent>
<form onSubmit={handleSubmit(onSubmit)}>
<DialogHeader>
<DialogTitle>Delete User</DialogTitle>
</DialogHeader>
<DialogBody>
<Text mb={4}>
All items associated with this user will also be{" "}
<strong>permanently deleted.</strong> Are you sure? You will not
be able to undo this action.
</Text>
</DialogBody>
<DialogFooter gap={2}>
<DialogActionTrigger asChild>
<Button
variant="subtle"
colorPalette="gray"
disabled={isSubmitting}
>
Cancel
</Button>
</DialogActionTrigger>
<Button
variant="solid"
colorPalette="red"
type="submit"
loading={isSubmitting}
>
Delete
</Button>
</DialogFooter>
<DialogCloseTrigger />
</form>
</DialogContent>
</DialogRoot>
)
}
export default DeleteUser
+172 -130
View File
@@ -1,51 +1,53 @@
import {
Button,
Checkbox,
Flex,
FormControl,
FormErrorMessage,
FormLabel,
Input,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
} from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query" import { useMutation, useQueryClient } from "@tanstack/react-query"
import { type SubmitHandler, useForm } from "react-hook-form" import { Controller, type SubmitHandler, useForm } from "react-hook-form"
import { import {
type ApiError, Button,
type UserPublic, DialogActionTrigger,
type UserUpdate, DialogRoot,
UsersService, DialogTrigger,
} from "../../client" Flex,
import useCustomToast from "../../hooks/useCustomToast" Input,
import { emailPattern, handleError } from "../../utils" Text,
VStack,
} from "@chakra-ui/react"
import { useState } from "react"
import { FaExchangeAlt } from "react-icons/fa"
import { type UserPublic, type UserUpdate, UsersService } from "@/client"
import type { ApiError } from "@/client/core/ApiError"
import useCustomToast from "@/hooks/useCustomToast"
import { emailPattern, handleError } from "@/utils"
import { Checkbox } from "../ui/checkbox"
import {
DialogBody,
DialogCloseTrigger,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../ui/dialog"
import { Field } from "../ui/field"
interface EditUserProps { interface EditUserProps {
user: UserPublic user: UserPublic
isOpen: boolean
onClose: () => void
} }
interface UserUpdateForm extends UserUpdate { interface UserUpdateForm extends UserUpdate {
confirm_password: string confirm_password?: string
} }
const EditUser = ({ user, isOpen, onClose }: EditUserProps) => { const EditUser = ({ user }: EditUserProps) => {
const [isOpen, setIsOpen] = useState(false)
const queryClient = useQueryClient() const queryClient = useQueryClient()
const showToast = useCustomToast() const { showSuccessToast } = useCustomToast()
const { const {
control,
register, register,
handleSubmit, handleSubmit,
reset, reset,
getValues, getValues,
formState: { errors, isSubmitting, isDirty }, formState: { errors, isSubmitting },
} = useForm<UserUpdateForm>({ } = useForm<UserUpdateForm>({
mode: "onBlur", mode: "onBlur",
criteriaMode: "all", criteriaMode: "all",
@@ -56,11 +58,12 @@ const EditUser = ({ user, isOpen, onClose }: EditUserProps) => {
mutationFn: (data: UserUpdateForm) => mutationFn: (data: UserUpdateForm) =>
UsersService.updateUser({ userId: user.id, requestBody: data }), UsersService.updateUser({ userId: user.id, requestBody: data }),
onSuccess: () => { onSuccess: () => {
showToast("Success!", "User updated successfully.", "success") showSuccessToast("User updated successfully.")
onClose() reset()
setIsOpen(false)
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
handleError(err, showToast) handleError(err)
}, },
onSettled: () => { onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["users"] }) queryClient.invalidateQueries({ queryKey: ["users"] })
@@ -74,106 +77,145 @@ const EditUser = ({ user, isOpen, onClose }: EditUserProps) => {
mutation.mutate(data) mutation.mutate(data)
} }
const onCancel = () => {
reset()
onClose()
}
return ( return (
<> <DialogRoot
<Modal size={{ base: "xs", md: "md" }}
isOpen={isOpen} placement="center"
onClose={onClose} open={isOpen}
size={{ base: "sm", md: "md" }} onOpenChange={({ open }) => setIsOpen(open)}
isCentered >
> <DialogTrigger asChild>
<ModalOverlay /> <Button variant="ghost" size="sm">
<ModalContent as="form" onSubmit={handleSubmit(onSubmit)}> <FaExchangeAlt fontSize="16px" />
<ModalHeader>Edit User</ModalHeader> Edit User
<ModalCloseButton /> </Button>
<ModalBody pb={6}> </DialogTrigger>
<FormControl isInvalid={!!errors.email}> <DialogContent>
<FormLabel htmlFor="email">Email</FormLabel> <form onSubmit={handleSubmit(onSubmit)}>
<Input <DialogHeader>
id="email" <DialogTitle>Edit User</DialogTitle>
{...register("email", { </DialogHeader>
required: "Email is required", <DialogBody>
pattern: emailPattern, <Text mb={4}>Update the user details below.</Text>
})} <VStack gap={4}>
placeholder="Email" <Field
type="email" required
/> invalid={!!errors.email}
{errors.email && ( errorText={errors.email?.message}
<FormErrorMessage>{errors.email.message}</FormErrorMessage> label="Email"
)} >
</FormControl> <Input
<FormControl mt={4}> id="email"
<FormLabel htmlFor="name">Full name</FormLabel> {...register("email", {
<Input id="name" {...register("full_name")} type="text" /> required: "Email is required",
</FormControl> pattern: emailPattern,
<FormControl mt={4} isInvalid={!!errors.password}> })}
<FormLabel htmlFor="password">Set Password</FormLabel> placeholder="Email"
<Input type="email"
id="password" />
{...register("password", { </Field>
minLength: {
value: 8,
message: "Password must be at least 8 characters",
},
})}
placeholder="Password"
type="password"
/>
{errors.password && (
<FormErrorMessage>{errors.password.message}</FormErrorMessage>
)}
</FormControl>
<FormControl mt={4} isInvalid={!!errors.confirm_password}>
<FormLabel htmlFor="confirm_password">Confirm Password</FormLabel>
<Input
id="confirm_password"
{...register("confirm_password", {
validate: (value) =>
value === getValues().password ||
"The passwords do not match",
})}
placeholder="Password"
type="password"
/>
{errors.confirm_password && (
<FormErrorMessage>
{errors.confirm_password.message}
</FormErrorMessage>
)}
</FormControl>
<Flex>
<FormControl mt={4}>
<Checkbox {...register("is_superuser")} colorScheme="teal">
Is superuser?
</Checkbox>
</FormControl>
<FormControl mt={4}>
<Checkbox {...register("is_active")} colorScheme="teal">
Is active?
</Checkbox>
</FormControl>
</Flex>
</ModalBody>
<ModalFooter gap={3}> <Field
<Button invalid={!!errors.full_name}
variant="primary" errorText={errors.full_name?.message}
type="submit" label="Full Name"
isLoading={isSubmitting} >
isDisabled={!isDirty} <Input
> id="name"
{...register("full_name")}
placeholder="Full name"
type="text"
/>
</Field>
<Field
required
invalid={!!errors.password}
errorText={errors.password?.message}
label="Set Password"
>
<Input
id="password"
{...register("password", {
minLength: {
value: 8,
message: "Password must be at least 8 characters",
},
})}
placeholder="Password"
type="password"
/>
</Field>
<Field
required
invalid={!!errors.confirm_password}
errorText={errors.confirm_password?.message}
label="Confirm Password"
>
<Input
id="confirm_password"
{...register("confirm_password", {
validate: (value) =>
value === getValues().password ||
"The passwords do not match",
})}
placeholder="Password"
type="password"
/>
</Field>
</VStack>
<Flex mt={4} direction="column" gap={4}>
<Controller
control={control}
name="is_superuser"
render={({ field }) => (
<Field disabled={field.disabled} colorPalette="teal">
<Checkbox
checked={field.value}
onCheckedChange={({ checked }) => field.onChange(checked)}
>
Is superuser?
</Checkbox>
</Field>
)}
/>
<Controller
control={control}
name="is_active"
render={({ field }) => (
<Field disabled={field.disabled} colorPalette="teal">
<Checkbox
checked={field.value}
onCheckedChange={({ checked }) => field.onChange(checked)}
>
Is active?
</Checkbox>
</Field>
)}
/>
</Flex>
</DialogBody>
<DialogFooter gap={2}>
<DialogActionTrigger asChild>
<Button
variant="subtle"
colorPalette="gray"
disabled={isSubmitting}
>
Cancel
</Button>
</DialogActionTrigger>
<Button variant="solid" type="submit" loading={isSubmitting}>
Save Save
</Button> </Button>
<Button onClick={onCancel}>Cancel</Button> </DialogFooter>
</ModalFooter> <DialogCloseTrigger />
</ModalContent> </form>
</Modal> </DialogContent>
</> </DialogRoot>
) )
} }
@@ -1,75 +0,0 @@
import {
Button,
Menu,
MenuButton,
MenuItem,
MenuList,
useDisclosure,
} from "@chakra-ui/react"
import { BsThreeDotsVertical } from "react-icons/bs"
import { FiEdit, FiTrash } from "react-icons/fi"
import type { ItemPublic, UserPublic } from "../../client"
import EditUser from "../Admin/EditUser"
import EditItem from "../Items/EditItem"
import Delete from "./DeleteAlert"
interface ActionsMenuProps {
type: string
value: ItemPublic | UserPublic
disabled?: boolean
}
const ActionsMenu = ({ type, value, disabled }: ActionsMenuProps) => {
const editUserModal = useDisclosure()
const deleteModal = useDisclosure()
return (
<>
<Menu>
<MenuButton
isDisabled={disabled}
as={Button}
rightIcon={<BsThreeDotsVertical />}
variant="unstyled"
/>
<MenuList>
<MenuItem
onClick={editUserModal.onOpen}
icon={<FiEdit fontSize="16px" />}
>
Edit {type}
</MenuItem>
<MenuItem
onClick={deleteModal.onOpen}
icon={<FiTrash fontSize="16px" />}
color="ui.danger"
>
Delete {type}
</MenuItem>
</MenuList>
{type === "User" ? (
<EditUser
user={value as UserPublic}
isOpen={editUserModal.isOpen}
onClose={editUserModal.onClose}
/>
) : (
<EditItem
item={value as ItemPublic}
isOpen={editUserModal.isOpen}
onClose={editUserModal.onClose}
/>
)}
<Delete
type={type}
id={value.id}
isOpen={deleteModal.isOpen}
onClose={deleteModal.onClose}
/>
</Menu>
</>
)
}
export default ActionsMenu
@@ -1,113 +0,0 @@
import {
AlertDialog,
AlertDialogBody,
AlertDialogContent,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogOverlay,
Button,
} from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import React from "react"
import { useForm } from "react-hook-form"
import { ItemsService, UsersService } from "../../client"
import useCustomToast from "../../hooks/useCustomToast"
interface DeleteProps {
type: string
id: string
isOpen: boolean
onClose: () => void
}
const Delete = ({ type, id, isOpen, onClose }: DeleteProps) => {
const queryClient = useQueryClient()
const showToast = useCustomToast()
const cancelRef = React.useRef<HTMLButtonElement | null>(null)
const {
handleSubmit,
formState: { isSubmitting },
} = useForm()
const deleteEntity = async (id: string) => {
if (type === "Item") {
await ItemsService.deleteItem({ id: id })
} else if (type === "User") {
await UsersService.deleteUser({ userId: id })
} else {
throw new Error(`Unexpected type: ${type}`)
}
}
const mutation = useMutation({
mutationFn: deleteEntity,
onSuccess: () => {
showToast(
"Success",
`The ${type.toLowerCase()} was deleted successfully.`,
"success",
)
onClose()
},
onError: () => {
showToast(
"An error occurred.",
`An error occurred while deleting the ${type.toLowerCase()}.`,
"error",
)
},
onSettled: () => {
queryClient.invalidateQueries({
queryKey: [type === "Item" ? "items" : "users"],
})
},
})
const onSubmit = async () => {
mutation.mutate(id)
}
return (
<>
<AlertDialog
isOpen={isOpen}
onClose={onClose}
leastDestructiveRef={cancelRef}
size={{ base: "sm", md: "md" }}
isCentered
>
<AlertDialogOverlay>
<AlertDialogContent as="form" onSubmit={handleSubmit(onSubmit)}>
<AlertDialogHeader>Delete {type}</AlertDialogHeader>
<AlertDialogBody>
{type === "User" && (
<span>
All items associated with this user will also be{" "}
<strong>permantly deleted. </strong>
</span>
)}
Are you sure? You will not be able to undo this action.
</AlertDialogBody>
<AlertDialogFooter gap={3}>
<Button variant="danger" type="submit" isLoading={isSubmitting}>
Delete
</Button>
<Button
ref={cancelRef}
onClick={onClose}
isDisabled={isSubmitting}
>
Cancel
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialogOverlay>
</AlertDialog>
</>
)
}
export default Delete
@@ -0,0 +1,27 @@
import { IconButton } from "@chakra-ui/react"
import { BsThreeDotsVertical } from "react-icons/bs"
import { MenuContent, MenuRoot, MenuTrigger } from "../ui/menu"
import type { ItemPublic } from "@/client"
import DeleteItem from "../Items/DeleteItem"
import EditItem from "../Items/EditItem"
interface ItemActionsMenuProps {
item: ItemPublic
}
export const ItemActionsMenu = ({ item }: ItemActionsMenuProps) => {
return (
<MenuRoot>
<MenuTrigger asChild>
<IconButton variant="ghost" color="inherit">
<BsThreeDotsVertical />
</IconButton>
</MenuTrigger>
<MenuContent>
<EditItem item={item} />
<DeleteItem id={item.id} />
</MenuContent>
</MenuRoot>
)
}
+23 -30
View File
@@ -1,38 +1,31 @@
import type { ComponentType, ElementType } from "react" import { Flex, Image, useBreakpointValue } from "@chakra-ui/react"
import { Link } from "@tanstack/react-router"
import { Button, Flex, Icon, useDisclosure } from "@chakra-ui/react" import Logo from "/assets/images/fastapi-logo.svg"
import { FaPlus } from "react-icons/fa" import UserMenu from "./UserMenu"
interface NavbarProps { function Navbar() {
type: string const display = useBreakpointValue({ base: "none", md: "flex" })
addModalAs: ComponentType | ElementType
}
const Navbar = ({ type, addModalAs }: NavbarProps) => {
const addModal = useDisclosure()
const AddModal = addModalAs
return ( return (
<> <Flex
<Flex py={8} gap={4}> display={display}
{/* TODO: Complete search functionality */} justify="space-between"
{/* <InputGroup w={{ base: '100%', md: 'auto' }}> position="sticky"
<InputLeftElement pointerEvents='none'> color="white"
<Icon as={FaSearch} color='ui.dim' /> align="center"
</InputLeftElement> bg="bg.muted"
<Input type='text' placeholder='Search' fontSize={{ base: 'sm', md: 'inherit' }} borderRadius='8px' /> w="100%"
</InputGroup> */} top={0}
<Button p={4}
variant="primary" >
gap={1} <Link to="/">
fontSize={{ base: "sm", md: "inherit" }} <Image src={Logo} alt="Logo" w="180px" maxW="2xs" px={2} />
onClick={addModal.onOpen} </Link>
> <Flex gap={2} alignItems="center">
<Icon as={FaPlus} /> Add {type} <UserMenu />
</Button>
<AddModal isOpen={addModal.isOpen} onClose={addModal.onClose} />
</Flex> </Flex>
</> </Flex>
) )
} }
+42 -26
View File
@@ -1,39 +1,55 @@
import { Button, Container, Text } from "@chakra-ui/react" import { Button, Center, Flex, Text } from "@chakra-ui/react"
import { Link } from "@tanstack/react-router" import { Link } from "@tanstack/react-router"
const NotFound = () => { const NotFound = () => {
return ( return (
<> <>
<Container <Flex
h="100vh" height="100vh"
alignItems="stretch" align="center"
justifyContent="center" justify="center"
textAlign="center" flexDir="column"
maxW="sm" data-testid="not-found"
centerContent p={4}
> >
<Flex alignItems="center" zIndex={1}>
<Flex flexDir="column" ml={4} align="center" justify="center" p={4}>
<Text
fontSize={{ base: "6xl", md: "8xl" }}
fontWeight="bold"
lineHeight="1"
mb={4}
>
404
</Text>
<Text fontSize="2xl" fontWeight="bold" mb={2}>
Oops!
</Text>
</Flex>
</Flex>
<Text <Text
fontSize="8xl" fontSize="lg"
color="ui.main" color="gray.600"
fontWeight="bold"
lineHeight="1"
mb={4} mb={4}
textAlign="center"
zIndex={1}
> >
404 The page you are looking for was not found.
</Text> </Text>
<Text fontSize="md">Oops!</Text> <Center zIndex={1}>
<Text fontSize="md">Page not found.</Text> <Link to="/">
<Button <Button
as={Link} variant="solid"
to="/" colorScheme="teal"
color="ui.main" mt={4}
borderColor="ui.main" alignSelf="center"
variant="outline" >
mt={4} Go Back
> </Button>
Go back </Link>
</Button> </Center>
</Container> </Flex>
</> </>
) )
} }
+55 -72
View File
@@ -1,33 +1,26 @@
import { import { Box, Flex, IconButton, Text } from "@chakra-ui/react"
Box,
Drawer,
DrawerBody,
DrawerCloseButton,
DrawerContent,
DrawerOverlay,
Flex,
IconButton,
Image,
Text,
useColorModeValue,
useDisclosure,
} from "@chakra-ui/react"
import { useQueryClient } from "@tanstack/react-query" import { useQueryClient } from "@tanstack/react-query"
import { FiLogOut, FiMenu } from "react-icons/fi" import { useState } from "react"
import { FaBars } from "react-icons/fa"
import { FiLogOut } from "react-icons/fi"
import Logo from "/assets/images/fastapi-logo.svg" import type { UserPublic } from "@/client"
import type { UserPublic } from "../../client" import useAuth from "@/hooks/useAuth"
import useAuth from "../../hooks/useAuth" import {
DrawerBackdrop,
DrawerBody,
DrawerCloseTrigger,
DrawerContent,
DrawerRoot,
DrawerTrigger,
} from "../ui/drawer"
import SidebarItems from "./SidebarItems" import SidebarItems from "./SidebarItems"
const Sidebar = () => { const Sidebar = () => {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const bgColor = useColorModeValue("ui.light", "ui.dark")
const textColor = useColorModeValue("ui.dark", "ui.light")
const secBgColor = useColorModeValue("ui.secondary", "ui.darkSlate")
const currentUser = queryClient.getQueryData<UserPublic>(["currentUser"]) const currentUser = queryClient.getQueryData<UserPublic>(["currentUser"])
const { isOpen, onOpen, onClose } = useDisclosure()
const { logout } = useAuth() const { logout } = useAuth()
const [open, setOpen] = useState(false)
const handleLogout = async () => { const handleLogout = async () => {
logout() logout()
@@ -36,78 +29,68 @@ const Sidebar = () => {
return ( return (
<> <>
{/* Mobile */} {/* Mobile */}
<IconButton <DrawerRoot
onClick={onOpen} placement="start"
display={{ base: "flex", md: "none" }} open={open}
aria-label="Open Menu" onOpenChange={(e) => setOpen(e.open)}
position="absolute" >
fontSize="20px" <DrawerBackdrop />
m={4} <DrawerTrigger asChild>
icon={<FiMenu />} <IconButton
/> variant="ghost"
<Drawer isOpen={isOpen} placement="left" onClose={onClose}> color="inherit"
<DrawerOverlay /> display={{ base: "flex", md: "none" }}
<DrawerContent maxW="250px"> aria-label="Open Menu"
<DrawerCloseButton /> position="absolute"
<DrawerBody py={8}> zIndex="100"
m={4}
>
<FaBars />
</IconButton>
</DrawerTrigger>
<DrawerContent maxW="280px">
<DrawerCloseTrigger />
<DrawerBody>
<Flex flexDir="column" justify="space-between"> <Flex flexDir="column" justify="space-between">
<Box> <Box>
<Image src={Logo} alt="logo" p={6} /> <SidebarItems />
<SidebarItems onClose={onClose} />
<Flex <Flex
as="button" as="button"
onClick={handleLogout} onClick={handleLogout}
p={2}
color="ui.danger"
fontWeight="bold"
alignItems="center" alignItems="center"
gap={4}
px={4}
py={2}
> >
<FiLogOut /> <FiLogOut />
<Text ml={2}>Log out</Text> <Text>Log Out</Text>
</Flex> </Flex>
</Box> </Box>
{currentUser?.email && ( {currentUser?.email && (
<Text color={textColor} noOfLines={2} fontSize="sm" p={2}> <Text fontSize="sm" p={2}>
Logged in as: {currentUser.email} Logged in as: {currentUser.email}
</Text> </Text>
)} )}
</Flex> </Flex>
</DrawerBody> </DrawerBody>
<DrawerCloseTrigger />
</DrawerContent> </DrawerContent>
</Drawer> </DrawerRoot>
{/* Desktop */} {/* Desktop */}
<Box <Box
bg={bgColor}
p={3}
h="100vh"
position="sticky"
top="0"
display={{ base: "none", md: "flex" }} display={{ base: "none", md: "flex" }}
position="sticky"
bg="bg.subtle"
top={0}
minW="280px"
h="100vh"
p={4}
> >
<Flex <Box w="100%">
flexDir="column" <SidebarItems />
justify="space-between" </Box>
bg={secBgColor}
p={4}
borderRadius={12}
>
<Box>
<Image src={Logo} alt="Logo" w="180px" maxW="2xs" p={6} />
<SidebarItems />
</Box>
{currentUser?.email && (
<Text
color={textColor}
noOfLines={2}
fontSize="sm"
p={2}
maxW="180px"
>
Logged in as: {currentUser.email}
</Text>
)}
</Flex>
</Box> </Box>
</> </>
) )
+29 -24
View File
@@ -1,9 +1,10 @@
import { Box, Flex, Icon, Text, useColorModeValue } from "@chakra-ui/react" import { Box, Flex, Icon, Text } from "@chakra-ui/react"
import { useQueryClient } from "@tanstack/react-query" import { useQueryClient } from "@tanstack/react-query"
import { Link } from "@tanstack/react-router" import { Link as RouterLink } from "@tanstack/react-router"
import { FiBriefcase, FiHome, FiSettings, FiUsers } from "react-icons/fi" import { FiBriefcase, FiHome, FiSettings, FiUsers } from "react-icons/fi"
import type { IconType } from "react-icons/lib"
import type { UserPublic } from "../../client" import type { UserPublic } from "@/client"
const items = [ const items = [
{ icon: FiHome, title: "Dashboard", path: "/" }, { icon: FiHome, title: "Dashboard", path: "/" },
@@ -15,39 +16,43 @@ interface SidebarItemsProps {
onClose?: () => void onClose?: () => void
} }
interface Item {
icon: IconType
title: string
path: string
}
const SidebarItems = ({ onClose }: SidebarItemsProps) => { const SidebarItems = ({ onClose }: SidebarItemsProps) => {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const textColor = useColorModeValue("ui.main", "ui.light")
const bgActive = useColorModeValue("#E2E8F0", "#4A5568")
const currentUser = queryClient.getQueryData<UserPublic>(["currentUser"]) const currentUser = queryClient.getQueryData<UserPublic>(["currentUser"])
const finalItems = currentUser?.is_superuser const finalItems: Item[] = currentUser?.is_superuser
? [...items, { icon: FiUsers, title: "Admin", path: "/admin" }] ? [...items, { icon: FiUsers, title: "Admin", path: "/admin" }]
: items : items
const listItems = finalItems.map(({ icon, title, path }) => ( const listItems = finalItems.map(({ icon, title, path }) => (
<Flex <RouterLink key={title} to={path} onClick={onClose}>
as={Link} <Flex
to={path} gap={4}
w="100%" px={4}
p={2} py={2}
key={title} _hover={{
activeProps={{ background: "gray.subtle",
style: { }}
background: bgActive, alignItems="center"
borderRadius: "12px", fontSize="sm"
}, >
}} <Icon as={icon} alignSelf="center" />
color={textColor} <Text ml={2}>{title}</Text>
onClick={onClose} </Flex>
> </RouterLink>
<Icon as={icon} alignSelf="center" />
<Text ml={2}>{title}</Text>
</Flex>
)) ))
return ( return (
<> <>
<Text fontSize="xs" px={4} py={2} fontWeight="bold">
Menu
</Text>
<Box>{listItems}</Box> <Box>{listItems}</Box>
</> </>
) )
@@ -0,0 +1,28 @@
import { IconButton } from "@chakra-ui/react"
import { BsThreeDotsVertical } from "react-icons/bs"
import { MenuContent, MenuRoot, MenuTrigger } from "../ui/menu"
import type { UserPublic } from "@/client"
import DeleteUser from "../Admin/DeleteUser"
import EditUser from "../Admin/EditUser"
interface UserActionsMenuProps {
user: UserPublic
disabled?: boolean
}
export const UserActionsMenu = ({ user, disabled }: UserActionsMenuProps) => {
return (
<MenuRoot>
<MenuTrigger asChild>
<IconButton variant="ghost" color="inherit" disabled={disabled}>
<BsThreeDotsVertical />
</IconButton>
</MenuTrigger>
<MenuContent>
<EditUser user={user} />
<DeleteUser id={user.id} />
</MenuContent>
</MenuRoot>
)
}
+43 -38
View File
@@ -1,19 +1,13 @@
import { import { Box, Button, Flex, Text } from "@chakra-ui/react"
Box,
IconButton,
Menu,
MenuButton,
MenuItem,
MenuList,
} from "@chakra-ui/react"
import { Link } from "@tanstack/react-router" import { Link } from "@tanstack/react-router"
import { FaUserAstronaut } from "react-icons/fa" import { FaUserAstronaut } from "react-icons/fa"
import { FiLogOut, FiUser } from "react-icons/fi" import { FiLogOut, FiUser } from "react-icons/fi"
import useAuth from "../../hooks/useAuth" import useAuth from "@/hooks/useAuth"
import { MenuContent, MenuItem, MenuRoot, MenuTrigger } from "../ui/menu"
const UserMenu = () => { const UserMenu = () => {
const { logout } = useAuth() const { user, logout } = useAuth()
const handleLogout = async () => { const handleLogout = async () => {
logout() logout()
@@ -22,36 +16,47 @@ const UserMenu = () => {
return ( return (
<> <>
{/* Desktop */} {/* Desktop */}
<Box <Flex>
display={{ base: "none", md: "block" }} <MenuRoot>
position="fixed" <MenuTrigger asChild p={2}>
top={4} <Button
right={4} data-testid="user-menu"
> variant="solid"
<Menu> maxW="150px"
<MenuButton truncate
as={IconButton}
aria-label="Options"
icon={<FaUserAstronaut color="white" fontSize="18px" />}
bg="ui.main"
isRound
data-testid="user-menu"
/>
<MenuList>
<MenuItem icon={<FiUser fontSize="18px" />} as={Link} to="settings">
My profile
</MenuItem>
<MenuItem
icon={<FiLogOut fontSize="18px" />}
onClick={handleLogout}
color="ui.danger"
fontWeight="bold"
> >
Log out <FaUserAstronaut fontSize="18" />
<Text>{user?.full_name || "User"}</Text>
</Button>
</MenuTrigger>
<MenuContent>
<Link to="settings">
<MenuItem
closeOnSelect
value="user-settings"
gap={2}
py={2}
style={{ cursor: "pointer" }}
>
<FiUser fontSize="18px" />
<Box flex="1">My Profile</Box>
</MenuItem>
</Link>
<MenuItem
value="logout"
gap={2}
py={2}
onClick={handleLogout}
style={{ cursor: "pointer" }}
>
<FiLogOut />
Log Out
</MenuItem> </MenuItem>
</MenuList> </MenuContent>
</Menu> </MenuRoot>
</Box> </Flex>
</> </>
) )
} }
+102 -70
View File
@@ -1,37 +1,41 @@
import {
Button,
FormControl,
FormErrorMessage,
FormLabel,
Input,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
} from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query" import { useMutation, useQueryClient } from "@tanstack/react-query"
import { type SubmitHandler, useForm } from "react-hook-form" import { type SubmitHandler, useForm } from "react-hook-form"
import { type ApiError, type ItemCreate, ItemsService } from "../../client" import {
import useCustomToast from "../../hooks/useCustomToast" Button,
import { handleError } from "../../utils" DialogActionTrigger,
DialogTitle,
Input,
Text,
VStack,
} from "@chakra-ui/react"
import { useState } from "react"
import { FaPlus } from "react-icons/fa"
interface AddItemProps { import { type ItemCreate, ItemsService } from "@/client"
isOpen: boolean import type { ApiError } from "@/client/core/ApiError"
onClose: () => void import useCustomToast from "@/hooks/useCustomToast"
} import { handleError } from "@/utils"
import {
DialogBody,
DialogCloseTrigger,
DialogContent,
DialogFooter,
DialogHeader,
DialogRoot,
DialogTrigger,
} from "../ui/dialog"
import { Field } from "../ui/field"
const AddItem = ({ isOpen, onClose }: AddItemProps) => { const AddItem = () => {
const [isOpen, setIsOpen] = useState(false)
const queryClient = useQueryClient() const queryClient = useQueryClient()
const showToast = useCustomToast() const { showSuccessToast } = useCustomToast()
const { const {
register, register,
handleSubmit, handleSubmit,
reset, reset,
formState: { errors, isSubmitting }, formState: { errors, isValid, isSubmitting },
} = useForm<ItemCreate>({ } = useForm<ItemCreate>({
mode: "onBlur", mode: "onBlur",
criteriaMode: "all", criteriaMode: "all",
@@ -45,12 +49,12 @@ const AddItem = ({ isOpen, onClose }: AddItemProps) => {
mutationFn: (data: ItemCreate) => mutationFn: (data: ItemCreate) =>
ItemsService.createItem({ requestBody: data }), ItemsService.createItem({ requestBody: data }),
onSuccess: () => { onSuccess: () => {
showToast("Success!", "Item created successfully.", "success") showSuccessToast("Item created successfully.")
reset() reset()
onClose() setIsOpen(false)
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
handleError(err, showToast) handleError(err)
}, },
onSettled: () => { onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["items"] }) queryClient.invalidateQueries({ queryKey: ["items"] })
@@ -62,52 +66,80 @@ const AddItem = ({ isOpen, onClose }: AddItemProps) => {
} }
return ( return (
<> <DialogRoot
<Modal size={{ base: "xs", md: "md" }}
isOpen={isOpen} placement="center"
onClose={onClose} open={isOpen}
size={{ base: "sm", md: "md" }} onOpenChange={({ open }) => setIsOpen(open)}
isCentered >
> <DialogTrigger asChild>
<ModalOverlay /> <Button value="add-item" my={4}>
<ModalContent as="form" onSubmit={handleSubmit(onSubmit)}> <FaPlus fontSize="16px" />
<ModalHeader>Add Item</ModalHeader> Add Item
<ModalCloseButton /> </Button>
<ModalBody pb={6}> </DialogTrigger>
<FormControl isRequired isInvalid={!!errors.title}> <DialogContent>
<FormLabel htmlFor="title">Title</FormLabel> <form onSubmit={handleSubmit(onSubmit)}>
<Input <DialogHeader>
id="title" <DialogTitle>Add Item</DialogTitle>
{...register("title", { </DialogHeader>
required: "Title is required.", <DialogBody>
})} <Text mb={4}>Fill in the details to add a new item.</Text>
placeholder="Title" <VStack gap={4}>
type="text" <Field
/> required
{errors.title && ( invalid={!!errors.title}
<FormErrorMessage>{errors.title.message}</FormErrorMessage> errorText={errors.title?.message}
)} label="Title"
</FormControl> >
<FormControl mt={4}> <Input
<FormLabel htmlFor="description">Description</FormLabel> id="title"
<Input {...register("title", {
id="description" required: "Title is required.",
{...register("description")} })}
placeholder="Description" placeholder="Title"
type="text" type="text"
/> />
</FormControl> </Field>
</ModalBody>
<ModalFooter gap={3}> <Field
<Button variant="primary" type="submit" isLoading={isSubmitting}> invalid={!!errors.description}
errorText={errors.description?.message}
label="Description"
>
<Input
id="description"
{...register("description")}
placeholder="Description"
type="text"
/>
</Field>
</VStack>
</DialogBody>
<DialogFooter gap={2}>
<DialogActionTrigger asChild>
<Button
variant="subtle"
colorPalette="gray"
disabled={isSubmitting}
>
Cancel
</Button>
</DialogActionTrigger>
<Button
variant="solid"
type="submit"
disabled={!isValid}
loading={isSubmitting}
>
Save Save
</Button> </Button>
<Button onClick={onClose}>Cancel</Button> </DialogFooter>
</ModalFooter> </form>
</ModalContent> <DialogCloseTrigger />
</Modal> </DialogContent>
</> </DialogRoot>
) )
} }
@@ -0,0 +1,104 @@
import { Button, DialogTitle, Text } from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { useState } from "react"
import { useForm } from "react-hook-form"
import { FiTrash2 } from "react-icons/fi"
import { ItemsService } from "@/client"
import {
DialogActionTrigger,
DialogBody,
DialogCloseTrigger,
DialogContent,
DialogFooter,
DialogHeader,
DialogRoot,
DialogTrigger,
} from "@/components/ui/dialog"
import useCustomToast from "@/hooks/useCustomToast"
const DeleteItem = ({ id }: { id: string }) => {
const [isOpen, setIsOpen] = useState(false)
const queryClient = useQueryClient()
const { showSuccessToast, showErrorToast } = useCustomToast()
const {
handleSubmit,
formState: { isSubmitting },
} = useForm()
const deleteItem = async (id: string) => {
await ItemsService.deleteItem({ id: id })
}
const mutation = useMutation({
mutationFn: deleteItem,
onSuccess: () => {
showSuccessToast("The item was deleted successfully")
setIsOpen(false)
},
onError: () => {
showErrorToast("An error occurred while deleting the item")
},
onSettled: () => {
queryClient.invalidateQueries()
},
})
const onSubmit = async () => {
mutation.mutate(id)
}
return (
<DialogRoot
size={{ base: "xs", md: "md" }}
placement="center"
role="alertdialog"
open={isOpen}
onOpenChange={({ open }) => setIsOpen(open)}
>
<DialogTrigger asChild>
<Button variant="ghost" size="sm" colorPalette="red">
<FiTrash2 fontSize="16px" />
Delete Item
</Button>
</DialogTrigger>
<DialogContent>
<form onSubmit={handleSubmit(onSubmit)}>
<DialogCloseTrigger />
<DialogHeader>
<DialogTitle>Delete Item</DialogTitle>
</DialogHeader>
<DialogBody>
<Text mb={4}>
This item will be permanently deleted. Are you sure? You will not
be able to undo this action.
</Text>
</DialogBody>
<DialogFooter gap={2}>
<DialogActionTrigger asChild>
<Button
variant="subtle"
colorPalette="gray"
disabled={isSubmitting}
>
Cancel
</Button>
</DialogActionTrigger>
<Button
variant="solid"
colorPalette="red"
type="submit"
loading={isSubmitting}
>
Delete
</Button>
</DialogFooter>
</form>
</DialogContent>
</DialogRoot>
)
}
export default DeleteItem
+110 -83
View File
@@ -1,123 +1,150 @@
import { import {
Button, Button,
FormControl, ButtonGroup,
FormErrorMessage, DialogActionTrigger,
FormLabel,
Input, Input,
Modal, Text,
ModalBody, VStack,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
} from "@chakra-ui/react" } from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query" import { useMutation, useQueryClient } from "@tanstack/react-query"
import { useState } from "react"
import { type SubmitHandler, useForm } from "react-hook-form" import { type SubmitHandler, useForm } from "react-hook-form"
import { FaExchangeAlt } from "react-icons/fa"
import { type ApiError, type ItemPublic, ItemsService } from "@/client"
import useCustomToast from "@/hooks/useCustomToast"
import { handleError } from "@/utils"
import { import {
type ApiError, DialogBody,
type ItemPublic, DialogCloseTrigger,
type ItemUpdate, DialogContent,
ItemsService, DialogFooter,
} from "../../client" DialogHeader,
import useCustomToast from "../../hooks/useCustomToast" DialogRoot,
import { handleError } from "../../utils" DialogTitle,
DialogTrigger,
} from "../ui/dialog"
import { Field } from "../ui/field"
interface EditItemProps { interface EditItemProps {
item: ItemPublic item: ItemPublic
isOpen: boolean
onClose: () => void
} }
const EditItem = ({ item, isOpen, onClose }: EditItemProps) => { interface ItemUpdateForm {
title: string
description?: string
}
const EditItem = ({ item }: EditItemProps) => {
const [isOpen, setIsOpen] = useState(false)
const queryClient = useQueryClient() const queryClient = useQueryClient()
const showToast = useCustomToast() const { showSuccessToast } = useCustomToast()
const { const {
register, register,
handleSubmit, handleSubmit,
reset, reset,
formState: { isSubmitting, errors, isDirty }, formState: { errors, isSubmitting },
} = useForm<ItemUpdate>({ } = useForm<ItemUpdateForm>({
mode: "onBlur", mode: "onBlur",
criteriaMode: "all", criteriaMode: "all",
defaultValues: item, defaultValues: {
...item,
description: item.description ?? undefined,
},
}) })
const mutation = useMutation({ const mutation = useMutation({
mutationFn: (data: ItemUpdate) => mutationFn: (data: ItemUpdateForm) =>
ItemsService.updateItem({ id: item.id, requestBody: data }), ItemsService.updateItem({ id: item.id, requestBody: data }),
onSuccess: () => { onSuccess: () => {
showToast("Success!", "Item updated successfully.", "success") showSuccessToast("Item updated successfully.")
onClose() reset()
setIsOpen(false)
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
handleError(err, showToast) handleError(err)
}, },
onSettled: () => { onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["items"] }) queryClient.invalidateQueries({ queryKey: ["items"] })
}, },
}) })
const onSubmit: SubmitHandler<ItemUpdate> = async (data) => { const onSubmit: SubmitHandler<ItemUpdateForm> = async (data) => {
mutation.mutate(data) mutation.mutate(data)
} }
const onCancel = () => {
reset()
onClose()
}
return ( return (
<> <DialogRoot
<Modal size={{ base: "xs", md: "md" }}
isOpen={isOpen} placement="center"
onClose={onClose} open={isOpen}
size={{ base: "sm", md: "md" }} onOpenChange={({ open }) => setIsOpen(open)}
isCentered >
> <DialogTrigger asChild>
<ModalOverlay /> <Button variant="ghost">
<ModalContent as="form" onSubmit={handleSubmit(onSubmit)}> <FaExchangeAlt fontSize="16px" />
<ModalHeader>Edit Item</ModalHeader> Edit Item
<ModalCloseButton /> </Button>
<ModalBody pb={6}> </DialogTrigger>
<FormControl isInvalid={!!errors.title}> <DialogContent>
<FormLabel htmlFor="title">Title</FormLabel> <form onSubmit={handleSubmit(onSubmit)}>
<Input <DialogHeader>
id="title" <DialogTitle>Edit Item</DialogTitle>
{...register("title", { </DialogHeader>
required: "Title is required", <DialogBody>
})} <Text mb={4}>Update the item details below.</Text>
type="text" <VStack gap={4}>
/> <Field
{errors.title && ( required
<FormErrorMessage>{errors.title.message}</FormErrorMessage> invalid={!!errors.title}
)} errorText={errors.title?.message}
</FormControl> label="Title"
<FormControl mt={4}> >
<FormLabel htmlFor="description">Description</FormLabel> <Input
<Input id="title"
id="description" {...register("title", {
{...register("description")} required: "Title is required",
placeholder="Description" })}
type="text" placeholder="Title"
/> type="text"
</FormControl> />
</ModalBody> </Field>
<ModalFooter gap={3}>
<Button <Field
variant="primary" invalid={!!errors.description}
type="submit" errorText={errors.description?.message}
isLoading={isSubmitting} label="Description"
isDisabled={!isDirty} >
> <Input
Save id="description"
</Button> {...register("description")}
<Button onClick={onCancel}>Cancel</Button> placeholder="Description"
</ModalFooter> type="text"
</ModalContent> />
</Modal> </Field>
</> </VStack>
</DialogBody>
<DialogFooter gap={2}>
<ButtonGroup>
<DialogActionTrigger asChild>
<Button
variant="subtle"
colorPalette="gray"
disabled={isSubmitting}
>
Cancel
</Button>
</DialogActionTrigger>
<Button variant="solid" type="submit" loading={isSubmitting}>
Save
</Button>
</ButtonGroup>
</DialogFooter>
</form>
<DialogCloseTrigger />
</DialogContent>
</DialogRoot>
) )
} }
@@ -0,0 +1,34 @@
import { Skeleton, Table } from "@chakra-ui/react"
const PendingItems = () => (
<Table.Root size={{ base: "sm", md: "md" }}>
<Table.Header>
<Table.Row>
<Table.ColumnHeader w="30%">ID</Table.ColumnHeader>
<Table.ColumnHeader w="30%">Title</Table.ColumnHeader>
<Table.ColumnHeader w="30%">Description</Table.ColumnHeader>
<Table.ColumnHeader w="10%">Actions</Table.ColumnHeader>
</Table.Row>
</Table.Header>
<Table.Body>
{[...Array(5)].map((_, index) => (
<Table.Row key={index}>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table.Root>
)
export default PendingItems
@@ -0,0 +1,38 @@
import { Skeleton, Table } from "@chakra-ui/react"
const PendingUsers = () => (
<Table.Root size={{ base: "sm", md: "md" }}>
<Table.Header>
<Table.Row>
<Table.ColumnHeader w="20%">Full name</Table.ColumnHeader>
<Table.ColumnHeader w="25%">Email</Table.ColumnHeader>
<Table.ColumnHeader w="15%">Role</Table.ColumnHeader>
<Table.ColumnHeader w="20%">Status</Table.ColumnHeader>
<Table.ColumnHeader w="20%">Actions</Table.ColumnHeader>
</Table.Row>
</Table.Header>
<Table.Body>
{[...Array(5)].map((_, index) => (
<Table.Row key={index}>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
<Table.Cell>
<Skeleton h="20px" />
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table.Root>
)
export default PendingUsers
@@ -1,15 +1,10 @@
import { import { Container, Heading, Stack } from "@chakra-ui/react"
Badge, import { useTheme } from "next-themes"
Container,
Heading, import { Radio, RadioGroup } from "@/components/ui/radio"
Radio,
RadioGroup,
Stack,
useColorMode,
} from "@chakra-ui/react"
const Appearance = () => { const Appearance = () => {
const { colorMode, toggleColorMode } = useColorMode() const { theme, setTheme } = useTheme()
return ( return (
<> <>
@@ -17,18 +12,16 @@ const Appearance = () => {
<Heading size="sm" py={4}> <Heading size="sm" py={4}>
Appearance Appearance
</Heading> </Heading>
<RadioGroup onChange={toggleColorMode} value={colorMode}>
<RadioGroup
onValueChange={(e) => setTheme(e.value)}
value={theme}
colorPalette="teal"
>
<Stack> <Stack>
{/* TODO: Add system default option */} <Radio value="system">System</Radio>
<Radio value="light" colorScheme="teal"> <Radio value="light">Light Mode</Radio>
Light Mode <Radio value="dark">Dark Mode</Radio>
<Badge ml="1" colorScheme="teal">
Default
</Badge>
</Radio>
<Radio value="dark" colorScheme="teal">
Dark Mode
</Radio>
</Stack> </Stack>
</RadioGroup> </RadioGroup>
</Container> </Container>
@@ -1,34 +1,25 @@
import { import { Box, Button, Container, Heading, VStack } from "@chakra-ui/react"
Box,
Button,
Container,
FormControl,
FormErrorMessage,
FormLabel,
Heading,
Input,
useColorModeValue,
} from "@chakra-ui/react"
import { useMutation } from "@tanstack/react-query" import { useMutation } from "@tanstack/react-query"
import { type SubmitHandler, useForm } from "react-hook-form" import { type SubmitHandler, useForm } from "react-hook-form"
import { FiLock } from "react-icons/fi"
import { type ApiError, type UpdatePassword, UsersService } from "../../client" import { type ApiError, type UpdatePassword, UsersService } from "@/client"
import useCustomToast from "../../hooks/useCustomToast" import useCustomToast from "@/hooks/useCustomToast"
import { confirmPasswordRules, handleError, passwordRules } from "../../utils" import { confirmPasswordRules, handleError, passwordRules } from "@/utils"
import { PasswordInput } from "../ui/password-input"
interface UpdatePasswordForm extends UpdatePassword { interface UpdatePasswordForm extends UpdatePassword {
confirm_password: string confirm_password: string
} }
const ChangePassword = () => { const ChangePassword = () => {
const color = useColorModeValue("inherit", "ui.light") const { showSuccessToast } = useCustomToast()
const showToast = useCustomToast()
const { const {
register, register,
handleSubmit, handleSubmit,
reset, reset,
getValues, getValues,
formState: { errors, isSubmitting }, formState: { errors, isValid, isSubmitting },
} = useForm<UpdatePasswordForm>({ } = useForm<UpdatePasswordForm>({
mode: "onBlur", mode: "onBlur",
criteriaMode: "all", criteriaMode: "all",
@@ -38,11 +29,11 @@ const ChangePassword = () => {
mutationFn: (data: UpdatePassword) => mutationFn: (data: UpdatePassword) =>
UsersService.updatePasswordMe({ requestBody: data }), UsersService.updatePasswordMe({ requestBody: data }),
onSuccess: () => { onSuccess: () => {
showToast("Success!", "Password updated successfully.", "success") showSuccessToast("Password updated successfully.")
reset() reset()
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
handleError(err, showToast) handleError(err)
}, },
}) })
@@ -57,60 +48,39 @@ const ChangePassword = () => {
Change Password Change Password
</Heading> </Heading>
<Box <Box
w={{ sm: "full", md: "50%" }} w={{ sm: "full", md: "300px" }}
as="form" as="form"
onSubmit={handleSubmit(onSubmit)} onSubmit={handleSubmit(onSubmit)}
> >
<FormControl isRequired isInvalid={!!errors.current_password}> <VStack gap={4}>
<FormLabel color={color} htmlFor="current_password"> <PasswordInput
Current Password type="current_password"
</FormLabel> startElement={<FiLock />}
<Input {...register("current_password", passwordRules())}
id="current_password" placeholder="Current Password"
{...register("current_password")} errors={errors}
placeholder="Password"
type="password"
w="auto"
/> />
{errors.current_password && ( <PasswordInput
<FormErrorMessage> type="new_password"
{errors.current_password.message} startElement={<FiLock />}
</FormErrorMessage>
)}
</FormControl>
<FormControl mt={4} isRequired isInvalid={!!errors.new_password}>
<FormLabel htmlFor="password">Set Password</FormLabel>
<Input
id="password"
{...register("new_password", passwordRules())} {...register("new_password", passwordRules())}
placeholder="Password" placeholder="New Password"
type="password" errors={errors}
w="auto"
/> />
{errors.new_password && ( <PasswordInput
<FormErrorMessage>{errors.new_password.message}</FormErrorMessage> type="confirm_password"
)} startElement={<FiLock />}
</FormControl>
<FormControl mt={4} isRequired isInvalid={!!errors.confirm_password}>
<FormLabel htmlFor="confirm_password">Confirm Password</FormLabel>
<Input
id="confirm_password"
{...register("confirm_password", confirmPasswordRules(getValues))} {...register("confirm_password", confirmPasswordRules(getValues))}
placeholder="Password" placeholder="Confirm Password"
type="password" errors={errors}
w="auto"
/> />
{errors.confirm_password && ( </VStack>
<FormErrorMessage>
{errors.confirm_password.message}
</FormErrorMessage>
)}
</FormControl>
<Button <Button
variant="primary" variant="solid"
mt={4} mt={4}
type="submit" type="submit"
isLoading={isSubmitting} loading={isSubmitting}
disabled={!isValid}
> >
Save Save
</Button> </Button>
@@ -1,35 +1,19 @@
import { import { Container, Heading, Text } from "@chakra-ui/react"
Button,
Container,
Heading,
Text,
useDisclosure,
} from "@chakra-ui/react"
import DeleteConfirmation from "./DeleteConfirmation" import DeleteConfirmation from "./DeleteConfirmation"
const DeleteAccount = () => { const DeleteAccount = () => {
const confirmationModal = useDisclosure()
return ( return (
<> <Container maxW="full">
<Container maxW="full"> <Heading size="sm" py={4}>
<Heading size="sm" py={4}> Delete Account
Delete Account </Heading>
</Heading> <Text>
<Text> Permanently delete your data and everything associated with your
Permanently delete your data and everything associated with your account.
account. </Text>
</Text> <DeleteConfirmation />
<Button variant="danger" mt={4} onClick={confirmationModal.onOpen}> </Container>
Delete
</Button>
<DeleteConfirmation
isOpen={confirmationModal.isOpen}
onClose={confirmationModal.onClose}
/>
</Container>
</>
) )
} }
export default DeleteAccount export default DeleteAccount
@@ -1,30 +1,28 @@
import { import { Button, ButtonGroup, Text } from "@chakra-ui/react"
AlertDialog,
AlertDialogBody,
AlertDialogContent,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogOverlay,
Button,
} from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query" import { useMutation, useQueryClient } from "@tanstack/react-query"
import React from "react" import { useState } from "react"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { type ApiError, UsersService } from "../../client" import { type ApiError, UsersService } from "@/client"
import useAuth from "../../hooks/useAuth" import {
import useCustomToast from "../../hooks/useCustomToast" DialogActionTrigger,
import { handleError } from "../../utils" DialogBody,
DialogCloseTrigger,
DialogContent,
DialogFooter,
DialogHeader,
DialogRoot,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import useAuth from "@/hooks/useAuth"
import useCustomToast from "@/hooks/useCustomToast"
import { handleError } from "@/utils"
interface DeleteProps { const DeleteConfirmation = () => {
isOpen: boolean const [isOpen, setIsOpen] = useState(false)
onClose: () => void
}
const DeleteConfirmation = ({ isOpen, onClose }: DeleteProps) => {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const showToast = useCustomToast() const { showSuccessToast } = useCustomToast()
const cancelRef = React.useRef<HTMLButtonElement | null>(null)
const { const {
handleSubmit, handleSubmit,
formState: { isSubmitting }, formState: { isSubmitting },
@@ -34,16 +32,12 @@ const DeleteConfirmation = ({ isOpen, onClose }: DeleteProps) => {
const mutation = useMutation({ const mutation = useMutation({
mutationFn: () => UsersService.deleteUserMe(), mutationFn: () => UsersService.deleteUserMe(),
onSuccess: () => { onSuccess: () => {
showToast( showSuccessToast("Your account has been successfully deleted")
"Success", setIsOpen(false)
"Your account has been successfully deleted.",
"success",
)
logout() logout()
onClose()
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
handleError(err, showToast) handleError(err)
}, },
onSettled: () => { onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["currentUser"] }) queryClient.invalidateQueries({ queryKey: ["currentUser"] })
@@ -56,39 +50,58 @@ const DeleteConfirmation = ({ isOpen, onClose }: DeleteProps) => {
return ( return (
<> <>
<AlertDialog <DialogRoot
isOpen={isOpen} size={{ base: "xs", md: "md" }}
onClose={onClose} role="alertdialog"
leastDestructiveRef={cancelRef} placement="center"
size={{ base: "sm", md: "md" }} open={isOpen}
isCentered onOpenChange={({ open }) => setIsOpen(open)}
> >
<AlertDialogOverlay> <DialogTrigger asChild>
<AlertDialogContent as="form" onSubmit={handleSubmit(onSubmit)}> <Button variant="solid" colorPalette="red" mt={4}>
<AlertDialogHeader>Confirmation Required</AlertDialogHeader> Delete
</Button>
</DialogTrigger>
<AlertDialogBody> <DialogContent>
All your account data will be{" "} <form onSubmit={handleSubmit(onSubmit)}>
<strong>permanently deleted.</strong> If you are sure, please <DialogCloseTrigger />
click <strong>"Confirm"</strong> to proceed. This action cannot be <DialogHeader>
undone. <DialogTitle>Confirmation Required</DialogTitle>
</AlertDialogBody> </DialogHeader>
<DialogBody>
<Text mb={4}>
All your account data will be{" "}
<strong>permanently deleted.</strong> If you are sure, please
click <strong>"Confirm"</strong> to proceed. This action cannot
be undone.
</Text>
</DialogBody>
<AlertDialogFooter gap={3}> <DialogFooter gap={2}>
<Button variant="danger" type="submit" isLoading={isSubmitting}> <ButtonGroup>
Confirm <DialogActionTrigger asChild>
</Button> <Button
<Button variant="subtle"
ref={cancelRef} colorPalette="gray"
onClick={onClose} disabled={isSubmitting}
isDisabled={isSubmitting} >
> Cancel
Cancel </Button>
</Button> </DialogActionTrigger>
</AlertDialogFooter> <Button
</AlertDialogContent> variant="solid"
</AlertDialogOverlay> colorPalette="red"
</AlertDialog> type="submit"
loading={isSubmitting}
>
Delete
</Button>
</ButtonGroup>
</DialogFooter>
</form>
</DialogContent>
</DialogRoot>
</> </>
) )
} }
@@ -3,13 +3,9 @@ import {
Button, Button,
Container, Container,
Flex, Flex,
FormControl,
FormErrorMessage,
FormLabel,
Heading, Heading,
Input, Input,
Text, Text,
useColorModeValue,
} from "@chakra-ui/react" } from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query" import { useMutation, useQueryClient } from "@tanstack/react-query"
import { useState } from "react" import { useState } from "react"
@@ -20,15 +16,15 @@ import {
type UserPublic, type UserPublic,
type UserUpdateMe, type UserUpdateMe,
UsersService, UsersService,
} from "../../client" } from "@/client"
import useAuth from "../../hooks/useAuth" import useAuth from "@/hooks/useAuth"
import useCustomToast from "../../hooks/useCustomToast" import useCustomToast from "@/hooks/useCustomToast"
import { emailPattern, handleError } from "../../utils" import { emailPattern, handleError } from "@/utils"
import { Field } from "../ui/field"
const UserInformation = () => { const UserInformation = () => {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const color = useColorModeValue("inherit", "ui.light") const { showSuccessToast } = useCustomToast()
const showToast = useCustomToast()
const [editMode, setEditMode] = useState(false) const [editMode, setEditMode] = useState(false)
const { user: currentUser } = useAuth() const { user: currentUser } = useAuth()
const { const {
@@ -54,10 +50,10 @@ const UserInformation = () => {
mutationFn: (data: UserUpdateMe) => mutationFn: (data: UserUpdateMe) =>
UsersService.updateUserMe({ requestBody: data }), UsersService.updateUserMe({ requestBody: data }),
onSuccess: () => { onSuccess: () => {
showToast("Success!", "User updated successfully.", "success") showSuccessToast("User updated successfully.")
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
handleError(err, showToast) handleError(err)
}, },
onSettled: () => { onSettled: () => {
queryClient.invalidateQueries() queryClient.invalidateQueries()
@@ -84,13 +80,9 @@ const UserInformation = () => {
as="form" as="form"
onSubmit={handleSubmit(onSubmit)} onSubmit={handleSubmit(onSubmit)}
> >
<FormControl> <Field label="Full name">
<FormLabel color={color} htmlFor="name">
Full name
</FormLabel>
{editMode ? ( {editMode ? (
<Input <Input
id="name"
{...register("full_name", { maxLength: 30 })} {...register("full_name", { maxLength: 30 })}
type="text" type="text"
size="md" size="md"
@@ -98,23 +90,24 @@ const UserInformation = () => {
/> />
) : ( ) : (
<Text <Text
size="md" fontSize="md"
py={2} py={2}
color={!currentUser?.full_name ? "ui.dim" : "inherit"} color={!currentUser?.full_name ? "gray" : "inherit"}
isTruncated truncate
maxWidth="250px" maxWidth="250px"
> >
{currentUser?.full_name || "N/A"} {currentUser?.full_name || "N/A"}
</Text> </Text>
)} )}
</FormControl> </Field>
<FormControl mt={4} isInvalid={!!errors.email}> <Field
<FormLabel color={color} htmlFor="email"> mt={4}
Email label="Email"
</FormLabel> invalid={!!errors.email}
errorText={errors.email?.message}
>
{editMode ? ( {editMode ? (
<Input <Input
id="email"
{...register("email", { {...register("email", {
required: "Email is required", required: "Email is required",
pattern: emailPattern, pattern: emailPattern,
@@ -124,26 +117,28 @@ const UserInformation = () => {
w="auto" w="auto"
/> />
) : ( ) : (
<Text size="md" py={2} isTruncated maxWidth="250px"> <Text fontSize="md" py={2} truncate maxWidth="250px">
{currentUser?.email} {currentUser?.email}
</Text> </Text>
)} )}
{errors.email && ( </Field>
<FormErrorMessage>{errors.email.message}</FormErrorMessage>
)}
</FormControl>
<Flex mt={4} gap={3}> <Flex mt={4} gap={3}>
<Button <Button
variant="primary" variant="solid"
onClick={toggleEditMode} onClick={toggleEditMode}
type={editMode ? "button" : "submit"} type={editMode ? "button" : "submit"}
isLoading={editMode ? isSubmitting : false} loading={editMode ? isSubmitting : false}
isDisabled={editMode ? !isDirty || !getValues("email") : false} disabled={editMode ? !isDirty || !getValues("email") : false}
> >
{editMode ? "Save" : "Edit"} {editMode ? "Save" : "Edit"}
</Button> </Button>
{editMode && ( {editMode && (
<Button onClick={onCancel} isDisabled={isSubmitting}> <Button
variant="subtle"
colorPalette="gray"
onClick={onCancel}
disabled={isSubmitting}
>
Cancel Cancel
</Button> </Button>
)} )}
+40
View File
@@ -0,0 +1,40 @@
import type { ButtonProps as ChakraButtonProps } from "@chakra-ui/react"
import {
AbsoluteCenter,
Button as ChakraButton,
Span,
Spinner,
} from "@chakra-ui/react"
import * as React from "react"
interface ButtonLoadingProps {
loading?: boolean
loadingText?: React.ReactNode
}
export interface ButtonProps extends ChakraButtonProps, ButtonLoadingProps {}
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
function Button(props, ref) {
const { loading, disabled, loadingText, children, ...rest } = props
return (
<ChakraButton disabled={loading || disabled} ref={ref} {...rest}>
{loading && !loadingText ? (
<>
<AbsoluteCenter display="inline-flex">
<Spinner size="inherit" color="inherit" />
</AbsoluteCenter>
<Span opacity={0}>{children}</Span>
</>
) : loading && loadingText ? (
<>
<Spinner size="inherit" color="inherit" />
{loadingText}
</>
) : (
children
)}
</ChakraButton>
)
},
)
+25
View File
@@ -0,0 +1,25 @@
import { Checkbox as ChakraCheckbox } from "@chakra-ui/react"
import * as React from "react"
export interface CheckboxProps extends ChakraCheckbox.RootProps {
icon?: React.ReactNode
inputProps?: React.InputHTMLAttributes<HTMLInputElement>
rootRef?: React.Ref<HTMLLabelElement>
}
export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
function Checkbox(props, ref) {
const { icon, children, inputProps, rootRef, ...rest } = props
return (
<ChakraCheckbox.Root ref={rootRef} {...rest}>
<ChakraCheckbox.HiddenInput ref={ref} {...inputProps} />
<ChakraCheckbox.Control>
{icon || <ChakraCheckbox.Indicator />}
</ChakraCheckbox.Control>
{children != null && (
<ChakraCheckbox.Label>{children}</ChakraCheckbox.Label>
)}
</ChakraCheckbox.Root>
)
},
)
@@ -0,0 +1,17 @@
import type { ButtonProps } from "@chakra-ui/react"
import { IconButton as ChakraIconButton } from "@chakra-ui/react"
import * as React from "react"
import { LuX } from "react-icons/lu"
export type CloseButtonProps = ButtonProps
export const CloseButton = React.forwardRef<
HTMLButtonElement,
CloseButtonProps
>(function CloseButton(props, ref) {
return (
<ChakraIconButton variant="ghost" aria-label="Close" ref={ref} {...props}>
{props.children ?? <LuX />}
</ChakraIconButton>
)
})
+107
View File
@@ -0,0 +1,107 @@
"use client"
import type { IconButtonProps, SpanProps } from "@chakra-ui/react"
import { ClientOnly, IconButton, Skeleton, Span } from "@chakra-ui/react"
import { ThemeProvider, useTheme } from "next-themes"
import type { ThemeProviderProps } from "next-themes"
import * as React from "react"
import { LuMoon, LuSun } from "react-icons/lu"
export interface ColorModeProviderProps extends ThemeProviderProps {}
export function ColorModeProvider(props: ColorModeProviderProps) {
return (
<ThemeProvider attribute="class" disableTransitionOnChange {...props} />
)
}
export type ColorMode = "light" | "dark"
export interface UseColorModeReturn {
colorMode: ColorMode
setColorMode: (colorMode: ColorMode) => void
toggleColorMode: () => void
}
export function useColorMode(): UseColorModeReturn {
const { resolvedTheme, setTheme } = useTheme()
const toggleColorMode = () => {
setTheme(resolvedTheme === "dark" ? "light" : "dark")
}
return {
colorMode: resolvedTheme as ColorMode,
setColorMode: setTheme,
toggleColorMode,
}
}
export function useColorModeValue<T>(light: T, dark: T) {
const { colorMode } = useColorMode()
return colorMode === "dark" ? dark : light
}
export function ColorModeIcon() {
const { colorMode } = useColorMode()
return colorMode === "dark" ? <LuMoon /> : <LuSun />
}
interface ColorModeButtonProps extends Omit<IconButtonProps, "aria-label"> {}
export const ColorModeButton = React.forwardRef<
HTMLButtonElement,
ColorModeButtonProps
>(function ColorModeButton(props, ref) {
const { toggleColorMode } = useColorMode()
return (
<ClientOnly fallback={<Skeleton boxSize="8" />}>
<IconButton
onClick={toggleColorMode}
variant="ghost"
aria-label="Toggle color mode"
size="sm"
ref={ref}
{...props}
css={{
_icon: {
width: "5",
height: "5",
},
}}
>
<ColorModeIcon />
</IconButton>
</ClientOnly>
)
})
export const LightMode = React.forwardRef<HTMLSpanElement, SpanProps>(
function LightMode(props, ref) {
return (
<Span
color="fg"
display="contents"
className="chakra-theme light"
colorPalette="gray"
colorScheme="light"
ref={ref}
{...props}
/>
)
},
)
export const DarkMode = React.forwardRef<HTMLSpanElement, SpanProps>(
function DarkMode(props, ref) {
return (
<Span
color="fg"
display="contents"
className="chakra-theme dark"
colorPalette="gray"
colorScheme="dark"
ref={ref}
{...props}
/>
)
},
)
+62
View File
@@ -0,0 +1,62 @@
import { Dialog as ChakraDialog, Portal } from "@chakra-ui/react"
import * as React from "react"
import { CloseButton } from "./close-button"
interface DialogContentProps extends ChakraDialog.ContentProps {
portalled?: boolean
portalRef?: React.RefObject<HTMLElement>
backdrop?: boolean
}
export const DialogContent = React.forwardRef<
HTMLDivElement,
DialogContentProps
>(function DialogContent(props, ref) {
const {
children,
portalled = true,
portalRef,
backdrop = true,
...rest
} = props
return (
<Portal disabled={!portalled} container={portalRef}>
{backdrop && <ChakraDialog.Backdrop />}
<ChakraDialog.Positioner>
<ChakraDialog.Content ref={ref} {...rest} asChild={false}>
{children}
</ChakraDialog.Content>
</ChakraDialog.Positioner>
</Portal>
)
})
export const DialogCloseTrigger = React.forwardRef<
HTMLButtonElement,
ChakraDialog.CloseTriggerProps
>(function DialogCloseTrigger(props, ref) {
return (
<ChakraDialog.CloseTrigger
position="absolute"
top="2"
insetEnd="2"
{...props}
asChild
>
<CloseButton size="sm" ref={ref}>
{props.children}
</CloseButton>
</ChakraDialog.CloseTrigger>
)
})
export const DialogRoot = ChakraDialog.Root
export const DialogFooter = ChakraDialog.Footer
export const DialogHeader = ChakraDialog.Header
export const DialogBody = ChakraDialog.Body
export const DialogBackdrop = ChakraDialog.Backdrop
export const DialogTitle = ChakraDialog.Title
export const DialogDescription = ChakraDialog.Description
export const DialogTrigger = ChakraDialog.Trigger
export const DialogActionTrigger = ChakraDialog.ActionTrigger
+52
View File
@@ -0,0 +1,52 @@
import { Drawer as ChakraDrawer, Portal } from "@chakra-ui/react"
import * as React from "react"
import { CloseButton } from "./close-button"
interface DrawerContentProps extends ChakraDrawer.ContentProps {
portalled?: boolean
portalRef?: React.RefObject<HTMLElement>
offset?: ChakraDrawer.ContentProps["padding"]
}
export const DrawerContent = React.forwardRef<
HTMLDivElement,
DrawerContentProps
>(function DrawerContent(props, ref) {
const { children, portalled = true, portalRef, offset, ...rest } = props
return (
<Portal disabled={!portalled} container={portalRef}>
<ChakraDrawer.Positioner padding={offset}>
<ChakraDrawer.Content ref={ref} {...rest} asChild={false}>
{children}
</ChakraDrawer.Content>
</ChakraDrawer.Positioner>
</Portal>
)
})
export const DrawerCloseTrigger = React.forwardRef<
HTMLButtonElement,
ChakraDrawer.CloseTriggerProps
>(function DrawerCloseTrigger(props, ref) {
return (
<ChakraDrawer.CloseTrigger
position="absolute"
top="2"
insetEnd="2"
{...props}
asChild
>
<CloseButton size="sm" ref={ref} />
</ChakraDrawer.CloseTrigger>
)
})
export const DrawerTrigger = ChakraDrawer.Trigger
export const DrawerRoot = ChakraDrawer.Root
export const DrawerFooter = ChakraDrawer.Footer
export const DrawerHeader = ChakraDrawer.Header
export const DrawerBody = ChakraDrawer.Body
export const DrawerBackdrop = ChakraDrawer.Backdrop
export const DrawerDescription = ChakraDrawer.Description
export const DrawerTitle = ChakraDrawer.Title
export const DrawerActionTrigger = ChakraDrawer.ActionTrigger
+33
View File
@@ -0,0 +1,33 @@
import { Field as ChakraField } from "@chakra-ui/react"
import * as React from "react"
export interface FieldProps extends Omit<ChakraField.RootProps, "label"> {
label?: React.ReactNode
helperText?: React.ReactNode
errorText?: React.ReactNode
optionalText?: React.ReactNode
}
export const Field = React.forwardRef<HTMLDivElement, FieldProps>(
function Field(props, ref) {
const { label, children, helperText, errorText, optionalText, ...rest } =
props
return (
<ChakraField.Root ref={ref} {...rest}>
{label && (
<ChakraField.Label>
{label}
<ChakraField.RequiredIndicator fallback={optionalText} />
</ChakraField.Label>
)}
{children}
{helperText && (
<ChakraField.HelperText>{helperText}</ChakraField.HelperText>
)}
{errorText && (
<ChakraField.ErrorText>{errorText}</ChakraField.ErrorText>
)}
</ChakraField.Root>
)
},
)
@@ -0,0 +1,53 @@
import type { BoxProps, InputElementProps } from "@chakra-ui/react"
import { Group, InputElement } from "@chakra-ui/react"
import * as React from "react"
export interface InputGroupProps extends BoxProps {
startElementProps?: InputElementProps
endElementProps?: InputElementProps
startElement?: React.ReactNode
endElement?: React.ReactNode
children: React.ReactElement<InputElementProps>
startOffset?: InputElementProps["paddingStart"]
endOffset?: InputElementProps["paddingEnd"]
}
export const InputGroup = React.forwardRef<HTMLDivElement, InputGroupProps>(
function InputGroup(props, ref) {
const {
startElement,
startElementProps,
endElement,
endElementProps,
children,
startOffset = "6px",
endOffset = "6px",
...rest
} = props
const child =
React.Children.only<React.ReactElement<InputElementProps>>(children)
return (
<Group ref={ref} {...rest}>
{startElement && (
<InputElement pointerEvents="none" {...startElementProps}>
{startElement}
</InputElement>
)}
{React.cloneElement(child, {
...(startElement && {
ps: `calc(var(--input-height) - ${startOffset})`,
}),
...(endElement && { pe: `calc(var(--input-height) - ${endOffset})` }),
...children.props,
})}
{endElement && (
<InputElement placement="end" {...endElementProps}>
{endElement}
</InputElement>
)}
</Group>
)
},
)
@@ -0,0 +1,12 @@
"use client"
import type { HTMLChakraProps, RecipeProps } from "@chakra-ui/react"
import { createRecipeContext } from "@chakra-ui/react"
export interface LinkButtonProps
extends HTMLChakraProps<"a", RecipeProps<"button">> {}
const { withContext } = createRecipeContext({ key: "button" })
// Replace "a" with your framework's link component
export const LinkButton = withContext<HTMLAnchorElement, LinkButtonProps>("a")
+112
View File
@@ -0,0 +1,112 @@
"use client"
import { AbsoluteCenter, Menu as ChakraMenu, Portal } from "@chakra-ui/react"
import * as React from "react"
import { LuCheck, LuChevronRight } from "react-icons/lu"
interface MenuContentProps extends ChakraMenu.ContentProps {
portalled?: boolean
portalRef?: React.RefObject<HTMLElement>
}
export const MenuContent = React.forwardRef<HTMLDivElement, MenuContentProps>(
function MenuContent(props, ref) {
const { portalled = true, portalRef, ...rest } = props
return (
<Portal disabled={!portalled} container={portalRef}>
<ChakraMenu.Positioner>
<ChakraMenu.Content ref={ref} {...rest} />
</ChakraMenu.Positioner>
</Portal>
)
},
)
export const MenuArrow = React.forwardRef<
HTMLDivElement,
ChakraMenu.ArrowProps
>(function MenuArrow(props, ref) {
return (
<ChakraMenu.Arrow ref={ref} {...props}>
<ChakraMenu.ArrowTip />
</ChakraMenu.Arrow>
)
})
export const MenuCheckboxItem = React.forwardRef<
HTMLDivElement,
ChakraMenu.CheckboxItemProps
>(function MenuCheckboxItem(props, ref) {
return (
<ChakraMenu.CheckboxItem ps="8" ref={ref} {...props}>
<AbsoluteCenter axis="horizontal" insetStart="4" asChild>
<ChakraMenu.ItemIndicator>
<LuCheck />
</ChakraMenu.ItemIndicator>
</AbsoluteCenter>
{props.children}
</ChakraMenu.CheckboxItem>
)
})
export const MenuRadioItem = React.forwardRef<
HTMLDivElement,
ChakraMenu.RadioItemProps
>(function MenuRadioItem(props, ref) {
const { children, ...rest } = props
return (
<ChakraMenu.RadioItem ps="8" ref={ref} {...rest}>
<AbsoluteCenter axis="horizontal" insetStart="4" asChild>
<ChakraMenu.ItemIndicator>
<LuCheck />
</ChakraMenu.ItemIndicator>
</AbsoluteCenter>
<ChakraMenu.ItemText>{children}</ChakraMenu.ItemText>
</ChakraMenu.RadioItem>
)
})
export const MenuItemGroup = React.forwardRef<
HTMLDivElement,
ChakraMenu.ItemGroupProps
>(function MenuItemGroup(props, ref) {
const { title, children, ...rest } = props
return (
<ChakraMenu.ItemGroup ref={ref} {...rest}>
{title && (
<ChakraMenu.ItemGroupLabel userSelect="none">
{title}
</ChakraMenu.ItemGroupLabel>
)}
{children}
</ChakraMenu.ItemGroup>
)
})
export interface MenuTriggerItemProps extends ChakraMenu.ItemProps {
startIcon?: React.ReactNode
}
export const MenuTriggerItem = React.forwardRef<
HTMLDivElement,
MenuTriggerItemProps
>(function MenuTriggerItem(props, ref) {
const { startIcon, children, ...rest } = props
return (
<ChakraMenu.TriggerItem ref={ref} {...rest}>
{startIcon}
{children}
<LuChevronRight />
</ChakraMenu.TriggerItem>
)
})
export const MenuRadioItemGroup = ChakraMenu.RadioItemGroup
export const MenuContextTrigger = ChakraMenu.ContextTrigger
export const MenuRoot = ChakraMenu.Root
export const MenuSeparator = ChakraMenu.Separator
export const MenuItem = ChakraMenu.Item
export const MenuItemText = ChakraMenu.ItemText
export const MenuItemCommand = ChakraMenu.ItemCommand
export const MenuTrigger = ChakraMenu.Trigger
+211
View File
@@ -0,0 +1,211 @@
"use client"
import type { ButtonProps, TextProps } from "@chakra-ui/react"
import {
Button,
Pagination as ChakraPagination,
IconButton,
Text,
createContext,
usePaginationContext,
} from "@chakra-ui/react"
import * as React from "react"
import {
HiChevronLeft,
HiChevronRight,
HiMiniEllipsisHorizontal,
} from "react-icons/hi2"
import { LinkButton } from "./link-button"
interface ButtonVariantMap {
current: ButtonProps["variant"]
default: ButtonProps["variant"]
ellipsis: ButtonProps["variant"]
}
type PaginationVariant = "outline" | "solid" | "subtle"
interface ButtonVariantContext {
size: ButtonProps["size"]
variantMap: ButtonVariantMap
getHref?: (page: number) => string
}
const [RootPropsProvider, useRootProps] = createContext<ButtonVariantContext>({
name: "RootPropsProvider",
})
export interface PaginationRootProps
extends Omit<ChakraPagination.RootProps, "type"> {
size?: ButtonProps["size"]
variant?: PaginationVariant
getHref?: (page: number) => string
}
const variantMap: Record<PaginationVariant, ButtonVariantMap> = {
outline: { default: "ghost", ellipsis: "plain", current: "outline" },
solid: { default: "outline", ellipsis: "outline", current: "solid" },
subtle: { default: "ghost", ellipsis: "plain", current: "subtle" },
}
export const PaginationRoot = React.forwardRef<
HTMLDivElement,
PaginationRootProps
>(function PaginationRoot(props, ref) {
const { size = "sm", variant = "outline", getHref, ...rest } = props
return (
<RootPropsProvider
value={{ size, variantMap: variantMap[variant], getHref }}
>
<ChakraPagination.Root
ref={ref}
type={getHref ? "link" : "button"}
{...rest}
/>
</RootPropsProvider>
)
})
export const PaginationEllipsis = React.forwardRef<
HTMLDivElement,
ChakraPagination.EllipsisProps
>(function PaginationEllipsis(props, ref) {
const { size, variantMap } = useRootProps()
return (
<ChakraPagination.Ellipsis ref={ref} {...props} asChild>
<Button as="span" variant={variantMap.ellipsis} size={size}>
<HiMiniEllipsisHorizontal />
</Button>
</ChakraPagination.Ellipsis>
)
})
export const PaginationItem = React.forwardRef<
HTMLButtonElement,
ChakraPagination.ItemProps
>(function PaginationItem(props, ref) {
const { page } = usePaginationContext()
const { size, variantMap, getHref } = useRootProps()
const current = page === props.value
const variant = current ? variantMap.current : variantMap.default
if (getHref) {
return (
<LinkButton href={getHref(props.value)} variant={variant} size={size}>
{props.value}
</LinkButton>
)
}
return (
<ChakraPagination.Item ref={ref} {...props} asChild>
<Button variant={variant} size={size}>
{props.value}
</Button>
</ChakraPagination.Item>
)
})
export const PaginationPrevTrigger = React.forwardRef<
HTMLButtonElement,
ChakraPagination.PrevTriggerProps
>(function PaginationPrevTrigger(props, ref) {
const { size, variantMap, getHref } = useRootProps()
const { previousPage } = usePaginationContext()
if (getHref) {
return (
<LinkButton
href={previousPage != null ? getHref(previousPage) : undefined}
variant={variantMap.default}
size={size}
>
<HiChevronLeft />
</LinkButton>
)
}
return (
<ChakraPagination.PrevTrigger ref={ref} asChild {...props}>
<IconButton variant={variantMap.default} size={size}>
<HiChevronLeft />
</IconButton>
</ChakraPagination.PrevTrigger>
)
})
export const PaginationNextTrigger = React.forwardRef<
HTMLButtonElement,
ChakraPagination.NextTriggerProps
>(function PaginationNextTrigger(props, ref) {
const { size, variantMap, getHref } = useRootProps()
const { nextPage } = usePaginationContext()
if (getHref) {
return (
<LinkButton
href={nextPage != null ? getHref(nextPage) : undefined}
variant={variantMap.default}
size={size}
>
<HiChevronRight />
</LinkButton>
)
}
return (
<ChakraPagination.NextTrigger ref={ref} asChild {...props}>
<IconButton variant={variantMap.default} size={size}>
<HiChevronRight />
</IconButton>
</ChakraPagination.NextTrigger>
)
})
export const PaginationItems = (props: React.HTMLAttributes<HTMLElement>) => {
return (
<ChakraPagination.Context>
{({ pages }) =>
pages.map((page, index) => {
return page.type === "ellipsis" ? (
<PaginationEllipsis key={index} index={index} {...props} />
) : (
<PaginationItem
key={index}
type="page"
value={page.value}
{...props}
/>
)
})
}
</ChakraPagination.Context>
)
}
interface PageTextProps extends TextProps {
format?: "short" | "compact" | "long"
}
export const PaginationPageText = React.forwardRef<
HTMLParagraphElement,
PageTextProps
>(function PaginationPageText(props, ref) {
const { format = "compact", ...rest } = props
const { page, totalPages, pageRange, count } = usePaginationContext()
const content = React.useMemo(() => {
if (format === "short") return `${page} / ${totalPages}`
if (format === "compact") return `${page} of ${totalPages}`
return `${pageRange.start + 1} - ${Math.min(
pageRange.end,
count,
)} of ${count}`
}, [format, page, totalPages, pageRange, count])
return (
<Text fontWeight="medium" ref={ref} {...rest}>
{content}
</Text>
)
})
@@ -0,0 +1,162 @@
"use client"
import type {
ButtonProps,
GroupProps,
InputProps,
StackProps,
} from "@chakra-ui/react"
import {
Box,
HStack,
IconButton,
Input,
Stack,
mergeRefs,
useControllableState,
} from "@chakra-ui/react"
import { forwardRef, useRef } from "react"
import { FiEye, FiEyeOff } from "react-icons/fi"
import { Field } from "./field"
import { InputGroup } from "./input-group"
export interface PasswordVisibilityProps {
defaultVisible?: boolean
visible?: boolean
onVisibleChange?: (visible: boolean) => void
visibilityIcon?: { on: React.ReactNode; off: React.ReactNode }
}
export interface PasswordInputProps
extends InputProps,
PasswordVisibilityProps {
rootProps?: GroupProps
startElement?: React.ReactNode
type: string
errors: any
}
export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
function PasswordInput(props, ref) {
const {
rootProps,
defaultVisible,
visible: visibleProp,
onVisibleChange,
visibilityIcon = { on: <FiEye />, off: <FiEyeOff /> },
startElement,
type,
errors,
...rest
} = props
const [visible, setVisible] = useControllableState({
value: visibleProp,
defaultValue: defaultVisible || false,
onChange: onVisibleChange,
})
const inputRef = useRef<HTMLInputElement>(null)
return (
<Field
invalid={!!errors[type]}
errorText={errors[type]?.message}
alignSelf="start"
>
<InputGroup
width="100%"
startElement={startElement}
endElement={
<VisibilityTrigger
disabled={rest.disabled}
onPointerDown={(e) => {
if (rest.disabled) return
if (e.button !== 0) return
e.preventDefault()
setVisible(!visible)
}}
>
{visible ? visibilityIcon.off : visibilityIcon.on}
</VisibilityTrigger>
}
{...rootProps}
>
<Input
{...rest}
ref={mergeRefs(ref, inputRef)}
type={visible ? "text" : "password"}
/>
</InputGroup>
</Field>
)
},
)
const VisibilityTrigger = forwardRef<HTMLButtonElement, ButtonProps>(
function VisibilityTrigger(props, ref) {
return (
<IconButton
tabIndex={-1}
ref={ref}
me="-2"
aspectRatio="square"
size="sm"
variant="ghost"
height="calc(100% - {spacing.2})"
aria-label="Toggle password visibility"
color="inherit"
{...props}
/>
)
},
)
interface PasswordStrengthMeterProps extends StackProps {
max?: number
value: number
}
export const PasswordStrengthMeter = forwardRef<
HTMLDivElement,
PasswordStrengthMeterProps
>(function PasswordStrengthMeter(props, ref) {
const { max = 4, value, ...rest } = props
const percent = (value / max) * 100
const { label, colorPalette } = getColorPalette(percent)
return (
<Stack align="flex-end" gap="1" ref={ref} {...rest}>
<HStack width="full" ref={ref} {...rest}>
{Array.from({ length: max }).map((_, index) => (
<Box
key={index}
height="1"
flex="1"
rounded="sm"
data-selected={index < value ? "" : undefined}
layerStyle="fill.subtle"
colorPalette="gray"
_selected={{
colorPalette,
layerStyle: "fill.solid",
}}
/>
))}
</HStack>
{label && <HStack textStyle="xs">{label}</HStack>}
</Stack>
)
})
function getColorPalette(percent: number) {
switch (true) {
case percent < 33:
return { label: "Low", colorPalette: "red" }
case percent < 66:
return { label: "Medium", colorPalette: "orange" }
default:
return { label: "High", colorPalette: "green" }
}
}
+18
View File
@@ -0,0 +1,18 @@
"use client"
import { ChakraProvider } from "@chakra-ui/react"
import React, { type PropsWithChildren } from "react"
import { system } from "../../theme"
import { ColorModeProvider } from "./color-mode"
import { Toaster } from "./toaster"
export function CustomProvider(props: PropsWithChildren) {
return (
<ChakraProvider value={system}>
<ColorModeProvider defaultTheme="light">
{props.children}
</ColorModeProvider>
<Toaster />
</ChakraProvider>
)
}
+24
View File
@@ -0,0 +1,24 @@
import { RadioGroup as ChakraRadioGroup } from "@chakra-ui/react"
import * as React from "react"
export interface RadioProps extends ChakraRadioGroup.ItemProps {
rootRef?: React.Ref<HTMLDivElement>
inputProps?: React.InputHTMLAttributes<HTMLInputElement>
}
export const Radio = React.forwardRef<HTMLInputElement, RadioProps>(
function Radio(props, ref) {
const { children, inputProps, rootRef, ...rest } = props
return (
<ChakraRadioGroup.Item ref={rootRef} {...rest}>
<ChakraRadioGroup.ItemHiddenInput ref={ref} {...inputProps} />
<ChakraRadioGroup.ItemIndicator />
{children && (
<ChakraRadioGroup.ItemText>{children}</ChakraRadioGroup.ItemText>
)}
</ChakraRadioGroup.Item>
)
},
)
export const RadioGroup = ChakraRadioGroup.Root
+47
View File
@@ -0,0 +1,47 @@
import type {
SkeletonProps as ChakraSkeletonProps,
CircleProps,
} from "@chakra-ui/react"
import { Skeleton as ChakraSkeleton, Circle, Stack } from "@chakra-ui/react"
import * as React from "react"
export interface SkeletonCircleProps extends ChakraSkeletonProps {
size?: CircleProps["size"]
}
export const SkeletonCircle = React.forwardRef<
HTMLDivElement,
SkeletonCircleProps
>(function SkeletonCircle(props, ref) {
const { size, ...rest } = props
return (
<Circle size={size} asChild ref={ref}>
<ChakraSkeleton {...rest} />
</Circle>
)
})
export interface SkeletonTextProps extends ChakraSkeletonProps {
noOfLines?: number
}
export const SkeletonText = React.forwardRef<HTMLDivElement, SkeletonTextProps>(
function SkeletonText(props, ref) {
const { noOfLines = 3, gap, ...rest } = props
return (
<Stack gap={gap} width="full" ref={ref}>
{Array.from({ length: noOfLines }).map((_, index) => (
<ChakraSkeleton
height="4"
key={index}
{...props}
_last={{ maxW: "80%" }}
{...rest}
/>
))}
</Stack>
)
},
)
export const Skeleton = ChakraSkeleton
+43
View File
@@ -0,0 +1,43 @@
"use client"
import {
Toaster as ChakraToaster,
Portal,
Spinner,
Stack,
Toast,
createToaster,
} from "@chakra-ui/react"
export const toaster = createToaster({
placement: "top-end",
pauseOnPageIdle: true,
})
export const Toaster = () => {
return (
<Portal>
<ChakraToaster toaster={toaster} insetInline={{ mdDown: "4" }}>
{(toast) => (
<Toast.Root width={{ md: "sm" }} color={toast.meta?.color}>
{toast.type === "loading" ? (
<Spinner size="sm" color="blue.solid" />
) : (
<Toast.Indicator />
)}
<Stack gap="1" flex="1" maxWidth="100%">
{toast.title && <Toast.Title>{toast.title}</Toast.Title>}
{toast.description && (
<Toast.Description>{toast.description}</Toast.Description>
)}
</Stack>
{toast.action && (
<Toast.ActionTrigger>{toast.action.label}</Toast.ActionTrigger>
)}
{toast.meta?.closable && <Toast.CloseTrigger />}
</Toast.Root>
)}
</ChakraToaster>
</Portal>
)
}
+5 -29
View File
@@ -2,7 +2,6 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { useNavigate } from "@tanstack/react-router" import { useNavigate } from "@tanstack/react-router"
import { useState } from "react" import { useState } from "react"
import { AxiosError } from "axios"
import { import {
type Body_login_login_access_token as AccessToken, type Body_login_login_access_token as AccessToken,
type ApiError, type ApiError,
@@ -10,8 +9,8 @@ import {
type UserPublic, type UserPublic,
type UserRegister, type UserRegister,
UsersService, UsersService,
} from "../client" } from "@/client"
import useCustomToast from "./useCustomToast" import { handleError } from "@/utils"
const isLoggedIn = () => { const isLoggedIn = () => {
return localStorage.getItem("access_token") !== null return localStorage.getItem("access_token") !== null
@@ -20,9 +19,8 @@ const isLoggedIn = () => {
const useAuth = () => { const useAuth = () => {
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const navigate = useNavigate() const navigate = useNavigate()
const showToast = useCustomToast()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const { data: user, isLoading } = useQuery<UserPublic | null, Error>({ const { data: user } = useQuery<UserPublic | null, Error>({
queryKey: ["currentUser"], queryKey: ["currentUser"],
queryFn: UsersService.readUserMe, queryFn: UsersService.readUserMe,
enabled: isLoggedIn(), enabled: isLoggedIn(),
@@ -34,20 +32,9 @@ const useAuth = () => {
onSuccess: () => { onSuccess: () => {
navigate({ to: "/login" }) navigate({ to: "/login" })
showToast(
"Account created.",
"Your account has been created successfully.",
"success",
)
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
let errDetail = (err.body as any)?.detail handleError(err)
if (err instanceof AxiosError) {
errDetail = err.message
}
showToast("Something went wrong.", errDetail, "error")
}, },
onSettled: () => { onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["users"] }) queryClient.invalidateQueries({ queryKey: ["users"] })
@@ -67,17 +54,7 @@ const useAuth = () => {
navigate({ to: "/" }) navigate({ to: "/" })
}, },
onError: (err: ApiError) => { onError: (err: ApiError) => {
let errDetail = (err.body as any)?.detail handleError(err)
if (err instanceof AxiosError) {
errDetail = err.message
}
if (Array.isArray(errDetail)) {
errDetail = "Something went wrong"
}
setError(errDetail)
}, },
}) })
@@ -91,7 +68,6 @@ const useAuth = () => {
loginMutation, loginMutation,
logout, logout,
user, user,
isLoading,
error, error,
resetError: () => setError(null), resetError: () => setError(null),
} }
+18 -16
View File
@@ -1,23 +1,25 @@
import { useToast } from "@chakra-ui/react" "use client"
import { useCallback } from "react"
import { toaster } from "@/components/ui/toaster"
const useCustomToast = () => { const useCustomToast = () => {
const toast = useToast() const showSuccessToast = (description: string) => {
toaster.create({
title: "Success!",
description,
type: "success",
})
}
const showToast = useCallback( const showErrorToast = (description: string) => {
(title: string, description: string, status: "success" | "error") => { toaster.create({
toast({ title: "Something went wrong!",
title, description,
description, type: "error",
status, })
isClosable: true, }
position: "bottom-right",
})
},
[toast],
)
return showToast return { showSuccessToast, showErrorToast }
} }
export default useCustomToast export default useCustomToast

Some files were not shown because too many files have changed in this diff Show More