Files
projet_gestion_commande/frontend-admin/src/api/api_cabine.ts
T

457 lines
14 KiB
TypeScript

import apiClient from "./client";
import type {
OrderItem,
DeliveryPerson,
DeliveryPersonsStats,
Alert,
} from "./types";
const API = "https://5.181.0.112.nip.io/api/v1/cabine";
const V2 = "https://5.181.0.112.nip.io/api/v2";
// ============================================
// ITEMS
// ============================================
export const getCommandItems = async (commandId: number) => {
const { data } = await apiClient.get(`${API}/commands/${commandId}/items`);
return {
success: true,
items: (data.items || []) as OrderItem[],
count: data.count || 0,
command_info: data.command_info,
client_info: data.client_info,
};
};
export const updateItemStatus = async (itemId: number, status: string) => {
const { data } = await apiClient.put(`${API}/items/${itemId}/status`, {
status,
});
return { success: true, message: data.message };
};
export const confirmReceptionCabine = async (commandId: number) => {
const { data } = await apiClient.post(
`${API}/commands/${commandId}/confirm-reception`,
);
return {
success: true,
message: data.message,
points_earned: data.points_earned,
client_username: data.client_username,
};
};
// ============================================
// PENALITES
// ============================================
export const applyClientPenalty = async (
clientUsername: string,
reason: string,
amount?: number,
) => {
const { data } = await apiClient.post(`${API}/penalty`, {
client_username: clientUsername,
reason,
amount,
});
return { success: true, message: data.message, penalty: data.penalty };
};
export const getClientPenalties = async (clientUsername: string) => {
const { data } = await apiClient.get(
`${API}/client/${clientUsername}/penalties`,
);
return { success: true, penalties: data.penalties };
};
export const resetClientPenalties = async (clientUsername: string) => {
const { data } = await apiClient.post(
`${API}/client/${clientUsername}/penalties/reset`,
);
return { success: true, message: data.message };
};
// pool: index dans pool_names/pool_keys, -1 = reset tous les points
export const resetClientPoints = async (
clientUsername: string,
pool: number = -1,
) => {
const { data } = await apiClient.post(
`${API}/client/${clientUsername}/point/reset`,
{ pool },
);
return { success: true, message: data.message };
};
export const getAllClientsWithPenalties = async () => {
const { data } = await apiClient.get(`${API}/penalties/all`);
return {
success: true,
clients: data.clients || [],
count: data.count || 0,
};
};
export const getPenaltiesStats = async () => {
const { data } = await apiClient.get(`${API}/penalties/stats`);
return { success: true, data: data.data };
};
// ============================================
// COMMANDES
// ============================================
export const getCancelledOrders = async () => {
const { data } = await apiClient.get(`${API}/commands/cancelled`);
return {
success: true,
commands: data.commands || [],
count: data.count || 0,
};
};
export const deleteCommand = async (commandId: number) => {
const { data } = await apiClient.delete(`${API}/commands/${commandId}`);
return { success: true, message: data.message };
};
export const proposeAddressChangeCabine = async (
commandId: number,
proposedAddress: string,
) => {
const { data } = await apiClient.post(
`${API}/commands/${commandId}/propose-address`,
{ proposed_address: proposedAddress },
);
return { success: true, message: data.message };
};
export const notifyClientToDescendCabine = async (commandId: number) => {
const { data } = await apiClient.post(
`${API}/commands/${commandId}/notify-client`,
);
return {
success: true,
message: data.message,
client_username: data.client_username,
};
};
export const getCabineLivreursList = async (): Promise<
{ id: number; username: string }[]
> => {
const { data } = await apiClient.get(`${API}/all/deliveryman`);
return data.users || [];
};
export const assignDeliveryPersonByCabine = async (
commandId: number,
livreurUsername: string,
) => {
const { data } = await apiClient.post(
`${API}/commands/${commandId}/assign`,
{ livreur_username: livreurUsername },
);
return { success: true, message: data.message };
};
export const getDeliverymanLocationForCommand = async (commandId: number) => {
try {
const { data } = await apiClient.get(
`${API}/commands/${commandId}/deliveryman/location`,
);
return { success: true, data: data.data };
} catch (error: any) {
return {
success: false,
error: error.response?.data?.error || "Erreur",
};
}
};
// ============================================
// LIVREURS
// ============================================
const parseStatus = (status: any): "available" | "busy" | "offline" => {
if (!status) return "offline";
if (status === "available" || status === "busy" || status === "offline")
return status;
if (typeof status === "string" && status.startsWith("{")) {
try {
return JSON.parse(status).status || "offline";
} catch {
/* ignore */
}
}
return "offline";
};
export const getAllDeliveryPersonsWithDetails = async (): Promise<{
success: boolean;
deliveryPersons: DeliveryPerson[];
count: number;
stats: DeliveryPersonsStats;
}> => {
try {
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(
`${V2}/admin/protected/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 stats: DeliveryPersonsStats = {
total: enriched.length,
available: enriched.filter((d) => d.status === "available").length,
busy: enriched.filter((d) => d.status === "busy").length,
offline: enriched.filter((d) => d.status === "offline").length,
active_deliveries: enriched.filter(
(d) => d.stats.current_command !== null,
).length,
};
return {
success: true,
deliveryPersons: enriched,
count: enriched.length,
stats,
};
} catch {
return {
success: false,
deliveryPersons: [],
count: 0,
stats: {
total: 0,
available: 0,
busy: 0,
offline: 0,
active_deliveries: 0,
},
};
}
};
export const getDeliveryPersonMapLinks = async (username: string) => {
try {
const { data } = await apiClient.get(
`${API}/deliveryman/${username}/location`,
);
return {
success: true,
location: data.location,
map_links: data.map_links,
};
} catch (error: any) {
return {
success: false,
error: error.response?.data?.error || "Erreur",
};
}
};
// ============================================
// ALERTES
// ============================================
export const getActiveAlerts = async (): Promise<{
success: boolean;
alerts: Alert[];
count: number;
}> => {
try {
const { data } = await apiClient.get(`${API}/alerts`);
return {
success: true,
alerts: data.alerts || [],
count: data.count || 0,
};
} catch {
return { success: false, alerts: [], count: 0 };
}
};
export const getAllAlerts = async (): Promise<{
success: boolean;
alerts: Alert[];
count: number;
}> => {
try {
const { data } = await apiClient.get(`${API}/all/alerts`);
return {
success: true,
alerts: data.alerts || [],
count: data.count || 0,
};
} catch {
return { success: false, alerts: [], count: 0 };
}
};
// ============================================
// PARAMÈTRES PUBLICS
// ============================================
export interface PublicSettings {
penalties_enabled: boolean;
show_amende_score: boolean;
points_enabled: boolean;
points_separated: boolean;
pool_names: string[];
pool_keys: string[];
}
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(
`https://5.181.0.112.nip.io/api/v1/app-settings`,
);
return {
penalties_enabled: data.penalties_enabled ?? true,
show_amende_score: data.show_amende_score ?? true,
points_enabled: data.points_enabled ?? true,
points_separated: data.points_separated ?? true,
pool_names: data.pool_names ?? [],
pool_keys: data.pool_keys ?? [],
};
} catch {
return {
penalties_enabled: true,
show_amende_score: true,
points_enabled: true,
points_separated: true,
pool_names: [],
pool_keys: [],
};
}
};
// ============================================
// ADDRESSES
// ============================================
export const addAddress = async (
invalidAddress: string,
correctAddress: string,
): Promise<{ success: boolean; message: string }> => {
const { data } = await apiClient.post(`${API}/add/address`, {
invalid_address: invalidAddress,
correct_address: correctAddress,
});
return { success: true, message: data.message };
};
export const deleteAddress = async (
invalidAddress: string,
correctAddress: string,
): Promise<{ success: boolean; message: string }> => {
const { data } = await apiClient.delete(`${API}/delete/address`, {
data: {
invalid_address: invalidAddress,
correct_address: correctAddress,
},
});
return { success: true, message: data.message };
};
export const getAllAddresses = async (): Promise<
{ invalid_address: string; correct_address: string }[]
> => {
const { data } = await apiClient.get(`${API}/addresses`);
return (data.addresses ?? []).map((a: any) => ({
invalid_address: a.invalid_address ?? a.InvalidAddress ?? "",
correct_address: a.correct_address ?? a.CorrectAddress ?? "",
}));
};