Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: restrict user to not post a message in the outdated channel #231

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion app/(app)/ActionMenu/Booking/Doctor_details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { supabase } from "@/lib/supabase";
import HeaderComponent from "@/components/HeaderComponent";
import ReviewerCardComponent from "@/components/ReviewerCardComponent";
import { StatusBar } from "expo-status-bar";
import { color } from "react-native-elements/dist/helpers";

interface Doctor{
id: number,
Expand Down Expand Up @@ -548,7 +549,9 @@ const visibleReviews = reviews.slice(0, 1);
)

) : (
<Text style={[Typography.semiBold.large] }> No available reviews</Text>
<Text style={[Typography.semiBold.large,
{color: theme === "dark" ? Colors.others.white : "#212121",}
] }> No available reviews</Text>
)}
</View>
</View>
Expand Down
4 changes: 3 additions & 1 deletion app/(app)/ActionMenu/Booking/Patient-details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@ const PatientDetails = () => {
Write Your Problem
</Text>

<TextArea text={text} onChangeText={setText} />
<TextArea
text={text}
onChangeText={setText} />
</View>

<View
Expand Down
2 changes: 1 addition & 1 deletion app/(app)/ActionMenu/Booking/Select-package.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const SelectPackage = () => {
const { Doctor_id, hour, date,patient_id } = useLocalSearchParams()
const [selectedPackageTitle, setSelectedPackageTitle] = useState<{ title: string, price: string }>({ title: "Messaging", price: "Rwf20" })
const [selectedDuration, setSelectedDuration] = useState<string>("1 hour")
console.log("this is new:", Doctor_id, hour, date)

const handleNextPress = () => {
if (!selectedPackageTitle||!selectedDuration) {
Alert.alert("Please select both Duration and package")
Expand Down
9 changes: 5 additions & 4 deletions app/(app)/ActionMenu/Booking/SelectPayment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ export default function SelectPayment() {

const modal = useModal()
const flutterKey = process.env.EXPO_PUBLIC_FLUTTERWAVE_KEY ?? ""
console.log("this is packageprice from slect Payment:",packagePrice)

interface RedirectParams {
status: "successful" | "cancelled";
Expand Down Expand Up @@ -78,7 +77,7 @@ const total:number=price*num

}
function successBooking() {
router.push("ActionMenu");;
router.push("ActionMenu");
modal.hide();
}
const showSuccefulModal = () => {
Expand Down Expand Up @@ -138,7 +137,10 @@ const total:number=price*num
></View>
<Button
title="View Appointment"
onPress={successBooking}
onPress={()=> {
successBooking()
router.push("(app)/Appointments")
}}
/>
<TouchableOpacity
onPress={() => {
Expand Down Expand Up @@ -174,7 +176,6 @@ const total:number=price*num
}
const handleOnRedirect = (data: RedirectParams) => {

console.log("redire data:", data)
if (data.status === "successful") {
bookAppointment()
showSuccefulModal()
Expand Down
2 changes: 1 addition & 1 deletion app/(app)/ActionMenu/Booking/reviewSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default function Reviewsummary() {
}
fetchDoctordata()
}, [doctor_id])
console.log("this is packagePrice:",packagePrice)

let num:number=1;
if (duration === "30 minutes") {
num=1
Expand Down
13 changes: 8 additions & 5 deletions app/(app)/Appointments/MessagingAppointment/ChannelList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ import React, { useContext, useEffect, useState } from 'react'
import { fetchPatientData } from '@/utils/LoggedInUser';
import { AuthContext } from '@/ctx/AuthContext';
import {
ChannelList
ChannelList,
DefaultStreamChatGenerics
} from 'stream-chat-expo'
import { useAppContext } from '@/ctx/ChatContext';
import { PatientTypes } from '@/constants/Types';
import {useRouter } from 'expo-router';
import { ChannelSort } from 'stream-chat';

const ChannelLists = ({appointmentId}:{appointmentId:any}) => {

const ChannelLists = ({appointmentId, loggedInUserId}:{appointmentId:any, loggedInUserId:string}) => {
const { channel, setChannel } = useAppContext();
const [patientData, setPatientData] = useState<PatientTypes[] | null>(null);
const { userId, } = useContext(AuthContext);
Expand All @@ -28,13 +31,13 @@ const ChannelLists = ({appointmentId}:{appointmentId:any}) => {
};
}

const sort = {last_message_at: -1,};
const sort : ChannelSort<DefaultStreamChatGenerics> = { last_message_at: -1 }

const handleNavigateToChannel = (channel: any) => {
setChannel(channel);
router.push({
pathname: "(app)/Appointments/MessagingAppointment/ChannelScreen",
params: { id: channel?.id, appointmentId },
params: { chanelId: channel?.id, appointmentId, loggedInUserId},
});
};

Expand All @@ -45,7 +48,7 @@ const ChannelLists = ({appointmentId}:{appointmentId:any}) => {
filters={filters}
sort={sort}
/>

)
}

Expand Down
20 changes: 16 additions & 4 deletions app/(app)/Appointments/MessagingAppointment/ChannelScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,31 @@ import { supabase } from "@/lib/supabase";
import { useGlobalSearchParams } from "expo-router";
import Typography from "@/constants/Typography";
import { useModal } from "@/ctx/ModalContext";
import { StreamChat } from "stream-chat";

const ChannelScreen = () => {
const { theme, changeTheme } = useContext(ThemeContext);
const { theme} = useContext(ThemeContext);
const [isloading, setIsLoading] = useState(false);
const ios = Platform.OS === "ios";
const modal = useModal();
const {appointmentId} = useGlobalSearchParams();
const {chanelId,appointmentId, loggedInUserId} = useGlobalSearchParams();
const { channel } = useAppContext();
const API_KEY = process.env.EXPO_PUBLIC_STREAM_API_KEY;

const chatClient = StreamChat.getInstance(`${API_KEY}`);

const disableUser = async () => {
try{
await chatClient.channel('messaging', `${chanelId}`).removeMembers([`${loggedInUserId}`])
}catch(error){
console.log("user not deleted",error);
}
}


const endAppointment = async() => {
try {
disableUser();
setIsLoading(true);
const { error } = await supabase
.from("appointment")
Expand Down Expand Up @@ -126,12 +140,10 @@ const ChannelScreen = () => {
>
<Channel
channel={channel}
// MessageText={MessageStyle}
audioRecordingEnabled={true}
enforceUniqueReaction={true}
giphyEnabled={true}
>

<SafeAreaView style={{ marginBottom: ios ? 10 : 40 }}>
<StatusBar style={theme === "dark" ? "dark" : "dark"} />
</SafeAreaView>
Expand Down
91 changes: 43 additions & 48 deletions app/(app)/Appointments/MessagingAppointment/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,76 +3,71 @@ import { AuthContext } from "@/ctx/AuthContext";
import { useContext, useEffect, useState } from "react";
import { StreamChat } from "stream-chat";
import { fetchPatientData } from "@/utils/LoggedInUser";
import {PatientTypes} from "@/constants/Types";
import { PatientTypes } from "@/constants/Types";
import { useAppContext } from "@/ctx/ChatContext";
import ChannelLists from "./ChannelList";
import uuid from "react-native-uuid";
import {useGlobalSearchParams } from "expo-router";
import { useGlobalSearchParams } from "expo-router";

const API_KEY = process.env.EXPO_PUBLIC_STREAM_API_KEY;
const SECRETE_KEY = process.env.EXPO_PUBLIC_STREAM_API_SECRET;

export function Home() {
const [clientIsReady, setClientIsReady] = useState<boolean>(false);
const [patientData, setPatientData] = useState<PatientTypes[] | null>(null);
const [client, setClient] = useState<StreamChat | null>(null);
const { channel, setChannel } = useAppContext();
const [clientIsReady, setClientIsReady] = useState<boolean>(false);
const [patientData, setPatientData] = useState<PatientTypes[] | null>(null);
const [client, setClient] = useState<StreamChat | null>(null);
const { channel, setChannel } = useAppContext();
const [loggedInUserId , setLoggedInUserId] = useState<string>("");
const { userId } = useContext(AuthContext);
const CDNURL =
"https://vbwbfflzxuhktdvpbspd.supabase.co/storage/v1/object/public/patients/";
const { doctorId, appointmentId } = useGlobalSearchParams();
const chatRoomId = "matadores-medica" + uuid.v4();

useEffect(() => {
if (userId) {
fetchPatientData(userId, setPatientData);
}
}, [userId]);

const { userId } = useContext(AuthContext);

const {id, appointmentId} = useGlobalSearchParams()
const doctorId = id;
const chatRoomId = "matadores-medica"+uuid.v4();

useEffect(() => {
if (userId) {
fetchPatientData(userId, setPatientData);
}
}, [userId]);

const chatClient = StreamChat.getInstance(`${API_KEY}`);
const chatClient = StreamChat.getInstance(`${API_KEY}`);

useEffect(() => {
const setupClient = async () => {
try {
if (patientData && patientData[0]) {
const user = {
id: patientData[0].id,
name: `${patientData[0].first_name} ${patientData[0].last_name}`,
image: "https://i.imgur.com/fR9Jz14.png",
};
try {
if (patientData && patientData[0]) {
setLoggedInUserId(patientData[0].id);
const user = {
id: patientData[0].id,
name: `${patientData[0].first_name} ${patientData[0].last_name}`,
image: `${CDNURL + patientData[0]?.image}`,
};

await chatClient.connectUser(
user,
chatClient.devToken(user.id));
setClientIsReady(true);
setClient(chatClient);
await chatClient.connectUser(user, chatClient.devToken(user.id));

const channel = chatClient.channel("messaging", `${chatRoomId}`, {
image: "https://vbwbfflzxuhktdvpbspd.supabase.co/storage/v1/object/public/doctors/adaptive_icon.png",
name: "Medica Chat Room",
members: [user?.id , `${doctorId}`],
});
await channel.watch();
setChannel(channel);
} else {
console.log("No patient data found");
}
} catch (error) {
console.error("An error occurred while connecting the user:", error);
setClientIsReady(true);
setClient(chatClient);
const channel = chatClient.channel("messaging", `${chatRoomId}`, {
image:
"https://vbwbfflzxuhktdvpbspd.supabase.co/storage/v1/object/public/doctors/adaptive_icon.png",
name: `${user?.name} in the chat`,
members: [user?.id, `${doctorId}`],
});
await channel.watch();
setChannel(channel);
} else {
console.log("No patient data found");
}
} catch (error) {
console.error("An error occurred while connecting the user:", error);
}
};
if (!chatClient.userID) {
setupClient();
}
// if(client){return async()=> await client.disconnectUser()}
}, [patientData]);

return (
<ChannelLists appointmentId={appointmentId}/>
)
return <ChannelLists appointmentId={appointmentId} loggedInUserId={loggedInUserId }/>;
}

export default Home;

7 changes: 2 additions & 5 deletions app/(app)/Appointments/MessagingAppointment/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,6 @@ try {
fetchUserProfile()
}, [loggeduser])




return (
<View
style={{
Expand Down Expand Up @@ -409,7 +406,7 @@ try {
flexDirection: "row",
gap: 10,
},
]}>{appointment.paid ? "(Paid)" : "(not paid)"}</Text>
]}>(Paid)</Text>
</View>
</View>
</View>
Expand All @@ -419,7 +416,7 @@ try {
router.push(
{
pathname: "(app)/Appointments/MessagingAppointment/Home",
params: {id: "1f4c9b93-5d95-427b-93fc-4936e4046454", appointmentId: appointment?.id}
params: {doctorId: appointment?.doctor_id, appointmentId: appointment?.id}
}
)
}
Expand Down
1 change: 1 addition & 0 deletions components/UI/Accordion.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React from "react";
import { BlueDownIcon } from "@/assets/icons/Profile/Icons";
import { Colors } from "@/constants/Colors";
import Typography from "@/constants/Typography";
Expand Down
3 changes: 2 additions & 1 deletion components/UI/DropDown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export default function DropDown({ data, leftIcon, rightIcon, search,defaultValu
flexDirection: "row",
paddingHorizontal: 20,
gap: 20,
backgroundColor: theme === "light" ? Colors.grayScale._50 : Colors.dark._2,
}}
data={data}
maxHeight={300}
Expand Down Expand Up @@ -94,7 +95,7 @@ export default function DropDown({ data, leftIcon, rightIcon, search,defaultValu
)}
itemTextStyle={{
color:
theme === "light" ? Colors.grayScale._900 : Colors.others.white,
theme === "light" ? Colors.grayScale._900 : Colors.main.primary._500,
}}
/>
</>
Expand Down
3 changes: 3 additions & 0 deletions components/UI/TextArea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export default function TextArea({ text,onChangeText }: Props) {
>
<TextInput
placeholder="Describe how you are feeling here..."
placeholderTextColor={
theme === "light" ? Colors.grayScale._500 : Colors.grayScale._400
}
style={[
Typography.semiBold.medium,
{
Expand Down
1 change: 0 additions & 1 deletion utils/LoggedInUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export async function getPatientData(supabase: any, userInfo: any): Promise<any>
return;
}
patentInfo(data);
console.log(data)
} catch (error) {
console.error("Error while fetching data:", error);
return;
Expand Down
Loading