# API Instruction Guide

This document explains how the API layer works in this project — how GET and POST requests flow from the UI to the backend, how data is fetched inside hooks, how services are written, and the role of [middleware/API.ts](middleware/API.ts) and [middleware/endPoints.ts](middleware/endPoints.ts).

> Naming note: the user-facing names are sometimes spoken as `api.tsx` and `endpoint.tsx`, but the actual files are `.ts` (TypeScript only, no JSX) and live under `middleware/`.

---

## 1. High-level architecture

Every network call passes through **four layers**. The browser never talks to the Odoo backend directly — a Next.js API route always sits in the middle so that session cookies, secrets, and the backend base URL stay on the server.

```
┌────────────────────────────┐
│ 1. Component (page/UI)     │   e.g. app/my-tasks/page.tsx
└─────────────┬──────────────┘
              │ calls
              ▼
┌────────────────────────────┐
│ 2. Hook (React Query)      │   hooks/useProjectTasks.ts
│    useQuery / useMutation  │
└─────────────┬──────────────┘
              │ calls
              ▼
┌────────────────────────────┐
│ 3. Service (fetch wrapper) │   services/fetch-my-tasks.tsx
│    hits  /api/<feature>    │
└─────────────┬──────────────┘
              │ fetch
              ▼
┌────────────────────────────┐
│ 4. Next.js Route Handler   │   app/api/tasks/route.ts
│    (server-only proxy)     │
└─────────────┬──────────────┘
              │ fetch + cookie forward
              ▼
┌────────────────────────────┐
│    Odoo backend            │   NEXT_PUBLIC_API_URL + endPoints.xxx
└────────────────────────────┘
```

### Why this layering?

| Layer | Responsibility |
|---|---|
| Component | Render UI, read query/mutation state |
| Hook | Cache, retry, invalidate, deduplicate (React Query) |
| Service | Build URL + payload, parse JSON, throw typed `ApiError` |
| Route handler | Forward cookies, hide backend URL, proxy to Odoo |
| `endPoints.ts` | Single source of truth for all backend paths |
| `API.ts` | Legacy axios wrapper (still used by a few server routes) |

---

## 2. `middleware/endPoints.ts` — the endpoint registry

[middleware/endPoints.ts](middleware/endPoints.ts) exports a single object where **keys are logical names** and **values are backend paths** (relative to `process.env.NEXT_PUBLIC_API_URL`).

```ts
// middleware/endPoints.ts (excerpt)
const endPoints = {
  UserAuth:           "/session/auth/login",
  tasks:              "/session/auth/api/task",
  createTask:         "/session/auth/api/project-task/create",
  updateTask:         "/session/auth/api/project-task/update",
  taskById:           "/session/auth/api/task",
  projectCenter:      "/session/auth/api/project-center",
  createProject:      "/session/auth/api/project/create",
  createIdea:         "/session/auth/api/idea/create",
  ideationStages:     "/api/ideation-stages",
  // ... etc.
};
export default endPoints;
```

### Rules

- **Never hardcode a backend path** anywhere else. Always import from `endPoints`.
- Add a new key when a new backend route is introduced; group it under the related comment block (`//Task APIs`, `//Document APIs`, etc.).
- Some entries contain placeholders (`{{submissionUuid}}`, `{{projectId}}`) — these are replaced by the caller using `.replace()`.

---

## 3. `middleware/API.ts` — the axios helper

[middleware/API.ts](middleware/API.ts) exports a default object `APIs` with three methods: `GET`, `POST`, and `DELETE`. Each method wraps `axios.request`, prepends `process.env.NEXT_PUBLIC_API_URL` to the endpoint, and centralises error handling (including `toast.error` for failed POSTs).

```ts
// middleware/API.ts (signatures)
APIs.GET(endpoint, body = {}, headers = {})
APIs.POST(endpoint, body = {}, headers = {}, withCredentials = false)
APIs.DELETE(endpoint, deleteid, headers = {})
```

### Behaviour

