File size: 7,073 Bytes
68715d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

// Feedback Modal POP-UP on Back Button
backButton.addEventListener("click", async function(event){
  console.log("Back button clicked");
  event.preventDefault();

  if(!currentZoneId){
    console.log("no configuration selected, going back directly")
    window.location.href = `/notebook/?effort_id=${effortId}&user_id=${userId}`;
    return;
  }

  console.log("Debug BackBtn:", {userId, notebookId, currentZoneId, effortId});
  try {
    console.log("Checking user feedback eligibility...");
    // CHANGED/ADDED: Fetch eligibility data from the server
    const response = await fetch(`/chat_feature/user_feedback_eligibility?user_id=${userId}&notebook_id=${notebookId}&zone_id=${currentZoneId}`);
    const data = await response.json();

    if (data.eligible_for_feedback) {
      console.log("User is eligible for feedback:", data);
      // CHANGED/ADDED: Initialize the modal here
      if(data.has_feedback){
        document.getElementById("feedbackLevel").value = data.rating ||"";
        document.getElementById("comment").value = data.comment ||"";
        document.getElementById("updateNotice").style.display = "block";
      }
      else{
        document.getElementById("feedbackLevel").value = data.rating ||"";
        document.getElementById("comment").value = data.comment ||"";
        document.getElementById("updateNotice").style.display = "none";
      }
      // CHANGED/ADDED: Now modal will always be initialized and ready here
      
      console.log(bootstrapFeedbackModal);
      if (bootstrapFeedbackModal) {
        console.log("Showing feedback modal");
        bootstrapFeedbackModal.show();
      } else {
        alert("Feedback modal not initialized!");
      }
    } else {
      console.log("User is not eligible for feedback:", data);
      window.location.href = `/notebook/?effort_id=${effortId}&user_id=${userId}`;
    }
  } catch (error) {
    console.error('Error checking eligibility:', error);
    window.location.href = `/notebook/?effort_id=${effortId}&user_id=${userId}`;
  }
});

// Feedback Submit 
document.getElementById("submitFeedback").addEventListener("click", async function () {
  const rating = document.getElementById("feedbackLevel").value;
  const comment = document.getElementById("comment").value;

  const payload = {
    user_id: userId,
    notebook_id: parseInt(notebookId),
    effort_id: parseInt(effortId),
    zone_id: parseInt(currentZoneId),
    rating: rating ? parseInt(rating) : null,
    comment: comment
  };

  try {
    const response = await fetch("/chat_feature/submit_feedback", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    if (response.ok) {
      bootstrapFeedbackModal.hide();
      window.location.href = `/notebook/?effort_id=${effortId}&user_id=${userId}`;
    } else {
      alert("Error submitting feedback");
    }
  } catch (error) {
    console.error("Error submitting feedback:", error);
    alert("Error submitting feedback");
  }
});

// Skip feedback
document.getElementById("skipFeedback").addEventListener("click", function () {
  bootstrapFeedbackModal.hide();
  window.location.href = `/notebook/?effort_id=${effortId}&user_id=${userId}`;
});  ------

# #-------to post the feedback data-------
@chat_feature_bp.route('/submit_feedback', methods=['POST'])
@login_required
def submit_feedback():
    data = request.json
    print(data)
    feedback_payload = {
        "user_id": data.get("user_id"),
        "notebook_id": data.get("notebook_id"),
        "effort_id": data.get("effort_id"),
        "zone_id": data.get("zone_id"),
        "rating": data.get("rating"),
        "comment": data.get("comment"),
    }

    response =  requests.post("http://localhost:8044/feedback/", json = feedback_payload)
   
    print("Recieved Feedback", feedback_payload)

    return jsonify(response.json()),response.status_code

@chat_feature_bp.route("/user_feedback_eligibility", methods=["GET"])
@login_required
def user_feedback_eligibility():
    user_id = request.args.get("user_id")
    notebook_id = request.args.get("notebook_id")
    zone_id = request.args.get("zone_id")

    if not zone_id:
        return jsonify({"eligible_for_feedback": False})

    try:
        notebook_response = requests.get(f"http://localhost:8044/user/get_notebook_details/{notebook_id}")
        notebook_response.raise_for_status()
        chat_data = notebook_response.json().get('chat', {}).get('message', [])
        eligible = len(chat_data) > 0
    except Exception as e:
        print(f"Error fetching notebook details: {e}")
        return jsonify({"eligible_for_feedback": False, "error": "notebook fetch failed"}), 500

    try:
        feedback_response = requests.get(
            "http://localhost:8044/feedback/",
            params={"user_id": user_id, "notebook_id": notebook_id, "zone_id": zone_id}
        )
        feedback_data = feedback_response.json() if feedback_response.ok else {"exists": False}
    except Exception as e:
        print(f"Error fetching feedback: {e}")
        feedback_data = {"exists": False}

    response = {
        "eligible_for_feedback": eligible,
        "has_feedback": feedback_data.get("exists", False)
    }

    if feedback_data.get("exists"):
        response.update({
            "rating": feedback_data.get("rating"),
            "comment": feedback_data.get("comment")
        })
    print("User feedback eligibility response:", response)
    return jsonify(response) ---> this is flask ui python file and  #created a api to call that create_feedback function-------
@router.post("/feedback/")
async def create_feedback_endpoint(feedback: Feedback): 
    try:
        # result = create_feedback(user_id= feedback.user_id, notebook_id= feedback.notebook_id, effort_id= feedback.effort_id, rating= feedback.rating, comment= feedback.comment)
        
        create_or_update_feedback(
            user_id=feedback.user_id,
            notebook_id=feedback.notebook_id,
            effort_id=feedback.effort_id,
            zone_id=feedback.zone_id,
            rating=feedback.rating,
            comment=feedback.comment
        )
        
        return {"message": "Feedback submitted successfully"}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail="Failed to submit feedback")

@router.get("/feedback/")
async def get_existing_feedback(user_id: str, notebook_id: str, zone_id: str):
    try:
        feedback= get_feedback(user_id, notebook_id, zone_id)
        if feedback:
            return{"exists": True, "rating": feedback["rating"], "comment": feedback["comment"]}
        else:
            return{"exists": False}
    except Exception as e:
        raise HTTPException(status_code=500, details="Failed to fetch feedback") --> this my backend api endpoint with class #feedbackModal class
class Feedback(BaseModel):
    user_id: str
    notebook_id: str
    effort_id: str
    zone_id: str
    #rating: Optional[str] = None
    rating: Optional[int] = None
    comment: Optional[str] = None