diff --git a/omnex-plateform-app/src/api/api_admin.ts b/omnex-plateform-app/src/api/api_admin.ts index 615905c..471362a 100644 --- a/omnex-plateform-app/src/api/api_admin.ts +++ b/omnex-plateform-app/src/api/api_admin.ts @@ -56,6 +56,8 @@ export const logoutAdmin = async (): Promise => { export interface StatsSummary { total_orders: number; total_revenue: number; + total_promo_discount: number; + promo_orders_count: number; peak_weekday: string; top_product: string; avg_per_day: number; @@ -1126,6 +1128,36 @@ export interface PointsReward { category_configs: RewardCategoryConfig[]; } +export interface PromotionProductQuantity { + product_id: number; + quantity: number; // quantité individuelle de ce produit (palier de prix catalogue) +} + +export interface CategoryPromotionConfig { + category: string; + discount_percent: number; // pourcentage de réduction libre (ex: 10, 20, 33.5) + all_products: boolean; + quantity: number; // quantité uniforme si all_products = true + products: PromotionProductQuantity[]; // produits + quantité individuelle si all_products = false +} + +export interface FreeGiftTier { + buy_quantity: number; // quantité à acheter pour déclencher l'offre + free_quantity: number; // quantité offerte du même produit +} + +export interface FreeGiftProductQuantity { + product_id: number; + tiers: FreeGiftTier[]; // seuils propres à ce produit +} + +export interface CategoryFreeGiftConfig { + category: string; + all_products: boolean; + tiers: FreeGiftTier[]; // seuils uniformes si all_products = true + products: FreeGiftProductQuantity[]; // produits + seuils individuels si all_products = false +} + export interface PointsPool { key: string; name: string; @@ -1225,6 +1257,10 @@ export interface AppSettings { points_enabled: boolean; points_pools: PointsPool[]; points_reward?: PointsReward | null; + promotions_enabled: boolean; + promotions: CategoryPromotionConfig[]; + free_gifts_enabled: boolean; + free_gifts: CategoryFreeGiftConfig[]; referral_enabled: boolean; delivery_schedule: DeliverySchedule; postal_zones: PostalZone[]; diff --git a/omnex-plateform-app/src/api/types.ts b/omnex-plateform-app/src/api/types.ts index e93cc34..e344c4b 100644 --- a/omnex-plateform-app/src/api/types.ts +++ b/omnex-plateform-app/src/api/types.ts @@ -142,6 +142,7 @@ export interface DeliveryItem { adresse: string; total_prix: number; referral_used?: number; + is_new_client?: boolean; created_at: string; updated_at: string; eta?: string; diff --git a/omnex-plateform-app/src/screens/admin/SettingsScreen.tsx b/omnex-plateform-app/src/screens/admin/SettingsScreen.tsx index 278fdfb..29ff9ab 100644 --- a/omnex-plateform-app/src/screens/admin/SettingsScreen.tsx +++ b/omnex-plateform-app/src/screens/admin/SettingsScreen.tsx @@ -17,7 +17,7 @@ import { Ionicons } from "@expo/vector-icons"; import { spacing, fontSize, borderRadius } from "../../theme"; import { useTheme } from "../../context/ThemeContext"; import { getSettings, updateSettings, getCategories, getAvailableDeliveryPersons, getAllProductsAdmin, DEFAULT_DELIVERY_SCHEDULE, DEFAULT_POSTAL_ZONES } from "../../api/api_admin"; -import type { AppSettings, Category, CategoryRoute, DeliveryModeConfig, PointsTier, PointsPool, PointsReward, RewardCategoryConfig, DaySchedule, DeliverySchedule, PostalZone } from "../../api/api_admin"; +import type { AppSettings, Category, CategoryRoute, DeliveryModeConfig, PointsTier, PointsPool, PointsReward, RewardCategoryConfig, CategoryPromotionConfig, CategoryFreeGiftConfig, FreeGiftProductQuantity, FreeGiftTier, DaySchedule, DeliverySchedule, PostalZone } from "../../api/api_admin"; import type { Product } from "../../api/types"; import AlertModal from "../../components/ui/AlertModal"; import { useAlert } from "../../hooks/useAlert"; @@ -1123,6 +1123,802 @@ function CentralRewardSection({ ); } +// ────────────────────────────────────────────────────────────── +// Sélecteur de produits pour une catégorie dans une promotion — +// même logique que CategoryProductPicker (récompenses), sans notion +// de "type" : une seule réduction (%) par catégorie. +// ────────────────────────────────────────────────────────────── +const PROMO_ACCENT = "#22c55e"; + +function PromotionProductPicker({ + catConfig, + products, + onChange, + colors, + s, +}: { + catConfig: CategoryPromotionConfig; + products: Product[]; + onChange: (cfg: CategoryPromotionConfig) => void; + colors: any; + s: any; +}) { + const catProducts = products.filter((p) => p.category === catConfig.category); + + const toggleProduct = (id: number) => { + const exists = catConfig.products.some((pq) => pq.product_id === id); + if (exists) { + onChange({ ...catConfig, products: catConfig.products.filter((pq) => pq.product_id !== id), all_products: false }); + return; + } + // Présélectionne le premier palier de prix actif du produit. + const prod = catProducts.find((p) => p.id === id); + const firstTier = (prod?.prices ?? []).find((pr) => pr.active_price !== false); + onChange({ + ...catConfig, + products: [...catConfig.products, { product_id: id, quantity: firstTier?.quantity ?? 0 }], + all_products: false, + }); + }; + + // Chaque produit peut être en promo sur plusieurs paliers de quantité en + // même temps (ex: 1g ET 3g) — on ajoute/retire l'entrée {product_id, + // quantity} correspondante plutôt que de remplacer une quantité unique. + const toggleProductQuantity = (id: number, quantity: number) => { + const exists = catConfig.products.some((pq) => pq.product_id === id && pq.quantity === quantity); + if (exists) { + onChange({ + ...catConfig, + products: catConfig.products.filter((pq) => !(pq.product_id === id && pq.quantity === quantity)), + }); + } else { + onChange({ + ...catConfig, + products: [...catConfig.products, { product_id: id, quantity }], + }); + } + }; + + return ( + + {/* Toggle tous / sélection */} + + onChange({ ...catConfig, all_products: true, products: [] })} + style={{ + flexDirection: "row", alignItems: "center", gap: spacing.xs, + paddingHorizontal: spacing.m, paddingVertical: spacing.xs, + borderRadius: borderRadius.full, borderWidth: 1.5, + borderColor: catConfig.all_products ? PROMO_ACCENT : colors.border, + backgroundColor: catConfig.all_products ? PROMO_ACCENT + "22" : "transparent", + }} + > + + + Tous ({catProducts.length}) + + + onChange({ ...catConfig, all_products: false })} + style={{ + flexDirection: "row", alignItems: "center", gap: spacing.xs, + paddingHorizontal: spacing.m, paddingVertical: spacing.xs, + borderRadius: borderRadius.full, borderWidth: 1.5, + borderColor: !catConfig.all_products ? PROMO_ACCENT : colors.border, + backgroundColor: !catConfig.all_products ? PROMO_ACCENT + "22" : "transparent", + }} + > + + + Sélection + + + + + {/* Mode "Tous" : une quantité uniforme pour tous les produits de la catégorie */} + {catConfig.all_products && ( + + Quantité : + 0 ? String(catConfig.quantity) : ""} + onChangeText={(v) => { + const n = parseFloat(v); + onChange({ ...catConfig, quantity: isNaN(n) ? 0 : n }); + }} + placeholder="1" + placeholderTextColor={colors.textMuted} + /> + + doit correspondre à un palier de prix existant + + + )} + + {/* Mode "Sélection" : chaque produit choisi peut être en promo sur + plusieurs paliers de quantité à la fois, via les paliers de + prix réels du produit (pas de saisie libre) */} + {!catConfig.all_products && ( + + {catProducts.length === 0 ? ( + + Aucun produit dans cette catégorie + + ) : ( + + {catProducts.map((p) => { + const sel = catConfig.products.some((pq) => pq.product_id === p.id); + return ( + toggleProduct(p.id)} + style={{ + paddingHorizontal: spacing.s, paddingVertical: 4, + borderRadius: borderRadius.sm, borderWidth: 1.5, + borderColor: sel ? PROMO_ACCENT : colors.border, + backgroundColor: sel ? PROMO_ACCENT + "22" : "transparent", + flexDirection: "row", alignItems: "center", gap: 4, + }} + > + {sel && } + + {p.name} + + + ); + })} + + )} + + {catConfig.products.length > 0 && ( + + {Array.from(new Set(catConfig.products.map((pq) => pq.product_id))).map((productId) => { + const prod = catProducts.find((p) => p.id === productId); + const tiers = (prod?.prices ?? []).filter((pr) => pr.active_price !== false); + const selectedQuantities = catConfig.products + .filter((pq) => pq.product_id === productId) + .map((pq) => pq.quantity); + return ( + + + {prod?.name ?? `Produit #${productId}`} + + + {tiers.length === 0 ? ( + + Aucun palier de prix actif pour ce produit + + ) : tiers.map((tier) => { + const isSel = selectedQuantities.includes(tier.quantity); + return ( + toggleProductQuantity(productId, tier.quantity)} + style={{ + paddingHorizontal: spacing.s, paddingVertical: 3, + borderRadius: borderRadius.sm, borderWidth: 1.5, + borderColor: isSel ? PROMO_ACCENT : colors.border, + backgroundColor: isSel ? PROMO_ACCENT + "22" : "transparent", + flexDirection: "row", alignItems: "center", gap: 4, + }} + > + {isSel && } + + {tier.quantity}{prod?.unit ?? ""} · {tier.price}€ + + + ); + })} + + + ); + })} + + )} + + )} + + ); +} + +// ────────────────────────────────────────────────────────────── +// Section centralisée promotions — réduction (%) automatique sur des +// produits/quantités d'une catégorie, appliquée à toute commande +// (indépendant des points de fidélité, contrairement aux récompenses). +// ────────────────────────────────────────────────────────────── +function PromotionsSection({ + enabled, + promotions, + allCategories, + productsByCategory, + onToggle, + onChangePromotions, + colors, + s, +}: { + enabled: boolean; + promotions: CategoryPromotionConfig[]; + allCategories: Category[]; + productsByCategory: Record; + onToggle: (v: boolean) => void; + onChangePromotions: (promotions: CategoryPromotionConfig[]) => void; + colors: any; + s: any; +}) { + const getCatConfig = (catName: string): CategoryPromotionConfig => + promotions.find((p) => p.category === catName) ?? + { category: catName, discount_percent: 10, all_products: true, quantity: 1, products: [] }; + + const isCatSelected = (catName: string) => promotions.some((p) => p.category === catName); + + const toggleCategory = (catName: string) => { + if (isCatSelected(catName)) { + onChangePromotions(promotions.filter((p) => p.category !== catName)); + } else { + onChangePromotions([...promotions, { category: catName, discount_percent: 10, all_products: true, quantity: 1, products: [] }]); + } + }; + + const updateCatConfig = (cfg: CategoryPromotionConfig) => { + onChangePromotions(promotions.map((p) => (p.category === cfg.category ? cfg : p))); + }; + + const [expandedCats, setExpandedCats] = useState>(new Set()); + const toggleExpanded = (catName: string) => { + setExpandedCats((prev) => { + const next = new Set(prev); + if (next.has(catName)) next.delete(catName); else next.add(catName); + return next; + }); + }; + + const promoBadge = ( + + + {enabled ? "Activées" : "Désactivées"} + + + ); + + return ( + + + + Promotions activées + + Réduction automatique appliquée au prix affiché et facturé, pour tout client — indépendant des points de fidélité. + + + + + + {enabled && ( + + + Catégories en promo + + Sélectionnez une catégorie, définissez le pourcentage de réduction, puis tous les produits ou une sélection avec leur quantité. + + {allCategories.length === 0 ? ( + Aucune catégorie disponible + ) : ( + + {allCategories.map((cat) => { + const selected = isCatSelected(cat.name); + const expanded = expandedCats.has(cat.name); + const catColor = cat.color || PROMO_ACCENT; + const cfg = getCatConfig(cat.name); + return ( + + toggleExpanded(cat.name)} + style={{ + flexDirection: "row", alignItems: "center", gap: spacing.xs, + alignSelf: "flex-start", + paddingHorizontal: spacing.m, paddingVertical: spacing.s, + borderRadius: borderRadius.full, borderWidth: 1.5, + borderColor: selected ? catColor : colors.border, + backgroundColor: selected ? catColor + "22" : "transparent", + }} + > + + + {cat.name}{selected ? ` · -${cfg.discount_percent}%` : ""} + + + + + {expanded && ( + + toggleCategory(cat.name)} + style={{ + flexDirection: "row", alignItems: "center", gap: 4, + alignSelf: "flex-start", + paddingHorizontal: spacing.s, paddingVertical: 4, + borderRadius: borderRadius.sm, borderWidth: 1.5, + borderColor: selected ? PROMO_ACCENT : colors.border, + backgroundColor: selected ? PROMO_ACCENT + "22" : "transparent", + }} + > + + + + Promo active sur cette catégorie + + + + {selected && ( + <> + + Réduction : + 0 ? String(cfg.discount_percent) : ""} + onChangeText={(v) => { + const n = parseFloat(v); + updateCatConfig({ ...cfg, discount_percent: isNaN(n) ? 0 : n }); + }} + placeholder="10" + placeholderTextColor={colors.textMuted} + /> + % + + + + )} + + )} + + ); + })} + + )} + + + {/* Récapitulatif */} + {promotions.length > 0 && ( + + Récapitulatif + {promotions.map((cfg, idx) => ( + + • {cfg.category} — -{cfg.discount_percent}% sur {cfg.all_products + ? `tous les produits · qté ${cfg.quantity > 0 ? cfg.quantity : 1}` + : `${cfg.products.length} produit(s) : ${cfg.products.map((pq) => `#${pq.product_id}×${pq.quantity}`).join(", ")}`} + + ))} + + )} + + )} + + ); +} + +// ────────────────────────────────────────────────────────────── +// Offres "achetez X, Y offert" — quantité supplémentaire du même +// produit livrée gratuitement dès qu'un seuil d'achat est atteint, +// indépendant des points et des promotions (cumulable avec elles). +// Plusieurs seuils peuvent coexister sur un même produit (ex: 10g→+1g, +// 20g→+3g) : le seuil le plus élevé atteint par la commande est retenu. +// ────────────────────────────────────────────────────────────── +const FREEGIFT_ACCENT = "#f59e0b"; + +function FreeGiftTierListEditor({ + tiers, + onChange, + colors, + s, +}: { + tiers: FreeGiftTier[]; + onChange: (tiers: FreeGiftTier[]) => void; + colors: any; + s: any; +}) { + const updateTier = (idx: number, patch: Partial) => { + onChange(tiers.map((t, i) => (i === idx ? { ...t, ...patch } : t))); + }; + const removeTier = (idx: number) => { + onChange(tiers.filter((_, i) => i !== idx)); + }; + const addTier = () => { + onChange([...tiers, { buy_quantity: 0, free_quantity: 0 }]); + }; + + return ( + + {tiers.map((t, idx) => ( + + Acheté : + 0 ? String(t.buy_quantity) : ""} + onChangeText={(v) => { + const n = parseFloat(v); + updateTier(idx, { buy_quantity: isNaN(n) ? 0 : n }); + }} + placeholder="10" + placeholderTextColor={colors.textMuted} + /> + + Offert : + 0 ? String(t.free_quantity) : ""} + onChangeText={(v) => { + const n = parseFloat(v); + updateTier(idx, { free_quantity: isNaN(n) ? 0 : n }); + }} + placeholder="1" + placeholderTextColor={colors.textMuted} + /> + removeTier(idx)} hitSlop={8}> + + + + ))} + + + Ajouter un seuil + + + ); +} + +function FreeGiftProductPicker({ + catConfig, + products, + onChange, + colors, + s, +}: { + catConfig: CategoryFreeGiftConfig; + products: Product[]; + onChange: (cfg: CategoryFreeGiftConfig) => void; + colors: any; + s: any; +}) { + const catProducts = products.filter((p) => p.category === catConfig.category); + + const toggleProduct = (id: number) => { + const exists = catConfig.products.some((pq) => pq.product_id === id); + if (exists) { + onChange({ ...catConfig, products: catConfig.products.filter((pq) => pq.product_id !== id), all_products: false }); + return; + } + onChange({ + ...catConfig, + products: [...catConfig.products, { product_id: id, tiers: [{ buy_quantity: 0, free_quantity: 0 }] }], + all_products: false, + }); + }; + + const updateProductTiers = (id: number, tiers: FreeGiftTier[]) => { + onChange({ + ...catConfig, + products: catConfig.products.map((pq) => (pq.product_id === id ? { ...pq, tiers } : pq)), + }); + }; + + return ( + + {/* Toggle tous / sélection */} + + onChange({ ...catConfig, all_products: true, products: [] })} + style={{ + flexDirection: "row", alignItems: "center", gap: spacing.xs, + paddingHorizontal: spacing.m, paddingVertical: spacing.xs, + borderRadius: borderRadius.full, borderWidth: 1.5, + borderColor: catConfig.all_products ? FREEGIFT_ACCENT : colors.border, + backgroundColor: catConfig.all_products ? FREEGIFT_ACCENT + "22" : "transparent", + }} + > + + + Tous ({catProducts.length}) + + + onChange({ ...catConfig, all_products: false })} + style={{ + flexDirection: "row", alignItems: "center", gap: spacing.xs, + paddingHorizontal: spacing.m, paddingVertical: spacing.xs, + borderRadius: borderRadius.full, borderWidth: 1.5, + borderColor: !catConfig.all_products ? FREEGIFT_ACCENT : colors.border, + backgroundColor: !catConfig.all_products ? FREEGIFT_ACCENT + "22" : "transparent", + }} + > + + + Sélection + + + + + {/* Mode "Tous" : seuils uniformes pour tous les produits de la catégorie */} + {catConfig.all_products && ( + + + Les quantités achetées doivent correspondre à des paliers de prix existants + + onChange({ ...catConfig, tiers })} + colors={colors} + s={s} + /> + + )} + + {/* Mode "Sélection" : chaque produit choisi a ses propres seuils */} + {!catConfig.all_products && ( + + {catProducts.length === 0 ? ( + + Aucun produit dans cette catégorie + + ) : ( + + {catProducts.map((p) => { + const sel = catConfig.products.some((pq) => pq.product_id === p.id); + return ( + toggleProduct(p.id)} + style={{ + paddingHorizontal: spacing.s, paddingVertical: 4, + borderRadius: borderRadius.sm, borderWidth: 1.5, + borderColor: sel ? FREEGIFT_ACCENT : colors.border, + backgroundColor: sel ? FREEGIFT_ACCENT + "22" : "transparent", + flexDirection: "row", alignItems: "center", gap: 4, + }} + > + {sel && } + + {p.name} + + + ); + })} + + )} + + {catConfig.products.length > 0 && ( + + {catConfig.products.map((pq) => { + const prod = catProducts.find((p) => p.id === pq.product_id); + return ( + + + {prod?.name ?? `Produit #${pq.product_id}`} + + updateProductTiers(pq.product_id, tiers)} + colors={colors} + s={s} + /> + + ); + })} + + )} + + )} + + ); +} + +function FreeGiftsSection({ + enabled, + freeGifts, + allCategories, + productsByCategory, + onToggle, + onChangeFreeGifts, + colors, + s, +}: { + enabled: boolean; + freeGifts: CategoryFreeGiftConfig[]; + allCategories: Category[]; + productsByCategory: Record; + onToggle: (v: boolean) => void; + onChangeFreeGifts: (freeGifts: CategoryFreeGiftConfig[]) => void; + colors: any; + s: any; +}) { + const getCatConfig = (catName: string): CategoryFreeGiftConfig => + freeGifts.find((g) => g.category === catName) ?? + { category: catName, all_products: true, tiers: [], products: [] }; + + const isCatSelected = (catName: string) => freeGifts.some((g) => g.category === catName); + + const toggleCategory = (catName: string) => { + if (isCatSelected(catName)) { + onChangeFreeGifts(freeGifts.filter((g) => g.category !== catName)); + } else { + onChangeFreeGifts([...freeGifts, { category: catName, all_products: true, tiers: [], products: [] }]); + } + }; + + const updateCatConfig = (cfg: CategoryFreeGiftConfig) => { + onChangeFreeGifts(freeGifts.map((g) => (g.category === cfg.category ? cfg : g))); + }; + + const [expandedCats, setExpandedCats] = useState>(new Set()); + const toggleExpanded = (catName: string) => { + setExpandedCats((prev) => { + const next = new Set(prev); + if (next.has(catName)) next.delete(catName); else next.add(catName); + return next; + }); + }; + + const countTiers = (cfg: CategoryFreeGiftConfig) => + cfg.all_products ? cfg.tiers.length : cfg.products.reduce((sum, pq) => sum + pq.tiers.length, 0); + + const badge = ( + + + {enabled ? "Activées" : "Désactivées"} + + + ); + + return ( + + + + Offres activées + + Quantité supplémentaire du même produit livrée gratuitement dès qu'un seuil d'achat est atteint (ex: 10g achetés → 1g offert) — indépendant des points et des promotions, cumulable avec elles. + + + + + + {enabled && ( + + + Catégories concernées + + Sélectionnez une catégorie, puis tous les produits ou une sélection, avec un ou plusieurs seuils achat/offert par produit. + + {allCategories.length === 0 ? ( + Aucune catégorie disponible + ) : ( + + {allCategories.map((cat) => { + const selected = isCatSelected(cat.name); + const expanded = expandedCats.has(cat.name); + const catColor = cat.color || FREEGIFT_ACCENT; + const cfg = getCatConfig(cat.name); + return ( + + toggleExpanded(cat.name)} + style={{ + flexDirection: "row", alignItems: "center", gap: spacing.xs, + alignSelf: "flex-start", + paddingHorizontal: spacing.m, paddingVertical: spacing.s, + borderRadius: borderRadius.full, borderWidth: 1.5, + borderColor: selected ? catColor : colors.border, + backgroundColor: selected ? catColor + "22" : "transparent", + }} + > + + + {cat.name}{selected && countTiers(cfg) > 0 ? ` · ${countTiers(cfg)} seuil(s)` : ""} + + + + + {expanded && ( + + toggleCategory(cat.name)} + style={{ + flexDirection: "row", alignItems: "center", gap: 4, + alignSelf: "flex-start", + paddingHorizontal: spacing.s, paddingVertical: 4, + borderRadius: borderRadius.sm, borderWidth: 1.5, + borderColor: selected ? FREEGIFT_ACCENT : colors.border, + backgroundColor: selected ? FREEGIFT_ACCENT + "22" : "transparent", + }} + > + + + + Offre active sur cette catégorie + + + + {selected && ( + + )} + + )} + + ); + })} + + )} + + + {/* Récapitulatif */} + {freeGifts.length > 0 && ( + + Récapitulatif + {freeGifts.map((cfg, idx) => ( + + • {cfg.category} — {cfg.all_products + ? `tous les produits · ${cfg.tiers.map((t) => `${t.buy_quantity}→+${t.free_quantity}`).join(", ") || "aucun seuil"}` + : `${cfg.products.length} produit(s) : ${cfg.products.map((pq) => `#${pq.product_id}[${pq.tiers.map((t) => `${t.buy_quantity}→+${t.free_quantity}`).join(",")}]`).join(", ")}`} + + ))} + + )} + + )} + + ); +} + // Palette violette d'origine de l'application (thème par défaut historique) const ORIGINAL_THEME_COLORS = { admin_color_primary: "#7c3aed", @@ -1178,6 +1974,10 @@ export default function SettingsScreen() { shop_name: "Milieu-Nantais", contact_telegram: "", points_reward: null, + promotions_enabled: false, + promotions: [], + free_gifts_enabled: false, + free_gifts: [], admin_color_primary: "#7c3aed", admin_color_secondary: "#22d3ee", admin_color_success: "#4ade80", @@ -1257,6 +2057,20 @@ export default function SettingsScreen() { })), } : null, + promotions_enabled: s.promotions_enabled ?? false, + promotions: (s.promotions ?? []).map((cfg) => ({ + ...cfg, + products: cfg.products ?? [], + })), + free_gifts_enabled: s.free_gifts_enabled ?? false, + free_gifts: (s.free_gifts ?? []).map((cfg) => ({ + ...cfg, + tiers: cfg.tiers ?? [], + products: (cfg.products ?? []).map((pq) => ({ + ...pq, + tiers: pq.tiers ?? [], + })), + })), }); } if (categoriesRes) { @@ -1872,6 +2686,30 @@ export default function SettingsScreen() { s={s} /> + {/* Promotions — réduction automatique, indépendante des points */} + setSettings((p) => ({ ...p, promotions_enabled: v }))} + onChangePromotions={(promotions) => setSettings((p) => ({ ...p, promotions }))} + colors={colors} + s={s} + /> + + {/* Offres "achetez X, Y offert" — quantité offerte du même produit */} + setSettings((p) => ({ ...p, free_gifts_enabled: v }))} + onChangeFreeGifts={(free_gifts) => setSettings((p) => ({ ...p, free_gifts }))} + colors={colors} + s={s} + /> + {/* Horaires de livraison */} + + + + {/* ── Activité du jour ── */} {stats?.daily_detail && ( diff --git a/omnex-plateform-app/src/screens/delivery/DashboardScreen.tsx b/omnex-plateform-app/src/screens/delivery/DashboardScreen.tsx index 626da74..dc1f9e2 100644 --- a/omnex-plateform-app/src/screens/delivery/DashboardScreen.tsx +++ b/omnex-plateform-app/src/screens/delivery/DashboardScreen.tsx @@ -22,7 +22,7 @@ import { useWindowDimensions, } from "react-native"; import Geolocation from "@react-native-community/geolocation"; -import { Ionicons } from "@expo/vector-icons"; +import { Ionicons, FontAwesome5 } from "@expo/vector-icons"; import * as Location from "expo-location"; import { spacing, fontSize, borderRadius } from "../../theme"; import { useTheme } from "../../context/ThemeContext"; @@ -75,7 +75,7 @@ interface EnrichedDelivery extends DeliveryItem { clientUsername?: string; clientNom?: string; clientPrenom?: string; - items?: Array<{ produit: string; quantite: number; prix: number; unit?: string; is_reward?: boolean }>; + items?: Array<{ produit: string; quantite: number; prix: number; unit?: string; is_reward?: boolean; promo_discount?: number }>; } export default function DashboardScreen() { @@ -271,6 +271,8 @@ export default function DashboardScreen() { [], referral_used: detail.delivery?.referral_used || 0, + is_new_client: + detail.delivery?.is_new_client || false, }; } } catch { @@ -623,6 +625,38 @@ export default function DashboardScreen() { {item.clientName} )} + {item.is_new_client && ( + + + + NEW + + + )} )} - {item.items.map((prod, idx) => ( + {item.items.map((prod, idx) => { + const promoDiscount = prod.promo_discount ?? 0; + const hasPromo = !prod.is_reward && promoDiscount > 0; + const originalPrice = (prod.prix ?? 0) + promoDiscount; + const promoPercent = hasPromo && originalPrice > 0 + ? Math.round((promoDiscount / originalPrice) * 100) + : 0; + return ( @@ -718,16 +759,34 @@ export default function DashboardScreen() { Récompense )} + {hasPromo && ( + + + -{promoPercent}% + + )} Quantité: {prod.quantite}{prod.unit || ""} - - {prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`} - + {hasPromo ? ( + + + {originalPrice.toFixed(2)}€ + + + {(prod.prix ?? 0).toFixed(2)}€ + + + ) : ( + + {prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`} + + )} - ))} + ); + })} Total @@ -2010,7 +2069,14 @@ export default function DashboardScreen() { )} - {detailsDelivery.items.map((prod, idx) => ( + {detailsDelivery.items.map((prod, idx) => { + const promoDiscount = prod.promo_discount ?? 0; + const hasPromo = !prod.is_reward && promoDiscount > 0; + const originalPrice = (prod.prix ?? 0) + promoDiscount; + const promoPercent = hasPromo && originalPrice > 0 + ? Math.round((promoDiscount / originalPrice) * 100) + : 0; + return ( @@ -2021,16 +2087,34 @@ export default function DashboardScreen() { Récompense )} + {hasPromo && ( + + + -{promoPercent}% + + )} Quantité : {prod.quantite}{prod.unit || ""} - - {prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`} - + {hasPromo ? ( + + + {originalPrice.toFixed(2)}€ + + + {(prod.prix ?? 0).toFixed(2)}€ + + + ) : ( + + {prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`} + + )} - ))} + ); + })} ) : ( Aucun produit diff --git a/omnex-plateform-client/src/api/api.ts b/omnex-plateform-client/src/api/api.ts index 644e33b..b37f964 100644 --- a/omnex-plateform-client/src/api/api.ts +++ b/omnex-plateform-client/src/api/api.ts @@ -457,6 +457,29 @@ export const respondToAddressProposal = async ( } }; +export const updateOwnCommandAddress = async ( + commandId: number, + deliveryAddress: string, +): Promise<{ success: boolean; message: string }> => { + try { + const { data } = await apiClient.put( + `${V1}/commands/${commandId}/address`, + { delivery_address: deliveryAddress }, + ); + return { + success: true, + message: data.message || "Adresse mise à jour", + }; + } catch (error: any) { + return { + success: false, + message: + error.response?.data?.error || + "Erreur lors de la mise à jour de l'adresse", + }; + } +}; + export const getOrderTracking = async ( commandId: number, ): Promise => { diff --git a/omnex-plateform-client/src/api/api_types.ts b/omnex-plateform-client/src/api/api_types.ts index b66244c..5876835 100644 --- a/omnex-plateform-client/src/api/api_types.ts +++ b/omnex-plateform-client/src/api/api_types.ts @@ -355,6 +355,8 @@ export interface ProductPrice { quantity: number; price: number; active_price?: boolean; + promo_price?: number; // prix réduit si une promotion couvre ce palier + promo_percent?: number; // pourcentage de réduction appliqué } export interface Product { id: number; diff --git a/omnex-plateform-client/src/components/ProductCard.tsx b/omnex-plateform-client/src/components/ProductCard.tsx index 5e150d0..e6c6050 100644 --- a/omnex-plateform-client/src/components/ProductCard.tsx +++ b/omnex-plateform-client/src/components/ProductCard.tsx @@ -47,6 +47,8 @@ interface ProductCardProps { quantity: number; price: number; active_price?: boolean; + promo_price?: number | null; + promo_percent?: number; }>; media?: Array<{ url: string; type: string }>; }; @@ -67,6 +69,11 @@ export default function ProductCard({ const activePrices = product.prices?.filter((p) => p.active_price !== false) ?? []; const firstPrice = activePrices[0]?.price ?? null; + const firstPromoPrice = + activePrices[0]?.promo_price != null && + activePrices[0].promo_price < activePrices[0].price + ? activePrices[0].promo_price + : null; const imageMedia = product.media?.find((m) => m.type === "image"); const videoMedia = product.media?.find((m) => m.type === "video"); @@ -198,11 +205,33 @@ export default function ProductCard({ > {product.name} - - {firstPrice !== null - ? `${firstPrice.toFixed(2)} €` - : "Prix non disponible"} - + {firstPrice !== null ? ( + firstPromoPrice !== null ? ( + + + {firstPrice.toFixed(2)} € + + + {firstPromoPrice.toFixed(2)} € + + + ) : ( + + {firstPrice.toFixed(2)} € + + ) + ) : ( + + Prix non disponible + + )} - - {p.price.toFixed(2)} € - + {p.promo_price != null && + p.promo_price < p.price ? ( + + + {p.price.toFixed(2)} € + + + {p.promo_price.toFixed(2)} € + {p.promo_percent + ? ` (-${p.promo_percent}%)` + : ""} + + + ) : ( + + {p.price.toFixed(2)} € + + )} (null); const [penaltyOrderId, setPenaltyOrderId] = useState(null); const [penaltiesEnabled, setPenaltiesEnabled] = useState(false); + const [editingAddressId, setEditingAddressId] = useState( + null, + ); + const [newAddress, setNewAddress] = useState(""); + const [editAddressLoading, setEditAddressLoading] = useState(false); const [toastMsg, setToastMsg] = useState(""); const [toastType, setToastType] = useState< "success" | "error" | "warning" | "info" @@ -187,6 +193,29 @@ export default function OrderTrackingScreen() { } }; + const handleUpdateAddress = async (orderId: number) => { + if (!newAddress.trim()) return; + setEditAddressLoading(true); + try { + const res = await updateOwnCommandAddress( + orderId, + newAddress.trim(), + ); + if (res.success) { + showToast("Adresse mise à jour", "success"); + setEditingAddressId(null); + setNewAddress(""); + fetchOrders(); + } else { + showToast(res.message || "Erreur", "error"); + } + } catch { + showToast("Erreur lors de la mise à jour de l'adresse", "error"); + } finally { + setEditAddressLoading(false); + } + }; + const styles = useMemo( () => StyleSheet.create({ @@ -407,6 +436,10 @@ export default function OrderTrackingScreen() { "assigned", "en_route", ].includes(order.status); + const canEditAddress = [ + "pending", + "assigned", + ].includes(order.status); return ( )} + {canEditAddress && ( +