Skip to content

Commit

Permalink
wip refactor db
Browse files Browse the repository at this point in the history
  • Loading branch information
jho44 committed Feb 13, 2024
1 parent 7a9e98e commit 9a2117a
Show file tree
Hide file tree
Showing 13 changed files with 294 additions and 220 deletions.
45 changes: 34 additions & 11 deletions src/lib/components/Calendar/ScheduleTable.svelte
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
<script lang="ts">
import { EMOTICONS, UNAVAILABLE } from '$lib/logics/Calendar/_shared/constants';
import { EMOTICONS_REVERSE } from '$lib/constants';
import type { Row } from '$lib/types';
import type { Row, Unavailable } from '$lib/types';
import Legend from '$lib/components/Legend.svelte';
import Button from '$lib/components/Button.svelte';
import {
closeEditor,
getRowColor,
isAvailableOnRow,
markRowAsAvailable,
markRowAsUnavailable,
markRowUnavailableLocally,
requestToMarkOneRow,
// markRowAsUnavailable,
showEditor,
toggleEmoticon
} from '$lib/logics/Calendar/ScheduleTable/logic';
Expand All @@ -18,7 +20,6 @@
export let rows: Row[];
export let timeZone: string;
let rowLabels: string[] = [];
let openedRows = new Set<number>(); // row inds which have open editors
let rowIndsWithTimeErrs = new Set<number>();
/*
Expand All @@ -30,11 +31,6 @@
*/
let rowColors: string[] = [];
$: rowLabels = rows.map((row) => {
if (row.availRange === AvailabilityStatus.BUSY) return 'Busy';
return '';
});
$: {
if (!rows.length) break $;
Expand All @@ -51,6 +47,33 @@
const handleEditorOpen = (i: number) => {
openedRows = showEditor({ i, openedRows });
};
const markRowAsUnavailable = async ({
i,
status
}: {
i: number;
status: Unavailable;
}) => {
const dbRows = [...rows]
rows = markRowUnavailableLocally({ i, displayedRows: rows, status });
try {
await requestToMarkOneRow({
i,
status,
// dbRows,
displayedRows: rows,
availableDetails: null
});
closeEditor({ i, openedRows });
} catch (err) {
console.error(err);
console.error('Something went wrong with marking row as unavailable');
rows = [...dbRows]
}
};
</script>

<table id="schedule">
Expand Down Expand Up @@ -78,9 +101,9 @@
on:click={() => handleEditorOpen(i)}
on:keyup={() => handleEditorOpen(i)}
>
{#if !row.availRange}
{#if row.availRange === AvailabilityStatus.UNSPECIFIED}
<p>Unspecified (<span class="edit">edit</span>)</p>
{:else if row.availRange === 'Busy'}
{:else if row.availRange === AvailabilityStatus.BUSY}
<p>Busy (<span class="edit">edit</span>)</p>
{:else}
<p class="timeDisplay">{row.availRange}</p>
Expand All @@ -97,7 +120,7 @@
<p class="changeTime">(edit)</p>
{/if}
</td>
{#if !row.availRange}
{#if row.availRange === AvailabilityStatus.UNSPECIFIED}
<td
on:click={() => {
markRowAsUnavailable({
Expand Down
37 changes: 20 additions & 17 deletions src/lib/logics/Calendar/ScheduleTable/logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export const getRowColor = ({
isAvailable: boolean;
isRowExpanded: boolean;
}) => {
console.log({ i, numRows, isAvailable, isRowExpanded });
if (i >= numRows) return i % 2 ? LIGHT_GRAY : WHITE;
if (isAvailable && !isRowExpanded) {
return LIGHT_BLUE;
Expand Down Expand Up @@ -54,7 +53,7 @@ export const updateRowColors = ({
});
};

const markRowUnavailableLocally = ({
export const markRowUnavailableLocally = ({
i,
displayedRows,
// dbRow,
Expand All @@ -68,6 +67,7 @@ const markRowUnavailableLocally = ({
displayedRows[i].notes = '';
displayedRows[i].emoticons = new Set();
displayedRows[i].availRange = status;
return displayedRows;
// dbRow.notes = '';
// dbRow.emoticons = new Set();
// dbRow.availRange = status;
Expand Down Expand Up @@ -193,7 +193,7 @@ const updateDisplayedRow = async ({
// updateRowColors();
};

const requestToMarkOneRow = async ({
export const requestToMarkOneRow = async ({
i,
status,
// dbRows,
Expand Down Expand Up @@ -224,6 +224,9 @@ const requestToMarkOneRow = async ({
}
: {})
});
console.log(response)
console.log(await response.json())

return;

// if (response.status == 200) {
Expand Down Expand Up @@ -265,20 +268,20 @@ export const markRowAsUnavailable = async ({
}) => {
markRowUnavailableLocally({ i, displayedRows, status });

try {
await requestToMarkOneRow({
i,
status,
// dbRows,
displayedRows,
availableDetails: null
});
closeEditor({ i, openedRows });
} catch (err) {
console.error(err);
console.error('Something went wrong with marking row as unavailable');
throw new Error();
}
// try {
// await requestToMarkOneRow({
// i,
// status,
// // dbRows,
// displayedRows,
// availableDetails: null
// });
// closeEditor({ i, openedRows });
// } catch (err) {
// console.error(err);
// console.error('Something went wrong with marking row as unavailable');
// throw new Error();
// }
};

export const markRowAsAvailable = async ({
Expand Down
166 changes: 37 additions & 129 deletions src/lib/server/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { User } from '@prisma/client';
import { dateTo12Hour, toLocalTimezone } from '../date';
import { dateNotes } from './sanitize';
import prisma from '$lib/prisma';
import { findHouseConnection } from './shared';
import { findHouseConnection, getHousehold, getUserAttrsInHousehold } from './shared';
import { sendMsg } from './twilio';
import { DAYS } from '$lib/constants';
import { destructRange } from '$lib/parse';
Expand Down Expand Up @@ -340,44 +340,6 @@ async function saveSchedule(
return res;
}

async function createHouseholdInvite(
req: {
targetPhone: string;
},
user: User
) {
const { targetPhone } = req;
const { id: fromUserId } = user;
const { householdId } = user;
if (!householdId) {
throw error(401, {
message: 'You need to create / join a household before inviting others to join it.'
});
}

const existingInvites = await prisma.joinHouseholdRequest.findMany({
where: {
targetPhone,
householdId
}
});
if (existingInvites.length)
throw error(400, {
message: 'The user associated with this number has already been invited to this household.'
});
const now = new Date();
const expires = now;
expires.setDate(now.getDate() + 7); // expire 1 week from now
await prisma.joinHouseholdRequest.create({
data: {
expires,
targetPhone,
householdId,
fromUserId
}
});
}

async function saveUser(
req: {
firstName: string;
Expand Down Expand Up @@ -481,92 +443,6 @@ async function saveUser(
return updatedUser.id;
}

async function createHousehold(
user: User,
data?: { name: string; publicNotes: string; updatedAt: Date }
) {
if (user.householdId)
throw error(400, {
message: "Can't create household for someone who's already in a household"
});
// create household
const household = await prisma.household.create({
data: data ?? {
name: '',
publicNotes: '',
updatedAt: new Date()
}
});
console.log('CREATED HOUSEHOLD', household);
// then associate user to it
await prisma.user.update({
where: {
id: user.id
},
data: {
householdId: household.id
}
});

return household.id;
}

async function saveHousehold(
req: {
name: string;
publicNotes: string;
},
user: User
) {
const { name, publicNotes } = req;
const { householdId } = user;
const data = {
name,
publicNotes,
updatedAt: new Date()
};

if (!householdId) {
await createHousehold(user, data);
} else {
await prisma.household.update({
where: {
id: householdId
},
data
});
}
}

async function saveKid(
req: {
firstName: string;
pronouns: Pronoun;
lastName: string;
dateOfBirth: Date;
},
user: User
) {
const { firstName, pronouns, lastName, dateOfBirth } = req;
const { householdId } = user;
// ensure the household exists before adding kid to it
if (!householdId) {
throw error(401, {
message: 'Create a household before trying to add a child to it'
});
}
const kid = await prisma.householdChild.create({
data: {
householdId,
firstName,
pronouns,
lastName,
dateOfBirth
}
});
return kid.id;
}

async function deleteKid(req: { id: number }, user: User) {
const { id } = req;
const kid = await prisma.householdChild.findUnique({
Expand Down Expand Up @@ -867,7 +743,43 @@ 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,
Expand All @@ -877,11 +789,7 @@ export {
acceptFriendReq,
deleteFriendReq,
saveSchedule,
createHouseholdInvite,
saveUser,
createHousehold,
saveHousehold,
saveKid,
deleteKid,
deleteHousehold,
removeHouseholdAdult,
Expand Down
Loading

0 comments on commit 9a2117a

Please sign in to comment.