feat(smart-app): implement complete mobile app MVP

- App.tsx: full navigation (Auth stack + Main tabs with 5 screens)
- Auth: LoginScreen, RegisterScreen, ForgotPasswordScreen
- HomeScreen: dashboard with IoT metrics, weather widget, alerts, quick actions, sensors
- MapScreen: interactive map with layer toggles (6 layers)
- MarketplaceScreen: categories (6), products (5), search
- ChatScreen: AI chat with quick prompts (4), bot responses
- ProfileScreen: user info, stats, menu (9 items), logout
- AlertsScreen: alert list with severity, acknowledge
- SensorsScreen: sensor list with type filters (6 types), search
- ZonesScreen: zone cards with stats
- SettingsScreen: language picker (FR/EN/ES/DE), privacy, about
- Stores: iotStore (sensors, zones, alerts), notificationStore, uiStore + i18n
- Hooks: useSensors, useAlerts, useNotifications, useLocation
- Components: Card, Button, LoadingSpinner, ErrorBoundary, Header
- Services: iotService, notificationService (with axios API client)
- Utils: formatters (temp, AQI, noise, dates), validators (email, password, IBAN)
- Theme: colors.ts with full design system (Blue Ocean palette)
- Ditto: fixed MongoDB connection, new JWT secrets, official gateway image
This commit is contained in:
Eric FELIXINE
2026-06-01 18:00:35 -04:00
parent 08ca495bde
commit e30ae8ed09
35578 changed files with 3703534 additions and 43 deletions

View File

