This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50) hide show
  1. .dockerignore +0 -13
  2. .env.example +0 -19
  3. .gitignore +0 -45
  4. AGENTS.md +0 -9
  5. CLAUDE.md +0 -1
  6. Dockerfile +0 -46
  7. README.md +4 -315
  8. components.json +0 -25
  9. eslint.config.mjs +0 -18
  10. next.config.ts +0 -7
  11. package-lock.json +0 -0
  12. package.json +0 -42
  13. postcss.config.mjs +0 -7
  14. public/file.svg +0 -1
  15. public/globe.svg +0 -1
  16. public/next.svg +0 -1
  17. public/vercel.svg +0 -1
  18. public/window.svg +0 -1
  19. src/app/api/search/route.ts +0 -64
  20. src/app/api/shortlist/comments/route.ts +0 -67
  21. src/app/api/shortlist/documents/route.ts +0 -245
  22. src/app/api/shortlist/important-dates/route.ts +0 -82
  23. src/app/api/shortlist/route.ts +0 -249
  24. src/app/api/shortlist/shares/route.ts +0 -111
  25. src/app/auth/callback/route.ts +0 -20
  26. src/app/favicon.ico +0 -0
  27. src/app/globals.css +0 -130
  28. src/app/layout.tsx +0 -44
  29. src/app/login/page.tsx +0 -27
  30. src/app/page.tsx +0 -11
  31. src/app/providers.tsx +0 -12
  32. src/app/search/page.tsx +0 -47
  33. src/app/shortlist/page.tsx +0 -62
  34. src/components/auth/auth-form.tsx +0 -179
  35. src/components/layout/app-header.tsx +0 -105
  36. src/components/search/country-multi-select.tsx +0 -98
  37. src/components/search/results-table.tsx +0 -355
  38. src/components/search/search-form.tsx +0 -268
  39. src/components/search/search-view.tsx +0 -162
  40. src/components/shortlist/add-manual-dialog.tsx +0 -219
  41. src/components/shortlist/course-details-dialog.tsx +0 -204
  42. src/components/shortlist/documents-dialog.tsx +0 -200
  43. src/components/shortlist/fit-badge.tsx +0 -23
  44. src/components/shortlist/important-dates-dialog.tsx +0 -423
  45. src/components/shortlist/share-wishlist-dialog.tsx +0 -153
  46. src/components/shortlist/shortlist-table.tsx +0 -362
  47. src/components/shortlist/shortlist-view.tsx +0 -160
  48. src/components/ui/avatar.tsx +0 -111
  49. src/components/ui/badge.tsx +0 -48
  50. src/components/ui/button.tsx +0 -66
