source: components/BuildDetailsDialog.tsx@ ad3c219

main
Last change on this file since ad3c219 was ad3c219, checked in by Mihail <mihail2.naumov@…>, 4 months ago

Added check so that user cant rate his own builds

  • Property mode set to 100644
File size: 21.0 KB
Line 
1import React, {useEffect, useState} from 'react';
2import {
3 Dialog, DialogTitle, DialogContent, DialogActions, Button, Box, Typography,
4 IconButton, Tab, Tabs, Table, TableBody, TableCell, TableRow, Rating, TextField, Avatar, Chip, Alert, Snackbar
5} from '@mui/material';
6import CloseIcon from '@mui/icons-material/Close';
7import AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';
8import FavoriteIcon from '@mui/icons-material/Favorite';
9import FavoriteBorderIcon from '@mui/icons-material/FavoriteBorder';
10import PersonIcon from "@mui/icons-material/Person";
11import {onGetBuildDetails, onSetReview, onToggleFavorite, onCloneBuild, onSetRating} from '../pages/+Layout.telefunc';
12import {onGetBuildState} from '../pages/forge/forge.telefunc';
13
14const formatPrice = (price: any) => new Intl.NumberFormat('en-US', {
15 style: 'currency',
16 currency: 'USD'
17}).format(Number(price) || 0);
18
19export default function BuildDetailsDialog({open, buildId, onClose, currentUser, isDashboardView = false}: {
20 open: boolean;
21 buildId: number | null;
22 onClose: () => void;
23 currentUser: any;
24 isDashboardView?: boolean;
25}) {
26 const [details, setDetails] = useState<any>(null);
27 const [loading, setLoading] = useState(false);
28 const [tabIndex, setTabIndex] = useState(0);
29 const [cloneDialogOpen, setCloneDialogOpen] = useState(false);
30 const [cloningBuildId, setCloningBuildId] = useState<number | null>(null);
31 const [isOwner, setIsOwner] = useState(false);
32
33 const [reviewText, setReviewText] = useState("");
34 const [ratingVal, setRatingVal] = useState(5);
35
36 const [snackbar, setSnackbar] = useState<{
37 open: boolean;
38 message: string;
39 severity: 'error' | 'warning' | 'info' | 'success';
40 }>({
41 open: false,
42 message: '',
43 severity: 'warning'
44 });
45
46 useEffect(() => {
47 if (open && buildId !== null) {
48 setLoading(true);
49 setReviewText("");
50 setRatingVal(5);
51
52 onGetBuildDetails({buildId})
53 .then(data => {
54 setDetails(data);
55 if (data.userRating) setRatingVal(data.userRating);
56 if (data.userReview) setReviewText(data.userReview);
57 })
58 .finally(() => setLoading(false));
59 }
60 }, [open, buildId]);
61
62 useEffect(() => {
63 if (open && buildId !== null) {
64 onGetBuildState({buildId})
65 .then(state => {
66 setIsOwner(!!state);
67 })
68 .catch(() => setIsOwner(false));
69 } else {
70 setIsOwner(false);
71 }
72 }, [open, buildId]);
73
74 useEffect(() => {
75 if (open) {
76 setTabIndex(0);
77 }
78 }, [open, buildId]);
79
80 const handleFavorite = async () => {
81 if (!currentUser || buildId === null) return alert("Please login to favorite builds.");
82 const res = await onToggleFavorite({buildId});
83 setDetails((prev: any) => ({...prev, isFavorite: res}));
84 };
85
86 const handleSubmitReview = async () => {
87 if (!currentUser || buildId === null) return alert("Please login to review.");
88
89 await onSetReview({
90 buildId,
91 content: reviewText,
92 });
93
94 await onSetRating({
95 buildId,
96 value: ratingVal
97 });
98
99 const refreshed = await onGetBuildDetails({buildId});
100 setDetails(refreshed);
101 };
102
103 const handleCloneConfirm = async () => {
104 if (!cloningBuildId) return;
105
106 if(!currentUser){
107 window.location.href="/auth/login";
108 return;
109 }
110
111 try {
112 const newBuildId = await onCloneBuild({buildId: cloningBuildId});
113 window.location.href = `/forge?buildId=${newBuildId}`;
114 setCloneDialogOpen(false);
115 setCloningBuildId(null);
116 } catch (e) {
117 // alert("Failed to clone build. Please try again.");
118 setCloneDialogOpen(false);
119 setSnackbar({
120 open: true,
121 message: 'Failed to clone build. Please try again!',
122 severity: 'error'
123 })
124 }
125 };
126
127 const isCreator = currentUser && details && details.userId === currentUser;
128
129 if (!open) return null;
130
131 return (
132 <>
133 <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth scroll="body">
134 {loading || !details ? (
135 <Box sx={{p: 5, textAlign: 'center'}}>Loading Forge Schematics...</Box>
136 ) : (
137 <>
138 <DialogTitle sx={{
139 display: 'flex',
140 justifyContent: 'space-between',
141 alignItems: 'center',
142 bgcolor: '#ff8201'
143 }}>
144 <Box>
145 <Typography variant="h5" fontWeight="bold">{details.name}</Typography>
146 <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>
147 <PersonIcon sx={{fontSize: 16}}/>
148 <Typography variant="subtitle2" color="text.secondary" fontWeight="bold">
149 by {details.creator}
150 </Typography>
151 <Chip label={formatPrice(details.totalPrice)} size="small" color="primary"
152 variant="outlined"/>
153 </Box>
154 </Box>
155 <IconButton onClick={onClose}><CloseIcon/></IconButton>
156 </DialogTitle>
157
158 <DialogContent sx={{p: 0}}>
159 <Box sx={{
160 borderBottom: 1,
161 borderColor: 'divider',
162 px: 2,
163 bgcolor: 'primary',
164 position: 'sticky',
165 top: 0,
166 zIndex: 1
167 }}>
168 <Tabs value={tabIndex} onChange={(_, v) => setTabIndex(v)}>
169 <Tab label="Specs"/>
170 <Tab label={`Reviews (${details.ratingStatistics.ratingCount})`}/>
171 </Tabs>
172 </Box>
173
174 <Box sx={{p: 3}}>
175 {tabIndex === 0 && (
176 <Box
177 sx={{
178 display: 'grid',
179 gridTemplateColumns: {
180 xs: '1fr',
181 md: '2fr 1fr'
182 },
183 gap: 2,
184 width: '100%'
185 }}
186 >
187 <Box>
188 <Table size="small">
189 <TableBody>
190 {details.components.map((comp: any) => (
191 <TableRow key={comp.id}>
192 <TableCell sx={{width: 50}}>
193 <Avatar
194 src={comp.imgUrl || undefined}
195 variant="rounded"
196 sx={{width: 50, height: 50, bgcolor: '#ff8201'}}
197 >
198 {comp.type?.substring(0, 3)?.toUpperCase()}
199 </Avatar>
200 </TableCell>
201 <TableCell>
202 <Typography variant="body2" color="text.secondary" sx={{
203 fontSize: '0.75rem',
204 textTransform: 'uppercase'
205 }}>
206 {comp.type}
207 </Typography>
208 <Typography variant="body1" fontWeight="500">
209 {comp.brand} {comp.name}
210 </Typography>
211 </TableCell>
212 <TableCell align="right"
213 sx={{fontWeight: 'bold', color: '#ff8201'}}>
214 {formatPrice(comp.price)}
215 </TableCell>
216 </TableRow>
217 ))}
218 <TableRow sx={{bgcolor: '#424343'}}>
219 <TableCell colSpan={2} sx={{
220 fontWeight: 'bold',
221 color: '#ff8201'
222 }}>TOTAL</TableCell>
223 <TableCell align="right" sx={{
224 fontWeight: 'bold',
225 fontSize: '1.1rem',
226 color: 'primary.main'
227 }}>
228 {formatPrice(details.totalPrice)}
229 </TableCell>
230 </TableRow>
231 </TableBody>
232 </Table>
233 </Box>
234
235 <Box>
236 <Box sx={{bgcolor: '#424343', p: 2, borderRadius: 2, mb: 2}}>
237 <Typography color="primary.main" gutterBottom fontWeight="bold">
238 Builder's Notes
239 </Typography>
240 <Typography color="primary.main" variant="body2"
241 sx={{fontStyle: 'italic'}}>
242 "{details.description || "No notes provided."}"
243 </Typography>
244 </Box>
245
246 <Box sx={{display: 'flex', flexDirection: 'column', gap: 1}}>
247 {isDashboardView && isOwner ? (
248 <Button
249 variant="contained"
250 color="primary"
251 size="large"
252 startIcon={<AutoFixHighIcon/>}
253 onClick={() => {
254 window.location.href = `/forge?buildId=${details.id}`;
255 onClose();
256 }}
257 >
258 Edit Build
259 </Button>
260 ) : (
261 <Button
262 variant="contained"
263 color="primary"
264 size="large"
265 startIcon={<AutoFixHighIcon/>}
266 onClick={() => {
267 setCloningBuildId(details.id);
268 setCloneDialogOpen(true);
269 }} >
270 Clone & Edit
271 </Button>
272 )}
273 <Button
274 variant={details.isFavorite ? "contained" : "outlined"}
275 color={details.isFavorite ? "error" : "primary"}
276 startIcon={details.isFavorite ? <FavoriteIcon/> :
277 <FavoriteBorderIcon/>}
278 onClick={handleFavorite}
279 >
280 {details.isFavorite ? "Favorited" : "Add to Favorites"}
281 </Button>
282 </Box>
283 </Box>
284 </Box>
285 )}
286
287 {tabIndex === 1 && (
288 <Box>
289 <Box sx={{
290 display: 'flex',
291 alignItems: 'center',
292 gap: 2,
293 mb: 4,
294 p: 2,
295 bgcolor: '#5e5e5e',
296 borderRadius: 2
297 }}>
298 <Typography variant="h3"
299 fontWeight="bold">{details.ratingStatistics.averageRating.toFixed(1)}</Typography>
300 <Box>
301 <Rating value={details.ratingStatistics.averageRating} readOnly
302 precision={0.5}/>
303 <Typography variant="body2"
304 color="text.secondary">{details.ratingStatistics.ratingCount} ratings</Typography>
305 </Box>
306 </Box>
307
308 {currentUser && !isCreator && (
309 <Box sx={{mb: 4, p: 2, border: '1px solid #ddd', borderRadius: 2}}>
310 <Typography variant="subtitle2" gutterBottom>Your Review</Typography>
311 <Box sx={{display: 'flex', alignItems: 'center', mb: 1}}>
312 <Rating value={ratingVal}
313 onChange={(_, v) => setRatingVal(v || 5)}/>
314 </Box>
315 <TextField
316 fullWidth
317 multiline
318 rows={2}
319 placeholder="Share your thoughts on this build..."
320 value={reviewText}
321 onChange={(e) => setReviewText(e.target.value)}
322 sx={{mb: 1}}
323 />
324 <Button size="small" variant="contained" onClick={handleSubmitReview}>
325 Submit Review
326 </Button>
327 </Box>
328 )}
329
330 {currentUser && isCreator && (
331 <Alert severity="error" sx={{mb: 4}}>
332 You cannot rate your own builds.
333 </Alert>
334 )}
335
336 <Box sx={{display: 'flex', flexDirection: 'column', gap: 2}}>
337 {details.reviews.map((rev: any, i: number) => (
338 <Box key={i} sx={{pb: 2, borderBottom: '1px solid #eee'}}>
339 <Box sx={{
340 display: 'flex',
341 justifyContent: 'space-between',
342 mb: 0.5
343 }}>
344 <Typography fontWeight="bold"
345 variant="body2">{rev.username}</Typography>
346 <Typography variant="caption"
347 color="text.secondary">{rev.createdAt}</Typography>
348 </Box>
349 <Typography variant="body2">{rev.content}</Typography>
350 </Box>
351 ))}
352 {details.reviews.length === 0 && (
353 <Typography color="text.secondary" align="center">
354 No reviews yet. Be the first!
355 </Typography>
356 )}
357 </Box>
358 </Box>
359 )}
360 </Box>
361 </DialogContent>
362 </>
363 )}
364 </Dialog>
365
366 <Dialog open={cloneDialogOpen} onClose={() => setCloneDialogOpen(false)}>
367 <DialogTitle>Clone Build</DialogTitle>
368 <DialogContent>
369 <Typography>
370 This will create a copy of "{details?.name}" in your Forge so you can edit it.
371 All components will be copied over.
372 </Typography>
373 </DialogContent>
374 <DialogActions>
375 <Button onClick={() => setCloneDialogOpen(false)}>Cancel</Button>
376 <Button
377 variant="contained"
378 onClick={handleCloneConfirm}
379 disabled={!cloningBuildId}
380 >
381 Clone Build
382 </Button>
383 </DialogActions>
384 </Dialog>
385 <Snackbar
386 open={snackbar.open}
387 autoHideDuration={5000}
388 onClose={() => setSnackbar(prev => ({...prev, open: false}))}
389 anchorOrigin={{vertical: 'bottom', horizontal: 'center'}}
390 >
391 <Alert
392 onClose={() => setSnackbar(prev => ({...prev, open: false}))}
393 severity={snackbar.severity}
394 variant="filled"
395 sx={{width: '100%'}}
396 >
397 {snackbar.message}
398 </Alert>
399 </Snackbar>
400 </>
401 );
402}
Note: See TracBrowser for help on using the repository browser.