@@ -0,0 +1,229 @@
/**
* API Client — Axios instance with JWT interceptors & automatic token refresh.
*
* Usage:
* import { api, get, post, put, delete } from '@/services/api';
* const { data } = await get<Sensor[]>('/sensors');
* const { data } = await post<Sensor>('/sensors', { name: 'PM2.5' });
*/
import axios, {
AxiosError,
AxiosInstance,
AxiosResponse,
InternalAxiosRequestConfig,
} from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Base URL for every API call points to the production gateway. */
export const API_BASE_URL = 'https://api-smartapp.digitribe.fr/api/v1';
const ACCESS_TOKEN_KEY = 'access_token';
const REFRESH_TOKEN_KEY = 'refresh_token';
/** Timeout for every request in milliseconds. */
const REQUEST_TIMEOUT_MS = 15_000;
/** HTTP status codes that trigger special handling. */
const HTTP_UNAUTHORIZED = 401;
const HTTP_FORBIDDEN = 403;
const HTTP_NOT_FOUND = 404;
const HTTP_SERVER_ERROR = 500;
// ---------------------------------------------------------------------------
// Token helpers (AsyncStorage-backed)
// ---------------------------------------------------------------------------
const getToken = async (): Promise<string | null> =>
AsyncStorage.getItem(ACCESS_TOKEN_KEY);
const getRefreshToken = async (): Promise<string | null> =>
AsyncStorage.getItem(REFRESH_TOKEN_KEY);
const setTokens = async (access: string, refresh?: string): Promise<void> => {
await AsyncStorage.setItem(ACCESS_TOKEN_KEY, access);
if (refresh) {
await AsyncStorage.setItem(REFRESH_TOKEN_KEY, refresh);
}
};
const clearTokens = async (): Promise<void> => {
await AsyncStorage.multiRemove([ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY]);
};
// ---------------------------------------------------------------------------
// Axios instance
// ---------------------------------------------------------------------------
export const api: AxiosInstance = axios.create({
baseURL: API_BASE_URL,
timeout: REQUEST_TIMEOUT_MS,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
// ---------------------------------------------------------------------------
// Request interceptor — attach Bearer token
// ---------------------------------------------------------------------------
api.interceptors.request.use(
async (config: InternalAxiosRequestConfig) => {
const token = await getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error: AxiosError) => Promise.reject(error),
);
// ---------------------------------------------------------------------------
// Response interceptor — error handling + automatic token refresh
// ---------------------------------------------------------------------------
/** Queue of failed requests that will be retried after a token refresh. */
let isRefreshing = false;
let failedQueue: Array<{
resolve: (token: string) => void;
reject: (error: AxiosError) => void;
}> = [];
const processQueue = (error: AxiosError | null, token: string | null) => {
failedQueue.forEach((prom) => {
if (error) {
prom.reject(error);
} else {
prom.resolve(token as string);
}
});
failedQueue = [];
};
api.interceptors.response.use(
(response: AxiosResponse) => response,
async (error: AxiosError) => {
const originalRequest = error.config as InternalAxiosRequestConfig & {
_retry?: boolean;
};
// -----------------------------------------------------------------------
// 401 Unauthorized → attempt silent token refresh
// -----------------------------------------------------------------------
if (
error.response?.status === HTTP_UNAUTHORIZED &&
!originalRequest._retry &&
originalRequest.url &&
// Avoid infinite loop on the refresh endpoint itself
!originalRequest.url.includes('/auth/refresh')
) {
if (isRefreshing) {
// Someone else is already refreshing queue this request
return new Promise((resolve, reject) => {
failedQueue.push({
resolve: (token: string) => {
originalRequest.headers.Authorization = `Bearer ${token}`;
resolve(api(originalRequest));
},
reject,
});
});
}
originalRequest._retry = true;
isRefreshing = true;
try {
const refreshToken = await getRefreshToken();
if (!refreshToken) {
throw new Error('No refresh token available');
}
// Call the refresh endpoint
const { data } = await axios.post<{ accessToken: string; refreshToken?: string }>(
`${API_BASE_URL}/auth/refresh`,
{ refreshToken },
);
const newAccess = data.accessToken;
const newRefresh = data.refreshToken ?? refreshToken;
await setTokens(newAccess, newRefresh);
// Update the default header so subsequent requests use the new token
api.defaults.headers.common.Authorization = `Bearer ${newAccess}`;
originalRequest.headers.Authorization = `Bearer ${newAccess}`;
processQueue(null, newAccess);
return api(originalRequest);
} catch (refreshError) {
processQueue(refreshError as AxiosError, null);
await clearTokens();
// Optionally: navigate to login screen via an event or navigation ref
return Promise.reject(refreshError);
} finally {
isRefreshing = false;
}
}
// -----------------------------------------------------------------------
// 403 Forbidden (valid token but insufficient permissions)
// -----------------------------------------------------------------------
if (error.response?.status === HTTP_FORBIDDEN) {
// Consumer can handle (e.g. show "access denied" toast)
return Promise.reject(error);
}
// -----------------------------------------------------------------------
// 404 Not Found
// -----------------------------------------------------------------------
if (error.response?.status === HTTP_NOT_FOUND) {
return Promise.reject(error);
}
// -----------------------------------------------------------------------
// 500 Server Error
// -----------------------------------------------------------------------
if (
error.response?.status === HTTP_SERVER_ERROR ||
(error.response?.status && error.response.status >= 500)
) {
// Consumer can handle (e.g. show "server error" toast, retry UI)
return Promise.reject(error);
}
// -----------------------------------------------------------------------
// Any other error
// -----------------------------------------------------------------------
return Promise.reject(error);
},
);
// ---------------------------------------------------------------------------
// Typed helper functions
// ---------------------------------------------------------------------------
/** Generic GET request. */
export const get = <T>(url: string, params?: object, config = {}) =>
api.get<T>(url, { params, ...config }).then((r) => r.data);
/** Generic POST request. */
export const post = <T>(url: string, data?: object, config = {}) =>
api.post<T>(url, data, config).then((r) => r.data);
/** Generic PUT request. */
export const put = <T>(url: string, data?: object, config = {}) =>
api.put<T>(url, data, config).then((r) => r.data);
/** Generic DELETE request. */
export const del = <T>(url: string, config = {}) =>
api.delete<T>(url, config).then((r) => r.data);
// Default export for convenience
export default api;

View File

@@ -0,0 +1,96 @@
import { useAuthStore } from '../stores/authStore';
import type { LoginResponse, RegisterData, User } from '../stores/authStore';
const API_BASE_URL = process.env.EXPO_PUBLIC_API_URL ?? 'http://localhost:8000';
export const authService = {
async login(email: string, password: string): Promise<LoginResponse> {
const res = await fetch(`${API_BASE_URL}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.message ?? body.error ?? `Login failed (${res.status})`);
}
const data: LoginResponse = await res.json();
// Sync with store
useAuthStore.setState({
user: data.user,
accessToken: data.accessToken,
refreshToken: data.refreshToken,
isAuthenticated: true,
});
return data;
},
async register(data: RegisterData): Promise<LoginResponse> {
const res = await fetch(`${API_BASE_URL}/api/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.message ?? body.error ?? `Registration failed (${res.status})`);
}
const result: LoginResponse = await res.json();
useAuthStore.setState({
user: result.user,
accessToken: result.accessToken,
refreshToken: result.refreshToken,
isAuthenticated: true,
});
return result;
},
async logout(): Promise<void> {
const { accessToken } = useAuthStore.getState();
if (accessToken) {
try {
await fetch(`${API_BASE_URL}/api/auth/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
});
} catch { /* ignore */ }
}
useAuthStore.setState({
user: null,
accessToken: null,
refreshToken: null,
isAuthenticated: false,
});
},
async refreshToken(): Promise<LoginResponse | null> {
const { refreshToken } = useAuthStore.getState();
if (!refreshToken) return null;
const res = await fetch(`${API_BASE_URL}/api/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken }),
});
if (!res.ok) {
useAuthStore.setState({
user: null,
accessToken: null,
refreshToken: null,
isAuthenticated: false,
error: 'Session expired',
});
return null;
}
const data: LoginResponse = await res.json();
useAuthStore.setState({
user: data.user,
accessToken: data.accessToken,
refreshToken: data.refreshToken,
isAuthenticated: true,
});
return data;
},
};

