chore: add parrainage

This commit is contained in:
2026-03-08 13:57:25 +01:00
parent 51c65d1179
commit fee1972435
20 changed files with 1356 additions and 348 deletions
+9
View File
@@ -36,6 +36,15 @@
"plugins": [
"expo-font",
"expo-location",
[
"expo-notifications",
{
"icon": "./assets/icon.png",
"color": "#ffffff",
"androidMode": "default",
"androidCollapsedTitle": "#{unread_notifications} nouvelles commandes"
}
],
[
"expo-build-properties",
{
+68
View File
@@ -471,6 +471,44 @@ export const deleteClientAdmin = async (clientId: number) => {
return { success: true, message: data.message };
};
// ============================================
// PARRAINAGE ADMIN
// ============================================
export const creditClientReferral = async (
username: string,
amount: number,
): Promise<{ success: boolean; balance?: number; message?: string }> => {
try {
const { data } = await apiClient.post(
`${V2}/admin/protected/client/${username}/referral/credit`,
{ amount },
);
return { success: true, balance: data.balance, message: data.message };
} catch (error: any) {
return {
success: false,
message: error.response?.data?.error || "Erreur crédit parrainage",
};
}
};
export const getClientReferralAdmin = async (
username: string,
): Promise<{ success: boolean; balance?: number; message?: string }> => {
try {
const { data } = await apiClient.get(
`${V2}/admin/protected/client/${username}/referral`,
);
return { success: true, balance: data.balance };
} catch (error: any) {
return {
success: false,
message: error.response?.data?.error || "Erreur récupération",
};
}
};
// ============================================
// ALERTES
// ============================================
@@ -676,6 +714,7 @@ export interface AppSettings {
points_separated: boolean;
points_weed_tiers: PointsTier[];
points_zipette_tiers: PointsTier[];
referral_enabled: boolean;
}
export const getSettings = async (): Promise<{ success: boolean; settings?: AppSettings; error?: string }> => {
@@ -687,6 +726,35 @@ export const getSettings = async (): Promise<{ success: boolean; settings?: AppS
}
};
export const registerAdminPushToken = async (pushToken: string): Promise<void> => {
try {
await apiClient.post(`${V2}/admin/protected/push-token`, { push_token: pushToken });
} catch { /* ignore */ }
};
export const unregisterAdminPushToken = async (): Promise<void> => {
try {
await apiClient.delete(`${V2}/admin/protected/push-token`);
} catch { /* ignore */ }
};
export interface AppNotification {
command_id: number;
type: string;
message: string;
created_at: string;
read: boolean;
}
export const getAdminNotifications = async (): Promise<{ notifications: AppNotification[]; unread_count: number }> => {
const { data } = await apiClient.get(`${V2}/admin/protected/notifications`);
return data;
};
export const markAdminNotificationsRead = async (): Promise<void> => {
await apiClient.post(`${V2}/admin/protected/notifications/read`);
};
export const updateSettings = async (
settings: AppSettings,
): Promise<{ success: boolean; settings?: AppSettings; error?: string }> => {
+29
View File
@@ -351,6 +351,35 @@ export interface PublicSettings {
points_separated: boolean;
}
export const registerCabinePushToken = async (pushToken: string): Promise<void> => {
try {
await apiClient.post(`${API}/push-token`, { push_token: pushToken });
} catch { /* ignore */ }
};
export const unregisterCabinePushToken = async (): Promise<void> => {
try {
await apiClient.delete(`${API}/push-token`);
} catch { /* ignore */ }
};
export interface AppNotification {
command_id: number;
type: string;
message: string;
created_at: string;
read: boolean;
}
export const getCabineNotifications = async (): Promise<{ notifications: AppNotification[]; unread_count: number }> => {
const { data } = await apiClient.get(`${API}/notifications`);
return data;
};
export const markCabineNotificationsRead = async (): Promise<void> => {
await apiClient.post(`${API}/notifications/read`);
};
export const getPublicSettings = async (): Promise<PublicSettings> => {
try {
const { data } = await apiClient.get(`http://5.181.0.112/api/v1/app-settings`);
+1
View File
@@ -31,6 +31,7 @@ export interface ClientResponse {
amende: number;
cancellations_count: number;
last_penalty_reason?: string;
referral_balance?: number;
}
export interface CommandResponse {
+353 -164
View File
@@ -1,5 +1,12 @@
import React from "react";
import { TouchableOpacity, View } from "react-native";
import React, { useState, useEffect, useRef, useCallback } from "react";
import {
TouchableOpacity,
View,
Modal,
Text,
ScrollView,
StyleSheet,
} from "react-native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { useNavigation } from "@react-navigation/native";
@@ -7,7 +14,12 @@ import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
import { Ionicons } from "@expo/vector-icons";
import { useAuth } from "../auth/AuthContext";
import { useTheme } from "../context/ThemeContext";
import { logoutAdmin } from "../api/api_admin";
import {
logoutAdmin,
getAdminNotifications,
markAdminNotificationsRead,
} from "../api/api_admin";
import type { AppNotification } from "../api/api_admin";
import { fontSize, spacing } from "../theme";
import type { AdminTabParamList, AdminStackParamList } from "./types";
@@ -30,176 +42,288 @@ function AdminTabs() {
const { colors, isDark, toggleTheme } = useTheme();
const navigation = useNavigation<NativeStackNavigationProp<AdminStackParamList>>();
const [notifications, setNotifications] = useState<AppNotification[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const [modalVisible, setModalVisible] = useState(false);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const fetchNotifications = useCallback(async () => {
try {
const res = await getAdminNotifications();
setNotifications(res.notifications ?? []);
setUnreadCount(res.unread_count ?? 0);
} catch { /* ignore */ }
}, []);
useEffect(() => {
fetchNotifications();
intervalRef.current = setInterval(fetchNotifications, 15000);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, [fetchNotifications]);
const openModal = async () => {
setModalVisible(true);
if (unreadCount > 0) {
try {
await markAdminNotificationsRead();
setUnreadCount(0);
setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
} catch { /* ignore */ }
}
};
const handleLogout = async () => {
await logoutAdmin();
await logout();
};
const formatTime = (iso: string) => {
const diff = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
if (diff < 1) return "à l'instant";
if (diff < 60) return `il y a ${diff} min`;
const h = Math.floor(diff / 60);
if (h < 24) return `il y a ${h}h`;
return `il y a ${Math.floor(h / 24)}j`;
};
return (
<Tab.Navigator
screenOptions={{
headerStyle: { backgroundColor: colors.bgSecondary },
headerTintColor: colors.textWhite,
headerRight: () => (
<>
<Tab.Navigator
screenOptions={{
headerStyle: { backgroundColor: colors.bgSecondary },
headerTintColor: colors.textWhite,
headerRight: () => (
<View
style={{
flexDirection: "row",
alignItems: "center",
marginRight: spacing.l,
}}
>
<TouchableOpacity
onPress={openModal}
style={{ marginRight: spacing.m }}
>
<View>
<Ionicons
name="notifications-outline"
size={22}
color={colors.textSecondary}
/>
{unreadCount > 0 && (
<View
style={[
styles.badge,
{ backgroundColor: colors.error ?? "#e74c3c" },
]}
>
<Text style={styles.badgeText}>
{unreadCount > 9 ? "9+" : unreadCount}
</Text>
</View>
)}
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={toggleTheme}
style={{ marginRight: spacing.m }}
>
<Ionicons
name={isDark ? "sunny-outline" : "moon-outline"}
size={22}
color={colors.textSecondary}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={() => navigation.navigate("Settings")}
style={{ marginRight: spacing.m }}
>
<Ionicons
name="settings-outline"
size={22}
color={colors.textSecondary}
/>
</TouchableOpacity>
<TouchableOpacity onPress={handleLogout}>
<Ionicons
name="log-out-outline"
size={24}
color={colors.textSecondary}
/>
</TouchableOpacity>
</View>
),
tabBarStyle: {
backgroundColor: colors.bgSecondary,
borderTopColor: colors.border,
borderTopWidth: 1,
},
tabBarActiveTintColor: colors.accent,
tabBarInactiveTintColor: colors.textMuted,
tabBarLabelStyle: { fontSize: fontSize.xs },
}}
>
<Tab.Screen
name="Dashboard"
component={DashboardScreen}
options={{
title: "Dashboard",
tabBarIcon: ({ color, size }) => (
<Ionicons name="grid-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Orders"
component={OrdersScreen}
options={{
title: "Commandes",
tabBarIcon: ({ color, size }) => (
<Ionicons name="receipt-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Users"
component={UsersScreen}
options={{
title: "Clients",
tabBarIcon: ({ color, size }) => (
<Ionicons name="people-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Products"
component={ProductsScreen}
options={{
title: "Produits",
tabBarIcon: ({ color, size }) => (
<Ionicons name="cube-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Categories"
component={CategoriesScreen}
options={{
title: "Catégories",
tabBarIcon: ({ color, size }) => (
<Ionicons name="pricetag-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Delivery"
component={DeliveryScreen}
options={{
title: "Livreurs",
tabBarIcon: ({ color, size }) => (
<Ionicons name="bicycle-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Alerts"
component={AlertsScreen}
options={{
title: "Alertes",
tabBarIcon: ({ color, size }) => (
<Ionicons name="alert-circle-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Addresses"
component={AddressScreen}
options={{
title: "Adresses",
tabBarIcon: ({ color, size }) => (
<Ionicons name="map-outline" size={size} color={color} />
),
}}
/>
</Tab.Navigator>
<Modal
visible={modalVisible}
transparent
animationType="slide"
onRequestClose={() => setModalVisible(false)}
>
<View style={styles.modalOverlay}>
<View
style={{
flexDirection: "row",
alignItems: "center",
marginRight: spacing.l,
}}
style={[
styles.modalContainer,
{ backgroundColor: colors.bgSecondary },
]}
>
<TouchableOpacity
onPress={toggleTheme}
style={{ marginRight: spacing.m }}
>
<Ionicons
name={isDark ? "sunny-outline" : "moon-outline"}
size={22}
color={colors.textSecondary}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={() => navigation.navigate("Settings")}
style={{ marginRight: spacing.m }}
>
<Ionicons
name="settings-outline"
size={22}
color={colors.textSecondary}
/>
</TouchableOpacity>
<TouchableOpacity onPress={handleLogout}>
<Ionicons
name="log-out-outline"
size={24}
color={colors.textSecondary}
/>
</TouchableOpacity>
<View style={styles.modalHeader}>
<Text
style={[styles.modalTitle, { color: colors.textWhite }]}
>
Notifications
</Text>
<TouchableOpacity onPress={() => setModalVisible(false)}>
<Ionicons
name="close"
size={24}
color={colors.textSecondary}
/>
</TouchableOpacity>
</View>
<ScrollView style={styles.notifList}>
{notifications.length === 0 ? (
<Text
style={[
styles.emptyText,
{ color: colors.textMuted },
]}
>
Aucune notification
</Text>
) : (
notifications.map((n, i) => (
<View
key={i}
style={[
styles.notifItem,
{
borderLeftColor: n.read
? colors.border
: colors.accent,
backgroundColor: n.read
? "transparent"
: colors.bgPrimary ?? colors.bgSecondary,
},
]}
>
<Text
style={[
styles.notifMessage,
{ color: colors.textWhite },
]}
>
{n.message}
</Text>
<Text
style={[
styles.notifTime,
{ color: colors.textMuted },
]}
>
{formatTime(n.created_at)}
</Text>
</View>
))
)}
</ScrollView>
</View>
),
tabBarStyle: {
backgroundColor: colors.bgSecondary,
borderTopColor: colors.border,
borderTopWidth: 1,
},
tabBarActiveTintColor: colors.accent,
tabBarInactiveTintColor: colors.textMuted,
tabBarLabelStyle: { fontSize: fontSize.xs },
}}
>
<Tab.Screen
name="Dashboard"
component={DashboardScreen}
options={{
title: "Dashboard",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="grid-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Orders"
component={OrdersScreen}
options={{
title: "Commandes",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="receipt-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Users"
component={UsersScreen}
options={{
title: "Clients",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="people-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Products"
component={ProductsScreen}
options={{
title: "Produits",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="cube-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Categories"
component={CategoriesScreen}
options={{
title: "Catégories",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="pricetag-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Delivery"
component={DeliveryScreen}
options={{
title: "Livreurs",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="bicycle-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Alerts"
component={AlertsScreen}
options={{
title: "Alertes",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="alert-circle-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Addresses"
component={AddressScreen}
options={{
title: "Adresses",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="map-outline"
size={size}
color={color}
/>
),
}}
/>
</Tab.Navigator>
</View>
</Modal>
</>
);
}
@@ -231,3 +355,68 @@ export default function AdminNavigator() {
</Stack.Navigator>
);
}
const styles = StyleSheet.create({
badge: {
position: "absolute",
top: -4,
right: -6,
minWidth: 16,
height: 16,
borderRadius: 8,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: 2,
},
badgeText: {
color: "#fff",
fontSize: 9,
fontWeight: "bold",
},
modalOverlay: {
flex: 1,
backgroundColor: "rgba(0,0,0,0.5)",
justifyContent: "flex-end",
},
modalContainer: {
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
maxHeight: "70%",
paddingBottom: 32,
},
modalHeader: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
padding: 16,
borderBottomWidth: 1,
borderBottomColor: "rgba(255,255,255,0.1)",
},
modalTitle: {
fontSize: 18,
fontWeight: "bold",
},
notifList: {
padding: 12,
},
notifItem: {
borderLeftWidth: 3,
paddingLeft: 12,
paddingVertical: 10,
marginBottom: 8,
borderRadius: 4,
paddingRight: 8,
},
notifMessage: {
fontSize: 14,
},
notifTime: {
fontSize: 12,
marginTop: 4,
},
emptyText: {
textAlign: "center",
marginTop: 32,
fontSize: 14,
},
});
+299 -112
View File
@@ -1,10 +1,22 @@
import React from "react";
import { TouchableOpacity, View } from "react-native";
import React, { useState, useEffect, useRef, useCallback } from "react";
import {
TouchableOpacity,
View,
Modal,
Text,
ScrollView,
StyleSheet,
} from "react-native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { Ionicons } from "@expo/vector-icons";
import { useAuth } from "../auth/AuthContext";
import { useTheme } from "../context/ThemeContext";
import { logoutAdmin } from "../api/api_admin";
import {
getCabineNotifications,
markCabineNotificationsRead,
} from "../api/api_cabine";
import type { AppNotification } from "../api/api_cabine";
import { fontSize, spacing } from "../theme";
import type { CabineTabParamList } from "./types";
@@ -20,123 +32,298 @@ export default function CabineNavigator() {
const { logout } = useAuth();
const { colors, isDark, toggleTheme } = useTheme();
const [notifications, setNotifications] = useState<AppNotification[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const [modalVisible, setModalVisible] = useState(false);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const fetchNotifications = useCallback(async () => {
try {
const res = await getCabineNotifications();
setNotifications(res.notifications ?? []);
setUnreadCount(res.unread_count ?? 0);
} catch { /* ignore */ }
}, []);
useEffect(() => {
fetchNotifications();
intervalRef.current = setInterval(fetchNotifications, 15000);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, [fetchNotifications]);
const openModal = async () => {
setModalVisible(true);
if (unreadCount > 0) {
try {
await markCabineNotificationsRead();
setUnreadCount(0);
setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
} catch { /* ignore */ }
}
};
const handleLogout = async () => {
await logoutAdmin();
await logout();
};
const formatTime = (iso: string) => {
const diff = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
if (diff < 1) return "à l'instant";
if (diff < 60) return `il y a ${diff} min`;
const h = Math.floor(diff / 60);
if (h < 24) return `il y a ${h}h`;
return `il y a ${Math.floor(h / 24)}j`;
};
return (
<Tab.Navigator
screenOptions={{
headerStyle: { backgroundColor: colors.bgSecondary },
headerTintColor: colors.textWhite,
headerRight: () => (
<View
style={{
flexDirection: "row",
alignItems: "center",
marginRight: spacing.l,
}}
>
<TouchableOpacity
onPress={toggleTheme}
style={{ marginRight: spacing.m }}
<>
<Tab.Navigator
screenOptions={{
headerStyle: { backgroundColor: colors.bgSecondary },
headerTintColor: colors.textWhite,
headerRight: () => (
<View
style={{
flexDirection: "row",
alignItems: "center",
marginRight: spacing.l,
}}
>
<Ionicons
name={isDark ? "sunny-outline" : "moon-outline"}
size={22}
color={colors.textSecondary}
/>
</TouchableOpacity>
<TouchableOpacity onPress={handleLogout}>
<Ionicons
name="log-out-outline"
size={24}
color={colors.textSecondary}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={openModal}
style={{ marginRight: spacing.m }}
>
<View>
<Ionicons
name="notifications-outline"
size={22}
color={colors.textSecondary}
/>
{unreadCount > 0 && (
<View
style={[
styles.badge,
{ backgroundColor: colors.error ?? "#e74c3c" },
]}
>
<Text style={styles.badgeText}>
{unreadCount > 9 ? "9+" : unreadCount}
</Text>
</View>
)}
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={toggleTheme}
style={{ marginRight: spacing.m }}
>
<Ionicons
name={isDark ? "sunny-outline" : "moon-outline"}
size={22}
color={colors.textSecondary}
/>
</TouchableOpacity>
<TouchableOpacity onPress={handleLogout}>
<Ionicons
name="log-out-outline"
size={24}
color={colors.textSecondary}
/>
</TouchableOpacity>
</View>
),
tabBarStyle: {
backgroundColor: colors.bgSecondary,
borderTopColor: colors.border,
borderTopWidth: 1,
},
tabBarActiveTintColor: colors.info,
tabBarInactiveTintColor: colors.textMuted,
tabBarLabelStyle: { fontSize: fontSize.xs },
}}
>
<Tab.Screen
name="Dashboard"
component={DashboardScreen}
options={{
title: "Dashboard",
tabBarIcon: ({ color, size }) => (
<Ionicons name="grid-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Orders"
component={OrdersScreen}
options={{
title: "Commandes",
tabBarIcon: ({ color, size }) => (
<Ionicons name="receipt-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Delivery"
component={DeliveryScreen}
options={{
title: "Livreurs",
tabBarIcon: ({ color, size }) => (
<Ionicons name="bicycle-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Users"
component={UsersScreen}
options={{
title: "Clients",
tabBarIcon: ({ color, size }) => (
<Ionicons name="people-outline" size={size} color={color} />
),
}}
/>
<Tab.Screen
name="Alerts"
component={AlertsScreen}
options={{
title: "Alertes",
tabBarIcon: ({ color, size }) => (
<Ionicons name="alert-circle-outline" size={size} color={color} />
),
}}
/>
</Tab.Navigator>
<Modal
visible={modalVisible}
transparent
animationType="slide"
onRequestClose={() => setModalVisible(false)}
>
<View style={styles.modalOverlay}>
<View
style={[
styles.modalContainer,
{ backgroundColor: colors.bgSecondary },
]}
>
<View style={styles.modalHeader}>
<Text style={[styles.modalTitle, { color: colors.textWhite }]}>
Notifications
</Text>
<TouchableOpacity onPress={() => setModalVisible(false)}>
<Ionicons name="close" size={24} color={colors.textSecondary} />
</TouchableOpacity>
</View>
<ScrollView style={styles.notifList}>
{notifications.length === 0 ? (
<Text style={[styles.emptyText, { color: colors.textMuted }]}>
Aucune notification
</Text>
) : (
notifications.map((n, i) => (
<View
key={i}
style={[
styles.notifItem,
{
borderLeftColor: n.read
? colors.border
: colors.info,
backgroundColor: n.read
? "transparent"
: colors.bgPrimary ?? colors.bgSecondary,
},
]}
>
<Text
style={[
styles.notifMessage,
{ color: colors.textWhite },
]}
>
{n.message}
</Text>
<Text
style={[styles.notifTime, { color: colors.textMuted }]}
>
{formatTime(n.created_at)}
</Text>
</View>
))
)}
</ScrollView>
</View>
),
tabBarStyle: {
backgroundColor: colors.bgSecondary,
borderTopColor: colors.border,
borderTopWidth: 1,
},
tabBarActiveTintColor: colors.info,
tabBarInactiveTintColor: colors.textMuted,
tabBarLabelStyle: { fontSize: fontSize.xs },
}}
>
<Tab.Screen
name="Dashboard"
component={DashboardScreen}
options={{
title: "Dashboard",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="grid-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Orders"
component={OrdersScreen}
options={{
title: "Commandes",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="receipt-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Delivery"
component={DeliveryScreen}
options={{
title: "Livreurs",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="bicycle-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Users"
component={UsersScreen}
options={{
title: "Clients",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="people-outline"
size={size}
color={color}
/>
),
}}
/>
<Tab.Screen
name="Alerts"
component={AlertsScreen}
options={{
title: "Alertes",
tabBarIcon: ({ color, size }) => (
<Ionicons
name="alert-circle-outline"
size={size}
color={color}
/>
),
}}
/>
</Tab.Navigator>
</View>
</Modal>
</>
);
}
const styles = StyleSheet.create({
badge: {
position: "absolute",
top: -4,
right: -6,
minWidth: 16,
height: 16,
borderRadius: 8,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: 2,
},
badgeText: {
color: "#fff",
fontSize: 9,
fontWeight: "bold",
},
modalOverlay: {
flex: 1,
backgroundColor: "rgba(0,0,0,0.5)",
justifyContent: "flex-end",
},
modalContainer: {
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
maxHeight: "70%",
paddingBottom: 32,
},
modalHeader: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
padding: 16,
borderBottomWidth: 1,
borderBottomColor: "rgba(255,255,255,0.1)",
},
modalTitle: {
fontSize: 18,
fontWeight: "bold",
},
notifList: {
padding: 12,
},
notifItem: {
borderLeftWidth: 3,
paddingLeft: 12,
paddingVertical: 10,
marginBottom: 8,
borderRadius: 4,
paddingRight: 8,
},
notifMessage: {
fontSize: 14,
},
notifTime: {
fontSize: 12,
marginTop: 4,
},
emptyText: {
textAlign: "center",
marginTop: 32,
fontSize: 14,
},
});
@@ -16,7 +16,10 @@ import {
getAllClients,
getAvailableDeliveryPersons,
getCommandCountByStatus,
registerAdminPushToken,
unregisterAdminPushToken,
} from "../../api/api_admin";
import { getExpoPushToken } from "../../utils/pushTokenUtils";
import LoadingSpinner from "../../components/ui/LoadingSpinner";
interface StatCard {
@@ -33,6 +36,14 @@ export default function DashboardScreen() {
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
// Enregistrement push token admin au montage
useEffect(() => {
getExpoPushToken().then((token) => {
if (token) registerAdminPushToken(token);
});
return () => { unregisterAdminPushToken(); };
}, []);
const loadStats = useCallback(async () => {
try {
const [allCmd, pending, enRoute, completed, clients, livreurs] =
@@ -149,6 +149,7 @@ export default function SettingsScreen() {
points_separated: true,
points_weed_tiers: [],
points_zipette_tiers: [],
referral_enabled: true,
});
const [categories, setCategories] = useState<Category[]>([]);
@@ -350,6 +351,28 @@ export default function SettingsScreen() {
</View>
</View>
{/* Parrainage */}
<View style={s.section}>
<Text style={s.sectionTitle}>Parrainage</Text>
<View style={[s.row, s.rowFirst]}>
<View style={s.rowLeft}>
<Text style={s.rowLabel}>Parrainage activé</Text>
<Text style={s.rowDesc}>
Les clients peuvent voir et utiliser leur solde parrainage au checkout.{"\n"}
Désactivé : le solde reste en base mais ne peut plus être utilisé.
</Text>
</View>
<Switch
value={settings.referral_enabled}
onValueChange={(v) =>
setSettings((prev) => ({ ...prev, referral_enabled: v }))
}
trackColor={{ false: colors.border, true: colors.accent }}
thumbColor="#fff"
/>
</View>
</View>
{/* Système de points */}
<View style={s.section}>
<Text style={s.sectionTitle}>Système de points</Text>
+108 -10
View File
@@ -19,6 +19,7 @@ import {
deleteClientAdmin,
createClientByAdmin,
createUserByAdmin,
creditClientReferral,
} from "../../api/api_admin";
import type { ClientResponse } from "../../api/types";
import LoadingSpinner from "../../components/ui/LoadingSpinner";
@@ -155,6 +156,15 @@ export default function UsersScreen() {
const [createTel, setCreateTel] = useState("");
const [creating, setCreating] = useState(false);
// Referral credit modal
const [referralModal, setReferralModal] = useState<{
visible: boolean;
username: string;
currentBalance: number;
}>({ visible: false, username: "", currentBalance: 0 });
const [referralAmount, setReferralAmount] = useState("");
const [referralLoading, setReferralLoading] = useState(false);
const { alert, showError, showConfirm, hideAlert } = useAlert();
// --------------------------------------------------
@@ -318,6 +328,40 @@ export default function UsersScreen() {
);
};
// --------------------------------------------------
// Referral credit
// --------------------------------------------------
const openReferralModal = (client: ClientResponse) => {
setReferralAmount("");
setReferralModal({
visible: true,
username: client.username,
currentBalance: client.referral_balance ?? 0,
});
};
const handleCreditReferral = async () => {
const amount = parseFloat(referralAmount);
if (isNaN(amount) || amount <= 0) {
showError("Erreur", "Entrez un montant valide");
return;
}
setReferralLoading(true);
try {
const res = await creditClientReferral(referralModal.username, amount);
if (res.success) {
setReferralModal((prev) => ({ ...prev, visible: false }));
await loadData();
} else {
showError("Erreur", res.message || "Echec du crédit");
}
} catch (e: any) {
showError("Erreur", e.message);
} finally {
setReferralLoading(false);
}
};
// --------------------------------------------------
// Create user
// --------------------------------------------------
@@ -603,16 +647,28 @@ export default function UsersScreen() {
</View>
<View style={{ flexDirection: "row", gap: spacing.xs }}>
{isClient && (
<TouchableOpacity
style={styles.editIconBtn}
onPress={() => openEditClient(item.clientData!)}
>
<Ionicons
name="create-outline"
size={20}
color={colors.info}
/>
</TouchableOpacity>
<>
<TouchableOpacity
style={styles.editIconBtn}
onPress={() => openReferralModal(item.clientData!)}
>
<Ionicons
name="gift-outline"
size={20}
color={colors.success}
/>
</TouchableOpacity>
<TouchableOpacity
style={styles.editIconBtn}
onPress={() => openEditClient(item.clientData!)}
>
<Ionicons
name="create-outline"
size={20}
color={colors.info}
/>
</TouchableOpacity>
</>
)}
{(item.role === "livreur" ||
item.role === "cabine") && (
@@ -704,6 +760,19 @@ export default function UsersScreen() {
</Text>
<Text style={styles.statLabel}>Annul.</Text>
</View>
{(item.clientData.referral_balance ?? 0) > 0 && (
<View style={styles.stat}>
<Text
style={[
styles.statValue,
{ color: colors.success },
]}
>
{(item.clientData.referral_balance ?? 0).toFixed(0)}
</Text>
<Text style={styles.statLabel}>Parrain</Text>
</View>
)}
</View>
</>
)}
@@ -977,6 +1046,35 @@ export default function UsersScreen() {
confirmText={alert.confirmText}
cancelText={alert.cancelText}
/>
{/* Modal crédit parrainage */}
<Modal
visible={referralModal.visible}
onClose={() => setReferralModal((prev) => ({ ...prev, visible: false }))}
title={`Crédit parrainage — ${referralModal.username}`}
icon="gift-outline"
iconColor={colors.success}
>
<Text style={{ color: colors.textSecondary, fontSize: fontSize.sm, marginBottom: spacing.s }}>
Solde actuel : {referralModal.currentBalance.toFixed(2)} €
</Text>
<TextInput
placeholder="Montant à créditer (ex: 10)"
value={referralAmount}
onChangeText={setReferralAmount}
keyboardType="decimal-pad"
icon={<Ionicons name="cash-outline" size={18} color={colors.textMuted} />}
/>
<Button
title={referralLoading ? "Chargement..." : "Créditer"}
onPress={handleCreditReferral}
disabled={referralLoading}
variant="success"
size="md"
fullWidth
style={{ marginTop: spacing.m }}
/>
</Modal>
</View>
);
}
@@ -12,12 +12,21 @@ import { useTheme } from "../../context/ThemeContext";
import { shadows } from "../../theme/shadows";
import { useAuth } from "../../auth/AuthContext";
import { getAllCommands } from "../../api/api_admin";
import { getAllDeliveryPersonsWithDetails } from "../../api/api_cabine";
import { getAllDeliveryPersonsWithDetails, registerCabinePushToken, unregisterCabinePushToken } from "../../api/api_cabine";
import { getExpoPushToken } from "../../utils/pushTokenUtils";
import LoadingSpinner from "../../components/ui/LoadingSpinner";
export default function DashboardScreen() {
const { colors } = useTheme();
const { username } = useAuth();
// Enregistrement push token cabine au montage
useEffect(() => {
getExpoPushToken().then((token) => {
if (token) registerCabinePushToken(token);
});
return () => { unregisterCabinePushToken(); };
}, []);
const [stats, setStats] = useState<
Array<{
label: string;
@@ -0,0 +1,33 @@
import * as Notifications from "expo-notifications";
import * as Device from "expo-device";
import { Platform } from "react-native";
/**
* Demande les permissions et retourne le token Expo push.
* Retourne null si non supporté (simulateur, refus de permission).
*/
export async function getExpoPushToken(): Promise<string | null> {
if (!Device.isDevice) return null;
const { status: existing } = await Notifications.getPermissionsAsync();
let finalStatus = existing;
if (existing !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") return null;
if (Platform.OS === "android") {
await Notifications.setNotificationChannelAsync("orders", {
name: "Nouvelles commandes",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
sound: "default",
});
}
const tokenData = await Notifications.getExpoPushTokenAsync();
return tokenData.data;
}