Skip to content

Commit

Permalink
db POST refactor done
Browse files Browse the repository at this point in the history
  • Loading branch information
Jessica Ho authored and Jessica Ho committed Feb 15, 2024
1 parent 816ea23 commit 0b557c9
Show file tree
Hide file tree
Showing 24 changed files with 539 additions and 501 deletions.
8 changes: 0 additions & 8 deletions src/lib/components/Calendar/ScheduleTable.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -125,16 +125,12 @@
on:click={() => {
markRowAsUnavailable({
i,
displayedRows: rows,
openedRows,
status: AvailabilityStatus.BUSY
});
}}
on:keyup={() =>
markRowAsUnavailable({
i,
displayedRows: rows,
openedRows,
status: AvailabilityStatus.BUSY
})}
class="busy"
Expand All @@ -147,15 +143,11 @@
on:click={() =>
markRowAsUnavailable({
i,
displayedRows: rows,
openedRows,
status: AvailabilityStatus.UNSPECIFIED
})}
on:keyup={() =>
markRowAsUnavailable({
i,
displayedRows: rows,
openedRows,
status: AvailabilityStatus.UNSPECIFIED
})}
>
Expand Down
302 changes: 1 addition & 301 deletions src/lib/server/db.ts
Original file line number Diff line number Diff line change
@@ -1,124 +1,6 @@
import { error } from '@sveltejs/kit';

import { AvailabilityStatus, type Pronoun } from '@prisma/client';
import type { User } from '@prisma/client';
import { dateTo12Hour, toLocalTimezone } from '../date';
import { dateNotes } from './sanitize';
import prisma from '$lib/prisma';
import { findHouseConnection, getHousehold, getUserAttrsInHousehold } from './shared';
import { sendMsg } from './twilio';
import { DAYS } from '$lib/constants';
import { destructRange } from '$lib/parse';
import { generateFullSchedule } from '$lib/format';

async function findHouseholdInvite(reqId: number) {
return await prisma.joinHouseholdRequest.findUnique({
where: {
id: reqId
}
});
}

async function deleteHouseholdInvite(req: { id: number }, user: User) {
const { id } = req;

const invite = await findHouseholdInvite(id);
if (!invite || invite.targetPhone !== user.phone) {
throw error(401, {
message: "You can't delete a household invite that wsan't issued to you"
});
}

await prisma.joinHouseholdRequest.delete({
where: {
id
}
});
}

async function acceptHouseholdInvite(req: { id: number }, user: User) {
const { id } = req;
const invite = await findHouseholdInvite(id);
const { phone, householdId: userHouseholdId } = user;

if (!invite || invite.targetPhone !== phone) {
throw error(401, {
message: "You can't accept a household invite that wasn't issued to you"
});
}

// if part of existing household, then don't accept
if (userHouseholdId)
throw error(400, {
message: 'You are still part of a household!'
});

const { householdId: newHouseholdId } = invite;
await prisma.user.update({
where: {
phone
},
data: {
householdId: newHouseholdId
}
});

// don't need to worry about household invites from diff users in the household
// bc we prevent that when issuing household invites
await deleteHouseholdInvite({ id }, user);

// delete any leftover reqs from this same household
const friendReqs = await prisma.friendRequest.findMany({
where: {
fromHouseholdId: newHouseholdId,
targetPhone: phone
}
});
console.log('leftover friendReqs', friendReqs);
return await Promise.all(friendReqs.map((x) => deleteFriendReq({ reqId: x.id }, user)));
}


async function deleteFriend(req: { connectionId: number }, user: User) {
const friend = await prisma.householdConnection.findUnique({
where: {
id: req.connectionId
}
});

const { householdId: hId } = user;
if (!friend || (friend.householdId !== hId && friend.friendHouseholdId !== hId)) {
throw error(401, {
message: "You can't delete a household connection that you're not a part of"
});
}

await prisma.householdConnection.delete({
where: {
id: req.connectionId
}
});
}





async function deleteFriendReq(req: { reqId: number }, user: User) {
const friendReq = await findFriendReq(req.reqId);
if (!friendReq || friendReq.targetPhone !== user.phone) {
throw error(401, {
message: "Can't delete friend request not issued to you"
});
}
return await prisma.friendRequest.delete({
where: {
id: req.reqId
}
});
}



async function deleteKid(req: { id: number }, user: User) {
const { id } = req;
Expand Down Expand Up @@ -256,139 +138,6 @@ async function removeHouseholdAdult(req: { id: number }, user: User) {
});
}

async function sendFaqLinks(
adults1: { phone: string }[],
adults2: { phone: string }[],
household1: { name: string; id: number },
household2: { name: string; id: number },
initiator: User
) {
// go through each number and send the FAQ links
return await Promise.all([
...adults1.map(async ({ phone }: { phone: string }) =>
sendMsg(
{
phone,
type: 'householdFaq',
otherHouseholdName: household2.name,
otherHouseholdId: household2.id
},
initiator
)
),
...adults2.map(async ({ phone }: { phone: string }) =>
sendMsg(
{
phone,
type: 'householdFaq',
otherHouseholdName: household1.name,
otherHouseholdId: household1.id
},
initiator
)
)
]);
}

