@campxdev/shared 1.8.22 → 1.8.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@campxdev/shared",
3
- "version": "1.8.22",
3
+ "version": "1.8.24",
4
4
  "main": "./exports.ts",
5
5
  "scripts": {
6
6
  "start": "react-scripts start",
@@ -0,0 +1,325 @@
1
+ import {
2
+ Avatar,
3
+ Box,
4
+ Button,
5
+ CircularProgress,
6
+ InputAdornment,
7
+ Typography,
8
+ styled,
9
+ } from '@mui/material'
10
+ import { useState } from 'react'
11
+ import { useMutation, useQuery } from 'react-query'
12
+ import { toast } from 'react-toastify'
13
+ import { useImmer } from 'use-immer'
14
+ import UserProfileRelation from './UserProfileRelation'
15
+ import {
16
+ defaultFilterObj,
17
+ fetchApplicationUsers,
18
+ fetchProfiles,
19
+ removeUserApplicationProfile,
20
+ updateUserApplicationProfile,
21
+ } from './Service'
22
+ import useConfirm from '../PopupConfirm/useConfirm'
23
+ import Spinner from '../Spinner'
24
+ import PageHeader from '../PageHeader'
25
+ import { PageContent } from '../PageContent'
26
+
27
+ import { SingleSelect } from '../Input'
28
+ import ActionButton from '../ActionButton'
29
+ import { axiosErrorToast } from '../../config/axios'
30
+ import { DialogButton } from '../ModalButtons'
31
+ import SearchBar from '../FilterComponents/SearchBar'
32
+ import Table from '../Tables/BasicTable/Table'
33
+ import { ValidateAccess } from '../../permissions'
34
+ import { Permission } from '../../shared-state'
35
+
36
+ interface ApplicationProfileProps {
37
+ application: 'exams' | 'square' | 'payments' | 'enroll_x'
38
+ title: string
39
+ permissions?: {
40
+ add: string
41
+ edit: string
42
+ view: string
43
+ delete: string
44
+ }
45
+ }
46
+ function ApplicationProfile({
47
+ application = 'exams',
48
+ title,
49
+ permissions,
50
+ }: ApplicationProfileProps) {
51
+ const { isConfirmed } = useConfirm()
52
+ const [filters, setFilters] = useImmer(defaultFilterObj)
53
+ const { data, isLoading, refetch } = useQuery(
54
+ ['application-users', ...Object.keys(filters)?.map((key) => filters[key])],
55
+ () => fetchApplicationUsers({ application, ...filters }),
56
+ )
57
+
58
+ const { data: profiles, isLoading: profilesLoading } = useQuery(
59
+ 'profiles',
60
+ () => fetchProfiles({ application }),
61
+ )
62
+
63
+ const { mutate, isLoading: removingUserProfile } = useMutation(
64
+ removeUserApplicationProfile,
65
+ {
66
+ onSuccess: (res) => {
67
+ refetch()
68
+ toast.success('User profile removed from application')
69
+ },
70
+ },
71
+ )
72
+
73
+ const handleRemove = async (data) => {
74
+ const confirmed = await isConfirmed(
75
+ 'Are you sure you want to remove the user profile?',
76
+ )
77
+ if (!confirmed) return
78
+ mutate({ userId: data.id, application: application })
79
+ }
80
+ const columns = [
81
+ {
82
+ title: 'User',
83
+ key: '',
84
+ dataIndex: '',
85
+ render: (_, row) => <UserComponent userData={row} />,
86
+ },
87
+ {
88
+ title: 'Profile',
89
+ key: '',
90
+ dataIndex: '',
91
+ render: (_, row) => (
92
+ <RenderProfileDropDown
93
+ profiles={profiles?.profiles}
94
+ data={row}
95
+ application={application}
96
+ refetchFn={refetch}
97
+ permissions={permissions}
98
+ />
99
+ ),
100
+ },
101
+ {
102
+ title: 'Actions',
103
+ key: '',
104
+ dataIndex: '',
105
+ render: (_, row) => (
106
+ <ValidateAccess
107
+ accessKey={permissions ? Permission[permissions.delete] : 1}
108
+ >
109
+ <Button
110
+ variant="text"
111
+ onClick={() => handleRemove(row)}
112
+ sx={{ padding: '0px', margin: '0px' }}
113
+ >
114
+ Remove
115
+ </Button>
116
+ </ValidateAccess>
117
+ ),
118
+ },
119
+ ]
120
+ const handleLimitChange = (value: number) => {
121
+ setFilters((s) => {
122
+ s.limit = value
123
+ s.offset = 0
124
+ })
125
+ }
126
+
127
+ const handlePagination = (value: number) => {
128
+ setFilters((s) => {
129
+ s.offset = value * s.limit - s.limit
130
+ })
131
+ }
132
+ if (profilesLoading) {
133
+ return <Spinner />
134
+ }
135
+ return (
136
+ <>
137
+ <PageHeader
138
+ title={title}
139
+ actions={[
140
+ <ValidateAccess
141
+ key={0}
142
+ accessKey={permissions ? Permissions[permissions.add] : 1}
143
+ >
144
+ <DialogButton
145
+ key={0}
146
+ title={'Add User Profile Relation'}
147
+ anchor={({ open }) => (
148
+ <ActionButton onClick={open}>
149
+ Add User Profile Relation
150
+ </ActionButton>
151
+ )}
152
+ content={({ close }) => (
153
+ <UserProfileRelation
154
+ close={close}
155
+ application={application}
156
+ profiles={profiles?.profiles}
157
+ />
158
+ )}
159
+ />
160
+ </ValidateAccess>,
161
+ ]}
162
+ />
163
+ <PageContent sx={{ marginTop: '25px' }}>
164
+ <StyledTableContainer>
165
+ <SearchBar
166
+ onSearch={(value) => {
167
+ setFilters((s) => {
168
+ s.search = value
169
+ })
170
+ }}
171
+ textFieldProps={{
172
+ placeholder: 'Search by Name',
173
+ title: 'Search by Name',
174
+ sx: { width: '300px', marginBottom: '25px' },
175
+ size: 'small',
176
+ }}
177
+ />
178
+ <Table
179
+ columns={columns}
180
+ dataSource={data?.users ?? []}
181
+ loading={isLoading || removingUserProfile}
182
+ pagination={{
183
+ limit: filters.limit,
184
+ onChangeLimit: handleLimitChange,
185
+ onChange: handlePagination,
186
+ totalCount: data?.count,
187
+ page: filters.offset / filters.limit,
188
+ }}
189
+ />
190
+ </StyledTableContainer>
191
+ </PageContent>
192
+ </>
193
+ )
194
+ }
195
+ export default ApplicationProfile
196
+
197
+ export const RenderProfileDropDown = ({
198
+ profiles,
199
+ data,
200
+ refetchFn,
201
+ application,
202
+ permissions,
203
+ }) => {
204
+ const CanEdit = permissions ? Permissions[permissions.edit] : 1
205
+ const [state, setState] = useState({
206
+ userId: data.id,
207
+ profileId: data.profiles[0].id,
208
+ })
209
+
210
+ const { mutate, isLoading } = useMutation(updateUserApplicationProfile, {
211
+ onSuccess: (res) => {
212
+ refetchFn()
213
+ toast.success('User application profile updated successfully')
214
+ },
215
+ onError: (err) => {
216
+ // eslint-disable-next-line no-console
217
+ console.log(err)
218
+ axiosErrorToast(err)
219
+ },
220
+ })
221
+ const handleChange = (e) => {
222
+ setState({
223
+ userId: data.id,
224
+ profileId: e.target.value,
225
+ })
226
+ mutate({
227
+ userId: state.userId,
228
+ profileIds: [e.target.value],
229
+ application: application,
230
+ })
231
+ }
232
+ return (
233
+ <>
234
+ <StyledDropDownContainer>
235
+ <SingleSelect
236
+ label={'Profile'}
237
+ name={'profile'}
238
+ value={state?.profileId}
239
+ onChange={(e) => {
240
+ handleChange(e)
241
+ }}
242
+ disabled={!CanEdit}
243
+ endAdornment={
244
+ isLoading && (
245
+ <InputAdornment position="end">
246
+ <CircularProgress
247
+ size={20}
248
+ color={'secondary'}
249
+ sx={{ marginRight: '10px' }}
250
+ />
251
+ </InputAdornment>
252
+ )
253
+ }
254
+ options={
255
+ profiles?.map((profile) => ({
256
+ label: profile.name,
257
+ value: profile.id,
258
+ })) ?? []
259
+ }
260
+ />
261
+ </StyledDropDownContainer>
262
+ </>
263
+ )
264
+ }
265
+
266
+ export const UserComponent = ({ userData }) => {
267
+ return (
268
+ <>
269
+ <Box
270
+ sx={{
271
+ width: '100%',
272
+ display: 'flex',
273
+ gap: '10px',
274
+ alignItems: 'center',
275
+ justifyContent: 'flex-start',
276
+ }}
277
+ >
278
+ <Avatar alt={userData?.fullName} />
279
+ <Typography variant="subtitle1">{userData?.fullName}</Typography>
280
+ </Box>
281
+ </>
282
+ )
283
+ }
284
+ export const StyledTableContainer = styled(Box)(({ theme }) => ({
285
+ width: '70%',
286
+ margin: 'auto',
287
+ '& .MuiTableHead-root': {
288
+ border: '1px solid white',
289
+ borderBottom: theme.borders.grayLight,
290
+ borderWidth: '2px',
291
+
292
+ backgroundColor: 'white',
293
+ '& th': {
294
+ textAlign: 'left',
295
+ padding: '5px',
296
+ },
297
+ '& .MuiBox-root': {
298
+ color: '#121212b3',
299
+ fontSize: '164x',
300
+ },
301
+ },
302
+ '& tbody': {
303
+ border: '1px solid white',
304
+ borderBottom: theme.borders.grayLight,
305
+ borderWidth: '2px',
306
+ '& tr': {
307
+ border: '1px solid white',
308
+ },
309
+ },
310
+ '& td': {
311
+ textAlign: 'center',
312
+ border: '1px solid white',
313
+ padding: '15px 0px',
314
+ },
315
+ }))
316
+
317
+ export const StyledDropDownContainer = styled(Box)(({ theme }) => ({
318
+ width: '200px',
319
+ '& .MuiTypography-root': {
320
+ display: 'none',
321
+ },
322
+ '& .MuiInputBase-root': {
323
+ backgroundColor: '#f5f6f8',
324
+ },
325
+ }))
@@ -0,0 +1,68 @@
1
+ import * as yup from 'yup'
2
+ import axios from '../../config/axios'
3
+ export const defaultFilterObj = {
4
+ search: null,
5
+ limit: 10,
6
+ offset: 0,
7
+ }
8
+
9
+ export const userProfileSchema = yup.object().shape({
10
+ userId: yup
11
+ .object()
12
+ .shape({
13
+ label: yup.string().required('User is required'),
14
+ value: yup.string().required('User is required'),
15
+ })
16
+ .required('User is required'),
17
+ profileIds: yup.string().required('Profile is required'),
18
+ })
19
+ export const fetchUsers = (params) => {
20
+ return axios
21
+ .get(`/square/profile-permissions/new-users`, {
22
+ params: params,
23
+ })
24
+ .then((res) => res.data)
25
+ }
26
+
27
+ export const fetchApplicationUsers = (params) => {
28
+ return axios
29
+ .get(`/square/profile-permissions/application-users`, {
30
+ params: params,
31
+ })
32
+ .then((res) => res.data)
33
+ }
34
+
35
+ export const fetchProfiles = (application) => {
36
+ return axios
37
+ .get(`/square/profiles`, {
38
+ params: application,
39
+ })
40
+ .then((res) => res.data)
41
+ }
42
+
43
+ interface ApplicationUserProfile {
44
+ application: string
45
+ userId: number
46
+ profileIds: number[]
47
+ }
48
+ export const createApplicationUserProfile = (
49
+ postBody: ApplicationUserProfile,
50
+ ) => {
51
+ return axios
52
+ .post(`/square/profile-permissions/add-user`, postBody)
53
+ .then((res) => res.data)
54
+ }
55
+
56
+ export const removeUserApplicationProfile = (postBody) => {
57
+ return axios
58
+ .post(`/square/profile-permissions/remove-user`, postBody)
59
+ .then((res) => res.data)
60
+ }
61
+
62
+ export const updateUserApplicationProfile = (
63
+ postBody: ApplicationUserProfile,
64
+ ) => {
65
+ return axios
66
+ .put(`/square/profile-permissions/edit-user-permissions`, postBody)
67
+ .then((res) => res.data)
68
+ }
@@ -0,0 +1,174 @@
1
+ import { yupResolver } from '@hookform/resolvers/yup'
2
+ import {
3
+ Autocomplete,
4
+ CircularProgress,
5
+ Popper,
6
+ Stack,
7
+ styled,
8
+ } from '@mui/material'
9
+ import { useState } from 'react'
10
+ import { Controller, useForm } from 'react-hook-form'
11
+ import { useMutation, useQueryClient } from 'react-query'
12
+ import { toast } from 'react-toastify'
13
+ import {
14
+ createApplicationUserProfile,
15
+ fetchUsers,
16
+ userProfileSchema,
17
+ } from './Service'
18
+ import { useImmer } from 'use-immer'
19
+ import { axiosErrorToast } from '../../config/axios'
20
+ import { FormMultiSelect, FormSingleSelect } from '../HookForm'
21
+ import ActionButton from '../ActionButton'
22
+ interface UserProps {
23
+ options: {
24
+ label: any
25
+ value: any
26
+ }[]
27
+ inputValue: string
28
+ }
29
+ function UserProfileRelation({ close, application, profiles }) {
30
+ const [state, setState] = useImmer<UserProps>({
31
+ options: [],
32
+ inputValue: '',
33
+ })
34
+ const queryClient = useQueryClient()
35
+
36
+ const { control, handleSubmit, formState } = useForm({
37
+ defaultValues: {},
38
+ resolver: yupResolver(userProfileSchema),
39
+ })
40
+
41
+ const { mutate, isLoading: creatingUserProfile } = useMutation(
42
+ createApplicationUserProfile,
43
+ {
44
+ onSuccess: (res) => {
45
+ queryClient.invalidateQueries(`application-users`)
46
+ toast.success('User profile added to application successfully')
47
+ close()
48
+ },
49
+ onError: (err) => {
50
+ // eslint-disable-next-line no-console
51
+ console.log(err)
52
+ axiosErrorToast(err)
53
+ },
54
+ },
55
+ )
56
+
57
+ const { mutate: fetchUsersFn, isLoading: gettingUsers } = useMutation(
58
+ fetchUsers,
59
+ {
60
+ onSuccess: (res) => {
61
+ setState((s) => {
62
+ s.options = res.users?.map((item) => ({
63
+ label: item.fullName,
64
+ value: item.id,
65
+ }))
66
+ })
67
+ },
68
+ },
69
+ )
70
+ const onSubmit = (formData) => {
71
+ mutate({
72
+ application: application,
73
+ profileIds: [+formData.profileIds],
74
+ userId: +formData.userId?.value,
75
+ })
76
+ }
77
+ const onError = (err) => {
78
+ // eslint-disable-next-line no-console
79
+ console.log(err)
80
+ }
81
+
82
+ const handleInputChange = (e) => {
83
+ if (e) {
84
+ setState((s) => {
85
+ s.inputValue = e.target.value
86
+ })
87
+ if (e.target.value.length > 3) {
88
+ fetchUsersFn({
89
+ application: application,
90
+ search: e.target.value,
91
+ })
92
+ }
93
+ }
94
+ }
95
+
96
+ return (
97
+ <>
98
+ <form onSubmit={handleSubmit(onSubmit, onError)}>
99
+ <Stack gap={4} sx={{ padding: '10px' }}>
100
+ <FormMultiSelect
101
+ multiple={false}
102
+ label={'User'}
103
+ name={'userId'}
104
+ onInputChange={handleInputChange}
105
+ loading={gettingUsers}
106
+ control={control}
107
+ options={state.options ?? []}
108
+ required
109
+ />
110
+
111
+ <FormSingleSelect
112
+ label={'Profile'}
113
+ name={'profileIds'}
114
+ control={control}
115
+ options={
116
+ profiles?.map((profile) => ({
117
+ label: profile.name,
118
+ value: profile.id,
119
+ })) ?? []
120
+ }
121
+ required
122
+ />
123
+ <Stack gap={2} direction={'row'} sx={{ justifyContent: 'flex-end' }}>
124
+ <ActionButton variant="outlined" onClick={close}>
125
+ Cancel
126
+ </ActionButton>
127
+ <ActionButton type="submit" loading={creatingUserProfile}>
128
+ Confirm
129
+ </ActionButton>
130
+ </Stack>
131
+ </Stack>
132
+ </form>
133
+ </>
134
+ )
135
+ }
136
+ export default UserProfileRelation
137
+
138
+ const StyledPopper = styled(Popper)(({ theme }) => ({
139
+ '& .MuiPaper-root': {
140
+ borderRadius: '10px',
141
+ borderTopRightRadius: 0,
142
+ borderTopLeftRadius: 0,
143
+ boxShadow: '0px 4px 16px #0000000F',
144
+ marginTop: '1px',
145
+ '& .MuiAutocomplete-listbox': {
146
+ minWidth: '240px',
147
+ padding: '10px',
148
+ '& .MuiAutocomplete-option': {
149
+ padding: '10px',
150
+ background: 'none',
151
+ '&.Mui-focused': {
152
+ background: 'none',
153
+ },
154
+ },
155
+ '& .MuiCheckbox-root': {
156
+ padding: 0,
157
+ marginRight: '10px',
158
+ },
159
+ },
160
+ '&::-webkit-scrollbar': {
161
+ width: '0.5em',
162
+ height: '0.5em',
163
+ },
164
+
165
+ '&::-webkit-scrollbar-thumb': {
166
+ backgroundColor: 'rgba(0, 0, 0, 0.15)',
167
+ borderRadius: '3px',
168
+
169
+ '&:hover': {
170
+ background: 'rgba(0, 0, 0, 0.2)',
171
+ },
172
+ },
173
+ },
174
+ }))
@@ -0,0 +1 @@
1
+ export { default } from "./ApplicationProfile";
@@ -2,6 +2,7 @@ import { ReactNode } from 'react'
2
2
  import { Controller } from 'react-hook-form'
3
3
  import { MultiSelect } from '../Input'
4
4
  import { IOption } from '../Input/types'
5
+ import { AutocompleteInputChangeReason } from '@mui/material'
5
6
 
6
7
  interface MultiSelectProps {
7
8
  control: any
@@ -10,6 +11,11 @@ interface MultiSelectProps {
10
11
  options: IOption[]
11
12
  placeholder?: string
12
13
  loading?: boolean
14
+ onInputChange?: (
15
+ event: React.SyntheticEvent,
16
+ value: string,
17
+ reason: AutocompleteInputChangeReason,
18
+ ) => void
13
19
  required?: boolean
14
20
  value?: IOption[] | IOption
15
21
  onChange?: (value: IOption[] | IOption) => void
@@ -24,6 +30,7 @@ export default function FormMultiSelect({
24
30
  loading,
25
31
  required,
26
32
  multiple = true,
33
+ onInputChange,
27
34
  ...props
28
35
  }: MultiSelectProps) {
29
36
  return (
@@ -39,6 +46,7 @@ export default function FormMultiSelect({
39
46
  onChange={(value) => {
40
47
  field.onChange(value)
41
48
  }}
49
+ onInputChange={onInputChange}
42
50
  loading={loading}
43
51
  options={options || []}
44
52
  error={!!error}
@@ -2,6 +2,7 @@ import { Close, KeyboardArrowDown } from '@mui/icons-material'
2
2
  import {
3
3
  alpha,
4
4
  Autocomplete,
5
+ AutocompleteInputChangeReason,
5
6
  Checkbox,
6
7
  CircularProgress,
7
8
  Popper,
@@ -76,6 +77,11 @@ interface MultiSelectProps {
76
77
  loading?: boolean
77
78
  value: IOption[] | IOption
78
79
  onChange: (value: IOption[] | IOption) => void
80
+ onInputChange?: (
81
+ event: React.SyntheticEvent,
82
+ value: string,
83
+ reason: AutocompleteInputChangeReason,
84
+ ) => void
79
85
  required?: boolean
80
86
  error?: boolean
81
87
  helperText?: string
@@ -90,6 +96,7 @@ export default function MultiSelect({
90
96
  loading,
91
97
  value,
92
98
  onChange,
99
+ onInputChange,
93
100
  required,
94
101
  error,
95
102
  helperText,
@@ -109,6 +116,7 @@ export default function MultiSelect({
109
116
  if (!onChange) return
110
117
  onChange(value)
111
118
  }}
119
+ onInputChange={onInputChange}
112
120
  limitTags={limitTags}
113
121
  isOptionEqualToValue={(option: any, value: any) =>
114
122
  option?.value === value?.value
@@ -58,7 +58,7 @@ export { default as ReactTable } from './Tables/ReactTable'
58
58
  export { default as TableFooter } from './Tables/BasicTable/TableFooter'
59
59
  export { default as DropDownButton } from './DropDownButton'
60
60
  export { default as useConfirm } from './PopupConfirm/useConfirm'
61
-
61
+ export { default } from './ApplicationProfile'
62
62
  export {
63
63
  UploadFileDialog,
64
64
  Chips,