From 33743765121f21e5db4ab0056ad9f3f73d9444f7 Mon Sep 17 00:00:00 2001 From: Soham Aggarwal Date: Thu, 3 Dec 2026 16:31:52 -0500 Subject: [PATCH] Add verified member portfolio page (#150) Members can opt in to a public, read-only portfolio at /u/:username showing their name, photo, club roles, awards, project teams and a "Verified by App Dev Club" badge. Portfolios are private by default; a private, unknown or ambiguous username gets the same 404. Settings live on the member's Authentik attributes and are changed from a settings card on their own profile page. Role history: removing a member from a team now copies the role (team, subteam, title, type, season, year, end date) into a roleHistory user attribute in the same update, so past roles stay on the portfolio. The public response merges current roles with history and de-duplicates them. Awards: leads holding corp:membermgmt on a team (team owners and executives pass) can grant and revoke awards for that team's members from the team member list. Only the granting team can revoke, and nobody can grant or revoke their own. Members can hide an award but never add or edit one. Member-written section: an optional headline and GitHub and LinkedIn links, validated on the server (https only, expected site, length caps, plain text) and shown apart from the verified record. The LinkedIn on file is never used. Share previews: /u/:username serves the app with Open Graph and Twitter tags for public portfolios, HTML-escaped. Private and missing pages get identical generic tags. API: GET /api/portfolio/{username} (public, whitelisted fields only); GET and PATCH /api/portfolio/me/settings (signed-in member's own settings); GET, POST /api/portfolio/teams/{teamId}/members/{userPk}/awards and DELETE .../awards/{awardId} (corp:membermgmt). --- peopleportal/server/src/app.ts | 18 + .../src/clients/AuthentikClient/index.ts | 69 ++ .../src/clients/AuthentikClient/models.ts | 50 ++ .../server/src/controllers/OrgController.ts | 27 +- .../src/controllers/PortfolioController.ts | 347 ++++++++ peopleportal/server/src/routes.ts | 560 ++++++++++-- .../server/src/utils/portfolio-loader.ts | 84 ++ .../server/src/utils/portfolio-share.ts | 143 ++++ peopleportal/server/src/utils/portfolio.ts | 698 +++++++++++++++ .../server/test/unit/portfolio.test.js | 803 ++++++++++++++++++ peopleportal/webui/src/App.tsx | 2 + .../components/fabric/DashboardPeopleInfo.tsx | 8 + .../components/fabric/DashboardTeamInfo.tsx | 15 + .../fabric/MemberAwardsDialog.test.tsx | 117 +++ .../components/fabric/MemberAwardsDialog.tsx | 273 ++++++ .../fabric/PortfolioSettingsCard.test.tsx | 221 +++++ .../fabric/PortfolioSettingsCard.tsx | 517 +++++++++++ .../fragments/UserInformationTable.tsx | 46 +- peopleportal/webui/src/lib/portfolio.ts | 154 ++++ .../webui/src/pages/MemberPortfolio.test.tsx | 222 +++++ .../webui/src/pages/MemberPortfolio.tsx | 402 +++++++++ 21 files changed, 4670 insertions(+), 106 deletions(-) create mode 100644 peopleportal/server/src/controllers/PortfolioController.ts create mode 100644 peopleportal/server/src/utils/portfolio-loader.ts create mode 100644 peopleportal/server/src/utils/portfolio-share.ts create mode 100644 peopleportal/server/src/utils/portfolio.ts create mode 100644 peopleportal/server/test/unit/portfolio.test.js create mode 100644 peopleportal/webui/src/components/fabric/MemberAwardsDialog.test.tsx create mode 100644 peopleportal/webui/src/components/fabric/MemberAwardsDialog.tsx create mode 100644 peopleportal/webui/src/components/fabric/PortfolioSettingsCard.test.tsx create mode 100644 peopleportal/webui/src/components/fabric/PortfolioSettingsCard.tsx create mode 100644 peopleportal/webui/src/lib/portfolio.ts create mode 100644 peopleportal/webui/src/pages/MemberPortfolio.test.tsx create mode 100644 peopleportal/webui/src/pages/MemberPortfolio.tsx diff --git a/peopleportal/server/src/app.ts b/peopleportal/server/src/app.ts index f43584dd..a7de2e26 100644 --- a/peopleportal/server/src/app.ts +++ b/peopleportal/server/src/app.ts @@ -45,6 +45,8 @@ import { logger, requestLogger } from "./utils/logger"; import { agendaClient } from "./clients/AgendaClient"; import { authenticateGiteaWebhook } from "./utils/gitea-webhook-auth"; import { describeUnknownError } from "./utils/errors"; +import { portfolioPageHandler } from "./utils/portfolio-share"; +import { loadPublicPortfolio } from "./utils/portfolio-loader"; assertRequiredEnvironment(); logger.info( @@ -147,6 +149,22 @@ app.get(["/apply", "/apply/*splat"], (req, res) => { res.sendFile(path.join(__dirname, "ui", "index.html")); }); +/* Member portfolios (#150) are public, so they skip the login redirect below. + The page itself only shows what /api/portfolio returns for opted-in members, + and the served HTML carries share-preview tags only for those members. */ +app.get( + "/u/:username", + portfolioPageHandler({ + indexHtmlPath: path.join(__dirname, "ui", "index.html"), + baseUrl: process.env.PEOPLEPORTAL_BASE_URL, + load: (username) => + loadPublicPortfolio(new AuthentikClient(), username), + }), +); +app.get("/u/*splat", (req, res) => { + res.sendFile(path.join(__dirname, "ui", "index.html")); +}); + app.use(express.static(path.join(__dirname, "ui"), { index: false })); app.get("*splat", NativeExpressOIDCAuthPort, (req, res) => { diff --git a/peopleportal/server/src/clients/AuthentikClient/index.ts b/peopleportal/server/src/clients/AuthentikClient/index.ts index 7b68ca08..afd98589 100644 --- a/peopleportal/server/src/clients/AuthentikClient/index.ts +++ b/peopleportal/server/src/clients/AuthentikClient/index.ts @@ -1374,6 +1374,75 @@ export class AuthentikClient { } }; + /** + * Looks up an onboarded People Portal user by exact username. Unlike + * getUserInfoFromEmail, a missing user surfaces as USER_NOT_FOUND rather + * than a generic failure, so a caller can answer "not found" without + * mistaking an Authentik outage for an absent user. + * + * @param username Exact People Portal username + * @returns User Information + */ + public getUserInfoFromUsername = async ( + username: string, + ): Promise => { + const ONBOARDED_USER_PATH = "peopleportal.atheesh.org/onboardeduser"; + var RequestConfig: any = { + ...this.AxiosBaseConfig, + method: "get", + url: `/api/v3/core/users/`, + params: { + username, + path: ONBOARDED_USER_PATH, + type: "internal", + }, + }; + + let users: any[]; + try { + const res = await axios.request(RequestConfig); + users = res.data.results; + } catch (e) { + log.error( + AuthentikClient.TAG, + "Get User by Username Request Failed with Error: ", + e, + ); + throw new AuthentikClientError( + AuthentikClientErrorType.USERINFO_REQUEST_FAILED, + ); + } + + /* Filter for Exact Match; never trust the API filters alone */ + const exactMatches = users.filter( + (u: any) => + u.username === username && u.path === ONBOARDED_USER_PATH, + ); + + if (exactMatches.length < 1) + throw new AuthentikClientError( + AuthentikClientErrorType.USER_NOT_FOUND, + ); + + if (exactMatches.length > 1) + throw new AuthentikClientError( + AuthentikClientErrorType.MULTIPLE_RESULTS_RETURNED, + ); + + const user = exactMatches[0]; + return { + pk: user.pk, + username: user.username, + name: user.name, + email: user.email, + memberSince: user.date_joined, + active: user.is_active, + attributes: user.attributes, + is_superuser: user.is_superuser, + avatar: user.avatar, + }; + }; + public createNewUser = async ( request: CreateUserRequest, ): Promise => { diff --git a/peopleportal/server/src/clients/AuthentikClient/models.ts b/peopleportal/server/src/clients/AuthentikClient/models.ts index 137df455..930b9d89 100644 --- a/peopleportal/server/src/clients/AuthentikClient/models.ts +++ b/peopleportal/server/src/clients/AuthentikClient/models.ts @@ -75,6 +75,56 @@ export interface UserAttributeDefinition { [key: string]: string; }; avatar?: string; + /* Absent means the member never opted in, so the portfolio is private */ + portfolio?: PortfolioSettings; + /* Roles the member held in teams they have since left (#150) */ + roleHistory?: RoleHistoryEntry[]; + /* Recognition granted by team leads or admins (#150) */ + awards?: MemberAward[]; +} + +/* Member portfolio (#150). Stored on the user so it needs no new collection. */ +export interface PortfolioSettings { + isPublic: boolean; + /* Role ids left off the public page: a current membership's group pk + (the key of `roles`) or a role history entry id */ + hiddenRoleIds: string[]; + /* Award ids left off the public page */ + hiddenAwardIds: string[]; + /* Member-written, shown apart from the verified record. Plain text. */ + headline?: string; + githubUrl?: string; + linkedinUrl?: string; +} + +/** + * A role kept after the member left the team. Copied from the team at the + * moment of removal, so it survives the team being renamed or deleted. + */ +export interface RoleHistoryEntry { + id: string; + teamPk: string; + teamName: string; + subteamName?: string; + roleTitle: string; + teamType: TeamType; + seasonType: SeasonType | ServiceSeasonType; + seasonYear: number; + /* ISO date the membership ended: the end marker */ + endedAt: string; +} + +/* Granted and revoked only by leads or admins; members can only hide one */ +export interface MemberAward { + id: string; + title: string; + reason?: string; + /* YYYY-MM-DD */ + awardedOn: string; + /* Root team the award was granted through, which may revoke it */ + teamPk: string; + grantedByPk: number; + grantedAt: string; } export interface AuthentikFilterCursor { diff --git a/peopleportal/server/src/controllers/OrgController.ts b/peopleportal/server/src/controllers/OrgController.ts index 93128fbe..0cbfd01f 100644 --- a/peopleportal/server/src/controllers/OrgController.ts +++ b/peopleportal/server/src/controllers/OrgController.ts @@ -104,6 +104,7 @@ import { describeUnknownError, } from "../utils/errors"; import { ExpressRequestBindleExtension } from "../types/express"; +import { appendRoleHistory, makeRoleHistoryEntry } from "../utils/portfolio"; import { validateS3FileSignature, FILE_SIGNATURES, @@ -3177,15 +3178,39 @@ export class OrgController extends Controller { teamName = parentInfo.attributes.friendlyName ?? parentInfo.name; } - /* Remove the Role Attribute from Authentik if it exists */ + /* Remove the Role Attribute from Authentik if it exists, keeping a + copy in the member's role history so the role stays on their + portfolio (#150) after they leave. Written in the same update. */ if ( userInfo.attributes.roles && userInfo.attributes.roles[request.groupId] ) { const updatedRoles = { ...userInfo.attributes.roles }; delete updatedRoles[request.groupId]; + + const historyEntry = makeRoleHistoryEntry({ + teamPk: request.groupId, + rootTeamName: teamName, + subteamName: groupInfo.parentPk + ? groupInfo.attributes.friendlyName + : undefined, + roleTitle: userInfo.attributes.roles[request.groupId], + teamType: groupInfo.attributes.teamType, + seasonType: groupInfo.attributes.seasonType, + seasonYear: groupInfo.attributes.seasonYear, + endedAt: new Date(), + }); + await this.authentikClient.updateUserAttributes(request.userPk, { roles: updatedRoles, + ...(historyEntry + ? { + roleHistory: appendRoleHistory( + userInfo.attributes.roleHistory, + historyEntry, + ), + } + : {}), }); } diff --git a/peopleportal/server/src/controllers/PortfolioController.ts b/peopleportal/server/src/controllers/PortfolioController.ts new file mode 100644 index 00000000..2db96c42 --- /dev/null +++ b/peopleportal/server/src/controllers/PortfolioController.ts @@ -0,0 +1,347 @@ +/** + People Portal Server + Copyright (C) 2026 Atheesh Thirumalairajan + + 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 . +*/ + +import * as express from "express"; +import { + Body, + Controller, + Delete, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + SuccessResponse, + Tags, +} from "tsoa"; +import { AuthentikClient } from "../clients/AuthentikClient"; +import { + GetGroupInfoResponse, + PortfolioSettings, +} from "../clients/AuthentikClient/models"; +import { AuthorizedUser } from "../clients/OpenIdClient"; +import { CustomValidationError } from "../utils/errors"; +import { + GrantAwardRequest, + PORTFOLIO_MAX_AWARDS, + PortfolioSettingsAward, + PortfolioSettingsResponse, + PublicPortfolioResponse, + UpdatePortfolioSettingsRequest, + applyPortfolioSettingsUpdate, + collectMemberRoles, + makeAward, + normalizeAwards, + normalizePortfolioSettings, + publicAward, + sortAwards, +} from "../utils/portfolio"; +import { loadPublicPortfolio } from "../utils/portfolio-loader"; + +/** + * One response for every reason a portfolio is not shown (no such user, not + * an onboarded member, or not opted in), so the endpoint cannot be used to + * learn who is in the club. + */ +function portfolioNotFound(): CustomValidationError { + return new CustomValidationError(404, "Portfolio not found"); +} + +/* An award as a lead sees it while managing a member */ +export interface ManagedAward extends PortfolioSettingsAward { + /* Granted through this team, so this team may revoke it */ + revocable: boolean; +} + +interface BindleRequest { + bindle?: { teamInfo: GetGroupInfoResponse }; +} + +@Route("/api/portfolio") +export class PortfolioController extends Controller { + private readonly authentikClient: AuthentikClient; + + constructor() { + super(); + this.authentikClient = new AuthentikClient(); + } + + /** + * Returns a member's public, club-verified portfolio: their roles by + * season (current and past), awards, projects, and the section they wrote + * themselves. Requires no sign-in. Members are private by default and + * only appear here after opting in. + * + * @param username People Portal Username + * @returns Public Portfolio + */ + @Get("{username}") + @Tags("Member Portfolio") + @SuccessResponse(200) + async getPublicPortfolio( + @Path() username: string, + ): Promise { + const portfolio = await loadPublicPortfolio( + this.authentikClient, + username, + ); + if (!portfolio) throw portfolioNotFound(); + return portfolio; + } + + private async signedInMember(req: express.Request) { + const authorizedUser = (req as any).session + .authorizedUser as AuthorizedUser; + return this.authentikClient.getUserInfoFromEmail(authorizedUser.email); + } + + /** + * Returns the signed-in member's own portfolio settings, with every role + * and award they can show or hide. The member is taken from the session. + * + * @param req Express Request Object + * @returns Settings, roles and awards + */ + @Get("me/settings") + @Tags("Member Portfolio") + @SuccessResponse(200) + @Security("oidc") + async getPortfolioSettings( + @Request() req: express.Request, + ): Promise { + const caller = await this.signedInMember(req); + const { memberships } = + await this.authentikClient.getTeamMembershipsForUsername( + caller.username, + ); + + return { + settings: normalizePortfolioSettings(caller.attributes?.portfolio), + roles: collectMemberRoles({ + roles: caller.attributes?.roles, + memberships, + roleHistory: caller.attributes?.roleHistory, + now: new Date(), + }), + awards: sortAwards(normalizeAwards(caller.attributes?.awards)).map( + (a) => ({ id: a.id, ...publicAward(a) }), + ), + }; + } + + /** + * Updates the signed-in member's own portfolio settings: whether the + * public page is on, which roles and awards it leaves out, and the + * member-written headline and links. The member is always taken from the + * session, never from the request. + * + * @param req Express Request Object + * @param body Settings to change; omitted fields keep their value + * @returns The member's settings after the update + */ + @Patch("me/settings") + @Tags("Member Portfolio") + @SuccessResponse(200) + @Security("oidc") + async updatePortfolioSettings( + @Request() req: express.Request, + @Body() body: UpdatePortfolioSettingsRequest, + ): Promise { + const caller = await this.signedInMember(req); + const nextSettings = applyPortfolioSettingsUpdate( + normalizePortfolioSettings(caller.attributes?.portfolio), + body ?? {}, + ); + + await this.authentikClient.updateUserAttributes(Number(caller.pk), { + portfolio: nextSettings, + }); + + return nextSettings; + } + + /** + * Resolves the root team behind a bindle-checked team and confirms the + * member belongs to it (the root or any of its subteams). Awards are + * only granted to and revoked from a team's own members. + */ + private async teamMember( + req: express.Request, + teamId: string, + userPk: number, + ) { + const teamInfo = + (req as BindleRequest).bindle?.teamInfo ?? + (await this.authentikClient.getGroupInfo(teamId)); + const rootTeam = teamInfo.parentPk + ? await this.authentikClient.getGroupInfo(teamInfo.parentPk) + : teamInfo; + + const family = new Set([rootTeam.pk, ...rootTeam.subteamPkList]); + if (!Number.isInteger(userPk) || userPk <= 0) + throw new CustomValidationError(404, "Member not found"); + const member = await this.authentikClient.getUserInfo(userPk); + if (!member.groups.some((groupPk) => family.has(groupPk))) + throw new CustomValidationError( + 404, + "This person isn't a member of this team.", + ); + return { rootTeam, member }; + } + + /** + * Team owners pass the bindle check for their own team, so without this a + * member who owns a team could grant (or revoke) their own awards. + */ + private refuseSelf(req: express.Request, userPk: number) { + const caller = (req as any).session.authorizedUser as AuthorizedUser; + if (Number(caller?.pk) === userPk) + throw new CustomValidationError( + 403, + "You can't grant or revoke your own awards.", + ); + } + + private managedAwards(raw: unknown, rootTeamPk: string): ManagedAward[] { + return sortAwards(normalizeAwards(raw)).map((a) => ({ + id: a.id, + ...publicAward(a), + revocable: a.teamPk === rootTeamPk, + })); + } + + /** + * Lists a team member's awards for a lead managing them. Requires the + * `corp:membermgmt` bindle on the team (team owners and executives pass). + * + * @param teamId Team ID + * @param userPk Member PK + * @returns The member's awards + */ + @Get("teams/{teamId}/members/{userPk}/awards") + @Tags("Member Portfolio") + @SuccessResponse(200) + @Security("bindles", ["corp:membermgmt"]) + async getMemberAwards( + @Request() req: express.Request, + @Path() teamId: string, + @Path() userPk: number, + ): Promise { + const { rootTeam, member } = await this.teamMember(req, teamId, userPk); + return this.managedAwards(member.attributes?.awards, rootTeam.pk); + } + + /** + * Grants an award to a member of the team. Requires the + * `corp:membermgmt` bindle on the team. Members can hide an award on + * their page but can never add or edit one. + * + * @param teamId Team ID + * @param userPk Member PK + * @param body Title, optional reason, and date granted + * @returns The member's awards after the grant + */ + @Post("teams/{teamId}/members/{userPk}/awards") + @Tags("Member Portfolio") + @SuccessResponse(201) + @Security("bindles", ["corp:membermgmt"]) + async grantMemberAward( + @Request() req: express.Request, + @Path() teamId: string, + @Path() userPk: number, + @Body() body: GrantAwardRequest, + ): Promise { + this.refuseSelf(req, userPk); + const { rootTeam, member } = await this.teamMember(req, teamId, userPk); + const existing = normalizeAwards(member.attributes?.awards); + if (existing.length >= PORTFOLIO_MAX_AWARDS) + throw new CustomValidationError( + 400, + `A member can hold at most ${PORTFOLIO_MAX_AWARDS} awards.`, + ); + + const granter = (req as any).session.authorizedUser as AuthorizedUser; + const award = makeAward(body, { + teamPk: rootTeam.pk, + grantedByPk: Number(granter.pk) || 0, + now: new Date(), + }); + const awards = [...existing, award]; + await this.authentikClient.updateUserAttributes(userPk, { awards }); + + this.setStatus(201); + return this.managedAwards(awards, rootTeam.pk); + } + + /** + * Revokes an award granted through this team. Requires the + * `corp:membermgmt` bindle on the team. + * + * @param teamId Team ID + * @param userPk Member PK + * @param awardId Award ID + * @returns The member's awards after the revoke + */ + @Delete("teams/{teamId}/members/{userPk}/awards/{awardId}") + @Tags("Member Portfolio") + @SuccessResponse(200) + @Security("bindles", ["corp:membermgmt"]) + async revokeMemberAward( + @Request() req: express.Request, + @Path() teamId: string, + @Path() userPk: number, + @Path() awardId: string, + ): Promise { + this.refuseSelf(req, userPk); + const { rootTeam, member } = await this.teamMember(req, teamId, userPk); + const existing = normalizeAwards(member.attributes?.awards); + const award = existing.find((a) => a.id === awardId); + if (!award) throw new CustomValidationError(404, "Award not found"); + if (award.teamPk !== rootTeam.pk) + throw new CustomValidationError( + 403, + "Only the team that granted this award can revoke it.", + ); + + const awards = existing.filter((a) => a.id !== awardId); + + /* Drop the id from the member's hidden list too, so it can't go + stale. Only touched when it was there: a member who never set up a + portfolio keeps no portfolio attribute. */ + const settings = normalizePortfolioSettings( + member.attributes?.portfolio, + ); + await this.authentikClient.updateUserAttributes(userPk, { + awards, + ...(settings.hiddenAwardIds.includes(awardId) + ? { + portfolio: { + ...settings, + hiddenAwardIds: settings.hiddenAwardIds.filter( + (id) => id !== awardId, + ), + }, + } + : {}), + }); + + return this.managedAwards(awards, rootTeam.pk); + } +} diff --git a/peopleportal/server/src/routes.ts b/peopleportal/server/src/routes.ts index 4a19fa81..b4fea929 100644 --- a/peopleportal/server/src/routes.ts +++ b/peopleportal/server/src/routes.ts @@ -4,11 +4,13 @@ import type { TsoaRoute } from '@tsoa/runtime'; import { fetchMiddlewares, ExpressTemplateService } from '@tsoa/runtime'; // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa -import { PlatformController } from './controllers/PlatformController'; +import { OrgController } from './controllers/OrgController'; // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa import { BindleController } from './controllers/BindleController'; // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa -import { OrgController } from './controllers/OrgController'; +import { PortfolioController } from './controllers/PortfolioController'; +// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa +import { PlatformController } from './controllers/PlatformController'; // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa import { MeetingsController } from './controllers/MeetingsController'; // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa @@ -29,41 +31,74 @@ const expressAuthenticationRecasted = expressAuthentication as (req: ExRequest, // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa const models: TsoaRoute.Models = { - "PlatformLicenseResponse": { + "PaginationDefinition": { "dataType": "refObject", "properties": { - "licenseText": {"dataType":"string","required":true}, - "dependencies": {"dataType":"array","array":{"dataType":"nestedObjectLiteral","nestedProperties":{"version":{"dataType":"string","required":true},"name":{"dataType":"string","required":true}}},"required":true}, + "next": {"dataType":"double","required":true}, + "previous": {"dataType":"double","required":true}, + "count": {"dataType":"double","required":true}, + "current": {"dataType":"double","required":true}, + "total_pages": {"dataType":"double","required":true}, + "start_index": {"dataType":"double","required":true}, + "end_index": {"dataType":"double","required":true}, }, "additionalProperties": false, }, // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - "BindlePermission": { + "PortfolioSettings": { "dataType": "refObject", "properties": { - "friendlyName": {"dataType":"string","required":true}, - "description": {"dataType":"string","required":true}, + "isPublic": {"dataType":"boolean","required":true}, + "hiddenRoleIds": {"dataType":"array","array":{"dataType":"string"},"required":true}, + "hiddenAwardIds": {"dataType":"array","array":{"dataType":"string"},"required":true}, + "headline": {"dataType":"string"}, + "githubUrl": {"dataType":"string"}, + "linkedinUrl": {"dataType":"string"}, }, "additionalProperties": false, }, // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - "BindlePermissionMap": { + "TeamType": { + "dataType": "refEnum", + "enums": ["PROJECT","CORPORATE","BOOTCAMP","SERVICE"], + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "SeasonType": { + "dataType": "refEnum", + "enums": ["FALL","SPRING"], + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "ServiceSeasonType": { + "dataType": "refEnum", + "enums": ["ROLLING"], + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "RoleHistoryEntry": { "dataType": "refObject", "properties": { + "id": {"dataType":"string","required":true}, + "teamPk": {"dataType":"string","required":true}, + "teamName": {"dataType":"string","required":true}, + "subteamName": {"dataType":"string"}, + "roleTitle": {"dataType":"string","required":true}, + "teamType": {"ref":"TeamType","required":true}, + "seasonType": {"dataType":"union","subSchemas":[{"ref":"SeasonType"},{"ref":"ServiceSeasonType"}],"required":true}, + "seasonYear": {"dataType":"double","required":true}, + "endedAt": {"dataType":"string","required":true}, }, - "additionalProperties": {"ref":"BindlePermission"}, + "additionalProperties": false, }, // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - "PaginationDefinition": { + "MemberAward": { "dataType": "refObject", "properties": { - "next": {"dataType":"double","required":true}, - "previous": {"dataType":"double","required":true}, - "count": {"dataType":"double","required":true}, - "current": {"dataType":"double","required":true}, - "total_pages": {"dataType":"double","required":true}, - "start_index": {"dataType":"double","required":true}, - "end_index": {"dataType":"double","required":true}, + "id": {"dataType":"string","required":true}, + "title": {"dataType":"string","required":true}, + "reason": {"dataType":"string"}, + "awardedOn": {"dataType":"string","required":true}, + "teamPk": {"dataType":"string","required":true}, + "grantedByPk": {"dataType":"double","required":true}, + "grantedAt": {"dataType":"string","required":true}, }, "additionalProperties": false, }, @@ -79,6 +114,9 @@ const models: TsoaRoute.Models = { "linkedinUrl": {"dataType":"string"}, "roles": {"dataType":"nestedObjectLiteral","nestedProperties":{},"additionalProperties":{"dataType":"string"},"required":true}, "avatar": {"dataType":"string"}, + "portfolio": {"ref":"PortfolioSettings"}, + "roleHistory": {"dataType":"array","array":{"dataType":"refObject","ref":"RoleHistoryEntry"}}, + "awards": {"dataType":"array","array":{"dataType":"refObject","ref":"MemberAward"}}, }, "additionalProperties": false, }, @@ -133,21 +171,6 @@ const models: TsoaRoute.Models = { "additionalProperties": false, }, // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - "TeamType": { - "dataType": "refEnum", - "enums": ["PROJECT","CORPORATE","BOOTCAMP","SERVICE"], - }, - // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - "SeasonType": { - "dataType": "refEnum", - "enums": ["FALL","SPRING"], - }, - // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - "ServiceSeasonType": { - "dataType": "refEnum", - "enums": ["ROLLING"], - }, - // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa "EnabledRootSettings": { "dataType": "refObject", "properties": { @@ -516,6 +539,165 @@ const models: TsoaRoute.Models = { "additionalProperties": false, }, // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "BindlePermission": { + "dataType": "refObject", + "properties": { + "friendlyName": {"dataType":"string","required":true}, + "description": {"dataType":"string","required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "BindlePermissionMap": { + "dataType": "refObject", + "properties": { + }, + "additionalProperties": {"ref":"BindlePermission"}, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PortfolioRole": { + "dataType": "refObject", + "properties": { + "teamName": {"dataType":"string","required":true}, + "subteamName": {"dataType":"string"}, + "roleTitle": {"dataType":"string","required":true}, + "teamType": {"ref":"TeamType","required":true}, + "seasonType": {"dataType":"union","subSchemas":[{"ref":"SeasonType"},{"ref":"ServiceSeasonType"}],"required":true}, + "seasonYear": {"dataType":"double","required":true}, + "current": {"dataType":"boolean","required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PortfolioAward": { + "dataType": "refObject", + "properties": { + "title": {"dataType":"string","required":true}, + "reason": {"dataType":"string"}, + "awardedOn": {"dataType":"string","required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PortfolioProject": { + "dataType": "refObject", + "properties": { + "name": {"dataType":"string","required":true}, + "firstSeasonType": {"dataType":"union","subSchemas":[{"ref":"SeasonType"},{"ref":"ServiceSeasonType"}],"required":true}, + "firstSeasonYear": {"dataType":"double","required":true}, + "lastSeasonType": {"dataType":"union","subSchemas":[{"ref":"SeasonType"},{"ref":"ServiceSeasonType"}],"required":true}, + "lastSeasonYear": {"dataType":"double","required":true}, + "roles": {"dataType":"array","array":{"dataType":"string"},"required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PortfolioAbout": { + "dataType": "refObject", + "properties": { + "headline": {"dataType":"string"}, + "githubUrl": {"dataType":"string"}, + "linkedinUrl": {"dataType":"string"}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PublicPortfolioResponse": { + "dataType": "refObject", + "properties": { + "username": {"dataType":"string","required":true}, + "name": {"dataType":"string","required":true}, + "avatar": {"dataType":"string","required":true}, + "isAlumni": {"dataType":"boolean","required":true}, + "syncedAt": {"dataType":"string","required":true}, + "roles": {"dataType":"array","array":{"dataType":"refObject","ref":"PortfolioRole"},"required":true}, + "awards": {"dataType":"array","array":{"dataType":"refObject","ref":"PortfolioAward"},"required":true}, + "projects": {"dataType":"array","array":{"dataType":"refObject","ref":"PortfolioProject"},"required":true}, + "about": {"ref":"PortfolioAbout"}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PortfolioSettingsRole": { + "dataType": "refObject", + "properties": { + "teamName": {"dataType":"string","required":true}, + "subteamName": {"dataType":"string"}, + "roleTitle": {"dataType":"string","required":true}, + "teamType": {"ref":"TeamType","required":true}, + "seasonType": {"dataType":"union","subSchemas":[{"ref":"SeasonType"},{"ref":"ServiceSeasonType"}],"required":true}, + "seasonYear": {"dataType":"double","required":true}, + "current": {"dataType":"boolean","required":true}, + "id": {"dataType":"string","required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PortfolioSettingsAward": { + "dataType": "refObject", + "properties": { + "title": {"dataType":"string","required":true}, + "reason": {"dataType":"string"}, + "awardedOn": {"dataType":"string","required":true}, + "id": {"dataType":"string","required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PortfolioSettingsResponse": { + "dataType": "refObject", + "properties": { + "settings": {"ref":"PortfolioSettings","required":true}, + "roles": {"dataType":"array","array":{"dataType":"refObject","ref":"PortfolioSettingsRole"},"required":true}, + "awards": {"dataType":"array","array":{"dataType":"refObject","ref":"PortfolioSettingsAward"},"required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "UpdatePortfolioSettingsRequest": { + "dataType": "refObject", + "properties": { + "isPublic": {"dataType":"boolean"}, + "hiddenRoleIds": {"dataType":"array","array":{"dataType":"string"}}, + "hiddenAwardIds": {"dataType":"array","array":{"dataType":"string"}}, + "headline": {"dataType":"string"}, + "githubUrl": {"dataType":"string"}, + "linkedinUrl": {"dataType":"string"}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "ManagedAward": { + "dataType": "refObject", + "properties": { + "title": {"dataType":"string","required":true}, + "reason": {"dataType":"string"}, + "awardedOn": {"dataType":"string","required":true}, + "id": {"dataType":"string","required":true}, + "revocable": {"dataType":"boolean","required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "GrantAwardRequest": { + "dataType": "refObject", + "properties": { + "title": {"dataType":"string","required":true}, + "reason": {"dataType":"string"}, + "awardedOn": {"dataType":"string","required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "PlatformLicenseResponse": { + "dataType": "refObject", + "properties": { + "licenseText": {"dataType":"string","required":true}, + "dependencies": {"dataType":"array","array":{"dataType":"nestedObjectLiteral","nestedProperties":{"version":{"dataType":"string","required":true},"name":{"dataType":"string","required":true}}},"required":true}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa "APITeamMeetingResponse": { "dataType": "refObject", "properties": { @@ -1171,65 +1353,6 @@ export function RegisterRoutes(app: Router) { - const argsPlatformController_getPlatformLicense: Record = { - }; - app.get('/api/platform/license', - authenticateMiddleware([{"oidc":[]}]), - ...(fetchMiddlewares(PlatformController)), - ...(fetchMiddlewares(PlatformController.prototype.getPlatformLicense)), - - async function PlatformController_getPlatformLicense(request: ExRequest, response: ExResponse, next: any) { - - // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - - let validatedArgs: any[] = []; - try { - validatedArgs = templateService.getValidatedArgs({ args: argsPlatformController_getPlatformLicense, request, response }); - - const controller = new PlatformController(); - - await templateService.apiHandler({ - methodName: 'getPlatformLicense', - controller, - response, - next, - validatedArgs, - successStatus: 200, - }); - } catch (err) { - return next(err); - } - }); - // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - const argsBindleController_getDefinitions: Record = { - }; - app.get('/api/bindles/definitions', - ...(fetchMiddlewares(BindleController)), - ...(fetchMiddlewares(BindleController.prototype.getDefinitions)), - - async function BindleController_getDefinitions(request: ExRequest, response: ExResponse, next: any) { - - // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa - - let validatedArgs: any[] = []; - try { - validatedArgs = templateService.getValidatedArgs({ args: argsBindleController_getDefinitions, request, response }); - - const controller = new BindleController(); - - await templateService.apiHandler({ - methodName: 'getDefinitions', - controller, - response, - next, - validatedArgs, - successStatus: 200, - }); - } catch (err) { - return next(err); - } - }); - // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa const argsOrgController_getPeople: Record = { options: {"in":"queries","name":"options","required":true,"ref":"GetUserListOptions"}, }; @@ -2470,6 +2593,259 @@ export function RegisterRoutes(app: Router) { } }); // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsBindleController_getDefinitions: Record = { + }; + app.get('/api/bindles/definitions', + ...(fetchMiddlewares(BindleController)), + ...(fetchMiddlewares(BindleController.prototype.getDefinitions)), + + async function BindleController_getDefinitions(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsBindleController_getDefinitions, request, response }); + + const controller = new BindleController(); + + await templateService.apiHandler({ + methodName: 'getDefinitions', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsPortfolioController_getPublicPortfolio: Record = { + username: {"in":"path","name":"username","required":true,"dataType":"string"}, + }; + app.get('/api/portfolio/:username', + ...(fetchMiddlewares(PortfolioController)), + ...(fetchMiddlewares(PortfolioController.prototype.getPublicPortfolio)), + + async function PortfolioController_getPublicPortfolio(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsPortfolioController_getPublicPortfolio, request, response }); + + const controller = new PortfolioController(); + + await templateService.apiHandler({ + methodName: 'getPublicPortfolio', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsPortfolioController_getPortfolioSettings: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + }; + app.get('/api/portfolio/me/settings', + authenticateMiddleware([{"oidc":[]}]), + ...(fetchMiddlewares(PortfolioController)), + ...(fetchMiddlewares(PortfolioController.prototype.getPortfolioSettings)), + + async function PortfolioController_getPortfolioSettings(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsPortfolioController_getPortfolioSettings, request, response }); + + const controller = new PortfolioController(); + + await templateService.apiHandler({ + methodName: 'getPortfolioSettings', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsPortfolioController_updatePortfolioSettings: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + body: {"in":"body","name":"body","required":true,"ref":"UpdatePortfolioSettingsRequest"}, + }; + app.patch('/api/portfolio/me/settings', + authenticateMiddleware([{"oidc":[]}]), + ...(fetchMiddlewares(PortfolioController)), + ...(fetchMiddlewares(PortfolioController.prototype.updatePortfolioSettings)), + + async function PortfolioController_updatePortfolioSettings(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsPortfolioController_updatePortfolioSettings, request, response }); + + const controller = new PortfolioController(); + + await templateService.apiHandler({ + methodName: 'updatePortfolioSettings', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsPortfolioController_getMemberAwards: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, + userPk: {"in":"path","name":"userPk","required":true,"dataType":"double"}, + }; + app.get('/api/portfolio/teams/:teamId/members/:userPk/awards', + authenticateMiddleware([{"bindles":["corp:membermgmt"]}]), + ...(fetchMiddlewares(PortfolioController)), + ...(fetchMiddlewares(PortfolioController.prototype.getMemberAwards)), + + async function PortfolioController_getMemberAwards(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsPortfolioController_getMemberAwards, request, response }); + + const controller = new PortfolioController(); + + await templateService.apiHandler({ + methodName: 'getMemberAwards', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsPortfolioController_grantMemberAward: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, + userPk: {"in":"path","name":"userPk","required":true,"dataType":"double"}, + body: {"in":"body","name":"body","required":true,"ref":"GrantAwardRequest"}, + }; + app.post('/api/portfolio/teams/:teamId/members/:userPk/awards', + authenticateMiddleware([{"bindles":["corp:membermgmt"]}]), + ...(fetchMiddlewares(PortfolioController)), + ...(fetchMiddlewares(PortfolioController.prototype.grantMemberAward)), + + async function PortfolioController_grantMemberAward(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsPortfolioController_grantMemberAward, request, response }); + + const controller = new PortfolioController(); + + await templateService.apiHandler({ + methodName: 'grantMemberAward', + controller, + response, + next, + validatedArgs, + successStatus: 201, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsPortfolioController_revokeMemberAward: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, + userPk: {"in":"path","name":"userPk","required":true,"dataType":"double"}, + awardId: {"in":"path","name":"awardId","required":true,"dataType":"string"}, + }; + app.delete('/api/portfolio/teams/:teamId/members/:userPk/awards/:awardId', + authenticateMiddleware([{"bindles":["corp:membermgmt"]}]), + ...(fetchMiddlewares(PortfolioController)), + ...(fetchMiddlewares(PortfolioController.prototype.revokeMemberAward)), + + async function PortfolioController_revokeMemberAward(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsPortfolioController_revokeMemberAward, request, response }); + + const controller = new PortfolioController(); + + await templateService.apiHandler({ + methodName: 'revokeMemberAward', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsPlatformController_getPlatformLicense: Record = { + }; + app.get('/api/platform/license', + authenticateMiddleware([{"oidc":[]}]), + ...(fetchMiddlewares(PlatformController)), + ...(fetchMiddlewares(PlatformController.prototype.getPlatformLicense)), + + async function PlatformController_getPlatformLicense(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsPlatformController_getPlatformLicense, request, response }); + + const controller = new PlatformController(); + + await templateService.apiHandler({ + methodName: 'getPlatformLicense', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa const argsMeetingsController_getTeamMeetings: Record = { req: {"in":"request","name":"req","required":true,"dataType":"object"}, teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, diff --git a/peopleportal/server/src/utils/portfolio-loader.ts b/peopleportal/server/src/utils/portfolio-loader.ts new file mode 100644 index 00000000..9e9a3617 --- /dev/null +++ b/peopleportal/server/src/utils/portfolio-loader.ts @@ -0,0 +1,84 @@ +/** + People Portal Server + Copyright (C) 2026 Atheesh Thirumalairajan + + 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 . +*/ + +import { AuthentikClient } from "../clients/AuthentikClient"; +import { + AuthentikClientError, + AuthentikClientErrorType, +} from "../clients/AuthentikClient/models"; +import { signAvatarUrl } from "./avatars"; +import { + PublicPortfolioResponse, + buildPublicPortfolio, + normalizePortfolioSettings, +} from "./portfolio"; + +/* Authentik caps usernames at 150 characters */ +const MAX_USERNAME_LENGTH = 150; + +export type PortfolioDirectory = Pick< + AuthentikClient, + "getUserInfoFromUsername" | "getTeamMembershipsForUsername" +>; + +/** + * Loads a member's public portfolio, or null for every reason it is not + * shown: no such user, not an onboarded member, an ambiguous username, or + * not opted in. Callers must treat all of those the same, so the page + * cannot be used to learn who is in the club. A directory outage is thrown, + * not reported as null. + */ +export async function loadPublicPortfolio( + directory: PortfolioDirectory, + username: string, + now: Date = new Date(), +): Promise { + if (!username || username.length > MAX_USERNAME_LENGTH) return null; + + let user; + try { + user = await directory.getUserInfoFromUsername(username); + } catch (e) { + if ( + e instanceof AuthentikClientError && + (e.code === AuthentikClientErrorType.USER_NOT_FOUND || + e.code === AuthentikClientErrorType.MULTIPLE_RESULTS_RETURNED) + ) + return null; + throw e; + } + + const settings = normalizePortfolioSettings(user.attributes?.portfolio); + if (!settings.isPublic) return null; + + const { memberships } = await directory.getTeamMembershipsForUsername( + user.username, + ); + + return buildPublicPortfolio({ + username: user.username, + name: user.name, + avatar: await signAvatarUrl(user.pk, user.attributes?.avatar), + roles: user.attributes?.roles, + memberships, + roleHistory: user.attributes?.roleHistory, + awards: user.attributes?.awards, + settings, + now, + }); +} diff --git a/peopleportal/server/src/utils/portfolio-share.ts b/peopleportal/server/src/utils/portfolio-share.ts new file mode 100644 index 00000000..3846a223 --- /dev/null +++ b/peopleportal/server/src/utils/portfolio-share.ts @@ -0,0 +1,143 @@ +/** + People Portal Server + Copyright (C) 2026 Atheesh Thirumalairajan + + 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 . +*/ + +import { promises as fs } from "node:fs"; +import type { Request, Response } from "express"; +import { PublicPortfolioResponse } from "./portfolio"; +import { logger } from "./logger"; + +const log = logger.child({ component: "portfolio-share" }); + +const GENERIC_TITLE = "App Dev Club People Portal"; +const GENERIC_DESCRIPTION = + "Verified member portfolios from App Dev Club's People Portal."; +const SHARE_MARKER = "data-portfolio-share"; + +/** Escapes text for use in HTML content and double-quoted attributes. */ +export function escapeHtml(value: string): string { + return value + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +/** "Tech Lead at People Portal · Developer at Terp Planner" */ +export function shareDescription(portfolio: PublicPortfolioResponse): string { + const current = portfolio.roles.filter((r) => r.current); + if (current.length === 0) + return portfolio.roles.length > 0 + ? `App Dev Club alumni. Verified record of ${portfolio.roles.length} club role${portfolio.roles.length === 1 ? "" : "s"}.` + : "Verified App Dev Club member record."; + return current + .slice(0, 3) + .map( + (r) => + `${r.roleTitle} at ${r.teamName}${r.subteamName ? ` (${r.subteamName})` : ""}`, + ) + .join(" · "); +} + +/** + * The share-preview tags for a portfolio page. A missing or private page + * gets generic tags with no member data, identical for both. + */ +export function buildShareMeta( + portfolio: PublicPortfolioResponse | null, + pageUrl: string | null, +): { title: string; tags: string } { + const title = portfolio + ? `${portfolio.name} · Verified by App Dev Club` + : GENERIC_TITLE; + const description = portfolio + ? shareDescription(portfolio) + : GENERIC_DESCRIPTION; + + const meta: [string, string, string][] = [ + ["name", "description", description], + ["property", "og:type", portfolio ? "profile" : "website"], + ["property", "og:site_name", "App Dev Club"], + ["property", "og:title", title], + ["property", "og:description", description], + ["name", "twitter:card", "summary"], + ["name", "twitter:title", title], + ["name", "twitter:description", description], + ]; + if (portfolio && pageUrl) meta.push(["property", "og:url", pageUrl]); + + const tags = meta + .map( + ([attr, key, content]) => + ``, + ) + .join("\n "); + return { title, tags }; +} + +/** Puts the tags and title into the app's index.html head. */ +export function injectShareMeta( + html: string, + share: { title: string; tags: string }, +): string { + const titleTag = `${escapeHtml(share.title)}`; + const withTitle = /[\s\S]*?<\/title>/i.test(html) + ? html.replace(/<title>[\s\S]*?<\/title>/i, () => titleTag) + : html.replace(/<\/head>/i, () => ` ${titleTag}\n</head>`); + return withTitle.replace(/<\/head>/i, () => ` ${share.tags}\n </head>`); +} + +/** + * Serves the app shell for /u/:username with share-preview tags. The page + * loads without sign-in; the status and markup for a private or missing + * member are identical, matching the API's single 404. + */ +export function portfolioPageHandler(options: { + indexHtmlPath: string; + baseUrl: string | undefined; + load: (username: string) => Promise<PublicPortfolioResponse | null>; +}) { + return async (req: Request, res: Response) => { + const raw = (req.params as { username?: string }).username ?? ""; + let html: string; + try { + html = await fs.readFile(options.indexHtmlPath, "utf8"); + } catch (e) { + log.error({ err: e }, "Portfolio page shell missing"); + res.status(500).send("Not available"); + return; + } + + let portfolio: PublicPortfolioResponse | null = null; + try { + portfolio = await options.load(raw); + } catch (e) { + /* An outage still serves the page; the app shows its own error */ + log.warn({ err: e }, "Portfolio share lookup failed"); + } + + const pageUrl = + portfolio && options.baseUrl + ? `${options.baseUrl.replace(/\/$/, "")}/u/${encodeURIComponent(portfolio.username)}` + : null; + res.set("Cache-Control", "no-store"); + res.type("html").send( + injectShareMeta(html, buildShareMeta(portfolio, pageUrl)), + ); + }; +} diff --git a/peopleportal/server/src/utils/portfolio.ts b/peopleportal/server/src/utils/portfolio.ts new file mode 100644 index 00000000..7a829979 --- /dev/null +++ b/peopleportal/server/src/utils/portfolio.ts @@ -0,0 +1,698 @@ +/** + People Portal Server + Copyright (C) 2026 Atheesh Thirumalairajan + + 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/>. +*/ + +import { randomUUID } from "node:crypto"; +import { + MemberAward, + PortfolioSettings, + RoleHistoryEntry, + SeasonType, + ServiceSeasonType, + TeamMembershipBrief, + TeamType, +} from "../clients/AuthentikClient/models"; +import { CustomValidationError } from "./errors"; +import { normalizeLinkedInProfileUrl } from "./linkedin"; + +/* Generous for a member's whole history, small enough to bound the payload */ +export const PORTFOLIO_MAX_HIDDEN_ITEMS = 200; +export const PORTFOLIO_MAX_HISTORY = 100; +export const PORTFOLIO_MAX_AWARDS = 50; +export const PORTFOLIO_HEADLINE_MAX = 160; +export const PORTFOLIO_URL_MAX = 200; +export const AWARD_TITLE_MAX = 80; +export const AWARD_REASON_MAX = 200; + +/* Group pks and generated ids (UUIDs) both fit */ +const ITEM_ID_PATTERN = /^[A-Za-z0-9-]{1,64}$/; +const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +/* Control characters (plain text here is a single line) and angle brackets, + so stored text can never be read as markup by any renderer */ +const NOT_PLAIN_TEXT = /[\u0000-\u001f\u007f<>]/; +const GITHUB_HOSTS = new Set(["github.com", "www.github.com"]); + +/** + * One role on a member's public portfolio. Built from a whitelist: nothing + * here may identify or contact the member beyond what the page is for. + */ +export interface PortfolioRole { + /* Root team display name, e.g. "People Portal" */ + teamName: string; + /* Present when the role is held in a subteam, e.g. "Engineering" */ + subteamName?: string; + roleTitle: string; + teamType: TeamType; + seasonType: SeasonType | ServiceSeasonType; + seasonYear: number; + /* Held now: a current membership in the current or a later season */ + current: boolean; +} + +export interface PortfolioProject { + name: string; + firstSeasonType: SeasonType | ServiceSeasonType; + firstSeasonYear: number; + lastSeasonType: SeasonType | ServiceSeasonType; + lastSeasonYear: number; + /* Role titles held on the project, in the order first held */ + roles: string[]; +} + +export interface PortfolioAward { + title: string; + reason?: string; + /* YYYY-MM-DD */ + awardedOn: string; +} + +/* Member-written and not verified by the club */ +export interface PortfolioAbout { + headline?: string; + githubUrl?: string; + linkedinUrl?: string; +} + +export interface PublicPortfolioResponse { + username: string; + name: string; + avatar: string; + /* No current team membership at all */ + isAlumni: boolean; + /* When the server built this response, ISO 8601 */ + syncedAt: string; + roles: PortfolioRole[]; + awards: PortfolioAward[]; + projects: PortfolioProject[]; + /* Absent when the member wrote nothing */ + about?: PortfolioAbout; +} + +export interface UpdatePortfolioSettingsRequest { + isPublic?: boolean; + hiddenRoleIds?: string[]; + hiddenAwardIds?: string[]; + /* Empty string clears */ + headline?: string; + githubUrl?: string; + linkedinUrl?: string; +} + +/* A role or award as the member sees it in their own settings */ +export interface PortfolioSettingsRole extends PortfolioRole { + id: string; +} + +export interface PortfolioSettingsAward extends PortfolioAward { + id: string; +} + +export interface PortfolioSettingsResponse { + settings: PortfolioSettings; + roles: PortfolioSettingsRole[]; + awards: PortfolioSettingsAward[]; +} + +export interface GrantAwardRequest { + title: string; + reason?: string; + /* YYYY-MM-DD */ + awardedOn: string; +} + +function normalizeIdList(raw: unknown): string[] { + if (!Array.isArray(raw)) return []; + const ids = raw.filter( + (id): id is string => + typeof id === "string" && ITEM_ID_PATTERN.test(id), + ); + return [...new Set(ids)].slice(0, PORTFOLIO_MAX_HIDDEN_ITEMS); +} + +/* Stored text is re-checked on read, so a value written around the API + (straight into Authentik) still cannot reach the page unchecked */ +function storedText(raw: unknown, max: number): string | undefined { + if (typeof raw !== "string") return undefined; + const value = raw.trim(); + if (!value || value.length > max || NOT_PLAIN_TEXT.test(value)) + return undefined; + return value; +} + +function storedHttpsUrl( + raw: unknown, + kind: "github" | "linkedin", +): string | undefined { + if (typeof raw !== "string" || !raw) return undefined; + try { + return normalizeProfileUrl(raw, kind); + } catch { + return undefined; + } +} + +/** + * Reads stored settings defensively. Anything missing or malformed means + * private, because the safe failure for an opt-in page is "not shown". + */ +export function normalizePortfolioSettings(raw: unknown): PortfolioSettings { + const value = (raw ?? {}) as Partial<PortfolioSettings>; + const settings: PortfolioSettings = { + isPublic: value.isPublic === true, + hiddenRoleIds: normalizeIdList(value.hiddenRoleIds), + hiddenAwardIds: normalizeIdList(value.hiddenAwardIds), + }; + + const headline = storedText(value.headline, PORTFOLIO_HEADLINE_MAX); + if (headline) settings.headline = headline; + const githubUrl = storedHttpsUrl(value.githubUrl, "github"); + if (githubUrl) settings.githubUrl = githubUrl; + const linkedinUrl = storedHttpsUrl(value.linkedinUrl, "linkedin"); + if (linkedinUrl) settings.linkedinUrl = linkedinUrl; + return settings; +} + +/** + * Validates one line of member- or lead-written plain text. Returns the + * trimmed value, or "" for blank input when blank is allowed. + */ +export function validatePlainText( + raw: unknown, + max: number, + label: string, + { allowEmpty = true } = {}, +): string { + if (typeof raw !== "string") + throw new CustomValidationError(400, `Invalid ${label}.`); + const value = raw.trim(); + if (!value && !allowEmpty) + throw new CustomValidationError(400, `${label} is required.`); + if (value.length > max) + throw new CustomValidationError( + 400, + `${label} must be ${max} characters or fewer.`, + ); + if (NOT_PLAIN_TEXT.test(value)) + throw new CustomValidationError( + 400, + `${label} must be plain text on one line, without < or >.`, + ); + return value; +} + +/** + * Validates a member-supplied profile link: https only, the expected site, + * no credentials or port, bounded length. Returns the normalized URL or "" + * for blank input. LinkedIn links are reduced to the /in/<handle> form. + */ +export function normalizeProfileUrl( + raw: unknown, + kind: "github" | "linkedin", +): string { + const label = kind === "github" ? "GitHub link" : "LinkedIn link"; + if (typeof raw !== "string") + throw new CustomValidationError(400, `Invalid ${label}.`); + const value = raw.trim(); + if (!value) return ""; + if (value.length > PORTFOLIO_URL_MAX) + throw new CustomValidationError(400, `${label} is too long.`); + if (!/^https:\/\//i.test(value)) + throw new CustomValidationError( + 400, + `${label} must start with https://`, + ); + + if (kind === "linkedin") { + const normalized = normalizeLinkedInProfileUrl(value); + if (!normalized) + throw new CustomValidationError( + 400, + "LinkedIn link must be a linkedin.com/in/ profile.", + ); + return normalized; + } + + let url: URL; + try { + url = new URL(value); + } catch { + throw new CustomValidationError(400, `Invalid ${label}.`); + } + const handle = url.pathname.match(/^\/([A-Za-z0-9-]{1,39})\/?$/); + if ( + url.protocol !== "https:" || + !GITHUB_HOSTS.has(url.hostname.toLowerCase()) || + url.username || + url.password || + url.port || + url.search || + url.hash || + !handle + ) + throw new CustomValidationError( + 400, + "GitHub link must be a github.com/<username> profile.", + ); + return `https://github.com/${handle[1]}`; +} + +function validateIdListUpdate(raw: unknown): string[] { + if (!Array.isArray(raw)) + throw new CustomValidationError(400, "Invalid hidden items."); + if (raw.length > PORTFOLIO_MAX_HIDDEN_ITEMS) + throw new CustomValidationError(400, "Too many hidden items."); + for (const id of raw) { + if (typeof id !== "string" || !ITEM_ID_PATTERN.test(id)) + throw new CustomValidationError(400, "Invalid hidden item."); + } + return [...new Set(raw as string[])]; +} + +/** + * Applies a settings update on top of the current settings, validating it. + * Fields left out of the update keep their current value; an empty string + * clears a member-written field. + */ +export function applyPortfolioSettingsUpdate( + current: PortfolioSettings, + update: UpdatePortfolioSettingsRequest, +): PortfolioSettings { + const next: PortfolioSettings = { ...current }; + + if (update.isPublic !== undefined) { + if (typeof update.isPublic !== "boolean") + throw new CustomValidationError(400, "Invalid visibility value."); + next.isPublic = update.isPublic; + } + if (update.hiddenRoleIds !== undefined) + next.hiddenRoleIds = validateIdListUpdate(update.hiddenRoleIds); + if (update.hiddenAwardIds !== undefined) + next.hiddenAwardIds = validateIdListUpdate(update.hiddenAwardIds); + + const setOptional = ( + key: "headline" | "githubUrl" | "linkedinUrl", + value: string, + ) => { + if (value) next[key] = value; + else delete next[key]; + }; + if (update.headline !== undefined) + setOptional( + "headline", + validatePlainText( + update.headline, + PORTFOLIO_HEADLINE_MAX, + "Headline", + ), + ); + if (update.githubUrl !== undefined) + setOptional( + "githubUrl", + normalizeProfileUrl(update.githubUrl, "github"), + ); + if (update.linkedinUrl !== undefined) + setOptional( + "linkedinUrl", + normalizeProfileUrl(update.linkedinUrl, "linkedin"), + ); + + return next; +} + +/* Chronological position; ROLLING (service) roles have no season, so last */ +function seasonRank(seasonType: string, seasonYear: number): number { + const season = (seasonType ?? "").toUpperCase(); + if (season !== "FALL" && season !== "SPRING") + return Number.MAX_SAFE_INTEGER; + if (!Number.isFinite(seasonYear)) return Number.MAX_SAFE_INTEGER; + return seasonYear * 2 + (season === "FALL" ? 1 : 0); +} + +/* Spring runs January to July, Fall August to December */ +function currentSeasonRank(now: Date): number { + return seasonRank( + now.getUTCMonth() >= 7 ? "FALL" : "SPRING", + now.getUTCFullYear(), + ); +} + +/** Reads stored role history defensively, dropping malformed entries. */ +export function normalizeRoleHistory(raw: unknown): RoleHistoryEntry[] { + if (!Array.isArray(raw)) return []; + const entries: RoleHistoryEntry[] = []; + for (const item of raw) { + if (!item || typeof item !== "object") continue; + const e = item as Partial<RoleHistoryEntry>; + const teamName = storedText(e.teamName, 120); + const roleTitle = storedText(e.roleTitle, 120); + if ( + typeof e.id !== "string" || + !ITEM_ID_PATTERN.test(e.id) || + !teamName || + !roleTitle || + typeof e.teamType !== "string" || + typeof e.seasonType !== "string" || + typeof e.seasonYear !== "number" + ) + continue; + const entry: RoleHistoryEntry = { + id: e.id, + teamPk: typeof e.teamPk === "string" ? e.teamPk : "", + teamName, + roleTitle, + teamType: e.teamType, + seasonType: e.seasonType, + seasonYear: e.seasonYear, + endedAt: typeof e.endedAt === "string" ? e.endedAt : "", + }; + const subteamName = storedText(e.subteamName, 120); + if (subteamName) entry.subteamName = subteamName; + entries.push(entry); + } + return entries; +} + +/** Reads stored awards defensively, dropping malformed entries. */ +export function normalizeAwards(raw: unknown): MemberAward[] { + if (!Array.isArray(raw)) return []; + const awards: MemberAward[] = []; + for (const item of raw) { + if (!item || typeof item !== "object") continue; + const a = item as Partial<MemberAward>; + const title = storedText(a.title, AWARD_TITLE_MAX); + if ( + typeof a.id !== "string" || + !ITEM_ID_PATTERN.test(a.id) || + !title || + typeof a.awardedOn !== "string" || + !ISO_DATE_PATTERN.test(a.awardedOn) || + typeof a.teamPk !== "string" + ) + continue; + const award: MemberAward = { + id: a.id, + title, + awardedOn: a.awardedOn, + teamPk: a.teamPk, + grantedByPk: Number(a.grantedByPk) || 0, + grantedAt: typeof a.grantedAt === "string" ? a.grantedAt : "", + }; + const reason = storedText(a.reason, AWARD_REASON_MAX); + if (reason) award.reason = reason; + awards.push(award); + } + return awards; +} + +/** + * Builds the history entry stored when a member leaves a team. Returns null + * when there is no role to remember. + */ +export function makeRoleHistoryEntry(input: { + teamPk: string; + rootTeamName: string; + subteamName?: string | undefined; + roleTitle: string | undefined; + teamType: TeamType; + seasonType: SeasonType | ServiceSeasonType; + seasonYear: number; + endedAt: Date; +}): RoleHistoryEntry | null { + if (!input.roleTitle || !input.roleTitle.trim() || !input.rootTeamName) + return null; + const entry: RoleHistoryEntry = { + id: randomUUID(), + teamPk: input.teamPk, + teamName: input.rootTeamName, + roleTitle: input.roleTitle.trim(), + teamType: input.teamType, + seasonType: input.seasonType, + seasonYear: input.seasonYear, + endedAt: input.endedAt.toISOString().slice(0, 10), + }; + if (input.subteamName) entry.subteamName = input.subteamName; + return entry; +} + +/** Appends to stored history, keeping the newest entries within the cap. */ +export function appendRoleHistory( + existing: unknown, + entry: RoleHistoryEntry, +): RoleHistoryEntry[] { + return [...normalizeRoleHistory(existing), entry].slice( + -PORTFOLIO_MAX_HISTORY, + ); +} + +/** + * Every role a member has held, each with the id its hide switch uses: + * current memberships (keyed by group pk) and stored history (keyed by + * entry id). A history entry that repeats a current role is dropped, so a + * member removed and re-added shows the role once. + */ +export function collectMemberRoles(input: { + roles: { [teamPk: string]: string } | undefined; + memberships: TeamMembershipBrief[]; + roleHistory: unknown; + now: Date; +}): PortfolioSettingsRole[] { + const membershipByPk = new Map(input.memberships.map((m) => [m.pk, m])); + const nowRank = currentSeasonRank(input.now); + const collected: PortfolioSettingsRole[] = []; + const seen = new Set<string>(); + const keyOf = (r: PortfolioRole) => + [ + r.teamName, + r.subteamName ?? "", + r.roleTitle, + r.seasonType, + r.seasonYear, + ].join("|"); + + for (const [teamPk, roleTitle] of Object.entries(input.roles ?? {})) { + if (typeof roleTitle !== "string" || roleTitle.trim() === "") continue; + const membership = membershipByPk.get(teamPk); + if (!membership || membership.flaggedForDeletion) continue; + + const isSubteam = Boolean(membership.parent); + const rootName = isSubteam + ? membership.parentFriendlyName || membership.parentName + : membership.friendlyName; + if (!rootName) continue; + + const role: PortfolioSettingsRole = { + id: teamPk, + teamName: rootName, + roleTitle, + teamType: membership.teamType, + seasonType: membership.seasonType, + seasonYear: membership.seasonYear, + current: + seasonRank(membership.seasonType, membership.seasonYear) >= + nowRank, + }; + if (isSubteam && membership.friendlyName) + role.subteamName = membership.friendlyName; + seen.add(keyOf(role)); + collected.push(role); + } + + for (const entry of normalizeRoleHistory(input.roleHistory)) { + const role: PortfolioSettingsRole = { + id: entry.id, + teamName: entry.teamName, + roleTitle: entry.roleTitle, + teamType: entry.teamType, + seasonType: entry.seasonType, + seasonYear: entry.seasonYear, + current: false, + }; + if (entry.subteamName) role.subteamName = entry.subteamName; + const key = keyOf(role); + if (seen.has(key)) continue; + seen.add(key); + collected.push(role); + } + + /* Current first, then newest season first */ + collected.sort( + (a, b) => + Number(b.current) - Number(a.current) || + seasonRank(b.seasonType, b.seasonYear) - + seasonRank(a.seasonType, a.seasonYear) || + a.teamName.localeCompare(b.teamName), + ); + return collected; +} + +/* Field by field, so stored grant metadata never reaches a response */ +export function publicAward(award: MemberAward): PortfolioAward { + const out: PortfolioAward = { + title: award.title, + awardedOn: award.awardedOn, + }; + if (award.reason) out.reason = award.reason; + return out; +} + +export function sortAwards<T extends { awardedOn: string }>(awards: T[]): T[] { + return [...awards].sort((a, b) => b.awardedOn.localeCompare(a.awardedOn)); +} + +/** + * Builds the public portfolio. Hidden roles and awards are left out + * entirely, and a project is built only from visible roles. + * + * The output is assembled field by field rather than by spreading the input, + * so a new attribute added to users or teams later cannot leak here. + */ +export function buildPublicPortfolio(input: { + username: string; + name: string; + avatar: string; + roles: { [teamPk: string]: string } | undefined; + memberships: TeamMembershipBrief[]; + roleHistory: unknown; + awards: unknown; + settings: PortfolioSettings; + now: Date; +}): PublicPortfolioResponse { + const all = collectMemberRoles(input); + const hiddenRoles = new Set(input.settings.hiddenRoleIds); + const hiddenAwards = new Set(input.settings.hiddenAwardIds); + + const roles: PortfolioRole[] = all + .filter((r) => !hiddenRoles.has(r.id)) + .map((r) => { + const role: PortfolioRole = { + teamName: r.teamName, + roleTitle: r.roleTitle, + teamType: r.teamType, + seasonType: r.seasonType, + seasonYear: r.seasonYear, + current: r.current, + }; + if (r.subteamName) role.subteamName = r.subteamName; + return role; + }); + + /* One card per project team, spanning the seasons of its visible roles */ + const projectsByName = new Map<string, PortfolioProject>(); + for (const role of [...roles].reverse()) { + if (role.teamType !== TeamType.PROJECT) continue; + const project = projectsByName.get(role.teamName); + if (!project) { + projectsByName.set(role.teamName, { + name: role.teamName, + firstSeasonType: role.seasonType, + firstSeasonYear: role.seasonYear, + lastSeasonType: role.seasonType, + lastSeasonYear: role.seasonYear, + roles: [role.roleTitle], + }); + continue; + } + const rank = seasonRank(role.seasonType, role.seasonYear); + if ( + rank < seasonRank(project.firstSeasonType, project.firstSeasonYear) + ) { + project.firstSeasonType = role.seasonType; + project.firstSeasonYear = role.seasonYear; + } + if (rank > seasonRank(project.lastSeasonType, project.lastSeasonYear)) { + project.lastSeasonType = role.seasonType; + project.lastSeasonYear = role.seasonYear; + } + if (!project.roles.includes(role.roleTitle)) + project.roles.push(role.roleTitle); + } + const projects = [...projectsByName.values()].sort( + (a, b) => + seasonRank(b.lastSeasonType, b.lastSeasonYear) - + seasonRank(a.lastSeasonType, a.lastSeasonYear) || + a.name.localeCompare(b.name), + ); + + const awards = sortAwards( + normalizeAwards(input.awards).filter((a) => !hiddenAwards.has(a.id)), + ).map(publicAward); + + const response: PublicPortfolioResponse = { + username: input.username, + name: input.name, + avatar: input.avatar, + isAlumni: !all.some((r) => r.current), + syncedAt: input.now.toISOString(), + roles, + awards, + projects, + }; + + const about: PortfolioAbout = {}; + if (input.settings.headline) about.headline = input.settings.headline; + if (input.settings.githubUrl) about.githubUrl = input.settings.githubUrl; + if (input.settings.linkedinUrl) + about.linkedinUrl = input.settings.linkedinUrl; + if (Object.keys(about).length > 0) response.about = about; + + return response; +} + +/** Validates a grant request and builds the stored award. */ +export function makeAward( + request: GrantAwardRequest, + grant: { teamPk: string; grantedByPk: number; now: Date }, +): MemberAward { + if (!request || typeof request !== "object") + throw new CustomValidationError(400, "Invalid award."); + const title = validatePlainText(request.title, AWARD_TITLE_MAX, "Title", { + allowEmpty: false, + }); + const reason = + request.reason === undefined || request.reason === null + ? "" + : validatePlainText(request.reason, AWARD_REASON_MAX, "Reason"); + + const awardedOn = request.awardedOn; + const parsed = + typeof awardedOn === "string" && ISO_DATE_PATTERN.test(awardedOn) + ? new Date(`${awardedOn}T00:00:00Z`) + : null; + if ( + !parsed || + Number.isNaN(parsed.getTime()) || + parsed.toISOString().slice(0, 10) !== awardedOn + ) + throw new CustomValidationError(400, "Invalid award date."); + /* A day of slack for time zones ahead of UTC */ + if (parsed.getTime() > grant.now.getTime() + 24 * 60 * 60 * 1000) + throw new CustomValidationError( + 400, + "Award date can't be in the future.", + ); + + const award: MemberAward = { + id: randomUUID(), + title, + awardedOn, + teamPk: grant.teamPk, + grantedByPk: grant.grantedByPk, + grantedAt: grant.now.toISOString(), + }; + if (reason) award.reason = reason; + return award; +} diff --git a/peopleportal/server/test/unit/portfolio.test.js b/peopleportal/server/test/unit/portfolio.test.js new file mode 100644 index 00000000..fa9c51c0 --- /dev/null +++ b/peopleportal/server/test/unit/portfolio.test.js @@ -0,0 +1,803 @@ +/** + * Member portfolio (#150). The public endpoint needs no sign-in, so the tests + * that matter most are the privacy ones: members are private until they opt + * in, a private member looks exactly like a missing one, and nothing beyond + * the whitelisted fields ever leaves the server. Then role history, awards, + * the member-written section and share-preview tags. + */ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); + +const { PortfolioController } = require("../../dist/controllers/PortfolioController.js"); +const { OrgController } = require("../../dist/controllers/OrgController.js"); +const { + AuthentikClientError, + AuthentikClientErrorType, +} = require("../../dist/clients/AuthentikClient/models.js"); +const { + buildPublicPortfolio, + normalizePortfolioSettings, + applyPortfolioSettingsUpdate, + makeAward, + normalizeProfileUrl, +} = require("../../dist/utils/portfolio.js"); +const { + buildShareMeta, + escapeHtml, + injectShareMeta, + portfolioPageHandler, +} = require("../../dist/utils/portfolio-share.js"); +const { loadPublicPortfolio } = require("../../dist/utils/portfolio-loader.js"); + +/* Fall 2026 is the current season */ +const NOW = new Date("2026-12-03T12:00:00Z"); + +/* Private details that must never reach the public response. */ +const PRIVATE_VALUES = [ + "ada@terpmail.umd.edu", + "+1 301 555 0100", + "Computer Science", + "2027-05-20", + "https://www.linkedin.com/in/ada-private", + "sub-secret-subject", +]; + +const MEMBERSHIPS = [ + { + pk: "pp-fa25", + name: "peopleportal-fa25", + parent: null, + friendlyName: "People Portal", + teamType: "PROJECT", + seasonType: "FALL", + seasonYear: 2025, + description: "Internal tooling", + }, + { + pk: "pp-sp26-eng", + name: "peopleportal-sp26-eng", + parent: "pp-sp26", + friendlyName: "Engineering", + parentName: "peopleportal-sp26", + parentFriendlyName: "People Portal", + teamType: "PROJECT", + seasonType: "SPRING", + seasonYear: 2026, + description: "Subteam", + }, + { + pk: "techops", + name: "techops", + parent: null, + friendlyName: "Tech Ops", + teamType: "SERVICE", + seasonType: "ROLLING", + seasonYear: 2024, + description: "Service team", + }, +]; + +const HISTORY = [ + { + id: "hist-1", + teamPk: "tp-fa24", + teamName: "Terp Planner", + roleTitle: "Designer", + teamType: "PROJECT", + seasonType: "FALL", + seasonYear: 2024, + endedAt: "2024-12-15", + }, + /* Repeats a current role: shown once, as the current one */ + { + id: "hist-dup", + teamPk: "pp-fa25", + teamName: "People Portal", + roleTitle: "Developer", + teamType: "PROJECT", + seasonType: "FALL", + seasonYear: 2025, + endedAt: "2025-10-01", + }, +]; + +const AWARDS = [ + { + id: "award-1", + title: "Best Demo", + reason: "Shipped the portfolio page", + awardedOn: "2026-04-30", + teamPk: "pp-sp26", + grantedByPk: 7, + grantedAt: "2026-04-30T18:00:00.000Z", + }, + { + id: "award-2", + title: "Mentor of the Season", + awardedOn: "2025-12-10", + teamPk: "pp-fa25", + grantedByPk: 7, + grantedAt: "2025-12-10T18:00:00.000Z", + }, +]; + +const PUBLIC = (extra = {}) => ({ isPublic: true, hiddenRoleIds: [], hiddenAwardIds: [], ...extra }); + +function makeUser({ portfolio, username = "ada", roleHistory, awards } = {}) { + return { + pk: 42, + username, + name: "Ada Lovelace", + email: "ada@terpmail.umd.edu", + active: true, + is_superuser: false, + memberSince: "2025-08-30", + avatar: "https://authentik.invalid/gravatar", + groups: ["pp-fa25", "pp-sp26-eng", "techops"], + attributes: { + major: "Computer Science", + expectedGrad: "2027-05-20", + phoneNumber: "+1 301 555 0100", + linkedinUrl: "https://www.linkedin.com/in/ada-private", + oidcSubject: "sub-secret-subject", + roles: { + "pp-fa25": "Developer", + "pp-sp26-eng": "Tech Lead", + techops: "Engineer", + /* A role left over from a team the member was removed from */ + "gone-team": "Ghost Role", + }, + ...(roleHistory === undefined ? {} : { roleHistory }), + ...(awards === undefined ? {} : { awards }), + ...(portfolio === undefined ? {} : { portfolio }), + }, + }; +} + +/* A fake directory standing in for Authentik */ +function fakeDirectory({ users = {}, lookupError, memberships = MEMBERSHIPS, groups = {} } = {}) { + const calls = { updates: [], membershipLookups: 0 }; + const directory = { + getUserInfoFromUsername: async (username) => { + if (lookupError) throw lookupError; + const user = users[username]; + if (!user) throw new AuthentikClientError(AuthentikClientErrorType.USER_NOT_FOUND); + return user; + }, + getUserInfoFromEmail: async (email) => { + const user = Object.values(users).find((u) => u.email === email); + if (!user) throw new AuthentikClientError(AuthentikClientErrorType.USERINFO_REQUEST_FAILED); + return user; + }, + getUserInfo: async (pk) => { + const user = Object.values(users).find((u) => u.pk === pk); + if (!user) throw new AuthentikClientError(AuthentikClientErrorType.USERINFO_REQUEST_FAILED); + return user; + }, + getGroupInfo: async (pk) => groups[pk], + getTeamMembershipsForUsername: async () => { + calls.membershipLookups += 1; + return { memberships }; + }, + updateUserAttributes: async (pk, payload) => { + calls.updates.push({ pk, payload }); + const user = Object.values(users).find((u) => u.pk === pk); + if (user) user.attributes = { ...user.attributes, ...payload }; + return true; + }, + removeGroupMember: async () => true, + }; + return { directory, calls }; +} + +function controllerWith(options) { + const { directory, calls } = fakeDirectory(options); + const controller = new PortfolioController(); + controller.authentikClient = directory; + return { controller, calls }; +} + +/* Captures the rejection so two of them can be compared field by field. */ +async function rejectionOf(promise) { + try { + await promise; + } catch (e) { + return { status: e.status, message: e.message, name: e.name }; + } + assert.fail("expected the request to be rejected"); +} + +/* ── Privacy ─────────────────────────────────────────────────────────── */ + +test("an opted-in member's portfolio shows current roles first, then past ones", async () => { + const { controller } = controllerWith({ users: { ada: makeUser({ portfolio: PUBLIC() }) } }); + + const portfolio = await controller.getPublicPortfolio("ada"); + + assert.equal(portfolio.username, "ada"); + assert.equal(portfolio.name, "Ada Lovelace"); + assert.deepEqual( + portfolio.roles.map((r) => [r.teamName, r.subteamName, r.roleTitle, r.seasonType, r.current]), + [ + ["Tech Ops", undefined, "Engineer", "ROLLING", true], + ["People Portal", "Engineering", "Tech Lead", "SPRING", false], + ["People Portal", undefined, "Developer", "FALL", false], + ], + "the orphaned role is dropped", + ); + assert.equal(portfolio.isAlumni, false); + assert.ok(!Number.isNaN(Date.parse(portfolio.syncedAt))); +}); + +test("the public response carries only whitelisted fields", async () => { + const { controller } = controllerWith({ + users: { + ada: makeUser({ + portfolio: PUBLIC({ headline: "Builds tools", githubUrl: "https://github.com/ada" }), + roleHistory: HISTORY, + awards: AWARDS, + }), + }, + }); + + const portfolio = await controller.getPublicPortfolio("ada"); + const serialized = JSON.stringify(portfolio); + + assert.deepEqual(Object.keys(portfolio).sort(), [ + "about", + "avatar", + "awards", + "isAlumni", + "name", + "projects", + "roles", + "syncedAt", + "username", + ]); + for (const role of portfolio.roles) + for (const key of Object.keys(role)) + assert.ok( + ["teamName", "subteamName", "roleTitle", "teamType", "seasonType", "seasonYear", "current"].includes(key), + `unexpected role field ${key}`, + ); + for (const award of portfolio.awards) + for (const key of Object.keys(award)) + assert.ok(["title", "reason", "awardedOn"].includes(key), `unexpected award field ${key}`); + assert.deepEqual(Object.keys(portfolio.about).sort(), ["githubUrl", "headline"]); + + for (const value of PRIVATE_VALUES) assert.ok(!serialized.includes(value), `private value leaked: ${value}`); + for (const id of ["pp-fa25", "techops", "hist-1", "award-1", "tp-fa24", "grantedBy", "endedAt"]) + assert.ok(!serialized.includes(id), `internal id leaked: ${id}`); + assert.ok(!serialized.includes('"pk"'), "user pk must not be exposed"); + /* The Authentik gravatar fallback is not the member's uploaded avatar */ + assert.ok(!serialized.includes("authentik.invalid")); +}); + +test("the LinkedIn on file is never used for the member-written section", async () => { + const { controller } = controllerWith({ users: { ada: makeUser({ portfolio: PUBLIC() }) } }); + const portfolio = await controller.getPublicPortfolio("ada"); + assert.equal(portfolio.about, undefined, "nothing written means no section"); +}); + +test("a member who never opted in is not found, without fetching their teams", async () => { + const { controller, calls } = controllerWith({ users: { ada: makeUser() } }); + + const rejection = await rejectionOf(controller.getPublicPortfolio("ada")); + + assert.equal(rejection.status, 404); + assert.equal(calls.membershipLookups, 0); +}); + +test("a member who turned the page off is not found", async () => { + const { controller } = controllerWith({ users: { ada: makeUser({ portfolio: PUBLIC({ isPublic: false }) }) } }); + assert.equal((await rejectionOf(controller.getPublicPortfolio("ada"))).status, 404); +}); + +test("private, missing, ambiguous and oversized usernames all get the identical 404", async () => { + const { controller } = controllerWith({ users: { ada: makeUser() } }); + const privateMember = await rejectionOf(controller.getPublicPortfolio("ada")); + const nobody = await rejectionOf(controller.getPublicPortfolio("no-such-user")); + const ambiguous = await rejectionOf( + controllerWith({ + lookupError: new AuthentikClientError(AuthentikClientErrorType.MULTIPLE_RESULTS_RETURNED), + }).controller.getPublicPortfolio("ada"), + ); + const oversized = await rejectionOf(controller.getPublicPortfolio("x".repeat(151))); + const empty = await rejectionOf(controller.getPublicPortfolio("")); + + const expected = { status: 404, message: "Portfolio not found", name: "CustomValidationError" }; + for (const r of [privateMember, nobody, ambiguous, oversized, empty]) assert.deepEqual(r, expected); +}); + +test("an Authentik outage is reported as an error, not as not-found", async () => { + const { controller } = controllerWith({ + lookupError: new AuthentikClientError(AuthentikClientErrorType.USERINFO_REQUEST_FAILED), + }); + await assert.rejects( + () => controller.getPublicPortfolio("ada"), + (e) => e instanceof AuthentikClientError && e.code === AuthentikClientErrorType.USERINFO_REQUEST_FAILED, + ); +}); + +/* ── Role history ────────────────────────────────────────────────────── */ + +test("role history merges with current roles, de-duplicated", () => { + const portfolio = buildPublicPortfolio({ + username: "ada", + name: "Ada", + avatar: "", + roles: { "pp-fa25": "Developer" }, + memberships: MEMBERSHIPS, + roleHistory: HISTORY, + awards: [], + settings: PUBLIC(), + now: NOW, + }); + + assert.deepEqual( + portfolio.roles.map((r) => [r.teamName, r.roleTitle, r.seasonYear]), + [ + ["People Portal", "Developer", 2025], + ["Terp Planner", "Designer", 2024], + ], + "the history copy of the current Developer role is dropped", + ); + assert.deepEqual( + portfolio.projects.map((p) => [p.name, p.roles, p.firstSeasonYear, p.lastSeasonYear]), + [ + ["People Portal", ["Developer"], 2025, 2025], + ["Terp Planner", ["Designer"], 2024, 2024], + ], + ); + assert.equal(portfolio.isAlumni, true, "no role is in the current season"); +}); + +test("a project card spans its seasons and lists each role once", () => { + const portfolio = buildPublicPortfolio({ + username: "ada", + name: "Ada", + avatar: "", + roles: { "pp-fa25": "Developer", "pp-sp26-eng": "Tech Lead" }, + memberships: MEMBERSHIPS, + roleHistory: [], + awards: [], + settings: PUBLIC(), + now: NOW, + }); + assert.deepEqual(portfolio.projects, [ + { + name: "People Portal", + firstSeasonType: "FALL", + firstSeasonYear: 2025, + lastSeasonType: "SPRING", + lastSeasonYear: 2026, + roles: ["Developer", "Tech Lead"], + }, + ]); +}); + +test("hide switches work on current roles and history entries alike", () => { + const portfolio = buildPublicPortfolio({ + username: "ada", + name: "Ada", + avatar: "", + roles: { "pp-fa25": "Developer", techops: "Engineer" }, + memberships: MEMBERSHIPS, + roleHistory: HISTORY, + awards: [], + settings: PUBLIC({ hiddenRoleIds: ["pp-fa25", "hist-1"] }), + now: NOW, + }); + assert.deepEqual(portfolio.roles.map((r) => r.roleTitle), ["Engineer"]); + assert.deepEqual(portfolio.projects, [], "hidden roles take their projects with them"); + assert.equal(portfolio.isAlumni, false); +}); + +test("malformed history entries are dropped, never shown", () => { + const portfolio = buildPublicPortfolio({ + username: "ada", + name: "Ada", + avatar: "", + roles: {}, + memberships: [], + roleHistory: [ + { id: "bad id!", teamName: "X", roleTitle: "Y", teamType: "PROJECT", seasonType: "FALL", seasonYear: 2024 }, + { id: "ok", teamName: "<script>", roleTitle: "Y", teamType: "PROJECT", seasonType: "FALL", seasonYear: 2024 }, + "nonsense", + ], + awards: [], + settings: PUBLIC(), + now: NOW, + }); + assert.deepEqual(portfolio.roles, []); +}); + +test("removing a member stores their role in history in the same update", async () => { + const ada = makeUser(); + const groups = { + "pp-sp26-eng": { + pk: "pp-sp26-eng", + name: "peopleportal-sp26-eng", + parentPk: "pp-sp26", + users: [], + subteamPkList: [], + subteams: [], + attributes: { friendlyName: "Engineering", teamType: "PROJECT", seasonType: "SPRING", seasonYear: 2026 }, + }, + "pp-sp26": { + pk: "pp-sp26", + name: "peopleportal-sp26", + parentPk: null, + users: [{}, {}], + subteamPkList: ["pp-sp26-eng"], + subteams: [], + attributes: { friendlyName: "People Portal", teamType: "PROJECT", seasonType: "SPRING", seasonYear: 2026 }, + }, + }; + const { directory, calls } = fakeDirectory({ users: { ada }, groups }); + const org = new OrgController(); + org.authentikClient = directory; + + await org.removeTeamMemberWrapper({ groupId: "pp-sp26-eng", userPk: 42 }); + + assert.equal(calls.updates.length, 1); + const { roles, roleHistory } = calls.updates[0].payload; + assert.equal(roles["pp-sp26-eng"], undefined, "the current role is removed"); + assert.equal(roleHistory.length, 1); + const [entry] = roleHistory; + assert.deepEqual( + { ...entry, id: undefined, endedAt: undefined }, + { + id: undefined, + teamPk: "pp-sp26-eng", + teamName: "People Portal", + subteamName: "Engineering", + roleTitle: "Tech Lead", + teamType: "PROJECT", + seasonType: "SPRING", + seasonYear: 2026, + endedAt: undefined, + }, + ); + assert.match(entry.id, /^[0-9a-f-]{36}$/); + assert.match(entry.endedAt, /^\d{4}-\d{2}-\d{2}$/); + + /* And the role stays on the portfolio afterwards */ + const portfolio = buildPublicPortfolio({ + username: "ada", + name: "Ada", + avatar: "", + roles: roles, + memberships: MEMBERSHIPS.filter((m) => m.pk !== "pp-sp26-eng"), + roleHistory, + awards: [], + settings: PUBLIC(), + now: NOW, + }); + assert.ok(portfolio.roles.some((r) => r.roleTitle === "Tech Lead" && r.subteamName === "Engineering")); +}); + +/* ── Awards ──────────────────────────────────────────────────────────── */ + +test("award endpoints require the corp:membermgmt bindle; the public page needs none", () => { + const spec = require("../../dist/swagger.json"); + const security = (p, m) => spec.paths[p][m].security; + const base = "/api/portfolio/teams/{teamId}/members/{userPk}/awards"; + for (const [p, m] of [ + [base, "get"], + [base, "post"], + [`${base}/{awardId}`, "delete"], + ]) + assert.deepEqual(security(p, m), [{ bindles: ["corp:membermgmt"] }], `${m} ${p}`); + assert.deepEqual(security("/api/portfolio/{username}", "get"), []); + assert.deepEqual(security("/api/portfolio/me/settings", "patch"), [{ oidc: [] }]); +}); + +function awardsSetup({ teamId = "pp-sp26", targetGroups = ["pp-sp26-eng"], awards } = {}) { + const ada = makeUser({ awards }); + ada.groups = targetGroups; + const groups = { + "pp-sp26": { pk: "pp-sp26", parentPk: null, subteamPkList: ["pp-sp26-eng"] }, + "pp-sp26-eng": { pk: "pp-sp26-eng", parentPk: "pp-sp26", subteamPkList: [] }, + other: { pk: "other", parentPk: null, subteamPkList: [] }, + }; + const { controller, calls } = controllerWith({ users: { ada }, groups }); + const req = { + session: { authorizedUser: { pk: 7, email: "lead@terpmail.umd.edu" } }, + bindle: { teamInfo: groups[teamId] }, + }; + return { controller, calls, req, ada }; +} + +test("a lead grants an award to a member of their team, through a subteam too", async () => { + const { controller, calls, req } = awardsSetup({ teamId: "pp-sp26-eng" }); + const awards = await controller.grantMemberAward(req, "pp-sp26-eng", 42, { + title: "Best Demo", + reason: "Great work", + awardedOn: "2026-11-30", + }); + assert.equal(awards.length, 1); + assert.equal(awards[0].revocable, true); + const stored = calls.updates[0].payload.awards[0]; + assert.equal(stored.teamPk, "pp-sp26", "recorded against the root team"); + assert.equal(stored.grantedByPk, 7); +}); + +test("a lead can't grant an award to someone outside their team", async () => { + const { controller, calls, req } = awardsSetup({ teamId: "other" }); + const rejection = await rejectionOf( + controller.grantMemberAward(req, "other", 42, { title: "X", awardedOn: "2026-11-30" }), + ); + assert.equal(rejection.status, 404); + assert.equal(calls.updates.length, 0); +}); + +test("a team owner can't grant or revoke their own awards", async () => { + const { controller, calls, req } = awardsSetup({ awards: AWARDS }); + req.session.authorizedUser.pk = 42; + for (const attempt of [ + controller.grantMemberAward(req, "pp-sp26", 42, { title: "Me", awardedOn: "2026-11-30" }), + controller.revokeMemberAward(req, "pp-sp26", 42, "award-1"), + ]) + assert.deepEqual(await rejectionOf(attempt), { + status: 403, + message: "You can't grant or revoke your own awards.", + name: "CustomValidationError", + }); + assert.equal(calls.updates.length, 0); +}); + +test("only the granting team can revoke an award", async () => { + const { controller, calls, req } = awardsSetup({ awards: AWARDS }); + /* award-2 was granted through pp-fa25, not this team */ + assert.equal((await rejectionOf(controller.revokeMemberAward(req, "pp-sp26", 42, "award-2"))).status, 403); + assert.equal(calls.updates.length, 0); + + const remaining = await controller.revokeMemberAward(req, "pp-sp26", 42, "award-1"); + assert.deepEqual(remaining.map((a) => a.id), ["award-2"]); + assert.equal(remaining[0].revocable, false); +}); + +test("award input is validated: plain text, length caps, a real past date", () => { + const grant = { teamPk: "t", grantedByPk: 1, now: NOW }; + assert.throws(() => makeAward({ title: "", awardedOn: "2026-01-01" }, grant), (e) => e.status === 400); + assert.throws(() => makeAward({ title: "x".repeat(81), awardedOn: "2026-01-01" }, grant), (e) => e.status === 400); + assert.throws(() => makeAward({ title: "<b>Hi</b>", awardedOn: "2026-01-01" }, grant), (e) => e.status === 400); + assert.throws(() => makeAward({ title: "Hi", reason: "y".repeat(201), awardedOn: "2026-01-01" }, grant), (e) => e.status === 400); + assert.throws(() => makeAward({ title: "Hi", awardedOn: "2026-02-30" }, grant), (e) => e.status === 400); + assert.throws(() => makeAward({ title: "Hi", awardedOn: "2027-06-01" }, grant), (e) => e.status === 400); + const award = makeAward({ title: " Hi ", awardedOn: "2026-01-01" }, grant); + assert.equal(award.title, "Hi"); + assert.equal(award.reason, undefined); +}); + +test("awards show only while the member leaves them visible, newest first", () => { + const build = (hiddenAwardIds) => + buildPublicPortfolio({ + username: "ada", + name: "Ada", + avatar: "", + roles: {}, + memberships: [], + roleHistory: [], + awards: AWARDS, + settings: PUBLIC({ hiddenAwardIds }), + now: NOW, + }).awards; + + assert.deepEqual(build([]).map((a) => a.title), ["Best Demo", "Mentor of the Season"]); + assert.deepEqual(build(["award-1"]), [{ title: "Mentor of the Season", awardedOn: "2025-12-10" }]); +}); + +test("a member can hide an award but has no way to add or edit one", async () => { + const { controller, calls, ada } = awardsSetup({ awards: AWARDS }); + const req = { session: { authorizedUser: { email: ada.email } } }; + + await controller.updatePortfolioSettings(req, { hiddenAwardIds: ["award-1"] }); + const payload = calls.updates[0].payload; + assert.deepEqual(Object.keys(payload), ["portfolio"], "only the portfolio attribute is written"); + assert.deepEqual(payload.portfolio.hiddenAwardIds, ["award-1"]); + + /* Award fields in a settings update are not part of the settings model */ + const next = applyPortfolioSettingsUpdate(normalizePortfolioSettings(undefined), { awards: [{ title: "Fake" }] }); + assert.equal(next.awards, undefined); +}); + +/* ── Settings and member-written fields ──────────────────────────────── */ + +test("settings are private by default and malformed values fail closed", () => { + assert.deepEqual(normalizePortfolioSettings(undefined), { isPublic: false, hiddenRoleIds: [], hiddenAwardIds: [] }); + assert.deepEqual(normalizePortfolioSettings({ isPublic: "true" }), { + isPublic: false, + hiddenRoleIds: [], + hiddenAwardIds: [], + }); + assert.deepEqual( + normalizePortfolioSettings({ + isPublic: true, + hiddenRoleIds: ["a", "a", 7, "bad pk!"], + headline: "<img onerror=x>", + githubUrl: "javascript:alert(1)", + }), + { isPublic: true, hiddenRoleIds: ["a"], hiddenAwardIds: [] }, + ); +}); + +test("a settings update validates its input and keeps omitted fields", () => { + const current = { isPublic: true, hiddenRoleIds: ["a"], hiddenAwardIds: [], headline: "Old" }; + + assert.deepEqual(applyPortfolioSettingsUpdate(current, { isPublic: false }), { ...current, isPublic: false }); + assert.deepEqual(applyPortfolioSettingsUpdate(current, { hiddenRoleIds: ["b", "b"] }).hiddenRoleIds, ["b"]); + assert.equal(applyPortfolioSettingsUpdate(current, { headline: "" }).headline, undefined, "empty clears"); + assert.throws(() => applyPortfolioSettingsUpdate(current, { hiddenRoleIds: ["../etc"] }), (e) => e.status === 400); + assert.throws( + () => applyPortfolioSettingsUpdate(current, { hiddenAwardIds: Array.from({ length: 201 }, (_, i) => `t${i}`) }), + (e) => e.status === 400, + ); +}); + +test("headline is plain text on one line, at most 160 characters", () => { + const base = normalizePortfolioSettings(undefined); + assert.equal(applyPortfolioSettingsUpdate(base, { headline: " Full-stack & design " }).headline, "Full-stack & design"); + assert.equal(applyPortfolioSettingsUpdate(base, { headline: "x".repeat(160) }).headline.length, 160); + for (const headline of ["x".repeat(161), "<b>bold</b>", "two\nlines", 42]) + assert.throws(() => applyPortfolioSettingsUpdate(base, { headline }), (e) => e.status === 400, String(headline)); +}); + +test("profile links must be https on the right site, and are normalized", () => { + assert.equal(normalizeProfileUrl("https://github.com/ada-l/", "github"), "https://github.com/ada-l"); + assert.equal(normalizeProfileUrl("https://www.github.com/ada", "github"), "https://github.com/ada"); + assert.equal(normalizeProfileUrl("https://linkedin.com/in/ada-l", "linkedin"), "https://www.linkedin.com/in/ada-l"); + assert.equal(normalizeProfileUrl("", "github"), ""); + for (const [url, kind] of [ + ["http://github.com/ada", "github"], + ["github.com/ada", "github"], + ["javascript:alert(1)", "github"], + ["https://github.com.evil.example/ada", "github"], + ["https://user:pw@github.com/ada", "github"], + ["https://github.com/ada/repo", "github"], + ["https://github.com/ada?x=1", "github"], + [`https://github.com/${"a".repeat(200)}`, "github"], + ["http://www.linkedin.com/in/ada", "linkedin"], + ["https://www.linkedin.com/company/x", "linkedin"], + ]) + assert.throws(() => normalizeProfileUrl(url, kind), (e) => e.status === 400, url); +}); + +test("a member can only change their own settings, taken from the session", async () => { + const ada = makeUser({ portfolio: PUBLIC({ isPublic: false, hiddenRoleIds: ["techops"] }) }); + const { controller, calls } = controllerWith({ users: { ada } }); + const request = { session: { authorizedUser: { email: ada.email, pk: 42 } } }; + + const result = await controller.updatePortfolioSettings(request, { + isPublic: true, + headline: "Builds tools", + githubUrl: "https://github.com/ada", + }); + + assert.deepEqual(result, { + isPublic: true, + hiddenRoleIds: ["techops"], + hiddenAwardIds: [], + headline: "Builds tools", + githubUrl: "https://github.com/ada", + }); + assert.deepEqual(calls.updates, [{ pk: 42, payload: { portfolio: result } }]); +}); + +test("the settings view lists every role with the id its switch uses", async () => { + const ada = makeUser({ roleHistory: HISTORY, awards: AWARDS }); + const { controller } = controllerWith({ users: { ada } }); + + const view = await controller.getPortfolioSettings({ session: { authorizedUser: { email: ada.email } } }); + + assert.deepEqual(view.settings, { isPublic: false, hiddenRoleIds: [], hiddenAwardIds: [] }); + assert.deepEqual( + view.roles.map((r) => r.id), + ["techops", "pp-sp26-eng", "pp-fa25", "hist-1"], + ); + assert.deepEqual(view.awards.map((a) => a.id), ["award-1", "award-2"]); + assert.ok(!JSON.stringify(view.awards).includes("grantedByPk")); +}); + +/* ── Share previews ──────────────────────────────────────────────────── */ + +const SHELL = `<!doctype html> +<html lang="en"> + <head> + <title>App Dev Club People Portal + +
+`; + +test("share tags HTML-escape every member value", () => { + const share = buildShareMeta( + { + username: "ada", + name: `Ada "" & Co`, + avatar: "", + isAlumni: false, + syncedAt: NOW.toISOString(), + roles: [ + { teamName: "T&", roleTitle: `Lead">"), "no raw script tag"); + assert.ok(!html.includes('">/g) || []).length, 1, "the title is replaced, not duplicated"); + assert.equal(escapeHtml(`'`), "'"); +}); + +function servePage(load) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pp-share-")); + const indexHtmlPath = path.join(dir, "index.html"); + fs.writeFileSync(indexHtmlPath, SHELL); + const handler = portfolioPageHandler({ indexHtmlPath, baseUrl: "https://pp.example", load }); + return async (username) => { + const res = { + statusCode: 200, + headers: {}, + body: "", + status(code) { + this.statusCode = code; + return this; + }, + set(k, v) { + this.headers[k] = v; + return this; + }, + type() { + return this; + }, + send(body) { + this.body = body; + return this; + }, + }; + await handler({ params: { username } }, res); + return res; + }; +} + +test("a public page gets the member's share tags", async () => { + const ada = makeUser({ portfolio: PUBLIC() }); + const { directory } = fakeDirectory({ users: { ada } }); + const get = servePage((u) => loadPublicPortfolio(directory, u, NOW)); + + const res = await get("ada"); + assert.equal(res.statusCode, 200); + assert.ok(res.body.includes(' { + const ada = makeUser({ portfolio: PUBLIC({ isPublic: false }) }); + const { directory } = fakeDirectory({ users: { ada } }); + const get = servePage((u) => loadPublicPortfolio(directory, u, NOW)); + + const privatePage = await get("ada"); + const missingPage = await get("nobody"); + const outage = await servePage(async () => { + throw new Error("down"); + })("ada"); + + assert.equal(privatePage.statusCode, missingPage.statusCode); + assert.equal(privatePage.body, missingPage.body); + assert.equal(outage.body, missingPage.body); + for (const leaked of ["Ada", "Lovelace", "Tech Ops", "og:url", "/u/ada"]) + assert.ok(!privatePage.body.includes(leaked), `leaked ${leaked}`); + assert.ok(privatePage.body.includes('content="App Dev Club People Portal"')); +}); diff --git a/peopleportal/webui/src/App.tsx b/peopleportal/webui/src/App.tsx index 41381c8c..7e6ea020 100644 --- a/peopleportal/webui/src/App.tsx +++ b/peopleportal/webui/src/App.tsx @@ -22,6 +22,7 @@ import { Toaster } from "sonner"; import { CorpDashboard } from "./pages/CorpDashboard"; import { ThemeProvider } from "./components/fabric/ThemeProvider"; import { ATSDashboard } from "./pages/ATSDashboard"; +import { MemberPortfolio } from "./pages/MemberPortfolio"; function App() { return ( @@ -35,6 +36,7 @@ function App() { element={} /> } /> + } /> diff --git a/peopleportal/webui/src/components/fabric/DashboardPeopleInfo.tsx b/peopleportal/webui/src/components/fabric/DashboardPeopleInfo.tsx index 5f65861a..75632c66 100644 --- a/peopleportal/webui/src/components/fabric/DashboardPeopleInfo.tsx +++ b/peopleportal/webui/src/components/fabric/DashboardPeopleInfo.tsx @@ -105,6 +105,7 @@ import { normalizeLinkedInProfileUrl, } from "@/lib/linkedin"; import imageCompression from "browser-image-compression"; +import { PortfolioSettingsCard } from "./PortfolioSettingsCard"; // --- Interfaces matching the Backend --- @@ -1287,6 +1288,13 @@ export const DashboardPeopleInfo = () => { )} + {loggedInPk !== null && Number(userPk) === loggedInPk && ( + + )} + {reviewTeams.length !== 0 && (
diff --git a/peopleportal/webui/src/components/fabric/DashboardTeamInfo.tsx b/peopleportal/webui/src/components/fabric/DashboardTeamInfo.tsx index 8f1bb28f..446e6ed9 100644 --- a/peopleportal/webui/src/components/fabric/DashboardTeamInfo.tsx +++ b/peopleportal/webui/src/components/fabric/DashboardTeamInfo.tsx @@ -74,6 +74,7 @@ import type { GetUserListResponse } from "./DashboardPeopleList"; import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar"; import { Alert, AlertDescription, AlertTitle } from "../ui/alert"; import { ProgressUpdateDialog } from "../fragments/ProgressUpdateDialog"; +import { MemberAwardsDialog } from "./MemberAwardsDialog"; import { SidebarGroup, SidebarGroupContent, @@ -153,6 +154,9 @@ export const DashboardTeamInfo = () => { teamName: string; } | null>(null); + const [awardsMember, setAwardsMember] = + React.useState(null); + const [syncDialogOpen, setSyncDialogOpen] = React.useState(false); const [syncDialogTitle, setSyncDialogTitle] = React.useState(""); const [syncDialogDescription, setSyncDialogDescription] = @@ -464,6 +468,15 @@ export const DashboardTeamInfo = () => { isLoading={isRemovingMember} /> + { + if (!open) setAwardsMember(null); + }} + teamPk={teamInfo?.pk} + member={awardsMember ?? undefined} + /> + { handleRemoveMember( user, @@ -642,6 +656,7 @@ export const DashboardTeamInfo = () => { handleRemoveMember( user, diff --git a/peopleportal/webui/src/components/fabric/MemberAwardsDialog.test.tsx b/peopleportal/webui/src/components/fabric/MemberAwardsDialog.test.tsx new file mode 100644 index 00000000..007a33bf --- /dev/null +++ b/peopleportal/webui/src/components/fabric/MemberAwardsDialog.test.tsx @@ -0,0 +1,117 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MemberAwardsDialog } from "./MemberAwardsDialog"; + +const BASE = "/api/portfolio/teams/team-1/members/42/awards"; + +let awards: { + id: string; + title: string; + reason?: string; + awardedOn: string; + revocable: boolean; +}[]; + +beforeEach(() => { + awards = [ + { + id: "a1", + title: "Best Demo", + awardedOn: "2026-04-30", + revocable: true, + }, + { + id: "a2", + title: "Mentor", + awardedOn: "2025-12-10", + revocable: false, + }, + ]; + vi.stubGlobal( + "fetch", + vi.fn(async (url: string, init?: RequestInit) => { + if (init?.method === "POST") { + const body = JSON.parse(String(init.body)); + awards = [{ id: "a3", revocable: true, ...body }, ...awards]; + } else if (init?.method === "DELETE") { + awards = awards.filter((a) => !url.endsWith(`/${a.id}`)); + } + return { ok: true, status: 200, json: async () => awards }; + }), + ); +}); +afterEach(() => vi.unstubAllGlobals()); + +const renderDialog = async () => { + render( + {}} + teamPk="team-1" + member={{ pk: "42", name: "Ada Lovelace" }} + />, + ); + await waitFor(() => + expect(screen.getByText("Best Demo")).toBeInTheDocument(), + ); +}; + +describe("MemberAwardsDialog", () => { + it("lists the member's awards; only this team's can be revoked", async () => { + await renderDialog(); + expect(fetch).toHaveBeenCalledWith(BASE, { credentials: "include" }); + expect( + screen.getByRole("button", { name: "Revoke Best Demo" }), + ).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Revoke Mentor" }), + ).not.toBeInTheDocument(); + expect(screen.getByText("Another team")).toBeInTheDocument(); + }); + + it("grants an award with title, reason and date", async () => { + const user = userEvent.setup(); + await renderDialog(); + + await user.type(screen.getByLabelText("Title"), "Top Reviewer"); + await user.type(screen.getByLabelText(/Reason/), "Reviewed 40 PRs"); + await user.clear(screen.getByLabelText("Date granted")); + await user.type(screen.getByLabelText("Date granted"), "2026-11-20"); + await user.click(screen.getByRole("button", { name: "Grant award" })); + + await waitFor(() => + expect(screen.getByText("Top Reviewer")).toBeInTheDocument(), + ); + const post = vi + .mocked(fetch) + .mock.calls.find(([, init]) => init?.method === "POST")!; + expect(post[0]).toBe(BASE); + expect(JSON.parse(String(post[1]!.body))).toEqual({ + title: "Top Reviewer", + reason: "Reviewed 40 PRs", + awardedOn: "2026-11-20", + }); + }); + + it("revokes an award", async () => { + const user = userEvent.setup(); + await renderDialog(); + + await user.click( + screen.getByRole("button", { name: "Revoke Best Demo" }), + ); + + await waitFor(() => + expect(screen.queryByText("Best Demo")).not.toBeInTheDocument(), + ); + expect( + vi + .mocked(fetch) + .mock.calls.some( + ([url, init]) => + url === `${BASE}/a1` && init?.method === "DELETE", + ), + ).toBe(true); + }); +}); diff --git a/peopleportal/webui/src/components/fabric/MemberAwardsDialog.tsx b/peopleportal/webui/src/components/fabric/MemberAwardsDialog.tsx new file mode 100644 index 00000000..2894e482 --- /dev/null +++ b/peopleportal/webui/src/components/fabric/MemberAwardsDialog.tsx @@ -0,0 +1,273 @@ +/** + People Portal UI + Copyright (C) 2026 Atheesh Thirumalairajan + + 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 . +*/ + +import React from "react"; +import { toast } from "sonner"; +import { Loader2Icon, Trash2Icon } from "lucide-react"; +import { PEOPLEPORTAL_SERVER_ENDPOINT } from "@/commons/config"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { formatDate, type PortfolioAward } from "@/lib/portfolio"; + +export interface ManagedAward extends PortfolioAward { + id: string; + /* Granted through this team, so this team may revoke it */ + revocable: boolean; +} + +const todayIso = () => new Date().toISOString().slice(0, 10); + +async function failure(res: Response): Promise { + try { + const body = await res.json(); + if (typeof body?.message === "string") return new Error(body.message); + } catch { + /* fall through */ + } + return new Error(`HTTP ${res.status}`); +} + +/** + * Lets a team lead (anyone holding `corp:membermgmt` on the team) grant and + * revoke awards for one member. Awards show on the member's public + * portfolio (#150) as verified, unless the member hides them. + */ +export function MemberAwardsDialog({ + open, + onOpenChange, + teamPk, + member, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + teamPk?: string; + member?: { pk: string; name: string }; +}) { + const [awards, setAwards] = React.useState(null); + const [busy, setBusy] = React.useState(false); + const [form, setForm] = React.useState({ + title: "", + reason: "", + awardedOn: todayIso(), + }); + + const base = + teamPk && member + ? `${PEOPLEPORTAL_SERVER_ENDPOINT}/api/portfolio/teams/${encodeURIComponent(teamPk)}/members/${encodeURIComponent(member.pk)}/awards` + : null; + + React.useEffect(() => { + if (!open || !base) return; + let cancelled = false; + setAwards(null); + setForm({ title: "", reason: "", awardedOn: todayIso() }); + fetch(base, { credentials: "include" }) + .then(async (res) => { + if (!res.ok) throw await failure(res); + const list: ManagedAward[] = await res.json(); + if (!cancelled) setAwards(list); + }) + .catch((e) => { + if (!cancelled) { + setAwards([]); + toast.error(`Couldn't load awards: ${e.message}`); + } + }); + return () => { + cancelled = true; + }; + }, [open, base]); + + const grant = async (e: React.FormEvent) => { + e.preventDefault(); + if (!base) return; + setBusy(true); + try { + const res = await fetch(base, { + method: "POST", + credentials: "include", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + title: form.title, + ...(form.reason.trim() ? { reason: form.reason } : {}), + awardedOn: form.awardedOn, + }), + }); + if (!res.ok) throw await failure(res); + setAwards(await res.json()); + setForm({ title: "", reason: "", awardedOn: todayIso() }); + toast.success(`Granted "${form.title.trim()}" to ${member?.name}`); + } catch (err) { + toast.error( + `Couldn't grant the award: ${err instanceof Error ? err.message : ""}`, + ); + } finally { + setBusy(false); + } + }; + + const revoke = async (award: ManagedAward) => { + if (!base) return; + setBusy(true); + try { + const res = await fetch(`${base}/${encodeURIComponent(award.id)}`, { + method: "DELETE", + credentials: "include", + }); + if (!res.ok) throw await failure(res); + setAwards(await res.json()); + toast.success(`Revoked "${award.title}"`); + } catch (err) { + toast.error( + `Couldn't revoke the award: ${err instanceof Error ? err.message : ""}`, + ); + } finally { + setBusy(false); + } + }; + + return ( + + + + Awards for {member?.name} + + Awards appear on {member?.name}'s public portfolio as + verified by the club. They can hide an award but can't + add or edit one. + + + +
+

Current awards

+ {awards === null ? ( +

+ Loading… +

+ ) : awards.length === 0 ? ( +

+ No awards yet. +

+ ) : ( +
    + {awards.map((award) => ( +
  • +
    +

    + {award.title} +

    +

    + {formatDate(award.awardedOn)} + {award.reason + ? ` · ${award.reason}` + : ""} +

    +
    + {award.revocable ? ( + + ) : ( + + Another team + + )} +
  • + ))} +
+ )} +
+ +
+

Grant an award

+
+ + + setForm({ ...form, title: e.target.value }) + } + /> +
+
+ + + setForm({ ...form, reason: e.target.value }) + } + /> +
+
+ + + setForm({ ...form, awardedOn: e.target.value }) + } + /> +
+ +
+
+
+ ); +} diff --git a/peopleportal/webui/src/components/fabric/PortfolioSettingsCard.test.tsx b/peopleportal/webui/src/components/fabric/PortfolioSettingsCard.test.tsx new file mode 100644 index 00000000..69e7f38f --- /dev/null +++ b/peopleportal/webui/src/components/fabric/PortfolioSettingsCard.test.tsx @@ -0,0 +1,221 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { PortfolioSettingsCard } from "./PortfolioSettingsCard"; + +const ROLES = [ + { + id: "techops", + teamName: "Tech Ops", + roleTitle: "Engineer", + teamType: "SERVICE", + seasonType: "ROLLING", + seasonYear: 2024, + current: true, + }, + { + id: "hist-1", + teamName: "People Portal", + subteamName: "Engineering", + roleTitle: "Tech Lead", + teamType: "PROJECT", + seasonType: "SPRING", + seasonYear: 2026, + current: false, + }, +]; + +const AWARDS = [{ id: "award-1", title: "Best Demo", awardedOn: "2026-04-30" }]; + +type Settings = { + isPublic: boolean; + hiddenRoleIds: string[]; + hiddenAwardIds: string[]; + headline?: string; + githubUrl?: string; + linkedinUrl?: string; +}; + +let serverState: Settings; +let rejectNext: { status: number; message: string } | null; + +/* GET returns the view; PATCH echoes the saved settings, as the server does */ +beforeEach(() => { + serverState = { isPublic: false, hiddenRoleIds: [], hiddenAwardIds: [] }; + rejectNext = null; + vi.stubGlobal( + "fetch", + vi.fn(async (_url: string, init?: RequestInit) => { + if (!init?.method || init.method === "GET") + return { + ok: true, + status: 200, + json: async () => ({ + settings: serverState, + roles: ROLES, + awards: AWARDS, + }), + }; + if (rejectNext) { + const r = rejectNext; + rejectNext = null; + return { + ok: false, + status: r.status, + json: async () => ({ message: r.message }), + }; + } + serverState = { ...serverState, ...JSON.parse(String(init.body)) }; + return { ok: true, status: 200, json: async () => serverState }; + }), + ); +}); +afterEach(() => vi.unstubAllGlobals()); + +const lastRequest = () => { + const calls = vi.mocked(fetch).mock.calls; + const [url, init] = calls[calls.length - 1]!; + return { url, init: init!, body: JSON.parse(String(init!.body)) }; +}; + +const renderCard = async (settings?: Partial) => { + if (settings) serverState = { ...serverState, ...settings }; + render(); + await waitFor(() => + expect( + screen.getByRole("switch", { name: /Engineer · Tech Ops/ }), + ).toBeInTheDocument(), + ); +}; + +const mainSwitch = () => + screen.getByRole("switch", { name: "Public portfolio" }); + +describe("PortfolioSettingsCard", () => { + it("loads the member's own settings and is off by default", async () => { + await renderCard(); + expect(fetch).toHaveBeenCalledWith("/api/portfolio/me/settings", { + credentials: "include", + }); + expect(mainSwitch()).not.toBeChecked(); + expect(screen.getByLabelText("Portfolio link")).toHaveValue( + `${window.location.origin}/u/ada`, + ); + expect( + screen.getByRole("button", { name: /Copy link/ }), + ).toBeDisabled(); + }); + + it("explains what is and isn't shown", async () => { + await renderCard(); + expect( + screen.getByText(/Anyone with the link sees:/), + ).toBeInTheDocument(); + expect( + screen.getByText(/Never shown:/).parentElement, + ).toHaveTextContent( + "email, phone, major, graduation date and your LinkedIn on file", + ); + expect( + screen.getByText( + /You can hide them, but you can't add or edit them/, + ), + ).toBeInTheDocument(); + }); + + it("keeps role and award switches visible but disabled while off", async () => { + await renderCard(); + for (const name of [ + /Engineer · Tech Ops/, + /Tech Lead · People Portal · Engineering/, + /Best Demo/, + ]) + expect(screen.getByRole("switch", { name })).toBeDisabled(); + }); + + it("turning it on saves the setting and enables the item switches", async () => { + const user = userEvent.setup(); + await renderCard(); + + await user.click(mainSwitch()); + + await waitFor(() => + expect( + screen.getByRole("switch", { name: /Engineer · Tech Ops/ }), + ).toBeEnabled(), + ); + const { url, init, body } = lastRequest(); + expect(url).toBe("/api/portfolio/me/settings"); + expect(init.method).toBe("PATCH"); + expect(body).toEqual({ isPublic: true }); + expect(screen.getByRole("link", { name: /Open/ })).toHaveAttribute( + "href", + "/u/ada", + ); + }); + + it("hiding a history role sends its id and marks it hidden", async () => { + const user = userEvent.setup(); + await renderCard({ isPublic: true }); + + await user.click( + screen.getByRole("switch", { name: /Tech Lead · People Portal/ }), + ); + + await waitFor(() => + expect( + screen.getByText(/hidden from your page/), + ).toBeInTheDocument(), + ); + expect(lastRequest().body).toEqual({ hiddenRoleIds: ["hist-1"] }); + }); + + it("hiding an award sends its id", async () => { + const user = userEvent.setup(); + await renderCard({ isPublic: true }); + + await user.click(screen.getByRole("switch", { name: /Best Demo/ })); + + await waitFor(() => + expect(lastRequest().body).toEqual({ hiddenAwardIds: ["award-1"] }), + ); + }); + + it("saves the member-written fields together", async () => { + const user = userEvent.setup(); + await renderCard({ isPublic: true }); + + const save = screen.getByRole("button", { name: "Save" }); + expect(save).toBeDisabled(); + await user.type(screen.getByLabelText("Headline"), "Builds tools"); + await user.type( + screen.getByLabelText("GitHub URL"), + "https://github.com/ada", + ); + expect(screen.getByText("12/160")).toBeInTheDocument(); + await user.click(save); + + await waitFor(() => + expect(lastRequest().body).toEqual({ + headline: "Builds tools", + githubUrl: "https://github.com/ada", + linkedinUrl: "", + }), + ); + expect(screen.getByLabelText("Headline")).toHaveAttribute( + "maxLength", + "160", + ); + }); + + it("rolls back a change the server refuses", async () => { + const user = userEvent.setup(); + await renderCard(); + rejectNext = { status: 400, message: "Nope" }; + + await user.click(mainSwitch()); + + await waitFor(() => expect(mainSwitch()).not.toBeChecked()); + expect(mainSwitch()).toBeEnabled(); + }); +}); diff --git a/peopleportal/webui/src/components/fabric/PortfolioSettingsCard.tsx b/peopleportal/webui/src/components/fabric/PortfolioSettingsCard.tsx new file mode 100644 index 00000000..6164abb8 --- /dev/null +++ b/peopleportal/webui/src/components/fabric/PortfolioSettingsCard.tsx @@ -0,0 +1,517 @@ +/** + People Portal UI + Copyright (C) 2026 Atheesh Thirumalairajan + + 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 . +*/ + +import { useEffect, useState, type ReactNode } from "react"; +import { toast } from "sonner"; +import { Copy, ExternalLink } from "lucide-react"; +import { PEOPLEPORTAL_SERVER_ENDPOINT } from "@/commons/config"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Switch } from "@/components/ui/switch"; +import { cn } from "@/lib/utils"; +import { + HEADLINE_MAX, + formatDate, + portfolioUrl, + seasonLabel, + teamLabel, + type PortfolioSettings, + type PortfolioSettingsView, +} from "@/lib/portfolio"; + +/* A pseudo-element widens the switch's hit area to 44px without changing how + it looks */ +const TOUCH_SWITCH = + "relative after:absolute after:-inset-x-1.5 after:-inset-y-3.5 after:content-['']"; + +const SETTINGS_URL = `${PEOPLEPORTAL_SERVER_ENDPOINT}/api/portfolio/me/settings`; + +async function errorMessage(res: Response): Promise { + try { + const body = await res.json(); + if (typeof body?.message === "string") return body.message; + } catch { + /* fall through */ + } + return "Please try again."; +} + +/** + * The member's own controls for their public portfolio (#150): turn the page + * on or off, copy its link, choose which roles and awards it shows, and + * write the separate, unverified "From you" section. Switches save at once + * and roll back if the server refuses; the text fields save with a button. + */ +export function PortfolioSettingsCard({ username }: { username: string }) { + const [view, setView] = useState(null); + const [loadFailed, setLoadFailed] = useState(false); + const [saving, setSaving] = useState(false); + const [draft, setDraft] = useState({ + headline: "", + githubUrl: "", + linkedinUrl: "", + }); + const shareLink = portfolioUrl(username, window.location.origin); + + useEffect(() => { + let cancelled = false; + fetch(SETTINGS_URL, { credentials: "include" }) + .then(async (res) => { + if (!res.ok) throw new Error(res.statusText); + const data: PortfolioSettingsView = await res.json(); + if (cancelled) return; + setView(data); + setDraft({ + headline: data.settings.headline ?? "", + githubUrl: data.settings.githubUrl ?? "", + linkedinUrl: data.settings.linkedinUrl ?? "", + }); + }) + .catch(() => { + if (!cancelled) setLoadFailed(true); + }); + return () => { + cancelled = true; + }; + }, []); + + const save = async ( + update: Partial, + ): Promise => { + if (!view) return false; + const previous = view.settings; + setView({ ...view, settings: { ...previous, ...update } }); + setSaving(true); + try { + const res = await fetch(SETTINGS_URL, { + method: "PATCH", + credentials: "include", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(update), + }); + if (!res.ok) throw new Error(await errorMessage(res)); + const settings: PortfolioSettings = await res.json(); + setView((v) => (v ? { ...v, settings } : v)); + return true; + } catch (e) { + setView((v) => (v ? { ...v, settings: previous } : v)); + toast.error( + `Couldn't update your portfolio. ${e instanceof Error ? e.message : ""}`, + ); + return false; + } finally { + setSaving(false); + } + }; + + const toggle = ( + key: "hiddenRoleIds" | "hiddenAwardIds", + id: string, + shown: boolean, + ) => { + if (!view) return; + const hidden = new Set(view.settings[key]); + if (shown) hidden.delete(id); + else hidden.add(id); + save({ [key]: [...hidden] }); + }; + + const saveAbout = async () => { + const saved = await save({ + headline: draft.headline, + githubUrl: draft.githubUrl, + linkedinUrl: draft.linkedinUrl, + }); + if (saved) toast.success("Saved"); + }; + + const copyLink = async () => { + try { + await navigator.clipboard.writeText(shareLink); + toast.info("Portfolio link copied to clipboard"); + } catch { + toast.error("Failed to copy link"); + } + }; + + return ( +
+
+
+

+ Public portfolio +

+

+ Share your verified club roles and projects with one + link. It stays off until you turn it on. +

+
+ save({ isPublic: checked })} + /> +
+ + {!view && !loadFailed && ( +
+ + +
+ )} + {loadFailed && ( +

+ Couldn't load your portfolio settings. Refresh to try again. +

+ )} + + {view && ( + + )} +
+ ); +} + +function PortfolioSettingsBody({ + view, + saving, + shareLink, + username, + draft, + onDraftChange, + onToggle, + onCopy, + onSaveAbout, +}: { + view: PortfolioSettingsView; + saving: boolean; + shareLink: string; + username: string; + draft: { headline: string; githubUrl: string; linkedinUrl: string }; + onDraftChange: (draft: { + headline: string; + githubUrl: string; + linkedinUrl: string; + }) => void; + onToggle: ( + key: "hiddenRoleIds" | "hiddenAwardIds", + id: string, + shown: boolean, + ) => void; + onCopy: () => void; + onSaveAbout: () => void; +}) { + const { settings } = view; + const off = !settings.isPublic; + const aboutChanged = + draft.headline !== (settings.headline ?? "") || + draft.githubUrl !== (settings.githubUrl ?? "") || + draft.linkedinUrl !== (settings.linkedinUrl ?? ""); + + return ( + <> +
+ e.currentTarget.select()} + /> +
+ + {off ? ( + + ) : ( + + )} +
+
+ +
+

+ + Anyone with the link sees: + {" "} + your name and photo, plus the roles, awards and projects you + leave on below. +

+

+ + Never shown: + {" "} + email, phone, major, graduation date and your LinkedIn on + file. +

+
+ + ({ + id: role.id, + primary: `${role.roleTitle} · ${teamLabel(role)}`, + secondary: role.current + ? "Ongoing" + : seasonLabel(role.seasonType, role.seasonYear), + shown: !settings.hiddenRoleIds.includes(role.id), + }))} + onToggle={(id, shown) => onToggle("hiddenRoleIds", id, shown)} + /> + + ({ + id: award.id, + primary: award.title, + secondary: formatDate(award.awardedOn), + shown: !settings.hiddenAwardIds.includes(award.id), + }))} + onToggle={(id, shown) => onToggle("hiddenAwardIds", id, shown)} + /> + +
+
+

From you

+

+ Shown in a separate section labelled as not verified by + the club. Your LinkedIn on file is never used. +

+
+ + + onDraftChange({ + ...draft, + headline: e.target.value, + }) + } + /> + +
+ + + onDraftChange({ + ...draft, + githubUrl: e.target.value, + }) + } + /> + + + + onDraftChange({ + ...draft, + linkedinUrl: e.target.value, + }) + } + /> + +
+ +
+ +

