Tom Butcher 43464f8054 Refactor Delete Functionality Across Multiple Components
- Removed the delete action from various components including InvoiceInfo, PaymentInfo, and others to streamline functionality.
- Introduced a new DeleteObject component to handle deletion logic in a centralized manner, enhancing code maintainability.
- Updated models to utilize the new DeleteObject component for consistent deletion handling across the application.
- Simplified ObjectForm by eliminating the previous delete modal, improving component structure and clarity.
2026-08-22 21:06:32 +01:00

77 lines
2.4 KiB
JavaScript

import { useState, useContext } from 'react'
import PropTypes from 'prop-types'
import { useLocation, useNavigate } from 'react-router-dom'
import { ApiServerContext } from '../context/ApiServerContext'
import { useMessageContext } from '../context/MessageContext'
import { useActions } from '../context/ActionsContext'
import { getModelByName } from '../../../database/ObjectModels'
import MessageDialogView from './MessageDialogView.jsx'
import BinIcon from '../../Icons/BinIcon'
const capitalizeFirstLetter = (value) => {
return String(value).charAt(0).toUpperCase() + String(value).slice(1)
}
const DeleteObject = ({ onOk, objectData, objectType: objectTypeProp }) => {
const [deleteLoading, setDeleteLoading] = useState(false)
const { deleteObject } = useContext(ApiServerContext)
const { showSuccess, showError } = useMessageContext()
const { currentObjectType } = useActions()
const location = useLocation()
const navigate = useNavigate()
const objectType =
objectTypeProp ||
new URLSearchParams(location.search).get('actionObjectType') ||
currentObjectType
const model = objectType ? getModelByName(objectType) : null
const modelLabel = model?.label || 'object'
const objectName =
objectData?.name || objectData?._reference || objectData?._id
const handleDelete = async () => {
if (!objectData?._id || !objectType) return
setDeleteLoading(true)
try {
await deleteObject(objectData._id, objectType)
showSuccess(
`${capitalizeFirstLetter(modelLabel.toLowerCase())} deleted successfully!`
)
const onInfoPage = model?.url && location.pathname === `${model.url}/info`
if (onInfoPage) {
navigate(model.url)
} else {
onOk()
}
} catch (error) {
console.error('Error deleting object:', error)
showError(`Failed to delete ${modelLabel.toLowerCase()}.`)
} finally {
setDeleteLoading(false)
}
}
return (
<MessageDialogView
icon={<BinIcon />}
title={`Are you sure you want to delete this ${modelLabel.toLowerCase()}?`}
description={
objectName ? `This will permanently delete ${objectName}.` : undefined
}
onOk={handleDelete}
okText='Delete'
okLoading={deleteLoading}
danger
/>
)
}
DeleteObject.propTypes = {
onOk: PropTypes.func.isRequired,
objectData: PropTypes.object,
objectType: PropTypes.string
}
export default DeleteObject