add group creation.

This commit is contained in:
mohammedzeglam-pg
2024-08-06 18:03:00 +02:00
parent 4e30eda06f
commit afe59f5a3a
3 changed files with 61 additions and 13 deletions

View File

@@ -10,6 +10,8 @@ import {
getDocs,
getDoc,
deleteDoc,
limit,
updateDoc,
} from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
@@ -44,18 +46,23 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
async function post(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) {
const maker = req.session.user;
if (!maker) {
return res
.status(401)
.json({ ok: false, reason: "You must be logged in to make user!" });
}
const { email, passport_id, type } = req.body as {
const { email, passport_id, type, groupName } = req.body as {
email: string;
passport_id: string;
type: string
type: string,
groupName: string
};
createUserWithEmailAndPassword(auth, email.toLowerCase(), passport_id)
// cleaning data
delete req.body.passport_id;
delete req.body.groupName;
await createUserWithEmailAndPassword(auth, email.toLowerCase(), passport_id)
.then(async (userCredentials) => {
const userId = userCredentials.user.uid;
@@ -101,10 +108,45 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
await setDoc(doc(db, "groups", defaultStudentsGroup.id), defaultStudentsGroup);
await setDoc(doc(db, "groups", defaultCorporateGroup.id), defaultCorporateGroup);
}
res.status(200).json({ ok: true });
if(typeof groupName === 'string' && groupName.trim().length > 0){
const q = query(collection(db, "groups"), where("admin", "==", maker.id), where("name", "==", groupName.trim()), limit(1))
const snapshot = await getDocs(q)
if(snapshot.empty){
const values = {
id: v4(),
admin: maker.id,
name: groupName.trim(),
participants: [userId],
disableEditing: false,
}
await setDoc(doc(db, "groups", values.id) , values)
}else{
const doc = snapshot.docs[0]
const participants : string[] = doc.get('participants');
if(!participants.includes(userId)){
updateDoc(doc.ref, {
participants: [...participants, userId]
})
}
}
}
})
.catch((error) => {
console.log(error);
res.status(401).json({error});
return res.status(401).json({error});
});
return res.status(200).json({ ok: true });
}