+ Roles and awards come from App Dev Club records. You can hide + them, but you can't add or edit them. That is what the Verified + badge means. +

+ + ); +} + +function Field({ + id, + label, + hint, + children, +}: { + id: string; + label: string; + hint?: string; + children: ReactNode; +}) { + return ( +
+
+ + {hint && ( + + {hint} + + )} +
+ {children} +
+ ); +} + +function ToggleList({ + title, + empty, + items, + off, + saving, + onToggle, +}: { + title: string; + empty: string; + items: { id: string; primary: string; secondary: string; shown: boolean }[]; + off: boolean; + saving: boolean; + onToggle: (id: string, shown: boolean) => void; +}) { + return ( + /* Kept in place while off so the card doesn't jump, but greyed out: + nothing is shown publicly until the page is on. */ +
+

{title}

+ {items.length === 0 ? ( +

{empty}

+ ) : ( +
    + {items.map((item) => { + const switchId = `portfolio-item-${item.id}`; + return ( +
  • + + + onToggle(item.id, checked) + } + /> +
  • + ); + })} +
+ )} +
+ ); +} diff --git a/peopleportal/webui/src/components/fragments/UserInformationTable.tsx b/peopleportal/webui/src/components/fragments/UserInformationTable.tsx index 15f70936..9cd43c2c 100644 --- a/peopleportal/webui/src/components/fragments/UserInformationTable.tsx +++ b/peopleportal/webui/src/components/fragments/UserInformationTable.tsx @@ -46,7 +46,7 @@ import { PaginationEllipsis, PaginationNext, } from "../ui/pagination"; -import { MailIcon, Trash2Icon, User2Icon } from "lucide-react"; +import { AwardIcon, MailIcon, Trash2Icon, User2Icon } from "lucide-react"; export interface UserInformationBrief { pk: string; @@ -64,6 +64,8 @@ export interface UserTableProps { showPagination?: boolean; onUserClick?: (userId: string) => void; onRemove?: (user: UserInformationBrief) => void; + /* Opens award management for a member (#150) */ + onAwards?: (user: UserInformationBrief) => void; filterPlaceholder?: string; className?: string; teamPk?: string; @@ -74,6 +76,7 @@ export const UserInformationTable: React.FC = ({ showPagination = false, onUserClick, onRemove, + onAwards, filterPlaceholder = "Start Typing to Filter by Name", className = "", teamPk, @@ -135,27 +138,44 @@ export const UserInformationTable: React.FC = ({
), }, - ...(onRemove + ...(onRemove || onAwards ? [ { id: "actions", header: "Actions", - size: 70, + size: 90, cell: ({ row, }: { row: { original: UserInformationBrief }; }) => ( - +
+ {onAwards && ( + + )} + {onRemove && ( + + )} +
), }, ] diff --git a/peopleportal/webui/src/lib/portfolio.ts b/peopleportal/webui/src/lib/portfolio.ts new file mode 100644 index 00000000..ed5d3697 --- /dev/null +++ b/peopleportal/webui/src/lib/portfolio.ts @@ -0,0 +1,154 @@ +/** + People Portal UI + Copyright (C) 2026 Atheesh Thirumalairajan + + 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 . +*/ + +/* Mirrors the server's PublicPortfolioResponse (#150) */ +export interface PortfolioRole { + teamName: string; + subteamName?: string; + roleTitle: string; + teamType: string; + seasonType: string; + seasonYear: number; + /* Held now */ + current: boolean; +} + +export interface PortfolioProject { + name: string; + firstSeasonType: string; + firstSeasonYear: number; + lastSeasonType: string; + lastSeasonYear: number; + roles: string[]; +} + +export interface PortfolioAward { + title: string; + reason?: string; + /* YYYY-MM-DD */ + awardedOn: string; +} + +export interface PortfolioAbout { + headline?: string; + githubUrl?: string; + linkedinUrl?: string; +} + +export interface PublicPortfolio { + username: string; + name: string; + avatar: string; + isAlumni: boolean; + syncedAt: string; + roles: PortfolioRole[]; + awards: PortfolioAward[]; + projects: PortfolioProject[]; + about?: PortfolioAbout; +} + +export interface PortfolioSettings { + isPublic: boolean; + hiddenRoleIds: string[]; + hiddenAwardIds: string[]; + headline?: string; + githubUrl?: string; + linkedinUrl?: string; +} + +/* GET /api/portfolio/me/settings */ +export interface PortfolioSettingsView { + settings: PortfolioSettings; + roles: (PortfolioRole & { id: string })[]; + awards: (PortfolioAward & { id: string })[]; +} + +export const HEADLINE_MAX = 160; + +/** "Fall 2025", or "Ongoing" for rolling (service) teams with no season. */ +export function seasonLabel(seasonType: string, seasonYear: number): string { + const season = (seasonType ?? "").toUpperCase(); + if ((season !== "FALL" && season !== "SPRING") || !seasonYear) + return "Ongoing"; + return `${season === "FALL" ? "Fall" : "Spring"} ${seasonYear}`; +} + +/** "Fall 2025 – Spring 2026", or one season when they match. */ +export function termRange(project: PortfolioProject): string { + const first = seasonLabel(project.firstSeasonType, project.firstSeasonYear); + const last = seasonLabel(project.lastSeasonType, project.lastSeasonYear); + return first === last ? first : `${first} – ${last}`; +} + +/** "People Portal · Engineering" for a subteam role. */ +export function teamLabel(role: { + teamName: string; + subteamName?: string; +}): string { + return role.subteamName + ? `${role.teamName} · ${role.subteamName}` + : role.teamName; +} + +/** The pill on each club record row. */ +export function teamTypeLabel(teamType: string): string { + switch ((teamType ?? "").toUpperCase()) { + case "PROJECT": + return "Project team"; + case "SERVICE": + return "Service team"; + case "CORPORATE": + return "Corporate team"; + case "BOOTCAMP": + return "Bootcamp"; + default: + return "Team"; + } +} + +export function firstName(name: string): string { + return name.trim().split(/\s+/)[0] || name; +} + +export function initialsOf(name: string): string { + return name + .split(/\s+/) + .filter(Boolean) + .slice(0, 2) + .map((part) => part[0]!.toUpperCase()) + .join(""); +} + +/** "Apr 30, 2026" for a YYYY-MM-DD date or an ISO timestamp, in UTC. */ +export function formatDate(value: string): string { + const date = new Date( + /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value, + ); + if (Number.isNaN(date.getTime())) return ""; + return date.toLocaleDateString("en-US", { + year: "numeric", + month: "short", + day: "numeric", + timeZone: "UTC", + }); +} + +/** The public page address for a username, absolute for sharing. */ +export function portfolioUrl(username: string, origin: string): string { + return `${origin}/u/${encodeURIComponent(username)}`; +} diff --git a/peopleportal/webui/src/pages/MemberPortfolio.test.tsx b/peopleportal/webui/src/pages/MemberPortfolio.test.tsx new file mode 100644 index 00000000..1b19e66e --- /dev/null +++ b/peopleportal/webui/src/pages/MemberPortfolio.test.tsx @@ -0,0 +1,222 @@ +import { describe, expect, it, vi, afterEach } from "vitest"; +import { render, screen, waitFor, within } from "@testing-library/react"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { MemberPortfolio } from "./MemberPortfolio"; + +const PORTFOLIO = { + username: "ada", + name: "Ada Lovelace", + avatar: "", + isAlumni: false, + syncedAt: "2026-12-03T15:00:00.000Z", + roles: [ + { + teamName: "Terp Planner", + roleTitle: "Developer", + teamType: "PROJECT", + seasonType: "FALL", + seasonYear: 2026, + current: true, + }, + { + teamName: "People Portal", + subteamName: "Engineering", + roleTitle: "Tech Lead", + teamType: "PROJECT", + seasonType: "SPRING", + seasonYear: 2026, + current: false, + }, + { + teamName: "Tech Ops", + roleTitle: "Engineer", + teamType: "SERVICE", + seasonType: "ROLLING", + seasonYear: 2024, + current: false, + }, + ], + awards: [ + { + title: "Best Demo", + reason: "Shipped the portfolio page", + awardedOn: "2026-04-30", + }, + ], + projects: [ + { + name: "People Portal", + firstSeasonType: "FALL", + firstSeasonYear: 2025, + lastSeasonType: "SPRING", + lastSeasonYear: 2026, + roles: ["Developer", "Tech Lead"], + }, + ], + about: { + headline: "Builds tools for clubs", + githubUrl: "https://github.com/ada", + linkedinUrl: "https://www.linkedin.com/in/ada", + }, +}; + +const respondWith = (status: number, body?: unknown) => + vi.stubGlobal( + "fetch", + vi.fn(async () => ({ + ok: status >= 200 && status < 300, + status, + statusText: String(status), + json: async () => body, + })), + ); + +const renderAt = (path: string) => + render( + + + } /> + + , + ); + +const ready = () => + waitFor(() => + expect( + screen.getByText("Verified by App Dev Club"), + ).toBeInTheDocument(), + ); + +afterEach(() => vi.unstubAllGlobals()); + +describe("MemberPortfolio", () => { + it("asks the public endpoint for the username in the URL", async () => { + respondWith(200, PORTFOLIO); + renderAt("/u/ada"); + await ready(); + expect(fetch).toHaveBeenCalledWith("/api/portfolio/ada"); + expect(screen.getByText("/u/ada")).toBeInTheDocument(); + expect(screen.getByText("@ada")).toBeInTheDocument(); + }); + + it("shows the club record with terms, teams and team-type pills", async () => { + respondWith(200, PORTFOLIO); + renderAt("/u/ada"); + await ready(); + + const record = screen.getByRole("region", { name: "Club record" }); + const rows = within(record).getAllByRole("listitem"); + expect(rows).toHaveLength(3); + /* The current role reads Ongoing instead of its season */ + expect(rows[0]).toHaveTextContent("Ongoing"); + expect(rows[0]).not.toHaveTextContent("Fall 2026"); + expect(rows[1]).toHaveTextContent("Spring 2026"); + expect(rows[1]).toHaveTextContent("People Portal · Engineering"); + expect(rows[1]).toHaveTextContent("Project team"); + expect(rows[2]).toHaveTextContent("Service team"); + }); + + it("shows the provenance strip with the sync date", async () => { + respondWith(200, PORTFOLIO); + renderAt("/u/ada"); + await ready(); + expect( + screen.getByText(/This record is issued by App Dev Club/), + ).toBeInTheDocument(); + expect(screen.getByText("Synced Dec 3, 2026")).toBeInTheDocument(); + }); + + it("shows awards and project cards with term range and roles", async () => { + respondWith(200, PORTFOLIO); + renderAt("/u/ada"); + await ready(); + + const awards = screen.getByRole("region", { name: "Awards" }); + expect(awards).toHaveTextContent("Best Demo"); + expect(awards).toHaveTextContent("Shipped the portfolio page"); + expect(awards).toHaveTextContent("Apr 30, 2026"); + + const projects = screen.getByRole("region", { name: "Projects" }); + expect(projects).toHaveTextContent("Fall 2025 – Spring 2026"); + expect(projects).toHaveTextContent("Developer, Tech Lead"); + }); + + it("labels the member-written section, escapes it, and marks its links", async () => { + respondWith(200, PORTFOLIO); + renderAt("/u/ada"); + await ready(); + + const about = screen.getByRole("region", { name: "From Ada" }); + expect(about).toHaveTextContent( + "Written by the member, not verified by the club", + ); + /* Rendered as text, never as markup */ + expect(about).toHaveTextContent("Builds tools for clubs"); + expect(about.querySelector("b")).toBeNull(); + + for (const name of ["GitHub", "LinkedIn"]) { + const link = within(about).getByRole("link", { name }); + expect(link).toHaveAttribute("rel", "noopener noreferrer nofollow"); + expect(link).toHaveAttribute("target", "_blank"); + } + expect( + screen.getByText("Page visible because Ada turned it on."), + ).toBeInTheDocument(); + }); + + it("hides the member-written section when nothing was written", async () => { + respondWith(200, { ...PORTFOLIO, about: undefined, awards: [] }); + renderAt("/u/ada"); + await ready(); + expect( + screen.queryByRole("region", { name: "From Ada" }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole("region", { name: "Awards" }), + ).not.toBeInTheDocument(); + }); + + it("shows the Alumni tag only for members with no current team", async () => { + respondWith(200, PORTFOLIO); + const { unmount } = renderAt("/u/ada"); + await ready(); + expect(screen.queryByText("Alumni")).not.toBeInTheDocument(); + unmount(); + + respondWith(200, { ...PORTFOLIO, isAlumni: true }); + renderAt("/u/ada"); + await ready(); + expect(screen.getByText("Alumni")).toBeInTheDocument(); + }); + + it("shows a plain not-found state for a private or missing member", async () => { + respondWith(404, { message: "Portfolio not found" }); + renderAt("/u/someone"); + + await waitFor(() => + expect(screen.getByText("Portfolio not found")).toBeInTheDocument(), + ); + expect( + screen.queryByText("Verified by App Dev Club"), + ).not.toBeInTheDocument(); + }); + + it("tells a server failure apart from not-found", async () => { + respondWith(500); + renderAt("/u/ada"); + + await waitFor(() => + expect( + screen.getByText("Couldn't load this portfolio"), + ).toBeInTheDocument(), + ); + }); + + it("encodes unusual usernames before requesting them", async () => { + respondWith(404); + renderAt("/u/a%2Fb"); + + await waitFor(() => expect(fetch).toHaveBeenCalled()); + expect(fetch).toHaveBeenCalledWith("/api/portfolio/a%2Fb"); + }); +}); diff --git a/peopleportal/webui/src/pages/MemberPortfolio.tsx b/peopleportal/webui/src/pages/MemberPortfolio.tsx new file mode 100644 index 00000000..7d550858 --- /dev/null +++ b/peopleportal/webui/src/pages/MemberPortfolio.tsx @@ -0,0 +1,402 @@ +/** + People Portal UI + Copyright (C) 2026 Atheesh Thirumalairajan + + 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 . +*/ + +import { useEffect, useState, type ReactNode } from "react"; +import { useParams } from "react-router-dom"; +import { CircleCheck, Github, Linkedin, SearchX } from "lucide-react"; +import { PEOPLEPORTAL_SERVER_ENDPOINT } from "@/commons/config"; +import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; +import { Skeleton } from "@/components/ui/skeleton"; +import { + firstName, + formatDate, + initialsOf, + seasonLabel, + teamLabel, + teamTypeLabel, + termRange, + type PublicPortfolio, +} from "@/lib/portfolio"; + +type LoadState = + | { status: "loading" } + | { status: "notfound" } + | { status: "error" } + | { status: "ready"; portfolio: PublicPortfolio }; + +/* Design values with no theme token or Tailwind equivalent */ +const SURFACE = "bg-[#111113]"; +const PROVENANCE = "bg-[#0b1d14]"; +/* Member links leave the site and are not endorsed by it */ +const EXTERNAL_REL = "noopener noreferrer nofollow"; + +/** + * Public, club-verified member portfolio (#150). Rendered outside the + * dashboard and without sign-in, so it shows only what the public portfolio + * endpoint returns for members who opted in. Always dark. + */ +export function MemberPortfolio() { + const { username = "" } = useParams(); + const [state, setState] = useState({ status: "loading" }); + + useEffect(() => { + let cancelled = false; + setState({ status: "loading" }); + + fetch( + `${PEOPLEPORTAL_SERVER_ENDPOINT}/api/portfolio/${encodeURIComponent(username)}`, + ) + .then(async (res) => { + if (cancelled) return; + if (res.status === 404) return setState({ status: "notfound" }); + if (!res.ok) throw new Error(res.statusText); + const portfolio: PublicPortfolio = await res.json(); + if (!cancelled) setState({ status: "ready", portfolio }); + }) + .catch(() => { + if (!cancelled) setState({ status: "error" }); + }); + + return () => { + cancelled = true; + }; + }, [username]); + + return ( +
+
+ + + {state.status === "loading" && ( +
+
+ +
+ + +
+
+ +
+ )} + + {(state.status === "notfound" || state.status === "error") && ( +
+ +

+ {state.status === "notfound" + ? "Portfolio not found" + : "Couldn't load this portfolio"} +

+

+ {state.status === "notfound" + ? "This portfolio doesn't exist or isn't public." + : "Something went wrong. Please try again later."} +

+
+ )} + + {state.status === "ready" && ( + + )} +
+
+ ); +} + +function TopRow({ username }: { username: string }) { + return ( +
+
+
+ + /u/{username} + +
+ ); +} + +function SectionLabel({ + id, + children, + verified = false, +}: { + id: string; + children: ReactNode; + verified?: boolean; +}) { + return ( +
+

+ {children} +

+ {verified && ( + + Verified + + )} +
+ ); +} + +function Pill({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +function PortfolioContent({ portfolio }: { portfolio: PublicPortfolio }) { + const first = firstName(portfolio.name); + const about = portfolio.about; + const hasAbout = Boolean( + about && (about.headline || about.githubUrl || about.linkedinUrl), + ); + + return ( +
+
+ + {portfolio.avatar && ( + + )} + + {initialsOf(portfolio.name)} + + +
+

+ {portfolio.name} +

+

+ @{portfolio.username} +

+
+ + + {portfolio.isAlumni && Alumni} +
+
+
+ +
+

+ This record is issued by App Dev Club from its own People + Portal records. The member can choose what to show, but + cannot add or change a role, project or award. +

+

+ Synced {formatDate(portfolio.syncedAt)} +

+
+ +
+ + Club record + +
+ {portfolio.roles.length === 0 ? ( +

+ No roles to show yet. +

+ ) : ( +
    + {portfolio.roles.map((role, index) => ( +
  1. +

    + {role.current ? ( + + + ) : ( + seasonLabel( + role.seasonType, + role.seasonYear, + ) + )} +

    +
    +

    + {role.roleTitle} +

    +

    + {teamLabel(role)} +

    +
    +
    + + {teamTypeLabel(role.teamType)} + +
    +
  2. + ))} +
+ )} +
+
+ + {portfolio.awards.length > 0 && ( +
+ + Awards + +
    + {portfolio.awards.map((award, index) => ( +
  • +
    +

    + {award.title} +

    + {award.reason && ( +

    + {award.reason} +

    + )} +
    +

    + {formatDate(award.awardedOn)} +

    +
  • + ))} +
+
+ )} + + {portfolio.projects.length > 0 && ( +
+ + Projects + +
    + {portfolio.projects.map((project) => ( +
  • +

    + {project.name} +

    +

    + {termRange(project)} +

    +

    + {project.roles.join(", ")} +

    +
  • + ))} +
+
+ )} + + {hasAbout && about && ( +
+
+

+ From {first} +

+ + Written by the member, not verified by the club + +
+ {about.headline && ( +

+ {about.headline} +

+ )} + {(about.githubUrl || about.linkedinUrl) && ( +
+ {about.githubUrl && ( + + + GitHub + + )} + {about.linkedinUrl && ( + + + LinkedIn + + )} +
+ )} +
+ )} + + +
+ ); +}