All files / src/app/student-page/components/settings ChangePhoto.jsx

77.27% Statements 51/66
85% Branches 17/20
73.68% Functions 14/19
78.68% Lines 48/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                              48x   48x 48x   48x 48x 48x   48x 1x     48x 13x 13x 13x 13x 11x   13x 13x   1x       48x 7x 7x     1x             7x 6x 6x 6x 6x 6x 6x     7x 1x     7x   7x 7x   7x   7x 7x 1x 1x     6x                   48x                                                         48x 48x 11x                     37x                                                       48x 1x 1x     48x                                                                                            
import * as React from "react";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import { Alert, Box, IconButton, Typography } from "@mui/material";
import DefaultPhoto from "@/assets/default_image.png";
import { useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useSnackbar } from "notistack";
import { _addProfilePicture, _deleteProfilePicture, _updateProfilePicture } from "@/store/slices/student/StudentData";
import CloseIcon from "@mui/icons-material/Close";
 
export default function ChangePhoto({ showDialog, setShowDialog, onPhotoUpdated }) {
    const { studentData, uploadPhotoHasErrors, uploadPhotoIsLoading } = useSelector((state) => state.StudentData);
 
    const dispatch = useDispatch();
    const { enqueueSnackbar, closeSnackbar } = useSnackbar();
 
    const inputRef = useRef(null);
    const [photo, setPhoto] = useState(""); //for displaying in browser
    const [selectedPhoto, setSelectedPhoto] = useState(null); //for sending payload
 
    const browseImage = () => {
        inputRef.current.click();
    };
 
    const handleChange = (event) => {
        try {
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onloadend = () => {
                setPhoto(reader.result);
            };
            setSelectedPhoto(file);
            if (file) reader.readAsDataURL(file);
        } catch (error) {
            console.log("");
        }
    };
 
    const clickSave = () => {
        const showSnackbar = (message, variant) => {
            enqueueSnackbar(message, {
                variant,
                action: (key) => (
                    <IconButton size="small" color="inherit" onClick={() => closeSnackbar(key)}>
                        <CloseIcon fontSize="small" />
                    </IconButton>
                ),
            });
        };
 
        const handleSuccess = () => {
            onPhotoUpdated?.(photo);
            window.dispatchEvent(new CustomEvent("profilePhotoUpdated", { detail: photo }));
            setPhoto("");
            setSelectedPhoto(null);
            setShowDialog(false);
            showSnackbar("Photo successfully updated", "success");
        };
 
        const handleError = () => {
            showSnackbar("Invalid image upload", "error");
        };
 
        Iif (!selectedPhoto) return;
 
        const formData = new FormData();
        formData.append("file", selectedPhoto);
 
        const action = studentData.profile_picture ? _updateProfilePicture : _addProfilePicture;
 
        dispatch(action(formData)).then((response) => {
            if (response?.error) {
                handleError();
                return;
            }
 
            handleSuccess();
        });
    };
 
    // Added by Allan Ninal — 2026-09-24 (EI-T81 "Student deletes their profile
    // picture"). The execution was failing with the note "No Delete Option", and
    // that was accurate about the UI — but not about the API: the backend has had
    // DELETE /v1/student/account/picture/delete all along, and the TEACHER
    // settings page already wires it up. Only the student side was missing the
    // endpoint declaration, the API method, the thunk and this button.
    const handleDelete = () => {
        dispatch(_deleteProfilePicture()).then((response) => {
            const showSnackbar = (message, variant) => {
                enqueueSnackbar(message, {
                    variant,
                    action: (key) => (
                        <IconButton size="small" color="inherit" onClick={() => closeSnackbar(key)}>
                            <CloseIcon fontSize="small" />
                        </IconButton>
                    ),
                });
            };
 
            if (response?.error) {
                showSnackbar("Unable to delete photo", "error");
                return;
            }
 
            // Same notifications the save path uses, so the avatar elsewhere on
            // the page clears immediately instead of showing a stale picture.
            onPhotoUpdated?.("");
            window.dispatchEvent(new CustomEvent("profilePhotoUpdated", { detail: "" }));
            setPhoto("");
            setSelectedPhoto(null);
            setShowDialog(false);
            showSnackbar("Photo successfully deleted", "success");
        });
    };
 
    const photoActions = () => {
        if (photo) {
            return (
                <React.Fragment>
                    <Button sx={{ width: "150px" }} variant="outlined" color="primary" onClick={browseImage}>
                        Change
                    </Button>
                    <Button sx={{ width: "150px" }} variant="contained" color="primary" onClick={clickSave}>
                        Save
                    </Button>
                </React.Fragment>
            );
        } else {
            return (
                <React.Fragment>
                    {studentData?.profile_picture && (
                        <Button
                            id="student-settings-button-remove-photo"
                            sx={{ width: "150px" }}
                            variant="outlined"
                            color="error"
                            disabled={uploadPhotoIsLoading}
                            onClick={handleDelete}
                        >
                            Remove
                        </Button>
                    )}
                    <Button
                        id="student-settings-button-upload"
                        sx={{ width: "150px" }}
                        variant="contained"
                        color="primary"
                        onClick={browseImage}
                    >
                        Upload
                    </Button>
                </React.Fragment>
            );
        }
    };
 
    const clickCancel = () => {
        setPhoto(null);
        setShowDialog(false);
    };
 
    return (
        <React.Fragment>
            <input
                ref={inputRef}
                id="student-settings-input-upload"
                type="file"
                accept="image/*"
                hidden
                onChange={handleChange}
            />
            <Dialog
                open={showDialog}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
                fullWidth
            >
                <DialogTitle
                    id="alert-dialog-title"
                    sx={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                    }}
                >
                    <Typography variant="body1">Edit Photo</Typography>
                </DialogTitle>
                <DialogContent dividers>
                    {uploadPhotoHasErrors && <Alert severity="error">{uploadPhotoHasErrors}</Alert>}
                    <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", objectFit: "cover" }}>
                        <img
                            style={{ width: "8rem", height: "8rem", borderRadius: "50%" }}
                            src={photo ? photo : studentData?.profile_picture || DefaultPhoto}
                            alt="Profile"
                        />
                    </Box>
                </DialogContent>
                <DialogActions sx={{ display: "flex", justifyContent: "space-between" }}>
                    <Button sx={{ width: "150px" }} variant="inherit" onClick={clickCancel}>
                        Cancel
                    </Button>
                    {photoActions()}
                </DialogActions>
            </Dialog>
        </React.Fragment>
    );
}