- **POST** — checks `res.status`; on failure shows `toast.error(res.message)`. Returns `null` on error.
- **GET** — returns `response.data` on success; on AxiosError returns `{ status: false, statusCode }`.
- **DELETE** — appends `/<deleteid>` to the URL.

### When to use it

`APIs` is a **legacy helper**. New code preferably uses the **service → route handler** pattern (see §5–6) because it keeps the Odoo URL on the server. `APIs` is still acceptable inside server-only files where you genuinely need axios features (e.g. some legacy server-side helpers), but for new client/server work, follow the patterns in §5 and §6.

---

## 4. `hooks/api-error.ts` — typed errors

[hooks/api-error.ts](hooks/api-error.ts) defines the `ApiError` class. All services throw `ApiError` (not plain `Error`) so that React Query and UI code can branch on `error.code` (e.g. `401 → redirect to login`).

```ts
export class ApiError extends Error {
  readonly code: number;     // numeric API code (e.g. 401)
  readonly apiName: string;  // "name" field from API payload
  constructor(message: string, code: number, apiName: string) { ... }
}
```

---

## 5. Services — `services/*.ts(x)`

A **service** is a thin async function that calls one Next.js route. It owns:

1. The request URL (always `/api/...` — a Next.js route, never the Odoo URL).
2. The query params or JSON body.
3. JSON parsing.
4. Throwing `ApiError` on non-OK responses.

### 5.1 GET service — `services/fetch-my-tasks.tsx`

