Skip to content

Commit

Permalink
Merge pull request #205 from priyanshuverma-dev/feat-comment-chatbot
Browse files Browse the repository at this point in the history
feat: Option to Comment on chatbot
  • Loading branch information
kom-senapati authored Oct 27, 2024
2 parents 3f1aaa1 + 4430f38 commit 9549e29
Show file tree
Hide file tree
Showing 5 changed files with 184 additions and 11 deletions.
32 changes: 30 additions & 2 deletions app/api_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import re

from sqlalchemy import func
from .models import User, Chatbot, Chat, Image
from .models import User, Chatbot, Chat, Image, Comment
from sqlalchemy.exc import IntegrityError
from flask_login import login_user
from typing import Union, List, Optional, Dict
Expand Down Expand Up @@ -642,16 +642,44 @@ def api_get_chatbot_data(chatbot_id: str):
chatbot: Chatbot = Chatbot.query.get(chatbot_id)
if chatbot == None:
return jsonify({"success": False, "message": "Chatbot not found"}), 404

comments: List[Comment] = Comment.query.filter_by(chatbot_id=chatbot_id).all()
return (
jsonify(
{
"success": True,
"bot": chatbot.to_dict(),
"comments": [comment.to_dict() for comment in comments],
}
),
200,
)

except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500


@api_bp.route("/api/chatbot/comment", methods=["POST"])
@jwt_required()
def api_comment_chatbot():
try:
data = request.get_json()
chatbot_id = data.get("chatbotId")
name = data.get("name")
message = data.get("message")
chatbot: Chatbot = Chatbot.query.get(chatbot_id)
if chatbot == None:
return jsonify({"success": False, "message": "Chatbot not found"}), 404
comment: Comment = Comment(
name=name,
chatbot_id=chatbot_id,
message=message,
)
db.session.add(comment)
user = get_current_user()
if user:
user.contribution_score += 3
db.session.commit()
return jsonify({"success": True, "message": "Comment saved"}), 200

except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
17 changes: 17 additions & 0 deletions app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,20 @@ def to_dict(self) -> dict:
"likes": self.likes,
"reports": self.reports,
}


class Comment(db.Model):
__tablename__ = "comments"

id: int = db.Column(db.Integer, primary_key=True)
name: str = db.Column(db.Text, nullable=False)
message: str = db.Column(db.Text, nullable=False)
chatbot_id: int = db.Column(db.Integer, nullable=False)

def to_dict(self) -> dict:
return {
"id": self.id,
"name": self.name,
"message": self.message,
"chatbot_id": self.chatbot_id,
}
9 changes: 7 additions & 2 deletions client/src/lib/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,16 @@ export const fetchChatbotData = async (
});
return data;
};
export const fetchChatbotViewData = async (id: string): Promise<Chatbot> => {
export const fetchChatbotViewData = async (
id: string
): Promise<{
bot: Chatbot;
comments: ChatbotComment[];
}> => {
const { data } = await axios.get(`${SERVER_URL}/api/chatbot_data/${id}`, {
headers: authHeaders,
});
return data.bot;
return data;
};

export const fetchImagesData = async (): Promise<ImageGen[]> => {
Expand Down
130 changes: 123 additions & 7 deletions client/src/pages/ChatbotView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,69 @@ import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { fetchChatbotViewData } from "@/lib/queries";
import { useQuery } from "@tanstack/react-query";
import { MessageCircle } from "lucide-react";
import { Textarea } from "@/components/ui/textarea";
import { authHeaders, fetchChatbotViewData } from "@/lib/queries";
import { SERVER_URL } from "@/lib/utils";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import { MessageCircle, Send, ThumbsUp } from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast";
import { Link, useNavigate, useParams } from "react-router-dom";

export default function ChatbotViewPage() {
const { chatbotId } = useParams();
const navigate = useNavigate();
const [name, setName] = useState("");
const [comment, setComment] = useState("");
const qc = useQueryClient();
if (!chatbotId) return null;

const { data: bot, isLoading } = useQuery({
const { data, isLoading } = useQuery({
queryKey: ["chatbot_view", chatbotId],
queryFn: () => fetchChatbotViewData(chatbotId),
});
const handleSubmitComment = async (e: React.FormEvent) => {
e.preventDefault();

if (!name || !comment) {
toast.error("Please fill in both fields");
return;
}

try {
const response = await axios.post(
`${SERVER_URL}/api/chatbot/comment`,
{
name,
message: comment,
chatbotId: chatbotId,
},
{ headers: { ...authHeaders } }
);

if (response.status == 200) {
toast.success("Comment submitted successfully!");
// Optionally, clear the form inputs
setName("");
setComment("");
// Refresh the comments list here (re-fetch data)
qc.invalidateQueries({
queryKey: ["chatbot_view", chatbotId],
});
} else {
toast.error("Failed to submit comment. Please try again.");
}
} catch (error) {
console.error("Error submitting comment:", error);
toast.error("An error occurred while submitting the comment.");
}
};

if (isLoading) {
return (
Expand All @@ -39,15 +84,15 @@ export default function ChatbotViewPage() {
);
}

if (!bot) {
if (!data) {
return (
<div className="text-center p-6 space-y-4">
<p>No Chatbot data available.</p>
<Button onClick={() => navigate("/hub")}>Go to Hub</Button>
</div>
);
}

const { bot, comments } = data;
return (
<>
<Navbar />
Expand Down Expand Up @@ -83,6 +128,77 @@ export default function ChatbotViewPage() {
</div>
</CardContent>
</Card>
<h2 className="text-2xl font-bold mb-4">Comments</h2>
<div
className="space-y-4 mb-8 max-h-[500px] overflow-auto [&::-webkit-scrollbar]:w-2
[&::-webkit-scrollbar-track]:rounded-full
[&::-webkit-scrollbar-track]:bg-gray-100
[&::-webkit-scrollbar-thumb]:rounded-full
[&::-webkit-scrollbar-thumb]:bg-gray-300
dark:[&::-webkit-scrollbar-track]:bg-neutral-700
dark:[&::-webkit-scrollbar-thumb]:bg-neutral-500"
>
{comments.map((c) => (
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Avatar className="h-8 w-8">
<AvatarFallback>
{c.name.at(0)}
{c.name.at(1)}
</AvatarFallback>
</Avatar>
<CardTitle className="text-base">{c.name}</CardTitle>
</div>
</CardHeader>
<CardContent>
<p>{c.message}</p>
</CardContent>
</Card>
))}
</div>

<Card>
<CardHeader>
<CardTitle>Leave a Comment</CardTitle>
</CardHeader>
<CardContent>
<form className="space-y-4" onSubmit={handleSubmitComment}>
<div className="space-y-2">
<label
htmlFor="name"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Name
</label>
<Input
id="name"
placeholder="Enter your name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="space-y-2">
<label
htmlFor="comment"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Comment
</label>
<Textarea
id="comment"
placeholder="Write your comment here"
value={comment}
onChange={(e) => setComment(e.target.value)}
/>
</div>
<Button>
<Send className="mr-2 h-4 w-4" type="submit" />
Submit Comment
</Button>
</form>
</CardContent>
</Card>
</div>
</>
);
Expand Down
7 changes: 7 additions & 0 deletions client/src/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ interface User {
created_at: Date;
}

type ChatbotComment = {
id: number;
name: string;
message: string;
chatbot_id: number;
};

type Chatbot = {
id: number;
name: string;
Expand Down

0 comments on commit 9549e29

Please sign in to comment.