chore: build
Omnex Plateform App - EAS Build / build (push) Failing after 5m30s
Omnex Plateform Client - EAS Build / build (push) Failing after 5m24s

This commit is contained in:
Xor290
2026-10-10 12:40:03 +02:00
parent c382244866
commit ca3da4eb02
10 changed files with 1262 additions and 49 deletions
+36
View File
@@ -56,6 +56,8 @@ export const logoutAdmin = async (): Promise<void> => {
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[];
+1
View File
@@ -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;
@@ -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 (
<View style={{ marginTop: spacing.s, paddingLeft: spacing.m, gap: spacing.s }}>
{/* Toggle tous / sélection */}
<View style={{ flexDirection: "row", gap: spacing.s }}>
<TouchableOpacity
onPress={() => 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",
}}
>
<Ionicons name="checkmark-done-outline" size={13} color={catConfig.all_products ? PROMO_ACCENT : colors.textMuted} />
<Text style={{ fontSize: 12, fontWeight: catConfig.all_products ? "700" : "400", color: catConfig.all_products ? PROMO_ACCENT : colors.textMuted }}>
Tous ({catProducts.length})
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => 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",
}}
>
<Ionicons name="list-outline" size={13} color={!catConfig.all_products ? PROMO_ACCENT : colors.textMuted} />
<Text style={{ fontSize: 12, fontWeight: !catConfig.all_products ? "700" : "400", color: !catConfig.all_products ? PROMO_ACCENT : colors.textMuted }}>
Sélection
</Text>
</TouchableOpacity>
</View>
{/* Mode "Tous" : une quantité uniforme pour tous les produits de la catégorie */}
{catConfig.all_products && (
<View style={{ flexDirection: "row", alignItems: "center", gap: spacing.xs }}>
<Text style={{ fontSize: 12, color: colors.textMuted }}>Quantité :</Text>
<TextInput
style={[s.thresholdInput, { width: 56, fontSize: 13 }]}
keyboardType="decimal-pad"
value={catConfig.quantity > 0 ? String(catConfig.quantity) : ""}
onChangeText={(v) => {
const n = parseFloat(v);
onChange({ ...catConfig, quantity: isNaN(n) ? 0 : n });
}}
placeholder="1"
placeholderTextColor={colors.textMuted}
/>
<Text style={{ fontSize: 11, color: colors.textMuted, fontStyle: "italic" }}>
doit correspondre à un palier de prix existant
</Text>
</View>
)}
{/* 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 && (
<View style={{ gap: spacing.xs }}>
{catProducts.length === 0 ? (
<Text style={{ fontSize: 12, color: colors.textMuted, fontStyle: "italic" }}>
Aucun produit dans cette catégorie
</Text>
) : (
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: spacing.xs }}>
{catProducts.map((p) => {
const sel = catConfig.products.some((pq) => pq.product_id === p.id);
return (
<TouchableOpacity
key={p.id}
onPress={() => 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 && <Ionicons name="checkmark" size={11} color={PROMO_ACCENT} />}
<Text style={{ fontSize: 12, fontWeight: sel ? "700" : "400", color: sel ? PROMO_ACCENT : colors.textMuted }}>
{p.name}
</Text>
</TouchableOpacity>
);
})}
</View>
)}
{catConfig.products.length > 0 && (
<View style={{ gap: spacing.s, marginTop: spacing.xs }}>
{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 (
<View key={productId} style={{ gap: 4 }}>
<Text style={{ fontSize: 12, color: colors.textMuted }} numberOfLines={1}>
{prod?.name ?? `Produit #${productId}`}
</Text>
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: 4 }}>
{tiers.length === 0 ? (
<Text style={{ fontSize: 11, color: colors.textMuted, fontStyle: "italic" }}>
Aucun palier de prix actif pour ce produit
</Text>
) : tiers.map((tier) => {
const isSel = selectedQuantities.includes(tier.quantity);
return (
<TouchableOpacity
key={tier.quantity}
onPress={() => 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 && <Ionicons name="checkmark" size={10} color={PROMO_ACCENT} />}
<Text style={{ fontSize: 11, fontWeight: isSel ? "700" : "400", color: isSel ? PROMO_ACCENT : colors.textMuted }}>
{tier.quantity}{prod?.unit ?? ""} · {tier.price}€
</Text>
</TouchableOpacity>
);
})}
</View>
</View>
);
})}
</View>
)}
</View>
)}
</View>
);
}
// ──────────────────────────────────────────────────────────────
// 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<string, Product[]>;
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<Set<string>>(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 = (
<View style={{
paddingHorizontal: spacing.s, paddingVertical: 2, borderRadius: 10,
backgroundColor: enabled ? PROMO_ACCENT + "25" : colors.border + "40",
borderWidth: 1, borderColor: enabled ? PROMO_ACCENT : colors.border,
}}>
<Text style={{ fontSize: 10, fontWeight: "700", color: enabled ? PROMO_ACCENT : colors.textMuted }}>
{enabled ? "Activées" : "Désactivées"}
</Text>
</View>
);
return (
<AccordionSection title="Promotions" badge={promoBadge} colors={colors} s={s}>
<View style={[s.row, s.rowFirst]}>
<View style={s.rowLeft}>
<Text style={s.rowLabel}>Promotions activées</Text>
<Text style={s.rowDesc}>
Réduction automatique appliquée au prix affiché et facturé, pour tout client — indépendant des points de fidélité.
</Text>
</View>
<Switch
value={enabled}
onValueChange={onToggle}
trackColor={{ false: colors.border, true: PROMO_ACCENT }}
thumbColor="#fff"
/>
</View>
{enabled && (
<View style={{ borderTopWidth: 1, borderTopColor: colors.border, paddingHorizontal: spacing.l, paddingTop: spacing.l, paddingBottom: spacing.l, gap: spacing.l }}>
<View>
<Text style={[s.rowLabel, { marginBottom: spacing.xs }]}>Catégories en promo</Text>
<Text style={[s.rowDesc, { marginBottom: spacing.m }]}>
Sélectionnez une catégorie, définissez le pourcentage de réduction, puis tous les produits ou une sélection avec leur quantité.
</Text>
{allCategories.length === 0 ? (
<Text style={[s.hint, { paddingHorizontal: 0 }]}>Aucune catégorie disponible</Text>
) : (
<View style={{ gap: spacing.m }}>
{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 (
<View key={cat.name}>
<TouchableOpacity
onPress={() => 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",
}}
>
<View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: catColor }} />
<Text style={{ fontSize: 13, fontWeight: selected ? "700" : "400", color: selected ? catColor : colors.textMuted }}>
{cat.name}{selected ? ` · -${cfg.discount_percent}%` : ""}
</Text>
<Ionicons
name={expanded ? "chevron-down" : "chevron-forward"}
size={12}
color={selected ? catColor : colors.textMuted}
/>
</TouchableOpacity>
{expanded && (
<View style={{ marginTop: spacing.s, paddingLeft: spacing.m, gap: spacing.s }}>
<TouchableOpacity
onPress={() => 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",
}}
>
<Ionicons
name={selected ? "checkbox" : "square-outline"}
size={14}
color={selected ? PROMO_ACCENT : colors.textMuted}
/>
<Ionicons name="pricetag-outline" size={12} color={selected ? PROMO_ACCENT : colors.textMuted} />
<Text style={{ fontSize: 12, fontWeight: selected ? "700" : "400", color: selected ? PROMO_ACCENT : colors.textMuted }}>
Promo active sur cette catégorie
</Text>
</TouchableOpacity>
{selected && (
<>
<View style={{ flexDirection: "row", alignItems: "center", gap: spacing.xs }}>
<Text style={{ fontSize: 12, color: colors.textMuted }}>Réduction :</Text>
<TextInput
style={[s.thresholdInput, { width: 56, fontSize: 13 }]}
keyboardType="decimal-pad"
value={cfg.discount_percent > 0 ? String(cfg.discount_percent) : ""}
onChangeText={(v) => {
const n = parseFloat(v);
updateCatConfig({ ...cfg, discount_percent: isNaN(n) ? 0 : n });
}}
placeholder="10"
placeholderTextColor={colors.textMuted}
/>
<Text style={{ fontSize: 12, color: colors.textMuted }}>%</Text>
</View>
<PromotionProductPicker
catConfig={cfg}
products={productsByCategory[cat.name] ?? []}
onChange={updateCatConfig}
colors={colors}
s={s}
/>
</>
)}
</View>
)}
</View>
);
})}
</View>
)}
</View>
{/* Récapitulatif */}
{promotions.length > 0 && (
<View style={{ backgroundColor: PROMO_ACCENT + "12", borderRadius: borderRadius.sm, borderLeftWidth: 3, borderLeftColor: PROMO_ACCENT, padding: spacing.m, gap: 4 }}>
<Text style={{ fontSize: 13, fontWeight: "700", color: PROMO_ACCENT }}>Récapitulatif</Text>
{promotions.map((cfg, idx) => (
<Text key={`${cfg.category}-${idx}`} style={{ fontSize: 12, color: colors.textSecondary }}>
• {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(", ")}`}
</Text>
))}
</View>
)}
</View>
)}
</AccordionSection>
);
}
// ──────────────────────────────────────────────────────────────
// 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<FreeGiftTier>) => {
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 (
<View style={{ gap: spacing.xs }}>
{tiers.map((t, idx) => (
<View key={idx} style={{ flexDirection: "row", alignItems: "center", gap: spacing.xs }}>
<Text style={{ fontSize: 11, color: colors.textMuted }}>Acheté :</Text>
<TextInput
style={[s.thresholdInput, { width: 50, fontSize: 12 }]}
keyboardType="decimal-pad"
value={t.buy_quantity > 0 ? String(t.buy_quantity) : ""}
onChangeText={(v) => {
const n = parseFloat(v);
updateTier(idx, { buy_quantity: isNaN(n) ? 0 : n });
}}
placeholder="10"
placeholderTextColor={colors.textMuted}
/>
<Ionicons name="arrow-forward" size={12} color={colors.textMuted} />
<Text style={{ fontSize: 11, color: colors.textMuted }}>Offert :</Text>
<TextInput
style={[s.thresholdInput, { width: 50, fontSize: 12 }]}
keyboardType="decimal-pad"
value={t.free_quantity > 0 ? String(t.free_quantity) : ""}
onChangeText={(v) => {
const n = parseFloat(v);
updateTier(idx, { free_quantity: isNaN(n) ? 0 : n });
}}
placeholder="1"
placeholderTextColor={colors.textMuted}
/>
<TouchableOpacity onPress={() => removeTier(idx)} hitSlop={8}>
<Ionicons name="trash-outline" size={15} color={colors.danger ?? "#ef4444"} />
</TouchableOpacity>
</View>
))}
<TouchableOpacity
onPress={addTier}
style={{ flexDirection: "row", alignItems: "center", gap: 4, alignSelf: "flex-start", marginTop: 2 }}
>
<Ionicons name="add-circle-outline" size={14} color={FREEGIFT_ACCENT} />
<Text style={{ fontSize: 12, color: FREEGIFT_ACCENT, fontWeight: "600" }}>Ajouter un seuil</Text>
</TouchableOpacity>
</View>
);
}
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 (
<View style={{ marginTop: spacing.s, paddingLeft: spacing.m, gap: spacing.s }}>
{/* Toggle tous / sélection */}
<View style={{ flexDirection: "row", gap: spacing.s }}>
<TouchableOpacity
onPress={() => 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",
}}
>
<Ionicons name="checkmark-done-outline" size={13} color={catConfig.all_products ? FREEGIFT_ACCENT : colors.textMuted} />
<Text style={{ fontSize: 12, fontWeight: catConfig.all_products ? "700" : "400", color: catConfig.all_products ? FREEGIFT_ACCENT : colors.textMuted }}>
Tous ({catProducts.length})
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => 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",
}}
>
<Ionicons name="list-outline" size={13} color={!catConfig.all_products ? FREEGIFT_ACCENT : colors.textMuted} />
<Text style={{ fontSize: 12, fontWeight: !catConfig.all_products ? "700" : "400", color: !catConfig.all_products ? FREEGIFT_ACCENT : colors.textMuted }}>
Sélection
</Text>
</TouchableOpacity>
</View>
{/* Mode "Tous" : seuils uniformes pour tous les produits de la catégorie */}
{catConfig.all_products && (
<View>
<Text style={{ fontSize: 11, color: colors.textMuted, fontStyle: "italic", marginBottom: 4 }}>
Les quantités achetées doivent correspondre à des paliers de prix existants
</Text>
<FreeGiftTierListEditor
tiers={catConfig.tiers}
onChange={(tiers) => onChange({ ...catConfig, tiers })}
colors={colors}
s={s}
/>
</View>
)}
{/* Mode "Sélection" : chaque produit choisi a ses propres seuils */}
{!catConfig.all_products && (
<View style={{ gap: spacing.xs }}>
{catProducts.length === 0 ? (
<Text style={{ fontSize: 12, color: colors.textMuted, fontStyle: "italic" }}>
Aucun produit dans cette catégorie
</Text>
) : (
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: spacing.xs }}>
{catProducts.map((p) => {
const sel = catConfig.products.some((pq) => pq.product_id === p.id);
return (
<TouchableOpacity
key={p.id}
onPress={() => 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 && <Ionicons name="checkmark" size={11} color={FREEGIFT_ACCENT} />}
<Text style={{ fontSize: 12, fontWeight: sel ? "700" : "400", color: sel ? FREEGIFT_ACCENT : colors.textMuted }}>
{p.name}
</Text>
</TouchableOpacity>
);
})}
</View>
)}
{catConfig.products.length > 0 && (
<View style={{ gap: spacing.s, marginTop: spacing.xs }}>
{catConfig.products.map((pq) => {
const prod = catProducts.find((p) => p.id === pq.product_id);
return (
<View key={pq.product_id} style={{ gap: 4 }}>
<Text style={{ fontSize: 12, color: colors.textMuted }} numberOfLines={1}>
{prod?.name ?? `Produit #${pq.product_id}`}
</Text>
<FreeGiftTierListEditor
tiers={pq.tiers}
onChange={(tiers) => updateProductTiers(pq.product_id, tiers)}
colors={colors}
s={s}
/>
</View>
);
})}
</View>
)}
</View>
)}
</View>
);
}
function FreeGiftsSection({
enabled,
freeGifts,
allCategories,
productsByCategory,
onToggle,
onChangeFreeGifts,
colors,
s,
}: {
enabled: boolean;
freeGifts: CategoryFreeGiftConfig[];
allCategories: Category[];
productsByCategory: Record<string, Product[]>;
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<Set<string>>(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 = (
<View style={{
paddingHorizontal: spacing.s, paddingVertical: 2, borderRadius: 10,
backgroundColor: enabled ? FREEGIFT_ACCENT + "25" : colors.border + "40",
borderWidth: 1, borderColor: enabled ? FREEGIFT_ACCENT : colors.border,
}}>
<Text style={{ fontSize: 10, fontWeight: "700", color: enabled ? FREEGIFT_ACCENT : colors.textMuted }}>
{enabled ? "Activées" : "Désactivées"}
</Text>
</View>
);
return (
<AccordionSection title="Offres quantité offerte" badge={badge} colors={colors} s={s}>
<View style={[s.row, s.rowFirst]}>
<View style={s.rowLeft}>
<Text style={s.rowLabel}>Offres activées</Text>
<Text style={s.rowDesc}>
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.
</Text>
</View>
<Switch
value={enabled}
onValueChange={onToggle}
trackColor={{ false: colors.border, true: FREEGIFT_ACCENT }}
thumbColor="#fff"
/>
</View>
{enabled && (
<View style={{ borderTopWidth: 1, borderTopColor: colors.border, paddingHorizontal: spacing.l, paddingTop: spacing.l, paddingBottom: spacing.l, gap: spacing.l }}>
<View>
<Text style={[s.rowLabel, { marginBottom: spacing.xs }]}>Catégories concernées</Text>
<Text style={[s.rowDesc, { marginBottom: spacing.m }]}>
Sélectionnez une catégorie, puis tous les produits ou une sélection, avec un ou plusieurs seuils achat/offert par produit.
</Text>
{allCategories.length === 0 ? (
<Text style={[s.hint, { paddingHorizontal: 0 }]}>Aucune catégorie disponible</Text>
) : (
<View style={{ gap: spacing.m }}>
{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 (
<View key={cat.name}>
<TouchableOpacity
onPress={() => 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",
}}
>
<View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: catColor }} />
<Text style={{ fontSize: 13, fontWeight: selected ? "700" : "400", color: selected ? catColor : colors.textMuted }}>
{cat.name}{selected && countTiers(cfg) > 0 ? ` · ${countTiers(cfg)} seuil(s)` : ""}
</Text>
<Ionicons
name={expanded ? "chevron-down" : "chevron-forward"}
size={12}
color={selected ? catColor : colors.textMuted}
/>
</TouchableOpacity>
{expanded && (
<View style={{ marginTop: spacing.s, paddingLeft: spacing.m, gap: spacing.s }}>
<TouchableOpacity
onPress={() => 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",
}}
>
<Ionicons
name={selected ? "checkbox" : "square-outline"}
size={14}
color={selected ? FREEGIFT_ACCENT : colors.textMuted}
/>
<Ionicons name="gift-outline" size={12} color={selected ? FREEGIFT_ACCENT : colors.textMuted} />
<Text style={{ fontSize: 12, fontWeight: selected ? "700" : "400", color: selected ? FREEGIFT_ACCENT : colors.textMuted }}>
Offre active sur cette catégorie
</Text>
</TouchableOpacity>
{selected && (
<FreeGiftProductPicker
catConfig={cfg}
products={productsByCategory[cat.name] ?? []}
onChange={updateCatConfig}
colors={colors}
s={s}
/>
)}
</View>
)}
</View>
);
})}
</View>
)}
</View>
{/* Récapitulatif */}
{freeGifts.length > 0 && (
<View style={{ backgroundColor: FREEGIFT_ACCENT + "12", borderRadius: borderRadius.sm, borderLeftWidth: 3, borderLeftColor: FREEGIFT_ACCENT, padding: spacing.m, gap: 4 }}>
<Text style={{ fontSize: 13, fontWeight: "700", color: FREEGIFT_ACCENT }}>Récapitulatif</Text>
{freeGifts.map((cfg, idx) => (
<Text key={`${cfg.category}-${idx}`} style={{ fontSize: 12, color: colors.textSecondary }}>
• {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(", ")}`}
</Text>
))}
</View>
)}
</View>
)}
</AccordionSection>
);
}
// 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 */}
<PromotionsSection
enabled={settings.promotions_enabled ?? false}
promotions={settings.promotions ?? []}
allCategories={categories}
productsByCategory={productsByCategory}
onToggle={(v) => 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 */}
<FreeGiftsSection
enabled={settings.free_gifts_enabled ?? false}
freeGifts={settings.free_gifts ?? []}
allCategories={categories}
productsByCategory={productsByCategory}
onToggle={(v) => setSettings((p) => ({ ...p, free_gifts_enabled: v }))}
onChangeFreeGifts={(free_gifts) => setSettings((p) => ({ ...p, free_gifts }))}
colors={colors}
s={s}
/>
{/* Horaires de livraison */}
<DeliveryScheduleSection
schedule={settings.delivery_schedule ?? DEFAULT_DELIVERY_SCHEDULE}
@@ -1643,6 +1643,20 @@ export default function StatsScreen() {
color={CHART_AMBER}
/>
</View>
<View style={styles.summaryRow}>
<SummaryCard
icon="pricetag-outline"
label="Économisé (promos)"
value={fmtEuro(s?.total_promo_discount ?? 0)}
color={CHART_GREEN}
/>
<SummaryCard
icon="gift-outline"
label="Commandes avec promo"
value={fmtNum(s?.promo_orders_count ?? 0)}
color={CHART_AMBER}
/>
</View>
{/* ── Activité du jour ── */}
{stats?.daily_detail && (
@@ -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}
</Text>
)}
{item.is_new_client && (
<View
style={{
flexDirection: "row",
alignItems: "center",
alignSelf: "flex-start",
gap: spacing.xs,
marginTop: spacing.xs,
paddingHorizontal: spacing.m,
paddingVertical: spacing.xs,
borderRadius: borderRadius.xl,
borderWidth: 1,
borderColor: "#EF4444",
backgroundColor: "#EF444422",
}}
>
<FontAwesome5
name="user-plus"
size={11}
color={"#EF4444"}
/>
<Text
style={{
color: "#EF4444",
fontSize: fontSize.xs,
fontWeight: "600",
}}
>
NEW
</Text>
</View>
)}
</View>
<Badge
label={
@@ -707,7 +741,14 @@ export default function DashboardScreen() {
</Text>
</View>
)}
{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 (
<View key={idx} style={styles.itemRow}>
<View style={{ flex: 1 }}>
<View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
@@ -718,16 +759,34 @@ export default function DashboardScreen() {
<Text style={{ fontSize: 10, color: "#f59e0b", fontWeight: "700" }}>Récompense</Text>
</View>
)}
{hasPromo && (
<View style={{ flexDirection: "row", alignItems: "center", gap: 2, backgroundColor: "rgba(34,197,94,0.15)", borderRadius: 4, paddingHorizontal: 4, paddingVertical: 1 }}>
<Ionicons name="pricetag-outline" size={10} color="#22c55e" />
<Text style={{ fontSize: 10, color: "#22c55e", fontWeight: "700" }}>-{promoPercent}%</Text>
</View>
)}
</View>
<Text style={styles.itemQty}>
Quantité: {prod.quantite}{prod.unit || ""}
</Text>
</View>
<Text style={[styles.itemPrice, prod.is_reward ? { color: "#10b981" } : {}]}>
{prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`}
</Text>
{hasPromo ? (
<View style={{ alignItems: "flex-end" }}>
<Text style={{ fontSize: 12, color: colors.textMuted, textDecorationLine: "line-through" }}>
{originalPrice.toFixed(2)}€
</Text>
<Text style={[styles.itemPrice, { color: "#22c55e" }]}>
{(prod.prix ?? 0).toFixed(2)}€
</Text>
</View>
) : (
<Text style={[styles.itemPrice, prod.is_reward ? { color: "#10b981" } : {}]}>
{prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`}
</Text>
)}
</View>
))}
);
})}
<View style={styles.totalRow}>
<Text style={styles.totalLabel}>Total</Text>
<Text style={styles.totalValue}>
@@ -2010,7 +2069,14 @@ export default function DashboardScreen() {
</Text>
</View>
)}
{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 (
<View key={idx} style={styles.detailProductRow}>
<View style={{ flex: 1 }}>
<View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
@@ -2021,16 +2087,34 @@ export default function DashboardScreen() {
<Text style={{ fontSize: 11, color: "#f59e0b", fontWeight: "700" }}>Récompense</Text>
</View>
)}
{hasPromo && (
<View style={{ flexDirection: "row", alignItems: "center", gap: 2, backgroundColor: "rgba(34,197,94,0.15)", borderRadius: 4, paddingHorizontal: 4, paddingVertical: 1 }}>
<Ionicons name="pricetag-outline" size={11} color="#22c55e" />
<Text style={{ fontSize: 11, color: "#22c55e", fontWeight: "700" }}>-{promoPercent}%</Text>
</View>
)}
</View>
<Text style={styles.detailProductQty}>
Quantité : {prod.quantite}{prod.unit || ""}
</Text>
</View>
<Text style={[styles.detailProductPrice, prod.is_reward ? { color: "#10b981" } : {}]}>
{prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`}
</Text>
{hasPromo ? (
<View style={{ alignItems: "flex-end" }}>
<Text style={{ fontSize: 12, color: colors.textMuted, textDecorationLine: "line-through" }}>
{originalPrice.toFixed(2)}€
</Text>
<Text style={[styles.detailProductPrice, { color: "#22c55e" }]}>
{(prod.prix ?? 0).toFixed(2)}€
</Text>
</View>
) : (
<Text style={[styles.detailProductPrice, prod.is_reward ? { color: "#10b981" } : {}]}>
{prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`}
</Text>
)}
</View>
))}
);
})}
</>
) : (
<Text style={styles.detailEmpty}>Aucun produit</Text>
+23
View File
@@ -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<TrackingResponse> => {
@@ -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;
@@ -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}
</Text>
<Text style={[styles.price, { color: colors.success }]}>
{firstPrice !== null
? `${firstPrice.toFixed(2)} €`
: "Prix non disponible"}
</Text>
{firstPrice !== null ? (
firstPromoPrice !== null ? (
<View style={styles.priceRow}>
<Text
style={[
styles.priceStrike,
{ color: colors.textMuted },
]}
>
{firstPrice.toFixed(2)} €
</Text>
<Text
style={[styles.price, { color: colors.success }]}
>
{firstPromoPrice.toFixed(2)} €
</Text>
</View>
) : (
<Text style={[styles.price, { color: colors.success }]}>
{firstPrice.toFixed(2)} €
</Text>
)
) : (
<Text style={[styles.price, { color: colors.success }]}>
Prix non disponible
</Text>
)}
</View>
<View
@@ -317,14 +346,39 @@ export default function ProductCard({
{p.quantity}
{product.unit || "g"}
</Text>
<Text
style={[
styles.pickerOptionPrice,
{ color: catColor },
]}
>
{p.price.toFixed(2)} €
</Text>
{p.promo_price != null &&
p.promo_price < p.price ? (
<View style={styles.pickerPriceRow}>
<Text
style={[
styles.priceStrike,
{ color: colors.textMuted },
]}
>
{p.price.toFixed(2)} €
</Text>
<Text
style={[
styles.pickerOptionPrice,
{ color: catColor },
]}
>
{p.promo_price.toFixed(2)} €
{p.promo_percent
? ` (-${p.promo_percent}%)`
: ""}
</Text>
</View>
) : (
<Text
style={[
styles.pickerOptionPrice,
{ color: catColor },
]}
>
{p.price.toFixed(2)} €
</Text>
)}
</View>
<Ionicons
name="add-circle"
@@ -515,6 +569,21 @@ const styles = StyleSheet.create({
fontWeight: fontWeight.bold,
textAlign: "center",
},
priceRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.xs,
},
pickerPriceRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.xs,
},
priceStrike: {
fontSize: fontSize.md,
textDecorationLine: "line-through",
},
quickAddSection: { padding: spacing.m, borderTopWidth: 1 },
quickAddBtn: {
width: "100%",
@@ -17,6 +17,7 @@ import {
confirmReception,
cancelCommand,
respondToAddressProposal,
updateOwnCommandAddress,
formatOrderDate,
formatPrice,
calculateOrderTotal,
@@ -74,6 +75,11 @@ export default function OrderTrackingScreen() {
useState<CancelCommandResponse | null>(null);
const [penaltyOrderId, setPenaltyOrderId] = useState<number | null>(null);
const [penaltiesEnabled, setPenaltiesEnabled] = useState(false);
const [editingAddressId, setEditingAddressId] = useState<number | null>(
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 (
<TouchableOpacity
@@ -636,6 +669,23 @@ export default function OrderTrackingScreen() {
size="sm"
/>
)}
{canEditAddress && (
<Button
title="Modifier l'adresse"
onPress={() => {
setNewAddress(
order.delivery_address ||
order.adresse ||
"",
);
setEditingAddressId(
order.id,
);
}}
variant="outline"
size="sm"
/>
)}
{canCancel && (
<Button
title="Annuler"
@@ -689,6 +739,52 @@ export default function OrderTrackingScreen() {
</View>
</Modal>
<Modal
visible={editingAddressId !== null}
onClose={() => {
setEditingAddressId(null);
setNewAddress("");
}}
title="Modifier l'adresse de livraison"
icon="location-outline"
iconColor={colors.accent}
>
<View style={styles.modalBody}>
<Text style={styles.modalText}>
Nouvelle adresse de livraison :
</Text>
<RNTextInput
style={styles.cancelInput}
placeholder="Adresse complète"
placeholderTextColor={colors.textMuted}
value={newAddress}
onChangeText={setNewAddress}
multiline
/>
<View style={styles.modalActions}>
<Button
title="Retour"
onPress={() => {
setEditingAddressId(null);
setNewAddress("");
}}
variant="outline"
size="md"
/>
<Button
title="Enregistrer"
onPress={() =>
editingAddressId &&
handleUpdateAddress(editingAddressId)
}
loading={editAddressLoading}
variant="success"
size="md"
/>
</View>
</View>
</Modal>
<Modal
visible={cancellingId !== null}
onClose={() => {
@@ -63,12 +63,18 @@ export default function ProductDetailScreen() {
quantity: parseFloat(String(pr.quantity)),
price: parseFloat(String(pr.price)),
active_price: pr.active_price,
promo_price:
pr.promo_price != null
? parseFloat(String(pr.promo_price))
: undefined,
promo_percent: pr.promo_percent,
})) || [],
};
setProduct(fixedProduct);
if (fixedProduct.prices.length > 0) {
setSelectedGrams(fixedProduct.prices[0].quantity);
setSelectedPrice(fixedProduct.prices[0].price);
const first = fixedProduct.prices[0];
setSelectedGrams(first.quantity);
setSelectedPrice(first.promo_price ?? first.price);
}
const matched = categories.find(
(c) =>
@@ -90,7 +96,7 @@ export default function ProductDetailScreen() {
const handleGramsChange = (quantity: number) => {
setSelectedGrams(quantity);
const opt = product?.prices?.find((p) => p.quantity === quantity);
if (opt) setSelectedPrice(opt.price);
if (opt) setSelectedPrice(opt.promo_price ?? opt.price);
setShowQuantityPicker(false);
};
@@ -585,16 +591,44 @@ export default function ProductDetailScreen() {
<View style={styles.infoSection}>
<Text style={styles.productName}>{product.name}</Text>
{selectedPrice > 0 && (
<View style={styles.priceRow}>
<View style={styles.priceIndicator} />
<Text style={styles.priceText}>
{selectedPrice.toFixed(2)} €{" "}
{selectedGrams &&
`pour ${selectedGrams}${product.unit || "g"}`}
</Text>
</View>
)}
{selectedPrice > 0 && (() => {
const selectedTier = product.prices?.find(
(p) => p.quantity === selectedGrams,
);
const hasPromo =
selectedTier?.promo_price != null &&
selectedTier.promo_price < selectedTier.price;
return (
<View style={styles.priceRow}>
<View style={styles.priceIndicator} />
{hasPromo && (
<Text
style={[
styles.priceText,
{
textDecorationLine: "line-through",
opacity: 0.6,
marginRight: 6,
},
]}
>
{selectedTier!.price.toFixed(2)} €
</Text>
)}
<Text
style={[
styles.priceText,
hasPromo && { color: "#22c55e" },
]}
>
{selectedPrice.toFixed(2)} €
{!hasPromo &&
selectedGrams &&
` pour ${selectedGrams}${product.unit || "g"}`}
</Text>
</View>
);
})()}
<View style={styles.descriptionCard}>
<Text style={styles.descriptionTitle}>Description</Text>
<Text style={styles.descriptionText}>
@@ -719,16 +753,32 @@ export default function ProductDetailScreen() {
{p.quantity}
{product.unit || "g"}
</Text>
<Text
style={[
styles.pickerOptionPrice,
selectedGrams === p.quantity && {
color: catColor,
},
]}
>
{p.price.toFixed(2)} €
</Text>
{p.promo_price != null && p.promo_price < p.price ? (
<View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
<Text
style={[
styles.pickerOptionPrice,
{ textDecorationLine: "line-through", opacity: 0.6 },
]}
>
{p.price.toFixed(2)} €
</Text>
<Text style={[styles.pickerOptionPrice, { color: "#22c55e" }]}>
{p.promo_price.toFixed(2)} € (-{p.promo_percent}%)
</Text>
</View>
) : (
<Text
style={[
styles.pickerOptionPrice,
selectedGrams === p.quantity && {
color: catColor,
},
]}
>
{p.price.toFixed(2)} €
</Text>
)}
</View>
{selectedGrams === p.quantity && (
<View