Skip to content

Commit

Permalink
Merge pull request #42 from sympoll/poll-submit
Browse files Browse the repository at this point in the history
Poll submit
  • Loading branch information
Idan-sh authored Aug 26, 2024
2 parents 5599c12 + ed11fe7 commit 7fddb90
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 30 deletions.
1 change: 1 addition & 0 deletions src/assets/styles/cmps/error-popup/_ErrorPopup.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
}

.error-popup-container p {
white-space: pre-wrap; /* Preserve line breaks and wrap text */
animation: textColorChange 3s forwards;
}

Expand Down
5 changes: 1 addition & 4 deletions src/cmps/feed/bar/FeedBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ export default function FeedBar({ groupId }: FeedBarProps) {
)}

{isCreatePollFormVisible && (
<CreatePollForm
groupId={groupId}
closePollFunction={toggleCreatePollForm}
/>
<CreatePollForm groupId={groupId} closePollFunction={toggleCreatePollForm} />
)}
</div>
);
Expand Down
45 changes: 23 additions & 22 deletions src/cmps/feed/poll/CreatePollForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@ import React, { useState } from "react";
import { CreatePollData } from "../../../models/CreatePollData.model";
import ErrorPopup from "../../popup/ErrorPopup";
import CustomButton from "../../global/CustomButton";
import {
isAllVotingItemsDefined,
isTitleDefined,
isDeadlineValid,
getCurrentDateTime
} from "../../../services/create.poll.form.service";
import { handleSubmit, getCurrentDateTime } from "../../../services/create.poll.form.service";
import CloseButton from "../../global/CloseButton";

interface CreatePollFormProps {
Expand All @@ -18,12 +13,14 @@ interface CreatePollFormProps {
export default function CreatePollForm({ groupId, closePollFunction }: CreatePollFormProps) {
const [isErrorPopupVisible, setIsErrorPopupVisible] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitButtonText, setSubmitButtonText] = useState("Submit");

const [formData, setFormData] = useState<CreatePollData>({
title: "",
description: "",
nofAnswersAllowed: undefined,
creatorId: "", // Replace with actual creatorId
creatorId: "b1f8e925-2129-473d-bc09-b3a2a331f839", // Replace with actual creatorId
groupId: groupId,
deadline: "",
votingItems: ["", "", ""]
Expand Down Expand Up @@ -89,19 +86,20 @@ export default function CreatePollForm({ groupId, closePollFunction }: CreatePol
}
};

// Validates the form contents, If everything is ok submits the form in the else case
const handleSubmit = (event: React.FormEvent) => {
const handleOnSubmit = async (event: React.FormEvent) => {
// Prevents from automatically submitting the form
event.preventDefault();
// Handle form submission logic with formData
if (!isAllVotingItemsDefined(formData.votingItems)) {
displayErrorPopup("All options need to contain a value");
} else if (!isTitleDefined(formData.title)) {
displayErrorPopup("Poll needs to have title.");
} else if (!isDeadlineValid(formData.deadline)) {
displayErrorPopup("Deadline need to be a valid date in the future");
} else {
closePollFunction(); //
console.log("Form submitted", formData);

setIsSubmitting(true);
setSubmitButtonText("Submitting...");

const result = await handleSubmit(formData, displayErrorPopup);

setIsSubmitting(false);
setSubmitButtonText("Submit");

if (result.success) {
closePollFunction();
}
};

Expand All @@ -127,7 +125,7 @@ export default function CreatePollForm({ groupId, closePollFunction }: CreatePol

return (
<div className="poll-form">
<form onSubmit={handleSubmit} className="poll-form__body">
<form onSubmit={handleOnSubmit} className="poll-form__body">
<CloseButton size="16px" onClose={closePollFunction} />
<div className="poll-form__body__title">Create Poll</div>
<input
Expand Down Expand Up @@ -157,7 +155,6 @@ export default function CreatePollForm({ groupId, closePollFunction }: CreatePol
value={formData.deadline}
onChange={handleInputChange}
min={getCurrentDateTime()}
onFocus={(e) => e.target.blur()}
className={formData.deadline ? "deadline-filled" : "deadline-empty"}
/>
</div>
Expand Down Expand Up @@ -185,7 +182,11 @@ export default function CreatePollForm({ groupId, closePollFunction }: CreatePol
<p>Add New Option</p>
</div>
<div className="poll-form__body__submit-button-container">
<CustomButton type="submit">Submit</CustomButton>
{groupId && (
<CustomButton type="submit" disabled={isSubmitting}>
{submitButtonText}
</CustomButton>
)}
</div>
<p>
{isErrorPopupVisible && (
Expand Down
5 changes: 3 additions & 2 deletions src/cmps/global/CustomButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ interface BtnProps {
name?: string;
onClick?(): void;
type?: "button" | "submit" | "reset";
disabled?: boolean;
}

export default function btn({ children, onClick, type, name }: BtnProps) {
export default function btn({ children, onClick, type, name, disabled = false }: BtnProps) {
return (
<button className="custom-button" onClick={onClick} type={type} name={name}>
<button className="custom-button" onClick={onClick} type={type} name={name} disabled={disabled}>
{children}
</button>
);
Expand Down
74 changes: 73 additions & 1 deletion src/services/create.poll.form.service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
import axios from "axios";
import { CreatePollData } from "../models/CreatePollData.model";
import { useState } from "react";

const pollServiceUrl =
import.meta.env.VITE_BASE_URL +
import.meta.env.VITE_API_GATEWAY_URL +
import.meta.env.VITE_POLL_SERVICE_URL;

interface SubmitResult {
success: boolean;
errors?: string;
}

export function isAllVotingItemsDefined(votingItems: string[]): boolean {
return votingItems.every(item => item !== "");
}
Expand All @@ -24,4 +38,62 @@ export function isAllVotingItemsDefined(votingItems: string[]): boolean {
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
}

export function validatePollForm(formData: CreatePollData): { isValid: boolean; errors: string } {
let errors: string[] = [];

if (!isTitleDefined(formData.title)) {
errors.push("Title is required.\n");
}

if (!isAllVotingItemsDefined(formData.votingItems)) {
errors.push("All voting options should be defined.\n");
}

if (!isDeadlineValid(formData.deadline)) {
errors.push("Deadline should be a valid date in the future.\n");
}

return {
isValid: errors.length === 0,
errors: errors.join(""),
};
}


export async function handleSubmit(
formData: CreatePollData,
displayErrorMessage: (errors: string) => void
): Promise<SubmitResult> {
const { isValid, errors } = validatePollForm(formData);

if (!isValid) {
displayErrorMessage(errors);
return { success: false, errors };
}

try {
const deadlineDate = new Date(formData.deadline);
formData.deadline = deadlineDate.toISOString();
const response = await fetch(pollServiceUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});

if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}

console.log("Poll created successfully:", await response.json());
return { success: true };
} catch (error) {
console.log("Error while trying to create poll:", error);
const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred.';
displayErrorMessage(errorMessage);
return { success: false, errors: errorMessage };
}
}
2 changes: 1 addition & 1 deletion src/services/vote.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const voteServiceUrl =
import.meta.env.VITE_VOTE_SERVICE_URL;

// TODO: once session mechanism is in place, replace this.
const userId = "0f3ffe0d-cc0b-4510-960f-4430a1a64a76";
const userId = "b1f8e925-2129-473d-bc09-b3a2a331f839";

// Helper function to handle API requests
async function sendVoteRequest(
Expand Down

0 comments on commit 7fddb90

Please sign in to comment.