-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsendInvitations.tsx
More file actions
262 lines (238 loc) · 7.97 KB
/
sendInvitations.tsx
File metadata and controls
262 lines (238 loc) · 7.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
'use client'
import * as Yup from 'yup'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { ErrorMessage, Field, Form, Formik } from 'formik'
import { MailIcon, PlusIcon, SendIcon } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import {
RoleI,
SendInvitationModalProps,
} from '../interfaces/invitation-interface'
import { AlertComponent } from '@/components/AlertComponent'
import { AxiosResponse } from 'axios'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { apiStatusCodes } from '@/config/CommonConstant'
import { createInvitations } from '@/app/api/Invitation'
import delSvg from '@/../public/svgs/del.svg'
import { getOrganizationRoles } from '@/app/api/organization'
import { useAppSelector } from '@/lib/hooks'
interface Invitation {
email: string
role: string
roleId: string
}
const validationSchema = Yup.object({
email: Yup.string()
.email('Email is invalid')
.required('Email is required')
.matches(
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
'Email is invalid',
)
.required('Email is required')
.trim(),
})
export default function SendInvitationModal({
getAllSentInvitations,
openModal,
setMessage,
setOpenModal,
}: SendInvitationModalProps): React.JSX.Element {
const [loading, setLoading] = useState<boolean>(false)
const [selfEmail, setSelfEmail] = useState<string>('')
const [invitations, setInvitations] = useState<Invitation[]>([])
const [memberRole, setMemberRole] = useState<RoleI | null>(null)
const [errorMsg, setErrorMsg] = useState<string | null>(null)
const selectedOrgId = useAppSelector((state) => state.organization.orgId)
const userProfileDetails = useAppSelector((state) => state.user.userInfo)
const getRoles = async (): Promise<void> => {
try {
const resRoles = await getOrganizationRoles(selectedOrgId)
const { data } = resRoles as AxiosResponse
if (data?.statusCode === apiStatusCodes.API_STATUS_SUCCESS) {
const roles: RoleI[] = data?.data
const memberRole = roles.find((role) => role.name === 'member')
setMemberRole(memberRole as RoleI)
} else {
setErrorMsg(resRoles as string)
}
} catch (error) {
console.error('Failed to fetch roles', error)
setErrorMsg('Failed to fetch roles')
}
}
useEffect(() => {
const getEmail = async (): Promise<void> => {
const email = userProfileDetails?.email
setSelfEmail(email)
}
if (openModal) {
setInvitations([])
getRoles()
getEmail()
}
}, [openModal, userProfileDetails?.email])
const includeInvitation = async (email: string): Promise<void> => {
setInvitations([
...invitations,
{
email,
role: memberRole?.name as string,
roleId: String(memberRole?.id),
},
])
}
const removeInvitation = (email: string): void => {
const invitationList = invitations.filter((item) => email !== item.email)
setInvitations(invitationList)
}
const sendInvitations = async (): Promise<void> => {
setLoading(true)
try {
const invitationPayload = invitations.map((invitation) => ({
email: invitation.email,
orgRoleId: [invitation.roleId],
}))
const resCreateOrg = await createInvitations(
selectedOrgId,
invitationPayload,
)
const { data } = resCreateOrg as AxiosResponse
if (data?.statusCode === apiStatusCodes.API_STATUS_CREATED) {
setMessage(data?.message)
setOpenModal(false)
if (getAllSentInvitations) {
getAllSentInvitations()
}
} else {
setErrorMsg(resCreateOrg as string)
}
} catch (error) {
console.error('Failed to send invitations', error)
setErrorMsg('Failed to send invitations')
} finally {
setLoading(false)
}
}
const validateAndAddEmail = (values: { email: string }): void => {
if (values.email.trim() === selfEmail.trim()) {
setErrorMsg('You can not send invitation to yourself')
return
}
if (invitations.some((inv) => inv.email === values.email)) {
setErrorMsg('This email has already been added')
return
}
includeInvitation(values.email)
}
return (
<Dialog open={openModal} onOpenChange={setOpenModal}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Send Invitation(s)</DialogTitle>
</DialogHeader>
{errorMsg && (
<AlertComponent
message={errorMsg}
type="failure"
onAlertClose={() => setErrorMsg(null)}
/>
)}
<Formik
initialValues={{ email: '' }}
validationSchema={validationSchema}
onSubmit={(values, formikHandlers) => {
formikHandlers.resetForm()
validateAndAddEmail(values)
}}
>
{({ errors, touched }) => (
<Form className="space-y-2">
<div className="flex items-end gap-4">
<div className="flex flex-1 items-end gap-4">
<div className="grow">
<label htmlFor="email" className="text-sm font-medium">
Email <span className="text-destructive">*</span>
</label>
<Field
as={Input}
id="email"
name="email"
placeholder="example@email.com"
className={`bg-background placeholder:text-muted-foreground/50 focus-visible:ring-1 ${
errors.email && touched.email
? 'border-destructive'
: ''
}`}
/>
</div>
<Button type="submit" className="flex items-center gap-2">
<PlusIcon className="h-5 w-5" />
Add
</Button>
</div>
</div>
<ErrorMessage
name="email"
component="div"
className="text-destructive mt-1 text-sm"
/>
<div className="flex justify-end">
<Button
onClick={sendInvitations}
disabled={loading || !(invitations.length > 0)}
className="flex items-center gap-2"
>
<SendIcon className="h-5 w-5" />
Send
</Button>
</div>
</Form>
)}
</Formik>
{invitations.length > 0 && (
<div className="mt-4 space-y-2">
<div className="divide-y rounded-lg border">
{invitations.map((invitation) => (
<div
key={invitation.email}
className="flex items-center justify-between p-3"
>
<div className="flex gap-3">
<div className="flex items-center justify-center">
<MailIcon className="text-muted-foreground h-9 w-9" />
</div>
<div>
<p className="font-medium">{invitation.email}</p>
<p className="text-muted-foreground text-sm">
Role: Member
</p>
</div>
</div>
<Button
variant="ghost"
size="icon"
className='hover:bg-transparent'
onClick={() => removeInvitation(invitation.email)}
>
<img
src={delSvg.src}
alt="delete"
className="mx-auto h-5 w-5"
/>
</Button>
</div>
))}
</div>
</div>
)}
</DialogContent>
</Dialog>
)
}