chore: build
Backend - Build & Lint / build (push) Successful in 31m59s
Frontend Admin - EAS Build / build (push) Successful in 1h32m56s

This commit is contained in:
Xor290
2026-11-01 13:08:58 +01:00
parent f3eaea4347
commit 0a18460f13
20 changed files with 1694 additions and 190 deletions
+78 -55
View File
@@ -207,14 +207,44 @@ export const getAdminStatsByMonth = async (
);
return data;
};
export const getAllClients = async (): Promise<ClientResponse[]> => {
const { data } = await apiClient.get(`${V2}/admin/protected/all/clients`);
return data.clients || [];
export interface AdminUserItem {
id: number;
username: string;
role: string;
}
export interface PagedResult<T> {
items: T[];
total: number;
hasMore: boolean;
}
export const getAllClients = async (
offset = 0,
limit = 100,
): Promise<PagedResult<ClientResponse>> => {
const { data } = await apiClient.get(`${V2}/admin/protected/all/clients`, {
params: { limit, offset },
});
return {
items: data.clients || [],
total: data.count ?? 0,
hasMore: !!data.has_more,
};
};
export const getAllUsers = async () => {
const { data } = await apiClient.get(`${V2}/admin/protected/all/users`);
return data.users || [];
export const getAllUsers = async (
offset = 0,
limit = 100,
): Promise<PagedResult<AdminUserItem>> => {
const { data } = await apiClient.get(`${V2}/admin/protected/all/users`, {
params: { limit, offset },
});
return {
items: data.users || [],
total: data.count ?? 0,
hasMore: !!data.has_more,
};
};
export const updateClientByAdmin = async (
@@ -489,60 +519,37 @@ export const getAllDeliveryPersonsWithDetails = async (): Promise<{
stats: DeliveryPersonsStats;
}> => {
try {
// Le backend renvoie désormais statut/position/compteurs déjà
// enrichis pour tous les livreurs en un seul appel (voir
// GetDeliveryPersonsDetailsBatch côté backend) : plus besoin d'un
// aller-retour /delivery-persons/:username par livreur ici.
const { data } = await apiClient.get(
`${V2}/admin/protected/delivery-persons`,
);
const livreurs = data.livreurs || [];
const enriched = await Promise.all(
livreurs.map(async (l: any): Promise<DeliveryPerson> => {
try {
const details = await getDeliveryPersonDetails(l.username);
const parsedStatus = parseStatus(details.status);
const hasLoc =
details.location?.latitude &&
details.location?.longitude;
return {
id: l.id,
username: l.username,
status: parsedStatus,
location: {
latitude: hasLoc ? details.location.latitude : 0,
longitude: hasLoc ? details.location.longitude : 0,
last_update: details.location?.last_update
? new Date(
details.location.last_update * 1000,
).toISOString()
: new Date().toISOString(),
is_recent: details.location?.is_recent || false,
},
stats: {
total_deliveries: details.total_deliveries || 0,
completed_today: details.completed_deliveries || 0,
queue_size: details.queue_size || 0,
current_command: details.current_command || null,
},
};
} catch {
return {
id: l.id,
username: l.username,
status: "offline",
location: {
latitude: 0,
longitude: 0,
last_update: new Date().toISOString(),
is_recent: false,
},
stats: {
total_deliveries: 0,
completed_today: 0,
queue_size: 0,
current_command: null,
},
};
}
}),
const enriched: DeliveryPerson[] = livreurs.map(
(l: any): DeliveryPerson => {
const parsedStatus = parseStatus(l.status);
const hasLoc = l.location?.latitude && l.location?.longitude;
return {
id: l.id,
username: l.username,
status: parsedStatus,
location: {
latitude: hasLoc ? l.location.latitude : 0,
longitude: hasLoc ? l.location.longitude : 0,
last_update: new Date().toISOString(),
is_recent: false,
},
stats: {
total_deliveries: l.total_deliveries || 0,
completed_today: l.completed_deliveries || 0,
queue_size: l.queue_size || 0,
current_command: l.current_command || null,
},
};
},
);
const stats: DeliveryPersonsStats = {
@@ -755,6 +762,22 @@ export const getClientReferralAdmin = async (
}
};
export const resetClientRateLimit = async (
username: string,
): Promise<{ success: boolean; error?: string }> => {
try {
await apiClient.post(
`${V2}/admin/protected/client/${username}/ratelimit/reset`,
);
return { success: true };
} catch (e: any) {
return {
success: false,
error: e.response?.data?.error || "Erreur levée du rate limit",
};
}
};
export const resetClientReferral = async (
username: string,
): Promise<{ success: boolean; message?: string }> => {
+41 -53
View File
@@ -186,60 +186,35 @@ export const getAllDeliveryPersonsWithDetails = async (): Promise<{
stats: DeliveryPersonsStats;
}> => {
try {
// Le backend renvoie désormais statut/position/compteurs déjà
// enrichis pour tous les livreurs en un seul appel (voir
// GetDeliveryPersonsDetailsBatch côté backend) : plus besoin d'un
// aller-retour /delivery-persons/:username par livreur ici.
const { data } = await apiClient.get(`${API}/all/deliveryman`);
const users = data.users || [];
const enriched = await Promise.all(
users.map(async (u: any): Promise<DeliveryPerson> => {
try {
const { data: details } = await apiClient.get(
`${API}/delivery-persons/${u.username}`,
);
const d = details.deliveryman || details;
const parsedStatus = parseStatus(d.status);
const hasLoc =
d.location?.latitude && d.location?.longitude;
return {
id: u.id,
username: u.username,
status: parsedStatus,
location: {
latitude: hasLoc ? d.location.latitude : 0,
longitude: hasLoc ? d.location.longitude : 0,
last_update: d.location?.last_update
? new Date(
d.location.last_update * 1000,
).toISOString()
: new Date().toISOString(),
is_recent: d.location?.is_recent || false,
},
stats: {
total_deliveries: d.total_deliveries || 0,
completed_today: d.completed_deliveries || 0,
queue_size: d.queue_size || 0,
current_command: d.current_command || null,
},
};
} catch {
return {
id: u.id,
username: u.username,
status: "offline",
location: {
latitude: 0,
longitude: 0,
last_update: new Date().toISOString(),
is_recent: false,
},
stats: {
total_deliveries: 0,
completed_today: 0,
queue_size: 0,
current_command: null,
},
};
}
}),
const enriched: DeliveryPerson[] = users.map(
(u: any): DeliveryPerson => {
const parsedStatus = parseStatus(u.status);
const hasLoc = u.location?.latitude && u.location?.longitude;
return {
id: u.id,
username: u.username,
status: parsedStatus,
location: {
latitude: hasLoc ? u.location.latitude : 0,
longitude: hasLoc ? u.location.longitude : 0,
last_update: new Date().toISOString(),
is_recent: false,
},
stats: {
total_deliveries: u.total_deliveries || 0,
completed_today: u.completed_deliveries || 0,
queue_size: u.queue_size || 0,
current_command: u.current_command || null,
},
};
},
);
const stats: DeliveryPersonsStats = {
@@ -447,10 +422,23 @@ export const getCabineCommands = async (): Promise<{
// CLIENTS — CABINE
// ============================================
// Le backend pagine désormais cette route (100 clients par page) ; on boucle
// ici pour que l'appelant continue de recevoir la liste complète d'un coup.
export const getCabineAllClients = async (): Promise<any[]> => {
try {
const { data } = await apiClient.get(`${API}/all/clients`);
return data.clients || [];
const all: any[] = [];
let offset = 0;
const limit = 100;
while (true) {
const { data } = await apiClient.get(`${API}/all/clients`, {
params: { limit, offset },
});
const clients = data.clients || [];
all.push(...clients);
if (!data.has_more || clients.length === 0) break;
offset += clients.length;
}
return all;
} catch {
return [];
}
+2
View File
@@ -31,6 +31,8 @@ export interface ClientResponse {
cancellations_count: number;
last_penalty_reason?: string;
referral_balance?: number;
parrain?: string | null;
rate_limited?: boolean;
}
export interface CommandResponse {
@@ -52,8 +52,8 @@ export default function DashboardScreen() {
getCommandCountByStatus("pending"),
getCommandCountByStatus("en_route"),
getCommandCountByStatus("approved"),
getAllClients()
.then((c) => c.length)
getAllClients(0, 1)
.then((r) => r.total)
.catch(() => 0),
getAvailableDeliveryPersons()
.then((r) => r.count)
+169 -48
View File
@@ -11,7 +11,7 @@ import {
ActivityIndicator,
useWindowDimensions,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { Ionicons, FontAwesome5 } from "@expo/vector-icons";
import { spacing, fontSize, borderRadius } from "../../theme";
import { useTheme } from "../../context/ThemeContext";
import {
@@ -24,13 +24,13 @@ import {
createClientByAdmin,
createUserByAdmin,
setClientParrain,
getClientParrain,
creditClientReferral,
resetClientReferral,
getClientCancelledOrders,
getSettings,
applyClientPenalty,
resetClientPenalties,
resetClientRateLimit,
resetClientPoints,
addClientPoints,
subtractClientPoints,
@@ -138,8 +138,12 @@ export default function UsersScreen() {
}
}, []);
const PAGE_SIZE = 100;
const [users, setUsers] = useState<UserItem[]>([]);
const [clients, setClients] = useState<ClientResponse[]>([]);
const [usersHasMore, setUsersHasMore] = useState(true);
const [clientsHasMore, setClientsHasMore] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [poolNames, setPoolNames] = useState<string[]>([]);
@@ -249,15 +253,19 @@ export default function UsersScreen() {
// --------------------------------------------------
// Data
// --------------------------------------------------
// Charge la première page (100 users + 100 clients). D'autres pages sont
// chargées via loadMore() au fur et à mesure que l'utilisateur scrolle.
const loadData = useCallback(async () => {
try {
const [usersData, clientsData, settingsRes] = await Promise.all([
getAllUsers(),
getAllClients(),
const [usersRes, clientsRes, settingsRes] = await Promise.all([
getAllUsers(0, PAGE_SIZE),
getAllClients(0, PAGE_SIZE),
getSettings(),
]);
setUsers(usersData);
setClients(clientsData);
setUsers(usersRes.items);
setClients(clientsRes.items);
setUsersHasMore(usersRes.hasMore);
setClientsHasMore(clientsRes.hasMore);
if (settingsRes.success && settingsRes.settings) {
const pools = settingsRes.settings.points_pools ?? [];
setPoolNames(pools.map((p) => p.name));
@@ -271,33 +279,58 @@ export default function UsersScreen() {
);
}
// Charger le parrain de chaque client en parallèle (best-effort,
// une erreur sur un client n'empêche pas les autres de s'afficher).
const clientUsernames = (clientsData ?? []).map((c) => c.username);
if (clientUsernames.length > 0) {
const results = await Promise.all(
clientUsernames.map(async (username) => {
const res = await getClientParrain(username);
return [
username,
res.success ? (res.parrain ?? null) : null,
] as const;
}),
);
const map: Record<string, string | null> = {};
for (const [username, parrain] of results) {
map[username] = parrain;
}
setParrainMap(map);
} else {
setParrainMap({});
const map: Record<string, string | null> = {};
for (const c of clientsRes.items) {
map[c.username] = c.parrain || null;
}
setParrainMap(map);
} catch {
/* ignore */
}
setLoading(false);
}, []);
// Charge la page suivante de users/clients et l'ajoute à la liste déjà
// affichée (déclenché par le scroll de la FlatList, cf. onEndReached).
const loadMore = useCallback(async () => {
if (loadingMore || (!usersHasMore && !clientsHasMore)) return;
setLoadingMore(true);
try {
const [usersRes, clientsRes] = await Promise.all([
usersHasMore
? getAllUsers(users.length, PAGE_SIZE)
: Promise.resolve<{
items: UserItem[];
hasMore: boolean;
}>({ items: [], hasMore: false }),
clientsHasMore
? getAllClients(clients.length, PAGE_SIZE)
: Promise.resolve<{
items: ClientResponse[];
hasMore: boolean;
}>({ items: [], hasMore: false }),
]);
if (usersRes.items.length > 0) {
setUsers((prev) => [...prev, ...usersRes.items]);
}
setUsersHasMore(usersRes.hasMore);
if (clientsRes.items.length > 0) {
setClients((prev) => [...prev, ...clientsRes.items]);
setParrainMap((prev) => {
const next = { ...prev };
for (const c of clientsRes.items) {
next[c.username] = c.parrain || null;
}
return next;
});
}
setClientsHasMore(clientsRes.hasMore);
} catch {
/* ignore, l'utilisateur peut re-scroller pour réessayer */
}
setLoadingMore(false);
}, [loadingMore, usersHasMore, clientsHasMore, users.length, clients.length]);
useEffect(() => {
loadData();
}, [loadData]);
@@ -310,21 +343,27 @@ export default function UsersScreen() {
// --------------------------------------------------
// Merged & filtered list
// --------------------------------------------------
const getMergedUsers = () => {
// Build a map of client details by username
// Merge users + clients once per data change, not on every render.
const allMergedUsers = useMemo(() => {
const clientMap = new Map<string, ClientResponse>();
clients.forEach((c) => clientMap.set(c.username, c));
// Merge: for each user from getAllUsers, attach client details if role=client
let merged = users.map((u) => ({
...u,
clientData:
u.role === "client" ? clientMap.get(u.username) || null : null,
}));
const seen = new Set<string>();
const merged = users.map((u) => {
seen.add(u.username);
return {
...u,
clientData:
u.role === "client"
? clientMap.get(u.username) || null
: null,
};
});
// Also add clients that might not be in users list
clients.forEach((c) => {
if (!merged.find((m) => m.username === c.username)) {
if (!seen.has(c.username)) {
seen.add(c.username);
merged.push({
id: c.id,
username: c.username,
@@ -334,6 +373,12 @@ export default function UsersScreen() {
}
});
return merged;
}, [users, clients]);
const mergedUsers = useMemo(() => {
let merged = allMergedUsers;
if (filter !== "all") {
merged = merged.filter((u) => u.role === filter);
}
@@ -355,9 +400,7 @@ export default function UsersScreen() {
}
return merged;
};
const mergedUsers = getMergedUsers();
}, [allMergedUsers, filter, search]);
// Stats
const totalClients =
@@ -459,7 +502,7 @@ export default function UsersScreen() {
// --------------------------------------------------
// Delete user/client
// --------------------------------------------------
const handleDelete = (item: ReturnType<typeof getMergedUsers>[0]) => {
const handleDelete = (item: (typeof allMergedUsers)[number]) => {
const label =
item.role === "client"
? "client"
@@ -592,6 +635,32 @@ export default function UsersScreen() {
);
};
const handleResetRateLimit = (client: ClientResponse) => {
showConfirm(
"Lever le rate limit",
`Débloquer "${client.username}" ? Ses compteurs de requêtes, d'annulations et de modifications d'adresse seront remis à zéro.`,
async () => {
const res = await resetClientRateLimit(client.username);
if (!res.success) {
showError("Erreur", res.error || "Echec");
return;
}
setClients((prev) =>
prev.map((c) =>
c.username === client.username
? { ...c, rate_limited: false }
: c,
),
);
showSuccess(
"Validé",
`Rate limit levé pour "${client.username}"`,
);
},
"Débloquer",
);
};
const handleResetAmende = () => {
if (!sanctionModal.client) return;
showConfirm(
@@ -844,10 +913,16 @@ export default function UsersScreen() {
if (!e.response) {
try {
if (createType === "client") {
const freshClients = await getAllClients();
setClients(freshClients);
// Trié par created_at DESC : un client qui vient
// d'être créé est forcément sur la première page.
const freshClients = await getAllClients(
0,
PAGE_SIZE,
);
setClients(freshClients.items);
setClientsHasMore(freshClients.hasMore);
if (
freshClients.find(
freshClients.items.find(
(c) => c.username === usernameToCreate,
)
) {
@@ -855,11 +930,12 @@ export default function UsersScreen() {
return;
}
} else {
const freshUsers = await getAllUsers();
setUsers(freshUsers);
const freshUsers = await getAllUsers(0, PAGE_SIZE);
setUsers(freshUsers.items);
setUsersHasMore(freshUsers.hasMore);
if (
freshUsers.find(
(u: any) => u.username === usernameToCreate,
freshUsers.items.find(
(u) => u.username === usernameToCreate,
)
) {
setCreateModal(false);
@@ -1084,6 +1160,23 @@ export default function UsersScreen() {
fontSize: fontSize.sm,
fontWeight: "600",
},
rateLimitBtn: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.xs,
marginTop: spacing.m,
paddingVertical: spacing.s,
borderRadius: borderRadius.md,
borderWidth: 1,
borderColor: colors.warning,
backgroundColor: colors.warning + "15",
},
rateLimitBtnText: {
color: colors.warning,
fontSize: fontSize.sm,
fontWeight: "600",
},
}),
[colors, screenWidth],
);
@@ -1094,7 +1187,7 @@ export default function UsersScreen() {
const renderUser = ({
item,
}: {
item: ReturnType<typeof getMergedUsers>[0];
item: (typeof allMergedUsers)[number];
}) => {
const isClient = item.role === "client" && item.clientData;
const roleColor = getRoleBadgeColor(item.role);
@@ -1395,6 +1488,24 @@ export default function UsersScreen() {
</View>
)}
</View>
{item.clientData.rate_limited && (
<TouchableOpacity
style={styles.rateLimitBtn}
onPress={() =>
handleResetRateLimit(item.clientData!)
}
activeOpacity={0.7}
>
<FontAwesome5
name="unlock"
size={14}
color={colors.warning}
/>
<Text style={styles.rateLimitBtnText}>
Rate limité — Débloquer
</Text>
</TouchableOpacity>
)}
</>
)}
@@ -1515,6 +1626,8 @@ export default function UsersScreen() {
data={mergedUsers}
keyExtractor={(item) => `${item.role}-${item.id}`}
renderItem={renderUser}
onEndReached={loadMore}
onEndReachedThreshold={0.5}
refreshControl={
<RefreshControl
refreshing={refreshing}
@@ -1529,6 +1642,14 @@ export default function UsersScreen() {
ListEmptyComponent={
<Text style={styles.empty}>Aucun utilisateur</Text>
}
ListFooterComponent={
loadingMore ? (
<ActivityIndicator
color={colors.accent}
style={{ marginVertical: spacing.l }}
/>
) : null
}
/>
{/* Edit client modal */}