normogen/web/normogen-web/src/services/api.ts
goose b6be945855 feat: Phase 3c — dose logging + adherence, profile management, tests
Three workstreams, all backend+frontend (per scope decisions):

Dose logging + real adherence (backend + frontend):
* log_dose now returns the created dose (201 + body) instead of an empty 201.
* get_adherence implemented for real: queries the medication_doses collection
  over the last 30 days, counts taken vs total, computes the rate. The previous
  implementation hardcoded zeros. Removed the dead calculate_adherence stub.
* Frontend: fixed DoseLog type to match backend MedicationDose (taken:bool,
  loggedAt, camelCase); added AdherenceStats + LogDoseRequest types; logDose() +
  getAdherence() in api.ts; loadAdherence/logDose actions in the medication
  store (adherence cache keyed by med id); new DoseLogger component (Taken/
  Skipped buttons + LinearProgress adherence bar) embedded in each
  MedicationManager card.

Profile management (backend + frontend):
* New GET/PUT /api/profiles/me endpoints (ProfileResponse excludes encryption
  fields; find_by_user_id + update_name on ProfileRepository).
* Register auto-creates a default 'patient' profile (deterministic profile_id =
  profile_<user_id>) — this is the contract the frontend relies on.
* Frontend: Profile type; getProfile()/updateProfileName() in api.ts; useProfileStore;
  new ProfileEditor component (view/edit name, shows role) as a 4th Dashboard tab.
* Resolved the MedicationManager profile_id TODO: now derives profile_<user_id>
  instead of the 'default' fallback.
* NOTE: profile name is stored plaintext (the model anticipates encryption via
  nameIv/nameAuthTag but no crypto layer is implemented yet — TODO).

Vitest tests:
* Added @testing-library/user-event; setupTests clears localStorage + cleanup
  between tests; new test/mockStore.ts helper (mocks the co-located stores,
  handles both selector and no-selector call patterns).
* 5 test files, 20 tests: SeverityChip (4), useMedicationStore actions incl.
  loadMedications/createMedication/logDose (4), MedicationManager render+dialog
  (5), InteractionsChecker selection+results (4), HealthStats table+dialog (3).

Verified: backend cargo fmt/build/clippy 0 warnings, 19 unit tests pass;
frontend npm build clean, 20 vitest tests pass. Solaria round-trip confirmed:
profile auto-created on register (GET /profiles/me), PUT updates name, dose log
returns the dose body, adherence computes 66.7% for 2-taken/1-skipped.

KNOWN FOLLOW-UP (separate task): the backend Medication list response is deeply
nested + camelCase + stores fields inside medicationData.data; the frontend
Medication type assumes flat top-level snake_case fields. This pre-dates Phase 3c
and affects the whole MedicationManager — needs a backend serialization fix or a
frontend adapter.
2026-06-28 10:32:28 -03:00

327 lines
9.7 KiB
TypeScript

