-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathAddProjectPopup.jsx
More file actions
241 lines (214 loc) · 8.04 KB
/
AddProjectPopup.jsx
File metadata and controls
241 lines (214 loc) · 8.04 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
import React, { useEffect, useMemo, useState } from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Alert, Input } from 'reactstrap';
import AddProjectsAutoComplete from './AddProjectsAutoComplete';
import { boxStyle, boxStyleDark } from '~/styles';
import '../../Header/DarkMode.css';
import { toast } from 'react-toastify';
import axios from 'axios';
import { ENDPOINTS } from '~/utils/URL';
import { useDispatch } from 'react-redux';
import { assignProject } from '~/actions/projectMembers';
const createUserProjectMembership = async (userId, projectId) => {
// If your ENDPOINTS key is named differently, use that one.
// Typical: POST /userProjects body: { userId, projectId, isActive }
return axios.post(ENDPOINTS.USER_PROJECTS, {
userId,
projectId,
isActive: true,
});
};
/*const AddProjectPopup = React.memo(function AddProjectPopup(props) {
const {
open,
onClose,
userId,
darkMode,
// projects already in DB (for autocomplete / create-new check)
projects = [],
// projects already assigned to this user (to block duplicates)
userProjects = [],
// optional: parent callback to update its local table immediately
onSelectAssignProject, // (project) => void
} = props;
const safeProjects = Array.isArray(projects) ? projects : [];
const safeUserProjects = Array.isArray(userProjects) ? userProjects : [];
// set data from props
useEffect(() => {
setAllProjects(safeProjects);
const categories = Array.from(
new Set(safeProjects.map(p => p?.category).filter(Boolean))
);
setCategoryOptions(categories.length ? categories : ['Unspecified']);
}, [projects]);*/
// eslint-disable-next-line react/display-name
const AddProjectPopup = React.memo(props => {
const { darkMode, projects = [], onClose } = props;
const dispatch = useDispatch();
// ---------- local state ----------
const [selectedProject, setSelectedProject] = useState(null);
const [isValidProject, setIsValidProject] = useState(true);
const [showDoesNotExistAlert, setShowDoesNotExistAlert] = useState(false);
const [categoryOptions, setCategoryOptions] = useState([]);
const [creatingNew, setCreatingNew] = useState(false);
const [newProjectCategory, setNewProjectCategory] = useState('Unspecified');
const [searchText, setSearchText] = useState('');
const [allProjects, setAllProjects] = useState([]);
// set data from props
useEffect(() => {
setAllProjects(projects || []);
const categories = Array.from(new Set((projects || []).map(p => p.category).filter(Boolean)));
setCategoryOptions(categories.length ? categories : ['Unspecified']);
}, [projects]);
// reset validation each time the modal opens
useEffect(() => {
if (open) {
setIsValidProject(true);
setShowDoesNotExistAlert(false);
setCreatingNew(false);
setSelectedProject(null);
setSearchText('');
}
}, [open]);
// ---------- helpers ----------
const format = s => (s || '').toLowerCase().trim();
const projectByName = name => (allProjects || []).find(p => format(p.projectName) === format(name));
const handleSelectProject = (project) => {
setSelectedProject(project);
setIsValidProject(true);
setShowDoesNotExistAlert(false);
};
const close = () => {
onClose?.();
setCreatingNew(false);
setShowDoesNotExistAlert(false);
};
// ---------- Confirm existing project ----------
const handleConfirm = async () => {
if (!selectedProject) {
setIsValidProject(false);
toast.error('Please select a project from the list.');
return;
}
if ((props.userProjects || []).some(p => p?._id === selectedProject._id)) {
setIsValidProject(false);
toast.error('Great idea, but they already have that one! Pick another!');
return;
}
try {
await dispatch(assignProject(selectedProject._id, props.userId, 'Assign'));
// ✅ Make sure we're passing the complete project object
props.onSelectAssignProject?.(selectedProject);
props.onClose?.();
} catch (e) {
// eslint-disable-next-line no-console
console.error('Error Assigning Project:', e);
toast.error('Failed to assign project. Please try again.');
}
};
// ---------- Create new project, then confirm ----------
const handleCreateNew = async () => {
if (!searchText.trim()) {
setIsValidProject(false);
setSelectedProject(null);
return;
}
if (projectByName(searchText)) {
toast.error('This project already exists.');
return;
}
const newProject = {
projectName: searchText.trim(),
projectCategory: newProjectCategory,
isActive: true,
};
try {
await axios.post(ENDPOINTS.PROJECTS, newProject);
const res = await axios.get(ENDPOINTS.PROJECTS);
const created =
(res.data || []).find(p => format(p.projectName) === format(searchText)) ||
null;
if (!created) {
toast.success('Project created successfully, but it was not auto-selected.');
setCreatingNew(false);
setSearchText('');
return;
}
// select the newly created project so pressing Confirm assigns it
setSelectedProject(created);
setAllProjects(res.data || []);
setCreatingNew(false);
toast.success('Project created successfully');
} catch {
toast.error('Project creation failed');
}
};
return (
<Modal
isOpen={props.open}
toggle={onClose}
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus={false}
className={darkMode ? 'text-light dark-mode' : ''}
>
<ModalHeader className={darkMode ? 'bg-space-cadet' : ''} toggle={onClose}>
{creatingNew ? 'Create' : ' Add'} Project{' '}
</ModalHeader>
<ModalBody className={darkMode ? 'bg-yinmn-blue' : ''} style={{ textAlign: 'center' }}>
<div className="input-group-prepend" style={{ marginBottom: 10 }}>
<AddProjectsAutoComplete
projectsData={allProjects}
onDropDownSelect={handleSelectProject}
selectedProject={selectedProject}
setIsOpenDropdown={setCreatingNew}
searchText={searchText}
onInputChange={setSearchText}
isSetUserIsNotSelectedAutoComplete={setShowDoesNotExistAlert}
formatText={(s) => format(s).replace(/\s+/g, '')}
/>
<Button
color={creatingNew ? 'success' : 'primary'}
style={darkMode ? {} : { ...boxStyle, marginLeft: 5 }}
onClick={creatingNew ? handleCreateNew : handleConfirm}
>
{creatingNew ? 'Create' : 'Confirm'}
</Button>
</div>
{creatingNew && (
<div className="input-group-prepend" style={{ marginBottom: 10, display: 'flex', gap: 10 }}>
<Input type="select" value={newProjectCategory} onChange={e => setNewProjectCategory(e.target.value)}>
{categoryOptions.map(opt => (
<option key={opt}>{opt}</option>
))}
</Input>
<Button
color="danger"
onClick={() => {
setCreatingNew(false);
setShowDoesNotExistAlert(false);
setSearchText('');
}}
style={{ width: '100%' }}
>
Cancel project creation
</Button>
</div>
)}
{!isValidProject && selectedProject && (
<Alert color="danger">Great idea, but they already have that one! Pick another!</Alert>
)}
{!isValidProject && !selectedProject && (
<Alert color="danger">
Hey, You need to {creatingNew ? 'write the name of' : 'pick'} a project first!
</Alert>
)}
{showDoesNotExistAlert && <Alert color="danger">This project does not exist.</Alert>}
</ModalBody>
<ModalFooter className={darkMode ? 'bg-yinmn-blue' : ''}>
<Button color="secondary" onClick={close} style={darkMode ? boxStyleDark : boxStyle}>
Close
</Button>
</ModalFooter>
</Modal>
);
});
export default AddProjectPopup;