Files
home_hub/frontend/src/pages/ShoppingPage.tsx
T
gillesandClaude Sonnet 4.6 c9cf452585 feat(shopping): bottom sheet multi-select pour l'ajout d'articles
- BottomSheet.tsx: panneau ancré en bas, max-height 85dvh (clavier-aware),
  centré sur laptop (max-width 600px), backdrop, drag handle visuel
- ShoppingPage: remplace le modal centré par le BottomSheet multi-select
  · sélection multiple avec toggle (cercle vert + fond teinté)
  · articles libres affichés en tête avec tag "article libre"
  · bouton "Ajouter (N)" sticky, grisé à 0 sélection
  · pas d'autoFocus → liste visible d'emblée, clavier fermé
  · FAB + masqué quand le sheet est ouvert

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 08:06:48 +02:00

660 lines
25 KiB
TypeScript

// frontend/src/pages/ShoppingPage.tsx
import { useState, useEffect, useCallback } from 'react'
import { matchesSearch } from '../utils/search'
import type { ShoppingListDetail, ShoppingList, Store, Product, ShoppingItem } from '../api/shopping'
import {
fetchLists, createList, fetchListDetail, deleteList,
addItem, updateItem, deleteItem, finishShopping, fetchStores, generateMagicList,
searchProducts,
} from '../api/shopping'
import Modal from '../components/Modal'
import BottomSheet from '../components/BottomSheet'
import ItemRow from '../components/shopping/ItemRow'
import CatalogueModal from '../components/shopping/CatalogueModal'
import BoutiquesModal from '../components/shopping/BoutiquesModal'
import { useWakeLock } from '../hooks/useWakeLock'
const inputStyle: React.CSSProperties = {
width: '100%',
background: 'var(--bg-4)',
border: '1px solid var(--bg-5)',
borderRadius: 8,
padding: '10px 12px',
color: 'var(--ink-1)',
fontFamily: 'var(--font-ui)',
fontSize: 14,
boxSizing: 'border-box',
}
const noSelect: React.CSSProperties = { userSelect: 'none' }
export default function ShoppingPage() {
const [currentList, setCurrentList] = useState<ShoppingListDetail | null>(null)
const [allLists, setAllLists] = useState<ShoppingList[]>([])
const [stores, setStores] = useState<Store[]>([])
const [products, setProducts] = useState<Product[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [generating, setGenerating] = useState(false)
const [showAddSheet, setShowAddSheet] = useState(false)
const [showHistoryModal, setShowHistoryModal] = useState(false)
const [showCatalogueModal, setShowCatalogueModal] = useState(false)
const [showBoutiquesModal, setShowBoutiquesModal] = useState(false)
const [editingItem, setEditingItem] = useState<ShoppingItem | null>(null)
const [editQty, setEditQty] = useState('')
const [editUnit, setEditUnit] = useState('')
type Selection = { type: 'product'; product: Product } | { type: 'custom'; name: string }
const [itemSearch, setItemSearch] = useState('')
const [selections, setSelections] = useState<Selection[]>([])
const [addSaving, setAddSaving] = useState(false)
useWakeLock(currentList !== null)
const loadData = useCallback(async () => {
setLoading(true)
setError(null)
try {
const [listsData, storesData, productsData] = await Promise.all([fetchLists(), fetchStores(), searchProducts()])
setAllLists(listsData)
setStores(storesData)
setProducts([...productsData].sort((a, b) => a.name.localeCompare(b.name, 'fr')))
const current = listsData.find(l => l.status === 'draft' || l.status === 'active')
if (current) {
setCurrentList(await fetchListDetail(current.id))
} else {
setCurrentList(null)
}
} catch {
setError('Erreur lors du chargement')
} finally {
setLoading(false)
}
}, [])
useEffect(() => { void loadData() }, [loadData])
async function refreshCurrentList() {
if (!currentList) return
try {
setCurrentList(await fetchListDetail(currentList.id))
} catch {
setError('Erreur de rafraîchissement')
}
}
async function handleCreateManualList() {
try {
const detail = await createList({})
setCurrentList(detail)
void loadData()
} catch {
setError('Erreur lors de la création')
}
}
async function handleGenerateMagicList() {
setGenerating(true)
setError(null)
try {
const detail = await generateMagicList()
setCurrentList(detail)
void loadData()
} catch {
setError('Erreur lors de la génération')
} finally {
setGenerating(false)
}
}
function closeAddSheet() {
setItemSearch('')
setSelections([])
setShowAddSheet(false)
}
function toggleProduct(p: Product) {
setSelections(prev => {
const exists = prev.some(s => s.type === 'product' && s.product.id === p.id)
if (exists) return prev.filter(s => !(s.type === 'product' && s.product.id === p.id))
return [...prev, { type: 'product' as const, product: p }]
})
}
function addCustomItem() {
const name = itemSearch.trim()
if (!name) return
setSelections(prev => {
const exists = prev.some(s => s.type === 'custom' && s.name === name)
if (exists) return prev
return [...prev, { type: 'custom' as const, name }]
})
setItemSearch('')
}
function removeSelection(key: string) {
setSelections(prev => prev.filter(s => {
if (s.type === 'product') return s.product.id !== key
return s.name !== key
}))
}
async function handleConfirmAdd() {
if (!currentList || selections.length === 0) return
setAddSaving(true)
try {
for (const sel of selections) {
if (sel.type === 'product') {
await addItem(currentList.id, {
product_id: sel.product.id,
unit: sel.product.default_unit || undefined,
})
} else {
await addItem(currentList.id, { custom_name: sel.name })
}
}
closeAddSheet()
void refreshCurrentList()
} catch {
setError("Erreur lors de l'ajout")
} finally {
setAddSaving(false)
}
}
async function handleCheckItem(itemId: string, checked: boolean) {
if (!currentList) return
try {
await updateItem(currentList.id, itemId, { is_checked: checked })
void refreshCurrentList()
} catch {
setError('Erreur lors du cochage')
}
}
async function handleDeleteItem(itemId: string) {
if (!currentList) return
try {
await deleteItem(currentList.id, itemId)
void refreshCurrentList()
} catch {
setError('Erreur lors de la suppression')
}
}
function openEditItem(item: ShoppingItem) {
setEditingItem(item)
setEditQty(item.quantity ?? '')
setEditUnit(item.unit ?? '')
}
async function handleEditItem() {
if (!currentList || !editingItem) return
try {
await updateItem(currentList.id, editingItem.id, {
quantity: editQty || undefined,
unit: editUnit || undefined,
})
setEditingItem(null)
void refreshCurrentList()
} catch {
setError('Erreur lors de la modification')
}
}
async function handleFinish() {
if (!currentList) return
try {
await finishShopping(currentList.id)
void loadData()
} catch {
setError('Erreur lors de la finalisation')
}
}
async function handleDeleteCurrentList() {
if (!currentList) return
if (!confirm('Supprimer la liste en cours ?')) return
try {
await deleteList(currentList.id)
void loadData()
} catch {
setError('Erreur lors de la suppression')
}
}
async function handleOpenHistoryList(list: ShoppingList) {
try {
const detail = await fetchListDetail(list.id)
setCurrentList(detail)
setShowHistoryModal(false)
} catch {
setError('Erreur lors du chargement')
}
}
// Tri : non cochés alpha, cochés alpha (en bas)
const sortedItems = [...(currentList?.items ?? [])].sort((a, b) => {
if (a.is_checked !== b.is_checked) return a.is_checked ? 1 : -1
return a.display_name.localeCompare(b.display_name, 'fr')
})
const uncheckedItems = sortedItems.filter(i => !i.is_checked)
const checkedItems = sortedItems.filter(i => i.is_checked)
const hasCurrentList = currentList !== null
const pastLists = allLists.filter(l => l.status === 'done')
const filteredProducts = products.filter(p => {
const term = itemSearch.trim()
return !term || matchesSearch(p.name, term) || matchesSearch(p.brand ?? '', term)
})
return (
<div style={{ display: 'flex', flexDirection: 'column', minHeight: '100%' }}>
{/* ── En-tête ── */}
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: '12px 16px',
background: 'var(--bg-2)',
borderBottom: '1px solid var(--bg-4)',
position: 'sticky', top: 0, zIndex: 10,
}}>
<h1 style={{ color: 'var(--accent)', fontFamily: 'var(--font-mono)', margin: 0, flex: 1, fontSize: 18, ...noSelect }}>
{hasCurrentList ? (currentList.name ?? 'Courses') : 'Courses'}
</h1>
<button
onClick={() => setShowCatalogueModal(true)}
style={{
background: 'var(--bg-3)', border: '1px solid var(--bg-5)',
borderRadius: 8, color: 'var(--ink-2)', cursor: 'pointer',
padding: '6px 12px', fontFamily: 'var(--font-ui)', fontSize: 12, minHeight: 36,
...noSelect,
}}
>Articles</button>
<button
onClick={() => setShowBoutiquesModal(true)}
style={{
background: 'var(--bg-3)', border: '1px solid var(--bg-5)',
borderRadius: 8, color: 'var(--ink-2)', cursor: 'pointer',
padding: '6px 12px', fontFamily: 'var(--font-ui)', fontSize: 12, minHeight: 36,
...noSelect,
}}
>Boutiques</button>
</div>
{/* ── Erreur ── */}
{error && (
<div style={{ padding: '8px 16px' }}>
<p style={{ color: 'var(--err)', background: 'var(--bg-3)', borderRadius: 8, padding: '8px 12px', margin: 0, fontSize: 13, fontFamily: 'var(--font-ui)' }}>
{error}
</p>
</div>
)}
{loading && (
<p style={{ color: 'var(--ink-3)', textAlign: 'center', padding: 40, fontFamily: 'var(--font-ui)', ...noSelect }}>Chargement</p>
)}
{/* ── Vue : pas de liste en cours ── */}
{!loading && !hasCurrentList && (
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 24, padding: 32 }}>
<p style={{ color: 'var(--ink-3)', fontFamily: 'var(--font-ui)', fontSize: 15, margin: 0, textAlign: 'center', ...noSelect }}>
Aucune liste de courses en cours
</p>
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
<button
onClick={() => void handleCreateManualList()}
style={{
padding: '14px 24px', borderRadius: 12,
background: 'var(--ok)', color: '#1d2021', border: 'none',
cursor: 'pointer', fontFamily: 'var(--font-ui)', fontWeight: 700,
fontSize: 15, minHeight: 56, minWidth: 140,
boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
...noSelect,
}}
>+ Nouvelle liste</button>
<button
onClick={() => void handleGenerateMagicList()}
disabled={generating}
style={{
padding: '14px 24px', borderRadius: 12,
background: generating ? 'var(--bg-4)' : 'var(--bg-3)',
color: generating ? 'var(--ink-4)' : 'var(--accent)',
border: '1px solid var(--bg-5)',
cursor: generating ? 'not-allowed' : 'pointer',
fontFamily: 'var(--font-ui)', fontWeight: 600,
fontSize: 15, minHeight: 56, minWidth: 140,
...noSelect,
}}
>
<i className="fa-solid fa-wand-magic-sparkles" style={{ marginRight: 8 }} />
{generating ? 'Génération…' : 'Liste magique'}
</button>
</div>
{pastLists.length > 0 && (
<button
onClick={() => setShowHistoryModal(true)}
style={{
background: 'transparent', border: 'none',
color: 'var(--ink-3)', cursor: 'pointer',
fontFamily: 'var(--font-ui)', fontSize: 13,
textDecoration: 'underline', padding: '4px 8px',
...noSelect,
}}
>Voir l'historique ({pastLists.length})</button>
)}
</div>
)}
{/* ── Vue : liste en cours ── */}
{!loading && hasCurrentList && (
<>
{/* Barre d'info + actions */}
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: '8px 16px',
background: 'var(--bg-3)',
borderBottom: '1px solid var(--bg-4)',
}}>
<span style={{ flex: 1, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', fontSize: 12, ...noSelect }}>
{checkedItems.length}/{currentList.item_count} cochés
</span>
{pastLists.length > 0 && (
<button
onClick={() => setShowHistoryModal(true)}
style={{ background: 'transparent', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', fontFamily: 'var(--font-ui)', fontSize: 12, padding: '4px 8px', ...noSelect }}
>Historique</button>
)}
<button
onClick={() => void handleDeleteCurrentList()}
style={{ background: 'transparent', border: 'none', color: 'var(--err)', cursor: 'pointer', fontFamily: 'var(--font-ui)', fontSize: 12, padding: '4px 8px', ...noSelect }}
>Supprimer</button>
<button
onClick={() => void handleFinish()}
style={{
background: 'var(--ok)', color: '#1d2021', border: 'none',
borderRadius: 8, padding: '6px 14px',
fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 13,
cursor: 'pointer', minHeight: 36, ...noSelect,
}}
>Terminer </button>
</div>
{/* Articles non cochés */}
{uncheckedItems.length === 0 && checkedItems.length === 0 && (
<p style={{ color: 'var(--ink-3)', textAlign: 'center', margin: '40px 0', fontFamily: 'var(--font-ui)', fontSize: 14, ...noSelect }}>
Liste vide ajoutez des articles avec le bouton +
</p>
)}
<div style={{ flex: 1, overflowY: 'auto', paddingBottom: 80 }}>
{uncheckedItems.map(item => (
<ItemRow
key={item.id}
item={item}
onCheck={() => void handleCheckItem(item.id, true)}
onDelete={() => void handleDeleteItem(item.id)}
onEdit={() => openEditItem(item)}
storeMode
/>
))}
{checkedItems.length > 0 && (
<>
<div style={{
padding: '6px 16px',
color: 'var(--ink-4)', fontSize: 11,
fontFamily: 'var(--font-ui)', textTransform: 'uppercase',
letterSpacing: 1, background: 'var(--bg-2)',
borderTop: '1px solid var(--bg-4)',
borderBottom: '1px solid var(--bg-4)',
...noSelect,
}}>
Cochés ({checkedItems.length})
</div>
{checkedItems.map(item => (
<ItemRow
key={item.id}
item={item}
onCheck={() => void handleCheckItem(item.id, false)}
onDelete={() => void handleDeleteItem(item.id)}
onEdit={() => openEditItem(item)}
storeMode
/>
))}
</>
)}
</div>
{/* FAB + — masqué quand le sheet est ouvert */}
{!showAddSheet && (
<button
onClick={() => setShowAddSheet(true)}
aria-label="Ajouter un article"
style={{
position: 'fixed', bottom: 72, right: 20,
width: 56, height: 56, borderRadius: '50%',
background: 'var(--accent)', color: '#1d2021', border: 'none',
fontSize: 28, cursor: 'pointer', boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>+</button>
)}
</>
)}
{/* ── Modals ── */}
{/* Modal édition quantité/unité */}
{editingItem && (
<Modal title={`Modifier — ${editingItem.display_name}`} onClose={() => setEditingItem(null)} width={320}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
<input
style={inputStyle}
placeholder="Quantité"
inputMode="decimal"
value={editQty}
onChange={e => setEditQty(e.target.value)}
autoFocus
onKeyDown={e => e.key === 'Enter' && void handleEditItem()}
/>
<input
style={inputStyle}
placeholder="Unité (kg, L…)"
value={editUnit}
onChange={e => setEditUnit(e.target.value)}
onKeyDown={e => e.key === 'Enter' && void handleEditItem()}
/>
</div>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
<button
onClick={() => setEditingItem(null)}
style={{ padding: '10px 16px', borderRadius: 8, border: '1px solid var(--bg-5)', background: 'transparent', color: 'var(--ink-2)', cursor: 'pointer', fontFamily: 'var(--font-ui)', minHeight: 48 }}
>Annuler</button>
<button
onClick={() => void handleEditItem()}
style={{ padding: '10px 20px', borderRadius: 8, border: 'none', background: 'var(--accent)', color: '#1d2021', cursor: 'pointer', fontFamily: 'var(--font-ui)', fontWeight: 600, minHeight: 48 }}
>Enregistrer</button>
</div>
</div>
</Modal>
)}
{showAddSheet && (
<BottomSheet onClose={closeAddSheet}>
{/* Recherche */}
<div style={{ padding: '4px 16px 10px', flexShrink: 0 }}>
<input
style={inputStyle}
placeholder="Rechercher ou saisir un article…"
value={itemSearch}
onChange={e => setItemSearch(e.target.value)}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
/>
</div>
{/* Liste scrollable */}
<div style={{ flex: 1, overflowY: 'auto' }}>
{/* Articles libres sélectionnés (affichés en tête) */}
{selections.filter(s => s.type === 'custom').map(s => (
<div
key={`custom:${s.name}`}
onClick={() => removeSelection(s.name)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px 16px', cursor: 'pointer', minHeight: 56,
background: 'rgba(142,192,124,0.12)',
borderBottom: '1px solid var(--bg-4)',
}}
>
<div style={{
width: 24, height: 24, borderRadius: '50%',
border: '2px solid var(--ok)', background: 'var(--ok)',
display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
}}>
<span style={{ color: '#1d2021', fontSize: 12, fontWeight: 700 }}></span>
</div>
<div style={{ flex: 1 }}>
<div style={{ fontFamily: 'var(--font-ui)', fontSize: 15, color: 'var(--ink-1)' }}>{s.name}</div>
<div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>article libre</div>
</div>
</div>
))}
{/* Produits du catalogue */}
{filteredProducts.map(p => {
const selected = selections.some(s => s.type === 'product' && s.product.id === p.id)
return (
<div
key={p.id}
onClick={() => toggleProduct(p)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px 16px', cursor: 'pointer', minHeight: 56,
background: selected ? 'rgba(142,192,124,0.12)' : 'transparent',
borderBottom: '1px solid var(--bg-4)',
transition: 'background 0.1s',
}}
>
<div style={{
width: 24, height: 24, borderRadius: '50%',
border: `2px solid ${selected ? 'var(--ok)' : 'var(--bg-5)'}`,
background: selected ? 'var(--ok)' : 'transparent',
display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
transition: 'all 0.15s',
}}>
{selected && <span style={{ color: '#1d2021', fontSize: 12, fontWeight: 700 }}></span>}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontFamily: 'var(--font-ui)', fontSize: 15, color: 'var(--ink-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{p.name}
</div>
{(p.brand || p.default_unit) && (
<div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>
{[p.brand, p.default_unit].filter(Boolean).join(' · ')}
</div>
)}
</div>
</div>
)
})}
{/* Article libre si aucun match */}
{itemSearch.trim() && filteredProducts.length === 0 && (
<div
onClick={addCustomItem}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '14px 16px', cursor: 'pointer',
color: 'var(--info)', borderBottom: '1px solid var(--bg-4)',
}}
>
<span style={{ fontSize: 22, fontWeight: 300, lineHeight: 1 }}>+</span>
<span style={{ fontFamily: 'var(--font-ui)', fontSize: 14 }}>
Ajouter <strong style={{ color: 'var(--ink-1)' }}>"{itemSearch.trim()}"</strong>
</span>
</div>
)}
{filteredProducts.length === 0 && !itemSearch.trim() && (
<p style={{ color: 'var(--ink-4)', textAlign: 'center', padding: '24px 16px', fontFamily: 'var(--font-ui)', fontSize: 13 }}>
Catalogue vide utilisez le bouton Articles
</p>
)}
</div>
{/* Bouton confirm sticky */}
<div style={{ padding: '12px 16px', borderTop: '1px solid var(--bg-4)', flexShrink: 0 }}>
<button
onClick={() => void handleConfirmAdd()}
disabled={selections.length === 0 || addSaving}
style={{
width: '100%', padding: '14px', borderRadius: 12, border: 'none',
background: selections.length === 0 ? 'var(--bg-4)' : 'var(--accent)',
color: selections.length === 0 ? 'var(--ink-4)' : '#1d2021',
fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 16,
cursor: selections.length === 0 ? 'default' : 'pointer',
minHeight: 52, transition: 'background 0.15s',
}}
>
{addSaving ? 'Ajout en cours…' : selections.length === 0 ? 'Sélectionner des articles' : `Ajouter (${selections.length})`}
</button>
</div>
</BottomSheet>
)}
{showHistoryModal && (
<Modal title="Historique des courses" onClose={() => setShowHistoryModal(false)}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{allLists.filter(l => l.status === 'done').map(list => (
<div
key={list.id}
onClick={() => void handleOpenHistoryList(list)}
className="glass interactive"
style={{ borderRadius: 8, padding: '10px 14px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10 }}
>
<div style={{ flex: 1 }}>
<div style={{ color: 'var(--ink-1)', fontFamily: 'var(--font-ui)', fontSize: 14, ...noSelect }}>
{list.name ?? 'Liste terminée'}
</div>
<div style={{ color: 'var(--ink-3)', fontSize: 11, fontFamily: 'var(--font-mono)', ...noSelect }}>
{new Date(list.created_at).toLocaleDateString('fr-FR')} · {list.checked_count}/{list.item_count} articles
</div>
</div>
<span style={{ color: 'var(--ink-3)', fontSize: 16 }}></span>
</div>
))}
{allLists.filter(l => l.status === 'done').length === 0 && (
<p style={{ color: 'var(--ink-3)', textAlign: 'center', padding: 16, fontFamily: 'var(--font-ui)', fontSize: 13, ...noSelect }}>
Aucune liste terminée
</p>
)}
</div>
</Modal>
)}
{showCatalogueModal && (
<CatalogueModal stores={stores} onClose={() => setShowCatalogueModal(false)} />
)}
{showBoutiquesModal && (
<BoutiquesModal
stores={stores}
onClose={() => setShowBoutiquesModal(false)}
onStoresChanged={() => void loadData()}
/>
)}
</div>
)
}