Files
Inventory/app/components/ConstructeurSelect.vue
2025-12-03 11:29:11 +01:00

417 lines
11 KiB
Vue

<template>
<div class="space-y-2 constructeur-select">
<label v-if="label" class="label"><span class="label-text">{{ label }}</span></label>
<div class="flex items-start gap-2">
<div class="relative flex-1">
<input
v-model="searchTerm"
type="text"
class="input input-bordered w-full pr-10"
:placeholder="placeholder"
@focus="openDropdown = true; ensureOptionsLoaded()"
@input="onSearch"
>
<button
type="button"
class="absolute right-2 top-1/2 -translate-y-1/2 btn btn-ghost btn-xs"
@click="ensureOptionsLoaded(true)"
>
<IconLucideChevronsUpDown class="w-4 h-4" aria-hidden="true" />
</button>
<div
v-if="openDropdown"
class="absolute z-20 mt-1 w-full max-h-48 overflow-y-auto bg-base-100 border border-base-200 rounded-box shadow-lg flex flex-col"
>
<div
v-if="options.length === 0"
class="px-3 py-2 text-xs text-gray-500"
>
Aucun fournisseur trouvé
</div>
<button
v-for="option in options"
:key="option.id"
type="button"
class="w-full text-left px-3 py-2 hover:bg-base-200 focus:bg-base-200 focus:outline-none"
:class="{ 'bg-base-200': isSelected(option.id) }"
@click="toggleOption(option)"
>
<div class="flex items-center justify-between gap-3">
<div class="flex flex-col">
<span class="font-medium">{{ option.name }}</span>
<span class="text-xs text-gray-500">
{{ formatConstructeurContact(option) || '—' }}
</span>
</div>
<IconLucideCheck v-if="isSelected(option.id)" class="w-4 h-4 text-primary" aria-hidden="true" />
</div>
</button>
</div>
</div>
<button type="button" class="btn btn-outline btn-sm" @click="openCreateModal = true">
Nouveau
</button>
</div>
<div class="flex flex-wrap gap-2 min-h-[1.5rem]">
<span v-if="!selectedConstructeurs.length" class="text-sm text-gray-500">
Aucun fournisseur sélectionné
</span>
<span
v-for="constructeur in selectedConstructeurs"
:key="constructeur.id"
class="badge badge-outline gap-1"
>
<span>{{ constructeur.name }}</span>
<button
type="button"
class="btn btn-ghost btn-xs p-0"
aria-label="Retirer le fournisseur"
@click="removeConstructeur(constructeur.id)"
>
<IconLucideX class="w-3 h-3" aria-hidden="true" />
</button>
</span>
</div>
<dialog class="modal" :class="{ 'modal-open': openCreateModal }">
<div class="modal-box">
<h3 class="font-bold text-lg mb-4">
Nouveau fournisseur
</h3>
<form @submit.prevent="handleCreate">
<div class="form-control mb-3">
<label class="label"><span class="label-text">Nom</span></label>
<input v-model="createForm.name" type="text" class="input input-bordered" required>
</div>
<FieldEmail
v-model="createForm.email"
class="mb-3"
label="Email"
placeholder="ex: contact@fournisseur.com"
autocomplete="email"
/>
<FieldPhone
v-model="createForm.phone"
class="mb-3"
label="Téléphone"
placeholder="ex: 01 23 45 67 89"
/>
<div class="modal-action">
<button type="button" class="btn" @click="closeCreateModal">
Annuler
</button>
<button type="submit" class="btn btn-primary" :disabled="creating">
<span v-if="creating" class="loading loading-spinner loading-xs mr-2" />
Créer
</button>
</div>
</form>
</div>
</dialog>
</div>
</template>
<script setup lang="ts">
import { ref, watch, computed, onMounted, onBeforeUnmount } from 'vue'
import type { PropType } from 'vue'
import FieldEmail from '~/components/form/FieldEmail.vue'
import FieldPhone from '~/components/form/FieldPhone.vue'
import { useConstructeurs } from '~/composables/useConstructeurs'
import IconLucideChevronsUpDown from '~icons/lucide/chevrons-up-down'
import IconLucideCheck from '~icons/lucide/check'
import IconLucideX from '~icons/lucide/x'
import {
type ConstructeurSummary,
formatConstructeurContact,
resolveConstructeurs,
uniqueConstructeurIds,
} from '~/shared/constructeurUtils'
const props = defineProps({
modelValue: {
type: Array as PropType<string[]>,
default: () => [],
},
label: {
type: String,
default: '',
},
placeholder: {
type: String,
default: 'Sélectionner ou créer un fournisseur...',
},
initialOptions: {
type: Array as PropType<ConstructeurSummary[]>,
default: () => [],
},
})
const emit = defineEmits<{
(e: 'update:modelValue', value: string[]): void
}>()
const {
constructeurs,
searchConstructeurs,
createConstructeur,
ensureConstructeurs,
} = useConstructeurs()
const searchTerm = ref('')
const openDropdown = ref(false)
const openCreateModal = ref(false)
const creating = ref(false)
const options = ref<ConstructeurSummary[]>([])
const selectedIds = ref<string[]>([])
let searchTimeout: ReturnType<typeof setTimeout> | null = null
let lastSearchTerm = ''
const uniqueOptions = (items: ConstructeurSummary[] = []) => {
const seen = new Map<string, ConstructeurSummary>()
items.forEach((item) => {
if (item && typeof item === 'object' && typeof item.id === 'string') {
seen.set(item.id, item)
}
})
return Array.from(seen.values())
}
const normalizedInitialOptions = computed(() =>
uniqueOptions((props.initialOptions as ConstructeurSummary[]) || []),
)
const applyOptions = (items: ConstructeurSummary[] = []) => {
const normalized = uniqueOptions([
...normalizedInitialOptions.value,
...items,
])
const limited = normalized.slice(0, 10)
selectedIds.value.forEach((id) => {
if (!limited.some((item) => item.id === id)) {
const match =
normalized.find((item) => item.id === id) ||
constructeurs.value.find((item) => item.id === id)
if (match) {
if (limited.length >= 10) {
limited.pop()
}
limited.unshift(match)
}
}
})
options.value = uniqueOptions([
...normalizedInitialOptions.value,
...limited,
])
}
const createForm = ref({
name: '',
email: '',
phone: '',
})
const optionLookup = computed(() => {
const map = new Map<string, ConstructeurSummary>()
normalizedInitialOptions.value.forEach((item) => {
map.set(item.id, item)
})
constructeurs.value.forEach((item: ConstructeurSummary) => {
map.set(item.id, item)
})
options.value.forEach((item) => {
map.set(item.id, item)
})
return map
})
const selectedConstructeurs = computed<ConstructeurSummary[]>(() => {
if (!selectedIds.value.length) {
return []
}
return selectedIds.value
.map((id) => optionLookup.value.get(id))
.filter((item): item is ConstructeurSummary => Boolean(item))
})
const isSelected = (id: string) => selectedIds.value.includes(id)
const emitSelection = (ids: string[]) => {
const normalized = uniqueConstructeurIds(ids)
selectedIds.value = normalized
emit('update:modelValue', normalized)
}
const ensureOptionsLoaded = async (force = false) => {
if (!force && !searchTerm.value && constructeurs.value.length) {
applyOptions(constructeurs.value as ConstructeurSummary[])
return
}
if (!force && searchTerm.value === lastSearchTerm && options.value.length) {
return
}
if (options.value.length && !force) {
return
}
const result = await searchConstructeurs(searchTerm.value)
if (result.success) {
applyOptions(result.data || [])
lastSearchTerm = searchTerm.value
}
}
const onSearch = () => {
openDropdown.value = true
if (searchTimeout) {
clearTimeout(searchTimeout)
}
searchTimeout = setTimeout(async () => {
if (!searchTerm.value && constructeurs.value.length) {
applyOptions(constructeurs.value as ConstructeurSummary[])
lastSearchTerm = ''
return
}
if (searchTerm.value === lastSearchTerm) {
return
}
const result = await searchConstructeurs(searchTerm.value)
if (result.success) {
applyOptions(result.data || [])
lastSearchTerm = searchTerm.value
}
}, 250)
}
const toggleOption = (option: ConstructeurSummary) => {
const ids = new Set(selectedIds.value)
if (ids.has(option.id)) {
ids.delete(option.id)
} else {
ids.add(option.id)
}
emitSelection(Array.from(ids))
}
const removeConstructeur = (id: string) => {
emitSelection(selectedIds.value.filter((item) => item !== id))
}
const closeCreateModal = () => {
openCreateModal.value = false
createForm.value = { name: '', email: '', phone: '' }
}
const handleCreate = async () => {
creating.value = true
const payload = { ...createForm.value }
if (!payload.phone) {
delete payload.phone
}
if (!payload.email) {
delete payload.email
}
const result = await createConstructeur(payload)
creating.value = false
if (result.success) {
emitSelection([...selectedIds.value, result.data.id])
searchTerm.value = ''
closeCreateModal()
await ensureOptionsLoaded(true)
}
}
const clickHandler = (event: Event) => {
const element = event.target as HTMLElement | null
if (element && element.closest) {
if (
element.closest('.menu') ||
element.closest('.modal-box') ||
element.closest('.btn') ||
element.closest('.constructeur-select')
) {
return
}
}
openDropdown.value = false
}
watch(
() => props.modelValue,
(newValue) => {
selectedIds.value = uniqueConstructeurIds(newValue)
},
{ immediate: true },
)
watch(
selectedIds,
async (ids) => {
if (!ids.length) {
return
}
const missing = ids.some((id) => !optionLookup.value.get(id))
if (missing) {
const fetched = await ensureConstructeurs(ids)
if (fetched.length) {
applyOptions([...options.value, ...fetched])
}
}
},
{ immediate: true },
)
watch(
constructeurs,
(list) => {
applyOptions((list as ConstructeurSummary[]) || [])
if (!searchTerm.value) {
lastSearchTerm = ''
}
},
{ immediate: true },
)
watch(
normalizedInitialOptions,
() => {
applyOptions(options.value)
},
{ immediate: true },
)
onMounted(() => {
window.addEventListener('click', clickHandler)
ensureOptionsLoaded()
})
onBeforeUnmount(() => {
window.removeEventListener('click', clickHandler)
if (searchTimeout) {
clearTimeout(searchTimeout)
}
})
watch(
selectedIds,
(ids) => {
// ensure options contain newly selected ids
const resolved = resolveConstructeurs(
ids,
constructeurs.value as ConstructeurSummary[],
options.value,
)
if (resolved.length) {
applyOptions([...resolved, ...options.value])
}
},
{ immediate: true },
)
</script>