723 lines
25 KiB
Vue
723 lines
25 KiB
Vue
<template>
|
|
<DocumentPreviewModal
|
|
:document="previewDocument"
|
|
:visible="previewVisible"
|
|
:documents="pieceDocuments"
|
|
@close="closePreview"
|
|
/>
|
|
<main class="container mx-auto px-6 py-10">
|
|
<div v-if="loading" class="flex flex-col items-center gap-4 py-20 text-center">
|
|
<span class="loading loading-spinner loading-lg" aria-hidden="true" />
|
|
<p class="text-sm text-base-content/70">Chargement de la pièce…</p>
|
|
</div>
|
|
|
|
<div v-else-if="!piece" class="max-w-xl mx-auto">
|
|
<div class="alert alert-error shadow-lg">
|
|
<div>
|
|
<h2 class="font-semibold text-lg">Pièce introuvable</h2>
|
|
<p class="text-sm text-base-content/80">
|
|
Nous n'avons pas pu retrouver la pièce demandée. Elle a peut-être été supprimée.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<button type="button" class="btn btn-primary mt-6" @click="$router.back()">
|
|
Retour au catalogue
|
|
</button>
|
|
</div>
|
|
|
|
<section v-else class="card border border-base-200 bg-base-100 shadow-sm max-w-5xl mx-auto">
|
|
<div class="card-body space-y-6">
|
|
<header class="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
|
|
<div>
|
|
<h1 class="text-3xl font-semibold text-base-content">Modifier la pièce</h1>
|
|
<p class="text-sm text-base-content/70">
|
|
Ajustez les informations de la pièce et ses champs personnalisés.
|
|
</p>
|
|
</div>
|
|
<button type="button" class="btn btn-ghost btn-sm md:btn-md self-start" @click="$router.back()">
|
|
Retour au catalogue
|
|
</button>
|
|
</header>
|
|
|
|
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
|
<div class="form-control">
|
|
<label class="label">
|
|
<span class="label-text">Catégorie de pièce</span>
|
|
</label>
|
|
<select
|
|
v-model="selectedTypeId"
|
|
class="select select-bordered select-sm md:select-md"
|
|
disabled
|
|
>
|
|
<option value="">Sélectionner une catégorie</option>
|
|
<option
|
|
v-for="type in pieceTypeList"
|
|
:key="type.id"
|
|
:value="type.id"
|
|
>
|
|
{{ type.name }}
|
|
</option>
|
|
</select>
|
|
<p class="text-xs text-base-content/60 mt-1">
|
|
La catégorie d'origine ne peut pas être modifiée depuis cette page.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
|
<div class="form-control">
|
|
<label class="label">
|
|
<span class="label-text">Nom de la pièce</span>
|
|
</label>
|
|
<input
|
|
v-model="editionForm.name"
|
|
type="text"
|
|
class="input input-bordered input-sm md:input-md"
|
|
:disabled="!canEdit || saving"
|
|
placeholder="Nom affiché dans le catalogue"
|
|
required
|
|
>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="form-control">
|
|
<label class="label">
|
|
<span class="label-text">Description</span>
|
|
</label>
|
|
<textarea
|
|
v-model="editionForm.description"
|
|
class="textarea textarea-bordered textarea-sm md:textarea-md"
|
|
:disabled="!canEdit || saving"
|
|
placeholder="Description de la pièce (optionnel)"
|
|
rows="3"
|
|
/>
|
|
</div>
|
|
|
|
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
|
<div class="form-control">
|
|
<label class="label">
|
|
<span class="label-text">Référence</span>
|
|
</label>
|
|
<input
|
|
v-model="editionForm.reference"
|
|
type="text"
|
|
class="input input-bordered input-sm md:input-md"
|
|
:disabled="!canEdit || saving"
|
|
placeholder="Référence interne ou fournisseur"
|
|
>
|
|
</div>
|
|
|
|
<div class="form-control">
|
|
<label class="label">
|
|
<span class="label-text">Fournisseur</span>
|
|
</label>
|
|
<ConstructeurSelect
|
|
v-model="editionForm.constructeurIds"
|
|
class="w-full"
|
|
:disabled="!canEdit || saving"
|
|
placeholder="Rechercher un ou plusieurs fournisseurs..."
|
|
:initial-options="piece?.constructeurs || []"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
|
<div class="form-control">
|
|
<label class="label">
|
|
<span class="label-text">Prix indicatif (€)</span>
|
|
</label>
|
|
<input
|
|
v-model="editionForm.prix"
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
class="input input-bordered input-sm md:input-md"
|
|
:disabled="!canEdit || saving"
|
|
placeholder="Valeur indicatrice"
|
|
>
|
|
</div>
|
|
</div>
|
|
|
|
<div
|
|
v-if="structureProducts.length"
|
|
class="space-y-3 rounded-lg border border-base-200 bg-base-200/40 p-4"
|
|
>
|
|
<header class="space-y-1">
|
|
<h2 class="font-semibold text-base-content">
|
|
Produit requis par le squelette
|
|
</h2>
|
|
<p class="text-xs text-base-content/70">
|
|
Cette pièce doit rester liée à un produit catalogue répondant aux critères suivants.
|
|
</p>
|
|
</header>
|
|
<ul class="space-y-2 text-sm text-base-content/80">
|
|
<li
|
|
v-for="(description, index) in productRequirementDescriptions"
|
|
:key="`edit-requirement-${index}`"
|
|
class="flex items-start gap-2"
|
|
>
|
|
<span class="mt-0.5 inline-flex h-2 w-2 flex-shrink-0 rounded-full bg-primary"></span>
|
|
<span>{{ description }}</span>
|
|
</li>
|
|
</ul>
|
|
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
|
<div
|
|
v-for="entry in productRequirementEntries"
|
|
:key="entry.key"
|
|
class="form-control"
|
|
>
|
|
<label class="label">
|
|
<span class="label-text text-xs font-medium">
|
|
{{ entry.label }}
|
|
</span>
|
|
</label>
|
|
<ProductSelect
|
|
:model-value="productSelections[entry.index] || null"
|
|
:disabled="!canEdit || saving"
|
|
:type-product-id="entry.typeProductId"
|
|
helper-text="Un produit valide est requis pour cette pièce."
|
|
@update:model-value="(value) => setProductSelection(entry.index, value)"
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<StructureSkeletonPreview
|
|
v-if="selectedType || resolvedStructure"
|
|
:structure="resolvedStructure"
|
|
:description="selectedType?.description || 'Ce squelette définit la structure et les champs personnalisés de la pièce.'"
|
|
:preview-badge="formatPieceStructurePreview(resolvedStructure)"
|
|
variant="piece"
|
|
/>
|
|
|
|
<div v-if="customFieldInputs.length" class="space-y-4 rounded-lg border border-base-200 bg-base-200/40 p-4">
|
|
<header class="space-y-1">
|
|
<h2 class="font-semibold text-base-content">Champs personnalisés</h2>
|
|
<p class="text-xs text-base-content/70">
|
|
Mettez à jour les valeurs propres à cette pièce.
|
|
</p>
|
|
</header>
|
|
<CustomFieldInputGrid :fields="customFieldInputs" :disabled="!canEdit || saving" />
|
|
</div>
|
|
|
|
<div class="space-y-4 rounded-lg border border-base-200 bg-base-200/40 p-4">
|
|
<header class="flex flex-col gap-1 md:flex-row md:items-center md:justify-between">
|
|
<div>
|
|
<h2 class="font-semibold text-base-content">Documents</h2>
|
|
<p class="text-xs text-base-content/70">
|
|
Gérez les documents associés à cette pièce.
|
|
</p>
|
|
</div>
|
|
<span v-if="selectedFiles.length" class="badge badge-outline">
|
|
{{ selectedFiles.length }} document{{ selectedFiles.length > 1 ? 's' : '' }} prêt{{ selectedFiles.length > 1 ? 's' : '' }} à être ajouté{{ selectedFiles.length > 1 ? 's' : '' }}
|
|
</span>
|
|
</header>
|
|
<div :class="{ 'pointer-events-none opacity-60': !canEdit || saving || uploadingDocuments }">
|
|
<DocumentUpload
|
|
v-model="selectedFiles"
|
|
title="Déposer vos fichiers"
|
|
subtitle="Formats acceptés : PDF, images, documents…"
|
|
@files-added="handleFilesAdded"
|
|
/>
|
|
</div>
|
|
<p v-if="uploadingDocuments" class="text-xs text-base-content/70">
|
|
Téléversement des documents en cours…
|
|
</p>
|
|
<p v-else-if="loadingDocuments" class="text-xs text-base-content/70">
|
|
Chargement des documents en cours…
|
|
</p>
|
|
<DocumentListInline
|
|
v-else
|
|
:documents="pieceDocuments"
|
|
:can-delete="canEdit"
|
|
:delete-disabled="uploadingDocuments"
|
|
empty-text="Aucun document n'est associé à cette pièce pour le moment."
|
|
@preview="openPreview"
|
|
@delete="removeDocument"
|
|
/>
|
|
</div>
|
|
|
|
<EntityHistorySection
|
|
:entries="history"
|
|
:loading="historyLoading"
|
|
:error="historyError"
|
|
:field-labels="historyFieldLabels"
|
|
/>
|
|
|
|
<div class="flex flex-col gap-3 md:flex-row md:justify-end">
|
|
<NuxtLink to="/pieces-catalog" class="btn btn-ghost" :class="{ 'btn-disabled': saving }">
|
|
Annuler
|
|
</NuxtLink>
|
|
<button type="button" class="btn btn-primary" :disabled="!canSubmit" @click="submitEdition">
|
|
<span v-if="saving" class="loading loading-spinner loading-sm mr-2" />
|
|
Enregistrer les modifications
|
|
</button>
|
|
</div>
|
|
|
|
<!-- Comments -->
|
|
<div class="mt-4">
|
|
<CommentSection
|
|
entity-type="piece"
|
|
:entity-id="String(route.params.id)"
|
|
:entity-name="piece?.name"
|
|
show-resolved
|
|
/>
|
|
</div>
|
|
</div>
|
|
</section>
|
|
</main>
|
|
</template>
|
|
|
|
<script setup lang="ts">
|
|
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
|
import { useRoute, useRouter } from '#imports'
|
|
import ConstructeurSelect from '~/components/ConstructeurSelect.vue'
|
|
import DocumentUpload from '~/components/DocumentUpload.vue'
|
|
import DocumentPreviewModal from '~/components/DocumentPreviewModal.vue'
|
|
import ProductSelect from '~/components/ProductSelect.vue'
|
|
import { usePieceTypes } from '~/composables/usePieceTypes'
|
|
import { usePieces } from '~/composables/usePieces'
|
|
import { useCustomFields } from '~/composables/useCustomFields'
|
|
import { useApi } from '~/composables/useApi'
|
|
import { useToast } from '~/composables/useToast'
|
|
import { useDocuments } from '~/composables/useDocuments'
|
|
import { useConstructeurs } from '~/composables/useConstructeurs'
|
|
import { usePieceHistory } from '~/composables/usePieceHistory'
|
|
import { extractRelationId } from '~/shared/apiRelations'
|
|
import { canPreviewDocument } from '~/utils/documentPreview'
|
|
import { formatPieceStructurePreview } from '~/shared/modelUtils'
|
|
import { uniqueConstructeurIds } from '~/shared/constructeurUtils'
|
|
import type { PieceModelProduct, PieceModelStructure } from '~/shared/types/inventory'
|
|
import type { ModelType } from '~/services/modelTypes'
|
|
import { getModelType } from '~/services/modelTypes'
|
|
import {
|
|
type CustomFieldInput,
|
|
buildCustomFieldInputs,
|
|
requiredCustomFieldsFilled as _requiredCustomFieldsFilled,
|
|
saveCustomFieldValues as _saveCustomFieldValues,
|
|
} from '~/shared/utils/customFieldFormUtils'
|
|
|
|
interface PieceCatalogType extends ModelType {
|
|
structure: PieceModelStructure | null
|
|
customFields?: Array<Record<string, any>>
|
|
}
|
|
|
|
const { canEdit } = usePermissions()
|
|
const route = useRoute()
|
|
const router = useRouter()
|
|
const { get } = useApi()
|
|
const { pieceTypes, loadPieceTypes } = usePieceTypes()
|
|
const { updatePiece } = usePieces()
|
|
const { upsertCustomFieldValue, updateCustomFieldValue } = useCustomFields()
|
|
const toast = useToast()
|
|
const { loadDocumentsByPiece, uploadDocuments, deleteDocument } = useDocuments()
|
|
const { ensureConstructeurs } = useConstructeurs()
|
|
const {
|
|
history,
|
|
loading: historyLoading,
|
|
error: historyError,
|
|
loadHistory,
|
|
} = usePieceHistory()
|
|
|
|
const piece = ref<any | null>(null)
|
|
const loading = ref(true)
|
|
const saving = ref(false)
|
|
const selectedFiles = ref<File[]>([])
|
|
const uploadingDocuments = ref(false)
|
|
const loadingDocuments = ref(false)
|
|
const pieceDocuments = ref<any[]>([])
|
|
const previewDocument = ref<any | null>(null)
|
|
const previewVisible = ref(false)
|
|
|
|
const historyFieldLabels: Record<string, string> = {
|
|
name: 'Nom',
|
|
reference: 'Référence',
|
|
prix: 'Prix',
|
|
typePiece: 'Catégorie',
|
|
product: 'Produit lié',
|
|
productIds: 'Produits liés',
|
|
constructeurIds: 'Fournisseurs',
|
|
}
|
|
|
|
const selectedTypeId = ref<string>('')
|
|
const pieceTypeDetails = ref<any | null>(null)
|
|
const editionForm = reactive({
|
|
name: '' as string,
|
|
description: '' as string,
|
|
reference: '' as string,
|
|
constructeurIds: [] as string[],
|
|
prix: '' as string,
|
|
})
|
|
const productSelections = ref<(string | null)[]>([])
|
|
|
|
const customFieldInputs = ref<CustomFieldInput[]>([])
|
|
const resolvedStructure = computed<PieceModelStructure | null>(() =>
|
|
pieceTypeDetails.value?.structure ?? selectedType.value?.structure ?? null,
|
|
)
|
|
|
|
const refreshCustomFieldInputs = (
|
|
structureOverride?: PieceModelStructure | null,
|
|
valuesOverride?: any[] | null,
|
|
) => {
|
|
const structure = structureOverride ?? resolvedStructure.value ?? null
|
|
const values = valuesOverride ?? piece.value?.customFieldValues ?? null
|
|
customFieldInputs.value = buildCustomFieldInputs(structure, values)
|
|
}
|
|
const openPreview = (doc: any) => {
|
|
if (!doc || !canPreviewDocument(doc)) {
|
|
return
|
|
}
|
|
previewDocument.value = doc
|
|
previewVisible.value = true
|
|
}
|
|
const closePreview = () => {
|
|
previewVisible.value = false
|
|
previewDocument.value = null
|
|
}
|
|
const removeDocument = async (documentId: string | number | null | undefined) => {
|
|
if (!documentId) {
|
|
return
|
|
}
|
|
const result = await deleteDocument(documentId, { updateStore: false })
|
|
if (result.success) {
|
|
pieceDocuments.value = pieceDocuments.value.filter((doc) => doc.id !== documentId)
|
|
}
|
|
}
|
|
const handleFilesAdded = async (files: File[]) => {
|
|
if (!files?.length || !piece.value?.id) {
|
|
return
|
|
}
|
|
uploadingDocuments.value = true
|
|
try {
|
|
const result = await uploadDocuments(
|
|
{
|
|
files,
|
|
context: { pieceId: piece.value.id },
|
|
},
|
|
{ updateStore: false },
|
|
)
|
|
if (result.success) {
|
|
selectedFiles.value = []
|
|
await refreshDocuments()
|
|
}
|
|
} finally {
|
|
uploadingDocuments.value = false
|
|
}
|
|
}
|
|
const refreshDocuments = async () => {
|
|
if (!piece.value?.id) {
|
|
pieceDocuments.value = []
|
|
return
|
|
}
|
|
loadingDocuments.value = true
|
|
try {
|
|
const result = await loadDocumentsByPiece(piece.value.id, { updateStore: false })
|
|
if (result.success) {
|
|
pieceDocuments.value = Array.isArray(result.data) ? result.data : result.data ? [result.data] : []
|
|
}
|
|
} finally {
|
|
loadingDocuments.value = false
|
|
}
|
|
}
|
|
|
|
const pieceTypeList = computed<PieceCatalogType[]>(() => (pieceTypes.value || []) as PieceCatalogType[])
|
|
|
|
const selectedType = computed(() => {
|
|
if (!selectedTypeId.value) {
|
|
return null
|
|
}
|
|
return pieceTypeList.value.find((type) => type.id === selectedTypeId.value) ?? null
|
|
})
|
|
|
|
const getStructureProducts = (structure: PieceModelStructure | null) =>
|
|
Array.isArray(structure?.products) ? structure.products : []
|
|
|
|
const structureProducts = computed(() =>
|
|
getStructureProducts(resolvedStructure.value),
|
|
)
|
|
|
|
const requiresProductSelection = computed(() => structureProducts.value.length > 0)
|
|
|
|
const describeProductRequirement = (requirement: PieceModelProduct, index: number) => {
|
|
if (!requirement) {
|
|
return `Produit ${index + 1}`
|
|
}
|
|
const parts: string[] = []
|
|
if (requirement.role) {
|
|
parts.push(requirement.role)
|
|
}
|
|
if (requirement.typeProductLabel) {
|
|
parts.push(requirement.typeProductLabel)
|
|
} else if (requirement.typeProductId) {
|
|
parts.push(`Catégorie #${requirement.typeProductId}`)
|
|
}
|
|
if (requirement.familyCode) {
|
|
parts.push(`Famille ${requirement.familyCode}`)
|
|
}
|
|
if (parts.length === 0) {
|
|
parts.push(`Produit ${index + 1}`)
|
|
}
|
|
return parts.join(' • ')
|
|
}
|
|
|
|
const productRequirementDescriptions = computed(() =>
|
|
structureProducts.value.map((requirement, index) =>
|
|
describeProductRequirement(requirement, index),
|
|
),
|
|
)
|
|
|
|
const ensureProductSelections = (count: number) => {
|
|
const next = Array.from({ length: count }, (_, index) => productSelections.value[index] ?? null)
|
|
productSelections.value = next
|
|
}
|
|
|
|
let pendingProductIds: string[] = []
|
|
|
|
const productRequirementEntries = computed(() =>
|
|
structureProducts.value.map((requirement, index) => ({
|
|
index,
|
|
key: `piece-product-requirement-${index}-${requirement?.typeProductId || 'any'}`,
|
|
label: describeProductRequirement(requirement, index),
|
|
typeProductId: requirement?.typeProductId ? String(requirement.typeProductId) : null,
|
|
})),
|
|
)
|
|
|
|
const productSelectionsFilled = computed(() =>
|
|
!requiresProductSelection.value ||
|
|
productRequirementEntries.value.every((entry) => {
|
|
const value = productSelections.value[entry.index]
|
|
return typeof value === 'string' && value.trim().length > 0
|
|
}),
|
|
)
|
|
|
|
const setProductSelection = (index: number, value: string | null) => {
|
|
const normalized = typeof value === 'string' ? value : null
|
|
const next = [...productSelections.value]
|
|
next[index] = normalized
|
|
productSelections.value = next
|
|
}
|
|
|
|
watch(structureProducts, (products) => {
|
|
ensureProductSelections(products.length)
|
|
if (!pendingProductIds.length || products.length === 0) {
|
|
return
|
|
}
|
|
const next = Array.from(
|
|
{ length: products.length },
|
|
(_, index) => pendingProductIds[index] ?? null,
|
|
)
|
|
productSelections.value = next
|
|
pendingProductIds = []
|
|
})
|
|
|
|
const requiredCustomFieldsFilled = computed(() =>
|
|
_requiredCustomFieldsFilled(customFieldInputs.value),
|
|
)
|
|
|
|
const canSubmit = computed(() =>
|
|
Boolean(
|
|
canEdit.value &&
|
|
piece.value &&
|
|
editionForm.name &&
|
|
requiredCustomFieldsFilled.value &&
|
|
productSelectionsFilled.value &&
|
|
!saving.value,
|
|
),
|
|
)
|
|
|
|
const fetchPiece = async () => {
|
|
const id = route.params.id
|
|
if (!id || typeof id !== 'string') {
|
|
piece.value = null
|
|
pieceDocuments.value = []
|
|
return
|
|
}
|
|
const result = await get(`/pieces/${id}`)
|
|
if (result.success) {
|
|
piece.value = result.data
|
|
pieceDocuments.value = Array.isArray(result.data?.documents) ? result.data.documents : []
|
|
|
|
// Use customFieldValues from entity response (enriched with customField definitions via serialization groups)
|
|
const customValues = Array.isArray(result.data?.customFieldValues) ? result.data.customFieldValues : []
|
|
refreshCustomFieldInputs(undefined, customValues)
|
|
|
|
// Use cached type from loadPieceTypes() instead of separate getModelType() call
|
|
loadPieceTypeDetailsFromCache(result.data)
|
|
|
|
// History is non-blocking — template handles its own loading state
|
|
loadHistory(result.data.id).catch(() => {})
|
|
} else {
|
|
piece.value = null
|
|
pieceDocuments.value = []
|
|
}
|
|
}
|
|
|
|
const loadPieceTypeDetailsFromCache = (currentPiece: any) => {
|
|
const typeId = currentPiece?.typePieceId
|
|
|| extractRelationId(currentPiece?.typePiece)
|
|
|| ''
|
|
if (!typeId) {
|
|
pieceTypeDetails.value = null
|
|
return
|
|
}
|
|
// Look up in the already-loaded pieceTypes cache (from loadPieceTypes in onMounted)
|
|
const cachedType = (pieceTypes.value || []).find((t: any) => t.id === typeId) ?? null
|
|
if (cachedType) {
|
|
pieceTypeDetails.value = cachedType
|
|
refreshCustomFieldInputs((cachedType.structure as PieceModelStructure | null) ?? null, currentPiece?.customFieldValues ?? null)
|
|
return
|
|
}
|
|
// Fallback: fetch if not in cache (edge case)
|
|
getModelType(typeId).then((type) => {
|
|
if (type && typeof type === 'object') {
|
|
pieceTypeDetails.value = type
|
|
refreshCustomFieldInputs((type.structure as PieceModelStructure | null) ?? null, currentPiece?.customFieldValues ?? null)
|
|
}
|
|
}).catch(() => {
|
|
pieceTypeDetails.value = null
|
|
})
|
|
}
|
|
|
|
let initialized = false
|
|
|
|
watch(
|
|
[piece, selectedType],
|
|
([currentPiece, currentType]) => {
|
|
if (!currentPiece || initialized) {
|
|
return
|
|
}
|
|
|
|
const resolvedTypeId = currentPiece.typePieceId
|
|
|| extractRelationId(currentPiece.typePiece)
|
|
|| ''
|
|
if (resolvedTypeId && !currentPiece.typePieceId) {
|
|
currentPiece.typePieceId = resolvedTypeId
|
|
}
|
|
selectedTypeId.value = resolvedTypeId
|
|
|
|
editionForm.name = currentPiece.name || ''
|
|
editionForm.description = currentPiece.description || ''
|
|
editionForm.reference = currentPiece.reference || ''
|
|
editionForm.constructeurIds = uniqueConstructeurIds(
|
|
currentPiece,
|
|
Array.isArray(currentPiece.constructeurs) ? currentPiece.constructeurs : [],
|
|
currentPiece.constructeur ? [currentPiece.constructeur] : [],
|
|
)
|
|
editionForm.prix = currentPiece.prix !== null && currentPiece.prix !== undefined ? String(currentPiece.prix) : ''
|
|
if (editionForm.constructeurIds.length) {
|
|
void ensureConstructeurs(editionForm.constructeurIds)
|
|
}
|
|
|
|
const existingProductIds = Array.isArray(currentPiece.productIds) && currentPiece.productIds.length
|
|
? currentPiece.productIds.map((id: unknown) => String(id))
|
|
: currentPiece.product?.id || currentPiece.productId
|
|
? [String(currentPiece.product?.id || currentPiece.productId)]
|
|
: []
|
|
pendingProductIds = existingProductIds
|
|
ensureProductSelections(structureProducts.value.length)
|
|
if (existingProductIds.length && structureProducts.value.length) {
|
|
const next = Array.from(
|
|
{ length: structureProducts.value.length },
|
|
(_, index) => existingProductIds[index] ?? null,
|
|
)
|
|
productSelections.value = next
|
|
pendingProductIds = []
|
|
}
|
|
|
|
// After setting selectedTypeId, read selectedType.value (now updated) instead of
|
|
// the stale destructured currentType which was captured before the ID change.
|
|
const resolvedType = selectedType.value ?? pieceTypeDetails.value ?? null
|
|
refreshCustomFieldInputs(resolvedType?.structure ?? null, currentPiece.customFieldValues)
|
|
|
|
initialized = true
|
|
},
|
|
{ immediate: true },
|
|
)
|
|
|
|
watch(selectedType, (currentType) => {
|
|
if (!piece.value || !currentType) {
|
|
return
|
|
}
|
|
refreshCustomFieldInputs(currentType.structure, piece.value.customFieldValues)
|
|
})
|
|
|
|
watch(resolvedStructure, (currentStructure) => {
|
|
if (!piece.value) {
|
|
return
|
|
}
|
|
ensureProductSelections(structureProducts.value.length)
|
|
refreshCustomFieldInputs(currentStructure, piece.value.customFieldValues)
|
|
})
|
|
|
|
const submitEdition = async () => {
|
|
if (!piece.value) {
|
|
return
|
|
}
|
|
|
|
if (!productSelectionsFilled.value) {
|
|
toast.showError('Sélectionnez un produit conforme au squelette.')
|
|
return
|
|
}
|
|
|
|
const rawPrice = typeof editionForm.prix === 'string'
|
|
? editionForm.prix.trim()
|
|
: editionForm.prix === null || editionForm.prix === undefined
|
|
? ''
|
|
: String(editionForm.prix).trim()
|
|
|
|
const constructeurIds = uniqueConstructeurIds(editionForm.constructeurIds)
|
|
|
|
const payload: Record<string, any> = {
|
|
name: editionForm.name.trim(),
|
|
description: editionForm.description.trim() || null,
|
|
constructeurIds,
|
|
}
|
|
|
|
const reference = editionForm.reference.trim()
|
|
payload.reference = reference ? reference : null
|
|
|
|
const normalizedProductIds = productRequirementEntries.value
|
|
.map((entry) => productSelections.value[entry.index])
|
|
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
|
.map((value) => value.trim())
|
|
|
|
payload.productIds = normalizedProductIds
|
|
payload.productId = normalizedProductIds[0] || null
|
|
|
|
if (rawPrice) {
|
|
const parsed = Number(rawPrice)
|
|
if (!Number.isNaN(parsed)) {
|
|
payload.prix = String(parsed)
|
|
}
|
|
} else {
|
|
payload.prix = null
|
|
}
|
|
|
|
saving.value = true
|
|
try {
|
|
const result = await updatePiece(piece.value.id, payload)
|
|
if (result.success && result.data) {
|
|
const updatedPiece = result.data as Record<string, any>
|
|
await _saveCustomFieldValues(
|
|
'piece',
|
|
updatedPiece.id,
|
|
[
|
|
updatedPiece?.typePiece?.pieceCustomFields,
|
|
],
|
|
{ customFieldInputs, upsertCustomFieldValue, updateCustomFieldValue, toast },
|
|
)
|
|
await router.push('/pieces-catalog')
|
|
}
|
|
} catch (error: any) {
|
|
toast.showError(error?.message || 'Erreur lors de la mise à jour de la pièce')
|
|
} finally {
|
|
saving.value = false
|
|
}
|
|
}
|
|
|
|
onMounted(async () => {
|
|
await Promise.allSettled([loadPieceTypes(), fetchPiece()])
|
|
loading.value = false
|
|
})
|
|
</script>
|