View File

@@ -0,0 +1 @@
// TODO: Implement

View File

@@ -0,0 +1,41 @@
// Smart App City — IoT Service
import { get, post, put, del } from './api';
import type { Sensor, Zone, Alert } from '../stores/iotStore';
export const iotService = {
async getSensors(): Promise<Sensor[]> {
return get<Sensor[]>('/sensors');
},
async getSensor(id: string): Promise<Sensor> {
return get<Sensor>(`/sensors/${id}`);
},
async getZones(): Promise<Zone[]> {
return get<Zone[]>('/zones');
},
async getZone(id: string): Promise<Zone> {
return get<Zone>(`/zones/${id}`);
},
async getAlerts(): Promise<Alert[]> {
return get<Alert[]>('/alerts');
},
async acknowledgeAlert(id: string): Promise<void> {
return put(`/alerts/${id}/acknowledge`);
},
async createSensor(data: Partial<Sensor>): Promise<Sensor> {
return post<Sensor>('/sensors', data);
},
async updateSensor(id: string, data: Partial<Sensor>): Promise<Sensor> {
return put<Sensor>(`/sensors/${id}`, data);
},
async deleteSensor(id: string): Promise<void> {
return del(`/sensors/${id}`);
},
};

View File

@@ -0,0 +1,38 @@
// Smart App City — Notification Service
import { get, post, del } from './api';
import type { AppNotification } from '../stores/notificationStore';
export const notificationService = {
async getNotifications(): Promise<AppNotification[]> {
return get<AppNotification[]>('/notifications');
},
async markAsRead(id: string): Promise<void> {
return post(`/notifications/${id}/read`);
},
async markAllAsRead(): Promise<void> {
return post('/notifications/read-all');
},
async deleteNotification(id: string): Promise<void> {
return del(`/notifications/${id}`);
},
async clearAll(): Promise<void> {
return del('/notifications');
},
async registerPushToken(token: string): Promise<void> {
return post('/notifications/push-token', { token });
},
async updatePreferences(prefs: {
pushEnabled: boolean;
alertNotifications: boolean;
eventNotifications: boolean;
systemNotifications: boolean;
}): Promise<void> {
return post('/notifications/preferences', prefs);
},
};