Skip to content

Commit

Permalink
Merge branch 'main' into 954_introduce_edit_for_departments
Browse files Browse the repository at this point in the history
  • Loading branch information
IanMayo authored Jan 23, 2024
2 parents 02a49fa + 3df9ce8 commit 0e7ed6e
Show file tree
Hide file tree
Showing 12 changed files with 114 additions and 81 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"react": "^18.2.0",
"react-admin": "4.13.1",
"react-dom": "^18.2.0",
"react-idle-timer": "^5.7.2",
"react-router-dom": "^6.9.0",
"soul-cli": "^0.6.1",
"vite": "^4.2.0",
Expand Down
17 changes: 15 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import { type AxiosError, isAxiosError } from 'axios'
import ChangePassword from './ChangePassword'
import { emitter } from './components/Layout/index'
import { CHANGE_PASSWORD_EVENT } from './constants'
import { useIdleTimer } from 'react-idle-timer'

const style = {
backgroundColor: 'white',
Expand Down Expand Up @@ -115,6 +116,18 @@ function App(): React.ReactElement {
})
const [openChangePasswordModal, setOpenChangePasswordModal] = useState(false)

const handleOnIdle = (): void => {
removeUserToken()
}
const handleOnAction = (): void => {
reset()
}
const { reset } = useIdleTimer({
timeout: 1000 * 60 * 60,
onIdle: handleOnIdle,
onActive: handleOnAction
})

const {
register,
handleSubmit,
Expand Down Expand Up @@ -192,9 +205,9 @@ function App(): React.ReactElement {
})