```ts
export const fetchTaskListService = async (
  projectTaskPage: Record<number, number>,
  activeProject: number,
): Promise<MyTaskResponse> => {
  const params = new URLSearchParams({
    project_id:    String(activeProject),
    task_limit:    "20",
    task_offset:   String(projectTaskPage[activeProject]),
    project_limit: "10",
    project_offset: "0",
  });

  const response = await fetch(`/api/tasks?${params}`, {
    method: "GET",
    credentials: "include",   // forward session cookie
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Task fetch failed (status ${response.status}): ${errorText}`);
  }

  return (await response.json()) as MyTaskResponse;
};
```

### 5.2 GET service with `ApiError` — `services/fetch-my-projects.tsx`

When the route can return `401`, parse the JSON error body and throw `ApiError`:

```ts
if (!response.ok) {
  let errPayload: { code?: number; name?: string } = {};
  try { errPayload = await response.json(); } catch {}
  const apiCode = errPayload.code ?? response.status;
  const apiName = errPayload.name ?? response.statusText;
  if (apiCode === 401) {
    throw new ApiError("Unauthorized – please log in", apiCode, apiName);
  }
  throw new ApiError(`Project fetch failed (${response.status})`, apiCode, apiName);
}
```

### 5.3 POST service — `services/create-task.ts`

```ts
export const createTaskService = async (
  payload: CreateTaskPayload,
): Promise<{ status: string; message: string; task_id?: number }> => {
  const response = await fetch("/api/tasks/create", {
    method:      "POST",
    headers:     { "Content-Type": "application/json" },
    credentials: "include",
    body:        JSON.stringify(payload),
  });

  const data = await response.json();

  if (!response.ok) {
    throw new ApiError(
      data?.message ?? `Create task failed (${response.status})`,
      data?.code   ?? response.status,
      data?.name   ?? response.statusText,
    );
  }
  return data;
};
```

### Service conventions

- **File name**: `fetch-<thing>.ts(x)` for GET, `create-<thing>.ts` / `update-<thing>.ts` for POST.
- **Export a single named function** (`fetchTaskListService`, `createTaskService`).
- **Always `credentials: "include"`** so the session cookie reaches the Next.js route.
- **Declare a typed payload interface** for POST bodies (e.g. `CreateTaskPayload`).
- **Return a typed shape** (e.g. `Promise<MyTaskResponse>`).
- **Throw `ApiError`** on non-OK; never return `null`.

---

## 6. Next.js route handlers — `app/api/<feature>/route.ts`

These are **server-only** files. Each exports `GET` and/or `POST` functions; their job is to forward the request to Odoo with the user's cookie attached. They are the only place where the real backend URL (`process.env.NEXT_PUBLIC_API_URL + endPoints.xxx`) is constructed for client-initiated traffic.

### 6.1 GET handler — `app/api/tasks/route.ts`

```ts
import { NextRequest, NextResponse } from "next/server";
import endPoints from "@/middleware/endPoints";

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const apiUrl =
      `${process.env.NEXT_PUBLIC_API_URL}${endPoints.tasks}?${searchParams.toString()}`;

    const headers: Record<string, string> = {};
    const cookie = request.headers.get("cookie");
    if (cookie) headers["cookie"] = cookie;   // forward session

    const resp = await fetch(apiUrl, { method: "GET", headers, credentials: "include" });
    const data = await resp.json();
    return NextResponse.json(data, { status: resp.status });
  } catch (error) {
    console.error("/api/tasks proxy error:", error);
    return NextResponse.json(
      { status: false, message: "Proxy request failed" },
      { status: 500 },
    );
  }
}
```

### 6.2 POST handler — `app/api/tasks/create/route.ts`

```ts
export async function POST(request: NextRequest) {
  try {
    const body   = await request.json();
    const apiUrl = `${process.env.NEXT_PUBLIC_API_URL}${endPoints.createTask}`;

    const headers: Record<string, string> = { "Content-Type": "application/json" };
    const cookie  = request.headers.get("cookie");
    if (cookie) headers["cookie"] = cookie;

    const resp = await fetch(apiUrl, {
      method: "POST",
      headers,
      body: JSON.stringify(body),
    });
    const data = await resp.json();
    return NextResponse.json(data, { status: resp.status });
  } catch (error) {
    console.error("/api/tasks/create proxy error:", error);
    return NextResponse.json(
      { status: false, message: "Proxy request failed" },
      { status: 500 },
    );
  }
}
```

### Route handler conventions

- Import the backend path from [middleware/endPoints.ts](middleware/endPoints.ts) — never inline the path.
- Always forward `cookie` from the incoming request.
- Always relay the upstream status code: `NextResponse.json(data, { status: resp.status })`.
- Catch errors, log with the route prefix, return `{ status: false, message: "..." }` with status `500`.

---

## 7. Hooks — `hooks/use<Feature>.ts`

Hooks wrap services with **React Query**. They give the UI caching, automatic refetching, loading/error state, and deduplication for free.

### 7.1 GET hook — `hooks/useProjectTasks.ts`

```ts
import { useQuery, UseQueryResult, QueryFunctionContext } from "@tanstack/react-query";
import { fetchTaskListService } from "@/services/fetch-my-tasks";
import { MyTaskResponse } from "@/types/my-task";

type ProjectTasksQueryKey = [
  "project-tasks",
  { projectTaskPage: Record<number, number>; activeProject: number },
];

export const useProjectTasks = ({
  projectTaskPage,
  activeProject,
}: UseProjectTasksParams): UseQueryResult<MyTaskResponse, Error> => {
  const queryKey: ProjectTasksQueryKey = useMemo(
    () => ["project-tasks", { projectTaskPage, activeProject }],
    [projectTaskPage, activeProject],
  );

  return useQuery({
    queryKey,
    queryFn: async ({ queryKey }: QueryFunctionContext<ProjectTasksQueryKey>) => {
      const [, p] = queryKey;
      return fetchTaskListService(p.projectTaskPage, p.activeProject);
    },
    placeholderData:      (prev) => prev,   // keep previous page while loading next
    staleTime:            30_000,           // 30 s before refetch
    refetchOnWindowFocus: true,
  });
};
```

### 7.2 Lighter GET hook — `hooks/useLessonLearn.ts`

```ts
export const useLessonLearnedList = ({ page, limit, projectId }: UseLessonLearnedListParams) => {
  const offset = Math.max(0, (page - 1) * limit);
  return useQuery({
    queryKey: ["lesson-learned-list", { page, limit, projectId: projectId ?? null }],
    queryFn:  () => fetchLessonLearnedListService({
      projectId: projectId ?? undefined,
      limit,
      offset,
    }),
    placeholderData:      (prev) => prev,
    staleTime:            30_000,
    refetchOnWindowFocus: true,
  });
};
```

### Hook conventions

- **One hook per resource**. Name: `use<Feature>` (`useProjectTasks`, `useLessonLearnedList`).
- **Query key** = `["feature-name", { ...allParams }]`. Memoise it with `useMemo` if params are objects.
- **`queryFn`** delegates to a service — never call `fetch` directly inside a hook.
- **Defaults**: `staleTime: 30_000`, `refetchOnWindowFocus: true`, `placeholderData: (prev) => prev`.
- For mutations (POST/PUT/DELETE), use `useMutation` and invalidate related query keys in `onSuccess`.

### 7.3 Component usage

```tsx
const { data, isLoading, error } = useProjectTasks({ projectTaskPage, activeProject });

