Implemented materials.
All checks were successful
farmcontrol/farmcontrol-ui/pipeline/head This commit looks good

This commit is contained in:
Tom Butcher 2026-03-08 01:28:09 +00:00
parent 6d1946b91a
commit 6870320ab4
9 changed files with 409 additions and 280 deletions

View File

@ -1,218 +1,26 @@
// src/materials.js import { useRef, useState } from 'react'
import { Button, Flex, Space, Modal, Dropdown } from 'antd'
import { useEffect, useState, useContext, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
import {
Table,
Button,
Flex,
Space,
Modal,
Dropdown,
Spin
} from 'antd'
import { createStyles } from 'antd-style'
import { LoadingOutlined } from '@ant-design/icons'
import { useMessageContext } from '../context/MessageContext'
import { AuthContext } from '../context/AuthContext'
import NewMaterial from './Materials/NewMaterial' import NewMaterial from './Materials/NewMaterial'
import IdDisplay from '../common/IdDisplay'
import MaterialIcon from '../../Icons/MaterialIcon' import useColumnVisibility from '../hooks/useColumnVisibility'
import InfoCircleIcon from '../../Icons/InfoCircleIcon' import ColumnViewButton from '../common/ColumnViewButton'
import ObjectTable from '../common/ObjectTable'
import PlusIcon from '../../Icons/PlusIcon' import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon' import ReloadIcon from '../../Icons/ReloadIcon'
import TimeDisplay from '../common/TimeDisplay' import ListIcon from '../../Icons/ListIcon'
import GridIcon from '../../Icons/GridIcon'
import config from '../../../config' import useViewMode from '../hooks/useViewMode'
import ExportListButton from '../common/ExportListButton'
const useStyle = createStyles(({ css, token }) => {
const { antCls } = token
return {
customTable: css`
${antCls}-table {
${antCls}-table-container {
${antCls}-table-body,
${antCls}-table-content {
scrollbar-width: thin;
scrollbar-color: #eaeaea transparent;
scrollbar-gutter: stable;
}
}
}
`
}
})
const Materials = () => { const Materials = () => {
const { showError } = useMessageContext()
const navigate = useNavigate()
const { styles } = useStyle()
const [materialsData, setMaterialsData] = useState([])
const [page, setPage] = useState(1)
const [hasMore, setHasMore] = useState(true)
const [loading, setLoading] = useState(true)
const [lazyLoading, setLazyLoading] = useState(false)
const [newMaterialOpen, setNewMaterialOpen] = useState(false) const [newMaterialOpen, setNewMaterialOpen] = useState(false)
const tableRef = useRef()
const { authenticated } = useContext(AuthContext) const [viewMode, setViewMode] = useViewMode('material')
const fetchMaterialsData = useCallback( const [columnVisibility, setColumnVisibility] =
async (pageNum = 1, append = false) => { useColumnVisibility('material')
try {
const response = await axios.get(`${config.backendUrl}/materials`, {
params: {
page: pageNum,
limit: 25
},
headers: {
Accept: 'application/json'
},
withCredentials: true
})
const newData = response.data
setHasMore(newData.length === 25) // If we get less than 25 items, we've reached the end
if (append) {
setMaterialsData((prev) => [...prev, ...newData])
} else {
setMaterialsData(newData)
}
setLoading(false)
setLazyLoading(false)
} catch (error) {
if (error.response) {
showError(
`Error updating material details: ${error.response.status}`
)
} else {
showError(
'An unexpected error occurred. Please try again later.'
)
}
setLoading(false)
setLazyLoading(false)
}
},
[showError]
)
useEffect(() => {
if (authenticated) {
fetchMaterialsData()
}
}, [authenticated, fetchMaterialsData])
const handleScroll = useCallback(
(e) => {
const { target } = e
const scrollHeight = target.scrollHeight
const scrollTop = target.scrollTop
const clientHeight = target.clientHeight
// If we're near the bottom (within 100px) and not currently loading
if (
scrollHeight - scrollTop - clientHeight < 100 &&
!lazyLoading &&
hasMore
) {
setLazyLoading(true)
const nextPage = page + 1
setPage(nextPage)
fetchMaterialsData(nextPage, true)
}
},
[page, lazyLoading, hasMore, fetchMaterialsData]
)
const getMaterialActionItems = (id) => {
return {
items: [
{
label: 'Info',
key: 'info',
icon: <InfoCircleIcon />
}
],
onClick: ({ key }) => {
if (key === 'info') {
navigate(`/dashboard/management/materials/info?materialId=${id}`)
}
}
}
}
const columns = [
{
title: '',
dataIndex: '',
key: 'icon',
width: 40,
fixed: 'left',
render: () => <MaterialIcon></MaterialIcon>
},
{
title: 'Name',
dataIndex: 'name',
key: 'name',
width: 200,
fixed: 'left'
},
{
title: 'ID',
dataIndex: '_id',
key: 'id',
width: 180,
render: (text) => <IdDisplay id={text} type={'material'} longId={false} />
},
{
title: 'Category',
dataIndex: 'category',
key: 'category',
width: 150
},
{
title: 'Created At',
dataIndex: 'createdAt',
key: 'createdAt',
width: 180,
render: (createdAt) => {
if (createdAt) {
return <TimeDisplay dateTime={createdAt} />
} else {
return 'n/a'
}
}
},
{
title: 'Actions',
key: 'actions',
fixed: 'right',
width: 150,
render: (text, record) => {
return (
<Space gap='small'>
<Button
icon={<InfoCircleIcon />}
onClick={() =>
navigate(
`/dashboard/management/materials/info?materialId=${record._id}`
)
}
/>
<Dropdown menu={getMaterialActionItems(record._id)}>
<Button>Actions</Button>
</Dropdown>
</Space>
)
}
}
]
const actionItems = { const actionItems = {
items: [ items: [
@ -230,7 +38,7 @@ const Materials = () => {
], ],
onClick: ({ key }) => { onClick: ({ key }) => {
if (key === 'reloadList') { if (key === 'reloadList') {
fetchMaterialsData() tableRef.current?.reload()
} else if (key === 'newMaterial') { } else if (key === 'newMaterial') {
setNewMaterialOpen(true) setNewMaterialOpen(true)
} }
@ -240,30 +48,38 @@ const Materials = () => {
return ( return (
<> <>
<Flex vertical={'true'} gap='large'> <Flex vertical={'true'} gap='large'>
<Flex justify={'space-between'}>
<Space> <Space>
<Dropdown menu={actionItems}> <Dropdown menu={actionItems}>
<Button>Actions</Button> <Button>Actions</Button>
</Dropdown> </Dropdown>
</Space> <ColumnViewButton
<Table type='material'
dataSource={materialsData} loading={false}
className={styles.customTable} visibleState={columnVisibility}
columns={columns} updateVisibleState={setColumnVisibility}
pagination={false}
rowKey='_id'
loading={{ spinning: loading, indicator: <LoadingOutlined spin /> }}
scroll={{ y: 'calc(100vh - 270px)' }}
onScroll={handleScroll}
/> />
{lazyLoading && ( <ExportListButton objectType='material' />
<div style={{ textAlign: 'center', padding: '10px' }}> </Space>
<Spin indicator={<LoadingOutlined spin />} /> <Space>
</div> <Button
)} icon={viewMode === 'cards' ? <ListIcon /> : <GridIcon />}
onClick={() =>
setViewMode(viewMode === 'cards' ? 'list' : 'cards')
}
/>
</Space>
</Flex> </Flex>
<ObjectTable
ref={tableRef}
type='material'
cards={viewMode === 'cards'}
visibleColumns={columnVisibility}
/>
<Modal <Modal
open={newMaterialOpen} open={newMaterialOpen}
styles={{ content: { paddingBottom: '24px' } }}
footer={null} footer={null}
width={700} width={700}
onCancel={() => { onCancel={() => {
@ -271,12 +87,14 @@ const Materials = () => {
}} }}
> >
<NewMaterial <NewMaterial
onSuccess={() => { onOk={() => {
setNewMaterialOpen(false) setNewMaterialOpen(false)
fetchMaterialsData() tableRef.current?.reload()
}} }}
reset={newMaterialOpen}
/> />
</Modal> </Modal>
</Flex>
</> </>
) )
} }

View File

@ -0,0 +1,199 @@
import { useRef, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { Space, Flex, Card } from 'antd'
import loglevel from 'loglevel'
import config from '../../../../config'
import useCollapseState from '../../hooks/useCollapseState'
import NotesPanel from '../../common/NotesPanel'
import InfoCollapse from '../../common/InfoCollapse'
import ObjectInfo from '../../common/ObjectInfo'
import ViewButton from '../../common/ViewButton'
import InfoCircleIcon from '../../../Icons/InfoCircleIcon.jsx'
import NoteIcon from '../../../Icons/NoteIcon.jsx'
import AuditLogIcon from '../../../Icons/AuditLogIcon.jsx'
import ObjectForm from '../../common/ObjectForm'
import EditButtons from '../../common/EditButtons'
import LockIndicator from '../../common/LockIndicator.jsx'
import ActionHandler from '../../common/ActionHandler.jsx'
import ObjectActions from '../../common/ObjectActions.jsx'
import ObjectTable from '../../common/ObjectTable.jsx'
import InfoCollapsePlaceholder from '../../common/InfoCollapsePlaceholder.jsx'
import DocumentPrintButton from '../../common/DocumentPrintButton.jsx'
import UserNotifierToggle from '../../common/UserNotifierToggle.jsx'
import ScrollBox from '../../common/ScrollBox.jsx'
const log = loglevel.getLogger('MaterialInfo')
log.setLevel(config.logLevel)
const MaterialInfo = () => {
const location = useLocation()
const objectFormRef = useRef(null)
const actionHandlerRef = useRef(null)
const materialId = new URLSearchParams(location.search).get('materialId')
const [collapseState, updateCollapseState] = useCollapseState('MaterialInfo', {
info: true,
notes: true,
auditLogs: true
})
const [objectFormState, setEditFormState] = useState({
isEditing: false,
editLoading: false,
formValid: false,
lock: null,
loading: false,
objectData: {}
})
const actions = {
reload: () => {
objectFormRef?.current?.handleFetchObject?.()
return true
},
edit: () => {
objectFormRef?.current?.startEditing?.()
return false
},
cancelEdit: () => {
objectFormRef?.current?.cancelEditing?.()
return true
},
finishEdit: () => {
objectFormRef?.current?.handleUpdate?.()
return true
},
delete: () => {
objectFormRef?.current?.handleDelete?.()
return true
}
}
return (
<>
<Flex
gap='large'
vertical='true'
style={{ maxHeight: '100%', minHeight: 0 }}
>
<Flex justify={'space-between'}>
<Space size='middle'>
<Space size='small'>
<ObjectActions
type='material'
id={materialId}
disabled={objectFormState.loading}
objectData={objectFormState.objectData}
/>
<ViewButton
disabled={objectFormState.loading}
items={[
{ key: 'info', label: 'Material Information' },
{ key: 'notes', label: 'Notes' },
{ key: 'auditLogs', label: 'Audit Logs' }
]}
visibleState={collapseState}
updateVisibleState={updateCollapseState}
/>
<UserNotifierToggle
type='material'
objectData={objectFormState.objectData}
disabled={objectFormState.loading}
/>
<DocumentPrintButton
type='material'
objectData={objectFormState.objectData}
disabled={objectFormState.loading}
/>
</Space>
<LockIndicator lock={objectFormState.lock} />
</Space>
<Space>
<EditButtons
isEditing={objectFormState.isEditing}
handleUpdate={() => {
actionHandlerRef.current.callAction('finishEdit')
}}
cancelEditing={() => {
actionHandlerRef.current.callAction('cancelEdit')
}}
startEditing={() => {
actionHandlerRef.current.callAction('edit')
}}
editLoading={objectFormState.editLoading}
formValid={objectFormState.formValid}
disabled={objectFormState.lock?.locked || objectFormState.loading}
loading={objectFormState.editLoading}
/>
</Space>
</Flex>
<ScrollBox>
<Flex vertical gap={'large'}>
<ActionHandler
actions={actions}
loading={objectFormState.loading}
ref={actionHandlerRef}
>
<InfoCollapse
title='Material Information'
icon={<InfoCircleIcon />}
active={collapseState.info}
onToggle={(expanded) => updateCollapseState('info', expanded)}
collapseKey='info'
>
<ObjectForm
id={materialId}
type='material'
style={{ height: '100%' }}
ref={objectFormRef}
onStateChange={(state) => {
setEditFormState((prev) => ({ ...prev, ...state }))
}}
>
{({ loading, isEditing, objectData }) => (
<ObjectInfo
loading={loading}
isEditing={isEditing}
type='material'
objectData={objectData}
/>
)}
</ObjectForm>
</InfoCollapse>
</ActionHandler>
<InfoCollapse
title='Notes'
icon={<NoteIcon />}
active={collapseState.notes}
onToggle={(expanded) => updateCollapseState('notes', expanded)}
collapseKey='notes'
>
<Card>
<NotesPanel _id={materialId} type='material' />
</Card>
</InfoCollapse>
<InfoCollapse
title='Audit Logs'
icon={<AuditLogIcon />}
active={collapseState.auditLogs}
onToggle={(expanded) =>
updateCollapseState('auditLogs', expanded)
}
collapseKey='auditLogs'
>
{objectFormState.loading ? (
<InfoCollapsePlaceholder />
) : (
<ObjectTable
type='auditLog'
masterFilter={{ 'parent._id': materialId }}
visibleColumns={{ _id: false, 'parent._id': false }}
/>
)}
</InfoCollapse>
</Flex>
</ScrollBox>
</Flex>
</>
)
}
export default MaterialInfo

View File

@ -61,9 +61,11 @@ const NewMaterial = ({ onOk }) => {
loading={submitLoading} loading={submitLoading}
formValid={formValid} formValid={formValid}
title='New Material' title='New Material'
onSubmit={() => { onSubmit={async () => {
handleSubmit() const result = await handleSubmit()
if (result) {
onOk() onOk()
}
}} }}
/> />
) )

View File

@ -51,15 +51,6 @@ import { round } from '../utils/Utils'
const { Text } = Typography const { Text } = Typography
const MATERIAL_OPTIONS = [
{ value: 'PLA', label: 'PLA' },
{ value: 'PETG', label: 'PETG' },
{ value: 'ABS', label: 'ABS' },
{ value: 'ASA', label: 'ASA' },
{ value: 'HIPS', label: 'HIPS' },
{ value: 'TPU', label: 'TPU' }
]
const ObjectProperty = ({ const ObjectProperty = ({
type = 'text', type = 'text',
prefix, prefix,
@ -432,17 +423,6 @@ const ObjectProperty = ({
) )
} }
} }
case 'material': {
if (value) {
return <Text {...textParams}>{value}</Text>
} else {
return (
<Text type='secondary' {...textParams}>
n/a
</Text>
)
}
}
case 'id': { case 'id': {
if (value) { if (value) {
return ( return (
@ -754,14 +734,6 @@ const ObjectProperty = ({
) )
case 'markdown': case 'markdown':
return <MarkdownInput {...inputProps} /> return <MarkdownInput {...inputProps} />
case 'material':
return (
<Select
options={MATERIAL_OPTIONS}
placeholder={label}
{...inputProps}
/>
)
case 'id': case 'id':
// id is not editable, just show view mode // id is not editable, just show view mode
if (value) { if (value) {

View File

@ -18,7 +18,8 @@ export const HistoryProvider = ({ children }) => {
'/dashboard/management/filaments': 'Filaments', '/dashboard/management/filaments': 'Filaments',
'/dashboard/management/parts': 'Parts', '/dashboard/management/parts': 'Parts',
'/dashboard/management/products': 'Products', '/dashboard/management/products': 'Products',
'/dashboard/management/vendors': 'Vendors' '/dashboard/management/vendors': 'Vendors',
'/dashboard/management/materials': 'Materials'
} }
const getEntityDetails = (pathname, search) => { const getEntityDetails = (pathname, search) => {
@ -65,6 +66,14 @@ export const HistoryProvider = ({ children }) => {
displayName: `Vendor Info${vendorId ? ` (${vendorId})` : ''}` displayName: `Vendor Info${vendorId ? ` (${vendorId})` : ''}`
} }
} }
if (pathname.includes('/materials/info')) {
const materialId = searchParams.get('materialId')
return {
type: 'material',
id: materialId,
displayName: `Material Info${materialId ? ` (${materialId})` : ''}`
}
}
// For base routes, return the simple name // For base routes, return the simple name
const baseName = baseRouteNames[pathname] const baseName = baseRouteNames[pathname]
@ -85,7 +94,8 @@ export const HistoryProvider = ({ children }) => {
if ( if (
newPath === '/dashboard/production/gcodefiles' || newPath === '/dashboard/production/gcodefiles' ||
newPath === '/dashboard/management/filaments' newPath === '/dashboard/management/filaments' ||
newPath === '/dashboard/management/materials'
) { ) {
setNavigationHistory([ setNavigationHistory([
{ {

View File

@ -1,6 +1,7 @@
import { Printer } from './models/Printer.js' import { Printer } from './models/Printer.js'
import { Host } from './models/Host.js' import { Host } from './models/Host.js'
import { Filament } from './models/Filament.js' import { Filament } from './models/Filament.js'
import { Material } from './models/Material.js'
import { FilamentSku } from './models/FilamentSku.js' import { FilamentSku } from './models/FilamentSku.js'
import { Spool } from './models/Spool' import { Spool } from './models/Spool'
import { GCodeFile } from './models/GCodeFile' import { GCodeFile } from './models/GCodeFile'
@ -45,6 +46,7 @@ export const objectModels = [
Host, Host,
Filament, Filament,
FilamentSku, FilamentSku,
Material,
Spool, Spool,
GCodeFile, GCodeFile,
Job, Job,
@ -89,6 +91,7 @@ export {
Host, Host,
Filament, Filament,
FilamentSku, FilamentSku,
Material,
Spool, Spool,
GCodeFile, GCodeFile,
Job, Job,

View File

@ -74,16 +74,16 @@ export const Filament = {
columns: [ columns: [
'_reference', '_reference',
'name', 'name',
'type', 'material',
'density', 'density',
'diameter', 'diameter',
'cost', 'cost',
'createdAt', 'createdAt',
'updatedAt' 'updatedAt'
], ],
filters: ['_id', 'name', 'type'], filters: ['_id', 'name', 'material'],
sorters: ['name', 'createdAt', 'type', 'updatedAt'], sorters: ['name', 'createdAt', 'material', 'updatedAt'],
group: ['diameter', 'type'], group: ['diameter', 'material'],
properties: [ properties: [
{ {
name: '_id', name: '_id',
@ -113,11 +113,13 @@ export const Filament = {
readOnly: true readOnly: true
}, },
{ {
name: 'type', name: 'material',
label: 'Material', label: 'Material',
required: true, required: true,
columnWidth: 150, columnWidth: 150,
type: 'material' type: 'object',
objectType: 'material',
showHyperlink: true
}, },
{ {
name: 'diameter', name: 'diameter',

View File

@ -0,0 +1,117 @@
import MaterialIcon from '../../components/Icons/MaterialIcon'
import InfoCircleIcon from '../../components/Icons/InfoCircleIcon'
import EditIcon from '../../components/Icons/EditIcon'
import CheckIcon from '../../components/Icons/CheckIcon'
import XMarkIcon from '../../components/Icons/XMarkIcon'
import ReloadIcon from '../../components/Icons/ReloadIcon'
import BinIcon from '../../components/Icons/BinIcon'
export const Material = {
name: 'material',
label: 'Material',
prefix: 'MAT',
icon: MaterialIcon,
actions: [
{
name: 'info',
label: 'Info',
default: true,
row: true,
icon: InfoCircleIcon,
url: (_id) => `/dashboard/management/materials/info?materialId=${_id}`
},
{
name: 'reload',
label: 'Reload',
icon: ReloadIcon,
url: (_id) =>
`/dashboard/management/materials/info?materialId=${_id}&action=reload`
},
{
name: 'edit',
label: 'Edit',
row: true,
icon: EditIcon,
url: (_id) =>
`/dashboard/management/materials/info?materialId=${_id}&action=edit`,
visible: (objectData) => {
return !(objectData?._isEditing && objectData?._isEditing == true)
}
},
{
name: 'finishEdit',
label: 'Save Edits',
icon: CheckIcon,
url: (_id) =>
`/dashboard/management/materials/info?materialId=${_id}&action=finishEdit`,
visible: (objectData) => {
return objectData?._isEditing && objectData?._isEditing == true
}
},
{
name: 'cancelEdit',
label: 'Cancel Edits',
icon: XMarkIcon,
url: (_id) =>
`/dashboard/management/materials/info?materialId=${_id}&action=cancelEdit`,
visible: (objectData) => {
return objectData?._isEditing && objectData?._isEditing == true
}
},
{ type: 'divider' },
{
name: 'delete',
label: 'Delete',
icon: BinIcon,
danger: true,
url: (_id) =>
`/dashboard/management/materials/info?materialId=${_id}&action=delete`
}
],
url: (id) => `/dashboard/management/materials/info?materialId=${id}`,
columns: ['_reference', 'name', 'tags', 'createdAt', 'updatedAt'],
filters: ['_id', 'name', 'tags'],
sorters: ['name', 'createdAt', 'updatedAt', '_id'],
group: ['tags'],
properties: [
{
name: '_id',
label: 'ID',
columnFixed: 'left',
type: 'id',
objectType: 'material',
showCopy: true
},
{
name: 'createdAt',
label: 'Created At',
type: 'dateTime',
readOnly: true
},
{
name: 'name',
label: 'Name',
columnFixed: 'left',
required: true,
type: 'text'
},
{
name: 'updatedAt',
label: 'Updated At',
type: 'dateTime',
readOnly: true
},
{
name: 'tags',
label: 'Tags',
required: false,
type: 'tags'
},
{
name: 'url',
label: 'Link',
required: false,
type: 'url'
}
]
}

View File

@ -16,6 +16,7 @@ const ProductSkuInfo = lazy(() => import('../components/Dashboard/Management/Pro
const Vendors = lazy(() => import('../components/Dashboard/Management/Vendors')) const Vendors = lazy(() => import('../components/Dashboard/Management/Vendors'))
const VendorInfo = lazy(() => import('../components/Dashboard/Management/Vendors/VendorInfo')) const VendorInfo = lazy(() => import('../components/Dashboard/Management/Vendors/VendorInfo'))
const Materials = lazy(() => import('../components/Dashboard/Management/Materials')) const Materials = lazy(() => import('../components/Dashboard/Management/Materials'))
const MaterialInfo = lazy(() => import('../components/Dashboard/Management/Materials/MaterialInfo.jsx'))
const Couriers = lazy(() => import('../components/Dashboard/Management/Couriers')) const Couriers = lazy(() => import('../components/Dashboard/Management/Couriers'))
const CourierInfo = lazy(() => import('../components/Dashboard/Management/Couriers/CourierInfo.jsx')) const CourierInfo = lazy(() => import('../components/Dashboard/Management/Couriers/CourierInfo.jsx'))
const CourierServices = lazy(() => import('../components/Dashboard/Management/CourierServices')) const CourierServices = lazy(() => import('../components/Dashboard/Management/CourierServices'))
@ -108,6 +109,11 @@ const ManagementRoutes = [
element={<FileInfo />} element={<FileInfo />}
/>, />,
<Route key='materials' path='management/materials' element={<Materials />} />, <Route key='materials' path='management/materials' element={<Materials />} />,
<Route
key='materials-info'
path='management/materials/info'
element={<MaterialInfo />}
/>,
<Route key='couriers' path='management/couriers' element={<Couriers />} />, <Route key='couriers' path='management/couriers' element={<Couriers />} />,
<Route <Route
key='couriers-info' key='couriers-info'