.dockerignore DELETED
@@ -1,13 +0,0 @@
1
- node_modules
2
- npm-debug.log
3
- .git
4
- .gitignore
5
- .next
6
- .env
7
- .env.*
8
- !.env.example
9
- README.md
10
- AGENTS.md
11
- CLAUDE.md
12
- Dockerfile
13
- .dockerignore
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.env.example DELETED
@@ -1,19 +0,0 @@
1
- # Copy to .env.local for `npm run dev`. Never commit .env.local.
2
- # On Hugging Face Spaces, set these in Space Settings instead (see README).
3
-
4
- # --- Browser-visible (OK to ship to the client) ---
5
- # Supabase → Project Settings → API
6
- # Use the publishable key (sb_publishable_…) or legacy anon key.
7
- # Never use the service_role / secret key here.
8
- NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
9
- NEXT_PUBLIC_SUPABASE_ANON_KEY=your-publishable-or-anon-key
10
-
11
- # --- Server-only (HF Space Secrets, not Variables) ---
12
- # https://huggingface.co/settings/tokens (fine-grained token with Inference)
13
- HUGGINGFACE_API_KEY=hf_your_token
14
- # https://api-dashboard.search.brave.com/app/documentation/web-search/get-started
15
- BRAVE_SEARCH_API_KEY=your_brave_search_api_key
16
-
17
- # --- Optional ---
18
- # Chat model for /api/search. Default is Qwen/Qwen2.5-72B-Instruct.
19
- # HF_MODEL=Qwen/Qwen2.5-72B-Instruct
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore DELETED
@@ -1,45 +0,0 @@
1
- # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
-
3
- # dependencies
4
- /node_modules
5
- /.pnp
6
- .pnp.*
7
- .yarn/*
8
- !.yarn/patches
9
- !.yarn/plugins
10
- !.yarn/releases
11
- !.yarn/versions
12
-
13
- # testing
14
- /coverage
15
-
16
- # next.js
17
- /.next/
18
- /out/
19
-
20
- # production
21
- /build
22
-
23
- # misc
24
- .DS_Store
25
- *.pem
26
-
27
- # debug
28
- npm-debug.log*
29
- yarn-debug.log*
30
- yarn-error.log*
31
- .pnpm-debug.log*
32
-
33
- # env files (can opt-in for committing if needed)
34
- .env*
35
- !.env.example
36
-
37
- # vercel
38
- .vercel
39
-
40
- # typescript
41
- *.tsbuildinfo
42
- next-env.d.ts
43
-
44
- # Local clone of the Hugging Face Space — do not nest it in this repo
45
- /UniHunt/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
AGENTS.md DELETED
@@ -1,9 +0,0 @@
1
- <!-- BEGIN:nextjs-agent-rules -->
2
-
3
- # This is NOT the Next.js you know
4
-
5
- This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
6
-
7
- This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
8
-
9
- <!-- END:nextjs-agent-rules -->
 
 
 
 
 
 
 
 
 
 
CLAUDE.md DELETED
@@ -1 +0,0 @@
1
- @AGENTS.md
 
 
Dockerfile DELETED
@@ -1,46 +0,0 @@
1
- # Hugging Face Spaces (Docker SDK). The platform runs the container as UID 1000.
2
- # NEXT_PUBLIC_* values are inlined at `next build`, so they must be Space
3
- # Variables (build-time ARGs). HUGGINGFACE_API_KEY and BRAVE_SEARCH_API_KEY
4
- # are runtime-only — never ARG them.
5
- FROM node:20-alpine AS base
6
- RUN apk add --no-cache libc6-compat
7
-
8
- FROM base AS deps
9
- WORKDIR /app
10
- COPY package.json package-lock.json ./
11
- RUN npm ci
12
-
13
- FROM base AS builder
14
- WORKDIR /app
15
- COPY --from=deps /app/node_modules ./node_modules
16
- COPY . .
17
-
18
- # Space Settings → Variables (not Secrets). HF passes Variables as Docker build-args.
19
- ARG NEXT_PUBLIC_SUPABASE_URL
20
- ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
21
- ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL
22
- ENV NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY
23
- ENV NEXT_TELEMETRY_DISABLED=1
24
-
25
- RUN npm run build
26
-
27
- FROM base AS runner
28
- # node:20-alpine already has UID 1000 as `node`. Creating another user
29
- # with that UID fails on Hugging Face Spaces (`adduser: uid '1000' in use`).
30
- ENV HOME=/home/node
31
- WORKDIR $HOME/app
32
-
33
- ENV NODE_ENV=production
34
- ENV PORT=7860
35
- ENV HOSTNAME=0.0.0.0
36
- ENV NEXT_TELEMETRY_DISABLED=1
37
-
38
- COPY --from=builder --chown=node:node /app/public ./public
39
- COPY --from=builder --chown=node:node /app/.next/standalone ./
40
- COPY --from=builder --chown=node:node /app/.next/static ./.next/static
41
-
42
- USER node
43
-
44
- EXPOSE 7860
45
-
46
- CMD ["node", "server.js"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,323 +1,12 @@
1
  ---
2
  title: UniHunt
3
- emoji: 🎓
4
- colorFrom: blue
5
- colorTo: indigo
6
  sdk: docker
7
- app_port: 7860
8
  pinned: false
9
  license: mit
10
  short_description: Web app to search for courses and universities across world
11
  ---
12
 
13
- # University Course Finder
14
-
15
- AI-powered web app to discover and shortlist university courses based on your academic profile, preferences, and budget. Works on desktop (Windows, macOS), tablets, and mobile phones.
16
-
17
- ## Status
18
-
19
- All build and backend steps below are **done**. Remaining work is only what you do in external dashboards (OAuth consoles, Space secrets, a push to a Space).
20
-
21
- | Step | Status |
22
- | --- | --- |
23
- | Next.js app (search, shortlist, notes, last-search restore) | Done |
24
- | TanStack Table v9 + Next 16 `proxy.ts` | Done |
25
- | Supabase project `university-course-finder` (`qnzkuskdkyqyeglvacqx`, Mumbai) | Done |
26
- | Schema, RLS, unique index `(user_id, university_name, course_name)` | Done |
27
- | Typed clients (`src/lib/supabase/database.types.ts`) | Done |
28
- | Email/password auth (tested) | Done |
29
- | Google OAuth in app (`signInWithOAuth`) | Done — paste Client ID/secret in [Supabase Google provider](https://supabase.com/dashboard/project/qnzkuskdkyqyeglvacqx/auth/providers) if not already |
30
- | Microsoft OAuth in app (`provider: "azure"`, `email` scope) | Done — needs an Entra **directory** first, then Azure app + [Supabase Azure provider](https://supabase.com/dashboard/project/qnzkuskdkyqyeglvacqx/auth/providers) |
31
- | Local env template (`.env.example`) | Done |
32
- | Hugging Face Spaces Docker config | Done (this file’s YAML + `Dockerfile`) |
33
-
34
- ## Features
35
-
36
- - **Smart search criteria**: course level, type, specialization, multi-country selection, candidate type (in-state / out-of-state / out-of-country)
37
- - **Candidate profile**: last qualification, school, curriculum, subjects, grades/GPA, budget
38
- - **AI search**: Brave Search finds live official course pages, then Hugging Face structures matching recommendations with verified URLs
39
- - **Sortable & filterable results**: QS World Ranking (default sort), tuition, location, admission requirements, http(s) URLs
40
- - **Shortlist**: save from search or add manually — per user in Supabase, with notes plus duration, language, intake, scholarships
41
- - **Key dates**: search the university's own website for application windows, deadlines, scholarship, exam, result and session-start dates, then add them to Google Calendar or Outlook (one click per date, or download an `.ics` file with all upcoming dates)
42
- - **Authentication**: email/password, Google, Microsoft via Supabase Auth
43
-
44
- ## Tech Stack
45
-
46
- - Next.js 16 (App Router)
47
- - Tailwind CSS 4 + shadcn/ui
48
- - Supabase (Auth + PostgreSQL)
49
- - Hugging Face Inference API
50
- - Brave Search API (verified course page URLs)
51
-
52
- ## Environment variables
53
-
54
- | Variable | Where it is read | Local | Hugging Face Space |
55
- | --- | --- | --- | --- |
56
- | `NEXT_PUBLIC_SUPABASE_URL` | Browser + server | `.env.local` | **Variable** (needed at Docker **build**) |
57
- | `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Browser + server | `.env.local` | **Variable** (needed at Docker **build**) |
58
- | `HUGGINGFACE_API_KEY` | Server only (`/api/search`) | `.env.local` | **Secret** (runtime only) |
59
- | `BRAVE_SEARCH_API_KEY` | Server only (`/api/search`) | `.env.local` | **Secret** (runtime only) |
60
- | `HF_MODEL` | Server only, optional | `.env.local` | **Variable** or **Secret**, optional |
61
-
62
- `NEXT_PUBLIC_*` is inlined into the JS bundle at `next build`. On Spaces, Variables are passed as Docker `ARG`s — that is why they must be Variables, not Secrets. `HUGGINGFACE_API_KEY` and `BRAVE_SEARCH_API_KEY` must stay Secrets so they are not baked into the image.
63
-
64
- Never put a Supabase `service_role` key, a Google client secret, or an Azure client secret in this repo or in Space Variables. OAuth secrets belong only in the Supabase provider forms.
65
-
66
- ```bash
67
- cp .env.example .env.local
68
- ```
69
-
70
- ## Local development
71
-
72
- ```bash
73
- npm install
74
- npm run dev
75
- ```
76
-
77
- Open [http://localhost:3000](http://localhost:3000).
78
-
79
- Supabase Auth URL config:
80
-
81
- - Site URL (production): `https://ashnhash-unihunt.hf.space`
82
- - Redirect URLs (need wildcards — `?next=` is part of the callback):
83
- - `http://localhost:3000/**`
84
- - `https://ashnhash-unihunt.hf.space/**`
85
-
86
- OAuth apps use the **Supabase** callback, not the Next.js one:
87
-
88
- ```
89
- https://qnzkuskdkyqyeglvacqx.supabase.co/auth/v1/callback
90
- ```
91
-
92
- Microsoft: creating an app under a personal account with no Entra directory is deprecated. Create or switch into a directory first ([Entra admin center](https://entra.microsoft.com)), then **App registrations → New registration**. Details are in the [Supabase Azure guide](https://supabase.com/docs/guides/auth/social-login/auth-azure).
93
-
94
- Optional: enable [leaked password protection](https://supabase.com/docs/guides/auth/password-security#password-strength-and-leaked-password-protection) on the Email provider.
95
-
96
- ## Deploy to Hugging Face Spaces
97
-
98
- Spaces builds this repo with the `Dockerfile` and serves the Next.js standalone
99
- server on port **7860**. The YAML block at the top of this file (`sdk: docker`,
100
- `app_port: 7860`) is what the platform reads — do not remove it.
101
-
102
- This repo is already wired to **[ashnhash/UniHunt](https://huggingface.co/spaces/ashnhash/UniHunt)**.
103
- The live app URL is **https://ashnhash-unihunt.hf.space**.
104
-
105
- ### 0. Prerequisites
106
-
107
- - A [Hugging Face](https://huggingface.co/join) account
108
- - This repo building locally (`npm run build`)
109
- - Values from `.env.local`:
110
- - `NEXT_PUBLIC_SUPABASE_URL`
111
- - `NEXT_PUBLIC_SUPABASE_ANON_KEY` (publishable or anon key — never `service_role`)
112
- - `HUGGINGFACE_API_KEY` (token from [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) with Inference permission)
113
- - `BRAVE_SEARCH_API_KEY` (key from [Brave Search API](https://api-dashboard.search.brave.com/app/documentation/web-search/get-started) with Web Search access)
114
- - Git, plus either:
115
- - the [Hugging Face CLI](https://huggingface.co/docs/huggingface_hub/guides/cli) (`pip install huggingface_hub`), or
116
- - a connected GitHub repo (Spaces can pull from GitHub)
117
-
118
- Log the CLI in once:
119
-
120
- ```bash
121
- huggingface-cli login
122
- ```
123
-
124
- Create a **Write** token if the CLI asks for one.
125
-
126
- ### 1. Create the Space
127
-
128
- 1. Open [huggingface.co/new-space](https://huggingface.co/new-space)
129
- 2. **Space name:** e.g. `university-course-finder` (lowercase, hyphens only)
130
- 3. **License:** MIT
131
- 4. **SDK:** **Docker** — not Gradio or Streamlit. A Gradio Space cannot run this Next.js app.
132
- 5. **Hardware:** CPU basic is enough
133
- 6. **Visibility:** Public or Private. Private Spaces still get a public-looking `*.hf.space` URL; anyone with the link can open the app unless you add Space authentication later.
134
- 7. Create the Space and wait until the empty repo page loads
135
-
136
- Do not paste a custom Dockerfile in the website form. This repo already has one.
137
-
138
- ### 2. Put the code on the Space
139
-
140
- This is **already done** for UniHunt (`git remote space` → `main` at
141
- `cbb11bf` and earlier). You only need this section again when you change code.
142
-
143
- Confirm the remote, then push any new commits:
144
-
145
- ```powershell
146
- cd C:\Users\User\Projects\university-course-finder
147
- git remote -v
148
- # should show: space https://huggingface.co/spaces/ashnhash/UniHunt
149
- git push space HEAD:main
150
- ```
151
-
152
- If Git asks for a password, use a Hugging Face **Write** token from
153
- [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens), not
154
- your account password.
155
-
156
- After the push, open [the Space](https://huggingface.co/spaces/ashnhash/UniHunt).
157
- The status pill at the top (Building / Running / Error) and the **Logs** tab
158
- show Docker output. You do **not** need to click anything for a code push —
159
- Spaces starts a new build by itself.
160
-
161
- ### 3. Add Variables and Secrets
162
-
163
- Open **[Space Settings](https://huggingface.co/spaces/ashnhash/UniHunt/settings)**
164
- while logged in as `ashnhash`.
165
-
166
- Scroll until you see **Variables and secrets** (sometimes titled
167
- **Repository secrets** / **App secrets**). There are two add buttons:
168
-
169
- - **New variable** — visible in the UI, passed into `docker build` as `ARG`
170
- - **New secret** — hidden, available to the running container only
171
-
172
- `NEXT_PUBLIC_*` is compiled into the browser bundle during `docker build`.
173
- If you save those as Secrets, the image builds with empty Supabase URLs and
174
- login will fail.
175
-
176
- Click **New variable** for each of these (names must match exactly):
177
-
178
- | Name | Value |
179
- | --- | --- |
180
- | `NEXT_PUBLIC_SUPABASE_URL` | `https://qnzkuskdkyqyeglvacqx.supabase.co` |
181
- | `NEXT_PUBLIC_SUPABASE_ANON_KEY` | publishable key from [Supabase API settings](https://supabase.com/dashboard/project/qnzkuskdkyqyeglvacqx/settings/api) |
182
- | `HF_MODEL` | `meta-llama/Llama-3.3-70B-Instruct` (optional; this is the default) |
183
-
184
- Click **New secret** for:
185
-
186
- | Name | Value |
187
- | --- | --- |
188
- | `HUGGINGFACE_API_KEY` | `hf_…` token with Inference access |
189
- | `BRAVE_SEARCH_API_KEY` | Brave Search API key with Web Search access |
190
-
191
- Do **not** add Google or Azure client secrets here.
192
-
193
- ### 3b. Rebuild after changing Variables (there is no “Factory reboot” on Logs)
194
-
195
- The button is **not** on the Logs tab. Hugging Face has renamed it several
196
- times. Look on **Settings**, in the **Danger zone** / **Runtime** block near
197
- the bottom of
198
- [https://huggingface.co/spaces/ashnhash/UniHunt/settings](https://huggingface.co/spaces/ashnhash/UniHunt/settings).
199
-
200
- You want the control that **rebuilds the Docker image**, not the one that only
201
- restarts the existing container. Current labels you may see:
202
-
203
- | Label | What it does | Use when |
204
- | --- | --- | --- |
205
- | **Factory rebuild** / **Factory reset** / **Factory reboot** | Deletes the old image and runs `docker build` again | You changed a **Variable** (`NEXT_PUBLIC_*`) |
206
- | **Restart this Space** | Starts the **same** image again | You only changed a **Secret** (`HUGGINGFACE_API_KEY`, `BRAVE_SEARCH_API_KEY`) |
207
- | **Pause** | Stops the Space (saves CPU) | You are done for the day |
208
-
209
- A **Restart** will not pick up new `NEXT_PUBLIC_*` values.
210
-
211
- If you cannot see Factory rebuild:
212
-
213
- 1. Confirm you are the Space **owner** (`ashnhash`) and not viewing as a guest
214
- 2. Scroll past Hardware, Sleep time, and Variables — the rebuild control is
215
- usually under **Danger Zone**
216
- 3. Skip the button entirely: make any tiny commit and `git push space HEAD:main`.
217
- A new commit always triggers a full Docker rebuild
218
- 4. Or from a terminal (after `huggingface-cli login`):
219
-
220
- ```powershell
221
- hf spaces restart ashnhash/UniHunt --factory-reboot
222
- ```
223
-
224
- Older CLI: `huggingface-cli` does not always have this flag; the `hf` CLI does.
225
-
226
- Then open **Logs** (top of the Space page, next to App / Files / Community).
227
- You should see a new `===== Build Queued` line and `npm run build`.
228
-
229
- ### 4. Confirm the build
230
-
231
- 1. Status pill becomes **Running** (green)
232
- 2. Open https://ashnhash-unihunt.hf.space — you should see the login page
233
- 3. In Logs, a healthy boot ends with something like `Ready` / `Listening` /
234
- `node server.js` (Next standalone)
235
-
236
- If the build fails:
237
-
238
- | Symptom | Likely cause |
239
- | --- | --- |
240
- | `NEXT_PUBLIC_SUPABASE_URL` empty / Supabase client error | Variables missing, or stored as Secrets |
241
- | `adduser: uid '1000' in use` | Fixed in `cbb11bf` — Spaces should be past this |
242
- | `npm run build` TypeScript errors | Push a commit that builds locally first |
243
- | App runs but search says API key not configured | Add `HUGGINGFACE_API_KEY` and `BRAVE_SEARCH_API_KEY`, then **Restart** (not Factory rebuild) |
244
- | 401 on `/search` after login | Space URL missing from Supabase redirects (step 5) |
245
- | Lands on `https://0.0.0.0:7860/search` after Google | Space is still on a build that used the container bind address. Push the auth callback fix and wait for **Running**. |
246
-
247
- ### 5. Point Supabase Auth at the Space
248
-
249
- 1. Open [URL Configuration](https://supabase.com/dashboard/project/qnzkuskdkyqyeglvacqx/auth/url-configuration)
250
- 2. Set **Site URL** to `https://ashnhash-unihunt.hf.space`
251
- (this is the fallback when a `redirectTo` is rejected — if it stays
252
- `http://localhost:3000`, Space logins bounce back to localhost)
253
- 3. Under **Redirect URLs** add both wildcards (exact `/auth/callback` is not
254
- enough, because the app sends `?next=/search`):
255
-
256
- `http://localhost:3000/**`
257
-
258
- `https://ashnhash-unihunt.hf.space/**`
259
-
260
- 4. Save. Local `npm run dev` still works; Google/Microsoft logins from the
261
- Space stay on the Space.
262
-
263
- OAuth still uses the **Supabase** callback (already on the Google/Azure apps):
264
-
265
- ```
266
- https://qnzkuskdkyqyeglvacqx.supabase.co/auth/v1/callback
267
- ```
268
-
269
- ### 6. Allow the Space origin on Google (and Azure if needed)
270
-
271
- **Google Cloud → APIs & Services → Credentials → your Web client**
272
-
273
- - Authorized JavaScript origins: add `https://ashnhash-unihunt.hf.space`
274
- - Authorized redirect URIs: keep only the Supabase callback above
275
-
276
- **Azure Entra → App registration → Authentication**
277
-
278
- - Web redirect URIs: same Supabase callback only
279
-
280
- ### 7. Smoke-test the live app
281
-
282
- 1. Open https://ashnhash-unihunt.hf.space
283
- 2. Sign in with email, or Google / Microsoft
284
- 3. You should land on `/search`
285
- 4. Run a search — proves `HUGGINGFACE_API_KEY` and `BRAVE_SEARCH_API_KEY`
286
- 5. Shortlist a course and open `/shortlist` — proves Supabase cookies on the Space host
287
-
288
- ### 8. Later updates
289
-
290
- ```powershell
291
- git push space HEAD:main
292
- ```
293
-
294
- - Code-only change → Spaces rebuilds automatically (no button)
295
- - `NEXT_PUBLIC_*` Variable change → **Factory rebuild** on Settings, or push any new commit
296
- - `HUGGINGFACE_API_KEY` or `BRAVE_SEARCH_API_KEY` Secret change → **Restart this Space**
297
- - Space rename → update the Supabase redirect and the Google JS origin again
298
-
299
- ## Project Structure
300
-
301
- ```
302
- src/
303
- app/
304
- api/search/ # Brave-grounded AI search endpoint
305
- api/shortlist/ # Shortlist CRUD + notes PATCH
306
- auth/callback/ # OAuth / email code exchange
307
- login/ # Auth page
308
- search/ # Search route (restores last session)
309
- shortlist/ # Saved courses
310
- lib/
311
- brave.ts # Brave Search API + official URL matching
312
- proxy.ts # Session refresh + route protection
313
- supabase/schema.sql # Database setup (safe to re-run)
314
- Dockerfile # HF Spaces / local Docker
315
- .env.example # Local env template
316
- ```
317
-
318
- `/search` and `/shortlist` load the user on the server, then hand off to client views. `/search` restores the latest `search_sessions` row.
319
-
320
- ## License
321
-
322
- MIT
323
-
 
1
  ---
2
  title: UniHunt
3
+ emoji: 👁
4
+ colorFrom: yellow
5
+ colorTo: gray
6
  sdk: docker
 
7
  pinned: false
8
  license: mit
9
  short_description: Web app to search for courses and universities across world
10
  ---
11
 
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
components.json DELETED
@@ -1,25 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema.json",
3
- "style": "radix-nova",
4
- "rsc": true,
5
- "tsx": true,
6
- "tailwind": {
7
- "config": "",
8
- "css": "src/app/globals.css",
9
- "baseColor": "neutral",
10
- "cssVariables": true,
11
- "prefix": ""
12
- },
13
- "iconLibrary": "lucide",
14
- "rtl": false,
15
- "aliases": {
16
- "components": "@/components",
17
- "utils": "@/lib/utils",
18
- "ui": "@/components/ui",
19
- "lib": "@/lib",
20
- "hooks": "@/hooks"
21
- },
22
- "menuColor": "default",
23
- "menuAccent": "subtle",
24
- "registries": {}
25
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eslint.config.mjs DELETED
@@ -1,18 +0,0 @@
1
- import { defineConfig, globalIgnores } from "eslint/config";
2
- import nextVitals from "eslint-config-next/core-web-vitals";
3
- import nextTs from "eslint-config-next/typescript";
4
-
5
- const eslintConfig = defineConfig([
6
- ...nextVitals,
7
- ...nextTs,
8
- // Override default ignores of eslint-config-next.
9
- globalIgnores([
10
- // Default ignores of eslint-config-next:
11
- ".next/**",
12
- "out/**",
13
- "build/**",
14
- "next-env.d.ts",
15
- ]),
16
- ]);
17
-
18
- export default eslintConfig;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
next.config.ts DELETED
@@ -1,7 +0,0 @@
1
- import type { NextConfig } from "next";
2
-
3
- const nextConfig: NextConfig = {
4
- output: "standalone",
5
- };
6
-
7
- export default nextConfig;
 
 
 
 
 
 
 
 
package-lock.json DELETED
The diff for this file is too large to render. See raw diff
 
package.json DELETED
@@ -1,42 +0,0 @@
1
- {
2
- "name": "university-course-finder",
3
- "version": "0.1.0",
4
- "private": true,
5
- "scripts": {
6
- "dev": "next dev",
7
- "build": "next build",
8
- "start": "next start",
9
- "lint": "eslint"
10
- },
11
- "dependencies": {
12
- "@huggingface/inference": "^4.13.28",
13
- "@supabase/ssr": "^0.12.7",
14
- "@supabase/supabase-js": "^2.116.0",
15
- "@tanstack/react-table": "^9.2.4",
16
- "class-variance-authority": "^0.7.1",
17
- "clsx": "^2.1.1",
18
- "cmdk": "^1.1.1",
19
- "cn": "^0.3.0",
20
- "lucide-react": "^1.45.0",
21
- "next": "16.3.5",
22
- "next-themes": "^0.4.6",
23
- "radix-ui": "^1.6.7",
24
- "react": "19.2.8",
25
- "react-dom": "19.2.8",
26
- "shadcn": "^4.21.0",
27
- "sonner": "^2.0.8",
28
- "tailwind-merge": "^3.7.0",
29
- "tw-animate-css": "^1.4.0",
30
- "zod": "^4.6.4"
31
- },
32
- "devDependencies": {
33
- "@tailwindcss/postcss": "^4",
34
- "@types/node": "^20",
35
- "@types/react": "^19",
36
- "@types/react-dom": "^19",
37
- "eslint": "^9",
38
- "eslint-config-next": "16.3.5",
39
- "tailwindcss": "^4",
40
- "typescript": "^5"
41
- }
42
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
postcss.config.mjs DELETED
@@ -1,7 +0,0 @@
1
- const config = {
2
- plugins: {
3
- "@tailwindcss/postcss": {},
4
- },
5
- };
6
-
7
- export default config;
 
 
 
 
 
 
 
 
public/file.svg DELETED
public/globe.svg DELETED
public/next.svg DELETED
public/vercel.svg DELETED
public/window.svg DELETED
src/app/api/search/route.ts DELETED
@@ -1,64 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import { z } from "zod";
3
- import { searchUniversityCourses } from "@/lib/huggingface";
4
- import type { Json } from "@/lib/supabase/database.types";
5
- import { createClient } from "@/lib/supabase/server";
6
-
7
- export const maxDuration = 180;
8
-
9
- const searchSchema = z.object({
10
- courseLevel: z.string(),
11
- courseType: z.string(),
12
- specialization: z.string(),
13
- countries: z.array(z.string()),
14
- candidateType: z.string(),
15
- lastQualification: z.string(),
16
- lastSchool: z.string(),
17
- curriculum: z.string(),
18
- subjects: z.string(),
19
- grades: z.string(),
20
- budgetMax: z.string(),
21
- additionalNotes: z.string(),
22
- });
23
-
24
- export async function POST(request: Request) {
25
- try {
26
- const supabase = await createClient();
27
- const {
28
- data: { user },
29
- } = await supabase.auth.getUser();
30
-
31
- if (!user) {
32
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
33
- }
34
-
35
- const parsed = searchSchema.safeParse(
36
- await request.json().catch(() => null)
37
- );
38
-
39
- if (!parsed.success) {
40
- return NextResponse.json(
41
- { error: z.prettifyError(parsed.error) },
42
- { status: 400 }
43
- );
44
- }
45
-
46
- const criteria = parsed.data;
47
- const { results, warning } = await searchUniversityCourses(criteria);
48
-
49
- if (results.length > 0) {
50
- await supabase.from("search_sessions").insert({
51
- user_id: user.id,
52
- criteria: criteria as Json,
53
- results: results as unknown as Json,
54
- });
55
- }
56
-
57
- return NextResponse.json({ results, warning });
58
- } catch (error) {
59
- console.error("Search error:", error);
60
- const message =
61
- error instanceof Error ? error.message : "Search failed. Please try again.";
62
- return NextResponse.json({ error: message }, { status: 500 });
63
- }
64
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/shortlist/comments/route.ts DELETED
@@ -1,67 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import { z } from "zod";
3
- import { createClient } from "@/lib/supabase/server";
4
- import { assertAccess, wishlistAccess } from "@/lib/wishlist-access";
5
-
6
- const createSchema = z.object({
7
- courseId: z.string().uuid(),
8
- body: z.string().trim().min(1).max(2000),
9
- });
10
-
11
- export async function GET(request: Request) {
12
- const supabase = await createClient();
13
- const {
14
- data: { user },
15
- } = await supabase.auth.getUser();
16
- if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
17
-
18
- const courseId = new URL(request.url).searchParams.get("courseId");
19
- if (!courseId) return NextResponse.json({ error: "Missing courseId" }, { status: 400 });
20
-
21
- const { data, error } = await supabase
22
- .from("shortlist_comments")
23
- .select("*")
24
- .eq("course_id", courseId)
25
- .order("created_at", { ascending: true });
26
- if (error) return NextResponse.json({ error: error.message }, { status: 500 });
27
- return NextResponse.json({ comments: data ?? [] });
28
- }
29
-
30
- export async function POST(request: Request) {
31
- const supabase = await createClient();
32
- const {
33
- data: { user },
34
- } = await supabase.auth.getUser();
35
- if (!user?.email) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
36
-
37
- const parsed = createSchema.safeParse(await request.json().catch(() => null));
38
- if (!parsed.success) {
39
- return NextResponse.json({ error: z.prettifyError(parsed.error) }, { status: 400 });
40
- }
41
-
42
- const { data: course, error: loadError } = await supabase
43
- .from("shortlisted_courses")
44
- .select("id, user_id")
45
- .eq("id", parsed.data.courseId)
46
- .maybeSingle();
47
- if (loadError) return NextResponse.json({ error: loadError.message }, { status: 500 });
48
- if (!course) return NextResponse.json({ error: "Course not found" }, { status: 404 });
49
-
50
- const access = await wishlistAccess(supabase, course.user_id, user.id, user.email);
51
- if (!assertAccess(access, "comment")) {
52
- return NextResponse.json({ error: "You cannot comment on this wishlist" }, { status: 403 });
53
- }
54
-
55
- const { data, error } = await supabase
56
- .from("shortlist_comments")
57
- .insert({
58
- course_id: course.id,
59
- author_id: user.id,
60
- author_email: user.email.toLowerCase(),
61
- body: parsed.data.body,
62
- })
63
- .select()
64
- .single();
65
- if (error) return NextResponse.json({ error: error.message }, { status: 500 });
66
- return NextResponse.json({ comment: data });
67
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/shortlist/documents/route.ts DELETED
@@ -1,245 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import { z } from "zod";
3
- import { createClient } from "@/lib/supabase/server";
4
- import { assertAccess, ensureDocumentChecklist, wishlistAccess } from "@/lib/wishlist-access";
5
-
6
- const BUCKET = "application-documents";
7
- const MAX_BYTES = 10 * 1024 * 1024;
8
- const ALLOWED_TYPES = new Set([
9
- "application/pdf",
10
- "image/jpeg",
11
- "image/png",
12
- "image/webp",
13
- "application/msword",
14
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
15
- ]);
16
- const ALLOWED_EXTENSIONS = new Set(["pdf", "jpg", "jpeg", "png", "webp", "doc", "docx"]);
17
-
18
- const addSchema = z.object({
19
- courseId: z.string().uuid(),
20
- label: z.string().trim().min(1).max(120),
21
- details: z.string().trim().max(300).optional(),
22
- });
23
-
24
- const clearSchema = z.object({
25
- id: z.string().uuid(),
26
- clearFile: z.literal(true),
27
- });
28
-
29
- function safeFileName(name: string): string {
30
- const base = name.split(/[/\\]/).pop() ?? "document";
31
- const cleaned = base.replace(/[^a-zA-Z0-9._-]/g, "_").replace(/^\.+/, "").slice(0, 80);
32
- return cleaned || "document";
33
- }
34
-
35
- async function loadDocument(
36
- supabase: Awaited<ReturnType<typeof createClient>>,
37
- documentId: string
38
- ) {
39
- const { data, error } = await supabase
40
- .from("application_documents")
41
- .select("*")
42
- .eq("id", documentId)
43
- .maybeSingle();
44
- if (error) throw new Error(error.message);
45
- if (!data) return null;
46
- const { data: course, error: courseError } = await supabase
47
- .from("shortlisted_courses")
48
- .select("user_id")
49
- .eq("id", data.course_id)
50
- .maybeSingle();
51
- if (courseError) throw new Error(courseError.message);
52
- if (!course) return null;
53
- return { document: data, ownerId: course.user_id };
54
- }
55
-
56
- export async function GET(request: Request) {
57
- const supabase = await createClient();
58
- const {
59
- data: { user },
60
- } = await supabase.auth.getUser();
61
- if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
62
-
63
- const params = new URL(request.url).searchParams;
64
- const documentId = params.get("documentId");
65
- if (documentId) {
66
- let loaded: Awaited<ReturnType<typeof loadDocument>>;
67
- try {
68
- loaded = await loadDocument(supabase, documentId);
69
- } catch (error) {
70
- const message = error instanceof Error ? error.message : "Could not open the file";
71
- return NextResponse.json({ error: message }, { status: 500 });
72
- }
73
- if (!loaded?.document.storage_path) {
74
- return NextResponse.json({ error: "No file uploaded" }, { status: 404 });
75
- }
76
- const { data, error } = await supabase.storage
77
- .from(BUCKET)
78
- .createSignedUrl(loaded.document.storage_path, 60);
79
- if (error || !data) {
80
- return NextResponse.json({ error: error?.message ?? "Could not open the file" }, { status: 500 });
81
- }
82
- return NextResponse.json({ url: data.signedUrl, fileName: loaded.document.file_name });
83
- }
84
-
85
- const courseId = params.get("courseId");
86
- if (!courseId) return NextResponse.json({ error: "Missing courseId" }, { status: 400 });
87
-
88
- const { data: course, error: courseError } = await supabase
89
- .from("shortlisted_courses")
90
- .select("id, user_id, course_level, course_type, language, admission_requirements, scholarship_info")
91
- .eq("id", courseId)
92
- .maybeSingle();
93
- if (courseError) return NextResponse.json({ error: courseError.message }, { status: 500 });
94
- if (!course) return NextResponse.json({ error: "Course not found" }, { status: 404 });
95
-
96
- const access = await wishlistAccess(supabase, course.user_id, user.id, user.email);
97
- if (!access) return NextResponse.json({ error: "Course not found" }, { status: 404 });
98
- if (assertAccess(access, "edit")) {
99
- try {
100
- await ensureDocumentChecklist(supabase, course);
101
- } catch (error) {
102
- console.error(error);
103
- }
104
- }
105
-
106
- const { data, error } = await supabase
107
- .from("application_documents")
108
- .select("*")
109
- .eq("course_id", courseId)
110
- .order("created_at", { ascending: true });
111
- if (error) return NextResponse.json({ error: error.message }, { status: 500 });
112
- return NextResponse.json({ documents: data ?? [] });
113
- }
114
-
115
- export async function POST(request: Request) {
116
- const supabase = await createClient();
117
- const {
118
- data: { user },
119
- } = await supabase.auth.getUser();
120
- if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
121
-
122
- const contentType = request.headers.get("content-type") ?? "";
123
- if (contentType.includes("multipart/form-data")) {
124
- const form = await request.formData();
125
- const documentId = String(form.get("documentId") ?? "");
126
- const file = form.get("file");
127
- if (!z.string().uuid().safeParse(documentId).success || !(file instanceof File)) {
128
- return NextResponse.json({ error: "Choose a file for this checklist item" }, { status: 400 });
129
- }
130
- if (file.size <= 0 || file.size > MAX_BYTES) {
131
- return NextResponse.json({ error: "Files must be between 1 byte and 10 MB" }, { status: 400 });
132
- }
133
- const extension = file.name.split(".").pop()?.toLowerCase() ?? "";
134
- if (!ALLOWED_EXTENSIONS.has(extension) || (file.type && !ALLOWED_TYPES.has(file.type))) {
135
- return NextResponse.json(
136
- { error: "Upload a PDF, Word document, or JPEG, PNG, or WebP image" },
137
- { status: 400 }
138
- );
139
- }
140
-
141
- const loaded = await loadDocument(supabase, documentId);
142
- if (!loaded) return NextResponse.json({ error: "Checklist item not found" }, { status: 404 });
143
- const { document, ownerId } = loaded;
144
- const access = await wishlistAccess(supabase, ownerId, user.id, user.email);
145
- if (!assertAccess(access, "edit")) {
146
- return NextResponse.json({ error: "You cannot upload documents here" }, { status: 403 });
147
- }
148
-
149
- const path = `${ownerId}/${document.course_id}/${document.id}/${safeFileName(file.name)}`;
150
- const bytes = new Uint8Array(await file.arrayBuffer());
151
- const { error: uploadError } = await supabase.storage.from(BUCKET).upload(path, bytes, {
152
- contentType: file.type || "application/octet-stream",
153
- upsert: true,
154
- });
155
- if (uploadError) return NextResponse.json({ error: uploadError.message }, { status: 500 });
156
-
157
- if (document.storage_path && document.storage_path !== path) {
158
- await supabase.storage.from(BUCKET).remove([document.storage_path]);
159
- }
160
-
161
- const { data, error } = await supabase
162
- .from("application_documents")
163
- .update({
164
- storage_path: path,
165
- file_name: safeFileName(file.name),
166
- uploaded_by: user.id,
167
- uploaded_at: new Date().toISOString(),
168
- })
169
- .eq("id", document.id)
170
- .select()
171
- .single();
172
- if (error) return NextResponse.json({ error: error.message }, { status: 500 });
173
- return NextResponse.json({ document: data });
174
- }
175
-
176
- const parsed = addSchema.safeParse(await request.json().catch(() => null));
177
- if (!parsed.success) {
178
- return NextResponse.json({ error: z.prettifyError(parsed.error) }, { status: 400 });
179
- }
180
- const { data: course, error: courseError } = await supabase
181
- .from("shortlisted_courses")
182
- .select("id, user_id")
183
- .eq("id", parsed.data.courseId)
184
- .maybeSingle();
185
- if (courseError) return NextResponse.json({ error: courseError.message }, { status: 500 });
186
- if (!course) return NextResponse.json({ error: "Course not found" }, { status: 404 });
187
- const access = await wishlistAccess(supabase, course.user_id, user.id, user.email);
188
- if (!assertAccess(access, "edit")) {
189
- return NextResponse.json({ error: "You cannot edit this checklist" }, { status: 403 });
190
- }
191
-
192
- const { data, error } = await supabase
193
- .from("application_documents")
194
- .insert({
195
- course_id: course.id,
196
- label: parsed.data.label,
197
- details: parsed.data.details ?? null,
198
- required: true,
199
- })
200
- .select()
201
- .single();
202
- if (error) {
203
- if (error.code === "23505") {
204
- return NextResponse.json({ error: "That document is already on the checklist" }, { status: 409 });
205
- }
206
- return NextResponse.json({ error: error.message }, { status: 500 });
207
- }
208
- return NextResponse.json({ document: data });
209
- }
210
-
211
- export async function PATCH(request: Request) {
212
- const supabase = await createClient();
213
- const {
214
- data: { user },
215
- } = await supabase.auth.getUser();
216
- if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
217
-
218
- const parsed = clearSchema.safeParse(await request.json().catch(() => null));
219
- if (!parsed.success) {
220
- return NextResponse.json({ error: z.prettifyError(parsed.error) }, { status: 400 });
221
- }
222
- const loaded = await loadDocument(supabase, parsed.data.id);
223
- if (!loaded) return NextResponse.json({ error: "Checklist item not found" }, { status: 404 });
224
- const { document } = loaded;
225
- const access = await wishlistAccess(supabase, loaded.ownerId, user.id, user.email);
226
- if (!assertAccess(access, "edit")) {
227
- return NextResponse.json({ error: "You cannot edit this checklist" }, { status: 403 });
228
- }
229
- if (document.storage_path) {
230
- await supabase.storage.from(BUCKET).remove([document.storage_path]);
231
- }
232
- const { data, error } = await supabase
233
- .from("application_documents")
234
- .update({
235
- storage_path: null,
236
- file_name: null,
237
- uploaded_by: null,
238
- uploaded_at: null,
239
- })
240
- .eq("id", document.id)
241
- .select()
242
- .single();
243
- if (error) return NextResponse.json({ error: error.message }, { status: 500 });
244
- return NextResponse.json({ document: data });
245
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/shortlist/important-dates/route.ts DELETED
@@ -1,82 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import { z } from "zod";
3
- import { findImportantDates } from "@/lib/important-dates";
4
- import type { Json } from "@/lib/supabase/database.types";
5
- import { createClient } from "@/lib/supabase/server";
6
- import { assertAccess, wishlistAccess } from "@/lib/wishlist-access";
7
-
8
- /** Four Brave queries (1 req/s), up to six page fetches, then one model call. */
9
- export const maxDuration = 120;
10
-
11
- const requestSchema = z.object({
12
- id: z.string().uuid(),
13
- });
14
-
15
- export async function POST(request: Request) {
16
- const supabase = await createClient();
17
- const {
18
- data: { user },
19
- } = await supabase.auth.getUser();
20
-
21
- if (!user) {
22
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
23
- }
24
-
25
- const parsed = requestSchema.safeParse(await request.json().catch(() => null));
26
- if (!parsed.success) {
27
- return NextResponse.json(
28
- { error: z.prettifyError(parsed.error) },
29
- { status: 400 }
30
- );
31
- }
32
-
33
- const { data: course, error: loadError } = await supabase
34
- .from("shortlisted_courses")
35
- .select("*")
36
- .eq("id", parsed.data.id)
37
- .maybeSingle();
38
-
39
- if (loadError) {
40
- return NextResponse.json({ error: loadError.message }, { status: 500 });
41
- }
42
- if (!course) {
43
- return NextResponse.json({ error: "Course not found" }, { status: 404 });
44
- }
45
- const access = await wishlistAccess(supabase, course.user_id, user.id, user.email);
46
- if (!assertAccess(access, "edit")) {
47
- return NextResponse.json({ error: "You cannot refresh dates on this wishlist" }, { status: 403 });
48
- }
49
-
50
- try {
51
- const report = await findImportantDates({
52
- universityName: course.university_name,
53
- courseName: course.course_name,
54
- courseUrl: course.course_url,
55
- country: course.country,
56
- courseLevel: course.course_level,
57
- });
58
-
59
- const { data: updated, error: updateError } = await supabase
60
- .from("shortlisted_courses")
61
- .update({
62
- important_dates: report as unknown as Json,
63
- important_dates_checked_at: report.checkedAt,
64
- })
65
- .eq("id", course.id)
66
- .select()
67
- .single();
68
-
69
- if (updateError) {
70
- return NextResponse.json({ error: updateError.message }, { status: 500 });
71
- }
72
-
73
- return NextResponse.json({ item: updated });
74
- } catch (error) {
75
- console.error("Important dates lookup failed:", error);
76
- const message =
77
- error instanceof Error
78
- ? error.message
79
- : "Could not search the university website. Please try again.";
80
- return NextResponse.json({ error: message }, { status: 500 });
81
- }
82
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/shortlist/route.ts DELETED
@@ -1,249 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import { z } from "zod";
3
- import { classifyCourseFit } from "@/lib/candidate-fit";
4
- import { createClient } from "@/lib/supabase/server";
5
- import { isHttpUrl } from "@/lib/url";
6
- import { assertAccess, ensureDocumentChecklist, wishlistAccess } from "@/lib/wishlist-access";
7
-
8
- /** Postgres unique-violation, raised by the per-user duplicate course index. */
9
- const UNIQUE_VIOLATION = "23505";
10
-
11
- const shortlistSchema = z.object({
12
- university_name: z.string().min(1),
13
- university_location: z.string().optional(),
14
- course_name: z.string().min(1),
15
- course_level: z.string().optional(),
16
- course_type: z.string().optional(),
17
- specialization: z.string().optional(),
18
- country: z.string().optional(),
19
- qs_world_ranking: z.number().nullable().optional(),
20
- tuition_fee: z.string().optional(),
21
- admission_requirements: z.string().optional(),
22
- course_url: z
23
- .string()
24
- .optional()
25
- .refine((value) => !value || isHttpUrl(value), {
26
- message: "course_url must be an http(s) URL",
27
- }),
28
- duration: z.string().optional(),
29
- language: z.string().optional(),
30
- intake_period: z.string().optional(),
31
- scholarship_info: z.string().optional(),
32
- notes: z.string().optional(),
33
- fit: z.enum(["dream", "reach", "target"]).optional(),
34
- fit_reason: z.string().max(500).optional(),
35
- fit_source: z.enum(["auto", "manual"]).optional(),
36
- is_manual: z.boolean().optional(),
37
- });
38
-
39
- const patchSchema = z
40
- .object({
41
- id: z.string().uuid(),
42
- notes: z.string().max(2000).optional(),
43
- fit: z.enum(["dream", "reach", "target"]).optional(),
44
- })
45
- .refine((value) => value.notes !== undefined || value.fit !== undefined, {
46
- message: "Nothing to update",
47
- });
48
-
49
- export async function GET() {
50
- const supabase = await createClient();
51
- const {
52
- data: { user },
53
- } = await supabase.auth.getUser();
54
-
55
- if (!user) {
56
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
57
- }
58
-
59
- const { data, error } = await supabase
60
- .from("shortlisted_courses")
61
- .select("*")
62
- .eq("user_id", user.id)
63
- .order("qs_world_ranking", { ascending: true, nullsFirst: false });
64
-
65
- if (error) {
66
- return NextResponse.json({ error: error.message }, { status: 500 });
67
- }
68
-
69
- return NextResponse.json({ items: data });
70
- }
71
-
72
- export async function POST(request: Request) {
73
- const supabase = await createClient();
74
- const {
75
- data: { user },
76
- } = await supabase.auth.getUser();
77
-
78
- if (!user) {
79
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
80
- }
81
-
82
- const parsed = shortlistSchema.safeParse(await request.json().catch(() => null));
83
-
84
- if (!parsed.success) {
85
- return NextResponse.json(
86
- { error: z.prettifyError(parsed.error) },
87
- { status: 400 }
88
- );
89
- }
90
-
91
- const labelled = parsed.data.fit
92
- ? null
93
- : classifyCourseFit(
94
- {
95
- universityName: parsed.data.university_name,
96
- courseName: parsed.data.course_name,
97
- courseLevel: parsed.data.course_level ?? "",
98
- specialization: parsed.data.specialization ?? "",
99
- qsWorldRanking: parsed.data.qs_world_ranking ?? null,
100
- tuitionFee: parsed.data.tuition_fee ?? "",
101
- admissionRequirements: parsed.data.admission_requirements ?? "",
102
- courseUrl: parsed.data.course_url ?? "",
103
- scholarshipInfo: parsed.data.scholarship_info ?? "",
104
- },
105
- {
106
- courseLevel: parsed.data.course_level ?? "",
107
- courseType: parsed.data.course_type ?? "",
108
- specialization: parsed.data.specialization ?? "",
109
- countries: parsed.data.country ? [parsed.data.country] : [],
110
- candidateType: "",
111
- lastQualification: "",
112
- lastSchool: "",
113
- curriculum: "",
114
- subjects: "",
115
- grades: "",
116
- budgetMax: "",
117
- additionalNotes: "",
118
- }
119
- );
120
-
121
- const { data, error } = await supabase
122
- .from("shortlisted_courses")
123
- .insert({
124
- ...parsed.data,
125
- fit: parsed.data.fit ?? labelled?.fit,
126
- fit_reason: parsed.data.fit_reason ?? labelled?.fitReason,
127
- fit_source: parsed.data.fit ? parsed.data.fit_source ?? "auto" : "auto",
128
- user_id: user.id,
129
- })
130
- .select()
131
- .single();
132
-
133
- if (error) {
134
- if (error.code === UNIQUE_VIOLATION) {
135
- return NextResponse.json(
136
- { error: "This course is already on your wishlist." },
137
- { status: 409 }
138
- );
139
- }
140
- return NextResponse.json({ error: error.message }, { status: 500 });
141
- }
142
-
143
- try {
144
- await ensureDocumentChecklist(supabase, data);
145
- } catch (checklistError) {
146
- console.error("Checklist seed failed:", checklistError);
147
- }
148
-
149
- return NextResponse.json({ item: data });
150
- }
151
-
152
- export async function PATCH(request: Request) {
153
- const supabase = await createClient();
154
- const {
155
- data: { user },
156
- } = await supabase.auth.getUser();
157
-
158
- if (!user) {
159
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
160
- }
161
-
162
- const parsed = patchSchema.safeParse(await request.json().catch(() => null));
163
-
164
- if (!parsed.success) {
165
- return NextResponse.json(
166
- { error: z.prettifyError(parsed.error) },
167
- { status: 400 }
168
- );
169
- }
170
-
171
- const { id, notes, fit } = parsed.data;
172
- const { data: existing, error: loadError } = await supabase
173
- .from("shortlisted_courses")
174
- .select("id, user_id")
175
- .eq("id", id)
176
- .maybeSingle();
177
- if (loadError) {
178
- return NextResponse.json({ error: loadError.message }, { status: 500 });
179
- }
180
- if (!existing) {
181
- return NextResponse.json({ error: "Course not found" }, { status: 404 });
182
- }
183
- const access = await wishlistAccess(supabase, existing.user_id, user.id, user.email);
184
- if (!assertAccess(access, "edit")) {
185
- return NextResponse.json({ error: "You cannot edit this wishlist" }, { status: 403 });
186
- }
187
-
188
- const { data, error } = await supabase
189
- .from("shortlisted_courses")
190
- .update({
191
- ...(notes !== undefined ? { notes } : {}),
192
- ...(fit !== undefined ? { fit, fit_source: "manual" as const } : {}),
193
- })
194
- .eq("id", id)
195
- .select()
196
- .maybeSingle();
197
-
198
- if (error) {
199
- return NextResponse.json({ error: error.message }, { status: 500 });
200
- }
201
-
202
- if (!data) {
203
- return NextResponse.json({ error: "Course not found" }, { status: 404 });
204
- }
205
-
206
- return NextResponse.json({ item: data });
207
- }
208
-
209
- export async function DELETE(request: Request) {
210
- const supabase = await createClient();
211
- const {
212
- data: { user },
213
- } = await supabase.auth.getUser();
214
-
215
- if (!user) {
216
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
217
- }
218
-
219
- const { searchParams } = new URL(request.url);
220
- const id = searchParams.get("id");
221
-
222
- if (!id) {
223
- return NextResponse.json({ error: "Missing id" }, { status: 400 });
224
- }
225
-
226
- const { data: existing, error: loadError } = await supabase
227
- .from("shortlisted_courses")
228
- .select("id, user_id")
229
- .eq("id", id)
230
- .maybeSingle();
231
- if (loadError) {
232
- return NextResponse.json({ error: loadError.message }, { status: 500 });
233
- }
234
- if (!existing) {
235
- return NextResponse.json({ error: "Course not found" }, { status: 404 });
236
- }
237
- const access = await wishlistAccess(supabase, existing.user_id, user.id, user.email);
238
- if (!assertAccess(access, "delete")) {
239
- return NextResponse.json({ error: "You cannot delete courses from this wishlist" }, { status: 403 });
240
- }
241
-
242
- const { error } = await supabase.from("shortlisted_courses").delete().eq("id", id);
243
-
244
- if (error) {
245
- return NextResponse.json({ error: error.message }, { status: 500 });
246
- }
247
-
248
- return NextResponse.json({ success: true });
249
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/shortlist/shares/route.ts DELETED
@@ -1,111 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import { z } from "zod";
3
- import { SHARE_PERMISSIONS } from "@/lib/share-access";
4
- import { createClient } from "@/lib/supabase/server";
5
-
6
- const createSchema = z.object({
7
- email: z.string().trim().email().max(200),
8
- permission: z.enum(SHARE_PERMISSIONS),
9
- });
10
-
11
- const deleteSchema = z.object({
12
- id: z.string().uuid(),
13
- });
14
-
15
- export async function GET() {
16
- const supabase = await createClient();
17
- const {
18
- data: { user },
19
- } = await supabase.auth.getUser();
20
- if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
21
-
22
- const email = user.email?.toLowerCase() ?? "";
23
- const [{ data: outgoing, error: outError }, { data: incoming, error: inError }] =
24
- await Promise.all([
25
- supabase
26
- .from("shortlist_shares")
27
- .select("*")
28
- .eq("owner_id", user.id)
29
- .order("created_at", { ascending: false }),
30
- email
31
- ? supabase
32
- .from("shortlist_shares")
33
- .select("*")
34
- .eq("invite_email", email)
35
- .order("created_at", { ascending: false })
36
- : Promise.resolve({ data: [], error: null }),
37
- ]);
38
-
39
- if (outError || inError) {
40
- return NextResponse.json(
41
- { error: outError?.message ?? inError?.message ?? "Could not load shares" },
42
- { status: 500 }
43
- );
44
- }
45
-
46
- return NextResponse.json({ outgoing: outgoing ?? [], incoming: incoming ?? [] });
47
- }
48
-
49
- export async function POST(request: Request) {
50
- const supabase = await createClient();
51
- const {
52
- data: { user },
53
- } = await supabase.auth.getUser();
54
- if (!user?.email) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
55
-
56
- const parsed = createSchema.safeParse(await request.json().catch(() => null));
57
- if (!parsed.success) {
58
- return NextResponse.json({ error: z.prettifyError(parsed.error) }, { status: 400 });
59
- }
60
-
61
- const invite = parsed.data.email.toLowerCase();
62
- if (invite === user.email.toLowerCase()) {
63
- return NextResponse.json({ error: "You cannot share a wishlist with yourself" }, { status: 400 });
64
- }
65
-
66
- const { count } = await supabase
67
- .from("shortlist_shares")
68
- .select("id", { count: "exact", head: true })
69
- .eq("owner_id", user.id);
70
- if ((count ?? 0) >= 20) {
71
- return NextResponse.json({ error: "You can share with at most 20 people" }, { status: 400 });
72
- }
73
-
74
- const { data, error } = await supabase
75
- .from("shortlist_shares")
76
- .upsert(
77
- {
78
- owner_id: user.id,
79
- owner_email: user.email.toLowerCase(),
80
- invite_email: invite,
81
- permission: parsed.data.permission,
82
- },
83
- { onConflict: "owner_id,invite_email" }
84
- )
85
- .select()
86
- .single();
87
-
88
- if (error) return NextResponse.json({ error: error.message }, { status: 500 });
89
- return NextResponse.json({ share: data });
90
- }
91
-
92
- export async function DELETE(request: Request) {
93
- const supabase = await createClient();
94
- const {
95
- data: { user },
96
- } = await supabase.auth.getUser();
97
- if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
98
-
99
- const parsed = deleteSchema.safeParse(await request.json().catch(() => null));
100
- if (!parsed.success) {
101
- return NextResponse.json({ error: z.prettifyError(parsed.error) }, { status: 400 });
102
- }
103
-
104
- const { error } = await supabase
105
- .from("shortlist_shares")
106
- .delete()
107
- .eq("id", parsed.data.id)
108
- .eq("owner_id", user.id);
109
- if (error) return NextResponse.json({ error: error.message }, { status: 500 });
110
- return NextResponse.json({ success: true });
111
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/auth/callback/route.ts DELETED
@@ -1,20 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import { publicAppOrigin, safeNextPath } from "@/lib/auth";
3
- import { createClient } from "@/lib/supabase/server";
4
-
5
- export async function GET(request: Request) {
6
- const { searchParams } = new URL(request.url);
7
- const origin = publicAppOrigin(request);
8
- const code = searchParams.get("code");
9
- const next = safeNextPath(searchParams.get("next"));
10
-
11
- if (code) {
12
- const supabase = await createClient();
13
- const { error } = await supabase.auth.exchangeCodeForSession(code);
14
- if (!error) {
15
- return NextResponse.redirect(`${origin}${next}`);
16
- }
17
- }
18
-
19
- return NextResponse.redirect(`${origin}/login?error=auth`);
20
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/favicon.ico DELETED
Binary file (25.9 kB)
 
src/app/globals.css DELETED
@@ -1,130 +0,0 @@
1
- @import "tailwindcss";
2
- @import "tw-animate-css";
3
- @import "shadcn/tailwind.css";
4
-
5
- @custom-variant dark (&:is(.dark *));
6
-
7
- @theme inline {
8
- --color-background: var(--background);
9
- --color-foreground: var(--foreground);
10
- --font-sans: var(--font-sans);
11
- --font-mono: var(--font-geist-mono);
12
- --font-heading: var(--font-sans);
13
- --color-sidebar-ring: var(--sidebar-ring);
14
- --color-sidebar-border: var(--sidebar-border);
15
- --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
16
- --color-sidebar-accent: var(--sidebar-accent);
17
- --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
18
- --color-sidebar-primary: var(--sidebar-primary);
19
- --color-sidebar-foreground: var(--sidebar-foreground);
20
- --color-sidebar: var(--sidebar);
21
- --color-chart-5: var(--chart-5);
22
- --color-chart-4: var(--chart-4);
23
- --color-chart-3: var(--chart-3);
24
- --color-chart-2: var(--chart-2);
25
- --color-chart-1: var(--chart-1);
26
- --color-ring: var(--ring);
27
- --color-input: var(--input);
28
- --color-border: var(--border);
29
- --color-destructive: var(--destructive);
30
- --color-accent-foreground: var(--accent-foreground);
31
- --color-accent: var(--accent);
32
- --color-muted-foreground: var(--muted-foreground);
33
- --color-muted: var(--muted);
34
- --color-secondary-foreground: var(--secondary-foreground);
35
- --color-secondary: var(--secondary);
36
- --color-primary-foreground: var(--primary-foreground);
37
- --color-primary: var(--primary);
38
- --color-popover-foreground: var(--popover-foreground);
39
- --color-popover: var(--popover);
40
- --color-card-foreground: var(--card-foreground);
41
- --color-card: var(--card);
42
- --radius-sm: calc(var(--radius) * 0.6);
43
- --radius-md: calc(var(--radius) * 0.8);
44
- --radius-lg: var(--radius);
45
- --radius-xl: calc(var(--radius) * 1.4);
46
- --radius-2xl: calc(var(--radius) * 1.8);
47
- --radius-3xl: calc(var(--radius) * 2.2);
48
- --radius-4xl: calc(var(--radius) * 2.6);
49
- }
50
-
51
- :root {
52
- --background: oklch(1 0 0);
53
- --foreground: oklch(0.145 0 0);
54
- --card: oklch(1 0 0);
55
- --card-foreground: oklch(0.145 0 0);
56
- --popover: oklch(1 0 0);
57
- --popover-foreground: oklch(0.145 0 0);
58
- --primary: oklch(0.205 0 0);
59
- --primary-foreground: oklch(0.985 0 0);
60
- --secondary: oklch(0.97 0 0);
61
- --secondary-foreground: oklch(0.205 0 0);
62
- --muted: oklch(0.97 0 0);
63
- --muted-foreground: oklch(0.556 0 0);
64
- --accent: oklch(0.97 0 0);
65
- --accent-foreground: oklch(0.205 0 0);
66
- --destructive: oklch(0.577 0.245 27.325);
67
- --border: oklch(0.922 0 0);
68
- --input: oklch(0.922 0 0);
69
- --ring: oklch(0.708 0 0);
70
- --chart-1: oklch(0.87 0 0);
71
- --chart-2: oklch(0.556 0 0);
72
- --chart-3: oklch(0.439 0 0);
73
- --chart-4: oklch(0.371 0 0);
74
- --chart-5: oklch(0.269 0 0);
75
- --radius: 0.625rem;
76
- --sidebar: oklch(0.985 0 0);
77
- --sidebar-foreground: oklch(0.145 0 0);
78
- --sidebar-primary: oklch(0.205 0 0);
79
- --sidebar-primary-foreground: oklch(0.985 0 0);
80
- --sidebar-accent: oklch(0.97 0 0);
81
- --sidebar-accent-foreground: oklch(0.205 0 0);
82
- --sidebar-border: oklch(0.922 0 0);
83
- --sidebar-ring: oklch(0.708 0 0);
84
- }
85
-
86
- .dark {
87
- --background: oklch(0.145 0 0);
88
- --foreground: oklch(0.985 0 0);
89
- --card: oklch(0.205 0 0);
90
- --card-foreground: oklch(0.985 0 0);
91
- --popover: oklch(0.205 0 0);
92
- --popover-foreground: oklch(0.985 0 0);
93
- --primary: oklch(0.922 0 0);
94
- --primary-foreground: oklch(0.205 0 0);
95
- --secondary: oklch(0.269 0 0);
96
- --secondary-foreground: oklch(0.985 0 0);
97
- --muted: oklch(0.269 0 0);
98
- --muted-foreground: oklch(0.708 0 0);
99
- --accent: oklch(0.269 0 0);
100
- --accent-foreground: oklch(0.985 0 0);
101
- --destructive: oklch(0.704 0.191 22.216);
102
- --border: oklch(1 0 0 / 10%);
103
- --input: oklch(1 0 0 / 15%);
104
- --ring: oklch(0.556 0 0);
105
- --chart-1: oklch(0.87 0 0);
106
- --chart-2: oklch(0.556 0 0);
107
- --chart-3: oklch(0.439 0 0);
108
- --chart-4: oklch(0.371 0 0);
109
- --chart-5: oklch(0.269 0 0);
110
- --sidebar: oklch(0.205 0 0);
111
- --sidebar-foreground: oklch(0.985 0 0);
112
- --sidebar-primary: oklch(0.488 0.243 264.376);
113
- --sidebar-primary-foreground: oklch(0.985 0 0);
114
- --sidebar-accent: oklch(0.269 0 0);
115
- --sidebar-accent-foreground: oklch(0.985 0 0);
116
- --sidebar-border: oklch(1 0 0 / 10%);
117
- --sidebar-ring: oklch(0.556 0 0);
118
- }
119
-
120
- @layer base {
121
- * {
122
- @apply border-border outline-ring/50;
123
- }
124
- body {
125
- @apply bg-background text-foreground;
126
- }
127
- html {
128
- @apply font-sans;
129
- }
130
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/layout.tsx DELETED
@@ -1,44 +0,0 @@
1
- import type { Metadata, Viewport } from "next";
2
- import { Geist, Geist_Mono } from "next/font/google";
3
- import { Providers } from "./providers";
4
- import "./globals.css";
5
-
6
- const geistSans = Geist({
7
- variable: "--font-geist-sans",
8
- subsets: ["latin"],
9
- });
10
-
11
- const geistMono = Geist_Mono({
12
- variable: "--font-geist-mono",
13
- subsets: ["latin"],
14
- });
15
-
16
- export const metadata: Metadata = {
17
- title: "University Course Finder",
18
- description:
19
- "AI-powered university and course search with personalized shortlisting for students worldwide.",
20
- applicationName: "University Course Finder",
21
- };
22
-
23
- export const viewport: Viewport = {
24
- width: "device-width",
25
- initialScale: 1,
26
- maximumScale: 5,
27
- themeColor: [
28
- { media: "(prefers-color-scheme: light)", color: "#ffffff" },
29
- { media: "(prefers-color-scheme: dark)", color: "#0a0a0a" },
30
- ],
31
- };
32
-
33
- export default function RootLayout({ children }: LayoutProps<"/">) {
34
- return (
35
- <html
36
- lang="en"
37
- className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
38
- >
39
- <body className="min-h-full flex flex-col">
40
- <Providers>{children}</Providers>
41
- </body>
42
- </html>
43
- );
44
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/login/page.tsx DELETED
@@ -1,27 +0,0 @@
1
- import { GraduationCap } from "lucide-react";
2
- import { AuthForm } from "@/components/auth/auth-form";
3
- import { safeNextPath } from "@/lib/auth";
4
-
5
- export default async function LoginPage({
6
- searchParams,
7
- }: {
8
- searchParams: Promise<{ error?: string; redirect?: string }>;
9
- }) {
10
- const params = await searchParams;
11
-
12
- return (
13
- <div className="flex min-h-full flex-col items-center justify-center bg-gradient-to-b from-background to-muted/40 px-4 py-12">
14
- <div className="mb-8 flex flex-col items-center gap-2 text-center">
15
- <GraduationCap className="size-12 text-primary" />
16
- <h1 className="text-3xl font-bold tracking-tight">University Course Finder</h1>
17
- <p className="max-w-md text-muted-foreground">
18
- Discover and shortlist university courses worldwide with AI-powered search
19
- </p>
20
- </div>
21
- <AuthForm
22
- redirectTo={safeNextPath(params.redirect)}
23
- authError={params.error === "auth"}
24
- />
25
- </div>
26
- );
27
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/page.tsx DELETED
@@ -1,11 +0,0 @@
1
- import { redirect } from "next/navigation";
2
- import { createClient } from "@/lib/supabase/server";
3
-
4
- export default async function HomePage() {
5
- const supabase = await createClient();
6
- const {
7
- data: { user },
8
- } = await supabase.auth.getUser();
9
-
10
- redirect(user ? "/search" : "/login");
11
- }
 
 
 
 
 
 
 
 
 
 
 
 
src/app/providers.tsx DELETED
@@ -1,12 +0,0 @@
1
- "use client";
2
-
3
- import { Toaster } from "@/components/ui/sonner";
4
-
5
- export function Providers({ children }: { children: React.ReactNode }) {
6
- return (
7
- <>
8
- {children}
9
- <Toaster richColors position="top-center" />
10
- </>
11
- );
12
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/search/page.tsx DELETED
@@ -1,47 +0,0 @@
1
- import { redirect } from "next/navigation";
2
- import { SearchView } from "@/components/search/search-view";
3
- import { parseSearchCriteria, parseSearchResults } from "@/lib/search-session";
4
- import { createClient } from "@/lib/supabase/server";
5
-
6
- export default async function SearchPage() {
7
- const supabase = await createClient();
8
- const {
9
- data: { user },
10
- } = await supabase.auth.getUser();
11
-
12
- if (!user) {
13
- redirect("/login");
14
- }
15
-
16
- const [{ data: shortlist }, { data: lastSession }] = await Promise.all([
17
- supabase
18
- .from("shortlisted_courses")
19
- .select("university_name, course_name")
20
- .eq("user_id", user.id),
21
- supabase
22
- .from("search_sessions")
23
- .select("criteria, results, created_at")
24
- .eq("user_id", user.id)
25
- .order("created_at", { ascending: false })
26
- .limit(1)
27
- .maybeSingle(),
28
- ]);
29
-
30
- const shortlistedKeys = (shortlist ?? []).map(
31
- (item) => `${item.university_name}|${item.course_name}`
32
- );
33
-
34
- return (
35
- <SearchView
36
- userEmail={user.email ?? null}
37
- shortlistedKeys={shortlistedKeys}
38
- initialCriteria={
39
- lastSession ? parseSearchCriteria(lastSession.criteria) : undefined
40
- }
41
- initialResults={
42
- lastSession ? parseSearchResults(lastSession.results) : undefined
43
- }
44
- lastSearchedAt={lastSession?.created_at ?? null}
45
- />
46
- );
47
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/shortlist/page.tsx DELETED
@@ -1,62 +0,0 @@
1
- import { redirect } from "next/navigation";
2
- import { ShortlistView } from "@/components/shortlist/shortlist-view";
3
- import type { ShortlistAccess } from "@/lib/share-access";
4
- import { createClient } from "@/lib/supabase/server";
5
- import type { ShortlistShare, ShortlistedCourse } from "@/lib/types";
6
-
7
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
-
9
- export default async function ShortlistPage({
10
- searchParams,
11
- }: {
12
- searchParams: Promise<{ owner?: string }>;
13
- }) {
14
- const { owner } = await searchParams;
15
- const supabase = await createClient();
16
- const {
17
- data: { user },
18
- } = await supabase.auth.getUser();
19
-
20
- if (!user) {
21
- redirect("/login");
22
- }
23
-
24
- const email = user.email?.toLowerCase() ?? "";
25
- const [{ data: outgoing }, { data: incoming }] = await Promise.all([
26
- supabase.from("shortlist_shares").select("*").eq("owner_id", user.id),
27
- email
28
- ? supabase.from("shortlist_shares").select("*").eq("invite_email", email)
29
- : Promise.resolve({ data: [] as ShortlistShare[] }),
30
- ]);
31
-
32
- const shared = (incoming ?? []) as ShortlistShare[];
33
- const viewingShared = Boolean(owner && UUID.test(owner) && owner !== user.id);
34
- const grant = viewingShared ? shared.find((share) => share.owner_id === owner) : undefined;
35
- if (viewingShared && !grant) {
36
- redirect("/shortlist");
37
- }
38
-
39
- const ownerId = viewingShared && owner ? owner : user.id;
40
- const { data, error } = await supabase
41
- .from("shortlisted_courses")
42
- .select("*")
43
- .eq("user_id", ownerId)
44
- .order("qs_world_ranking", { ascending: true, nullsFirst: false });
45
-
46
- if (error) {
47
- throw new Error(`Failed to load wishlist: ${error.message}`);
48
- }
49
-
50
- const access: ShortlistAccess = grant ? (grant.permission as ShortlistAccess) : "owner";
51
-
52
- return (
53
- <ShortlistView
54
- userEmail={user.email ?? null}
55
- items={(data ?? []) as ShortlistedCourse[]}
56
- access={access}
57
- ownerEmail={grant?.owner_email ?? null}
58
- outgoing={(outgoing ?? []) as ShortlistShare[]}
59
- incoming={shared.filter((share) => share.owner_id !== user.id)}
60
- />
61
- );
62
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/auth/auth-form.tsx DELETED
@@ -1,179 +0,0 @@
1
- "use client";
2
-
3
- import { useEffect, useState } from "react";
4
- import { useRouter } from "next/navigation";
5
- import { toast } from "sonner";
6
- import { createClient } from "@/lib/supabase/client";
7
- import { Button } from "@/components/ui/button";
8
- import { Input } from "@/components/ui/input";
9
- import { Label } from "@/components/ui/label";
10
- import {
11
- Card,
12
- CardContent,
13
- CardDescription,
14
- CardHeader,
15
- CardTitle,
16
- } from "@/components/ui/card";
17
- import { Separator } from "@/components/ui/separator";
18
-
19
- interface AuthFormProps {
20
- redirectTo?: string;
21
- authError?: boolean;
22
- }
23
-
24
- export function AuthForm({
25
- redirectTo = "/search",
26
- authError = false,
27
- }: AuthFormProps) {
28
- const router = useRouter();
29
- const [isSignUp, setIsSignUp] = useState(false);
30
- const [loading, setLoading] = useState(false);
31
- const [email, setEmail] = useState("");
32
- const [password, setPassword] = useState("");
33
-
34
- useEffect(() => {
35
- if (authError) {
36
- toast.error("Sign-in was cancelled or failed. Please try again.");
37
- }
38
- }, [authError]);
39
-
40
- async function handleEmailAuth(e: React.FormEvent) {
41
- e.preventDefault();
42
- setLoading(true);
43
-
44
- const supabase = createClient();
45
-
46
- try {
47
- if (isSignUp) {
48
- const { error } = await supabase.auth.signUp({
49
- email,
50
- password,
51
- options: {
52
- emailRedirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(redirectTo)}`,
53
- },
54
- });
55
- if (error) throw error;
56
- toast.success("Check your email to confirm your account.");
57
- } else {
58
- const { error } = await supabase.auth.signInWithPassword({
59
- email,
60
- password,
61
- });
62
- if (error) throw error;
63
- router.push(redirectTo);
64
- router.refresh();
65
- }
66
- } catch (error) {
67
- toast.error(error instanceof Error ? error.message : "Authentication failed");
68
- } finally {
69
- setLoading(false);
70
- }
71
- }
72
-
73
- async function handleOAuth(provider: "google" | "azure") {
74
- setLoading(true);
75
- const { error } = await createClient().auth.signInWithOAuth({
76
- provider,
77
- options: {
78
- redirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(redirectTo)}`,
79
- ...(provider === "google"
80
- ? {
81
- queryParams: {
82
- access_type: "offline",
83
- prompt: "select_account",
84
- },
85
- }
86
- : {
87
- // Azure must return a verified email or Supabase Auth rejects the user.
88
- scopes: "email",
89
- }),
90
- },
91
- });
92
- if (error) {
93
- toast.error(error.message);
94
- setLoading(false);
95
- }
96
- }
97
-
98
- return (
99
- <Card className="w-full max-w-md border-border/60 shadow-lg">
100
- <CardHeader className="space-y-1 text-center">
101
- <CardTitle className="text-2xl font-semibold tracking-tight">
102
- {isSignUp ? "Create account" : "Welcome back"}
103
- </CardTitle>
104
- <CardDescription>
105
- Sign in to search universities and manage your shortlist
106
- </CardDescription>
107
- </CardHeader>
108
- <CardContent className="space-y-4">
109
- <div className="grid gap-2">
110
- <Button
111
- type="button"
112
- variant="outline"
113
- disabled={loading}
114
- onClick={() => handleOAuth("google")}
115
- className="w-full"
116
- >
117
- Continue with Google
118
- </Button>
119
- <Button
120
- type="button"
121
- variant="outline"
122
- disabled={loading}
123
- onClick={() => handleOAuth("azure")}
124
- className="w-full"
125
- >
126
- Continue with Microsoft
127
- </Button>
128
- </div>
129
-
130
- <div className="relative">
131
- <Separator />
132
- <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-card px-2 text-xs text-muted-foreground">
133
- or use email
134
- </span>
135
- </div>
136
-
137
- <form onSubmit={handleEmailAuth} className="space-y-4">
138
- <div className="space-y-2">
139
- <Label htmlFor="email">Email</Label>
140
- <Input
141
- id="email"
142
- type="email"
143
- placeholder="you@example.com"
144
- value={email}
145
- onChange={(e) => setEmail(e.target.value)}
146
- required
147
- />
148
- </div>
149
- <div className="space-y-2">
150
- <Label htmlFor="password">Password</Label>
151
- <Input
152
- id="password"
153
- type="password"
154
- placeholder="••••••••"
155
- value={password}
156
- onChange={(e) => setPassword(e.target.value)}
157
- required
158
- minLength={6}
159
- />
160
- </div>
161
- <Button type="submit" className="w-full" disabled={loading}>
162
- {loading ? "Please wait..." : isSignUp ? "Sign up" : "Sign in"}
163
- </Button>
164
- </form>
165
-
166
- <p className="text-center text-sm text-muted-foreground">
167
- {isSignUp ? "Already have an account?" : "Don't have an account?"}{" "}
168
- <button
169
- type="button"
170
- className="font-medium text-primary underline-offset-4 hover:underline"
171
- onClick={() => setIsSignUp(!isSignUp)}
172
- >
173
- {isSignUp ? "Sign in" : "Create one"}
174
- </button>
175
- </p>
176
- </CardContent>
177
- </Card>
178
- );
179
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/layout/app-header.tsx DELETED
@@ -1,105 +0,0 @@
1
- "use client";
2
-
3
- import Link from "next/link";
4
- import { usePathname, useRouter } from "next/navigation";
5
- import { GraduationCap, LogOut, Menu, Search, Star } from "lucide-react";
6
- import { toast } from "sonner";
7
- import { createClient } from "@/lib/supabase/client";
8
- import { Button } from "@/components/ui/button";
9
- import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
10
- import { cn } from "@/lib/utils";
11
-
12
- const navItems = [
13
- { href: "/search", label: "Search", icon: Search },
14
- { href: "/shortlist", label: "Wishlist", icon: Star },
15
- ];
16
-
17
- function NavLinks({
18
- pathname,
19
- mobile = false,
20
- }: {
21
- pathname: string;
22
- mobile?: boolean;
23
- }) {
24
- return (
25
- <>
26
- {navItems.map(({ href, label, icon: Icon }) => (
27
- <Link
28
- key={href}
29
- href={href}
30
- className={cn(
31
- "flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
32
- pathname === href
33
- ? "bg-primary text-primary-foreground"
34
- : "text-muted-foreground hover:bg-muted hover:text-foreground",
35
- mobile && "text-base"
36
- )}
37
- >
38
- <Icon className="size-4" />
39
- {label}
40
- </Link>
41
- ))}
42
- </>
43
- );
44
- }
45
-
46
- interface AppHeaderProps {
47
- userEmail?: string | null;
48
- }
49
-
50
- export function AppHeader({ userEmail }: AppHeaderProps) {
51
- const pathname = usePathname();
52
- const router = useRouter();
53
-
54
- async function handleSignOut() {
55
- await createClient().auth.signOut();
56
- toast.success("Signed out");
57
- router.push("/login");
58
- router.refresh();
59
- }
60
-
61
- return (
62
- <header className="sticky top-0 z-50 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80">
63
- <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4 sm:px-6">
64
- <Link href="/search" className="flex items-center gap-2 font-semibold">
65
- <GraduationCap className="size-6 text-primary" />
66
- <span className="hidden sm:inline">University Course Finder</span>
67
- <span className="sm:hidden">UCF</span>
68
- </Link>
69
-
70
- <nav className="hidden items-center gap-1 md:flex">
71
- <NavLinks pathname={pathname} />
72
- </nav>
73
-
74
- <div className="flex items-center gap-2">
75
- {userEmail && (
76
- <span className="hidden max-w-[180px] truncate text-xs text-muted-foreground lg:inline">
77
- {userEmail}
78
- </span>
79
- )}
80
- <Button variant="ghost" size="sm" onClick={handleSignOut} className="hidden sm:flex">
81
- <LogOut className="size-4" />
82
- Sign out
83
- </Button>
84
-
85
- <Sheet>
86
- <SheetTrigger asChild>
87
- <Button variant="outline" size="icon" className="md:hidden">
88
- <Menu className="size-4" />
89
- </Button>
90
- </SheetTrigger>
91
- <SheetContent side="right" className="w-72">
92
- <div className="mt-8 flex flex-col gap-2">
93
- <NavLinks pathname={pathname} mobile />
94
- <Button variant="outline" onClick={handleSignOut} className="mt-4">
95
- <LogOut className="size-4" />
96
- Sign out
97
- </Button>
98
- </div>
99
- </SheetContent>
100
- </Sheet>
101
- </div>
102
- </div>
103
- </header>
104
- );
105
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/search/country-multi-select.tsx DELETED
@@ -1,98 +0,0 @@
1
- "use client";
2
-
3
- import { useState } from "react";
4
- import { Check, ChevronsUpDown, X } from "lucide-react";
5
- import { COUNTRIES } from "@/lib/countries";
6
- import { cn } from "@/lib/utils";
7
- import { Badge } from "@/components/ui/badge";
8
- import { Button } from "@/components/ui/button";
9
- import {
10
- Command,
11
- CommandEmpty,
12
- CommandGroup,
13
- CommandInput,
14
- CommandItem,
15
- CommandList,
16
- } from "@/components/ui/command";
17
- import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
18
-
19
- interface CountryMultiSelectProps {
20
- selected: string[];
21
- onChange: (countries: string[]) => void;
22
- }
23
-
24
- export function CountryMultiSelect({ selected, onChange }: CountryMultiSelectProps) {
25
- const [open, setOpen] = useState(false);
26
-
27
- function toggleCountry(country: string) {
28
- if (selected.includes(country)) {
29
- onChange(selected.filter((c) => c !== country));
30
- } else {
31
- onChange([...selected, country]);
32
- }
33
- }
34
-
35
- return (
36
- <div className="space-y-2">
37
- <Popover open={open} onOpenChange={setOpen}>
38
- <PopoverTrigger asChild>
39
- <Button
40
- variant="outline"
41
- role="combobox"
42
- aria-expanded={open}
43
- className="h-auto min-h-9 w-full justify-between font-normal"
44
- >
45
- <span className="truncate text-left">
46
- {selected.length === 0
47
- ? "Select countries..."
48
- : `${selected.length} countr${selected.length === 1 ? "y" : "ies"} selected`}
49
- </span>
50
- <ChevronsUpDown className="ml-2 size-4 shrink-0 opacity-50" />
51
- </Button>
52
- </PopoverTrigger>
53
- <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
54
- <Command>
55
- <CommandInput placeholder="Search countries..." />
56
- <CommandList>
57
- <CommandEmpty>No country found.</CommandEmpty>
58
- <CommandGroup>
59
- {COUNTRIES.map((country) => (
60
- <CommandItem
61
- key={country}
62
- value={country}
63
- onSelect={() => toggleCountry(country)}
64
- >
65
- <Check
66
- className={cn(
67
- "mr-2 size-4",
68
- selected.includes(country) ? "opacity-100" : "opacity-0"
69
- )}
70
- />
71
- {country}
72
- </CommandItem>
73
- ))}
74
- </CommandGroup>
75
- </CommandList>
76
- </Command>
77
- </PopoverContent>
78
- </Popover>
79
-
80
- {selected.length > 0 && (
81
- <div className="flex flex-wrap gap-1.5">
82
- {selected.map((country) => (
83
- <Badge key={country} variant="secondary" className="gap-1 pr-1">
84
- {country}
85
- <button
86
- type="button"
87
- onClick={() => toggleCountry(country)}
88
- className="rounded-full p-0.5 hover:bg-muted"
89
- >
90
- <X className="size-3" />
91
- </button>
92
- </Badge>
93
- ))}
94
- </div>
95
- )}
96
- </div>
97
- );
98
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/search/results-table.tsx DELETED
@@ -1,355 +0,0 @@
1
- "use client";
2
-
3
- import { useMemo, useState } from "react";
4
- import {
5
- columnFilteringFeature,
6
- createCoreRowModel,
7
- createFilteredRowModel,
8
- createSortedRowModel,
9
- filterFn_includesString,
10
- flexRender,
11
- globalFilteringFeature,
12
- rowSelectionFeature,
13
- rowSortingFeature,
14
- tableFeatures,
15
- useTable,
16
- type ColumnDef,
17
- type RowSelectionState,
18
- type SortingState,
19
- } from "@tanstack/react-table";
20
- import { ArrowUpDown, ExternalLink, Star } from "lucide-react";
21
- import { toast } from "sonner";
22
- import { classifyCourseFit } from "@/lib/candidate-fit";
23
- import { compareRanking } from "@/lib/ranking";
24
- import type { SearchCriteria, UniversityCourseResult } from "@/lib/types";
25
- import { FitBadge } from "@/components/shortlist/fit-badge";
26
- import { Button } from "@/components/ui/button";
27
- import { Input } from "@/components/ui/input";
28
- import { Checkbox } from "@/components/ui/checkbox";
29
- import {
30
- Table,
31
- TableBody,
32
- TableCell,
33
- TableHead,
34
- TableHeader,
35
- TableRow,
36
- } from "@/components/ui/table";
37
- import {
38
- Card,
39
- CardContent,
40
- CardDescription,
41
- CardHeader,
42
- CardTitle,
43
- } from "@/components/ui/card";
44
-
45
- const features = tableFeatures({
46
- columnFilteringFeature,
47
- globalFilteringFeature,
48
- rowSelectionFeature,
49
- rowSortingFeature,
50
- coreRowModel: createCoreRowModel(),
51
- filteredRowModel: createFilteredRowModel(),
52
- sortedRowModel: createSortedRowModel(),
53
- });
54
-
55
- const WRAP_COLUMN_IDS = new Set([
56
- "universityLocation",
57
- "tuitionFee",
58
- "admissionRequirements",
59
- ]);
60
-
61
- type ResultColumn = ColumnDef<typeof features, UniversityCourseResult>;
62
-
63
- interface ResultsTableProps {
64
- results: UniversityCourseResult[];
65
- criteria: SearchCriteria;
66
- shortlistedIds: Set<string>;
67
- onShortlist: (course: UniversityCourseResult) => Promise<void>;
68
- restored?: boolean;
69
- }
70
-
71
- export function ResultsTable({
72
- results,
73
- criteria,
74
- shortlistedIds,
75
- onShortlist,
76
- restored = false,
77
- }: ResultsTableProps) {
78
- const [sorting, setSorting] = useState<SortingState>([]);
79
- const [globalFilter, setGlobalFilter] = useState("");
80
- const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
81
- const [adding, setAdding] = useState(false);
82
-
83
- const columns = useMemo<ResultColumn[]>(
84
- () => [
85
- {
86
- id: "select",
87
- header: ({ table }) => (
88
- <Checkbox
89
- checked={
90
- table.getIsAllRowsSelected() ||
91
- (table.getIsSomeRowsSelected() && "indeterminate")
92
- }
93
- onCheckedChange={(value) => table.toggleAllRowsSelected(!!value)}
94
- aria-label="Select all"
95
- />
96
- ),
97
- cell: ({ row }) => (
98
- <Checkbox
99
- checked={row.getIsSelected()}
100
- onCheckedChange={(value) => row.toggleSelected(!!value)}
101
- aria-label="Select row"
102
- />
103
- ),
104
- enableSorting: false,
105
- },
106
- {
107
- accessorKey: "qsWorldRanking",
108
- header: ({ column }) => (
109
- <Button
110
- variant="ghost"
111
- size="sm"
112
- className="-ml-2"
113
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
114
- >
115
- QS Rank
116
- <ArrowUpDown className="size-3.5" />
117
- </Button>
118
- ),
119
- cell: ({ getValue }) => getValue<number | null>() ?? "—",
120
- sortFn: (a, b) =>
121
- compareRanking(a.original.qsWorldRanking, b.original.qsWorldRanking),
122
- },
123
- {
124
- accessorKey: "universityName",
125
- header: ({ column }) => (
126
- <Button
127
- variant="ghost"
128
- size="sm"
129
- className="-ml-2"
130
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
131
- >
132
- University
133
- <ArrowUpDown className="size-3.5" />
134
- </Button>
135
- ),
136
- },
137
- {
138
- accessorKey: "universityLocation",
139
- header: "Location",
140
- cell: ({ getValue }) => (
141
- <span className="block max-w-[16rem] whitespace-pre-wrap break-words leading-snug">
142
- {getValue<string>() || "—"}
143
- </span>
144
- ),
145
- },
146
- {
147
- accessorKey: "courseName",
148
- header: "Course",
149
- },
150
- {
151
- id: "fit",
152
- header: "Fit",
153
- accessorFn: (row) => row.fit ?? classifyCourseFit(row, criteria).fit,
154
- cell: ({ row }) => {
155
- const labelled = row.original.fit
156
- ? { fit: row.original.fit, fitReason: row.original.fitReason ?? "" }
157
- : classifyCourseFit(row.original, criteria);
158
- return <FitBadge fit={labelled.fit} reason={labelled.fitReason} />;
159
- },
160
- },
161
- {
162
- accessorKey: "courseLevel",
163
- header: "Level",
164
- },
165
- {
166
- accessorKey: "specialization",
167
- header: "Specialization",
168
- },
169
- {
170
- accessorKey: "country",
171
- header: "Country",
172
- },
173
- {
174
- accessorKey: "tuitionFee",
175
- header: "Tuition Fee",
176
- cell: ({ getValue }) => (
177
- <span className="block max-w-[18rem] whitespace-pre-wrap break-words leading-snug">
178
- {getValue<string>() || "—"}
179
- </span>
180
- ),
181
- },
182
- {
183
- accessorKey: "duration",
184
- header: "Duration",
185
- },
186
- {
187
- accessorKey: "admissionRequirements",
188
- header: "Admission Req.",
189
- cell: ({ getValue }) => (
190
- <span className="block max-w-[22rem] whitespace-pre-wrap break-words leading-snug">
191
- {getValue<string>() || "—"}
192
- </span>
193
- ),
194
- },
195
- {
196
- accessorKey: "courseUrl",
197
- header: "URL",
198
- cell: ({ getValue }) => {
199
- const url = getValue<string>();
200
- if (!url) return "—";
201
- return (
202
- <a
203
- href={url}
204
- target="_blank"
205
- rel="noopener noreferrer"
206
- className="inline-flex items-center gap-1 text-primary hover:underline"
207
- >
208
- Link
209
- <ExternalLink className="size-3" />
210
- </a>
211
- );
212
- },
213
- enableSorting: false,
214
- },
215
- {
216
- id: "actions",
217
- header: "Wishlist",
218
- cell: ({ row }) => {
219
- const course = row.original;
220
- const isShortlisted = shortlistedIds.has(course.id);
221
- return (
222
- <Button
223
- variant={isShortlisted ? "secondary" : "outline"}
224
- size="sm"
225
- disabled={isShortlisted || adding}
226
- onClick={async () => {
227
- try {
228
- await onShortlist(course);
229
- } catch {
230
- toast.error("Failed to add to wishlist");
231
- }
232
- }}
233
- >
234
- <Star className="size-3.5" />
235
- {isShortlisted ? "Added" : "Add"}
236
- </Button>
237
- );
238
- },
239
- enableSorting: false,
240
- },
241
- ],
242
- [shortlistedIds, adding, onShortlist, criteria]
243
- );
244
-
245
- const table = useTable({
246
- features,
247
- data: results,
248
- columns,
249
- state: { sorting, globalFilter, rowSelection },
250
- onSortingChange: setSorting,
251
- onGlobalFilterChange: setGlobalFilter,
252
- onRowSelectionChange: setRowSelection,
253
- globalFilterFn: filterFn_includesString,
254
- getRowId: (row) => row.id,
255
- });
256
-
257
- const selectedCourses = table
258
- .getFilteredSelectedRowModel()
259
- .rows.map((row) => row.original);
260
-
261
- async function handleBulkShortlist() {
262
- if (selectedCourses.length === 0) return;
263
- setAdding(true);
264
- try {
265
- for (const course of selectedCourses) {
266
- if (!shortlistedIds.has(course.id)) {
267
- await onShortlist(course);
268
- }
269
- }
270
- setRowSelection({});
271
- toast.success(`Added ${selectedCourses.length} course(s) to wishlist`);
272
- } catch {
273
- toast.error("Failed to add some courses to wishlist");
274
- } finally {
275
- setAdding(false);
276
- }
277
- }
278
-
279
- if (results.length === 0) return null;
280
-
281
- return (
282
- <Card>
283
- <CardHeader>
284
- <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
285
- <div>
286
- <CardTitle>Search Results</CardTitle>
287
- <CardDescription>
288
- {results.length} universities found — ordered by your grades, budget, subjects, and qualification, then labelled Dream, Reach, or Target
289
- {restored ? ". Showing your last search until you run a new one." : ""}
290
- </CardDescription>
291
- </div>
292
- <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
293
- <Input
294
- placeholder="Filter results..."
295
- value={globalFilter}
296
- onChange={(e) => setGlobalFilter(e.target.value)}
297
- className="max-w-xs"
298
- />
299
- {selectedCourses.length > 0 && (
300
- <Button onClick={handleBulkShortlist} disabled={adding}>
301
- <Star />
302
- Shortlist selected ({selectedCourses.length})
303
- </Button>
304
- )}
305
- </div>
306
- </div>
307
- </CardHeader>
308
- <CardContent>
309
- <div className="rounded-md border">
310
- <Table>
311
- <TableHeader>
312
- {table.getHeaderGroups().map((headerGroup) => (
313
- <TableRow key={headerGroup.id}>
314
- {headerGroup.headers.map((header) => (
315
- <TableHead key={header.id}>
316
- {header.isPlaceholder
317
- ? null
318
- : flexRender(header.column.columnDef.header, header.getContext())}
319
- </TableHead>
320
- ))}
321
- </TableRow>
322
- ))}
323
- </TableHeader>
324
- <TableBody>
325
- {table.getRowModel().rows.length ? (
326
- table.getRowModel().rows.map((row) => (
327
- <TableRow key={row.id} data-state={row.getIsSelected() && "selected"}>
328
- {row.getAllCells().map((cell) => (
329
- <TableCell
330
- key={cell.id}
331
- className={
332
- WRAP_COLUMN_IDS.has(cell.column.id)
333
- ? "max-w-[22rem] whitespace-normal align-top"
334
- : undefined
335
- }
336
- >
337
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
338
- </TableCell>
339
- ))}
340
- </TableRow>
341
- ))
342
- ) : (
343
- <TableRow>
344
- <TableCell colSpan={columns.length} className="h-24 text-center">
345
- No results match your filter.
346
- </TableCell>
347
- </TableRow>
348
- )}
349
- </TableBody>
350
- </Table>
351
- </div>
352
- </CardContent>
353
- </Card>
354
- );
355
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/search/search-form.tsx DELETED
@@ -1,268 +0,0 @@
1
- "use client";
2
-
3
- import { Loader2, Sparkles } from "lucide-react";
4
- import type { SearchCriteria } from "@/lib/types";
5
- import {
6
- CANDIDATE_TYPES,
7
- COURSE_LEVELS,
8
- COURSE_TYPES,
9
- MAX_SEARCH_COUNTRIES,
10
- } from "@/lib/constants";
11
- import { Button } from "@/components/ui/button";
12
- import { Input } from "@/components/ui/input";
13
- import { Label } from "@/components/ui/label";
14
- import { Textarea } from "@/components/ui/textarea";
15
- import {
16
- Select,
17
- SelectContent,
18
- SelectItem,
19
- SelectTrigger,
20
- SelectValue,
21
- } from "@/components/ui/select";
22
- import {
23
- Card,
24
- CardContent,
25
- CardDescription,
26
- CardHeader,
27
- CardTitle,
28
- } from "@/components/ui/card";
29
- import { CountryMultiSelect } from "./country-multi-select";
30
-
31
- interface SearchFormProps {
32
- criteria: SearchCriteria;
33
- onChange: (criteria: SearchCriteria) => void;
34
- onSearch: () => void;
35
- loading: boolean;
36
- restoredAt?: string | null;
37
- warning?: string | null;
38
- }
39
-
40
- export function SearchForm({
41
- criteria,
42
- onChange,
43
- onSearch,
44
- loading,
45
- restoredAt,
46
- warning,
47
- }: SearchFormProps) {
48
- function update<K extends keyof SearchCriteria>(key: K, value: SearchCriteria[K]) {
49
- onChange({ ...criteria, [key]: value });
50
- }
51
-
52
- return (
53
- <Card>
54
- <CardHeader>
55
- <CardTitle className="flex items-center gap-2">
56
- <Sparkles className="size-5 text-primary" />
57
- Course Search Criteria
58
- </CardTitle>
59
- <CardDescription>
60
- Fill in your preferences and candidate details. Grades, subjects, qualification,
61
- curriculum, and budget are all used, and each course is labelled Dream, Reach, or Target.
62
- Each selected country is searched independently, then results are combined.
63
- {restoredAt
64
- ? ` Last search restored from ${new Date(restoredAt).toLocaleString()}.`
65
- : null}
66
- </CardDescription>
67
- </CardHeader>
68
- <CardContent>
69
- <form
70
- onSubmit={(e) => {
71
- e.preventDefault();
72
- onSearch();
73
- }}
74
- className="grid gap-6"
75
- >
76
- <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
77
- <div className="space-y-2">
78
- <Label>Course Level</Label>
79
- <Select
80
- value={criteria.courseLevel || undefined}
81
- onValueChange={(v) => update("courseLevel", v as SearchCriteria["courseLevel"])}
82
- >
83
- <SelectTrigger className="w-full">
84
- <SelectValue placeholder="Select level" />
85
- </SelectTrigger>
86
- <SelectContent>
87
- {COURSE_LEVELS.map((level) => (
88
- <SelectItem key={level} value={level}>
89
- {level}
90
- </SelectItem>
91
- ))}
92
- </SelectContent>
93
- </Select>
94
- </div>
95
-
96
- <div className="space-y-2">
97
- <Label>Course Type</Label>
98
- <Select
99
- value={criteria.courseType || undefined}
100
- onValueChange={(v) => update("courseType", v as SearchCriteria["courseType"])}
101
- >
102
- <SelectTrigger className="w-full">
103
- <SelectValue placeholder="Select type" />
104
- </SelectTrigger>
105
- <SelectContent>
106
- {COURSE_TYPES.map((type) => (
107
- <SelectItem key={type} value={type}>
108
- {type}
109
- </SelectItem>
110
- ))}
111
- </SelectContent>
112
- </Select>
113
- </div>
114
-
115
- <div className="space-y-2">
116
- <Label htmlFor="specialization">Specialization</Label>
117
- <Input
118
- id="specialization"
119
- placeholder="e.g. Robotics and Mechatronics"
120
- value={criteria.specialization}
121
- onChange={(e) => update("specialization", e.target.value)}
122
- />
123
- </div>
124
- </div>
125
-
126
- <div className="grid gap-4 sm:grid-cols-2">
127
- <div className="space-y-2">
128
- <Label>Countries (multi-select)</Label>
129
- <CountryMultiSelect
130
- selected={criteria.countries}
131
- onChange={(countries) => update("countries", countries)}
132
- />
133
- <p
134
- className={
135
- criteria.countries.length > MAX_SEARCH_COUNTRIES
136
- ? "text-xs text-amber-700 dark:text-amber-300"
137
- : "text-xs text-muted-foreground"
138
- }
139
- >
140
- Each country is searched separately. Select at most{" "}
141
- {MAX_SEARCH_COUNTRIES} countries.
142
- </p>
143
- </div>
144
-
145
- <div className="space-y-2">
146
- <Label>Candidate Type</Label>
147
- <Select
148
- value={criteria.candidateType || undefined}
149
- onValueChange={(v) =>
150
- update("candidateType", v as SearchCriteria["candidateType"])
151
- }
152
- >
153
- <SelectTrigger className="w-full">
154
- <SelectValue placeholder="Select candidate type" />
155
- </SelectTrigger>
156
- <SelectContent>
157
- {CANDIDATE_TYPES.map(({ value, label }) => (
158
- <SelectItem key={value} value={value}>
159
- {label}
160
- </SelectItem>
161
- ))}
162
- </SelectContent>
163
- </Select>
164
- </div>
165
- </div>
166
-
167
- <div className="rounded-lg border bg-muted/30 p-4">
168
- <h3 className="mb-4 text-sm font-medium">Candidate Background</h3>
169
- <div className="grid gap-4 sm:grid-cols-2">
170
- <div className="space-y-2">
171
- <Label htmlFor="lastQualification">Last Qualification</Label>
172
- <Input
173
- id="lastQualification"
174
- placeholder="e.g. High School Diploma, B.Tech"
175
- value={criteria.lastQualification}
176
- onChange={(e) => update("lastQualification", e.target.value)}
177
- />
178
- </div>
179
- <div className="space-y-2">
180
- <Label htmlFor="lastSchool">Last School / College</Label>
181
- <Input
182
- id="lastSchool"
183
- placeholder="Institution name"
184
- value={criteria.lastSchool}
185
- onChange={(e) => update("lastSchool", e.target.value)}
186
- />
187
- </div>
188
- <div className="space-y-2">
189
- <Label htmlFor="curriculum">Curriculum</Label>
190
- <Input
191
- id="curriculum"
192
- placeholder="e.g. IB, CBSE, A-Levels, AP"
193
- value={criteria.curriculum}
194
- onChange={(e) => update("curriculum", e.target.value)}
195
- />
196
- </div>
197
- <div className="space-y-2">
198
- <Label htmlFor="subjects">Subjects / Courses</Label>
199
- <Input
200
- id="subjects"
201
- placeholder="e.g. Physics, Math, Chemistry"
202
- value={criteria.subjects}
203
- onChange={(e) => update("subjects", e.target.value)}
204
- />
205
- </div>
206
- <div className="space-y-2">
207
- <Label htmlFor="grades">Grades / GPA / CGPA</Label>
208
- <Input
209
- id="grades"
210
- placeholder="e.g. 3.8 GPA, 85%, AAB"
211
- value={criteria.grades}
212
- onChange={(e) => update("grades", e.target.value)}
213
- />
214
- </div>
215
- <div className="space-y-2">
216
- <Label htmlFor="budgetMax">Max Annual Budget (USD)</Label>
217
- <Input
218
- id="budgetMax"
219
- type="number"
220
- min="0"
221
- placeholder="e.g. 25000"
222
- value={criteria.budgetMax}
223
- onChange={(e) => update("budgetMax", e.target.value)}
224
- />
225
- </div>
226
- </div>
227
- </div>
228
-
229
- <div className="space-y-2">
230
- <Label htmlFor="additionalNotes">Additional Notes</Label>
231
- <Textarea
232
- id="additionalNotes"
233
- placeholder="Any other preferences: campus size, research focus, work opportunities..."
234
- value={criteria.additionalNotes}
235
- onChange={(e) => update("additionalNotes", e.target.value)}
236
- rows={3}
237
- />
238
- </div>
239
-
240
- {warning ? (
241
- <div
242
- role="alert"
243
- className="rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-950 dark:text-amber-100"
244
- >
245
- {warning}
246
- </div>
247
- ) : null}
248
-
249
- <Button type="submit" size="lg" disabled={loading} className="w-full sm:w-auto">
250
- {loading ? (
251
- <>
252
- <Loader2 className="animate-spin" />
253
- {criteria.countries.length > 1
254
- ? "Searching each country..."
255
- : "Searching..."}
256
- </>
257
- ) : (
258
- <>
259
- <Sparkles />
260
- Find Universities & Courses
261
- </>
262
- )}
263
- </Button>
264
- </form>
265
- </CardContent>
266
- </Card>
267
- );
268
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/search/search-view.tsx DELETED
@@ -1,162 +0,0 @@
1
- "use client";
2
-
3
- import { useCallback, useState } from "react";
4
- import { toast } from "sonner";
5
- import { AppHeader } from "@/components/layout/app-header";
6
- import { SearchForm } from "@/components/search/search-form";
7
- import { ResultsTable } from "@/components/search/results-table";
8
- import { DEFAULT_SEARCH_CRITERIA, MAX_SEARCH_COUNTRIES, tooManyCountriesWarning } from "@/lib/constants";
9
- import type { SearchCriteria, UniversityCourseResult } from "@/lib/types";
10
-
11
- interface SearchViewProps {
12
- userEmail: string | null;
13
- /** Identity keys of courses already on the user's shortlist, from the server. */
14
- shortlistedKeys: string[];
15
- initialCriteria?: SearchCriteria;
16
- initialResults?: UniversityCourseResult[];
17
- lastSearchedAt?: string | null;
18
- }
19
-
20
- /**
21
- * Must stay in step with the shortlisted_courses_user_course_idx unique index,
22
- * which ignores the URL — otherwise the button state and the API disagree about
23
- * what counts as already saved.
24
- */
25
- function courseKey(course: UniversityCourseResult) {
26
- return `${course.universityName}|${course.courseName}`;
27
- }
28
-
29
- export function SearchView({
30
- userEmail,
31
- shortlistedKeys,
32
- initialCriteria,
33
- initialResults,
34
- lastSearchedAt,
35
- }: SearchViewProps) {
36
- const [criteria, setCriteria] = useState<SearchCriteria>(
37
- initialCriteria ?? DEFAULT_SEARCH_CRITERIA
38
- );
39
- const [results, setResults] = useState<UniversityCourseResult[]>(
40
- initialResults ?? []
41
- );
42
- const [restoredAt, setRestoredAt] = useState<string | null>(
43
- lastSearchedAt ?? null
44
- );
45
- const [loading, setLoading] = useState(false);
46
- const [searchWarning, setSearchWarning] = useState<string | null>(null);
47
- const [savedKeys, setSavedKeys] = useState<Set<string>>(
48
- () => new Set(shortlistedKeys)
49
- );
50
-
51
- async function handleSearch() {
52
- setLoading(true);
53
- setResults([]);
54
- setRestoredAt(null);
55
- setSearchWarning(null);
56
- try {
57
- if (criteria.countries.length > MAX_SEARCH_COUNTRIES) {
58
- const warning = tooManyCountriesWarning(criteria.countries.length);
59
- setSearchWarning(warning);
60
- toast.warning(warning);
61
- return;
62
- }
63
-
64
- const res = await fetch("/api/search", {
65
- method: "POST",
66
- headers: { "Content-Type": "application/json" },
67
- body: JSON.stringify(criteria),
68
- });
69
- const data = await res.json();
70
- if (!res.ok) throw new Error(data.error ?? "Search failed");
71
- if (data.warning && (!Array.isArray(data.results) || data.results.length === 0)) {
72
- setSearchWarning(data.warning);
73
- toast.warning(data.warning);
74
- setResults([]);
75
- return;
76
- }
77
- setResults(data.results);
78
- if (data.warning) {
79
- setSearchWarning(data.warning);
80
- toast.warning(data.warning);
81
- }
82
- toast.success(`Found ${data.results.length} matching courses`);
83
- } catch (error) {
84
- toast.error(error instanceof Error ? error.message : "Search failed");
85
- } finally {
86
- setLoading(false);
87
- }
88
- }
89
-
90
- const handleShortlist = useCallback(
91
- async (course: UniversityCourseResult) => {
92
- const key = courseKey(course);
93
- if (savedKeys.has(key)) return;
94
-
95
- const res = await fetch("/api/shortlist", {
96
- method: "POST",
97
- headers: { "Content-Type": "application/json" },
98
- body: JSON.stringify({
99
- university_name: course.universityName,
100
- university_location: course.universityLocation,
101
- course_name: course.courseName,
102
- course_level: course.courseLevel,
103
- course_type: course.courseType,
104
- specialization: course.specialization,
105
- country: course.country,
106
- qs_world_ranking: course.qsWorldRanking,
107
- tuition_fee: course.tuitionFee,
108
- admission_requirements: course.admissionRequirements,
109
- course_url: course.courseUrl,
110
- duration: course.duration,
111
- language: course.language,
112
- intake_period: course.intakePeriod,
113
- scholarship_info: course.scholarshipInfo,
114
- fit: course.fit,
115
- fit_reason: course.fitReason,
116
- fit_source: course.fit ? "auto" : undefined,
117
- is_manual: false,
118
- }),
119
- });
120
-
121
- // A conflict means it is already saved, so the button should still settle
122
- // into the "Added" state rather than reporting a failure.
123
- if (!res.ok && res.status !== 409) {
124
- const data = await res.json();
125
- throw new Error(data.error ?? "Failed to shortlist");
126
- }
127
-
128
- setSavedKeys((prev) => new Set(prev).add(key));
129
- toast.success(
130
- res.status === 409 ? "Already on your wishlist" : "Added to wishlist"
131
- );
132
- },
133
- [savedKeys]
134
- );
135
-
136
- const shortlistedIds = new Set(
137
- results.filter((r) => savedKeys.has(courseKey(r))).map((r) => r.id)
138
- );
139
-
140
- return (
141
- <div className="min-h-full bg-muted/20">
142
- <AppHeader userEmail={userEmail} />
143
- <main className="mx-auto max-w-7xl space-y-8 px-4 py-8 sm:px-6">
144
- <SearchForm
145
- criteria={criteria}
146
- onChange={setCriteria}
147
- onSearch={handleSearch}
148
- loading={loading}
149
- restoredAt={restoredAt}
150
- warning={searchWarning}
151
- />
152
- <ResultsTable
153
- results={results}
154
- criteria={criteria}
155
- shortlistedIds={shortlistedIds}
156
- onShortlist={handleShortlist}
157
- restored={Boolean(restoredAt && results.length > 0)}
158
- />
159
- </main>
160
- </div>
161
- );
162
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/shortlist/add-manual-dialog.tsx DELETED
@@ -1,219 +0,0 @@
1
- "use client";
2
-
3
- import { useState } from "react";
4
- import { Plus } from "lucide-react";
5
- import { toast } from "sonner";
6
- import type { ShortlistInsert } from "@/lib/types";
7
- import { Button } from "@/components/ui/button";
8
- import { Input } from "@/components/ui/input";
9
- import { Label } from "@/components/ui/label";
10
- import { Textarea } from "@/components/ui/textarea";
11
- import {
12
- Dialog,
13
- DialogContent,
14
- DialogDescription,
15
- DialogFooter,
16
- DialogHeader,
17
- DialogTitle,
18
- DialogTrigger,
19
- } from "@/components/ui/dialog";
20
-
21
- interface AddManualDialogProps {
22
- onAdd: (item: ShortlistInsert) => Promise<void>;
23
- }
24
-
25
- const emptyForm: ShortlistInsert = {
26
- university_name: "",
27
- university_location: "",
28
- course_name: "",
29
- course_level: "",
30
- course_type: "",
31
- specialization: "",
32
- country: "",
33
- qs_world_ranking: null,
34
- tuition_fee: "",
35
- admission_requirements: "",
36
- course_url: "",
37
- duration: "",
38
- language: "",
39
- intake_period: "",
40
- scholarship_info: "",
41
- notes: "",
42
- is_manual: true,
43
- };
44
-
45
- export function AddManualDialog({ onAdd }: AddManualDialogProps) {
46
- const [open, setOpen] = useState(false);
47
- const [loading, setLoading] = useState(false);
48
- const [form, setForm] = useState<ShortlistInsert>(emptyForm);
49
-
50
- function update(field: keyof ShortlistInsert, value: string | number | null | boolean) {
51
- setForm((prev) => ({ ...prev, [field]: value }));
52
- }
53
-
54
- async function handleSubmit(e: React.FormEvent) {
55
- e.preventDefault();
56
- if (!form.university_name.trim() || !form.course_name.trim()) {
57
- toast.error("University name and course name are required");
58
- return;
59
- }
60
-
61
- setLoading(true);
62
- try {
63
- await onAdd(form);
64
- toast.success("Added to wishlist");
65
- setForm(emptyForm);
66
- setOpen(false);
67
- } catch (error) {
68
- toast.error(error instanceof Error ? error.message : "Failed to add course");
69
- } finally {
70
- setLoading(false);
71
- }
72
- }
73
-
74
- return (
75
- <Dialog open={open} onOpenChange={setOpen}>
76
- <DialogTrigger asChild>
77
- <Button>
78
- <Plus />
79
- Add manually
80
- </Button>
81
- </DialogTrigger>
82
- <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
83
- <DialogHeader>
84
- <DialogTitle>Add university manually</DialogTitle>
85
- <DialogDescription>
86
- Add a course you discovered outside the AI search results.
87
- </DialogDescription>
88
- </DialogHeader>
89
- <form onSubmit={handleSubmit} className="grid gap-4 py-2">
90
- <div className="grid gap-4 sm:grid-cols-2">
91
- <div className="space-y-2 sm:col-span-2">
92
- <Label htmlFor="uni-name">University Name *</Label>
93
- <Input
94
- id="uni-name"
95
- value={form.university_name}
96
- onChange={(e) => update("university_name", e.target.value)}
97
- required
98
- />
99
- </div>
100
- <div className="space-y-2 sm:col-span-2">
101
- <Label htmlFor="course-name">Course Name *</Label>
102
- <Input
103
- id="course-name"
104
- value={form.course_name}
105
- onChange={(e) => update("course_name", e.target.value)}
106
- required
107
- />
108
- </div>
109
- <div className="space-y-2">
110
- <Label htmlFor="location">Location</Label>
111
- <Input
112
- id="location"
113
- value={form.university_location ?? ""}
114
- onChange={(e) => update("university_location", e.target.value)}
115
- />
116
- </div>
117
- <div className="space-y-2">
118
- <Label htmlFor="country">Country</Label>
119
- <Input
120
- id="country"
121
- value={form.country ?? ""}
122
- onChange={(e) => update("country", e.target.value)}
123
- />
124
- </div>
125
- <div className="space-y-2">
126
- <Label htmlFor="qs">QS World Ranking</Label>
127
- <Input
128
- id="qs"
129
- type="number"
130
- value={form.qs_world_ranking ?? ""}
131
- onChange={(e) =>
132
- update(
133
- "qs_world_ranking",
134
- e.target.value ? Number(e.target.value) : null
135
- )
136
- }
137
- />
138
- </div>
139
- <div className="space-y-2">
140
- <Label htmlFor="tuition">Tuition Fee</Label>
141
- <Input
142
- id="tuition"
143
- value={form.tuition_fee ?? ""}
144
- onChange={(e) => update("tuition_fee", e.target.value)}
145
- />
146
- </div>
147
- <div className="space-y-2">
148
- <Label htmlFor="duration">Duration</Label>
149
- <Input
150
- id="duration"
151
- placeholder="e.g. 4 years"
152
- value={form.duration ?? ""}
153
- onChange={(e) => update("duration", e.target.value)}
154
- />
155
- </div>
156
- <div className="space-y-2">
157
- <Label htmlFor="language">Language</Label>
158
- <Input
159
- id="language"
160
- placeholder="e.g. English"
161
- value={form.language ?? ""}
162
- onChange={(e) => update("language", e.target.value)}
163
- />
164
- </div>
165
- <div className="space-y-2">
166
- <Label htmlFor="intake">Intake Period</Label>
167
- <Input
168
- id="intake"
169
- placeholder="e.g. Fall 2026"
170
- value={form.intake_period ?? ""}
171
- onChange={(e) => update("intake_period", e.target.value)}
172
- />
173
- </div>
174
- <div className="space-y-2">
175
- <Label htmlFor="scholarship">Scholarships</Label>
176
- <Input
177
- id="scholarship"
178
- value={form.scholarship_info ?? ""}
179
- onChange={(e) => update("scholarship_info", e.target.value)}
180
- />
181
- </div>
182
- <div className="space-y-2 sm:col-span-2">
183
- <Label htmlFor="url">Course URL</Label>
184
- <Input
185
- id="url"
186
- type="url"
187
- value={form.course_url ?? ""}
188
- onChange={(e) => update("course_url", e.target.value)}
189
- />
190
- </div>
191
- <div className="space-y-2 sm:col-span-2">
192
- <Label htmlFor="requirements">Admission Requirements</Label>
193
- <Textarea
194
- id="requirements"
195
- value={form.admission_requirements ?? ""}
196
- onChange={(e) => update("admission_requirements", e.target.value)}
197
- rows={2}
198
- />
199
- </div>
200
- <div className="space-y-2 sm:col-span-2">
201
- <Label htmlFor="notes">Notes</Label>
202
- <Textarea
203
- id="notes"
204
- value={form.notes ?? ""}
205
- onChange={(e) => update("notes", e.target.value)}
206
- rows={2}
207
- />
208
- </div>
209
- </div>
210
- <DialogFooter>
211
- <Button type="submit" disabled={loading}>
212
- {loading ? "Adding..." : "Add to wishlist"}
213
- </Button>
214
- </DialogFooter>
215
- </form>
216
- </DialogContent>
217
- </Dialog>
218
- );
219
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/shortlist/course-details-dialog.tsx DELETED
@@ -1,204 +0,0 @@
1
- "use client";
2
-
3
- import { useState } from "react";
4
- import { ExternalLink, NotebookPen } from "lucide-react";
5
- import { toast } from "sonner";
6
- import type { ShortlistComment, ShortlistedCourse } from "@/lib/types";
7
- import { Button } from "@/components/ui/button";
8
- import { Label } from "@/components/ui/label";
9
- import { Textarea } from "@/components/ui/textarea";
10
- import {
11
- Dialog,
12
- DialogContent,
13
- DialogDescription,
14
- DialogFooter,
15
- DialogHeader,
16
- DialogTitle,
17
- DialogTrigger,
18
- } from "@/components/ui/dialog";
19
-
20
- interface CourseDetailsDialogProps {
21
- course: ShortlistedCourse;
22
- onSaveNotes: (id: string, notes: string) => Promise<void>;
23
- canEdit?: boolean;
24
- canComment?: boolean;
25
- }
26
-
27
- function DetailRow({ label, value }: { label: string; value: string | null }) {
28
- return (
29
- <div className="grid grid-cols-3 gap-2 py-1.5">
30
- <dt className="text-sm text-muted-foreground">{label}</dt>
31
- <dd className="col-span-2 text-sm whitespace-pre-wrap break-words">
32
- {value?.trim() || "—"}
33
- </dd>
34
- </div>
35
- );
36
- }
37
-
38
- export function CourseDetailsDialog({
39
- course,
40
- onSaveNotes,
41
- canEdit = true,
42
- canComment = true,
43
- }: CourseDetailsDialogProps) {
44
- const [open, setOpen] = useState(false);
45
- const [notes, setNotes] = useState(course.notes ?? "");
46
- const [saving, setSaving] = useState(false);
47
- const [comments, setComments] = useState<ShortlistComment[]>([]);
48
- const [comment, setComment] = useState("");
49
- const [commenting, setCommenting] = useState(false);
50
-
51
- // Reset on open rather than in an effect, so the textarea always reflects the
52
- // latest saved notes without triggering a cascading render.
53
- function handleOpenChange(next: boolean) {
54
- if (next) {
55
- setNotes(course.notes ?? "");
56
- void fetch(`/api/shortlist/comments?courseId=${course.id}`)
57
- .then(async (res) => {
58
- const data = await res.json();
59
- if (res.ok) setComments(data.comments ?? []);
60
- })
61
- .catch(() => undefined);
62
- }
63
- setOpen(next);
64
- }
65
-
66
- async function handleComment(event: React.FormEvent) {
67
- event.preventDefault();
68
- setCommenting(true);
69
- try {
70
- const res = await fetch("/api/shortlist/comments", {
71
- method: "POST",
72
- headers: { "Content-Type": "application/json" },
73
- body: JSON.stringify({ courseId: course.id, body: comment }),
74
- });
75
- const data = await res.json();
76
- if (!res.ok) throw new Error(data.error ?? "Could not add the comment");
77
- setComments((current) => [...current, data.comment]);
78
- setComment("");
79
- } catch (error) {
80
- toast.error(error instanceof Error ? error.message : "Could not add the comment");
81
- } finally {
82
- setCommenting(false);
83
- }
84
- }
85
-
86
- async function handleSave() {
87
- setSaving(true);
88
- try {
89
- await onSaveNotes(course.id, notes);
90
- toast.success("Notes saved");
91
- setOpen(false);
92
- } catch (error) {
93
- toast.error(error instanceof Error ? error.message : "Failed to save notes");
94
- } finally {
95
- setSaving(false);
96
- }
97
- }
98
-
99
- return (
100
- <Dialog open={open} onOpenChange={handleOpenChange}>
101
- <DialogTrigger asChild>
102
- <Button
103
- variant={course.notes?.trim() ? "secondary" : "ghost"}
104
- size="icon-sm"
105
- aria-label={`Details and notes for ${course.course_name}`}
106
- >
107
- <NotebookPen className="size-4" />
108
- </Button>
109
- </DialogTrigger>
110
- <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
111
- <DialogHeader>
112
- <DialogTitle>{course.course_name}</DialogTitle>
113
- <DialogDescription>
114
- {course.university_name}
115
- {course.university_location ? ` — ${course.university_location}` : ""}
116
- </DialogDescription>
117
- </DialogHeader>
118
-
119
- <dl className="divide-y">
120
- <DetailRow label="Level" value={course.course_level} />
121
- <DetailRow label="Type" value={course.course_type} />
122
- <DetailRow label="Specialization" value={course.specialization} />
123
- <DetailRow label="Country" value={course.country} />
124
- <DetailRow
125
- label="QS Ranking"
126
- value={course.qs_world_ranking?.toString() ?? null}
127
- />
128
- <DetailRow label="Tuition" value={course.tuition_fee} />
129
- <DetailRow label="Duration" value={course.duration} />
130
- <DetailRow label="Language" value={course.language} />
131
- <DetailRow label="Intake" value={course.intake_period} />
132
- <DetailRow label="Scholarships" value={course.scholarship_info} />
133
- <DetailRow label="Requirements" value={course.admission_requirements} />
134
- <DetailRow label="Why this fit" value={course.fit_reason} />
135
- </dl>
136
-
137
- {course.course_url && (
138
- <a
139
- href={course.course_url}
140
- target="_blank"
141
- rel="noopener noreferrer"
142
- className="inline-flex items-center gap-1 text-sm text-primary hover:underline"
143
- >
144
- Official course page
145
- <ExternalLink className="size-3" />
146
- </a>
147
- )}
148
-
149
- <div className="space-y-2">
150
- <Label htmlFor={`notes-${course.id}`}>Your notes</Label>
151
- <Textarea
152
- id={`notes-${course.id}`}
153
- value={notes}
154
- onChange={(e) => setNotes(e.target.value)}
155
- rows={4}
156
- maxLength={2000}
157
- disabled={!canEdit}
158
- placeholder="Deadlines, contacts, why this one appeals to you…"
159
- />
160
- </div>
161
-
162
- <div className="space-y-2">
163
- <Label>Comments</Label>
164
- <ul className="space-y-2">
165
- {comments.map((item) => (
166
- <li key={item.id} className="rounded-md bg-muted/50 p-2 text-sm">
167
- <p className="text-xs text-muted-foreground">
168
- {item.author_email} · {new Date(item.created_at).toLocaleString()}
169
- </p>
170
- <p className="whitespace-pre-wrap break-words">{item.body}</p>
171
- </li>
172
- ))}
173
- {comments.length === 0 && (
174
- <li className="text-xs text-muted-foreground">No comments yet.</li>
175
- )}
176
- </ul>
177
- {canComment && (
178
- <form onSubmit={handleComment} className="space-y-2">
179
- <Textarea
180
- value={comment}
181
- onChange={(event) => setComment(event.target.value)}
182
- rows={2}
183
- maxLength={2000}
184
- placeholder="Leave a note for the applicant"
185
- required
186
- />
187
- <Button type="submit" variant="secondary" disabled={commenting}>
188
- {commenting ? "Posting…" : "Add comment"}
189
- </Button>
190
- </form>
191
- )}
192
- </div>
193
-
194
- {canEdit && (
195
- <DialogFooter>
196
- <Button onClick={handleSave} disabled={saving}>
197
- {saving ? "Saving..." : "Save notes"}
198
- </Button>
199
- </DialogFooter>
200
- )}
201
- </DialogContent>
202
- </Dialog>
203
- );
204
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/shortlist/documents-dialog.tsx DELETED
@@ -1,200 +0,0 @@
1
- "use client";
2
-
3
- import { useState } from "react";
4
- import { ExternalLink, FileUp, FolderOpen, Loader2 } from "lucide-react";
5
- import { toast } from "sonner";
6
- import type { ApplicationDocument } from "@/lib/types";
7
- import { Badge } from "@/components/ui/badge";
8
- import { Button } from "@/components/ui/button";
9
- import { Input } from "@/components/ui/input";
10
- import {
11
- Dialog,
12
- DialogContent,
13
- DialogDescription,
14
- DialogHeader,
15
- DialogTitle,
16
- DialogTrigger,
17
- } from "@/components/ui/dialog";
18
-
19
- interface DocumentsDialogProps {
20
- courseId: string;
21
- courseName: string;
22
- canEdit: boolean;
23
- }
24
-
25
- export function DocumentsDialog({ courseId, courseName, canEdit }: DocumentsDialogProps) {
26
- const [open, setOpen] = useState(false);
27
- const [documents, setDocuments] = useState<ApplicationDocument[]>([]);
28
- const [loading, setLoading] = useState(false);
29
- const [uploadingId, setUploadingId] = useState<string | null>(null);
30
- const [label, setLabel] = useState("");
31
-
32
- async function load() {
33
- setLoading(true);
34
- try {
35
- const res = await fetch(`/api/shortlist/documents?courseId=${courseId}`);
36
- const data = await res.json();
37
- if (!res.ok) throw new Error(data.error ?? "Could not load documents");
38
- setDocuments(data.documents ?? []);
39
- } catch (error) {
40
- toast.error(error instanceof Error ? error.message : "Could not load documents");
41
- } finally {
42
- setLoading(false);
43
- }
44
- }
45
-
46
- function handleOpen(next: boolean) {
47
- setOpen(next);
48
- if (next) void load();
49
- }
50
-
51
- async function upload(documentId: string, file: File | undefined) {
52
- if (!file) return;
53
- setUploadingId(documentId);
54
- try {
55
- const body = new FormData();
56
- body.set("documentId", documentId);
57
- body.set("file", file);
58
- const res = await fetch("/api/shortlist/documents", { method: "POST", body });
59
- const data = await res.json();
60
- if (!res.ok) throw new Error(data.error ?? "Upload failed");
61
- setDocuments((current) =>
62
- current.map((item) => (item.id === data.document.id ? data.document : item))
63
- );
64
- toast.success("Document uploaded");
65
- } catch (error) {
66
- toast.error(error instanceof Error ? error.message : "Upload failed");
67
- } finally {
68
- setUploadingId(null);
69
- }
70
- }
71
-
72
- async function openFile(documentId: string) {
73
- const res = await fetch(`/api/shortlist/documents?documentId=${documentId}`);
74
- const data = await res.json();
75
- if (!res.ok) {
76
- toast.error(data.error ?? "Could not open the file");
77
- return;
78
- }
79
- window.open(data.url, "_blank", "noopener,noreferrer");
80
- }
81
-
82
- async function clearFile(documentId: string) {
83
- const res = await fetch("/api/shortlist/documents", {
84
- method: "PATCH",
85
- headers: { "Content-Type": "application/json" },
86
- body: JSON.stringify({ id: documentId, clearFile: true }),
87
- });
88
- const data = await res.json();
89
- if (!res.ok) {
90
- toast.error(data.error ?? "Could not remove the file");
91
- return;
92
- }
93
- setDocuments((current) =>
94
- current.map((item) => (item.id === data.document.id ? data.document : item))
95
- );
96
- }
97
-
98
- async function addItem(event: React.FormEvent) {
99
- event.preventDefault();
100
- const res = await fetch("/api/shortlist/documents", {
101
- method: "POST",
102
- headers: { "Content-Type": "application/json" },
103
- body: JSON.stringify({ courseId, label }),
104
- });
105
- const data = await res.json();
106
- if (!res.ok) {
107
- toast.error(data.error ?? "Could not add the document");
108
- return;
109
- }
110
- setDocuments((current) => [...current, data.document]);
111
- setLabel("");
112
- }
113
-
114
- const uploaded = documents.filter((item) => item.storage_path).length;
115
-
116
- return (
117
- <Dialog open={open} onOpenChange={handleOpen}>
118
- <DialogTrigger asChild>
119
- <Button variant="ghost" size="icon-sm" aria-label={`Application documents for ${courseName}`}>
120
- <FolderOpen className="size-4" />
121
- </Button>
122
- </DialogTrigger>
123
- <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-xl">
124
- <DialogHeader>
125
- <DialogTitle>Application documents</DialogTitle>
126
- <DialogDescription>
127
- {courseName}. {uploaded} of {documents.length || "…"} uploaded.
128
- </DialogDescription>
129
- </DialogHeader>
130
- {loading ? (
131
- <div className="flex items-center gap-2 text-sm">
132
- <Loader2 className="size-4 animate-spin" />
133
- Loading checklist…
134
- </div>
135
- ) : (
136
- <ul className="space-y-3">
137
- {documents.map((item) => (
138
- <li key={item.id} className="rounded-md border p-3">
139
- <div className="flex flex-wrap items-center gap-2">
140
- <p className="text-sm font-medium">{item.label}</p>
141
- <Badge variant={item.required ? "secondary" : "outline"}>
142
- {item.required ? "Required" : "Optional"}
143
- </Badge>
144
- {item.file_name && <Badge variant="outline">Uploaded</Badge>}
145
- </div>
146
- {item.details && <p className="mt-1 text-xs text-muted-foreground">{item.details}</p>}
147
- <div className="mt-2 flex flex-wrap items-center gap-2">
148
- {item.file_name && (
149
- <Button variant="link" size="sm" className="h-auto px-0" onClick={() => openFile(item.id)}>
150
- {item.file_name}
151
- <ExternalLink className="size-3" />
152
- </Button>
153
- )}
154
- {canEdit && (
155
- <>
156
- <label className="inline-flex cursor-pointer items-center gap-1 text-xs text-primary hover:underline">
157
- <FileUp className="size-3" />
158
- {uploadingId === item.id ? "Uploading…" : item.file_name ? "Replace" : "Upload"}
159
- <input
160
- type="file"
161
- className="sr-only"
162
- accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,application/pdf,image/jpeg,image/png,image/webp"
163
- disabled={uploadingId === item.id}
164
- onChange={(event) => {
165
- const file = event.target.files?.[0];
166
- event.target.value = "";
167
- void upload(item.id, file);
168
- }}
169
- />
170
- </label>
171
- {item.file_name && (
172
- <Button variant="ghost" size="sm" onClick={() => clearFile(item.id)}>
173
- Remove file
174
- </Button>
175
- )}
176
- </>
177
- )}
178
- </div>
179
- </li>
180
- ))}
181
- </ul>
182
- )}
183
- {canEdit && !loading && (
184
- <form onSubmit={addItem} className="flex gap-2 border-t pt-3">
185
- <Input
186
- value={label}
187
- onChange={(event) => setLabel(event.target.value)}
188
- placeholder="Add another document"
189
- maxLength={120}
190
- required
191
- />
192
- <Button type="submit" variant="secondary">
193
- Add
194
- </Button>
195
- </form>
196
- )}
197
- </DialogContent>
198
- </Dialog>
199
- );
200
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/shortlist/fit-badge.tsx DELETED
@@ -1,23 +0,0 @@
1
- import { fitLabel, type FitCategory } from "@/lib/candidate-fit";
2
- import { Badge } from "@/components/ui/badge";
3
-
4
- const FIT_CLASS: Record<FitCategory, string> = {
5
- dream: "bg-violet-100 text-violet-950 dark:bg-violet-900/40 dark:text-violet-100",
6
- reach: "bg-amber-100 text-amber-950 dark:bg-amber-900/40 dark:text-amber-100",
7
- target: "bg-emerald-100 text-emerald-950 dark:bg-emerald-900/40 dark:text-emerald-100",
8
- };
9
-
10
- export function FitBadge({
11
- fit,
12
- reason,
13
- }: {
14
- fit: FitCategory | null | undefined;
15
- reason?: string | null;
16
- }) {
17
- if (!fit) return <span className="text-muted-foreground">—</span>;
18
- return (
19
- <Badge className={FIT_CLASS[fit]} title={reason ?? undefined}>
20
- {fitLabel(fit)}
21
- </Badge>
22
- );
23
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/shortlist/important-dates-dialog.tsx DELETED
@@ -1,423 +0,0 @@
1
- "use client";
2
-
3
- import { useState } from "react";
4
- import {
5
- CalendarClock,
6
- CalendarPlus,
7
- CalendarSearch,
8
- Download,
9
- ExternalLink,
10
- Loader2,
11
- RefreshCw,
12
- } from "lucide-react";
13
- import { toast } from "sonner";
14
- import {
15
- buildIcs,
16
- calendarEventFromDate,
17
- downloadIcs,
18
- googleCalendarUrl,
19
- icsFilename,
20
- outlookCalendarUrl,
21
- type CalendarEvent,
22
- } from "@/lib/calendar-links";
23
- import { importantDateCategoryLabel } from "@/lib/important-dates-format";
24
- import type {
25
- ImportantDate,
26
- ImportantDateCategory,
27
- ShortlistedCourse,
28
- } from "@/lib/types";
29
- import { Badge } from "@/components/ui/badge";
30
- import { Button } from "@/components/ui/button";
31
- import {
32
- Dialog,
33
- DialogContent,
34
- DialogDescription,
35
- DialogFooter,
36
- DialogHeader,
37
- DialogTitle,
38
- DialogTrigger,
39
- } from "@/components/ui/dialog";
40
- import {
41
- DropdownMenu,
42
- DropdownMenuContent,
43
- DropdownMenuItem,
44
- DropdownMenuLabel,
45
- DropdownMenuSeparator,
46
- DropdownMenuTrigger,
47
- } from "@/components/ui/dropdown-menu";
48
-
49
- interface ImportantDatesDialogProps {
50
- course: ShortlistedCourse;
51
- onLookup: (id: string) => Promise<void>;
52
- canSearch?: boolean;
53
- }
54
-
55
- const CATEGORY_BADGE: Record<ImportantDateCategory, string> = {
56
- application_open: "bg-emerald-100 text-emerald-900 dark:bg-emerald-900/40 dark:text-emerald-100",
57
- application_deadline: "bg-rose-100 text-rose-900 dark:bg-rose-900/40 dark:text-rose-100",
58
- entrance_exam: "bg-violet-100 text-violet-900 dark:bg-violet-900/40 dark:text-violet-100",
59
- scholarship: "bg-amber-100 text-amber-900 dark:bg-amber-900/40 dark:text-amber-100",
60
- offer_or_result: "bg-sky-100 text-sky-900 dark:bg-sky-900/40 dark:text-sky-100",
61
- fee_payment: "bg-orange-100 text-orange-900 dark:bg-orange-900/40 dark:text-orange-100",
62
- session_start: "bg-teal-100 text-teal-900 dark:bg-teal-900/40 dark:text-teal-100",
63
- orientation: "bg-indigo-100 text-indigo-900 dark:bg-indigo-900/40 dark:text-indigo-100",
64
- other: "bg-muted text-foreground",
65
- };
66
-
67
- const SHORT_DATE = new Intl.DateTimeFormat("en-GB", {
68
- day: "numeric",
69
- month: "short",
70
- year: "numeric",
71
- timeZone: "UTC",
72
- });
73
-
74
- function todayIso(): string {
75
- return new Date().toISOString().slice(0, 10);
76
- }
77
-
78
- export function formatIsoDate(iso: string | null, fallback: string): string {
79
- if (!iso) return fallback;
80
- const parsed = new Date(`${iso}T00:00:00Z`);
81
- return Number.isNaN(parsed.getTime()) ? fallback : SHORT_DATE.format(parsed);
82
- }
83
-
84
- /** The single most useful upcoming date for a compact table cell. */
85
- export function nextImportantDate(course: ShortlistedCourse): ImportantDate | null {
86
- const dates = course.important_dates?.dates ?? [];
87
- if (dates.length === 0) return null;
88
- const today = todayIso();
89
- const upcoming = dates.filter((date) => date.date && date.date >= today);
90
- return (
91
- upcoming.find((date) => date.category === "application_deadline") ??
92
- upcoming[0] ??
93
- dates.find((date) => !date.date) ??
94
- // Past dates are stored most-recent-first, so this is the latest one.
95
- dates.find((date) => date.date) ??
96
- dates[0]
97
- );
98
- }
99
-
100
- function daysUntil(iso: string): number {
101
- const target = Date.parse(`${iso}T00:00:00Z`);
102
- const now = Date.parse(`${todayIso()}T00:00:00Z`);
103
- return Math.round((target - now) / 86_400_000);
104
- }
105
-
106
- function openInNewTab(url: string) {
107
- window.open(url, "_blank", "noopener,noreferrer");
108
- }
109
-
110
- interface AddToCalendarMenuProps {
111
- events: CalendarEvent[];
112
- filename: string;
113
- label: string;
114
- size?: "sm" | "xs";
115
- variant?: "outline" | "secondary" | "ghost";
116
- }
117
-
118
- /**
119
- * Google and Outlook compose links can only create one event at a time.
120
- * Several dates are exported as an .ics file, which both services import.
121
- */
122
- function AddToCalendarMenu({ events, filename, label, size = "sm", variant = "outline" }: AddToCalendarMenuProps) {
123
- if (events.length === 0) return null;
124
- const single = events.length === 1 ? events[0] : null;
125
-
126
- function handleIcs(provider: "google" | "outlook" | "file") {
127
- downloadIcs(filename, buildIcs(events));
128
- if (provider === "google") {
129
- openInNewTab("https://calendar.google.com/calendar/u/0/r/settings/export");
130
- toast.success("Calendar file downloaded. In Google Calendar use Settings → Import to add all dates.");
131
- return;
132
- }
133
- if (provider === "outlook") {
134
- toast.success("Calendar file downloaded. Open it to add the dates to Outlook.");
135
- return;
136
- }
137
- toast.success(
138
- events.length === 1
139
- ? "Calendar file downloaded — open it to add the event"
140
- : `Calendar file with ${events.length} dates downloaded`
141
- );
142
- }
143
-
144
- return (
145
- <DropdownMenu modal={false}>
146
- <DropdownMenuTrigger asChild>
147
- <Button variant={variant} size={size} aria-label={label}>
148
- <CalendarPlus />
149
- {label}
150
- </Button>
151
- </DropdownMenuTrigger>
152
- <DropdownMenuContent align="end" className="z-[100] min-w-56">
153
- {single ? (
154
- <>
155
- <DropdownMenuItem asChild>
156
- <a href={googleCalendarUrl(single)} target="_blank" rel="noopener noreferrer">
157
- Google Calendar
158
- <ExternalLink className="ml-auto size-3 text-muted-foreground" />
159
- </a>
160
- </DropdownMenuItem>
161
- <DropdownMenuItem asChild>
162
- <a href={outlookCalendarUrl(single, "live")} target="_blank" rel="noopener noreferrer">
163
- Outlook.com
164
- <ExternalLink className="ml-auto size-3 text-muted-foreground" />
165
- </a>
166
- </DropdownMenuItem>
167
- <DropdownMenuItem asChild>
168
- <a href={outlookCalendarUrl(single, "office")} target="_blank" rel="noopener noreferrer">
169
- Outlook (work or school)
170
- <ExternalLink className="ml-auto size-3 text-muted-foreground" />
171
- </a>
172
- </DropdownMenuItem>
173
- <DropdownMenuSeparator />
174
- <DropdownMenuItem onSelect={() => handleIcs("file")}>
175
- <Download className="size-4" />
176
- Download .ics (Outlook desktop, Apple Calendar)
177
- </DropdownMenuItem>
178
- </>
179
- ) : (
180
- <>
181
- <DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
182
- {events.length} upcoming dates — Google and Outlook import them from a calendar file.
183
- </DropdownMenuLabel>
184
- <DropdownMenuSeparator />
185
- <DropdownMenuItem onSelect={() => handleIcs("google")}>
186
- Google Calendar
187
- <Download className="ml-auto size-3 text-muted-foreground" />
188
- </DropdownMenuItem>
189
- <DropdownMenuItem onSelect={() => handleIcs("outlook")}>
190
- Outlook
191
- <Download className="ml-auto size-3 text-muted-foreground" />
192
- </DropdownMenuItem>
193
- <DropdownMenuItem onSelect={() => handleIcs("file")}>
194
- <Download className="size-4" />
195
- Download .ics file
196
- </DropdownMenuItem>
197
- </>
198
- )}
199
- </DropdownMenuContent>
200
- </DropdownMenu>
201
- );
202
- }
203
-
204
- function DateRow({ date, course }: { date: ImportantDate; course: ShortlistedCourse }) {
205
- const days = date.date ? daysUntil(date.date) : null;
206
- const passed = days !== null && days < 0;
207
- const soon = days !== null && days >= 0 && days <= 30;
208
- const event = passed ? null : calendarEventFromDate(date, course);
209
-
210
- return (
211
- <li
212
- className={`flex flex-col gap-1 rounded-md border p-3 ${passed ? "opacity-60" : ""}`}
213
- >
214
- <div className="flex flex-wrap items-center gap-2">
215
- <span className="text-sm font-semibold tabular-nums">
216
- {formatIsoDate(date.date, date.dateText)}
217
- </span>
218
- <Badge className={CATEGORY_BADGE[date.category] ?? CATEGORY_BADGE.other}>
219
- {importantDateCategoryLabel(date.category)}
220
- </Badge>
221
- {passed && <Badge variant="outline">Passed</Badge>}
222
- {soon && (
223
- <Badge variant="destructive">
224
- {days === 0 ? "Today" : `In ${days} day${days === 1 ? "" : "s"}`}
225
- </Badge>
226
- )}
227
- </div>
228
- <p className="text-sm">{date.label}</p>
229
- {date.details && (
230
- <p className="text-xs text-muted-foreground whitespace-pre-wrap break-words">
231
- {date.details}
232
- </p>
233
- )}
234
- {date.date && date.dateText && formatIsoDate(date.date, "") !== date.dateText && (
235
- <p className="text-xs text-muted-foreground">As written: “{date.dateText}”</p>
236
- )}
237
- <div className="flex flex-wrap items-center justify-between gap-2">
238
- {date.sourceUrl ? (
239
- <a
240
- href={date.sourceUrl}
241
- target="_blank"
242
- rel="noopener noreferrer"
243
- className="inline-flex items-center gap-1 text-xs text-primary hover:underline break-all"
244
- >
245
- Source
246
- <ExternalLink className="size-3" />
247
- </a>
248
- ) : (
249
- <span />
250
- )}
251
- {event && (
252
- <AddToCalendarMenu
253
- events={[event]}
254
- filename={icsFilename(course)}
255
- label="Add to calendar"
256
- size="xs"
257
- variant="ghost"
258
- />
259
- )}
260
- </div>
261
- </li>
262
- );
263
- }
264
-
265
- export function ImportantDatesDialog({ course, onLookup, canSearch = true }: ImportantDatesDialogProps) {
266
- const [open, setOpen] = useState(false);
267
- const [loading, setLoading] = useState(false);
268
- const report = course.important_dates;
269
- const next = nextImportantDate(course);
270
- const today = todayIso();
271
- const upcomingEvents = (report?.dates ?? [])
272
- .filter((date) => date.date && date.date >= today)
273
- .map((date) => calendarEventFromDate(date, course))
274
- .filter((event): event is CalendarEvent => event !== null);
275
-
276
- async function handleLookup() {
277
- setLoading(true);
278
- try {
279
- await onLookup(course.id);
280
- toast.success("University website searched for important dates");
281
- } catch (error) {
282
- toast.error(
283
- error instanceof Error ? error.message : "Could not find important dates"
284
- );
285
- } finally {
286
- setLoading(false);
287
- }
288
- }
289
-
290
- const triggerLabel = next
291
- ? `${next.category === "application_deadline" ? "Apply by" : importantDateCategoryLabel(next.category)} ${formatIsoDate(next.date, next.dateText)}`
292
- : report
293
- ? "No dates found"
294
- : "Find dates";
295
-
296
- return (
297
- <Dialog open={open} onOpenChange={setOpen}>
298
- <DialogTrigger asChild>
299
- <Button
300
- variant={report ? "secondary" : "outline"}
301
- size="sm"
302
- className="max-w-[14rem] justify-start"
303
- aria-label={`Important dates for ${course.course_name} at ${course.university_name}`}
304
- >
305
- {report ? <CalendarClock /> : <CalendarSearch />}
306
- <span className="truncate">{triggerLabel}</span>
307
- </Button>
308
- </DialogTrigger>
309
- <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
310
- <DialogHeader>
311
- <DialogTitle>Important dates</DialogTitle>
312
- <DialogDescription>
313
- {course.course_name} — {course.university_name}
314
- </DialogDescription>
315
- </DialogHeader>
316
-
317
- {!report && !loading && canSearch && (
318
- <div className="rounded-lg border border-dashed p-6 text-center">
319
- <CalendarSearch className="mx-auto mb-2 size-8 text-muted-foreground" />
320
- <p className="text-sm">
321
- Search the university&apos;s own website for application opening and closing
322
- dates, scholarship deadlines, entrance tests, results, and session start.
323
- </p>
324
- <p className="mt-1 text-xs text-muted-foreground">
325
- Uses Brave Search restricted to the university domain. Takes about 30–60 seconds.
326
- </p>
327
- </div>
328
- )}
329
-
330
- {loading && (
331
- <div className="flex items-center gap-3 rounded-lg border p-4 text-sm">
332
- <Loader2 className="size-4 animate-spin" />
333
- Searching the university website and reading the admissions pages…
334
- </div>
335
- )}
336
-
337
- {report && !loading && (
338
- <div className="space-y-4">
339
- <div className="rounded-md bg-muted/50 p-3 text-sm">
340
- <p>{report.summary}</p>
341
- <p className="mt-1 text-xs text-muted-foreground">
342
- Checked {new Date(report.checkedAt).toLocaleString()}
343
- {report.host ? ` · ${report.host}` : ""}
344
- {report.method === "heuristic" ? " · extracted without AI model" : ""}
345
- </p>
346
- </div>
347
-
348
- {upcomingEvents.length > 0 && (
349
- <div className="flex flex-wrap items-center justify-between gap-2">
350
- <p className="text-xs text-muted-foreground">
351
- {upcomingEvents.length === 1
352
- ? "1 upcoming date. It is added as an all-day event with a reminder one week before."
353
- : `${upcomingEvents.length} upcoming dates. Each is added as an all-day event with a reminder one week before.`}
354
- </p>
355
- <AddToCalendarMenu
356
- events={upcomingEvents}
357
- filename={icsFilename(course)}
358
- label={upcomingEvents.length === 1 ? "Add to calendar" : "Add all to calendar"}
359
- variant="secondary"
360
- />
361
- </div>
362
- )}
363
-
364
- {report.dates.length > 0 && (
365
- <ul className="space-y-2">
366
- {report.dates.map((date, index) => (
367
- <DateRow
368
- key={`${date.category}-${date.date ?? date.dateText}-${index}`}
369
- date={date}
370
- course={course}
371
- />
372
- ))}
373
- </ul>
374
- )}
375
-
376
- {report.sources.length > 0 && (
377
- <details className="text-sm">
378
- <summary className="cursor-pointer text-muted-foreground">
379
- Pages checked ({report.sources.length})
380
- </summary>
381
- <ul className="mt-2 space-y-1">
382
- {report.sources.map((source) => (
383
- <li key={source.url}>
384
- <a
385
- href={source.url}
386
- target="_blank"
387
- rel="noopener noreferrer"
388
- className="inline-flex items-center gap-1 text-primary hover:underline break-all"
389
- >
390
- {source.title || source.url}
391
- <ExternalLink className="size-3 shrink-0" />
392
- </a>
393
- </li>
394
- ))}
395
- </ul>
396
- </details>
397
- )}
398
-
399
- <p className="text-xs text-muted-foreground">
400
- Dates are read automatically from the university website and can change —
401
- confirm on the official page before applying.
402
- </p>
403
- </div>
404
- )}
405
-
406
- {canSearch && (
407
- <DialogFooter>
408
- <Button onClick={handleLookup} disabled={loading}>
409
- {loading ? (
410
- <Loader2 className="animate-spin" />
411
- ) : report ? (
412
- <RefreshCw />
413
- ) : (
414
- <CalendarSearch />
415
- )}
416
- {loading ? "Searching…" : report ? "Search again" : "Search university website"}
417
- </Button>
418
- </DialogFooter>
419
- )}
420
- </DialogContent>
421
- </Dialog>
422
- );
423
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/shortlist/share-wishlist-dialog.tsx DELETED
@@ -1,153 +0,0 @@
1
- "use client";
2
-
3
- import { useState } from "react";
4
- import { Share2, Trash2 } from "lucide-react";
5
- import { toast } from "sonner";
6
- import { sharePermissionLabel, SHARE_PERMISSIONS, type SharePermission } from "@/lib/share-access";
7
- import type { ShortlistShare } from "@/lib/types";
8
- import { Button } from "@/components/ui/button";
9
- import { Input } from "@/components/ui/input";
10
- import { Label } from "@/components/ui/label";
11
- import {
12
- Select,
13
- SelectContent,
14
- SelectItem,
15
- SelectTrigger,
16
- SelectValue,
17
- } from "@/components/ui/select";
18
- import {
19
- Dialog,
20
- DialogContent,
21
- DialogDescription,
22
- DialogHeader,
23
- DialogTitle,
24
- DialogTrigger,
25
- } from "@/components/ui/dialog";
26
-
27
- interface ShareWishlistDialogProps {
28
- outgoing: ShortlistShare[];
29
- onChange: () => void;
30
- }
31
-
32
- export function ShareWishlistDialog({ outgoing, onChange }: ShareWishlistDialogProps) {
33
- const [open, setOpen] = useState(false);
34
- const [email, setEmail] = useState("");
35
- const [permission, setPermission] = useState<SharePermission>("read");
36
- const [saving, setSaving] = useState(false);
37
-
38
- async function handleShare(event: React.FormEvent) {
39
- event.preventDefault();
40
- setSaving(true);
41
- try {
42
- const res = await fetch("/api/shortlist/shares", {
43
- method: "POST",
44
- headers: { "Content-Type": "application/json" },
45
- body: JSON.stringify({ email, permission }),
46
- });
47
- const data = await res.json();
48
- if (!res.ok) throw new Error(data.error ?? "Could not share");
49
- setEmail("");
50
- toast.success(`Shared with ${email.trim().toLowerCase()}`);
51
- onChange();
52
- } catch (error) {
53
- toast.error(error instanceof Error ? error.message : "Could not share");
54
- } finally {
55
- setSaving(false);
56
- }
57
- }
58
-
59
- async function handleRevoke(share: ShortlistShare) {
60
- const res = await fetch("/api/shortlist/shares", {
61
- method: "DELETE",
62
- headers: { "Content-Type": "application/json" },
63
- body: JSON.stringify({ id: share.id }),
64
- });
65
- const data = await res.json().catch(() => ({}));
66
- if (!res.ok) {
67
- toast.error(data.error ?? "Could not remove access");
68
- return;
69
- }
70
- toast.success(`Removed ${share.invite_email}`);
71
- onChange();
72
- }
73
-
74
- return (
75
- <Dialog open={open} onOpenChange={setOpen}>
76
- <DialogTrigger asChild>
77
- <Button variant="outline">
78
- <Share2 />
79
- Share
80
- </Button>
81
- </DialogTrigger>
82
- <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
83
- <DialogHeader>
84
- <DialogTitle>Share wishlist</DialogTitle>
85
- <DialogDescription>
86
- Invite a counselor, parent, or anyone else with an account. They sign in with this
87
- email to open your wishlist.
88
- </DialogDescription>
89
- </DialogHeader>
90
- <form onSubmit={handleShare} className="grid gap-3">
91
- <div className="space-y-2">
92
- <Label htmlFor="share-email">Email</Label>
93
- <Input
94
- id="share-email"
95
- type="email"
96
- required
97
- value={email}
98
- placeholder="counselor@school.edu"
99
- onChange={(event) => setEmail(event.target.value)}
100
- />
101
- </div>
102
- <div className="space-y-2">
103
- <Label>Permission</Label>
104
- <Select
105
- value={permission}
106
- onValueChange={(value) => setPermission(value as SharePermission)}
107
- >
108
- <SelectTrigger className="w-full">
109
- <SelectValue />
110
- </SelectTrigger>
111
- <SelectContent>
112
- {SHARE_PERMISSIONS.map((value) => (
113
- <SelectItem key={value} value={value}>
114
- {sharePermissionLabel(value)}
115
- </SelectItem>
116
- ))}
117
- </SelectContent>
118
- </Select>
119
- <p className="text-xs text-muted-foreground">
120
- View only can read courses and files. Comment adds notes on each course. Edit can
121
- change the fit category, notes, dates, and uploads. Delete can also remove courses.
122
- </p>
123
- </div>
124
- <Button type="submit" disabled={saving}>
125
- {saving ? "Sharing…" : "Share wishlist"}
126
- </Button>
127
- </form>
128
- {outgoing.length > 0 && (
129
- <ul className="space-y-2 border-t pt-3">
130
- {outgoing.map((share) => (
131
- <li key={share.id} className="flex items-center justify-between gap-2 text-sm">
132
- <span>
133
- <span className="font-medium">{share.invite_email}</span>
134
- <span className="block text-xs text-muted-foreground">
135
- {sharePermissionLabel(share.permission)}
136
- </span>
137
- </span>
138
- <Button
139
- variant="ghost"
140
- size="icon-sm"
141
- aria-label={`Remove ${share.invite_email}`}
142
- onClick={() => handleRevoke(share)}
143
- >
144
- <Trash2 className="size-4 text-destructive" />
145
- </Button>
146
- </li>
147
- ))}
148
- </ul>
149
- )}
150
- </DialogContent>
151
- </Dialog>
152
- );
153
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/shortlist/shortlist-table.tsx DELETED
@@ -1,362 +0,0 @@
1
- "use client";
2
-
3
- import { useMemo, useState } from "react";
4
- import {
5
- columnFilteringFeature,
6
- createCoreRowModel,
7
- createFilteredRowModel,
8
- createSortedRowModel,
9
- filterFn_includesString,
10
- flexRender,
11
- globalFilteringFeature,
12
- rowSortingFeature,
13
- tableFeatures,
14
- useTable,
15
- type ColumnDef,
16
- type SortingState,
17
- } from "@tanstack/react-table";
18
- import { ArrowUpDown, ExternalLink, Trash2 } from "lucide-react";
19
- import type { FitCategory } from "@/lib/candidate-fit";
20
- import { compareRanking } from "@/lib/ranking";
21
- import type { ShortlistedCourse } from "@/lib/types";
22
- import { CourseDetailsDialog } from "@/components/shortlist/course-details-dialog";
23
- import { DocumentsDialog } from "@/components/shortlist/documents-dialog";
24
- import { FitBadge } from "@/components/shortlist/fit-badge";
25
- import {
26
- ImportantDatesDialog,
27
- nextImportantDate,
28
- } from "@/components/shortlist/important-dates-dialog";
29
- import { Button } from "@/components/ui/button";
30
- import { Input } from "@/components/ui/input";
31
- import { Badge } from "@/components/ui/badge";
32
- import {
33
- Select,
34
- SelectContent,
35
- SelectItem,
36
- SelectTrigger,
37
- SelectValue,
38
- } from "@/components/ui/select";
39
- import {
40
- Table,
41
- TableBody,
42
- TableCell,
43
- TableHead,
44
- TableHeader,
45
- TableRow,
46
- } from "@/components/ui/table";
47
- import {
48
- Card,
49
- CardContent,
50
- CardDescription,
51
- CardHeader,
52
- CardTitle,
53
- } from "@/components/ui/card";
54
-
55
- const features = tableFeatures({
56
- columnFilteringFeature,
57
- globalFilteringFeature,
58
- rowSortingFeature,
59
- coreRowModel: createCoreRowModel(),
60
- filteredRowModel: createFilteredRowModel(),
61
- sortedRowModel: createSortedRowModel(),
62
- });
63
-
64
- const WRAP_COLUMN_IDS = new Set([
65
- "university_location",
66
- "tuition_fee",
67
- "admission_requirements",
68
- ]);
69
-
70
- type ShortlistColumn = ColumnDef<typeof features, ShortlistedCourse>;
71
-
72
- interface ShortlistTableProps {
73
- items: ShortlistedCourse[];
74
- onRemove: (id: string) => Promise<void>;
75
- onSaveNotes: (id: string, notes: string) => Promise<void>;
76
- onLookupDates: (id: string) => Promise<void>;
77
- onSetFit: (id: string, fit: FitCategory) => Promise<void>;
78
- canEdit?: boolean;
79
- canComment?: boolean;
80
- canDelete?: boolean;
81
- }
82
-
83
- export function ShortlistTable({
84
- items,
85
- onRemove,
86
- onSaveNotes,
87
- onLookupDates,
88
- onSetFit,
89
- canEdit = true,
90
- canComment = true,
91
- canDelete = true,
92
- }: ShortlistTableProps) {
93
- const [sorting, setSorting] = useState<SortingState>([
94
- { id: "qs_world_ranking", desc: false },
95
- ]);
96
- const [globalFilter, setGlobalFilter] = useState("");
97
- const [removing, setRemoving] = useState<string | null>(null);
98
-
99
- const columns = useMemo<ShortlistColumn[]>(
100
- () => [
101
- {
102
- accessorKey: "qs_world_ranking",
103
- header: ({ column }) => (
104
- <Button
105
- variant="ghost"
106
- size="sm"
107
- className="-ml-2"
108
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
109
- >
110
- QS Rank
111
- <ArrowUpDown className="size-3.5" />
112
- </Button>
113
- ),
114
- cell: ({ getValue }) => getValue<number | null>() ?? "—",
115
- sortFn: (a, b) =>
116
- compareRanking(a.original.qs_world_ranking, b.original.qs_world_ranking),
117
- },
118
- {
119
- accessorKey: "university_name",
120
- header: ({ column }) => (
121
- <Button
122
- variant="ghost"
123
- size="sm"
124
- className="-ml-2"
125
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
126
- >
127
- University
128
- <ArrowUpDown className="size-3.5" />
129
- </Button>
130
- ),
131
- },
132
- {
133
- id: "fit",
134
- header: "Fit",
135
- accessorFn: (row) => row.fit ?? "",
136
- cell: ({ row }) =>
137
- canEdit ? (
138
- <Select
139
- value={row.original.fit ?? undefined}
140
- onValueChange={(value) => {
141
- void onSetFit(row.original.id, value as FitCategory).catch(() => undefined);
142
- }}
143
- >
144
- <SelectTrigger className="w-[7.5rem]" aria-label={`Fit for ${row.original.course_name}`}>
145
- <SelectValue placeholder="Set fit" />
146
- </SelectTrigger>
147
- <SelectContent>
148
- <SelectItem value="dream">Dream</SelectItem>
149
- <SelectItem value="reach">Reach</SelectItem>
150
- <SelectItem value="target">Target</SelectItem>
151
- </SelectContent>
152
- </Select>
153
- ) : (
154
- <FitBadge fit={row.original.fit} reason={row.original.fit_reason} />
155
- ),
156
- },
157
- {
158
- accessorKey: "university_location",
159
- header: "Location",
160
- cell: ({ getValue }) => (
161
- <span className="block max-w-[16rem] whitespace-pre-wrap break-words leading-snug">
162
- {getValue<string | null>() ?? "—"}
163
- </span>
164
- ),
165
- },
166
- {
167
- accessorKey: "course_name",
168
- header: "Course",
169
- },
170
- {
171
- accessorKey: "country",
172
- header: "Country",
173
- cell: ({ getValue }) => getValue<string | null>() ?? "—",
174
- },
175
- {
176
- accessorKey: "tuition_fee",
177
- header: "Tuition",
178
- cell: ({ getValue }) => (
179
- <span className="block max-w-[18rem] whitespace-pre-wrap break-words leading-snug">
180
- {getValue<string | null>() ?? "—"}
181
- </span>
182
- ),
183
- },
184
- {
185
- accessorKey: "duration",
186
- header: "Duration",
187
- cell: ({ getValue }) => getValue<string | null>() ?? "—",
188
- },
189
- {
190
- accessorKey: "admission_requirements",
191
- header: "Requirements",
192
- cell: ({ getValue }) => (
193
- <span className="block max-w-[22rem] whitespace-pre-wrap break-words leading-snug">
194
- {getValue<string | null>() ?? "—"}
195
- </span>
196
- ),
197
- },
198
- {
199
- id: "important_dates",
200
- header: "Key dates",
201
- accessorFn: (row) => nextImportantDate(row)?.date ?? "",
202
- sortFn: (a, b) => {
203
- const left = nextImportantDate(a.original)?.date ?? "9999";
204
- const right = nextImportantDate(b.original)?.date ?? "9999";
205
- return left < right ? -1 : left > right ? 1 : 0;
206
- },
207
- cell: ({ row }) => (
208
- <ImportantDatesDialog
209
- course={row.original}
210
- onLookup={onLookupDates}
211
- canSearch={canEdit}
212
- />
213
- ),
214
- },
215
- {
216
- accessorKey: "course_url",
217
- header: "URL",
218
- cell: ({ getValue }) => {
219
- const url = getValue<string | null>();
220
- if (!url) return "—";
221
- return (
222
- <a
223
- href={url}
224
- target="_blank"
225
- rel="noopener noreferrer"
226
- className="inline-flex items-center gap-1 text-primary hover:underline"
227
- >
228
- Link
229
- <ExternalLink className="size-3" />
230
- </a>
231
- );
232
- },
233
- },
234
- {
235
- accessorKey: "is_manual",
236
- header: "Source",
237
- cell: ({ getValue }) =>
238
- getValue<boolean>() ? (
239
- <Badge variant="outline">Manual</Badge>
240
- ) : (
241
- <Badge variant="secondary">AI Search</Badge>
242
- ),
243
- },
244
- {
245
- id: "actions",
246
- header: "",
247
- cell: ({ row }) => (
248
- <div className="flex items-center gap-1">
249
- <DocumentsDialog
250
- courseId={row.original.id}
251
- courseName={row.original.course_name}
252
- canEdit={canEdit}
253
- />
254
- <CourseDetailsDialog
255
- course={row.original}
256
- onSaveNotes={onSaveNotes}
257
- canEdit={canEdit}
258
- canComment={canComment}
259
- />
260
- {canDelete && (
261
- <Button
262
- variant="ghost"
263
- size="icon-sm"
264
- aria-label={`Remove ${row.original.course_name}`}
265
- disabled={removing === row.original.id}
266
- onClick={async () => {
267
- setRemoving(row.original.id);
268
- try {
269
- await onRemove(row.original.id);
270
- } finally {
271
- setRemoving(null);
272
- }
273
- }}
274
- >
275
- <Trash2 className="size-4 text-destructive" />
276
- </Button>
277
- )}
278
- </div>
279
- ),
280
- },
281
- ],
282
- [removing, onRemove, onSaveNotes, onLookupDates, onSetFit, canEdit, canComment, canDelete]
283
- );
284
-
285
- const table = useTable({
286
- features,
287
- data: items,
288
- columns,
289
- state: { sorting, globalFilter },
290
- onSortingChange: setSorting,
291
- onGlobalFilterChange: setGlobalFilter,
292
- globalFilterFn: filterFn_includesString,
293
- getRowId: (row) => row.id,
294
- });
295
-
296
- return (
297
- <Card>
298
- <CardHeader>
299
- <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
300
- <div>
301
- <CardTitle>Wishlist</CardTitle>
302
- <CardDescription>
303
- {items.length} course{items.length !== 1 ? "s" : ""} saved. Dream, Reach, and Target come from the candidate profile and can be changed.
304
- </CardDescription>
305
- </div>
306
- <Input
307
- placeholder="Filter wishlist..."
308
- value={globalFilter}
309
- onChange={(e) => setGlobalFilter(e.target.value)}
310
- className="max-w-xs"
311
- />
312
- </div>
313
- </CardHeader>
314
- <CardContent>
315
- {items.length === 0 ? (
316
- <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">
317
- <p className="text-muted-foreground">No courses on this wishlist yet.</p>
318
- <p className="mt-1 text-sm text-muted-foreground">
319
- Search for courses or add one manually.
320
- </p>
321
- </div>
322
- ) : (
323
- <div className="rounded-md border">
324
- <Table>
325
- <TableHeader>
326
- {table.getHeaderGroups().map((headerGroup) => (
327
- <TableRow key={headerGroup.id}>
328
- {headerGroup.headers.map((header) => (
329
- <TableHead key={header.id}>
330
- {header.isPlaceholder
331
- ? null
332
- : flexRender(header.column.columnDef.header, header.getContext())}
333
- </TableHead>
334
- ))}
335
- </TableRow>
336
- ))}
337
- </TableHeader>
338
- <TableBody>
339
- {table.getRowModel().rows.map((row) => (
340
- <TableRow key={row.id}>
341
- {row.getAllCells().map((cell) => (
342
- <TableCell
343
- key={cell.id}
344
- className={
345
- WRAP_COLUMN_IDS.has(cell.column.id)
346
- ? "max-w-[22rem] whitespace-normal align-top"
347
- : undefined
348
- }
349
- >
350
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
351
- </TableCell>
352
- ))}
353
- </TableRow>
354
- ))}
355
- </TableBody>
356
- </Table>
357
- </div>
358
- )}
359
- </CardContent>
360
- </Card>
361
- );
362
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/shortlist/shortlist-view.tsx DELETED
@@ -1,160 +0,0 @@
1
- "use client";
2
-
3
- import { useRouter } from "next/navigation";
4
- import { toast } from "sonner";
5
- import Link from "next/link";
6
- import { AppHeader } from "@/components/layout/app-header";
7
- import { AddManualDialog } from "@/components/shortlist/add-manual-dialog";
8
- import { ShareWishlistDialog } from "@/components/shortlist/share-wishlist-dialog";
9
- import { ShortlistTable } from "@/components/shortlist/shortlist-table";
10
- import type { FitCategory } from "@/lib/candidate-fit";
11
- import { permissionAllows, sharePermissionLabel, type ShortlistAccess } from "@/lib/share-access";
12
- import type { ShortlistInsert, ShortlistShare, ShortlistedCourse } from "@/lib/types";
13
-
14
- interface ShortlistViewProps {
15
- userEmail: string | null;
16
- items: ShortlistedCourse[];
17
- access: ShortlistAccess;
18
- ownerEmail: string | null;
19
- outgoing: ShortlistShare[];
20
- incoming: ShortlistShare[];
21
- }
22
-
23
- export function ShortlistView({
24
- userEmail,
25
- items,
26
- access,
27
- ownerEmail,
28
- outgoing,
29
- incoming,
30
- }: ShortlistViewProps) {
31
- const router = useRouter();
32
-
33
- async function handleAdd(item: ShortlistInsert) {
34
- const res = await fetch("/api/shortlist", {
35
- method: "POST",
36
- headers: { "Content-Type": "application/json" },
37
- body: JSON.stringify(item),
38
- });
39
- if (!res.ok) {
40
- const data = await res.json();
41
- throw new Error(data.error ?? "Failed to add");
42
- }
43
- router.refresh();
44
- }
45
-
46
- async function handleSaveNotes(id: string, notes: string) {
47
- const res = await fetch("/api/shortlist", {
48
- method: "PATCH",
49
- headers: { "Content-Type": "application/json" },
50
- body: JSON.stringify({ id, notes }),
51
- });
52
- if (!res.ok) {
53
- const data = await res.json();
54
- throw new Error(data.error ?? "Failed to save notes");
55
- }
56
- router.refresh();
57
- }
58
-
59
- async function handleLookupDates(id: string) {
60
- const res = await fetch("/api/shortlist/important-dates", {
61
- method: "POST",
62
- headers: { "Content-Type": "application/json" },
63
- body: JSON.stringify({ id }),
64
- });
65
- if (!res.ok) {
66
- const data = await res.json().catch(() => ({}));
67
- throw new Error(data.error ?? "Failed to find important dates");
68
- }
69
- router.refresh();
70
- }
71
-
72
- async function handleRemove(id: string) {
73
- const res = await fetch(`/api/shortlist?id=${id}`, { method: "DELETE" });
74
- if (!res.ok) {
75
- toast.error("Failed to remove course");
76
- return;
77
- }
78
- toast.success("Removed from wishlist");
79
- router.refresh();
80
- }
81
-
82
- async function handleSetFit(id: string, fit: FitCategory) {
83
- const res = await fetch("/api/shortlist", {
84
- method: "PATCH",
85
- headers: { "Content-Type": "application/json" },
86
- body: JSON.stringify({ id, fit }),
87
- });
88
- const data = await res.json().catch(() => ({}));
89
- if (!res.ok) {
90
- toast.error(data.error ?? "Could not update the category");
91
- return;
92
- }
93
- toast.success("Category updated");
94
- router.refresh();
95
- }
96
-
97
- const canEdit = permissionAllows(access, "edit");
98
- const canComment = permissionAllows(access, "comment");
99
- const canDelete = permissionAllows(access, "delete");
100
- const isOwner = access === "owner";
101
-
102
- return (
103
- <div className="min-h-full bg-muted/20">
104
- <AppHeader userEmail={userEmail} />
105
- <main className="mx-auto max-w-7xl space-y-6 px-4 py-8 sm:px-6">
106
- <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
107
- <div>
108
- <h1 className="text-2xl font-bold tracking-tight">
109
- {isOwner ? "Wishlist" : `Wishlist shared by ${ownerEmail ?? "another user"}`}
110
- </h1>
111
- <p className="text-muted-foreground">
112
- {isOwner
113
- ? "Saved courses, labelled Dream, Reach, or Target from your search profile."
114
- : `You can ${sharePermissionLabel(access).toLowerCase()}.`}
115
- </p>
116
- </div>
117
- <div className="flex flex-wrap gap-2">
118
- {isOwner && <ShareWishlistDialog outgoing={outgoing} onChange={() => router.refresh()} />}
119
- {canEdit && <AddManualDialog onAdd={handleAdd} />}
120
- </div>
121
- </div>
122
- {isOwner && incoming.length > 0 && (
123
- <div className="rounded-lg border bg-card p-4">
124
- <p className="text-sm font-medium">Shared with you</p>
125
- <ul className="mt-2 flex flex-wrap gap-2">
126
- {incoming.map((share) => (
127
- <li key={share.id}>
128
- <Link
129
- href={`/shortlist?owner=${share.owner_id}`}
130
- className="inline-flex rounded-md border px-3 py-1.5 text-sm hover:bg-muted"
131
- >
132
- {share.owner_email}
133
- <span className="ml-2 text-muted-foreground">
134
- {sharePermissionLabel(share.permission)}
135
- </span>
136
- </Link>
137
- </li>
138
- ))}
139
- </ul>
140
- </div>
141
- )}
142
- {!isOwner && (
143
- <Link href="/shortlist" className="text-sm text-primary hover:underline">
144
- Back to your wishlist
145
- </Link>
146
- )}
147
- <ShortlistTable
148
- items={items}
149
- onRemove={handleRemove}
150
- onSaveNotes={handleSaveNotes}
151
- onLookupDates={handleLookupDates}
152
- onSetFit={handleSetFit}
153
- canEdit={canEdit}
154
- canComment={canComment}
155
- canDelete={canDelete}
156
- />
157
- </main>
158
- </div>
159
- );
160
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/ui/avatar.tsx DELETED
@@ -1,111 +0,0 @@
1
- "use client"
2
-
3
- import * as React from "react"
4
- import { cn } from "cn"
5
- import { Avatar as AvatarPrimitive } from "radix-ui"
6
-
7
- function Avatar({
8
- className,
9
- size = "default",
10
- ...props
11
- }: React.ComponentProps<typeof AvatarPrimitive.Root> & {
12
- size?: "default" | "sm" | "lg"
13
- }) {
14
- return (
15
- <AvatarPrimitive.Root
16
- data-slot="avatar"
17
- data-size={size}
18
- className={cn(
19
- "group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
20
- className
21
- )}
22
- {...props}
23
- />
24
- )
25
- }
26
-
27
- function AvatarImage({
28
- className,
29
- ...props
30
- }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
31
- return (
32
- <AvatarPrimitive.Image
33
- data-slot="avatar-image"
34
- className={cn(
35
- "aspect-square size-full rounded-full object-cover",
36
- className
37
- )}
38
- {...props}
39
- />
40
- )
41
- }
42
-
43
- function AvatarFallback({
44
- className,
45
- ...props
46
- }: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
47
- return (
48
- <AvatarPrimitive.Fallback
49
- data-slot="avatar-fallback"
50
- className={cn(
51
- "flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
52
- className
53
- )}
54
- {...props}
55
- />
56
- )
57
- }
58
-
59
- function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
60
- return (
61
- <span
62
- data-slot="avatar-badge"
63
- className={cn(
64
- "absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
65
- "group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
66
- "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
67
- "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
68
- className
69
- )}
70
- {...props}
71
- />
72
- )
73
- }
74
-
75
- function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
76
- return (
77
- <div
78
- data-slot="avatar-group"
79
- className={cn(
80
- "group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
81
- className
82
- )}
83
- {...props}
84
- />
85
- )
86
- }
87
-
88
- function AvatarGroupCount({
89
- className,
90
- ...props
91
- }: React.ComponentProps<"div">) {
92
- return (
93
- <div
94
- data-slot="avatar-group-count"
95
- className={cn(
96
- "relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
97
- className
98
- )}
99
- {...props}
100
- />
101
- )
102
- }
103
-
104
- export {
105
- Avatar,
106
- AvatarImage,
107
- AvatarFallback,
108
- AvatarGroup,
109
- AvatarGroupCount,
110
- AvatarBadge,
111
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/ui/badge.tsx DELETED
@@ -1,48 +0,0 @@
1
- import * as React from "react"
2
- import { cva, type VariantProps } from "class-variance-authority"
3
- import { cn } from "cn"
4
- import { Slot } from "radix-ui"
5
-
6
- const badgeVariants = cva(
7
- "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
8
- {
9
- variants: {
10
- variant: {
11
- default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
12
- secondary:
13
- "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
14
- destructive:
15
- "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
16
- outline:
17
- "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
18
- ghost:
19
- "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
20
- link: "text-primary underline-offset-4 hover:underline",
21
- },
22
- },
23
- defaultVariants: {
24
- variant: "default",
25
- },
26
- }
27
- )
28
-
29
- function Badge({
30
- className,
31
- variant = "default",
32
- asChild = false,
33
- ...props
34
- }: React.ComponentProps<"span"> &
35
- VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
36
- const Comp = asChild ? Slot.Root : "span"
37
-
38
- return (
39
- <Comp
40
- data-slot="badge"
41
- data-variant={variant}
42
- className={cn(badgeVariants({ variant }), className)}
43
- {...props}
44
- />
45
- )
46
- }
47
-
48
- export { Badge, badgeVariants }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/ui/button.tsx DELETED
@@ -1,66 +0,0 @@
1
- import * as React from "react"
2
- import { cva, type VariantProps } from "class-variance-authority"
3
- import { cn } from "cn"
4
- import { Slot } from "radix-ui"
5
-
6
- const buttonVariants = cva(
7
- "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
8
- {
9
- variants: {
10
- variant: {
11
- default: "bg-primary text-primary-foreground hover:bg-primary/80",
12
- outline:
13
- "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
14
- secondary:
15
- "bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
16
- ghost:
17
- "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
18
- destructive:
19
- "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
20
- link: "text-primary underline-offset-4 hover:underline",
21
- },
22
- size: {
23
- default:
24
- "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
25
- xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
26
- sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
27
- lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
28
- icon: "size-8",
29
- "icon-xs":
30
- "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
31
- "icon-sm":
32
- "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
33
- "icon-lg": "size-9",
34
- },
35
- },
36
- defaultVariants: {
37
- variant: "default",
38
- size: "default",
39
- },
40
- }
41
- )
42
-
43
- function Button({
44
- className,
45
- variant = "default",
46
- size = "default",
47
- asChild = false,
48
- ...props
49
- }: React.ComponentProps<"button"> &
50
- VariantProps<typeof buttonVariants> & {
51
- asChild?: boolean
52
- }) {
53
- const Comp = asChild ? Slot.Root : "button"
54
-
55
- return (
56
- <Comp
57
- data-slot="button"
58
- data-variant={variant}
59
- data-size={size}
60
- className={cn(buttonVariants({ variant, size, className }))}
61
- {...props}
62
- />
63
- )
64
- }
65
-
66
- export { Button, buttonVariants }