adding workspaces install

This commit is contained in:
Arjun Patel
2022-01-28 14:16:29 -08:00
parent a3e6f7cf5e
commit fdb3b78817
33 changed files with 6642 additions and 3 deletions
+1
View File
@@ -0,0 +1 @@
node_modules
+127
View File
@@ -0,0 +1,127 @@
export enum KeyCode {
Backspace = 8,
Tab = 9,
Enter = 13,
Shift = 16,
Ctrl = 17,
Alt = 18,
PauseBreak = 19,
CapsLock = 20,
Escape = 27,
Space = 32,
PageUp = 33,
PageDown = 34,
End = 35,
Home = 36,
LeftArrow = 37,
UpArrow = 38,
RightArrow = 39,
DownArrow = 40,
Insert = 45,
Delete = 46,
Zero = 48,
ClosedParen = Zero,
One = 49,
ExclamationMark = One,
Two = 50,
AtSign = Two,
Three = 51,
PoundSign = Three,
Hash = PoundSign,
Four = 52,
DollarSign = Four,
Five = 53,
PercentSign = Five,
Six = 54,
Caret = Six,
Hat = Caret,
Seven = 55,
Ampersand = Seven,
Eight = 56,
Star = Eight,
Asterik = Star,
Nine = 57,
OpenParen = Nine,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftWindowKey = 91,
RightWindowKey = 92,
SelectKey = 93,
Numpad0 = 96,
Numpad1 = 97,
Numpad2 = 98,
Numpad3 = 99,
Numpad4 = 100,
Numpad5 = 101,
Numpad6 = 102,
Numpad7 = 103,
Numpad8 = 104,
Numpad9 = 105,
Multiply = 106,
Add = 107,
Subtract = 109,
DecimalPoint = 110,
Divide = 111,
F1 = 112,
F2 = 113,
F3 = 114,
F4 = 115,
F5 = 116,
F6 = 117,
F7 = 118,
F8 = 119,
F9 = 120,
F10 = 121,
F11 = 122,
F12 = 123,
NumLock = 144,
ScrollLock = 145,
SemiColon = 186,
Equals = 187,
Comma = 188,
Dash = 189,
Period = 190,
UnderScore = Dash,
PlusSign = Equals,
ForwardSlash = 191,
Tilde = 192,
GraveAccent = Tilde,
OpenBracket = 219,
ClosedBracket = 221,
Quote = 222
}
+3
View File
@@ -0,0 +1,3 @@
export enum CookieType {
TEAM_SHORTCUTS_ONBOARDING = "TEAM_SHORTCUTS_ONBOARDING",
}
+19
View File
@@ -0,0 +1,19 @@
import moment from "moment";
export function generateGreetings(): string {
const hour = moment().hour();
if (hour > 16) {
return "Good evening";
}
if (hour > 11) {
return "Good afternoon";
}
return "Good morning";
}
export function getTime(date?: Date) {
return date != null ? date.getTime() : 0;
}
+11
View File
@@ -0,0 +1,11 @@
export default function isValidHttpUrl(potentialUrl: string) {
let url;
try {
url = new URL(potentialUrl);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
+18
View File
@@ -0,0 +1,18 @@
import { User, UserStatus } from "../models/user";
function getStatusValue(status: UserStatus) {
switch (status) {
case UserStatus.online:
return 10;
case UserStatus.busy:
return 5;
case UserStatus.offline:
return 0;
default:
return -5;
}
}
export function compareStatus(usera: User, userb: User) {
return getStatusValue(userb.userStatus) - getStatusValue(usera.userStatus);
}
+25
View File
@@ -0,0 +1,25 @@
import { Timestamp } from "firebase/firestore";
export default class Announcement {
id: string;
teamId: string;
audioDataUrl: string; // link to cloud storage file
state: AnnouncementState = AnnouncementState.active;
createdByUserId: string;
createdDate: Timestamp;
lastUpdatedDate: Timestamp;
constructor(_audioUrl: string, _teamId: string, _createdByUserId: string) {
this.audioDataUrl = _audioUrl;
this.createdByUserId = _createdByUserId;
this.teamId = _teamId;
}
}
export enum AnnouncementState {
active = "active",
resolved = "resolved",
deleted = "deleted",
}
@@ -0,0 +1,7 @@
export default interface IFirestoreSerializable {
id: string;
serialize: () => {};
// deserialize: (firestoreData: {}) => {};
}
+87
View File
@@ -0,0 +1,87 @@
import { Timestamp } from "firebase/firestore";
export default class Link {
id: string;
name: string;
description: string;
link: string; //url for file
state: LinkState = LinkState.active;
type: LinkType;
teamId: string;
// if it's not a teamAttachment, then have a list of members who it's for
recipients: string[]; // userIds
createdByUserId: string;
createdDate: Timestamp;
constructor(
_name: string,
_description: string,
_link: string,
_teamId: string,
recipientsArr: string[],
_createdByUserId: string
) {
this.name = _name;
this.description = _description;
this.link = _link;
this.teamId = _teamId;
this.recipients = recipientsArr;
this.createdByUserId = _createdByUserId;
if (!recipientsArr || recipientsArr?.length == 0) {
this.recipients = null;
} else {
this.recipients = recipientsArr;
}
this.type = Link.getLinkType(_link);
}
static getLinkType(url: string): LinkType {
if (url.includes(LinkType.github)) {
return LinkType.github;
} else if (url.includes(LinkType.atlassian)) {
return LinkType.atlassian;
} else if (
url.includes(LinkType.googleDrive) ||
url.includes("docs.google")
) {
return LinkType.googleDrive;
} else if (
url.includes(".png") ||
url.includes(".jpg") ||
url.includes(".svg") ||
url.includes(".gif") ||
url.includes(LinkType.pastePics)
) {
return LinkType.image;
} else if (url.includes(LinkType.pdf)) {
return LinkType.pdf;
} else if (url.includes(LinkType.codePile)) {
return LinkType.codePile;
} else {
return LinkType.default;
}
}
}
export enum LinkState {
active = "active",
archived = "archived",
deleted = "deleted",
}
export enum LinkType {
default = "default",
github = "github",
atlassian = "atlassian",
googleDrive = "drive.google",
onedrive = "onedrive",
image = "image",
pdf = "pdf",
codePile = "codepile",
pastePics = "paste.pics",
}
+15
View File
@@ -0,0 +1,15 @@
import { Timestamp } from "firebase/firestore";
export class Message {
id: string;
audioDataUrl: string;
senderUserId: string;
receiverUserId: string;
senderReceiver: string[]; // composite to make querying easier in the future
createdDate: Timestamp;
// firstListenDate: Timestamp;
}
+37
View File
@@ -0,0 +1,37 @@
import { Timestamp } from "firebase/firestore";
import { v4 as uuidv4 } from "uuid";
export default class OfficeRoom {
id: string = uuidv4();
teamId: string;
name: string; // entrance, kitchen, etc.
createdDate: Timestamp;
createdByUserId: string;
lastUpdatedDate: Timestamp;
members: string[] = []; // id's of users in the office room
state: OfficeRoomState;
constructor(
_name: string,
_teamId: string,
_createdBy: string,
_state: OfficeRoomState = OfficeRoomState.idle
) {
this.name = _name;
this.teamId = _teamId;
this.createdByUserId = _createdBy;
this.state = _state;
}
}
export enum OfficeRoomState {
active = "active",
idle = "idle",
archived = "archived",
}
+50
View File
@@ -0,0 +1,50 @@
import { Timestamp } from "firebase/firestore";
export default class Room {
id: string;
name: string;
description: string;
link: string; // google meet link for now
members: string[] = []; //userIds of "mandatory"/invited people including the person who created it
membersInRoom: string[] = [];
attachments: string[] = []; // the links themselves (NOT Ids)...there will be duplicate entries in the attachments table which will be created
type: RoomType;
status: RoomStatus = RoomStatus.empty;
approximateDateTime: string; // vaguely say when the meeting should be...give user pointers
scheduledDateTime: Timestamp;
// scheduledJsDateTime(): Date {
// return this.scheduledDateTime.toDate();
// }
createdDate: Timestamp;
// createdJsDate(): Date {
// return this.createdDate.toDate();
// }
createdByUserId: string;
teamId: string;
lastUpdatedDate: Timestamp;
}
export enum RoomType {
now = "now",
scheduled = "scheduled", // one time sort of standard meeting
recurring = "recurring", //daily standup
}
export enum RoomStatus {
live = "live",
empty = "empty",
archived = "archived", // user marks it over
}
+30
View File
@@ -0,0 +1,30 @@
import { Timestamp } from "firebase/firestore";
export class Team {
id: string;
name: string;
status: TeamStatus;
allowedUserCount: number = 2;
// subscriptionPlan: TeamSubscriptionPlan = TeamSubscriptionPlan.basic
companySite: string;
createdByUserId: string;
createdDate: Timestamp;
lastUpdatedDate: Timestamp;
}
export enum TeamStatus {
created = "created",
deactivated = "deactivated",
deleted = "deleted",
}
export enum TeamSubscriptionPlan {
free = "free",
basic = "basic",
pro = "pro",
}
+26
View File
@@ -0,0 +1,26 @@
import { Timestamp } from "firebase/firestore";
export class TeamMember {
id: string;
userId: string;
teamId: string;
inviteEmailAddress: string;
invitedByUserId: string;
role: TeamMemberRole
status: TeamMemberStatus
createdDate: Timestamp
lastUpdatedDate: Timestamp
}
export enum TeamMemberRole {
admin = "admin"
}
export enum TeamMemberStatus {
invited = "invited",
activated = "activated",
deleted = "deleted"
}
+40
View File
@@ -0,0 +1,40 @@
import {
documentId,
Firestore,
serverTimestamp,
Timestamp,
} from "firebase/firestore";
import IFirestoreSerializable from "./firestoreSerializable";
export class User {
id: string;
emailAddress: string;
nickName: string;
firstName: string;
lastName: string;
avatarUrl: string;
userStatus: UserStatus;
/**designer? dev? */
teamRole: string;
createdDate: Timestamp;
lastUpdatedDate: Timestamp;
// serialize() {
// return {
// createdDate: Timestamp.fromDate(this.createdDate),
// lastUpdatedDate: Timestamp.fromDate(this.lastUpdatedDate)
// }
// }
// deserialize(firestoreData: {}) {
// this.lastUpdatedDate = firestoreData.lastUpdatedDate.toDate()
// }
}
export enum UserStatus {
online = "online",
offline = "offline",
busy = "busy",
}
+5
View File
@@ -0,0 +1,5 @@
import { Firestore } from "firebase/firestore";
export default interface IService {
db: Firestore;
}
+94
View File
@@ -0,0 +1,94 @@
import AgoraRTC, {
ClientConfig,
IAgoraRTCRemoteUser,
ICameraVideoTrack,
IMicrophoneAudioTrack,
} from "agora-rtc-sdk-ng";
// import {
// AgoraVideoPlayer,
// createClient,
// createMicrophoneAndCameraTracks,
// createMicrophoneAudioTrack,
// } from "agora-rtc-react";
import { getFunctions, httpsCallable } from "firebase/functions";
import toast from "react-hot-toast";
const config: ClientConfig = {
mode: "rtc",
codec: "vp8",
};
// const useClient = createClient(config);
// const useMicrophoneTracks = createMicrophoneAudioTrack();
// TODO: move this to env file
const appId: string = "c8dfd65deb5c4741bd564085627139d0"; //ENTER APP ID HERE
export default class AgoraService {
private functions = getFunctions();
// private rtcClient = useClient();
async getAgoraToken(channelName: string): Promise<string> {
const cfResult = httpsCallable(this.functions, "agoraToken");
return await cfResult({ channelName })
.then((result: { data: { token: string } }) => {
const data = result.data;
if (!data.token) {
throw new Error("No token retrieved from agora");
}
return data.token;
})
.catch((error) => {
// Getting the Error details.
const code = error.code;
const message = error.message;
const details = error.details;
throw error;
});
}
// async handleJoinChannel(channelName: string, agoraToken: string) {
// const localTrack: IMicrophoneAudioTrack =
// await AgoraRTC.createMicrophoneAudioTrack();
// let init = async (name: string) => {
// this.rtcClient.on("user-published", async (user, mediaType) => {
// await this.rtcClient.subscribe(user, mediaType);
// console.log("subscribe success");
// if (mediaType === "audio") {
// user.audioTrack?.play();
// }
// });
// this.rtcClient.on("user-unpublished", async (user, type) => {
// console.log("unpublished", user, type);
// if (type === "audio") {
// user.audioTrack?.stop();
// }
// await this.rtcClient.unsubscribe(user);
// });
// this.rtcClient.on("user-left", (user) => {
// console.log("user left", user);
// });
// await this.rtcClient.join(appId, name, agoraToken, null);
// if (localTrack) await this.rtcClient.publish(localTrack);
// };
// if (localTrack) {
// console.log("init ready");
// init(channelName);
// } else {
// toast.error("Not ready for joining call");
// return;
// }
// }
}
export { appId };
@@ -0,0 +1,27 @@
import {
addDoc,
collection,
doc,
Firestore,
getFirestore,
serverTimestamp,
setDoc,
} from "firebase/firestore";
import { AnnouncementState } from "../models/announcement";
import { Collections } from "./collections";
export class AnnouncementService {
private db: Firestore = getFirestore();
async updateAnnouncementState(
announcementId: string,
newState: AnnouncementState
) {
const docRef = doc(this.db, Collections.announcements, announcementId);
await setDoc(
docRef,
{ state: newState, lastUpdatedDate: serverTimestamp() },
{ merge: true }
);
}
}
+23
View File
@@ -0,0 +1,23 @@
/**
*
* wrapper for authentication for the future for each individual component
*/
export function requireAuthentication(gssp) {
return async (context) => {
const { req, res } = context;
const token = req.cookies.userToken;
if (!token) {
// Redirect to login page
return {
redirect: {
destination: '/admin/login',
statusCode: 302
}
};
}
return await gssp(context); // Continue on to call `getServerSideProps` logic
}
}
@@ -0,0 +1,75 @@
import {
getDownloadURL,
getStorage,
ref,
uploadBytesResumable,
} from "firebase/storage";
export default class CloudStorageService {
private storage = getStorage();
/**
* return the
*/
async uploadMessageAudioFile(audioFile: File): Promise<string> {
// Create the file metadata
/** @type {any} */
const metadata = {
contentType: "audio/mpeg",
};
// Upload file and metadata to the object 'images/mountains.jpg'
const storageRef = ref(this.storage, "messages/" + audioFile.name);
const uploadTask = uploadBytesResumable(storageRef, audioFile, metadata);
// Listen for state changes, errors, and completion of the upload.
return new Promise((resolve, reject) => {
uploadTask.on(
"state_changed",
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("Upload is " + progress + "% done");
switch (snapshot.state) {
case "paused":
console.log("Upload is paused");
break;
case "running":
console.log("Upload is running");
break;
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
reject(new Error(error.message));
switch (error.code) {
case "storage/unauthorized":
// User doesn't have permission to access the object
break;
case "storage/canceled":
// User canceled the upload
break;
// ...
case "storage/unknown":
// Unknown error occurred, inspect error.serverResponse
break;
}
},
() => {
// Upload completed successfully, now we can get the download URL
return getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log("File available at", downloadURL);
return resolve(downloadURL);
});
}
);
});
}
}
+13
View File
@@ -0,0 +1,13 @@
export enum Collections {
users = "users",
teams = "teams",
teamMembers = "teamMembers",
teamSubscriptions = "teamSubscriptions",
audioMessages = "audioMessages",
rooms = "rooms",
announcements = "announcements",
links = "links",
officeRooms = "officeRooms",
}
@@ -0,0 +1,15 @@
import firebaseAdmin from "firebase-admin/app";
import serviceAccount from "../nirvana-for-business-firebase-adminsdk";
const adminApp = firebaseAdmin.initializeApp({
credential: credential.cert({
privateKey: serviceAccount.private_key,
clientEmail: serviceAccount.client_email,
projectId: serviceAccount.project_id,
}),
});
console.log("initialized firebase admin");
export { adminApp };
@@ -0,0 +1,60 @@
// const firebaseConfig = {
// apiKey: process.env.NEXT_PUBLIC_FIREBASE_APIKEY,
// authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
// projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
// storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
// messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
// appId: process.env.NEXT_PUBLIC_APPID,
// measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
// };
// Import the functions you need from the SDKs you need
import * as firebase from "firebase/app";
// import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";
import {
browserSessionPersistence,
getAuth,
setPersistence,
} from "firebase/auth";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyAr3iEcoduqDv0IW9czwmt3Yqp5StZED0w",
authDomain: "nirvana-for-business.firebaseapp.com",
projectId: "nirvana-for-business",
storageBucket: "nirvana-for-business.appspot.com",
messagingSenderId: "825654222284",
appId: "1:825654222284:web:0778c8883de21917b51169",
measurementId: "G-MB5G7G09MR",
};
// Initialize Firebase
// if (typeof window !== "undefined") {
const app = firebase.initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);
console.log("initialized firebase");
setPersistence(getAuth(), browserSessionPersistence);
// }
// import { credential } from 'firebase-admin';
// import { initializeApp } from 'firebase-admin/app';
// import serviceAccount from '../nirvana-for-business-firebase-adminsdk'
// if(typeof window === 'undefined') {
// console.log('initializing firebase admin')
// initializeApp({
// credential: credential.cert({
// privateKey: serviceAccount.private_key,
// clientEmail: serviceAccount.client_email,
// projectId: serviceAccount.project_id,
// })
// });
// }
+24
View File
@@ -0,0 +1,24 @@
import {
addDoc,
collection,
doc,
Firestore,
getFirestore,
serverTimestamp,
setDoc,
} from "firebase/firestore";
import Link, { LinkState } from "../models/link";
import { Collections } from "./collections";
export class LinkService {
private db: Firestore = getFirestore();
async updateLinkState(linkId: string, newState: LinkState) {
const docRef = doc(this.db, Collections.links, linkId);
await setDoc(
docRef,
{ state: newState, lastUpdatedDate: serverTimestamp() },
{ merge: true }
);
}
}
@@ -0,0 +1,93 @@
import {
addDoc,
collection,
doc,
FieldValue,
Firestore,
getFirestore,
serverTimestamp,
setDoc,
writeBatch,
} from "firebase/firestore";
import OfficeRoom, { OfficeRoomState } from "../models/officeRoom";
// import AgoraService from "./agoraService";
import { Collections } from "./collections";
export default class OfficeRoomService {
private db: Firestore = getFirestore();
private batch = writeBatch(this.db);
// private agoraService = new AgoraService();
async createInitialOfficeRooms(createdByUserId: string, teamId: string) {
const entrance = new OfficeRoom("Entrance", teamId, createdByUserId);
const kitchen = new OfficeRoom("Kitchen", teamId, createdByUserId);
const hallway = new OfficeRoom("Hallway", teamId, createdByUserId);
const corner = new OfficeRoom("Corner", teamId, createdByUserId);
const main = new OfficeRoom("Team Hub", teamId, createdByUserId);
const handsOnDeck = new OfficeRoom(
"All Hands On Deck",
teamId,
createdByUserId
);
const initialORs: OfficeRoom[] = [
entrance,
kitchen,
hallway,
corner,
main,
handsOnDeck,
];
initialORs.forEach((oR) => {
const oRRef = doc(this.db, Collections.officeRooms, oR.id);
this.batch.set(oRRef, { ...oR, createdDate: serverTimestamp() });
});
await this.batch.commit();
}
async joinOfficeRoom(officeRoom: OfficeRoom, userId: string) {
// get agoraToken
// const agoraToken = await this.agoraService.getAgoraToken();
// join channel
// await this.agoraService.handleJoinChannel(officeRoom.id, agoraToken);
// update members list in firestore
const newMembers = [...officeRoom.members, userId];
await this.updateMembersInOfficeRoom(officeRoom.id, newMembers);
}
async updateMembersInOfficeRoom(
officeRoomId: string,
newMembersInRoom: string[]
) {
// if the room is going to be empty, then change status accordingly
var state: OfficeRoomState = OfficeRoomState.active;
if (newMembersInRoom.length == 0) {
state = OfficeRoomState.idle;
}
const docRef = doc(this.db, Collections.officeRooms, officeRoomId);
await setDoc(
docRef,
{
state,
members: newMembersInRoom,
lastUpdatedDate: serverTimestamp(),
},
{ merge: true }
);
}
// async updateRoom(room: Room) {
// const docRef = doc(this.db, Collections.rooms, room.id);
// await setDoc(
// docRef,
// { ...room, lastUpdatedDate: serverTimestamp() },
// { merge: true }
// );
// }
}
+56
View File
@@ -0,0 +1,56 @@
import {
addDoc,
collection,
doc,
Firestore,
getFirestore,
serverTimestamp,
setDoc,
} from "firebase/firestore";
import Room, { RoomStatus } from "../models/room";
import { Collections } from "./collections";
export default class RoomService {
private db: Firestore = getFirestore();
async createOrUpdateRoom(room: Room) {
if (room.id) {
//update
await this.updateRoom(room);
} else {
//create
const roomDocRef = await addDoc(collection(this.db, Collections.rooms), {
...room,
createdDate: serverTimestamp(),
});
}
}
async updateMembersInRoom(roomId: string, newMembersInRoom: string[]) {
// if the room is going to be empty, then change status accordingly
var status: RoomStatus = RoomStatus.live;
if (newMembersInRoom.length == 0) {
status = RoomStatus.empty;
}
const docRef = doc(this.db, Collections.rooms, roomId);
await setDoc(
docRef,
{
status,
membersInRoom: newMembersInRoom,
lastUpdatedDate: serverTimestamp(),
},
{ merge: true }
);
}
async updateRoom(room: Room) {
const docRef = doc(this.db, Collections.rooms, room.id);
await setDoc(
docRef,
{ ...room, lastUpdatedDate: serverTimestamp() },
{ merge: true }
);
}
}
+42
View File
@@ -0,0 +1,42 @@
import {
addDoc,
collection,
Firestore,
getFirestore,
serverTimestamp,
} from "firebase/firestore";
import Announcement from "../models/announcement";
import Link from "../models/link";
import { Message } from "../models/message";
import { Collections } from "./collections";
export class SendService {
private db: Firestore = getFirestore();
async sendMessage(message: Message) {
// do quick stuff to create the composite for easier future querying
message.senderReceiver = [message.senderUserId, message.receiverUserId];
const teamDocRef = await addDoc(
collection(this.db, Collections.audioMessages),
{
...message,
createdDate: serverTimestamp(),
}
);
}
async sendLink(link: Link) {
await addDoc(collection(this.db, Collections.links), {
...link,
createdDate: serverTimestamp(),
});
}
async sendAnnouncement(announcement: Announcement) {
await addDoc(collection(this.db, Collections.announcements), {
...announcement,
createdDate: serverTimestamp(),
});
}
}
+297
View File
@@ -0,0 +1,297 @@
import {
addDoc,
collection,
doc,
DocumentReference,
Firestore,
getDoc,
getDocs,
getFirestore,
orderBy,
query,
serverTimestamp,
setDoc,
where,
} from "firebase/firestore";
import { Team } from "../models/team";
import {
TeamMember,
TeamMemberRole,
TeamMemberStatus,
} from "../models/teamMember";
import { Collections } from "./collections";
import IService from "./IService";
export default class TeamService implements IService {
db: Firestore = getFirestore();
async createTeam(team: Team): Promise<string> {
// create team
const teamDocRef = await addDoc(collection(this.db, Collections.teams), {
...team,
createdDate: serverTimestamp(),
});
const teamMember = new TeamMember();
teamMember.role = TeamMemberRole.admin;
teamMember.teamId = teamDocRef.id;
teamMember.userId = team.createdByUserId;
teamMember.status = TeamMemberStatus.activated;
// create team member as admin who created the team
const teamMemberRef = await addDoc(
collection(this.db, Collections.teamMembers),
{
...teamMember,
createdDate: serverTimestamp(),
}
);
console.log("created team");
return teamDocRef.id;
}
async updateTeam(team: Team) {
const docRef = doc(this.db, Collections.teams, team.id);
await setDoc(
docRef,
{ ...team, lastUpdatedDate: serverTimestamp() },
{ merge: true }
);
}
async getTeam(teamId: string): Promise<Team | null> {
const docRef = doc(this.db, Collections.teams, teamId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("got team data");
let team: Team = docSnap.data() as Team;
team.id = docSnap.id;
return team;
} else {
// doc.data() will be undefined in this case
console.log("team not found!");
return null;
}
}
async getTeamMemberByUserId(
teamId: string,
userId: string
): Promise<TeamMember | null> {
const q = query(
collection(this.db, Collections.teamMembers),
where("teamId", "==", teamId),
where("userId", "==", userId)
);
const querySnapshot = await getDocs(q);
if (querySnapshot.size > 1) {
console.log(
"there are multiple teammembers for this user...error in teamservice"
);
}
var teamMember: TeamMember | null = null;
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
// get the first one and just return...shouldn't be more
console.log("got teammember data");
teamMember = doc.data() as TeamMember;
teamMember.id = doc.id;
});
return teamMember;
}
async getTeamMemberByEmailInvite(
teamId: string,
emailAddress: string
): Promise<TeamMember | null> {
const q = query(
collection(this.db, Collections.teamMembers),
where("teamId", "==", teamId),
where("inviteEmailAddress", "==", emailAddress)
);
const querySnapshot = await getDocs(q);
if (querySnapshot.size > 1) {
console.log(
"there are multiple teammembers for this user...error in teamservice"
);
}
var teamMember: TeamMember | null = null;
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
// get the first one and just return...shouldn't be more
console.log("got teammember data");
teamMember = doc.data() as TeamMember;
teamMember.id = doc.id;
});
return teamMember;
}
async getTeamMembersByEmailInvite(
emailAddress: string
): Promise<TeamMember[]> {
const q = query(
collection(this.db, Collections.teamMembers),
where("inviteEmailAddress", "==", emailAddress)
);
const querySnapshot = await getDocs(q);
var teamMembers: TeamMember[] = [];
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
// get the first one and just return...shouldn't be more
console.log("got teammember data");
let teamMember: TeamMember = doc.data() as TeamMember;
teamMember.id = doc.id;
teamMembers.push(teamMember);
});
return teamMembers;
}
async getTeamMembersByUserId(userId: string): Promise<TeamMember[]> {
const q = query(
collection(this.db, Collections.teamMembers),
where("userId", "==", userId)
);
const querySnapshot = await getDocs(q);
if (querySnapshot.size > 1) {
console.log("this user is part of multiple teams");
}
var teamMembers: TeamMember[] = [];
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
// get the first one and just return...shouldn't be more
console.log("got teammember data");
let teamMember: TeamMember = doc.data() as TeamMember;
teamMember.id = doc.id;
teamMembers.push(teamMember);
});
return teamMembers;
}
async getTeamMembersByTeamId(teamId: string): Promise<TeamMember[]> {
const q = query(
collection(this.db, Collections.teamMembers),
where("teamId", "==", teamId)
);
const querySnapshot = await getDocs(q);
var teamMembers: TeamMember[] = [];
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
// get the first one and just return...shouldn't be more
let teamMember: TeamMember = doc.data() as TeamMember;
teamMember.id = doc.id;
teamMembers.push(teamMember);
});
return teamMembers;
}
async updateTeamMember(teamMember: TeamMember) {
const docRef = doc(this.db, Collections.teamMembers, teamMember.id);
await setDoc(
docRef,
{ ...teamMember, lastUpdatedDate: serverTimestamp() },
{ merge: true }
);
}
async createTeamInvite(teamMember: TeamMember) {
if (teamMember.status == TeamMemberStatus.activated) {
console.log('cannot invite this user, already active.')
return
}
// if a person was already invited, then update that record, otherwise create a new one
const existingTeamMember = await this.getTeamMemberByEmailInvite(
teamMember.teamId,
teamMember.inviteEmailAddress
);
if (!existingTeamMember) {
const teamMemberRef = await addDoc(
collection(this.db, Collections.teamMembers),
{
...teamMember,
createdDate: serverTimestamp(),
}
);
return;
}
// just update the current user to active since we are activating again
await this.updateTeamMemberStatus(
existingTeamMember.id,
TeamMemberStatus.invited
);
}
async updateTeamMemberStatus(teamMemberId: string, status: TeamMemberStatus) {
const docRef = doc(this.db, Collections.teamMembers, teamMemberId);
await setDoc(
docRef,
{ status, lastUpdatedDate: serverTimestamp() },
{ merge: true }
);
}
async getActiveOrInvitedTeamsbyUser(
userId: string,
email: string
): Promise<Team[]> {
// get all of the teammember entries for the user
const userTeamMembers = await this.getTeamMembersByUserId(userId);
const userTeamMembersByEmail = await this.getTeamMembersByEmailInvite(
email
);
// traverse through and get the teams for each
var teams: Promise<Team>[];
if (userTeamMembers) {
teams = userTeamMembers.map(async (tm) => {
if (tm.status != TeamMemberStatus.deleted) {
let team = await this.getTeam(tm.teamId);
return team;
}
});
}
var invitedToTeams: Promise<Team>[] = [];
invitedToTeams = userTeamMembersByEmail
.filter((tm) => tm.status == TeamMemberStatus.invited)
.map(async (tm) => {
let team = await this.getTeam(tm.teamId);
return team;
});
return Promise.all([...teams, ...invitedToTeams]);
}
}
+77
View File
@@ -0,0 +1,77 @@
import { User as FirUser } from "firebase/auth";
import {
Firestore,
getFirestore,
doc,
getDoc,
setDoc,
Timestamp,
serverTimestamp,
onSnapshot,
Unsubscribe,
DocumentSnapshot,
} from "firebase/firestore";
import { User, UserStatus } from "../models/user";
import { Collections } from "./collections";
export default class UserService {
private db: Firestore = getFirestore();
// give back the avatar based on the person's google account avatar
getUserAvatar(displayName: string) {
return `https://ui-avatars.com/api/?name=${displayName}`;
}
async getUser(userId: string): Promise<User | null> {
const docRef = doc(this.db, Collections.users, userId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("got user data");
let user: User = docSnap.data() as User;
return user;
} else {
// doc.data() will be undefined in this case
console.log("user not found!");
return null;
}
}
async getUserRealtime(userId: string): Promise<Unsubscribe> {
const docRef = doc(this.db, Collections.users, userId);
const unsub = onSnapshot(docRef, (doc) => {
console.log(doc.data());
});
return unsub;
}
async createUser(userId: string, emailAddress: string, avatarUrl: string) {
const docRef = doc(this.db, Collections.users, userId);
await setDoc(
docRef,
{ emailAddress, avatarUrl, createdDate: serverTimestamp() },
{ merge: true }
);
}
async updateUser(user: User) {
const docRef = doc(this.db, Collections.users, user.id);
await setDoc(
docRef,
{ ...user, lastUpdatedDate: serverTimestamp() },
{ merge: true }
);
}
async updateUserStatus(userId: string, newStatus: UserStatus) {
const docRef = doc(this.db, Collections.users, userId);
await setDoc(
docRef,
{ userStatus: newStatus, lastUpdatedDate: serverTimestamp() },
{ merge: true }
);
}
}
+3 -2
View File
@@ -1,5 +1,5 @@
{
"name": "functions",
"name": "@nirvana/functions",
"scripts": {
"lint": "eslint --ext .js,.ts .",
"build": "npm run lint && tsc",
@@ -19,7 +19,8 @@
"@sendgrid/mail": "^7.6.0",
"agora-access-token": "^2.0.4",
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1"
"firebase-functions": "^3.14.1",
"@nirvana/common": "1.0.0"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^3.9.1",
+10
View File
@@ -0,0 +1,10 @@
{
"name": "nirvana",
"version": "1.0.0",
"main": "index.js",
"repository": "https://github.com/talksik/nirvana.git",
"author": "Arjun Patel <patel.arjun50@gmail.com>",
"license": "MIT",
"private": true,
"workspaces": ["packages/*"]
}
+3 -1
View File
@@ -1,5 +1,6 @@
{
"name": "nirvana",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -23,7 +24,8 @@
"react-hotkeys": "^2.0.0",
"react-icons": "^4.3.1",
"react-moment": "^1.1.1",
"uuid": "^8.3.2"
"uuid": "^8.3.2",
"@nirvana/common": "1.0.0"
},
"devDependencies": {
"@types/react": "^17.0.38",
+5229
View File
File diff suppressed because it is too large Load Diff