Skip to content

Commit

Permalink
Save data input form (#306)
Browse files Browse the repository at this point in the history
* patch: add a custom create observation

* patch: add custom save function for observations

* patch: save observation into db

* Update index.tsx

* patch: save data input form into db

* patch: update data being sent to api

* patch: add notification modals

* patch: remove repeating key

* patch: update path

* patch: update variables

* patch: make sure values are decimal before saving

* Update index.tsx

* patch: adjust syling

* patch: update file

* patch: save data input value

* patch: assign 0 for id when site id doesnt exists

* patch: adjust modals styling

* patch: update component

* patch: make sure site is not a string

* Update index.tsx

* Update observation_views.py

* patch: update message modals

* Update observation_views.py

* Update observation_views.py

* patch: save all fields data

* Update observation_views.py

* Update backend

* patch: return gid

---------

Co-authored-by: Irwan Fathurrahman <[email protected]>
  • Loading branch information
tinashechiraya and meomancer authored Nov 30, 2023
1 parent 8337bef commit 5ae41b0
Show file tree
Hide file tree
Showing 7 changed files with 279 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ function DegreeInput({ label, value, onChange }: DegreeInputInterface) {
min={min}
max={max}
placeholder="0.000000"
step={0.0001}
style={{
width: '300px',
maxWidth: '300px',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ function DmsInputSection(
color="black_900_3a"
size="xs"
variant="outline"
step={0.01}
min={min}
max={max}
placeholder="0.000000"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export interface Interface {
setFieldValue: (name: string, value: any) => void
}

const detailed = 10000

/** Coordinates input form. **/
export default function CoordinatesInputForm(
{ values, setFieldValue }: Interface
Expand All @@ -25,11 +27,13 @@ export default function CoordinatesInputForm(

/** set latitude **/
const setLatitude = (val) => {
val = Math.floor(val * detailed) / detailed
setFieldValue('latitude', val)
}

/** set longitude **/
const setLongitude = (val) => {
val = Math.floor(val * detailed) / detailed
setFieldValue('longitude', val)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,6 @@ const DataInputForm: React.FC<DataInputFormProps> = (props) => {
}
};


// Function to handle form submission
const handleSubmit = (values) => {
console.log('Form Values:', values);
};

const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);

const openUploadModal = () => {
Expand Down Expand Up @@ -201,6 +195,7 @@ const DataInputForm: React.FC<DataInputFormProps> = (props) => {
getSites()
}, [showSelectKnownSiteField]);


return (
<>
{!showScoreForm ? (
Expand Down Expand Up @@ -250,7 +245,8 @@ const DataInputForm: React.FC<DataInputFormProps> = (props) => {
<Formik
initialValues={formValues}
onSubmit={(values) => {
handleSubmit(values)
setFormValues(values)
handleShowScoreForm()
}}
>
{({ values, handleChange, setFieldValue }) => (
Expand Down Expand Up @@ -284,7 +280,9 @@ const DataInputForm: React.FC<DataInputFormProps> = (props) => {
marginBottom: '2%'
}}
value={values.riverName}
onChange={handleChange}
onChange={(e) => {
handleChange(e);
}}
/>
</div>

Expand Down Expand Up @@ -490,6 +488,8 @@ const DataInputForm: React.FC<DataInputFormProps> = (props) => {
padding: '8px 12px',
marginLeft: '40%'
}}
value={values.selectedSite}
onChange={handleChange}
>
{sites.map((option) => (
<option key={option.value} value={option.value} selected={option.value === values.selectedSite}>
Expand Down Expand Up @@ -753,6 +753,8 @@ const DataInputForm: React.FC<DataInputFormProps> = (props) => {
padding: '8px 12px',
marginLeft: '17%'
}}
value={values.dissolvedoxygenOneUnit}
onChange={handleChange}
>
{inputOxygenUnitsList.map((option) => (
<option key={option.value} value={option.value} selected={option.value === values.dissolvedoxygenOneUnit}>
Expand Down Expand Up @@ -812,6 +814,8 @@ const DataInputForm: React.FC<DataInputFormProps> = (props) => {
padding: '8px 12px',
marginLeft: '17%'
}}
value={values.electricalconduOneUnit}
onChange={handleChange}
>
{inputElectricConductivityUnitsList.map((option) => (
<option key={option.value} value={option.value} selected={option.value === values.electricalconduOneUnit}>
Expand All @@ -830,8 +834,7 @@ const DataInputForm: React.FC<DataInputFormProps> = (props) => {
color="blue_gray_500"
size="xs"
variant="fill"
type="button"
onClick={handleShowScoreForm}
type="submit"
>
next
</Button>
Expand Down
156 changes: 143 additions & 13 deletions django_project/minisass_frontend/src/components/ScoreForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,37 @@ import { Button, Img, List, Text } from "../../components";
import UploadModal from "../../components/UploadFormModal";
import ManageImagesModal from "../../components/ManageImagesModal";
import { globalVariables } from "../../utils";
import Modal from 'react-modal';

interface AdditionalData {
dataFormInput: string;
}

interface ScoreFormProps {
onCancel: () => void;
additionalData: AdditionalData;
additionalData: {};
setSidebarOpen: React.Dispatch<React.SetStateAction<boolean>>;
}


const ScoreForm: FC<ScoreFormProps> = ({ onCancel, additionalData, setSidebarOpen }) => {
const [scoreGroups, setScoreGroups] = useState([]);
const [isSuccessModalOpen, setIsSuccessModalOpen] = useState(false);
const [isErrorModalOpen, setIsErrorModalOpen] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const [buttonStates, setButtonStates] = useState([]);

const closeSuccessModal = () => {
setIsSuccessModalOpen(false);
};

const closeErrorModal = () => {
setIsErrorModalOpen(false);
};

useEffect(() => {
const fetchScoreGroups = async () => {
try {
const response = await axios.get(`${globalVariables.baseUrl}/group-scores/`);
setScoreGroups(response.data);
setButtonStates(response.data.map(score => ({ id: score.id, showManageImages: false })))
} catch (error) {
console.error('Error fetching score groups:', error);
}
Expand All @@ -40,8 +51,6 @@ const ScoreForm: FC<ScoreFormProps> = ({ onCancel, additionalData, setSidebarOpe

const [selectedButton, setSelectedButton] = useState(null);

const [buttonStates, setButtonStates] = useState(scoreGroups.map(score => ({ id: score.id, showManageImages: false })));

const handleButtonClick = (id) => {
const updatedButtonStates = buttonStates.map(buttonState => {
if (buttonState.id === id) {
Expand All @@ -63,12 +72,43 @@ const ScoreForm: FC<ScoreFormProps> = ({ onCancel, additionalData, setSidebarOpe
const averageScore = totalScore / numberOfGroups;

// Function to log the state of checkboxes
const handleSave = () => {
console.log(checkboxStates); // Log the state of checkboxes
console.log('values ', additionalData);
console.log(`Total Score: ${totalScore}`);
console.log(`Number of Groups: ${numberOfGroups}`);
console.log(`Average Score: ${averageScore}`);
const handleSave = async () => {

try {

console.log(checkboxStates); // Log the state of checkboxes
console.log('data from first form ', additionalData);
console.log(`Total Score: ${totalScore}`);
console.log(`Number of Groups: ${numberOfGroups}`);
console.log(`Average Score: ${averageScore}`);

// Create an object with the data to be saved
const observationsData = {
flatworms :checkboxStates['1'],
leeches:checkboxStates['2'],
crabs_shrimps :checkboxStates['3'],
stoneflies :checkboxStates['4'],
minnow_mayflies :checkboxStates['5'],
other_mayflies :checkboxStates['6'],
damselflies:checkboxStates['7'],
dragonflies:checkboxStates['8'],
bugs_beetles :checkboxStates['9'],
caddisflies:checkboxStates['10'],
true_flies:checkboxStates['11'],
snails:checkboxStates['12'],
score:totalScore,
datainput: additionalData,
};

const response = await axios.post(`${globalVariables.baseUrl}/monitor/observations-create/`, observationsData);

if(response.status == 200){
setIsSuccessModalOpen(true);
}
} catch (error) {
setErrorMessage(error.message);
setIsErrorModalOpen(true);
}
};

// Function to handle checkbox changes
Expand Down Expand Up @@ -112,7 +152,7 @@ const ScoreForm: FC<ScoreFormProps> = ({ onCancel, additionalData, setSidebarOpe
<>
<div className="flex flex-col font-raleway items-center justify-start mx-auto p-0.5 w-full"
style={{
height: '72vh',
height: '73vh',
overflowY: 'auto',
overflowX: 'auto'
}}
Expand Down Expand Up @@ -272,6 +312,96 @@ const ScoreForm: FC<ScoreFormProps> = ({ onCancel, additionalData, setSidebarOpe
</div>

</div>
{/* Success Modal */}
<Modal
isOpen={isSuccessModalOpen}
onRequestClose={closeSuccessModal}
style={{
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)',
width: '100%',
maxWidth: '400px',
background: 'white',
border: 'none',
borderRadius: '0px 25px 25px 25px',
},
}}
>
{isSuccessModalOpen && (
<div>
<Img
className="h-6 w-6 common-pointer"
src={`${globalVariables.staticPath}img_icbaselineclose.svg`}
alt="close"
onClick={closeSuccessModal}
style={{ marginLeft: '340px'}}
/>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginLeft: '80px',
}}
>
<Text size="txtRalewayBold18" className="text-green-500">
Your data was successfully captured.
</Text>
</div>
</div>
)}
</Modal>

{/* Error Modal */}
<Modal
isOpen={isErrorModalOpen}
onRequestClose={closeErrorModal}
style={{
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)',
width: '100%',
maxWidth: '400px',
background: 'white',
border: 'none',
borderRadius: '0px 25px 25px 25px',
},
}}
>
{isErrorModalOpen && (
<div>
<Img
className="h-6 w-6 common-pointer"
src={`${globalVariables.staticPath}img_icbaselineclose.svg`}
alt="close"
onClick={closeErrorModal}
style={{ marginLeft: '340px'}}
/>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginLeft: '80px',
}}
>
<Text size="txtRalewayBold18" className="text-red-500">
{errorMessage}
</Text>
</div>
</div>
)}
</Modal>

<UploadModal isOpen={isUploadModalOpen} onClose={closeUploadModal} onSubmit={null} />
<ManageImagesModal
title={manageImagesModalData.groups}
Expand Down
Loading

0 comments on commit 5ae41b0

Please sign in to comment.