Skip to content

Commit

Permalink
refactor db continued
Browse files Browse the repository at this point in the history
  • Loading branch information
jho44 committed Feb 14, 2024
1 parent 9a2117a commit 816ea23
Show file tree
Hide file tree
Showing 23 changed files with 547 additions and 422 deletions.
2 changes: 1 addition & 1 deletion src/lib/logics/Calendar/ScheduleTable/logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ export const requestToMarkOneRow = async ({
}) => {
const displayedRow = displayedRows[i];
const response = await writeReq('/db', {
type: 'schedule',
type: 'upsertDate',
status,
notes: displayedRow.notes,
emoticons: Array.from(displayedRow.emoticons).join(','),
Expand Down
325 changes: 0 additions & 325 deletions src/lib/server/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,63 +78,6 @@ async function acceptHouseholdInvite(req: { id: number }, user: User) {
return await Promise.all(friendReqs.map((x) => deleteFriendReq({ reqId: x.id }, user)));
}

async function createCircleInvite(
req: {
targetPhone: string;
},
user: User
) {
const { id: fromUserId, householdId: fromHouseholdId } = user;
const { targetPhone } = req;

if (!fromHouseholdId) {
throw error(401, {
message: 'You need to create a household before issuing friend requests'
});
}

const existingInvites = await prisma.friendRequest.findMany({
where: {
targetPhone,
fromHouseholdId
}
});
if (existingInvites.length)
throw error(400, {
message: 'The user associated with this number has already been invited to this circle.'
});

const targetUser = await prisma.user.findUnique({
where: {
phone: targetPhone
},
select: {
householdId: true
}
});
if (targetUser && targetUser.householdId) {
const { existingFriend1, existingFriend2 } = await findHouseConnection(
fromHouseholdId,
targetUser.householdId
);
if (existingFriend1 || existingFriend2)
throw error(400, {
message: 'The user associated with this number is already in your circle.'
});
}

const now = new Date();
const expires = now;
expires.setDate(now.getDate() + 7); // expire 1 week from now
await prisma.friendRequest.create({
data: {
expires,
targetPhone,
fromUserId,
fromHouseholdId
}
});
}

async function deleteFriend(req: { connectionId: number }, user: User) {
const friend = await prisma.householdConnection.findUnique({
Expand All @@ -157,102 +100,9 @@ async function deleteFriend(req: { connectionId: number }, user: User) {
});
}

async function acceptFriendReq(
req: {
friendReqId: number;
},
user: User
) {
const { householdId, phone } = user;
const { friendReqId } = req;

const friendReq = await findFriendReq(friendReqId);

if (!householdId) {
throw error(401, {
message: 'You need to create a household before accepting friend requests'
});
}

if (!friendReq || friendReq.targetPhone !== user.phone) {
throw error(401, {
message: 'No friend request with that id issued to you'
});
}

const { fromHouseholdId: friendHouseholdId } = friendReq;

// add to user's circle
await prisma.householdConnection.create({
data: {
householdId,
friendHouseholdId
}
});

// delete leftover friend reqs b/t the 2 households
const selectPhone = { phone: true };
const householdAUsers = await prisma.user.findMany({
where: {
householdId
},
select: selectPhone
});
const householdBUsers = await prisma.user.findMany({
where: {
householdId: friendHouseholdId
},
select: selectPhone
});

const householdAPhones = householdAUsers.map((x) => x.phone);
const householdBPhones = householdBUsers.map((x) => x.phone);

const selectId = { id: true };
const leftoverReqs1 = await prisma.friendRequest.findMany({
where: {
fromHouseholdId: householdId,
targetPhone: { in: householdBPhones }
},
select: selectId
});
const leftoverReqs2 = await prisma.friendRequest.findMany({
where: {
fromHouseholdId: friendHouseholdId,
targetPhone: { in: householdAPhones }
},
select: selectId
});
console.log('leftoverFriendReqs', leftoverReqs1.concat(leftoverReqs2));
leftoverReqs1.concat(leftoverReqs2).forEach(({ id }) => {
deleteFriendReq({ reqId: id }, user);
});

// delete leftover household invites from this householdId to user
// should just be 1 since we prevent multiple invites from 1 household
// to 1 user, but using a findMany since our schema doesn't know better
const leftoverReqs3 = await prisma.joinHouseholdRequest.findMany({
where: {
householdId: friendHouseholdId,
targetPhone: phone
},
select: {
id: true
}
});
console.log('leftover householdInvites', leftoverReqs3);
leftoverReqs3.forEach(({ id }) => deleteHouseholdInvite({ id }, user));

return friendHouseholdId;
}

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

async function deleteFriendReq(req: { reqId: number }, user: User) {
const friendReq = await findFriendReq(req.reqId);
Expand All @@ -268,180 +118,7 @@ async function deleteFriendReq(req: { reqId: number }, user: User) {
});
}

async function saveSchedule(
req: {
monthDay: string;
status: AvailabilityStatus;
notes: string | undefined;
emoticons: string | undefined;
startTime: Date;
endTime: Date;
},
user: User
) {
const { householdId } = user;
if (!householdId) {
throw error(401, {
message: 'You need to create / join a household before saving a schedule'
});
}
const { monthDay, status, notes, emoticons } = req;
const startTime = new Date(req.startTime);
const endTime = new Date(req.endTime);
const date = new Date(monthDay);
const res = {
date,
status,
notes: '',
emoticons,
startTime,
endTime
};

if (status === AvailabilityStatus.UNSPECIFIED) {
await prisma.availabilityDate.delete({
where: {
householdId_date: {
householdId,
date
}
}
});
return res;
}
// if an entry for this date already exists in the db, then patch it
// otherwise create it
const sanitizedNotes = dateNotes(notes ?? '');
await prisma.availabilityDate.upsert({
where: {
householdId_date: {
householdId,
date
}
},
update: {
status,
notes: sanitizedNotes,
emoticons,
startTime,
endTime
},
create: {
householdId,
date,
status,
notes: sanitizedNotes,
emoticons,
startTime,
endTime
}
});
res.notes = sanitizedNotes;
return res;
}

async function saveUser(
req: {
firstName: string;
lastName: string;
pronouns: Pronoun;
timeZone: string;
locale: string;
email: string;
notifFreq: number;
notifStartDay: number;
notifHr: number;
notifMin: number;
acceptedTermsAt: Date;
allowReminders: boolean;
allowInvites: boolean;
},
phone: string,
user: User | null
) {
const {
firstName,
lastName,
pronouns,
timeZone,
locale,
email,
notifFreq,
notifStartDay,
notifHr,
notifMin,
acceptedTermsAt,
allowInvites,
allowReminders
} = req;
// Get the current date in the user's timezone so we don't set reminderDatetime in the past
const d = toLocalTimezone(new Date(), timeZone);
// Calculate the desired date based on the user's timezone
let diff = d.day - (d.weekday % 7) + notifStartDay;

// either desired start day has already passed this week
// or the hour has passed today
// or the minute has passed this hour
if (
diff < d.day ||
(diff === d.day && (notifHr < d.hour || (notifHr === d.hour && notifMin < d.minute)))
) {
diff += notifFreq;
}
const newReminderDate = d.set({ day: diff, hour: notifHr, minute: notifMin });
const baseUser = {
locale,
firstName,
lastName,
timeZone,
pronouns,
email,
reminderDatetime: newReminderDate.toJSDate(),
reminderIntervalDays: notifFreq,
acceptedTermsAt
};
let updatedUser;
if (user) {
// user exists
console.log('UPDATE USER');
updatedUser = await prisma.user.update({
where: {
phone
},
data: {
...baseUser,
phonePermissions: {
update: {
allowInvites,
allowReminders
}
}
}
});
} else {
console.log('CREATE USER');
updatedUser = await prisma.user.create({
data: {
...baseUser,
phonePermissions: {
connectOrCreate: {
where: {
phone
},
create: {
phone,
blocked: false,
allowInvites,
allowReminders,
acceptedTermsAt
}
}
}
}
});
}
return updatedUser.id;
}

async function deleteKid(req: { id: number }, user: User) {
const { id } = req;
Expand Down Expand Up @@ -788,8 +465,6 @@ export {
deleteFriend,
acceptFriendReq,
deleteFriendReq,
saveSchedule,
saveUser,
deleteKid,
deleteHousehold,
removeHouseholdAdult,
Expand Down
Loading

0 comments on commit 816ea23

Please sign in to comment.