import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios';
import {
User,
LoginRequest,
RegisterRequest,
AuthTokens,
Medication,
CreateMedicationRequest,
UpdateMedicationRequest,
DrugInteraction,
CheckInteractionRequest,
CheckNewMedicationRequest,
HealthStat,
CreateHealthStatRequest,
TrendData,
ApiError,
DoseLog,
LogDoseRequest,
AdherenceStats,
Profile,
} from '../types/api';
// API base URL. In dev this is "/api", proxied by the Vite dev server to the
// backend (see vite.config.ts). For a production build pointed at a remote
// backend, set VITE_API_URL to the absolute URL at build time.
const API_BASE = import.meta.env.VITE_API_URL || '/api';
class ApiService {
private client: AxiosInstance;
private token: string | null = null;
private refreshToken: string | null = null;
private refreshing: Promise<string | null> | null = null;
constructor() {
this.client = axios.create({
baseURL: API_BASE,
headers: {
'Content-Type': 'application/json',
},
});
// Load tokens from localStorage (single source of truth shared with the
// zustand auth store's persist).
this.token = localStorage.getItem('token');
this.refreshToken = localStorage.getItem('refresh_token');
if (this.token) {
this.setAuthHeader(this.token);
}
// Request interceptor: attach the access token.
this.client.interceptors.request.use(
(config) => {
if (this.token) {
config.headers.Authorization = `Bearer ${this.token}`;
}
return config;
},
(error) => Promise.reject(error),
);
// Response interceptor: on 401, attempt ONE silent refresh; if it fails,
// clear credentials and redirect to /login.
this.client.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const original = error.config as InternalAxiosRequestConfig & {
_retried?: boolean;
_noRefresh?: boolean;
};
if (
error.response?.status === 401 &&
!original._retried &&
!original._noRefresh &&
this.refreshToken
) {
original._retried = true;
const newToken = await this.doRefresh();
if (newToken) {
original.headers!.Authorization = `Bearer ${newToken}`;
return this.client.request(original);
}
// Refresh failed: drop credentials and bounce to login.
this.clearCredentials();
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
return Promise.reject(this.handleError(error));
}
return Promise.reject(this.handleError(error));
},
);
}
private handleError(error: AxiosError): ApiError {
if (error.response) {
const data = error.response.data as Record<string, unknown>;
return {
message:
(data.error as string) ||
(data.message as string) ||
'An error occurred',
code: String(error.response.status),
details: data,
};
} else if (error.request) {
return {
message: 'No response from server',
code: 'NETWORK_ERROR',
};
} else {
return {
message: error.message || 'Unknown error',
code: 'UNKNOWN',
};
}
}
private setAuthHeader(token: string) {
this.client.defaults.headers.common['Authorization'] = `Bearer ${token}`;
}
setTokens(accessToken: string, refreshToken: string) {
this.token = accessToken;
this.refreshToken = refreshToken;
localStorage.setItem('token', accessToken);
localStorage.setItem('refresh_token', refreshToken);
this.setAuthHeader(accessToken);
}
setToken(token: string) {
this.token = token;
localStorage.setItem('token', token);
this.setAuthHeader(token);
}
getToken(): string | null {
return this.token;
}
getRefreshToken(): string | null {
return this.refreshToken;
}
clearCredentials() {
this.token = null;
this.refreshToken = null;
localStorage.removeItem('token');
localStorage.removeItem('refresh_token');
delete this.client.defaults.headers.common['Authorization'];
}
/** Log out: revoke the refresh token server-side, then clear local state. */
async logout() {
if (this.refreshToken) {
try {
await this.client.post('/auth/logout', { refresh_token: this.refreshToken });
} catch {
// Best-effort: even if the server call fails, drop local credentials.
}
}
this.clearCredentials();
}
/** Perform a single in-flight refresh, deduped across concurrent requests. */
private async doRefresh(): Promise<string | null> {
if (this.refreshing) return this.refreshing;
if (!this.refreshToken) return null;
this.refreshing = (async () => {
try {
const response = await this.client.post<AuthTokens>('/auth/refresh', {
refresh_token: this.refreshToken,
});
const { token, refresh_token } = response.data;
this.setTokens(token, refresh_token);
return token;
} catch {
return null;
} finally {
this.refreshing = null;
}
})();
return this.refreshing;
}
// ---- Authentication ----
async login(email: string, _password: string): Promise<AuthTokens> {
// _password is used in the request body below; renamed only to satisfy the
// interface signature kept for store compatibility.
const response = await this.client.post<AuthTokens>('/auth/login', {
email,
password: _password,
});
this.setTokens(response.data.token, response.data.refresh_token);
return response.data;
}
async register(data: RegisterRequest): Promise<AuthTokens> {
const response = await this.client.post<AuthTokens>('/auth/register', data);
this.setTokens(response.data.token, response.data.refresh_token);
return response.data;
}
async getCurrentUser(): Promise<User> {
const response = await this.client.get<User>('/users/me');
return response.data;
}
// ---- Profile (Phase 3c) ----
async getProfile(): Promise<Profile> {
const response = await this.client.get<Profile>('/profiles/me');
return response.data;
}
async updateProfileName(name: string): Promise<Profile> {
const response = await this.client.put<Profile>('/profiles/me', { name });
return response.data;
}
// ---- Medications ----
async getMedications(): Promise<Medication[]> {
const response = await this.client.get<Medication[]>('/medications');
return response.data;
}
async getMedication(id: string): Promise<Medication> {
const response = await this.client.get<Medication>(`/medications/${id}`);
return response.data;
}
async createMedication(data: CreateMedicationRequest): Promise<Medication> {
const response = await this.client.post<Medication>('/medications', data);
return response.data;
}
async updateMedication(id: string, data: UpdateMedicationRequest): Promise<Medication> {
// Backend update is POST /:id (not PUT).
const response = await this.client.post<Medication>(`/medications/${id}`, data);
return response.data;
}
async deleteMedication(id: string): Promise<void> {
// Backend delete is POST /:id/delete (not DELETE /:id).
await this.client.post(`/medications/${id}/delete`);
}
// ---- Dose logging + adherence (Phase 3c) ----
async logDose(medicationId: string, req: LogDoseRequest): Promise<DoseLog> {
const response = await this.client.post<DoseLog>(`/medications/${medicationId}/log`, req);
return response.data;
}
async getAdherence(medicationId: string): Promise<AdherenceStats> {
const response = await this.client.get<AdherenceStats>(`/medications/${medicationId}/adherence`);
return response.data;
}
// ---- Drug Interactions (Phase 2.8) ----
async checkInteractions(medications: string[]): Promise<DrugInteraction[]> {
const response = await this.client.post<DrugInteraction[]>('/interactions/check', {
medications,
});
return response.data;
}
async checkNewMedication(name: string, dosage: string): Promise<DrugInteraction[]> {
const response = await this.client.post<DrugInteraction[]>('/interactions/check-new', {
name,
dosage,
});
return response.data;
}
// ---- Health Statistics ----
async getHealthStats(): Promise<HealthStat[]> {
const response = await this.client.get<HealthStat[]>('/health-stats');
return response.data;
}
async getHealthStat(id: string): Promise<HealthStat> {
const response = await this.client.get<HealthStat>(`/health-stats/${id}`);
return response.data;
}
async createHealthStat(data: CreateHealthStatRequest): Promise<HealthStat> {
const response = await this.client.post<HealthStat>('/health-stats', data);
return response.data;
}
async updateHealthStat(id: string, data: Partial<CreateHealthStatRequest>): Promise<HealthStat> {
const response = await this.client.put<HealthStat>(`/health-stats/${id}`, data);
return response.data;
}
async deleteHealthStat(id: string): Promise<void> {
await this.client.delete(`/health-stats/${id}`);
}
async getHealthTrends(): Promise<TrendData[]> {
const response = await this.client.get<TrendData[]>('/health-stats/trends');
return response.data;
}
// NOTE: lab-results endpoints are intentionally absent — the backend has no
// /lab-results routes yet. The LabResult type stays in types/api.ts for when
// those routes land.
}
// Export singleton instance
export const apiService = new ApiService();
export default apiService;
// Satisfy the unused-import linter for types referenced only via generics above.
export type {
LoginRequest,
CheckInteractionRequest,
CheckNewMedicationRequest,
};