if (
lastUpdatedAt !== null &&
typeof lastUpdatedAt === 'string' &&
lastUpdatedAt !== '' &&
!isDateNotInPastDays(lastUpdatedAt, 1)
!isDateNotInPastDays(lastUpdatedAt, 0)
)
throw new Error(
'Password update not allowed. Please wait at least one day before updating your password again.'
Expand Down
10 changes: 9 additions & 1 deletion src/components/ProtectionRefInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ import {
useGetList,
useRecordContext,
useResourceContext,
type Identifier
type Identifier,
useRedirect
} from 'react-admin'
import { Box } from '@mui/system'
import { R_RICH_ITEMS } from '../constants'

interface Props<T, RefTable> {
reference: string
Expand Down Expand Up @@ -66,6 +68,8 @@ export default function ProtectionRefInput<
getValues,
reset
} = useFormContext()
const redirect = useRedirect()

const [valueLabel, setValueLabel] = useState<string>('')
type SelectedIdType = T['id'] | Array<T['id']>

Expand Down Expand Up @@ -163,6 +167,10 @@ export default function ProtectionRefInput<
if (record?.id) {
// onValueChange(getPreviousValue())
updateRecord(record.id as number, selectedData as number[])
.then(() => {
redirect(`/${R_RICH_ITEMS}/${record?.id}/show`)
})
.catch(console.log)
} else if (id) {
createRecord(id, selectedData as number[])
}
Expand Down
8 changes: 2 additions & 6 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export const MUTATION_MODE = 'optimistic'
// session storage value.
export const SESSION_LOGIN = 'login'


// major table/resource names
export const R_USERS = 'user'
export const R_BATCHES = 'batch'
Expand Down Expand Up @@ -110,8 +109,6 @@ export const ITEM_SAVE = 'item_save'

export const CHANGE_PASSWORD_EVENT = 'change_password'



export const cosmeticLabels = {
[R_USERS]: 'User',
[R_ITEMS]: 'Item',
Expand All @@ -127,6 +124,5 @@ export const cosmeticLabels = {
[R_CAT_CODE]: 'Cat Code',
[R_CAT_HANDLE]: 'Cat Handle',
[R_DEPARTMENT]: 'Department',
[R_PROTECTIVE_MARKING]: 'Protective Marking',

}
[R_PROTECTIVE_MARKING]: 'Protective Marking'
}
70 changes: 38 additions & 32 deletions src/hooks/useRefTable.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import {
useCreate,
useDataProvider,
// useDeleteMany,
useRedirect
} from 'react-admin'
import { R_ITEMS } from '../constants'
import { useCreate, useDataProvider, useRedirect } from 'react-admin'
import * as constants from '../constants'

interface DBMethods {
createRecord: (id: number, data?: number[]) => void
updateRecord: (id: number, data?: number[]) => void
updateRecord: (id: number, data?: number[]) => Promise<unknown>
}

export default function useRefTable(
Expand All @@ -17,32 +12,43 @@ export default function useRefTable(
resource: string
): DBMethods {
const [create] = useCreate()
// const [deleteMany] = useDeleteMany()
const redirect = useRedirect()
const dataProvider = useDataProvider()
const redirect = useRedirect()

const updateRecord = (id: number, data?: number[]): void => {
dataProvider
.getList(refTable, {
pagination: { page: 1, perPage: 100 },
sort: { field: 'id', order: 'ASC' },
filter: { [resource]: id }
})
.then(({ data: tableData = [] }) => {
const idsToDelete = tableData.map(
(item: Record<string, any>) => item.id
)

if (idsToDelete.length > 0)
{dataProvider.deleteMany(refTable, { ids: idsToDelete })
.then(() => {
const updateRecord = async (
id: number,
data?: number[]
): Promise<unknown> => {
return await new Promise((resolve, reject): void => {
dataProvider
.getList(refTable, {
pagination: { page: 1, perPage: 100 },
sort: { field: 'id', order: 'ASC' },
filter: { [resource]: id }
})
.then(({ data: tableData = [] }) => {
const idsToDelete = tableData.map(
(item: Record<string, any>) => item.id
)
if (idsToDelete.length > 0) {
dataProvider
.deleteMany(refTable, { ids: idsToDelete })
.then(() => {
createRecord(id, data)
resolve(null)
})
.catch((err) => {
reject(err)
})
} else {
createRecord(id, data)
})
.catch(console.log)
}
else createRecord(id, data)
})
.catch(console.log)
resolve(null)
}
})
.catch((err) => {
reject(err)
})
})
}

const createRecord = (id: number, data?: number[]): void => {
Expand All @@ -55,7 +61,7 @@ export default function useRefTable(
}
})
})
if (resource !== R_ITEMS) redirect(`/${resource}`)
if (resource !== constants.R_ITEMS) redirect(`/${resource}`)
} catch (error: any) {
console.log(error)
}
Expand Down
2 changes: 1 addition & 1 deletion src/providers/authProvider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const getCookie = (name: string): string | null => {

const setToken = (token: string): void => {
const date = new Date()
date.setTime(date.getTime() + 1 * 60 * 60 * 1000)
date.setTime(date.getTime() + 24 * 60 * 60 * 1000)
const expires = date.toUTCString()
document.cookie = `${constants.TOKEN_KEY}=${token}; expires=${expires}; path=/ `
}
Expand Down
3 changes: 2 additions & 1 deletion src/providers/authProvider/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const basePermissions = {
[constants.R_BATCHES]: { read: true, write: true, delete: false },
[constants.R_ITEMS]: { read: true, write: true, delete: false },
[constants.R_ALL_ITEMS]: { read: true, write: true, delete: false },
[constants.R_USERS]: { read: true, write: true, delete: false },
[constants.R_USERS]: { read: true, write: false, delete: false },
[constants.R_PLATFORMS]: { read: true, write: false, delete: false },
[constants.R_VAULT_LOCATION]: { read: true, write: false, delete: false },
[constants.R_ADDRESSES]: { read: true, write: true, delete: false },
Expand All @@ -20,6 +20,7 @@ const permissions: Record<UserRole, ResourcePermissions> = {
'rco-power-user': {
...basePermissions,
[constants.R_PLATFORMS]: { read: true, write: true, delete: false },
[constants.R_USERS]: { read: true, write: true, delete: false },
[constants.R_VAULT_LOCATION]: { read: true, write: true, delete: false },
'reference-data': { read: true, write: true, delete: false }
}
Expand Down
42 changes: 24 additions & 18 deletions src/providers/dataProvider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ export const getDataProvider = async (
const operators = ['_neq', '_eq', '_lte', '_gte']
const SEARCH_OPERATOR = 'q'
const nullOperators = ['__null', '__notnull']
const bridgingTables = [
constants.R_ITEMS_CODE,
constants.R_ITEMS_CAVE,
constants.R_ITEMS_HANDLE
]

export const dataProvider = (apiUrl: string): DataProvider => ({
getList: async (resource: string, params: any) => {
Expand Down Expand Up @@ -325,25 +330,26 @@ export const dataProvider = (apiUrl: string): DataProvider => ({
})
},

// Note: Deletion is not supported
delete: async (_resource: string, _params: any) => {
throw new Error('Deletion is not supported!')
// const url = `${apiUrl}/${resource}/rows/${params.id}`

// return await axios.delete(url).then(() => {
// return { data: params.id }
// })
// Note: Deletion is not supported (except for bridging tables)
delete: async (resource: string, params: any) => {
if (bridgingTables.includes(resource)) {
const url = `${apiUrl}/${resource}/rows/${params.id}`
return await axios.delete(url).then(() => ({ data: params.id }))
} else {
throw new Error('Deletion is not supported!')
}
},

// Note: Deletion is not supported
deleteMany: async (_resource: string, _params: any) => {
throw new Error('Deletion is not supported!')

// const ids = params.ids.toString()
// const url = `${apiUrl}/${resource}/rows/${ids}`

// return await axios.delete(url).then(() => {
// return { data: params.ids }
// })
// Note: Deletion is not supported (except for bridging tables)
deleteMany: async (resource: string, params: any) => {
if (bridgingTables.includes(resource)) {
const ids = params.ids.toString()
const url = `${apiUrl}/${resource}/rows/${ids}`
return await axios.delete(url).then(() => {
return { data: params.ids }
})
} else {
throw new Error('Deletion is not supported!')
}
}
})
2 changes: 1 addition & 1 deletion src/resources/dispatch/DispatchForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export default function DispatchForm(props: Props): React.ReactElement {
inputProps={{
helperText: (
<>
View{' '}
Manage{' '}
<span style={{ textDecoration: 'underline' }}>
<Link to={{ pathname: '/address' }}>Addresses</Link>
</span>
Expand Down
3 changes: 1 addition & 2 deletions src/resources/items/ItemForm/ItemFormToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,10 @@ interface ActionsProps {

const Actions = (props: ActionsProps): React.ReactElement => {
const { onSuccess, setOpenRemarks, vLocationAudits } = props
const redirect = useRedirect()

const onSuccessWithRemarksClose = (data: any): void => {
onSuccess(data)
setOpenRemarks(false)
redirect(`/${constants.R_RICH_ITEMS}/${data?.id}/show`)
}

return (
Expand Down
32 changes: 15 additions & 17 deletions src/resources/users/UserShow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -375,23 +375,21 @@ export default function UserShow(): React.ReactElement {
<Show
resource={constants.R_USERS}
actions={
hasWriteAccess && (
<TopToolbar sx={{ alignItems: 'center' }}>
<EditButton />
<HistoryButton
onClick={() => {
if (record) {
navigate(
`/audit?filter=${JSON.stringify({
resource: constants.R_USERS,
dataId: record.id ?? ''
})}`
)
}
}}
/>
</TopToolbar>
)
<TopToolbar sx={{ alignItems: 'center' }}>
{hasWriteAccess && <EditButton />}
<HistoryButton
onClick={() => {
if (record) {
navigate(
`/audit?filter=${JSON.stringify({
resource: constants.R_USERS,
dataId: record.id ?? ''
})}`
)
}
}}
/>
</TopToolbar>
}>
<UserShowComp setRecord={setRecord} audit={audit} />
</Show>
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6705,6 +6705,11 @@ react-hook-form@^7.43.9:
resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.45.4.tgz#73d228b704026ae95d7e5f7b207a681b173ec62a"
integrity sha512-HGDV1JOOBPZj10LB3+OZgfDBTn+IeEsNOKiq/cxbQAIbKaiJUe/KV8DBUzsx0Gx/7IG/orWqRRm736JwOfUSWQ==

react-idle-timer@^5.7.2:
version "5.7.2"
resolved "https://registry.yarnpkg.com/react-idle-timer/-/react-idle-timer-5.7.2.tgz#f506db28a86645dd1b87987116501703e512142b"
integrity sha512-+BaPfc7XEUU5JFkwZCx6fO1bLVK+RBlFH+iY4X34urvIzZiZINP6v2orePx3E6pAztJGE7t4DzvL7if2SL/0GQ==

react-is@^16.13.1, react-is@^16.7.0:
version "16.13.1"
resolved "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz"
Expand Down

0 comments on commit 0e7ed6e

Please sign in to comment.