async function getHouseholdsFullSched(householdId: number, user: { timeZone: string }) {
const now = new Date();
const startDate = new Date(`${now.getMonth() + 1}/${now.getDate()}`);
const endDate = new Date(startDate);
endDate.setDate(endDate.getDate() + 21);

const dates = await prisma.availabilityDate.findMany({
where: {
householdId,
date: {
gte: startDate,
lte: endDate
}
},
orderBy: [
{
date: 'asc'
}
]
});

const rows = dates.map((d) => {
const { date, status, startTime, endTime, notes, emoticons } = d;
const englishDay = DAYS[date.getDay()];
const monthDay = `${date.getMonth() + 1}/${date.getDate()}`;

let availRange;
let startHr;
let startMin;
let endHr;
let endMin;
let emoticonSet = new Set<string>(emoticons?.split(','));
if (status === AvailabilityStatus.AVAILABLE) {
availRange = 'Available';
if (startTime && endTime)
availRange = `${dateTo12Hour(toLocalTimezone(startTime, user.timeZone))}-${dateTo12Hour(
toLocalTimezone(endTime, user.timeZone)
)}`;
const timeParts = destructRange(availRange);
startHr = timeParts.startHr;
startMin = timeParts.startMin;
endHr = timeParts.endHr;
endMin = timeParts.endMin;
} else if (status === AvailabilityStatus.BUSY) {
availRange = 'Busy';
}

return {
englishDay,
monthDay,
availRange,
notes: notes ?? undefined,
emoticons: emoticonSet,
startHr,
startMin,
endHr,
endMin
};
});

return generateFullSchedule(rows);
}

async function sendSched(
adults1: { phone: string; timeZone: string }[],
adults2: { phone: string; timeZone: string }[],
household1: { name: string; id: number },
household2: { name: string; id: number },
initiator: User
) {
// go through each number and send sched
return await Promise.all([
...adults1.map(async (recipient: { phone: string; timeZone: string }) => {
const sched = await getHouseholdsFullSched(household2.id, recipient);
return await sendMsg(
{
phone: recipient.phone,
type: 'newFriendNotif',
sched: sched.join('\n'),
otherHouseholdName: household2.name
},
initiator
);
}),
...adults2.map(async (recipient: { phone: string; timeZone: string }) => {
const sched = await getHouseholdsFullSched(household1.id, recipient);
return await sendMsg(
{
phone: recipient.phone,
type: 'newFriendNotif',
sched: sched.join('\n'),
otherHouseholdName: household1.name
},
initiator
);
})
]);
}

async function deleteUser(user: User) {
const userToDelete = await prisma.user.findUnique({
where: {
Expand Down Expand Up @@ -420,53 +169,4 @@ async function deleteUser(user: User) {
});
}

async function acceptFriendReqRoute(
req: {
friendReqId: number;
},
user: User
) {
// get each household's id
const otherHouseholdId = await acceptFriendReq(req, user);

// get users' phones, time zones in both households
const userAttrs = ['phone', 'timeZone'];
const [adults1, adults2] = await Promise.all([
await getUserAttrsInHousehold(otherHouseholdId, userAttrs),
await getUserAttrsInHousehold(user.householdId, userAttrs)
]);

// get names for both households
const attrs = ['name', 'id'];
const household1 = await getHousehold(otherHouseholdId, attrs);
if (!household1) {
throw error(404, {
message: `Can't find household ${otherHouseholdId}`
});
}
const household2 = await getHousehold(user.householdId, attrs);
if (!household2) {
throw error(404, {
message: `Can't find household ${user.householdId}`
});
}

await sendFaqLinks(adults1, adults2, household1, household2, user);
await sendSched(adults1, adults2, household1, household2, user);
}

export {
acceptFriendReqRoute,
sendSched,
sendFaqLinks,
deleteHouseholdInvite,
acceptHouseholdInvite,
createCircleInvite,
deleteFriend,
acceptFriendReq,
deleteFriendReq,
deleteKid,
deleteHousehold,
removeHouseholdAdult,
deleteUser
};
export { deleteKid, deleteHousehold, removeHouseholdAdult, deleteUser };
14 changes: 14 additions & 0 deletions src/lib/server/dbRoutes/_shared/deleteFriendReq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import FriendRequestRepository from '$lib/server/repository/FriendRequest';
import { error } from '@sveltejs/kit';

export default async function deleteFriendReq(reqId: number, phone: string) {
const friendReq = await FriendRequestRepository.findOne({ id: reqId });
if (!friendReq || friendReq.targetPhone !== phone) {
throw error(401, {
message: "Can't delete friend request not issued to you"
});
}
return await FriendRequestRepository.delete({
id: reqId
});
}
13 changes: 13 additions & 0 deletions src/lib/server/dbRoutes/_shared/deleteHouseholdInvite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import HouseholdInviteRepository from '$lib/server/repository/HouseholdInvite';
import { error } from '@sveltejs/kit';

export default async function deleteHouseholdInvite(reqId: number, phone: string) {
const invite = await HouseholdInviteRepository.findOne({ id: reqId });
if (!invite || invite.targetPhone !== phone) {
throw error(401, {
message: "You can't delete a household invite that wasn't issued to you"
});
}

await HouseholdInviteRepository.delete({ id: reqId });
}
Loading

0 comments on commit 0b557c9

Please sign in to comment.