Compare commits

...

12 Commits

Author SHA1 Message Date
tophe 4c1cefc1f5 Add vercel.json for SPA routing 2026-05-27 01:08:23 +02:00
tophe f1c39eaae2 Maj du titre de la page index 2026-05-26 22:30:12 +02:00
tophe a52b4baddc Merge branch 'master' into main 2026-05-26 18:47:09 +02:00
tophe dc9fd58f66 Ajout de nv fichier de migration SQL 2026-05-26 01:12:28 +02:00
tophe 65a6c50fec Optimisation DB et Migration 2026-05-26 01:11:11 +02:00
tophe e6d2eee9ea Ajout de visuels sur la matrice pour sélection 2026-05-25 20:55:58 +02:00
tophe 24e08fca4f Ajout du composant Form Skill Member 2026-05-25 01:36:29 +02:00
tophe ac1b35b1d9 Ajout de visualisations pratiques de la matrice 2026-05-25 01:34:18 +02:00
tophe 24afa9a8e8 Ajout gitignore pour les opencode stuff 2026-05-24 21:05:03 +02:00
tophe 2ee7decbfd Remaster avec skill supabase only et grillme 2026-05-24 20:30:45 +02:00
tophe e38a3df248 Fix: Add .env to .gitignore and create .env.example
- Uncomment .env in .gitignore to prevent accidental commits
- Remove .env from git tracking
- Add .env.example with placeholder values for documentation
- Fixes security issue where .env was committed with credentials
2026-05-23 17:29:19 +02:00
tophe 3871be536c Initial commit 2026-05-18 00:18:45 +02:00
45 changed files with 29000 additions and 386 deletions
+2
View File
@@ -4,3 +4,5 @@ dist
*.local *.local
.env .env
.env.local .env.local
.agents
.dockerignore
+12
View File
@@ -0,0 +1,12 @@
# Supabase Configuration
# Copy this file to .env and fill in your actual values
# Supabase API URL
VITE_SUPABASE_URL=http://localhost:8000
# Supabase anonymous key (public, used by the frontend)
VITE_SUPABASE_ANON_KEY=your-anon-key-here
# Supabase service role key (secret, NEVER exposed to the frontend)
# Only used by scripts and edge functions
VITE_SUPABASE_SERVICE_ROLE_KEY=your-service-role-key-here
+5 -1
View File
@@ -24,5 +24,9 @@ dist-ssr
*.sw? *.sw?
# Environment # Environment
#.env .env
.env.local .env.local
# OpenCode Stuff
.agents/*
opencode*
+31 -4
View File
@@ -11,27 +11,51 @@ npm run dev # Vite dev server with HMR
npm run build # Production build → dist/ npm run build # Production build → dist/
npm run lint # ESLint (flat config) npm run lint # ESLint (flat config)
npm run preview # Serve dist/ locally npm run preview # Serve dist/ locally
npm run test # Vitest run (hooks tests)
npm run test:watch# Vitest watch mode
``` ```
No test runner, no typecheck script. No typecheck script.
## Architecture ## Architecture
- **Entry**: `src/main.jsx``src/App.jsx` - **Entry**: `src/main.jsx` wrapped in `<ThemeProvider>` (next-themes) → `src/App.jsx`
- **Auth**: `src/context/AuthContext.jsx` — Supabase Auth + `members` table profile (role: admin/member) - **Auth**: `src/context/AuthContext.jsx` — Supabase Auth + `members` table profile (role: admin/member)
- **Routing**: `src/App.jsx` — public routes `/login`, `/register`, `/accept-invite`; protected routes wrapped in `<ProtectedRoute>`; admin-only routes (`/members`, `/skills`) also wrapped in `<AdminRoute>` - **Routing**: `src/App.jsx` — public routes `/login`, `/register`, `/accept-invite`; protected routes wrapped in `<ProtectedRoute>`; admin-only routes (`/members`, `/skills`) also wrapped in `<AdminRoute>` + `<Suspense>` (React.lazy code splitting)
- **Error handling**: `<ErrorBoundary>` wraps all protected routes
- **Pages**: `src/pages/` — Dashboard, Members, Skills, SkillMatrix, History, Profile - **Pages**: `src/pages/` — Dashboard, Members, Skills, SkillMatrix, History, Profile
- **UI**: `src/components/ui/` — shadcn components (radix-nova style, JS, no TSX) - **UI**: `src/components/ui/` — shadcn components (radix-nova style, JS, no TSX)
- **Supabase client**: `src/lib/supabase.js` — reads `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` from env - **Supabase client**: `src/lib/supabase.js` — reads `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` from env
- **Path alias**: `@/*``src/*` (configured in both `vite.config.js` and `jsconfig.json`) - **Path alias**: `@/*``src/*` (configured in both `vite.config.js` and `jsconfig.json`)
## Data Layer
### Custom hooks in `src/hooks/`
| Hook | Returns | Notes |
|---|---|---|
| `useMembers()` | `{ members, loading, refetch }` | Full-text search via GIN index |
| `useSkills()` | `{ skills, loading, refetch }` | Includes `category:category_id(name)` join |
| `useCategories()` | `{ categories, loading, refetch }` | Ordered by name |
| `useSkillLevels()` | `{ levels, loading, refetch, updateLevel, getAverageSkillRating }` | `levels` is a `{memberId-skillId → level}` map. Has real-time subscription |
| `useHistory()` | `{ history, loading, count, page, totalPages, filters, setFilter, nextPage, prevPage, refetch }` | Paginated (50/page), real-time on INSERT |
### Data fetching patterns
- Hooks call Supabase directly (no additional API layer)
- No global state management (hooks + local state only)
- Real-time subscriptions via `supabase.channel()` on `skill_levels` and `skill_history`
## Supabase ## Supabase
- DB schema + RLS policies in `supabase/migrations/001_init.sql` - DB schema + RLS policies in `supabase/migrations/001_init.sql`
- Tables: `categories`, `skills`, `members`, `level_descriptions`, `skill_levels`, `skill_history`, `invitations` - Tables: `categories`, `skills`, `members`, `level_descriptions`, `skill_levels`, `skill_history`, `invitations`
- `handle_new_user()` trigger auto-creates a `members` row on auth signup - `handle_new_user()` trigger auto-creates a `members` row on auth signup
- RLS: read-all for most tables, write restricted to admin role - RLS: read-all for most tables, write restricted to admin role
- `.env` points to a local Supabase instance (`192.168.2.220:8000`) — this is committed but `.env` is gitignored; adjust for your environment - UPDATE policies include `WITH CHECK` matching the `USING` clause
- `invitations_read_admin` policy filters `expires_at > now()`
- Full-text search enabled via GIN indexes on `skills.name` and `members.full_name`
- Realtime publication enabled on `skill_levels` and `skill_history`
- `.env` points to a local Supabase instance (`vm-docker5.home.arpa:8000`) — this is committed but `.env` is gitignored; adjust for your environment
## Docker ## Docker
@@ -53,3 +77,6 @@ Components land in `src/components/ui/`. Uses Lucide icons.
- ESLint flat config (`eslint.config.js`) — ignores `dist/` - ESLint flat config (`eslint.config.js`) — ignores `dist/`
- Tailwind v4 via `@tailwindcss/vite` plugin (no `tailwind.config.js`) - Tailwind v4 via `@tailwindcss/vite` plugin (no `tailwind.config.js`)
- French UI labels (application is in French) - French UI labels (application is in French)
- Dark mode support via `next-themes` with class strategy
- Layout: Lucide icons, responsive sidebar (hamburger on mobile)
- CSV exports for Members and Matrix pages
+232
View File
@@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
gestiondescompetences
Copyright (C) 2026 tophe-garage
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
gestiondescompetences Copyright (C) 2026 tophe-garage
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
+5 -5
View File
@@ -1,4 +1,8 @@
# React + Vite # Gestion Des Compétences
Cette application permet la gestion et le suivi des compétences. Elle est construite avec React et Vite.
## Développement
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
@@ -10,7 +14,3 @@ Currently, two official plugins are available:
## React Compiler ## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
View File
+25839
View File
File diff suppressed because one or more lines are too long
+11
View File
@@ -18,4 +18,15 @@ export default defineConfig([
parserOptions: { ecmaFeatures: { jsx: true } }, parserOptions: { ecmaFeatures: { jsx: true } },
}, },
}, },
{
files: ['src/components/ui/**'],
rules: {
'no-unused-vars': 'off',
'react-refresh/only-export-components': 'off',
},
},
{
files: ['vite.config.js'],
rules: { 'no-undef': 'off' },
},
]) ])
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>gestiondescmpetences</title> <title>gestiondescompetences</title>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
+786 -4
View File
File diff suppressed because it is too large Load Diff
+9 -4
View File
@@ -1,5 +1,5 @@
{ {
"name": "gestiondescmpetences", "name": "gestiondescompetences",
"private": true, "private": true,
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
@@ -7,20 +7,23 @@
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest"
}, },
"dependencies": { "dependencies": {
"@fontsource-variable/geist": "^5.2.9", "@fontsource-variable/geist": "^5.2.9",
"@supabase/supabase-js": "^2.105.4", "@supabase/supabase-js": "^2.105.4",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"d3-force": "^3.0.0",
"lucide-react": "^1.16.0", "lucide-react": "^1.16.0",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"pg": "^8.21.0",
"radix-ui": "^1.4.3", "radix-ui": "^1.4.3",
"react": "^19.2.6", "react": "^19.2.6",
"react-dom": "^19.2.6", "react-dom": "^19.2.6",
"react-router-dom": "^7.15.1", "react-router-dom": "^7.15.1",
"recharts": "^3.8.1",
"shadcn": "^4.7.0", "shadcn": "^4.7.0",
"sonner": "^2.0.7", "sonner": "^2.0.7",
"tailwind-merge": "^3.6.0", "tailwind-merge": "^3.6.0",
@@ -37,7 +40,9 @@
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2", "eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.6.0", "globals": "^17.6.0",
"pg": "^8.21.0",
"tailwindcss": "^4.3.0", "tailwindcss": "^4.3.0",
"vite": "^8.0.12" "vite": "^8.0.12",
"vitest": "^4.1.7"
} }
} }
+19 -6
View File
@@ -1,11 +1,24 @@
import { readFileSync } from 'fs' import { readFileSync } from 'fs'
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'
const SUPABASE_URL = 'http://192.168.2.220:8000' const __dirname = dirname(fileURLToPath(import.meta.url))
const ANON_KEY = readFileSync('/home/tophe/10-Projets/DevOps/OpenCode/GestionDesCompetences/.env', 'utf8') const envPath = resolve(__dirname, '..', '.env')
.split('\n') const envContent = readFileSync(envPath, 'utf8')
.find(l => l.startsWith('VITE_SUPABASE_ANON_KEY='))
?.split('=').slice(1).join('=') function readEnv(key) {
const SERVICE_ROLE_KEY = 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImJmMzI4YWViLTYwMWYtNGEzZC04MjdiLTY1MTZlZTY0MWViMyJ9.eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaXNzIjoic3VwYWJhc2UiLCJpYXQiOjE3NzkzMDAyNDMsImV4cCI6MTkzNjk4MDI0M30.qt2IKVgwaQQkHIZVWH4tEcrozU0mT3F9dNC9Yo83UidKwsoxHRqZz8hBWjreRPsThUcCgjxOmhwxeTB7Zd7RFA' const line = envContent.split('\n').find(l => l.startsWith(`${key}=`))
return line?.split('=').slice(1).join('=')?.trim()
}
const SUPABASE_URL = readEnv('VITE_SUPABASE_URL')
const ANON_KEY = readEnv('VITE_SUPABASE_ANON_KEY')
const SERVICE_ROLE_KEY = readEnv('VITE_SUPABASE_SERVICE_ROLE_KEY')
if (!SUPABASE_URL || !ANON_KEY || !SERVICE_ROLE_KEY) {
console.error('Missing required env vars in .env. Need VITE_SUPABASE_URL, VITE_SUPABASE_ANON_KEY, VITE_SUPABASE_SERVICE_ROLE_KEY')
process.exit(1)
}
const headers = { const headers = {
'apikey': ANON_KEY, 'apikey': ANON_KEY,
+24
View File
@@ -1,12 +1,36 @@
{ {
"version": 1, "version": 1,
"skills": { "skills": {
"frontend-design": {
"source": "anthropics/skills",
"sourceType": "github",
"skillPath": "skills/frontend-design/SKILL.md",
"computedHash": "063a0e6448123cd359ad0044cc46b0e490cc7964d45ef4bb9fd842bd2ffbca67"
},
"grill-me": {
"source": "mattpocock/skills",
"sourceType": "github",
"skillPath": "skills/productivity/grill-me/SKILL.md",
"computedHash": "784f0dbb7403b0f00324bce9a112f715342777a0daee7bbb7385f9c6f0a170ea"
},
"improve-codebase-architecture": {
"source": "mattpocock/skills",
"sourceType": "github",
"skillPath": "skills/engineering/improve-codebase-architecture/SKILL.md",
"computedHash": "ef32aea0a8fab9b365ff9e08a95f8d353e20ca21ea46ec2e73587c86dd341351"
},
"pptx": { "pptx": {
"source": "anthropics/skills", "source": "anthropics/skills",
"sourceType": "github", "sourceType": "github",
"skillPath": "skills/pptx/SKILL.md", "skillPath": "skills/pptx/SKILL.md",
"computedHash": "6b8b859d26f93aa059c9870d1ab76b44ab69e3d6757ce4a03cc94cb760888073" "computedHash": "6b8b859d26f93aa059c9870d1ab76b44ab69e3d6757ce4a03cc94cb760888073"
}, },
"shadcn": {
"source": "shadcn/ui",
"sourceType": "github",
"skillPath": "skills/shadcn/SKILL.md",
"computedHash": "80a6226e78f6d1fe464214ae0ef449d49d8ffaa3e7704f011e9b418c678ad4d1"
},
"supabase": { "supabase": {
"source": "supabase/agent-skills", "source": "supabase/agent-skills",
"sourceType": "github", "sourceType": "github",
+20 -5
View File
@@ -1,21 +1,30 @@
import { lazy, Suspense } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom' import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { AuthProvider } from '@/context/AuthContext' import { AuthProvider } from '@/context/AuthContext'
import { ProtectedRoute, AdminRoute } from '@/components/ProtectedRoute' import { ProtectedRoute, AdminRoute } from '@/components/ProtectedRoute'
import { ErrorBoundary } from '@/components/ErrorBoundary'
import { Layout } from '@/components/Layout' import { Layout } from '@/components/Layout'
import { Toaster } from 'sonner' import { Toaster } from 'sonner'
import { Login } from '@/pages/Login' import { Login } from '@/pages/Login'
import { Register } from '@/pages/Register' import { Register } from '@/pages/Register'
import { AcceptInvite } from '@/pages/AcceptInvite' import { AcceptInvite } from '@/pages/AcceptInvite'
import { Dashboard } from '@/pages/Dashboard' import { Dashboard } from '@/pages/Dashboard'
import { Members } from '@/pages/Members'
import { Skills } from '@/pages/Skills'
import { SkillMatrix } from '@/pages/SkillMatrix' import { SkillMatrix } from '@/pages/SkillMatrix'
import { History } from '@/pages/History' import { History } from '@/pages/History'
import { Profile } from '@/pages/Profile' import { Profile } from '@/pages/Profile'
const Members = lazy(() => import('@/pages/Members').then(m => ({ default: m.Members })))
const Skills = lazy(() => import('@/pages/Skills').then(m => ({ default: m.Skills })))
function AppLayout({ children }) { function AppLayout({ children }) {
return <Layout>{children}</Layout>
}
function SuspenseWrapper({ children }) {
return ( return (
<Layout>{children}</Layout> <Suspense fallback={<div className="flex items-center justify-center min-h-[60vh] text-gray-400">Chargement...</div>}>
{children}
</Suspense>
) )
} }
@@ -23,6 +32,7 @@ export default function App() {
return ( return (
<BrowserRouter> <BrowserRouter>
<AuthProvider> <AuthProvider>
<ErrorBoundary>
<Toaster /> <Toaster />
<Routes> <Routes>
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
@@ -43,12 +53,17 @@ export default function App() {
} /> } />
<Route path="/members" element={ <Route path="/members" element={
<ProtectedRoute><AdminRoute><AppLayout><Members /></AppLayout></AdminRoute></ProtectedRoute> <ProtectedRoute><AdminRoute><AppLayout>
<SuspenseWrapper><Members /></SuspenseWrapper>
</AppLayout></AdminRoute></ProtectedRoute>
} /> } />
<Route path="/skills" element={ <Route path="/skills" element={
<ProtectedRoute><AdminRoute><AppLayout><Skills /></AppLayout></AdminRoute></ProtectedRoute> <ProtectedRoute><AdminRoute><AppLayout>
<SuspenseWrapper><Skills /></SuspenseWrapper>
</AppLayout></AdminRoute></ProtectedRoute>
} /> } />
</Routes> </Routes>
</ErrorBoundary>
</AuthProvider> </AuthProvider>
</BrowserRouter> </BrowserRouter>
) )
+34
View File
@@ -0,0 +1,34 @@
import { Component } from 'react'
export class ErrorBoundary extends Component {
constructor(props) {
super(props)
this.state = { hasError: false, error: null }
}
static getDerivedStateFromError(error) {
return { hasError: true, error }
}
render() {
if (this.state.hasError) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-center space-y-4">
<h1 className="text-2xl font-bold text-red-600">Une erreur est survenue</h1>
<p className="text-gray-600">
{this.state.error?.message || 'Erreur inattendue'}
</p>
<button
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
onClick={() => window.location.reload()}
>
Recharger la page
</button>
</div>
</div>
)
}
return this.props.children
}
}
+57 -14
View File
@@ -1,3 +1,4 @@
import { useState } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom' import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext' import { useAuth } from '@/context/AuthContext'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@@ -5,51 +6,74 @@ import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu' } from '@/components/ui/dropdown-menu'
import {
LayoutDashboard, BookOpen, Users, Table2, History, Menu, X, Sun, Moon, LogOut, User,
} from 'lucide-react'
import { useTheme } from 'next-themes'
const navItems = [ const navItems = [
{ to: '/', label: 'Tableau de bord', icon: '📊' }, { to: '/', label: 'Tableau de bord', icon: LayoutDashboard },
{ to: '/skills', label: 'Compétences', icon: '📚', admin: true }, { to: '/skills', label: 'Compétences', icon: BookOpen, admin: true },
{ to: '/members', label: 'Membres', icon: '👥', admin: true }, { to: '/members', label: 'Membres', icon: Users, admin: true },
{ to: '/matrix', label: 'Matrice', icon: '📋' }, { to: '/matrix', label: 'Matrice', icon: Table2 },
{ to: '/history', label: 'Historique', icon: '📜' }, { to: '/history', label: 'Historique', icon: History },
] ]
export function Layout({ children }) { export function Layout({ children }) {
const { profile, signOut } = useAuth() const { profile, signOut } = useAuth()
const { theme, setTheme } = useTheme()
const location = useLocation() const location = useLocation()
const navigate = useNavigate() const navigate = useNavigate()
const [sidebarOpen, setSidebarOpen] = useState(false)
async function handleSignOut() { async function handleSignOut() {
await signOut() await signOut()
navigate('/login') navigate('/login')
} }
return ( const sidebar = (
<div className="min-h-screen flex"> <aside className={`w-64 bg-gray-900 text-white flex flex-col shrink-0 ${sidebarOpen ? 'fixed inset-0 z-50' : 'hidden lg:flex'}`}>
<aside className="w-64 bg-gray-900 text-white flex flex-col"> <div className="p-4 border-b border-gray-700 flex items-center justify-between">
<div className="p-4 border-b border-gray-700"> <div>
<h1 className="text-lg font-bold">Compétences</h1> <h1 className="text-lg font-bold">Compétences</h1>
<p className="text-xs text-gray-400">Équipe SysAdmin</p> <p className="text-xs text-gray-400">Équipe SysAdmin</p>
</div> </div>
{sidebarOpen && (
<button className="lg:hidden text-gray-400 hover:text-white" onClick={() => setSidebarOpen(false)}>
<X className="h-5 w-5" />
</button>
)}
</div>
<nav className="flex-1 p-2 space-y-1"> <nav className="flex-1 p-2 space-y-1">
{navItems {navItems
.filter((item) => !item.admin || profile?.role === 'admin') .filter((item) => !item.admin || profile?.role === 'admin')
.map((item) => ( .map((item) => {
const Icon = item.icon
return (
<Link <Link
key={item.to} key={item.to}
to={item.to} to={item.to}
onClick={() => setSidebarOpen(false)}
className={`flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${ className={`flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
location.pathname === item.to location.pathname === item.to
? 'bg-gray-700 text-white' ? 'bg-gray-700 text-white'
: 'text-gray-300 hover:bg-gray-800 hover:text-white' : 'text-gray-300 hover:bg-gray-800 hover:text-white'
}`} }`}
> >
<span>{item.icon}</span> <Icon className="h-4 w-4" />
{item.label} {item.label}
</Link> </Link>
))} )
})}
</nav> </nav>
<div className="p-4 border-t border-gray-700"> <div className="p-4 border-t border-gray-700 space-y-2">
<button
className="flex items-center gap-2 text-sm text-gray-400 hover:text-white w-full"
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
>
{theme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
{theme === 'dark' ? 'Mode clair' : 'Mode sombre'}
</button>
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-full flex items-center gap-2 text-gray-300 hover:text-white"> <Button variant="ghost" className="w-full flex items-center gap-2 text-gray-300 hover:text-white">
@@ -63,17 +87,36 @@ export function Layout({ children }) {
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48"> <DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem onClick={() => navigate('/profile')}> <DropdownMenuItem onClick={() => navigate('/profile')}>
<User className="h-4 w-4 mr-2" />
Mon profil Mon profil
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={handleSignOut}> <DropdownMenuItem onClick={handleSignOut}>
<LogOut className="h-4 w-4 mr-2" />
Déconnexion Déconnexion
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
</div> </div>
</aside> </aside>
<main className="flex-1 bg-gray-50 p-8 overflow-auto"> )
return (
<div className="min-h-screen flex bg-gray-50 dark:bg-gray-950 dark:text-gray-100">
{sidebarOpen && (
<div className="fixed inset-0 bg-black/50 z-40 lg:hidden" onClick={() => setSidebarOpen(false)} />
)}
{sidebar}
<main className="flex-1 flex flex-col min-w-0">
<div className="lg:hidden flex items-center justify-between p-4 border-b bg-white dark:bg-gray-900 dark:border-gray-800">
<button onClick={() => setSidebarOpen(true)} className="text-gray-700 dark:text-gray-300">
<Menu className="h-5 w-5" />
</button>
<span className="font-bold text-sm">Compétences</span>
<div className="w-5" />
</div>
<div className="p-4 md:p-8 overflow-auto">
{children} {children}
</div>
</main> </main>
</div> </div>
) )
+1
View File
@@ -1,3 +1,4 @@
/* eslint-disable react-refresh/only-export-components */
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
const levelConfig = { const levelConfig = {
+83
View File
@@ -0,0 +1,83 @@
import {
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
} from 'recharts'
const levelLabels = {
1: { label: 'Débutant', color: '#9ca3af' },
2: { label: 'Intermédiaire', color: '#60a5fa' },
3: { label: 'Avancé', color: '#fbbf24' },
4: { label: 'Expert', color: '#34d399' },
}
export default function BarChartView({
categories, skills: allSkills, members, levels, filterCat,
onBarClick,
}) {
const cats = filterCat === 'all' ? categories : categories.filter((c) => c.id === filterCat)
const data = cats.map((cat) => {
const catSkills = allSkills.filter((s) => s.category_id === cat.id)
const buckets = { 1: 0, 2: 0, 3: 0, 4: 0 }
members.forEach((m) => {
catSkills.forEach((s) => {
const key = `${m.id}-${s.id}`
const lvl = levels[key]?.level
if (lvl) buckets[lvl]++
})
})
return {
name: cat.name,
color: cat.color,
id: cat.id,
...buckets,
}
})
if (data.length === 0) {
return <div className="p-8 text-center text-gray-400">Aucune donnée à afficher</div>
}
function handleClick(entry, _index, level) {
if (onBarClick && entry?.id) {
onBarClick(entry.id, level)
}
}
return (
<div className="bg-white dark:bg-gray-950 rounded-lg p-4">
<ResponsiveContainer width="100%" height={400}>
<BarChart data={data} layout="vertical" margin={{ top: 20, right: 30, left: 80, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />
<XAxis type="number" stroke="var(--foreground)" tick={{ fontSize: 12 }} />
<YAxis type="category" dataKey="name" stroke="var(--foreground)" tick={{ fontSize: 12 }} width={100} />
<Tooltip
contentStyle={{
background: 'var(--background)',
border: '1px solid var(--border)',
borderRadius: 'var(--radius)',
fontSize: 13,
}}
/>
<Legend
payload={[1, 2, 3, 4].map((l) => ({
value: `${l} - ${levelLabels[l].label}`,
type: 'rect',
color: levelLabels[l].color,
}))}
/>
{[1, 2, 3, 4].map((lvl) => (
<Bar
key={lvl}
dataKey={lvl}
stackId="a"
fill={levelLabels[lvl].color}
name={`Niveau ${lvl}`}
cursor="pointer"
onClick={(entry) => handleClick(entry, null, lvl)}
/>
))}
</BarChart>
</ResponsiveContainer>
</div>
)
}
+251
View File
@@ -0,0 +1,251 @@
import { useEffect, useRef, useState } from 'react'
import { forceSimulation, forceLink, forceManyBody, forceCenter, forceCollide } from 'd3-force'
import { Button } from '@/components/ui/button'
export default function GraphView({
categories, skills: allSkills, levels,
filteredSkills, filteredMembers,
}) {
const canvasRef = useRef(null)
const [aggregated, setAggregated] = useState(false)
const [selectedNode, setSelectedNode] = useState(null)
const width = 900
const height = 600
useEffect(() => {
const canvas = canvasRef.current
if (!canvas) return
const ctx = canvas.getContext('2d')
if (!ctx) return
const catMap = {}
categories.forEach((c) => { catMap[c.id] = c })
const nodes = []
const links = []
const nodeMap = new Map()
filteredMembers.forEach((m) => {
const node = { id: m.id, type: 'member', label: m.full_name || m.email, r: 10, x: width / 2, y: height / 2 }
nodes.push(node)
nodeMap.set(m.id, node)
})
if (aggregated) {
categories
.filter((cat) => filteredSkills.length === 0 || filteredSkills.some((s) => s.category_id === cat.id))
.forEach((cat) => {
const nid = `cat-${cat.id}`
const node = { id: nid, type: 'category', label: cat.name, r: 14, color: cat.color, catId: cat.id, x: width / 2, y: height / 2 }
nodes.push(node)
nodeMap.set(nid, node)
filteredMembers.forEach((m) => {
const catSkillIds = allSkills.filter((s) => s.category_id === cat.id).map((s) => s.id)
let total = 0
let count = 0
catSkillIds.forEach((sid) => {
const key = `${m.id}-${sid}`
const lvl = levels[key]?.level
if (lvl) { total += lvl; count++ }
})
if (count > 0) {
links.push({ source: m.id, target: nid, strength: total / count / 4 })
}
})
})
} else {
filteredSkills.forEach((s) => {
const nid = `skill-${s.id}`
const node = { id: nid, type: 'skill', label: s.name, r: 8, color: catMap[s.category_id]?.color || '#888', skillId: s.id, x: width / 2, y: height / 2 }
nodes.push(node)
nodeMap.set(nid, node)
})
filteredMembers.forEach((m) => {
filteredSkills.forEach((s) => {
const key = `${m.id}-${s.id}`
const lvl = levels[key]?.level
if (lvl) {
links.push({ source: m.id, target: `skill-${s.id}`, strength: lvl / 4 })
}
})
})
}
if (nodes.length === 0) return
const dpi = window.devicePixelRatio || 1
canvas.width = width * dpi
canvas.height = height * dpi
ctx.scale(dpi, dpi)
const borderColor = getComputedStyle(canvas).getPropertyValue('--border').trim() || '#e5e7eb'
const fgColor = getComputedStyle(canvas).getPropertyValue('--foreground').trim() || '#000'
const simulation = forceSimulation(nodes)
.force('link', forceLink(links).id((d) => d.id).distance(120).strength((d) => d.strength || 0.3))
.force('charge', forceManyBody().strength(-150))
.force('center', forceCenter(width / 2, height / 2))
.force('collide', forceCollide(20))
.on('tick', ticked)
function ticked() {
ctx.clearRect(0, 0, width, height)
ctx.strokeStyle = borderColor
ctx.lineWidth = 1
links.forEach((l) => {
const s = l.strength || 0.3
ctx.globalAlpha = s * 0.5 + 0.15
ctx.beginPath()
ctx.moveTo(l.source.x, l.source.y)
ctx.lineTo(l.target.x, l.target.y)
ctx.stroke()
})
ctx.globalAlpha = 1
nodes.forEach((n) => {
const isSel = selectedNode === n.id
const isNeighbor = isSel
? links.some((l) => {
const sid = typeof l.source === 'object' ? l.source.id : l.source
const tid = typeof l.target === 'object' ? l.target.id : l.target
return (sid === selectedNode && tid === n.id) || (tid === selectedNode && sid === n.id)
})
: false
ctx.globalAlpha = selectedNode && !isSel && !isNeighbor ? 0.12 : 1
if (n.type === 'member') {
ctx.beginPath()
ctx.arc(n.x, n.y, n.r, 0, 2 * Math.PI)
ctx.fillStyle = '#6366f1'
ctx.fill()
if (isSel) {
ctx.strokeStyle = '#fff'
ctx.lineWidth = 2
ctx.stroke()
}
} else if (n.type === 'category') {
ctx.beginPath()
ctx.arc(n.x, n.y, n.r, 0, 2 * Math.PI)
ctx.fillStyle = n.color || '#888'
ctx.fill()
if (isSel) {
ctx.strokeStyle = '#fff'
ctx.lineWidth = 2
ctx.stroke()
}
} else {
const s = 6
ctx.fillStyle = n.color || '#888'
ctx.fillRect(n.x - s / 2, n.y - s / 2, s, s)
if (isSel) {
ctx.strokeStyle = '#fff'
ctx.lineWidth = 2
ctx.strokeRect(n.x - s / 2, n.y - s / 2, s, s)
}
}
ctx.fillStyle = fgColor
ctx.font = '10px sans-serif'
ctx.textAlign = 'center'
ctx.fillText(n.label, n.x, n.y + n.r + 12)
})
ctx.globalAlpha = 1
}
let dragNode = null
function getCanvasPos(e) {
const rect = canvas.getBoundingClientRect()
return {
x: (e.clientX - rect.left) * (width / rect.width),
y: (e.clientY - rect.top) * (height / rect.height),
}
}
function findHit(px, py) {
for (let i = nodes.length - 1; i >= 0; i--) {
const n = nodes[i]
const dx = px - n.x
const dy = py - n.y
if (dx * dx + dy * dy <= (n.r + 8) * (n.r + 8)) return n
}
return null
}
function onPointerDown(e) {
const pos = getCanvasPos(e)
const hit = findHit(pos.x, pos.y)
if (hit) {
dragNode = hit
setSelectedNode(hit.id)
hit.fx = hit.x
hit.fy = hit.y
simulation.alphaTarget(0.3).restart()
}
}
function onPointerMove(e) {
if (!dragNode) return
const pos = getCanvasPos(e)
dragNode.fx = Math.max(0, Math.min(width, pos.x))
dragNode.fy = Math.max(0, Math.min(height, pos.y))
}
function onPointerUp() {
if (dragNode) {
dragNode.fx = null
dragNode.fy = null
dragNode = null
simulation.alphaTarget(0)
}
}
canvas.addEventListener('pointerdown', onPointerDown)
window.addEventListener('pointermove', onPointerMove)
window.addEventListener('pointerup', onPointerUp)
return () => {
simulation.stop()
canvas.removeEventListener('pointerdown', onPointerDown)
window.removeEventListener('pointermove', onPointerMove)
window.removeEventListener('pointerup', onPointerUp)
}
}, [filteredSkills, filteredMembers, levels, categories, aggregated, selectedNode, allSkills])
return (
<div className="space-y-4">
<div className="flex items-center justify-between flex-wrap gap-2">
<div className="flex items-center gap-3 text-sm text-gray-500 dark:text-gray-400">
<span className="inline-flex items-center gap-1.5">
<span className="w-3 h-3 rounded-full bg-indigo-500 inline-block" /> Membre
</span>
<span className="inline-flex items-center gap-1.5">
<span className="w-3 h-3 rounded-sm bg-gray-400 inline-block" /> Compétence
</span>
<span className="inline-flex items-center gap-1.5">
<span className="w-3 h-3 rounded-full border border-current inline-block" /> Catégorie
</span>
</div>
<Button variant="outline" size="sm" onClick={() => setAggregated(!aggregated)}>
{aggregated ? 'Détailler les compétences' : 'Agréger par catégorie'}
</Button>
</div>
<div className="bg-white dark:bg-gray-950 rounded-lg overflow-hidden relative">
<canvas
ref={canvasRef}
className="block w-full touch-none"
style={{ height: `${height}px`, cursor: 'grab' }}
/>
<div className="absolute bottom-3 left-1/2 -translate-x-1/2 text-xs text-gray-400 pointer-events-none">
Cliquez sur un nœud pour le sélectionner Glissez pour déplacer
</div>
</div>
</div>
)
}
+157
View File
@@ -0,0 +1,157 @@
import { useState } from 'react'
import { ChevronDown, ChevronRight, ListCollapse } from 'lucide-react'
import { SkillLevelSelect } from '@/components/SkillLevelBadge'
const heatColors = {
0: 'bg-gray-50 dark:bg-gray-900',
1: 'bg-gray-200 dark:bg-gray-700',
2: 'bg-blue-200 dark:bg-blue-900',
3: 'bg-amber-200 dark:bg-amber-900',
4: 'bg-green-200 dark:bg-green-900',
}
export function HeatmapView({
categories, levels,
isAdmin, currentUserId,
editing, onEdit, onUpdate, onCancel,
filteredSkills, visibleMembers,
}) {
const [collapsed, setCollapsed] = useState(new Set())
const grouped = categories
.map((cat) => ({
...cat,
catSkills: filteredSkills.filter((s) => s.category_id === cat.id),
}))
.filter((g) => g.catSkills.length > 0)
const allCollapsed = grouped.every((g) => collapsed.has(g.id))
function toggleCategory(catId) {
setCollapsed((prev) => {
const next = new Set(prev)
if (next.has(catId)) next.delete(catId)
else next.add(catId)
return next
})
}
function toggleAll() {
if (allCollapsed) {
setCollapsed(new Set())
} else {
setCollapsed(new Set(grouped.map((g) => g.id)))
}
}
if (visibleMembers.length === 0) {
return (
<div className="p-8 text-center text-gray-400">
Aucun résultat
</div>
)
}
return (
<div className="overflow-auto">
<table className="w-full border-collapse">
<thead>
<tr>
<th className="text-left p-2 bg-gray-100 dark:bg-gray-800 border dark:border-gray-700 sticky left-0 z-10 min-w-[180px]">
<button
className="inline-flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 mr-2"
onClick={toggleAll}
title={allCollapsed ? 'Tout dérouler' : 'Tout replier'}
>
<ListCollapse className={`h-3.5 w-3.5 transition-transform ${allCollapsed ? '' : 'rotate-180'}`} />
</button>
Compétence
</th>
{visibleMembers.map((m) => (
<th key={m.id} className="p-2 bg-gray-100 dark:bg-gray-800 border dark:border-gray-700 text-sm text-center min-w-[120px]">
{m.full_name || m.email}
</th>
))}
</tr>
</thead>
<tbody>
{grouped.map((g) => {
const isCollapsed = collapsed.has(g.id)
return (
<>
<tr key={g.id} className="bg-gray-50 dark:bg-gray-800/50 hover:bg-gray-100 dark:hover:bg-gray-800">
<td className="p-2 border dark:border-gray-700 font-semibold text-sm sticky left-0 bg-gray-50 dark:bg-gray-800/50 cursor-pointer" onClick={() => toggleCategory(g.id)}>
<span className="flex items-center gap-2">
{isCollapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
<span className="w-2 h-2 rounded-full" style={{ backgroundColor: g.color }} />
{g.name}
</span>
</td>
{visibleMembers.map((m) => {
const dotColors = ['bg-gray-200', 'bg-blue-200', 'bg-amber-200', 'bg-green-200']
const counts = [0, 0, 0, 0]
g.catSkills.forEach((s) => {
const lvl = levels[`${m.id}-${s.id}`]?.level
if (lvl) counts[lvl - 1]++
})
return (
<td key={m.id} className="p-2 border dark:border-gray-700 text-center bg-gray-50 dark:bg-gray-800/50">
<span className="inline-flex items-center gap-2 text-xs">
{counts.map((c, i) =>
c > 0 ? (
<span key={i} className="inline-flex items-center gap-0.5">
<span className={'inline-block w-2.5 h-2.5 rounded-full ' + dotColors[i]} />
<span className="font-semibold">{c}</span>
</span>
) : null
)}
</span>
</td>
)
})}
</tr>
{!isCollapsed && g.catSkills.map((s) => (
<tr key={s.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
<td className="p-2 border dark:border-gray-700 font-medium sticky left-0 bg-white dark:bg-gray-950">
<span className="text-sm pl-6">{s.name}</span>
</td>
{visibleMembers.map((m) => {
const key = `${m.id}-${s.id}`
const level = levels[key]
const lvl = level?.level || 0
const canEditCell = isAdmin || currentUserId === m.id
const isEditing = editing === key
return (
<td
key={m.id}
className={`p-2 border dark:border-gray-700 text-center ${heatColors[lvl]} ${currentUserId === m.id ? 'ring-2 ring-blue-400 dark:ring-blue-600 ring-inset' : ''}`}
>
{isEditing && canEditCell ? (
<SkillLevelSelect
value={level?.level || 1}
onChange={(v) => onUpdate(m.id, s.id, v)}
/>
) : (
<span
className="text-sm font-medium cursor-pointer"
onClick={() => canEditCell && onEdit(key)}
>
{lvl || '—'}
</span>
)}
{isEditing && canEditCell && (
<button className="ml-1 text-xs text-red-500" onClick={onCancel}></button>
)}
</td>
)
})}
</tr>
))}
</>
)
})}
</tbody>
</table>
</div>
)
}
+104
View File
@@ -0,0 +1,104 @@
import { useState } from 'react'
import {
RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, Tooltip, ResponsiveContainer, Legend,
} from 'recharts'
export default function RadarView({
categories, skills: allSkills, members, levels, filterMember,
}) {
const [selectedMember, setSelectedMember] = useState(filterMember !== 'all' ? filterMember : (members[0]?.id || ''))
function getCategoryAvg(catId) {
const catSkills = allSkills.filter((s) => s.category_id === catId)
if (catSkills.length === 0) return 0
let total = 0
let count = 0
members.forEach((m) => {
catSkills.forEach((s) => {
const key = `${m.id}-${s.id}`
const lvl = levels[key]?.level
if (lvl) { total += lvl; count++ }
})
})
return count > 0 ? +(total / count).toFixed(1) : 0
}
function getMemberAvg(catId, memberId) {
const catSkills = allSkills.filter((s) => s.category_id === catId)
if (catSkills.length === 0) return 0
let total = 0
let count = 0
catSkills.forEach((s) => {
const key = `${memberId}-${s.id}`
const lvl = levels[key]?.level
if (lvl) { total += lvl; count++ }
})
return count > 0 ? +(total / count).toFixed(1) : 0
}
const data = categories.map((cat) => {
const teamAvg = getCategoryAvg(cat.id)
const memberAvg = selectedMember ? getMemberAvg(cat.id, selectedMember) : 0
return {
category: cat.name,
color: cat.color,
teamAvg,
memberAvg,
}
})
const selectedMemberName = members.find((m) => m.id === selectedMember)?.full_name || 'Membre'
if (data.length === 0) {
return <div className="p-8 text-center text-gray-400">Aucune donnée à afficher</div>
}
return (
<div className="bg-white dark:bg-gray-950 rounded-lg p-4">
<div className="flex items-center gap-4 mb-4">
<label className="text-sm text-gray-600 dark:text-gray-400">Membre :</label>
<select
className="border rounded px-2 py-1 text-sm dark:bg-gray-800 dark:border-gray-700"
value={selectedMember}
onChange={(e) => setSelectedMember(e.target.value)}
>
{members.map((m) => (
<option key={m.id} value={m.id}>{m.full_name || m.email}</option>
))}
</select>
</div>
<ResponsiveContainer width="100%" height={450}>
<RadarChart data={data}>
<PolarGrid stroke="var(--border)" />
<PolarAngleAxis dataKey="category" stroke="var(--foreground)" tick={{ fontSize: 11 }} />
<PolarRadiusAxis domain={[0, 4]} tickCount={5} stroke="var(--border)" tick={{ fontSize: 10 }} />
<Tooltip
contentStyle={{
background: 'var(--background)',
border: '1px solid var(--border)',
borderRadius: 'var(--radius)',
fontSize: 13,
}}
/>
<Radar
name="Moyenne équipe"
dataKey="teamAvg"
stroke="var(--muted-foreground)"
fill="var(--muted-foreground)"
fillOpacity={0.1}
strokeDasharray="4 4"
/>
<Radar
name={selectedMemberName}
dataKey="memberAvg"
stroke="var(--foreground)"
fill="var(--foreground)"
fillOpacity={0.15}
/>
<Legend />
</RadarChart>
</ResponsiveContainer>
</div>
)
}
+126
View File
@@ -0,0 +1,126 @@
import {
ScatterChart, Scatter, XAxis, YAxis, ZAxis, CartesianGrid,
Tooltip, ResponsiveContainer, Legend,
} from 'recharts'
export default function ScatterView({
members, levels, categories,
filterMember,
filteredSkills, onMemberSelect,
}) {
const data = []
const catGaps = {}
let xPos = 0
categories.forEach((cat) => {
const catSkills = filteredSkills.filter((s) => s.category_id === cat.id)
if (catSkills.length === 0) return
xPos += 1
catGaps[cat.id] = { start: xPos, end: xPos + catSkills.length - 1 }
catSkills.forEach((s) => {
const x = xPos++
members.forEach((m) => {
if (filterMember !== 'all' && m.id !== filterMember) return
const key = `${m.id}-${s.id}`
const lvl = levels[key]?.level
if (!lvl) return
data.push({
x,
y: lvl + (Math.random() - 0.5) * 0.3,
memberName: m.full_name || m.email,
skillName: s.name,
level: lvl,
category: cat.name,
categoryColor: cat.color,
memberId: m.id,
})
})
})
})
const ticks = categories
.filter((cat) => catGaps[cat.id])
.map((cat) => ({
value: (catGaps[cat.id].start + catGaps[cat.id].end) / 2,
label: cat.name,
}))
if (data.length === 0) {
return <div className="p-8 text-center text-gray-400">Aucune donnée à afficher</div>
}
return (
<div className="bg-white dark:bg-gray-950 rounded-lg p-4">
<ResponsiveContainer width="100%" height={500}>
<ScatterChart margin={{ top: 20, right: 20, bottom: 60, left: 40 }}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
<XAxis
type="number"
dataKey="x"
domain={[0, 'dataMax']}
ticks={ticks.map((t) => t.value)}
tickFormatter={(v) => ticks.find((t) => t.value === v)?.label || ''}
stroke="var(--foreground)"
tick={{ fontSize: 12 }}
/>
<YAxis
type="number"
domain={[0.5, 4.5]}
ticks={[1, 2, 3, 4]}
tickFormatter={(v) => ['', '1 - Débutant', '2 - Intermédiaire', '3 - Avancé', '4 - Expert'][v]}
stroke="var(--foreground)"
tick={{ fontSize: 12 }}
/>
<ZAxis range={[60, 60]} />
<Tooltip
contentStyle={{
background: 'var(--background)',
border: '1px solid var(--border)',
borderRadius: 'var(--radius)',
fontSize: 13,
}}
formatter={(val, name) => {
if (name === 'y') return null
return [val, name]
}}
labelFormatter={() => ''}
content={({ active, payload }) => {
if (!active || !payload?.[0]) return null
const d = payload[0].payload
return (
<div className="bg-white dark:bg-gray-800 border rounded-lg p-3 shadow-lg text-sm space-y-1">
<p className="font-medium">{d.memberName}</p>
<p>{d.skillName}</p>
<p>Niveau : <strong>{d.level}</strong></p>
<p className="text-xs" style={{ color: d.categoryColor }}>{d.category}</p>
</div>
)
}}
/>
<Legend
payload={categories.map((c) => ({
id: c.id,
value: c.name,
type: 'circle',
color: c.color,
}))}
/>
{categories.map((cat) => {
const catData = data.filter((d) => d.category === cat.name)
return (
<Scatter
key={cat.id}
name={cat.name}
data={catData}
fill={cat.color}
stroke="none"
onClick={(point) => onMemberSelect?.(point.memberId)}
style={{ cursor: 'pointer' }}
/>
)
})}
</ScatterChart>
</ResponsiveContainer>
</div>
)
}
@@ -0,0 +1,45 @@
export function SkillMatrixFilters({ categories, members, filterCat, filterMember, filterMinLevel, onFilterChange, hideMember }) {
return (
<div className="flex gap-4 flex-wrap">
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600 dark:text-gray-400">Catégorie :</label>
<select
className="border rounded px-2 py-1 text-sm dark:bg-gray-800 dark:border-gray-700"
value={filterCat}
onChange={(e) => onFilterChange('cat', e.target.value)}
>
<option value="all">Toutes</option>
{categories.map((c) => (
<option key={c.id} value={c.id}>{c.name}</option>
))}
</select>
</div>
{!hideMember && (
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600 dark:text-gray-400">Membre :</label>
<select
className="border rounded px-2 py-1 text-sm dark:bg-gray-800 dark:border-gray-700"
value={filterMember}
onChange={(e) => onFilterChange('member', e.target.value)}
>
<option value="all">Tous</option>
{members.map((m) => (
<option key={m.id} value={m.id}>{m.full_name || m.email}</option>
))}
</select>
</div>
)}
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600 dark:text-gray-400">Niveau min. :</label>
<select
className="border rounded px-2 py-1 text-sm dark:bg-gray-800 dark:border-gray-700"
value={filterMinLevel}
onChange={(e) => onFilterChange('minLevel', Number(e.target.value))}
>
<option value={0}>Aucun</option>
{[1, 2, 3, 4].map((l) => <option key={l} value={l}>{l}</option>)}
</select>
</div>
</div>
)
}
+147
View File
@@ -0,0 +1,147 @@
import { useState } from 'react'
import { ChevronDown, ChevronRight, ListCollapse } from 'lucide-react'
import { SkillLevelBadge, SkillLevelSelect } from '@/components/SkillLevelBadge'
export function SkillMatrixTable({ categories, skills, members, levels, isAdmin, currentUserId, editing, onEdit, onUpdate, onCancel }) {
const [collapsed, setCollapsed] = useState(new Set())
const grouped = categories
.map((cat) => ({
...cat,
catSkills: skills.filter((s) => s.category_id === cat.id),
}))
.filter((g) => g.catSkills.length > 0)
const allCollapsed = grouped.every((g) => collapsed.has(g.id))
function toggleCategory(catId) {
setCollapsed((prev) => {
const next = new Set(prev)
if (next.has(catId)) next.delete(catId)
else next.add(catId)
return next
})
}
function toggleAll() {
if (allCollapsed) {
setCollapsed(new Set())
} else {
setCollapsed(new Set(grouped.map((g) => g.id)))
}
}
if (members.length === 0) {
return (
<div className="p-8 text-center text-gray-400">
Aucun résultat
</div>
)
}
return (
<div className="overflow-auto">
<table className="w-full border-collapse">
<thead>
<tr>
<th className="text-left p-2 bg-gray-100 dark:bg-gray-800 border dark:border-gray-700 sticky left-0 z-10 min-w-[180px]">
<button
className="inline-flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 mr-2"
onClick={toggleAll}
title={allCollapsed ? 'Tout dérouler' : 'Tout replier'}
>
<ListCollapse className={`h-3.5 w-3.5 transition-transform ${allCollapsed ? '' : 'rotate-180'}`} />
</button>
Compétence
</th>
{members.map((m) => (
<th key={m.id} className="p-2 bg-gray-100 dark:bg-gray-800 border dark:border-gray-700 text-sm text-center min-w-[120px]">
{m.full_name || m.email}
</th>
))}
</tr>
</thead>
<tbody>
{grouped.map((g) => {
const isCollapsed = collapsed.has(g.id)
return (
<>
<tr key={g.id} className="bg-gray-50 dark:bg-gray-800/50 hover:bg-gray-100 dark:hover:bg-gray-800">
<td className="p-2 border dark:border-gray-700 font-semibold text-sm sticky left-0 bg-gray-50 dark:bg-gray-800/50 cursor-pointer" onClick={() => toggleCategory(g.id)}>
<span className="flex items-center gap-2">
{isCollapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
<span className="w-2 h-2 rounded-full" style={{ backgroundColor: g.color }} />
{g.name}
</span>
</td>
{members.map((m) => {
const dotColors = ['bg-gray-200', 'bg-blue-200', 'bg-amber-200', 'bg-green-200']
const counts = [0, 0, 0, 0]
g.catSkills.forEach((s) => {
const lvl = levels[`${m.id}-${s.id}`]?.level
if (lvl) counts[lvl - 1]++
})
return (
<td key={m.id} className="p-2 border dark:border-gray-700 text-center bg-gray-50 dark:bg-gray-800/50">
<span className="inline-flex items-center gap-2 text-xs">
{counts.map((c, i) =>
c > 0 ? (
<span key={i} className="inline-flex items-center gap-0.5">
<span className={'inline-block w-2.5 h-2.5 rounded-full ' + dotColors[i]} />
<span className="font-semibold">{c}</span>
</span>
) : null
)}
</span>
</td>
)
})}
</tr>
{!isCollapsed && g.catSkills.map((s) => (
<tr key={s.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
<td className="p-2 border dark:border-gray-700 font-medium sticky left-0 bg-white dark:bg-gray-950">
<span className="text-sm pl-6">{s.name}</span>
</td>
{members.map((m) => {
const key = `${m.id}-${s.id}`
const level = levels[key]
const canEditCell = isAdmin || currentUserId === m.id
const isEditing = editing === key
return (
<td key={m.id} className={`p-2 border dark:border-gray-700 text-center ${currentUserId === m.id ? 'bg-blue-50 dark:bg-blue-950/20' : ''}`}>
{isEditing && canEditCell ? (
<SkillLevelSelect
value={level?.level || 1}
onChange={(v) => onUpdate(m.id, s.id, v)}
/>
) : (
level ? (
<SkillLevelBadge
level={level.level}
onClick={() => canEditCell && onEdit(key)}
/>
) : (
<span
className="text-gray-300 dark:text-gray-600 text-sm cursor-pointer"
onClick={() => canEditCell && onEdit(key)}
>
</span>
)
)}
{isEditing && canEditCell && (
<button className="ml-1 text-xs text-red-500" onClick={onCancel}></button>
)}
</td>
)
})}
</tr>
))}
</>
)
})}
</tbody>
</table>
</div>
)
}
+80
View File
@@ -0,0 +1,80 @@
import { useState } from 'react'
import { SkillLevelSelect } from '@/components/SkillLevelBadge'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Save } from 'lucide-react'
export function SkillMemberForm({ member, categories, skills, levels, isAdmin, currentUserId, onSave }) {
const canEdit = isAdmin || currentUserId === member.id
const initial = {}
skills.forEach((s) => {
const key = `${member.id}-${s.id}`
initial[s.id] = levels[key]?.level || 0
})
const [editedLevels, setEditedLevels] = useState(initial)
const hasChanges = skills.some((s) => {
const key = `${member.id}-${s.id}`
return (editedLevels[s.id] || 0) !== (levels[key]?.level || 0)
})
function handleSave() {
const changes = []
skills.forEach((s) => {
const key = `${member.id}-${s.id}`
const current = levels[key]?.level || 0
const edited = editedLevels[s.id] || 0
if (edited !== current) {
changes.push({ skillId: s.id, oldLevel: current || null, newLevel: edited })
}
})
if (changes.length > 0) onSave(member.id, changes)
}
return (
<div className="space-y-4">
<p className="text-sm text-gray-500 dark:text-gray-400">
Modification des compétences de <span className="font-medium text-gray-700 dark:text-gray-200">{member.full_name || member.email}</span>
</p>
{categories.map((cat) => {
const catSkills = skills.filter((s) => s.category_id === cat.id)
if (catSkills.length === 0) return null
return (
<Card key={cat.id}>
<CardContent className="p-4 space-y-3">
<h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider flex items-center gap-2">
<span className="w-2 h-2 rounded-full" style={{ backgroundColor: cat.color }} />
{cat.name}
</h3>
{catSkills.map((s) => (
<div key={s.id} className="flex items-center justify-between py-1.5 border-b dark:border-gray-800 last:border-0">
<span className="text-sm">{s.name}</span>
{canEdit ? (
<SkillLevelSelect
value={editedLevels[s.id] || 1}
onChange={(v) => setEditedLevels((prev) => ({ ...prev, [s.id]: v }))}
/>
) : (
<span className="text-sm font-medium">
{levels[`${member.id}-${s.id}`]?.level || '—'}
</span>
)}
</div>
))}
</CardContent>
</Card>
)
})}
{canEdit && (
<div className="flex justify-end">
<Button onClick={handleSave} disabled={!hasChanges}>
<Save className="h-4 w-4 mr-2" />
Enregistrer
</Button>
</div>
)}
</div>
)
}
+158
View File
@@ -0,0 +1,158 @@
import { Treemap, ResponsiveContainer, Tooltip } from 'recharts'
import { Card, CardContent } from '@/components/ui/card'
export default function TreemapView({
categories: allCategories, members, levels,
filterMember, filterCat,
filteredSkills, onCellClick,
}) {
const cats = allCategories
.filter((cat) => filterCat === 'all' || cat.id === filterCat)
.map((cat) => {
const catSkills = filteredSkills.filter((s) => s.category_id === cat.id)
return {
name: cat.name,
color: cat.color,
children: catSkills.map((s) => {
let total = 0
let count = 0
if (filterMember !== 'all') {
const key = `${filterMember}-${s.id}`
const lvl = levels[key]?.level
if (lvl) { total += lvl; count++ }
} else {
members.forEach((m) => {
const key = `${m.id}-${s.id}`
const lvl = levels[key]?.level
if (lvl) { total += lvl; count++ }
})
}
const avg = count > 0 ? +(total / count).toFixed(1) : 0
return {
name: s.name,
size: 1,
avg,
count,
skillId: s.id,
catId: cat.id,
}
}),
}
})
.filter((cat) => cat.children.length > 0)
const flatData = cats
.flatMap((cat) => cat.children)
.sort((a, b) => b.avg - a.avg)
if (flatData.length === 0) {
return <div className="p-8 text-center text-gray-400">Aucune donnée à afficher</div>
}
function getColor(avg) {
if (avg >= 3.5) return '#34d399'
if (avg >= 2.5) return '#fbbf24'
if (avg >= 1.5) return '#60a5fa'
return '#9ca3af'
}
return (
<div className="space-y-4">
<div className="bg-white dark:bg-gray-950 rounded-lg p-4">
<ResponsiveContainer width="100%" height={500}>
<Treemap
data={flatData}
dataKey="size"
aspectRatio={4 / 3}
stroke="var(--background)"
fill="#8884d8"
content={({ x, y, width, height, payload }) => {
if (!payload) return null
return (
<g>
<rect
x={x}
y={y}
width={width}
height={height}
fill={getColor(payload.avg)}
stroke="var(--background)"
strokeWidth={2}
style={{ cursor: 'pointer' }}
onClick={() => onCellClick?.(payload.catId, filterMember !== 'all' ? filterMember : undefined)}
rx={4}
/>
{width > 40 && height > 30 && (
<>
<text
x={x + width / 2}
y={y + height / 2 - 4}
textAnchor="middle"
fill={payload.avg >= 2.5 ? '#000' : '#fff'}
fontSize={12}
fontWeight={600}
>
{payload.name}
</text>
<text
x={x + width / 2}
y={y + height / 2 + 12}
textAnchor="middle"
fill={payload.avg >= 2.5 ? '#000' : '#fff'}
fontSize={11}
>
{payload.avg}
{filterMember === 'all' && ` (${payload.count})`}
</text>
</>
)}
</g>
)
}}
>
<Tooltip
contentStyle={{
background: 'var(--background)',
border: '1px solid var(--border)',
borderRadius: 'var(--radius)',
fontSize: 13,
}}
formatter={(value, name, props) => {
const p = props.payload
if (!p) return []
return [
filterMember === 'all'
? `Moyenne : ${p.avg}${p.count} évalué(s)`
: `Niveau : ${p.avg}`,
p.name,
]
}}
/>
</Treemap>
</ResponsiveContainer>
</div>
{flatData.length > 0 && (
<Card>
<CardContent className="p-4">
<h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 mb-3 uppercase tracking-wider">
Détail des compétences
</h3>
<div className="space-y-1">
{flatData.map((s) => (
<div
key={s.skillId}
className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-gray-100 dark:hover:bg-gray-800 cursor-pointer text-sm"
onClick={() => onCellClick?.(s.catId, filterMember !== 'all' ? filterMember : undefined)}
>
<span>{s.name}</span>
<span className="font-medium">{s.avg}</span>
</div>
))}
</div>
</CardContent>
</Card>
)}
</div>
)
}
+37
View File
@@ -0,0 +1,37 @@
import { Button } from '@/components/ui/button'
import {
Table2, Palette, ScatterChart, Share2, Grid3x3, Radar, BarChart3,
} from 'lucide-react'
const views = [
{ id: 'table', icon: Table2, label: 'Tableau' },
{ id: 'heat', icon: Palette, label: 'Matrice thermique' },
{ id: 'scatter', icon: ScatterChart, label: 'Nuage de points' },
{ id: 'graph', icon: Share2, label: 'Graphe' },
{ id: 'treemap', icon: Grid3x3, label: 'Treemap' },
{ id: 'radar', icon: Radar, label: 'Radar' },
{ id: 'bars', icon: BarChart3, label: 'Barres' },
]
export function ViewSwitcher({ active, onChange }) {
return (
<div className="flex gap-1" role="group" aria-label="Mode d'affichage">
{views.map((v) => {
const Icon = v.icon
const isActive = active === v.id
return (
<Button
key={v.id}
variant={isActive ? 'default' : 'outline'}
size="sm"
className="h-8 w-8 p-0"
onClick={() => onChange(v.id)}
title={v.label}
>
<Icon className="h-4 w-4" />
</Button>
)
})}
</div>
)
}
+38
View File
@@ -0,0 +1,38 @@
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
export function CategoryCard({ category, skills, onEdit, onDelete }) {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between py-3">
<CardTitle className="text-lg flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ backgroundColor: category.color }} />
{category.name}
<Badge variant="secondary" className="ml-2">{skills.length}</Badge>
</CardTitle>
<div className="flex gap-1">
<Button size="sm" variant="ghost" onClick={() => onEdit(category)}>
</Button>
<Button size="sm" variant="ghost" onClick={() => onDelete(category.id)}>
🗑
</Button>
</div>
</CardHeader>
<CardContent>
{skills.length === 0 ? (
<p className="text-sm text-gray-400 dark:text-gray-500">Aucune compétence dans cette catégorie</p>
) : (
<div className="flex flex-wrap gap-2">
{skills.map((s) => (
<Badge key={s.id} variant="outline" className="pr-1">
{s.name}
</Badge>
))}
</div>
)}
</CardContent>
</Card>
)
}
+1
View File
@@ -1,3 +1,4 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useEffect, useState } from 'react' import { createContext, useContext, useEffect, useState } from 'react'
import { supabase } from '@/lib/supabase' import { supabase } from '@/lib/supabase'
+19
View File
@@ -0,0 +1,19 @@
import { useEffect, useState, useCallback } from 'react'
import { supabase } from '@/lib/supabase'
export function useCategories() {
const [categories, setCategories] = useState([])
const [loading, setLoading] = useState(true)
const fetch = useCallback(async () => {
const { data, error } = await supabase.from('categories').select('*').order('name')
if (!error && data) setCategories(data)
setLoading(false)
return { data, error }
}, [])
// eslint-disable-next-line react-hooks/set-state-in-effect
useEffect(() => { fetch() }, [fetch])
return { categories, loading, refetch: fetch }
}
+68
View File
@@ -0,0 +1,68 @@
import { useEffect, useState, useCallback, useRef } from 'react'
import { supabase } from '@/lib/supabase'
const PAGE_SIZE = 50
export function useHistory() {
const [history, setHistory] = useState([])
const [loading, setLoading] = useState(true)
const [count, setCount] = useState(0)
const [page, setPage] = useState(0)
const [filters, setFilters] = useState({ memberId: 'all', skillId: 'all' })
const channelRef = useRef(null)
const totalPages = Math.ceil(count / PAGE_SIZE)
const fetch = useCallback(async () => {
setLoading(true)
let query = supabase
.from('skill_history')
.select('*, member:member_id(full_name), skill:skill_id(name), changer:changed_by(full_name)', { count: 'exact' })
.order('created_at', { ascending: false })
.range(page * PAGE_SIZE, (page + 1) * PAGE_SIZE - 1)
if (filters.memberId !== 'all') query = query.eq('member_id', filters.memberId)
if (filters.skillId !== 'all') query = query.eq('skill_id', filters.skillId)
const { data, count: total } = await query
if (data) setHistory(data)
if (total !== null) setCount(total)
setLoading(false)
}, [page, filters])
/* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => {
fetch()
channelRef.current = supabase
.channel('skill_history_changes')
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'skill_history' }, () => {
if (page === 0) fetch()
})
.subscribe()
return () => {
channelRef.current?.unsubscribe()
}
}, [fetch, page])
/* eslint-enable react-hooks/set-state-in-effect */
function setFilter(key, value) {
setFilters((f) => ({ ...f, [key]: value }))
setPage(0)
}
function nextPage() {
if (page < totalPages - 1) setPage((p) => p + 1)
}
function prevPage() {
if (page > 0) setPage((p) => p - 1)
}
return {
history, loading, count, page, totalPages, filters,
setFilter, nextPage, prevPage, refetch: fetch,
}
}
+19
View File
@@ -0,0 +1,19 @@
import { useEffect, useState, useCallback } from 'react'
import { supabase } from '@/lib/supabase'
export function useMembers() {
const [members, setMembers] = useState([])
const [loading, setLoading] = useState(true)
const fetch = useCallback(async () => {
const { data, error } = await supabase.from('members').select('*').order('full_name')
if (!error && data) setMembers(data)
setLoading(false)
return { data, error }
}, [])
// eslint-disable-next-line react-hooks/set-state-in-effect
useEffect(() => { fetch() }, [fetch])
return { members, loading, refetch: fetch }
}
+75
View File
@@ -0,0 +1,75 @@
import { useEffect, useState, useCallback, useRef } from 'react'
import { supabase } from '@/lib/supabase'
import { toast } from 'sonner'
export function useSkillLevels() {
const [levels, setLevels] = useState({})
const [loading, setLoading] = useState(true)
const channelRef = useRef(null)
const fetch = useCallback(async () => {
const { data, error } = await supabase.from('skill_levels').select('*')
if (!error && data) {
const map = {}
data.forEach((l) => { map[`${l.member_id}-${l.skill_id}`] = l })
setLevels(map)
}
setLoading(false)
return { data, error }
}, [])
/* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => {
fetch()
channelRef.current = supabase
.channel('skill_levels_changes')
.on('postgres_changes', { event: '*', schema: 'public', table: 'skill_levels' }, () => {
fetch()
})
.subscribe()
return () => {
channelRef.current?.unsubscribe()
}
}, [fetch])
/* eslint-enable react-hooks/set-state-in-effect */
async function updateLevel(memberId, skillId, newLevel, changedBy) {
const key = `${memberId}-${skillId}`
const existing = levels[key]
const oldLevel = existing?.level
if (existing) {
const { error } = await supabase.from('skill_levels').update({ level: newLevel }).eq('id', existing.id)
if (error) { toast.error(error.message); return }
} else {
const { error } = await supabase.from('skill_levels').insert({ member_id: memberId, skill_id: skillId, level: newLevel })
if (error) { toast.error(error.message); return }
}
if (oldLevel !== newLevel && changedBy) {
const { error } = await supabase.from('skill_history').insert({
member_id: memberId,
skill_id: skillId,
old_level: oldLevel || null,
new_level: newLevel,
changed_by: changedBy,
})
if (error) { toast.error(error.message); return }
}
await fetch()
}
async function getAverageSkillRating(skillId) {
const { data } = await supabase
.from('skill_levels')
.select('level')
.eq('skill_id', skillId)
if (!data || data.length === 0) return null
return (data.reduce((sum, l) => sum + l.level, 0) / data.length).toFixed(1)
}
return { levels, loading, refetch: fetch, updateLevel, getAverageSkillRating }
}
+19
View File
@@ -0,0 +1,19 @@
import { useEffect, useState, useCallback } from 'react'
import { supabase } from '@/lib/supabase'
export function useSkills() {
const [skills, setSkills] = useState([])
const [loading, setLoading] = useState(true)
const fetch = useCallback(async () => {
const { data, error } = await supabase.from('skills').select('*, category:category_id(name)').order('name')
if (!error && data) setSkills(data)
setLoading(false)
return { data, error }
}, [])
// eslint-disable-next-line react-hooks/set-state-in-effect
useEffect(() => { fetch() }, [fetch])
return { skills, loading, refetch: fetch }
}
+3
View File
@@ -1,10 +1,13 @@
import { StrictMode } from 'react' import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import { ThemeProvider } from 'next-themes'
import './index.css' import './index.css'
import App from './App.jsx' import App from './App.jsx'
createRoot(document.getElementById('root')).render( createRoot(document.getElementById('root')).render(
<StrictMode> <StrictMode>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
<App /> <App />
</ThemeProvider>
</StrictMode>, </StrictMode>,
) )
+14 -6
View File
@@ -16,29 +16,36 @@ export function AcceptInvite() {
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [valid, setValid] = useState(false) const [valid, setValid] = useState(false)
/* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => { useEffect(() => {
let cancelled = false
async function checkToken() { async function checkToken() {
const { data, error } = await supabase const { data } = await supabase
.from('invitations') .from('invitations')
.select('*') .select('*')
.eq('token', token) .eq('token', token)
.eq('accepted', false) .eq('accepted', false)
.gte('expires_at', new Date().toISOString())
.single() .single()
if (data && !error) { if (!cancelled) {
if (data) {
setEmail(data.email) setEmail(data.email)
setValid(true) setValid(true)
} }
setLoading(false) setLoading(false)
} }
}
if (token) checkToken() if (token) checkToken()
else setLoading(false) else setLoading(false)
return () => { cancelled = true }
}, [token]) }, [token])
/* eslint-enable react-hooks/set-state-in-effect */
async function handleSubmit(e) { async function handleSubmit(e) {
e.preventDefault() e.preventDefault()
setLoading(true) setLoading(true)
const { data, error } = await supabase.auth.signUp({ const { error } = await supabase.auth.signUp({
email, email,
password, password,
options: { data: { full_name: name } }, options: { data: { full_name: name } },
@@ -50,8 +57,9 @@ export function AcceptInvite() {
return return
} }
// Marquer l'invitation comme acceptée
await supabase.from('invitations').update({ accepted: true }).eq('token', token) await supabase.from('invitations').update({ accepted: true }).eq('token', token)
.then()
.catch(() => {})
toast.success('Compte créé ! Vous pouvez vous connecter.') toast.success('Compte créé ! Vous pouvez vous connecter.')
navigate('/login') navigate('/login')
@@ -69,11 +77,11 @@ export function AcceptInvite() {
) )
return ( return (
<div className="min-h-screen flex items-center justify-center bg-gray-100"> <div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-950">
<Card className="w-full max-w-md"> <Card className="w-full max-w-md">
<CardHeader> <CardHeader>
<CardTitle className="text-2xl text-center">Accepter l'invitation</CardTitle> <CardTitle className="text-2xl text-center">Accepter l'invitation</CardTitle>
<p className="text-sm text-gray-500 text-center mt-1">{email}</p> <p className="text-sm text-gray-500 dark:text-gray-400 text-center mt-1">{email}</p>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<form onSubmit={handleSubmit} className="space-y-4"> <form onSubmit={handleSubmit} className="space-y-4">
+5 -6
View File
@@ -29,7 +29,6 @@ export function Dashboard() {
}) })
setRecentChanges(history.data || []) setRecentChanges(history.data || [])
// Compétences les mieux notées (moyenne)
const { data: levels } = await supabase const { data: levels } = await supabase
.from('skill_levels') .from('skill_levels')
.select('skill_id, level, skill:skill_id(name)') .select('skill_id, level, skill:skill_id(name)')
@@ -54,7 +53,7 @@ export function Dashboard() {
<div className="space-y-6"> <div className="space-y-6">
<h1 className="text-2xl font-bold">Tableau de bord</h1> <h1 className="text-2xl font-bold">Tableau de bord</h1>
<div className="grid grid-cols-3 gap-4"> <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card> <Card>
<CardHeader><CardTitle className="text-lg">Membres</CardTitle></CardHeader> <CardHeader><CardTitle className="text-lg">Membres</CardTitle></CardHeader>
<CardContent><p className="text-3xl font-bold">{stats.members}</p></CardContent> <CardContent><p className="text-3xl font-bold">{stats.members}</p></CardContent>
@@ -69,12 +68,12 @@ export function Dashboard() {
</Card> </Card>
</div> </div>
<div className="grid grid-cols-2 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Card> <Card>
<CardHeader><CardTitle className="text-lg">Compétences les mieux notées</CardTitle></CardHeader> <CardHeader><CardTitle className="text-lg">Compétences les mieux notées</CardTitle></CardHeader>
<CardContent> <CardContent>
{topSkills.length === 0 ? ( {topSkills.length === 0 ? (
<p className="text-gray-500">Aucune évaluation pour le moment</p> <p className="text-gray-500 dark:text-gray-400">Aucune évaluation pour le moment</p>
) : ( ) : (
<ul className="space-y-2"> <ul className="space-y-2">
{topSkills.map((s) => ( {topSkills.map((s) => (
@@ -92,11 +91,11 @@ export function Dashboard() {
<CardHeader><CardTitle className="text-lg">Dernières évolutions</CardTitle></CardHeader> <CardHeader><CardTitle className="text-lg">Dernières évolutions</CardTitle></CardHeader>
<CardContent className="max-h-80 overflow-auto"> <CardContent className="max-h-80 overflow-auto">
{recentChanges.length === 0 ? ( {recentChanges.length === 0 ? (
<p className="text-gray-500">Aucun changement récent</p> <p className="text-gray-500 dark:text-gray-400">Aucun changement récent</p>
) : ( ) : (
<ul className="space-y-3"> <ul className="space-y-3">
{recentChanges.map((c) => ( {recentChanges.map((c) => (
<li key={c.id} className="text-sm border-b pb-2 last:border-0"> <li key={c.id} className="text-sm border-b dark:border-gray-800 pb-2 last:border-0">
<span className="font-medium">{c.member?.full_name}</span> <span className="font-medium">{c.member?.full_name}</span>
{' '}a mis à jour{' '} {' '}a mis à jour{' '}
<span className="font-medium">{c.skill?.name}</span> <span className="font-medium">{c.skill?.name}</span>
+40 -49
View File
@@ -1,44 +1,15 @@
import { useEffect, useState } from 'react' import { useMembers } from '@/hooks/useMembers'
import { supabase } from '@/lib/supabase' import { useSkills } from '@/hooks/useSkills'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { useHistory } from '@/hooks/useHistory'
import { Card, CardContent } from '@/components/ui/card'
import { SkillLevelBadge } from '@/components/SkillLevelBadge' import { SkillLevelBadge } from '@/components/SkillLevelBadge'
import { Input } from '@/components/ui/input' import { Button } from '@/components/ui/button'
import { ChevronLeft, ChevronRight } from 'lucide-react'
export function History() { export function History() {
const [history, setHistory] = useState([]) const { members } = useMembers()
const [members, setMembers] = useState([]) const { skills } = useSkills()
const [skills, setSkills] = useState([]) const { history, loading, count, page, totalPages, filters, setFilter, nextPage, prevPage } = useHistory()
const [filterMember, setFilterMember] = useState('all')
const [filterSkill, setFilterSkill] = useState('all')
useEffect(() => {
async function load() {
const [memRes, skillRes] = await Promise.all([
supabase.from('members').select('*').order('full_name'),
supabase.from('skills').select('*').order('name'),
])
if (memRes.data) setMembers(memRes.data)
if (skillRes.data) setSkills(skillRes.data)
}
load()
}, [])
useEffect(() => {
async function loadHistory() {
let query = supabase
.from('skill_history')
.select('*, member:member_id(full_name), skill:skill_id(name), changer:changed_by(full_name)')
.order('created_at', { ascending: false })
.limit(100)
if (filterMember !== 'all') query = query.eq('member_id', filterMember)
if (filterSkill !== 'all') query = query.eq('skill_id', filterSkill)
const { data } = await query
if (data) setHistory(data)
}
loadHistory()
}, [filterMember, filterSkill])
return ( return (
<div className="space-y-6"> <div className="space-y-6">
@@ -46,9 +17,9 @@ export function History() {
<div className="flex gap-4"> <div className="flex gap-4">
<select <select
className="border rounded px-2 py-1 text-sm" className="border rounded px-2 py-1 text-sm dark:bg-gray-800 dark:border-gray-700"
value={filterMember} value={filters.memberId}
onChange={(e) => setFilterMember(e.target.value)} onChange={(e) => setFilter('memberId', e.target.value)}
> >
<option value="all">Tous les membres</option> <option value="all">Tous les membres</option>
{members.map((m) => ( {members.map((m) => (
@@ -56,9 +27,9 @@ export function History() {
))} ))}
</select> </select>
<select <select
className="border rounded px-2 py-1 text-sm" className="border rounded px-2 py-1 text-sm dark:bg-gray-800 dark:border-gray-700"
value={filterSkill} value={filters.skillId}
onChange={(e) => setFilterSkill(e.target.value)} onChange={(e) => setFilter('skillId', e.target.value)}
> >
<option value="all">Toutes les compétences</option> <option value="all">Toutes les compétences</option>
{skills.map((s) => ( {skills.map((s) => (
@@ -69,18 +40,24 @@ export function History() {
<Card> <Card>
<CardContent className="p-0"> <CardContent className="p-0">
{history.length === 0 ? ( {loading ? (
<p className="p-6 text-gray-400">Chargement...</p>
) : history.length === 0 ? (
<p className="p-6 text-gray-400">Aucun historique</p> <p className="p-6 text-gray-400">Aucun historique</p>
) : ( ) : (
<ul className="divide-y"> <ul className="divide-y dark:divide-gray-800">
{history.map((h) => ( {history.map((h) => (
<li key={h.id} className="p-4 flex items-center justify-between"> <li key={h.id} className="p-4 flex items-center justify-between">
<div className="space-y-1"> <div className="space-y-1">
<p className="text-sm"> <p className="text-sm">
<span className="font-medium">{h.member?.full_name}</span> <span className="text-gray-500 dark:text-gray-400">Membre :</span>
{' '}<span className="font-medium">{h.skill?.name}</span> {' '}<span className="font-medium">{h.member?.full_name || h.member_id?.slice(0, 8)}</span>
</p> </p>
<p className="text-xs text-gray-500"> <p className="text-sm">
<span className="text-gray-500 dark:text-gray-400">Compétence :</span>
{' '}<span className="font-medium">{h.skill?.name}</span>
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">
Par {h.changer?.full_name} {new Date(h.created_at).toLocaleString()} Par {h.changer?.full_name} {new Date(h.created_at).toLocaleString()}
</p> </p>
</div> </div>
@@ -95,6 +72,20 @@ export function History() {
)} )}
</CardContent> </CardContent>
</Card> </Card>
{totalPages > 1 && (
<div className="flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
<span>{count} entrées Page {page + 1} / {totalPages}</span>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={prevPage} disabled={page === 0}>
<ChevronLeft className="h-4 w-4" /> Précédent
</Button>
<Button variant="outline" size="sm" onClick={nextPage} disabled={page >= totalPages - 1}>
Suivant <ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div> </div>
) )
} }
+27 -3
View File
@@ -4,10 +4,11 @@ import { useAuth } from '@/context/AuthContext'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { InviteUserModal } from '@/components/InviteUserModal' import { InviteUserModal } from '@/components/InviteUserModal'
import { Download } from 'lucide-react'
import { toast } from 'sonner' import { toast } from 'sonner'
export function Members() { export function Members() {
@@ -24,7 +25,8 @@ export function Members() {
} }
async function updateMember() { async function updateMember() {
await supabase.from('members').update({ full_name: editName }).eq('id', editMember.id) const { error } = await supabase.from('members').update({ full_name: editName }).eq('id', editMember.id)
if (error) { toast.error(error.message); return }
setEditMember(null) setEditMember(null)
load() load()
toast.success('Membre mis à jour') toast.success('Membre mis à jour')
@@ -32,17 +34,39 @@ export function Members() {
async function deleteMember(id) { async function deleteMember(id) {
if (!confirm('Supprimer ce membre ?')) return if (!confirm('Supprimer ce membre ?')) return
await supabase.from('members').delete().eq('id', id) const { error } = await supabase.from('members').delete().eq('id', id)
if (error) { toast.error(error.message); return }
load() load()
toast.success('Membre supprimé') toast.success('Membre supprimé')
} }
function exportCSV() {
const header = 'Nom,Email,Rôle,Inscrit le\n'
const rows = members.map((m) =>
`"${m.full_name || ''}","${m.email}","${m.role}","${new Date(m.created_at).toLocaleDateString()}"`
).join('\n')
const blob = new Blob([header + rows], { type: 'text/csv;charset=utf-8;' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'membres.csv'
a.click()
URL.revokeObjectURL(url)
toast.success('Fichier CSV téléchargé')
}
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Membres</h1> <h1 className="text-2xl font-bold">Membres</h1>
<div className="flex gap-2">
<Button variant="outline" onClick={exportCSV}>
<Download className="h-4 w-4 mr-2" />
CSV
</Button>
<InviteUserModal /> <InviteUserModal />
</div> </div>
</div>
<Card> <Card>
<CardContent className="p-0"> <CardContent className="p-0">
+3 -3
View File
@@ -27,15 +27,15 @@ export function Profile() {
<CardHeader><CardTitle>Informations</CardTitle></CardHeader> <CardHeader><CardTitle>Informations</CardTitle></CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div> <div>
<label className="text-sm text-gray-600">Email</label> <label className="text-sm text-gray-600 dark:text-gray-400">Email</label>
<p className="font-medium">{profile?.email}</p> <p className="font-medium">{profile?.email}</p>
</div> </div>
<div> <div>
<label className="text-sm text-gray-600">Rôle</label> <label className="text-sm text-gray-600 dark:text-gray-400">Rôle</label>
<p className="font-medium capitalize">{profile?.role}</p> <p className="font-medium capitalize">{profile?.role}</p>
</div> </div>
<div> <div>
<label className="text-sm text-gray-600">Nom complet</label> <label className="text-sm text-gray-600 dark:text-gray-400">Nom complet</label>
<Input value={name} onChange={(e) => setName(e.target.value)} /> <Input value={name} onChange={(e) => setName(e.target.value)} />
</div> </div>
<Button onClick={handleSave}>Enregistrer</Button> <Button onClick={handleSave}>Enregistrer</Button>
+205 -152
View File
@@ -1,42 +1,53 @@
import { useEffect, useState, useCallback } from 'react' import { lazy, Suspense, useState } from 'react'
import { supabase } from '@/lib/supabase' import { useSearchParams } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext' import { useAuth } from '@/context/AuthContext'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { useCategories } from '@/hooks/useCategories'
import { SkillLevelBadge, SkillLevelSelect } from '@/components/SkillLevelBadge' import { useSkills } from '@/hooks/useSkills'
import { Input } from '@/components/ui/input' import { useMembers } from '@/hooks/useMembers'
import { useSkillLevels } from '@/hooks/useSkillLevels'
import { SkillMatrixFilters } from '@/components/matrix/SkillMatrixFilters'
import { SkillMatrixTable } from '@/components/matrix/SkillMatrixTable'
import { SkillMemberForm } from '@/components/matrix/SkillMemberForm'
import { ViewSwitcher } from '@/components/matrix/ViewSwitcher'
import { HeatmapView } from '@/components/matrix/HeatmapView'
import { Download } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { toast } from 'sonner' import { toast } from 'sonner'
const ScatterView = lazy(() => import('@/components/matrix/ScatterView'))
const GraphView = lazy(() => import('@/components/matrix/GraphView'))
const TreemapView = lazy(() => import('@/components/matrix/TreemapView'))
const RadarView = lazy(() => import('@/components/matrix/RadarView'))
const BarChartView = lazy(() => import('@/components/matrix/BarChartView'))
const hideMemberViews = new Set(['bars'])
const showLevelLegendViews = new Set(['table', 'heat'])
export function SkillMatrix() { export function SkillMatrix() {
const { profile } = useAuth() const { profile } = useAuth()
const isAdmin = profile?.role === 'admin' const isAdmin = profile?.role === 'admin'
const [categories, setCategories] = useState([]) const currentUserId = profile?.id
const [skills, setSkills] = useState([]) const { categories } = useCategories()
const [members, setMembers] = useState([]) const { skills } = useSkills()
const [levels, setLevels] = useState({}) const { members } = useMembers()
const { levels, updateLevel } = useSkillLevels()
const [searchParams, setSearchParams] = useSearchParams()
const viewMode = searchParams.get('view') || 'table'
const [filterCat, setFilterCat] = useState('all') const [filterCat, setFilterCat] = useState('all')
const [filterMember, setFilterMember] = useState('all') const [filterMember, setFilterMember] = useState('all')
const [filterMinLevel, setFilterMinLevel] = useState(0) const [filterMinLevel, setFilterMinLevel] = useState(0)
const [editing, setEditing] = useState(null) const [editing, setEditing] = useState(null)
useEffect(() => { load() }, []) function setViewMode(mode) {
setSearchParams(mode === 'table' ? {} : { view: mode }, { replace: true })
async function load() {
const [catRes, skillRes, memberRes, levelRes] = await Promise.all([
supabase.from('categories').select('*').order('name'),
supabase.from('skills').select('*').order('name'),
supabase.from('members').select('*').order('full_name'),
supabase.from('skill_levels').select('*'),
])
if (catRes.data) setCategories(catRes.data)
if (skillRes.data) setSkills(skillRes.data)
if (memberRes.data) setMembers(memberRes.data)
if (levelRes.data) {
const map = {}
levelRes.data.forEach((l) => {
map[`${l.member_id}-${l.skill_id}`] = l
})
setLevels(map)
} }
function onFilterChange(key, value) {
if (key === 'cat') setFilterCat(value)
if (key === 'member') setFilterMember(value)
if (key === 'minLevel') setFilterMinLevel(value)
} }
const filteredSkills = filterCat === 'all' const filteredSkills = filterCat === 'all'
@@ -47,153 +58,195 @@ export function SkillMatrix() {
? members ? members
: members.filter((m) => m.id === filterMember) : members.filter((m) => m.id === filterMember)
const filteredByLevel = filteredMembers.filter((m) => { const visibleMembers = filterMinLevel === 0
if (filterMinLevel === 0) return true ? filteredMembers
return filteredSkills.some((s) => { : filteredMembers.filter((m) =>
filteredSkills.some((s) => {
const key = `${m.id}-${s.id}` const key = `${m.id}-${s.id}`
return (levels[key]?.level || 0) >= filterMinLevel return (levels[key]?.level || 0) >= filterMinLevel
}) })
}) )
async function updateLevel(memberId, skillId, newLevel) { async function handleUpdate(memberId, skillId, newLevel) {
const key = `${memberId}-${skillId}` await updateLevel(memberId, skillId, newLevel, profile.id)
const existing = levels[key]
const oldLevel = existing?.level
if (existing) {
await supabase.from('skill_levels').update({ level: newLevel }).eq('id', existing.id)
} else {
await supabase.from('skill_levels').insert({ member_id: memberId, skill_id: skillId, level: newLevel })
}
// Historique
if (oldLevel !== newLevel) {
await supabase.from('skill_history').insert({
member_id: memberId,
skill_id: skillId,
old_level: oldLevel || null,
new_level: newLevel,
changed_by: profile.id,
})
}
load()
setEditing(null) setEditing(null)
toast.success('Niveau mis à jour') toast.success('Niveau mis à jour')
} }
function exportCSV() {
const header = ['Compétence', ...visibleMembers.map((m) => m.full_name || m.email)].join(',')
const rows = filteredSkills.map((s) => {
const levelsRow = visibleMembers.map((m) => {
const key = `${m.id}-${s.id}`
return levels[key]?.level || ''
})
return [`"${s.name}"`, ...levelsRow].join(',')
})
const blob = new Blob(['\uFEFF' + header + '\n' + rows.join('\n')], { type: 'text/csv;charset=utf-8;' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'matrice-competences.csv'
a.click()
URL.revokeObjectURL(url)
toast.success('Fichier CSV téléchargé')
}
function navigateToView(mode, filters) {
if (filters.cat !== undefined) setFilterCat(filters.cat)
if (filters.member !== undefined) setFilterMember(filters.member)
if (filters.minLevel !== undefined) setFilterMinLevel(filters.minLevel)
setViewMode(mode)
}
const commonProps = {
categories, skills, members, levels,
isAdmin, currentUserId,
filterCat, filterMember, filterMinLevel,
}
const editableProps = {
editing, onEdit: setEditing, onUpdate: handleUpdate, onCancel: () => setEditing(null),
}
function renderView() {
switch (viewMode) {
case 'heat':
return (
<HeatmapView
{...commonProps}
{...editableProps}
filteredSkills={filteredSkills}
visibleMembers={visibleMembers}
/>
)
case 'scatter':
return (
<Suspense fallback={<Fallback />}>
<ScatterView
{...commonProps}
filteredSkills={filteredSkills}
onMemberSelect={(memberId) => navigateToView('table', { member: memberId })}
/>
</Suspense>
)
case 'graph':
return (
<Suspense fallback={<Fallback />}>
<GraphView
{...commonProps}
filteredSkills={filteredSkills}
filteredMembers={filteredMembers}
/>
</Suspense>
)
case 'treemap':
return (
<Suspense fallback={<Fallback />}>
<TreemapView
{...commonProps}
filteredSkills={filteredSkills}
onCellClick={(catId, memberId) => navigateToView('table', { cat: catId, member: memberId })}
/>
</Suspense>
)
case 'radar':
return (
<Suspense fallback={<Fallback />}>
<RadarView {...commonProps} />
</Suspense>
)
case 'bars':
return (
<Suspense fallback={<Fallback />}>
<BarChartView
{...commonProps}
onBarClick={(catId, level) => navigateToView('table', { cat: catId, minLevel: level })}
/>
</Suspense>
)
default:
if (filterMember !== 'all' && visibleMembers.length === 1) {
return (
<SkillMemberForm
member={visibleMembers[0]}
categories={categories}
skills={filteredSkills}
levels={levels}
isAdmin={isAdmin}
currentUserId={currentUserId}
onSave={(memberId, changes) => {
Promise.all(changes.map((c) => updateLevel(memberId, c.skillId, c.newLevel, profile.id)))
.then(() => toast.success('Compétences mises à jour'))
.catch(() => toast.error('Erreur lors de la mise à jour'))
}}
/>
)
}
return (
<SkillMatrixTable
categories={categories}
skills={filteredSkills}
members={visibleMembers}
levels={levels}
isAdmin={isAdmin}
currentUserId={currentUserId}
editing={editing}
onEdit={setEditing}
onUpdate={handleUpdate}
onCancel={() => setEditing(null)}
/>
)
}
}
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center justify-between flex-wrap gap-4">
<h1 className="text-2xl font-bold">Matrice des compétences</h1> <h1 className="text-2xl font-bold">Matrice des compétences</h1>
<div className="flex gap-4 flex-wrap">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<label className="text-sm text-gray-600">Catégorie :</label> <ViewSwitcher active={viewMode} onChange={setViewMode} />
<select <Button variant="outline" onClick={exportCSV}>
className="border rounded px-2 py-1 text-sm" <Download className="h-4 w-4 mr-2" />
value={filterCat} CSV
onChange={(e) => setFilterCat(e.target.value)} </Button>
>
<option value="all">Toutes</option>
{categories.map((c) => (
<option key={c.id} value={c.id}>{c.name}</option>
))}
</select>
</div>
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600">Membre :</label>
<select
className="border rounded px-2 py-1 text-sm"
value={filterMember}
onChange={(e) => setFilterMember(e.target.value)}
>
<option value="all">Tous</option>
{members.map((m) => (
<option key={m.id} value={m.id}>{m.full_name || m.email}</option>
))}
</select>
</div>
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600">Niveau min. :</label>
<select
className="border rounded px-2 py-1 text-sm"
value={filterMinLevel}
onChange={(e) => setFilterMinLevel(Number(e.target.value))}
>
<option value={0}>Aucun</option>
{[1, 2, 3, 4].map((l) => <option key={l} value={l}>{l}</option>)}
</select>
</div> </div>
</div> </div>
<div className="overflow-auto"> <SkillMatrixFilters
<table className="w-full border-collapse"> categories={categories}
<thead> members={members}
<tr> filterCat={filterCat}
<th className="text-left p-2 bg-gray-100 border sticky left-0 z-10 min-w-[180px]">Membre</th> filterMember={filterMember}
{filteredSkills.map((s) => ( filterMinLevel={filterMinLevel}
<th key={s.id} className="p-2 bg-gray-100 border text-sm text-center min-w-[120px]">{s.name}</th> onFilterChange={onFilterChange}
))} hideMember={hideMemberViews.has(viewMode)}
</tr>
</thead>
<tbody>
{filteredByLevel.length === 0 && (
<tr><td colSpan={filteredSkills.length + 1} className="p-8 text-center text-gray-400">Aucun résultat</td></tr>
)}
{filteredByLevel.map((m) => (
<tr key={m.id} className="hover:bg-gray-50">
<td className="p-2 border font-medium sticky left-0 bg-white">
<span className="text-sm">{m.full_name || m.email}</span>
</td>
{filteredSkills.map((s) => {
const key = `${m.id}-${s.id}`
const level = levels[key]
const isEditing = editing === key
return (
<td key={s.id} className="p-2 border text-center">
{isEditing && isAdmin ? (
<SkillLevelSelect
value={level?.level || 1}
onChange={(v) => updateLevel(m.id, s.id, v)}
/> />
) : (
level ? (
<SkillLevelBadge
level={level.level}
onClick={() => isAdmin && setEditing(key)}
/>
) : (
<span
className="text-gray-300 text-sm cursor-pointer"
onClick={() => isAdmin && setEditing(key)}
>
</span>
)
)}
{isEditing && isAdmin && (
<button
className="ml-1 text-xs text-red-500"
onClick={() => setEditing(null)}
>
</button>
)}
</td>
)
})}
</tr>
))}
</tbody>
</table>
</div>
<div className="flex gap-4 text-sm text-gray-500"> {showLevelLegendViews.has(viewMode) && (
<div className="flex gap-4 text-sm text-gray-500 dark:text-gray-400">
<span><span className="inline-block w-3 h-3 rounded-full bg-gray-200 mr-1" /> Débutant</span> <span><span className="inline-block w-3 h-3 rounded-full bg-gray-200 mr-1" /> Débutant</span>
<span><span className="inline-block w-3 h-3 rounded-full bg-blue-200 mr-1" /> Intermédiaire</span> <span><span className="inline-block w-3 h-3 rounded-full bg-blue-200 mr-1" /> Intermédiaire</span>
<span><span className="inline-block w-3 h-3 rounded-full bg-amber-200 mr-1" /> Avancé</span> <span><span className="inline-block w-3 h-3 rounded-full bg-amber-200 mr-1" /> Avancé</span>
<span><span className="inline-block w-3 h-3 rounded-full bg-green-200 mr-1" /> Expert</span> <span><span className="inline-block w-3 h-3 rounded-full bg-green-200 mr-1" /> Expert</span>
</div> </div>
)}
{renderView()}
</div>
)
}
function Fallback() {
return (
<div className="flex items-center justify-center min-h-[400px] text-gray-400">
Chargement...
</div> </div>
) )
} }
+42 -60
View File
@@ -1,15 +1,18 @@
import { useEffect, useState } from 'react' import { useState } from 'react'
import { supabase } from '@/lib/supabase' import { supabase } from '@/lib/supabase'
import { useCategories } from '@/hooks/useCategories'
import { useSkills } from '@/hooks/useSkills'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { CategoryCard } from '@/components/skills/CategoryCard'
import { Search } from 'lucide-react'
import { toast } from 'sonner' import { toast } from 'sonner'
export function Skills() { export function Skills() {
const [categories, setCategories] = useState([]) const { categories, refetch: refetchCats } = useCategories()
const [skills, setSkills] = useState([]) const { skills, refetch: refetchSkills } = useSkills()
const [search, setSearch] = useState('')
const [newCatName, setNewCatName] = useState('') const [newCatName, setNewCatName] = useState('')
const [newCatColor, setNewCatColor] = useState('#3b82f6') const [newCatColor, setNewCatColor] = useState('#3b82f6')
const [editCat, setEditCat] = useState(null) const [editCat, setEditCat] = useState(null)
@@ -17,48 +20,41 @@ export function Skills() {
const [catDialogOpen, setCatDialogOpen] = useState(false) const [catDialogOpen, setCatDialogOpen] = useState(false)
const [skillDialogOpen, setSkillDialogOpen] = useState(false) const [skillDialogOpen, setSkillDialogOpen] = useState(false)
useEffect(() => { load() }, [])
async function load() {
const [catRes, skillRes] = await Promise.all([
supabase.from('categories').select('*').order('name'),
supabase.from('skills').select('*, category:category_id(name)').order('name'),
])
if (catRes.data) setCategories(catRes.data)
if (skillRes.data) setSkills(skillRes.data)
}
async function saveCategory() { async function saveCategory() {
if (editCat) { if (editCat) {
await supabase.from('categories').update({ name: newCatName, color: newCatColor }).eq('id', editCat) const { error } = await supabase.from('categories').update({ name: newCatName, color: newCatColor }).eq('id', editCat)
if (error) { toast.error(error.message); return }
} else { } else {
await supabase.from('categories').insert({ name: newCatName, color: newCatColor }) const { error } = await supabase.from('categories').insert({ name: newCatName, color: newCatColor })
if (error) { toast.error(error.message); return }
} }
setCatDialogOpen(false) setCatDialogOpen(false)
setEditCat(null) setEditCat(null)
setNewCatName('') setNewCatName('')
load() refetchCats()
toast.success('Catégorie enregistrée') toast.success('Catégorie enregistrée')
} }
async function deleteCategory(id) { async function deleteCategory(id) {
const { error } = await supabase.from('categories').delete().eq('id', id) const { error } = await supabase.from('categories').delete().eq('id', id)
if (error) toast.error(error.message) if (error) toast.error(error.message)
else { load(); toast.success('Catégorie supprimée') } else { refetchCats(); toast.success('Catégorie supprimée') }
} }
async function saveSkill() { async function saveSkill() {
await supabase.from('skills').insert({ name: newSkill.name, category_id: newSkill.category_id }) const { error } = await supabase.from('skills').insert({ name: newSkill.name, category_id: newSkill.category_id })
if (error) { toast.error(error.message); return }
setSkillDialogOpen(false) setSkillDialogOpen(false)
setNewSkill({ name: '', category_id: '' }) setNewSkill({ name: '', category_id: '' })
load() refetchSkills()
toast.success('Compétence ajoutée') toast.success('Compétence ajoutée')
} }
async function deleteSkill(id) { function openEditCategory(cat) {
await supabase.from('skills').delete().eq('id', id) setEditCat(cat.id)
load() setNewCatName(cat.name)
toast.success('Compétence supprimée') setNewCatColor(cat.color)
setCatDialogOpen(true)
} }
return ( return (
@@ -73,7 +69,7 @@ export function Skills() {
<div className="space-y-4"> <div className="space-y-4">
<Input placeholder="Nom" value={newSkill.name} onChange={(e) => setNewSkill({ ...newSkill, name: e.target.value })} /> <Input placeholder="Nom" value={newSkill.name} onChange={(e) => setNewSkill({ ...newSkill, name: e.target.value })} />
<select <select
className="w-full border rounded-md px-3 py-2" className="w-full border rounded-md px-3 py-2 dark:bg-gray-800 dark:border-gray-700"
value={newSkill.category_id} value={newSkill.category_id}
onChange={(e) => setNewSkill({ ...newSkill, category_id: e.target.value })} onChange={(e) => setNewSkill({ ...newSkill, category_id: e.target.value })}
> >
@@ -99,41 +95,27 @@ export function Skills() {
</div> </div>
</div> </div>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<Input
className="pl-10"
placeholder="Rechercher une compétence..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{categories.map((cat) => { {categories.map((cat) => {
const catSkills = skills.filter((s) => s.category_id === cat.id) const catSkills = skills.filter((s) => s.category_id === cat.id && (!search || s.name.toLowerCase().includes(search.toLowerCase())))
if (search && catSkills.length === 0) return null
return ( return (
<Card key={cat.id}> <CategoryCard
<CardHeader className="flex flex-row items-center justify-between py-3"> key={cat.id}
<CardTitle className="text-lg flex items-center gap-2"> category={cat}
<span className="w-3 h-3 rounded-full" style={{ backgroundColor: cat.color }} /> skills={catSkills}
{cat.name} onEdit={openEditCategory}
<Badge variant="secondary" className="ml-2">{catSkills.length}</Badge> onDelete={deleteCategory}
</CardTitle> />
<div className="flex gap-1">
<Button size="sm" variant="ghost" onClick={() => {
setEditCat(cat.id)
setNewCatName(cat.name)
setNewCatColor(cat.color)
setCatDialogOpen(true)
}}></Button>
<Button size="sm" variant="ghost" onClick={() => deleteCategory(cat.id)}>🗑</Button>
</div>
</CardHeader>
<CardContent>
{catSkills.length === 0 ? (
<p className="text-sm text-gray-400">Aucune compétence dans cette catégorie</p>
) : (
<div className="flex flex-wrap gap-2">
{catSkills.map((s) => (
<Badge key={s.id} variant="outline" className="pr-1">
{s.name}
<button className="ml-1 text-gray-400 hover:text-red-500" onClick={() => deleteSkill(s.id)}>×</button>
</Badge>
))}
</div>
)}
</CardContent>
</Card>
) )
})} })}
</div> </div>
@@ -0,0 +1,80 @@
-- ============================================================
-- Migration 002: RLS WITH CHECK + GIN indexes + level_descriptions policies
-- ============================================================
-- 1. Ajout WITH CHECK sur les policies UPDATE existantes
-- (fonctionnellement identique au USING, mais explicite)
ALTER POLICY "categories_update_admin" ON categories
RENAME TO "categories_update_admin_old";
CREATE POLICY "categories_update_admin" ON categories FOR UPDATE USING (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
) WITH CHECK (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
);
DROP POLICY "categories_update_admin_old" ON categories;
ALTER POLICY "skills_update_admin" ON skills
RENAME TO "skills_update_admin_old";
CREATE POLICY "skills_update_admin" ON skills FOR UPDATE USING (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
) WITH CHECK (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
);
DROP POLICY "skills_update_admin_old" ON skills;
ALTER POLICY "members_update_admin" ON members
RENAME TO "members_update_admin_old";
CREATE POLICY "members_update_admin" ON members FOR UPDATE USING (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
) WITH CHECK (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
);
DROP POLICY "members_update_admin_old" ON members;
ALTER POLICY "skill_levels_update_admin" ON skill_levels
RENAME TO "skill_levels_update_admin_old";
CREATE POLICY "skill_levels_update_admin" ON skill_levels FOR UPDATE USING (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
) WITH CHECK (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
);
DROP POLICY "skill_levels_update_admin_old" ON skill_levels;
ALTER POLICY "invitations_update_admin" ON invitations
RENAME TO "invitations_update_admin_old";
CREATE POLICY "invitations_update_admin" ON invitations FOR UPDATE USING (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
) WITH CHECK (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
);
DROP POLICY "invitations_update_admin_old" ON invitations;
-- 2. Filtre expiration sur invitations_read_admin
ALTER POLICY "invitations_read_admin" ON invitations
RENAME TO "invitations_read_admin_old";
CREATE POLICY "invitations_read_admin" ON invitations FOR SELECT USING (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
AND expires_at > now()
);
DROP POLICY "invitations_read_admin_old" ON invitations;
-- 3. Policies d'écriture pour level_descriptions
CREATE POLICY "level_descriptions_insert_admin" ON level_descriptions FOR INSERT WITH CHECK (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
);
CREATE POLICY "level_descriptions_update_admin" ON level_descriptions FOR UPDATE USING (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
) WITH CHECK (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
);
CREATE POLICY "level_descriptions_delete_admin" ON level_descriptions FOR DELETE USING (
EXISTS (SELECT 1 FROM members WHERE id = auth.uid() AND role = 'admin')
);
-- 4. Index GIN pour full-text search (stemming français)
CREATE INDEX idx_skills_name_gin ON skills USING gin(to_tsvector('french', name));
CREATE INDEX idx_members_full_name_gin ON members USING gin(to_tsvector('french', full_name));
+3
View File
@@ -0,0 +1,3 @@
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}