if (isLoading) return <Skeleton />;
if (error)     return <ErrorBanner message={error.message} />;
return <TaskTable rows={data?.tasks ?? []} />;
```

---

## 8. End-to-end walkthroughs

### 8.1 GET — listing tasks

1. `app/my-tasks/page.tsx` calls `useProjectTasks({...})`.
2. React Query checks its cache for `["project-tasks", {...}]`. Cache miss → runs `queryFn`.
3. `queryFn` calls `fetchTaskListService(...)` ([services/fetch-my-tasks.tsx](services/fetch-my-tasks.tsx)).
4. Service `fetch("/api/tasks?project_id=...", { credentials: "include" })`.
5. Browser hits Next.js handler [app/api/tasks/route.ts](app/api/tasks/route.ts).
6. Handler builds `process.env.NEXT_PUBLIC_API_URL + endPoints.tasks + "?..."`, forwards the cookie, calls Odoo.
7. Response bubbles back through handler → service → hook → component.

### 8.2 POST — creating a task

1. User submits the **Add Task** form.
2. Handler calls `createTaskService(payload)` ([services/create-task.ts](services/create-task.ts)) — usually wrapped in a `useMutation`.
3. Service `fetch("/api/tasks/create", { method: "POST", body: JSON.stringify(payload), credentials: "include" })`.
4. Next.js handler [app/api/tasks/create/route.ts](app/api/tasks/create/route.ts) forwards JSON + cookie to `endPoints.createTask` on Odoo.
5. On success → toast + `queryClient.invalidateQueries(["project-tasks"])` to refresh the list.
6. On failure → service throws `ApiError`; the mutation's `onError` shows the message.

---

## 9. Checklist for adding a new API call

1. Add the backend path to [middleware/endPoints.ts](middleware/endPoints.ts) under the right comment block.
2. Create a Next.js route handler `app/api/<feature>/route.ts` that imports `endPoints.<key>`, forwards the cookie, and relays the upstream status.
3. Create a service `services/<verb>-<thing>.ts(x)`:
   - Hits `/api/<feature>` (the route from step 2 — never the Odoo URL).
   - Declares typed payload + response.
   - Throws `ApiError` on non-OK.
4. Create a hook `hooks/use<Feature>.ts` that wraps the service in `useQuery` (read) or `useMutation` (write).
5. Use the hook in your component. Never call `fetch` directly from a component.

---

## 10. Common pitfalls

- **Don't call `process.env.NEXT_PUBLIC_API_URL` from a client component.** That bypasses the proxy and exposes the backend URL.
- **Don't forget `credentials: "include"`** on client `fetch`s — the session cookie won't be sent.
- **Don't hardcode `/session/auth/...` paths.** Always go through `endPoints`.
- **Don't return `null` from a service on error.** Throw `ApiError` so React Query surfaces it via `error`.
- **Memoise the query key** when it contains objects or arrays; otherwise React Query treats every render as a new key and refetches forever.
