Fix fournisseur handling across catalog flows
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import { ref } from 'vue'
|
||||
import { useToast } from './useToast'
|
||||
import { useApi } from './useApi'
|
||||
import { buildConstructeurRequestPayload } from '~/shared/constructeurUtils'
|
||||
import { buildConstructeurRequestPayload, uniqueConstructeurIds } from '~/shared/constructeurUtils'
|
||||
import { useConstructeurs } from './useConstructeurs'
|
||||
|
||||
const pieces = ref([])
|
||||
const loading = ref(false)
|
||||
@@ -9,13 +10,38 @@ const loading = ref(false)
|
||||
export function usePieces () {
|
||||
const { showSuccess, showError, showInfo } = useToast()
|
||||
const { get, post, patch, delete: del } = useApi()
|
||||
const { ensureConstructeurs } = useConstructeurs()
|
||||
|
||||
const withResolvedConstructeurs = async (piece) => {
|
||||
if (!piece || typeof piece !== 'object') {
|
||||
return piece
|
||||
}
|
||||
const ids = uniqueConstructeurIds(
|
||||
piece.constructeurIds,
|
||||
piece.constructeurs,
|
||||
piece.constructeur,
|
||||
)
|
||||
const hasConstructeurs =
|
||||
Array.isArray(piece.constructeurs) && piece.constructeurs.length > 0
|
||||
|
||||
if (ids.length && !hasConstructeurs) {
|
||||
const resolved = await ensureConstructeurs(ids)
|
||||
if (resolved.length) {
|
||||
piece.constructeurs = resolved
|
||||
piece.constructeurIds = ids
|
||||
}
|
||||
}
|
||||
return piece
|
||||
}
|
||||
|
||||
const loadPieces = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await get('/pieces')
|
||||
if (result.success) {
|
||||
pieces.value = result.data
|
||||
const items = Array.isArray(result.data) ? result.data : []
|
||||
const enrichedItems = await Promise.all(items.map((item) => withResolvedConstructeurs(item)))
|
||||
pieces.value = enrichedItems
|
||||
showInfo(`Chargement de ${pieces.value.length} pièce(s) réussi`)
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -30,7 +56,8 @@ export function usePieces () {
|
||||
try {
|
||||
const result = await post('/pieces', buildConstructeurRequestPayload(pieceData))
|
||||
if (result.success) {
|
||||
pieces.value.push(result.data)
|
||||
const enriched = await withResolvedConstructeurs(result.data)
|
||||
pieces.value.push(enriched)
|
||||
const displayName = result.data?.name
|
||||
|| pieceData?.definition?.name
|
||||
|| pieceData?.name
|
||||
@@ -51,7 +78,7 @@ export function usePieces () {
|
||||
try {
|
||||
const result = await patch(`/pieces/${id}`, buildConstructeurRequestPayload(pieceData))
|
||||
if (result.success) {
|
||||
const updated = result.data
|
||||
const updated = await withResolvedConstructeurs(result.data)
|
||||
const index = pieces.value.findIndex(piece => piece.id === id)
|
||||
if (index !== -1) {
|
||||
pieces.value[index] = updated
|
||||
|
||||
Reference in New Issue
Block a user