chore: build
This commit is contained in:
@@ -867,3 +867,82 @@ func (d *Database) ResetClientRedeemed(username, poolKey string) error {
|
||||
UPDATE clients SET points_redeemed = '{}'::jsonb, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE username = ?`, username).Error
|
||||
}
|
||||
|
||||
type RewardOrderItem struct {
|
||||
Produit string `json:"produit"`
|
||||
Quantity float64 `json:"quantity"`
|
||||
Price float64 `json:"price"`
|
||||
RewardPoolKey string `json:"reward_pool_key"`
|
||||
}
|
||||
|
||||
type RewardOrder struct {
|
||||
CommandID int `json:"command_id"`
|
||||
Status string `json:"status"`
|
||||
Total float64 `json:"total"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Items []RewardOrderItem `json:"items"`
|
||||
}
|
||||
|
||||
// GetClientRewardOrders retourne les commandes du client contenant au moins un article récompense.
|
||||
func (d *Database) GetClientRewardOrders(username string) ([]RewardOrder, error) {
|
||||
var rows []struct {
|
||||
CommandID int `gorm:"column:command_id"`
|
||||
Status string `gorm:"column:status"`
|
||||
Total float64 `gorm:"column:total_prix"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
Produit string `gorm:"column:produit"`
|
||||
Quantity float64 `gorm:"column:quantite"`
|
||||
Price float64 `gorm:"column:prix"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key"`
|
||||
}
|
||||
if err := d.GDB.Raw(`
|
||||
SELECT c.id AS command_id, c.status, c.total_prix::float8 AS total_prix, c.created_at,
|
||||
ci.produit, ci.quantite::float8 AS quantite, ci.prix::float8 AS prix,
|
||||
COALESCE(ci.reward_pool_key, '') AS reward_pool_key
|
||||
FROM command_items ci
|
||||
JOIN commandes c ON c.id = ci.command_id
|
||||
WHERE c.username = ? AND ci.is_reward = true
|
||||
ORDER BY c.created_at DESC, ci.id`, username).Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("erreur lecture commandes récompense: %w", err)
|
||||
}
|
||||
|
||||
orders := make([]RewardOrder, 0)
|
||||
index := make(map[int]int)
|
||||
for _, r := range rows {
|
||||
i, ok := index[r.CommandID]
|
||||
if !ok {
|
||||
orders = append(orders, RewardOrder{
|
||||
CommandID: r.CommandID, Status: r.Status, Total: r.Total, CreatedAt: r.CreatedAt,
|
||||
Items: []RewardOrderItem{},
|
||||
})
|
||||
i = len(orders) - 1
|
||||
index[r.CommandID] = i
|
||||
}
|
||||
orders[i].Items = append(orders[i].Items, RewardOrderItem{
|
||||
Produit: r.Produit, Quantity: r.Quantity, Price: r.Price, RewardPoolKey: r.RewardPoolKey,
|
||||
})
|
||||
}
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
// DecrementClientRedeemed annule une seule récompense réclamée sur un pool (admin).
|
||||
func (d *Database) DecrementClientRedeemed(username, poolKey string) (int, error) {
|
||||
var newCount int
|
||||
err := d.GDB.Transaction(func(tx *gorm.DB) error {
|
||||
var current int
|
||||
if err := tx.Raw(`
|
||||
SELECT COALESCE((points_redeemed->>?)::int, 0)
|
||||
FROM clients WHERE username = ? FOR UPDATE`, poolKey, username).Scan(¤t).Error; err != nil {
|
||||
return fmt.Errorf("erreur lecture: %w", err)
|
||||
}
|
||||
if current <= 0 {
|
||||
return fmt.Errorf("aucune récompense réclamée sur ce pool")
|
||||
}
|
||||
if err := releaseRewardReservationTx(tx, username, poolKey); err != nil {
|
||||
return err
|
||||
}
|
||||
newCount = current - 1
|
||||
return nil
|
||||
})
|
||||
return newCount, err
|
||||
}
|
||||
|
||||
@@ -530,3 +530,64 @@ func AdminResetClientRedeemed(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
func AdminGetClientRewardOrders(c *gin.Context) {
|
||||
username := c.Param("username")
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
|
||||
orders, err := database.GetClientRewardOrders(username)
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur lecture commandes récompense", err)
|
||||
return
|
||||
}
|
||||
_, redeemed, err := database.GetClientPointsAndRewards(username)
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur lecture récompenses", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "orders": orders, "redeemed": redeemed})
|
||||
}
|
||||
|
||||
func AdminDecrementClientRedeemed(c *gin.Context) {
|
||||
username := c.Param("username")
|
||||
var req struct {
|
||||
PoolKey string `json:"pool_key" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "pool_key requis"})
|
||||
return
|
||||
}
|
||||
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
settings, err := database.GetSettings()
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur lecture paramètres", err)
|
||||
return
|
||||
}
|
||||
poolExists := false
|
||||
for _, p := range settings.PointsPools {
|
||||
if p.Key == req.PoolKey {
|
||||
poolExists = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !poolExists {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Pool de points invalide"})
|
||||
return
|
||||
}
|
||||
|
||||
remaining, err := database.DecrementClientRedeemed(username, req.PoolKey)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "aucune récompense") {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Aucune récompense réclamée sur ce pool"})
|
||||
return
|
||||
}
|
||||
utils.ServerErr(c, "Erreur annulation récompense", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("✅ [REWARD_DECREMENT] 1 récompense annulée (pool=%s) pour %s par %s, reste %d",
|
||||
req.PoolKey, username, c.GetString("username"), remaining)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "redeemed": remaining})
|
||||
}
|
||||
|
||||
@@ -286,15 +286,17 @@ func SetupRoutes(router *gin.Engine, database *db.Database, geoService *services
|
||||
// ============================================
|
||||
// ⭐⭐ PÉNALITÉS - GESTION ADMIN
|
||||
// ============================================
|
||||
adminGroupV2.POST("/penalty", handlers.ApplyClientPenalty) // Appliquer pénalité
|
||||
adminGroupV2.GET("/client/:username/penalties", handlers.GetClientPenaltiesAdmin) // Voir pénalités client
|
||||
adminGroupV2.POST("/client/:username/penalties/reset", handlers.ResetClientPenaltiesAdmin) // Reset amende
|
||||
adminGroupV2.POST("/client/:username/point/reset", handlers.ResetClientPointAdmin) // Reset points → 0
|
||||
adminGroupV2.POST("/client/:username/points/add", handlers.AddClientPointsAdmin) // Ajouter points par pool
|
||||
adminGroupV2.POST("/client/:username/points/subtract", handlers.SubtractClientPointsAdmin) // Enlever points par pool
|
||||
adminGroupV2.POST("/client/:username/rewards/reset", handlers.AdminResetClientRedeemed) // Reset récompenses réclamées
|
||||
adminGroupV2.POST("/client/:username/ratelimit/reset", handlers.ResetClientRateLimitAdmin) // Lever les rate limits
|
||||
adminGroupV2.GET("/penalties/all", handlers.GetAllClientsWithPenalties) // Liste clients avec pénalités
|
||||
adminGroupV2.POST("/penalty", handlers.ApplyClientPenalty) // Appliquer pénalité
|
||||
adminGroupV2.GET("/client/:username/penalties", handlers.GetClientPenaltiesAdmin) // Voir pénalités client
|
||||
adminGroupV2.POST("/client/:username/penalties/reset", handlers.ResetClientPenaltiesAdmin) // Reset amende
|
||||
adminGroupV2.POST("/client/:username/point/reset", handlers.ResetClientPointAdmin) // Reset points → 0
|
||||
adminGroupV2.POST("/client/:username/points/add", handlers.AddClientPointsAdmin) // Ajouter points par pool
|
||||
adminGroupV2.POST("/client/:username/points/subtract", handlers.SubtractClientPointsAdmin) // Enlever points par pool
|
||||
adminGroupV2.POST("/client/:username/rewards/reset", handlers.AdminResetClientRedeemed) // Reset récompenses réclamées
|
||||
adminGroupV2.GET("/client/:username/rewards/orders", handlers.AdminGetClientRewardOrders) // Commandes avec récompense
|
||||
adminGroupV2.POST("/client/:username/rewards/decrement", handlers.AdminDecrementClientRedeemed) // Annuler 1 récompense réclamée
|
||||
adminGroupV2.POST("/client/:username/ratelimit/reset", handlers.ResetClientRateLimitAdmin) // Lever les rate limits
|
||||
adminGroupV2.GET("/penalties/all", handlers.GetAllClientsWithPenalties) // Liste clients avec pénalités
|
||||
adminGroupV2.GET("/penalties/stats", handlers.GetPenaltiesStats)
|
||||
|
||||
// ============================================
|
||||
|
||||
@@ -836,6 +836,55 @@ export const getClientCancelledOrders = async (
|
||||
}
|
||||
};
|
||||
|
||||
export interface RewardOrder {
|
||||
command_id: number;
|
||||
status: string;
|
||||
total: number;
|
||||
created_at: string;
|
||||
items: {
|
||||
produit: string;
|
||||
quantity: number;
|
||||
price: number;
|
||||
reward_pool_key: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export const getClientRewardOrders = async (
|
||||
username: string,
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
orders: RewardOrder[];
|
||||
redeemed: Record<string, number>;
|
||||
}> => {
|
||||
try {
|
||||
const { data } = await apiClient.get(
|
||||
`${V2}/admin/protected/client/${encodeURIComponent(username)}/rewards/orders`,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
orders: data.orders ?? [],
|
||||
redeemed: data.redeemed ?? {},
|
||||
};
|
||||
} catch {
|
||||
return { success: false, orders: [], redeemed: {} };
|
||||
}
|
||||
};
|
||||
|
||||
export const decrementClientRedeemed = async (
|
||||
username: string,
|
||||
poolKey: string,
|
||||
): Promise<{ success: boolean; redeemed?: number; error?: string }> => {
|
||||
try {
|
||||
const { data } = await apiClient.post(
|
||||
`${V2}/admin/protected/client/${encodeURIComponent(username)}/rewards/decrement`,
|
||||
{ pool_key: poolKey },
|
||||
);
|
||||
return { success: true, redeemed: data.redeemed };
|
||||
} catch (e: any) {
|
||||
return { success: false, error: e.response?.data?.error || "Erreur" };
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// AMENDES & POINTS CLIENT (Admin)
|
||||
// ============================================
|
||||
|
||||
@@ -27,6 +27,8 @@ import {
|
||||
creditClientReferral,
|
||||
resetClientReferral,
|
||||
getClientCancelledOrders,
|
||||
getClientRewardOrders,
|
||||
decrementClientRedeemed,
|
||||
getSettings,
|
||||
applyClientPenalty,
|
||||
resetClientPenalties,
|
||||
@@ -38,10 +40,12 @@ import {
|
||||
} from "../../api/api_admin";
|
||||
import type {
|
||||
CancelledOrder,
|
||||
RewardOrder,
|
||||
LoginHistoryWeek,
|
||||
UserCounts,
|
||||
} from "../../api/api_admin";
|
||||
import type { ClientResponse } from "../../api/types";
|
||||
import { STATUS_LABELS } from "../../utils/constants";
|
||||
import LoadingSpinner from "../../components/ui/LoadingSpinner";
|
||||
import Card from "../../components/ui/Card";
|
||||
import Button from "../../components/ui/Button";
|
||||
@@ -237,6 +241,20 @@ export default function UsersScreen() {
|
||||
loading: boolean;
|
||||
}>({ visible: false, username: "", orders: [], loading: false });
|
||||
|
||||
const [rewardOrdersModal, setRewardOrdersModal] = useState<{
|
||||
visible: boolean;
|
||||
username: string;
|
||||
orders: RewardOrder[];
|
||||
redeemed: Record<string, number>;
|
||||
loading: boolean;
|
||||
}>({
|
||||
visible: false,
|
||||
username: "",
|
||||
orders: [],
|
||||
redeemed: {},
|
||||
loading: false,
|
||||
});
|
||||
|
||||
// Login history modal (livreur)
|
||||
const [loginHistoryModal, setLoginHistoryModal] = useState<{
|
||||
visible: boolean;
|
||||
@@ -809,6 +827,64 @@ export default function UsersScreen() {
|
||||
}));
|
||||
};
|
||||
|
||||
const openRewardOrders = async (client: ClientResponse) => {
|
||||
setRewardOrdersModal({
|
||||
visible: true,
|
||||
username: client.username,
|
||||
orders: [],
|
||||
redeemed: {},
|
||||
loading: true,
|
||||
});
|
||||
const res = await getClientRewardOrders(client.username);
|
||||
setRewardOrdersModal((prev) => ({
|
||||
...prev,
|
||||
orders: res.orders,
|
||||
redeemed: res.redeemed,
|
||||
loading: false,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleDecrementRedeemed = (poolKey: string) => {
|
||||
const username = rewardOrdersModal.username;
|
||||
const used = rewardOrdersModal.orders.filter(
|
||||
(o) =>
|
||||
o.status !== "cancelled" &&
|
||||
o.items.some((it) => it.reward_pool_key === poolKey),
|
||||
).length;
|
||||
const warning =
|
||||
used > 0
|
||||
? `\n\n⚠️ ${used} commande(s) avec récompense existent déjà sur ce pool : vérifiez que la récompense a bien été perdue.`
|
||||
: "";
|
||||
showConfirm(
|
||||
"Annuler 1 récompense",
|
||||
`Rendre 1 récompense "${poolLabel(poolKey)}" à "${username}" ? Le bouton de réclamation réapparaîtra chez le client.${warning}`,
|
||||
async () => {
|
||||
const res = await decrementClientRedeemed(username, poolKey);
|
||||
if (!res.success) {
|
||||
showError("Erreur", res.error || "Echec");
|
||||
return;
|
||||
}
|
||||
setRewardOrdersModal((prev) => ({
|
||||
...prev,
|
||||
redeemed: {
|
||||
...prev.redeemed,
|
||||
[poolKey]: res.redeemed ?? 0,
|
||||
},
|
||||
}));
|
||||
showSuccess(
|
||||
"Validé",
|
||||
`1 récompense "${poolLabel(poolKey)}" rendue à "${username}"`,
|
||||
);
|
||||
},
|
||||
"Rendre",
|
||||
);
|
||||
};
|
||||
|
||||
const poolLabel = (key: string) => {
|
||||
const idx = poolKeys.indexOf(key);
|
||||
return idx >= 0 && poolNames[idx] ? poolNames[idx] : key;
|
||||
};
|
||||
|
||||
// --------------------------------------------------
|
||||
// Login history (livreur)
|
||||
// --------------------------------------------------
|
||||
@@ -1285,6 +1361,20 @@ export default function UsersScreen() {
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
{pointsEnabled && (
|
||||
<TouchableOpacity
|
||||
style={styles.editIconBtn}
|
||||
onPress={() =>
|
||||
openRewardOrders(item.clientData!)
|
||||
}
|
||||
>
|
||||
<FontAwesome5
|
||||
name="trophy"
|
||||
size={17}
|
||||
color={colors.warning}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
<TouchableOpacity
|
||||
style={styles.editIconBtn}
|
||||
onPress={() =>
|
||||
@@ -1866,6 +1956,219 @@ export default function UsersScreen() {
|
||||
cancelText={alert.cancelText}
|
||||
/>
|
||||
|
||||
{/* Modal commandes avec récompense */}
|
||||
<Modal
|
||||
visible={rewardOrdersModal.visible}
|
||||
onClose={() =>
|
||||
setRewardOrdersModal((prev) => ({
|
||||
...prev,
|
||||
visible: false,
|
||||
}))
|
||||
}
|
||||
title={`Récompenses — ${rewardOrdersModal.username}`}
|
||||
icon="trophy-outline"
|
||||
iconColor={colors.warning}
|
||||
>
|
||||
{rewardOrdersModal.loading ? (
|
||||
<ActivityIndicator
|
||||
color={colors.warning}
|
||||
style={{ marginVertical: spacing.xl }}
|
||||
/>
|
||||
) : (
|
||||
<ScrollView
|
||||
style={{ maxHeight: 400 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{Object.keys(rewardOrdersModal.redeemed).length > 0 && (
|
||||
<View
|
||||
style={{
|
||||
paddingBottom: spacing.m,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: colors.border,
|
||||
gap: spacing.xs,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textMuted,
|
||||
fontSize: fontSize.xs,
|
||||
}}
|
||||
>
|
||||
Récompenses comptées comme réclamées
|
||||
</Text>
|
||||
{Object.entries(rewardOrdersModal.redeemed).map(
|
||||
([key, count]) => (
|
||||
<View
|
||||
key={key}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textWhite,
|
||||
fontSize: fontSize.sm,
|
||||
}}
|
||||
>
|
||||
{poolLabel(key)} : {count}
|
||||
</Text>
|
||||
{count > 0 && (
|
||||
<TouchableOpacity
|
||||
onPress={() =>
|
||||
handleDecrementRedeemed(
|
||||
key,
|
||||
)
|
||||
}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.xs,
|
||||
paddingHorizontal:
|
||||
spacing.s,
|
||||
paddingVertical: 4,
|
||||
borderRadius:
|
||||
borderRadius.sm,
|
||||
borderWidth: 1,
|
||||
borderColor:
|
||||
colors.warning,
|
||||
}}
|
||||
>
|
||||
<FontAwesome5
|
||||
name="undo"
|
||||
size={11}
|
||||
color={colors.warning}
|
||||
/>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.warning,
|
||||
fontSize:
|
||||
fontSize.xs,
|
||||
fontWeight: "700",
|
||||
}}
|
||||
>
|
||||
−1
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
),
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
{rewardOrdersModal.orders.length === 0 ? (
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textMuted,
|
||||
textAlign: "center",
|
||||
paddingVertical: spacing.xl,
|
||||
}}
|
||||
>
|
||||
Aucune commande avec récompense
|
||||
</Text>
|
||||
) : (
|
||||
rewardOrdersModal.orders.map((order, idx) => (
|
||||
<View
|
||||
key={order.command_id}
|
||||
style={{
|
||||
borderBottomWidth:
|
||||
idx <
|
||||
rewardOrdersModal.orders.length - 1
|
||||
? 1
|
||||
: 0,
|
||||
borderBottomColor: colors.border,
|
||||
paddingVertical: spacing.m,
|
||||
gap: spacing.xs,
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textWhite,
|
||||
fontWeight: "700",
|
||||
fontSize: fontSize.sm,
|
||||
}}
|
||||
>
|
||||
Commande #{order.command_id}
|
||||
</Text>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textMuted,
|
||||
fontSize: fontSize.xs,
|
||||
}}
|
||||
>
|
||||
{new Date(
|
||||
order.created_at,
|
||||
).toLocaleDateString("fr-FR", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textMuted,
|
||||
fontSize: fontSize.xs,
|
||||
}}
|
||||
>
|
||||
{STATUS_LABELS[order.status] ||
|
||||
order.status}{" "}
|
||||
· {Number(order.total).toFixed(2)} €
|
||||
</Text>
|
||||
{order.items.map((it, i) => (
|
||||
<View
|
||||
key={i}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.xs,
|
||||
}}
|
||||
>
|
||||
<FontAwesome5
|
||||
name="gift"
|
||||
size={12}
|
||||
color={colors.warning}
|
||||
/>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textWhite,
|
||||
fontSize: fontSize.sm,
|
||||
flex: 1,
|
||||
}}
|
||||
>
|
||||
{it.produit} ×{it.quantity}
|
||||
{it.reward_pool_key
|
||||
? ` · ${poolLabel(it.reward_pool_key)}`
|
||||
: ""}
|
||||
</Text>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.warning,
|
||||
fontSize: fontSize.sm,
|
||||
fontWeight: "600",
|
||||
}}
|
||||
>
|
||||
{it.price > 0
|
||||
? `${Number(it.price).toFixed(2)} €`
|
||||
: "Offert"}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
</ScrollView>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* Modal commandes annulées */}
|
||||
<Modal
|
||||
visible={cancelledModal.visible}
|
||||
|
||||
Reference in New Issue
Block a user