Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
jho44 committed Sep 16, 2023
1 parent 9c97690 commit d76040d
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 41 deletions.
5 changes: 4 additions & 1 deletion src/lib/format.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { EMOTICONS_REVERSE, type Row } from '$lib/constants';
import { getObjectivePronoun } from './parse';

function getScheduleItem(row: Row): string {
let scheduleItem = '';
Expand Down Expand Up @@ -118,3 +117,7 @@ export function circleInviteMsg(user: any, kidNames: string[], toPhone: string)
user.firstName
}`;
}

export function fullName(firstName: string, lastName: string | null) {
return `${firstName}${lastName ? ` ${lastName}` : ''}`;
}
1 change: 1 addition & 0 deletions src/lib/server/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ async function acceptFriendReq(
});
console.log('leftover householdInvites', leftoverReqs3);
leftoverReqs3.forEach(({ id }) => deleteHouseholdInvite({ id }, user));
return friendHouseholdId;
}

async function findFriendReq(reqId: number) {
Expand Down
113 changes: 81 additions & 32 deletions src/lib/server/twilio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ import { env as private_env } from '$env/dynamic/private';
import { env as public_env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import Twilio from 'twilio';
import type * as TwilioTypes from 'twilio';
import { AvailabilityStatus, type User } from '@prisma/client';
import { circleNotif } from './sanitize';
import { generate, save } from './login';
import { dateTo12Hour, toLocalTimezone } from '../date';
import { DateTime } from 'luxon';
import prisma from '$lib/prisma';
import { generateFullSchedule } from '$lib/format';
import { fullName, generateFullSchedule } from '$lib/format';
import { DAYS } from '$lib/constants';
import { getAvailRangeParts } from '$lib/parse';
import { findHouseConnection } from './shared';

const MessagingResponse = Twilio.twiml.MessagingResponse;

Expand All @@ -23,45 +25,42 @@ const msgToSend = async (
const url = public_env.PUBLIC_URL;
let msg;
switch (type) {
case 'newFriendSched': {
const { friendReqId } = msgComps;
const friendReq = await prisma.friendRequest.findUnique({
where: {
id: friendReqId
},
select: {
fromHouseholdId: true,
targetPhone: true
}
});

if (!friendReq) {
throw error(404, {
message: `Friend request ${friendReqId} not found`
});
case 'newFriend': {
if (!initiator) {
throw error(500, {
message: 'Missing initiator when constructing newFriend msg'
})
}

msg = `You are now in ${fullName(initiator.firstName, initiator.lastName)}`;
break;
}
case 'newFriendSched': {
const { friendHouseholdId } = msgComps;
// get availability dates from local today to local 21 days
if (!initiator) {
if (!initiator?.householdId) {
throw error(401, {
message: 'Request was not initiated by app user'
message: "Request was not initiated by app user or app user doesn't have household"
});
}
if (initiator.phone !== friendReq.targetPhone) {
const { existingFriend1, existingFriend2 } = await findHouseConnection(
initiator.householdId,
friendHouseholdId
);
const connection = existingFriend1 || existingFriend2;
if (!connection) {
throw error(401, {
message: 'Friend req is not to you'
});
message: `Household ${initiator.householdId} is not friends with Household ${friendHouseholdId}`
})
}

const now = new Date();
const startDate = new Date(`${now.getMonth() + 1}/${now.getDate()}`);
const endDate = new Date(startDate);
endDate.setDate(endDate.getDate() + 21);

const { fromHouseholdId } = friendReq;
const dates = await prisma.availabilityDate.findMany({
where: {
householdId: fromHouseholdId,
householdId: friendHouseholdId,
date: {
gte: startDate,
lte: endDate
Expand Down Expand Up @@ -269,8 +268,6 @@ export const sendMsg = async (
logLevel: 'debug'
});
}
let message;
let createMessageRequest;

const recipient = await prisma.user.findUnique({
where: { phone }
Expand Down Expand Up @@ -300,7 +297,63 @@ export const sendMsg = async (
}

const body = await msgToSend(type, recipient, initiator, { ...rest, phone });
try {
invokeTwilio(body, phone, sendAt, client);
} catch (e) {
throw e;
}

// any additional msgs to send to diff number(s)
switch (type) {
case 'newFriendSched': {
const { friendReqId } = rest as { friendReqId: number };
const friendReq = await prisma.friendRequest.findUnique({
where: {
id: friendReqId
},
select: {
fromUserId: true,
}
});
if (!friendReq) {
// should never get here since we alr do this check in msgToSend but this msg type
// so more for TS than anything else
throw error(404, {
message: `Friend request ${friendReqId} not found`
});
}
const { fromUserId } = friendReq;
const friendReqSender = await prisma.user.findUnique({
where: {
id: fromUserId,
},
})

if (!friendReqSender) {
throw error(404, {
message: `User ${fromUserId} not found`
});
}

const body2 = await msgToSend(type, friendReqSender, initiator, {});
try {
invokeTwilio(body2, friendReqSender.phone, sendAt, client);
} catch (e) {
throw e;
}
break;
}
default:
}

// It's a security issue to share the auth link with the client
// edit: so never pass it on
return json({});
};

export const invokeTwilio = async (body: string, phone: string, sendAt?: Date, client: TwilioTypes.Twilio) => {
let message;
let createMessageRequest;
try {
createMessageRequest = {
body,
Expand Down Expand Up @@ -332,11 +385,7 @@ export const sendMsg = async (
message: 'There was a problem sending you a magic link'
});
}

// It's a security issue to share the auth link with the client
// edit: so never pass it on
return json({});
};
}

export const getMsg = async (url: URL) => {
const body = url.searchParams.get('Body')?.toLowerCase();
Expand Down
9 changes: 8 additions & 1 deletion src/routes/db/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
removeHouseholdAdult
} from '$lib/server/db';
import { getProfileFromSession } from '$lib/server/shared';
import { writeReq } from '$lib/utils';

export async function POST({
request,
Expand Down Expand Up @@ -56,7 +57,13 @@ export async function POST({
} else if (req.type === 'inviteToCircle') {
await createCircleInvite(req, user);
} else if (req.type === 'acceptFriendReq') {
await acceptFriendReq(req, user);
const friendHouseholdId = await acceptFriendReq(req, user);
// send new friend's sched to req recipient (A) and let req sender (B) know that B is in A's circle now
await writeReq('/twilio', {
phone: user.phone,
type: 'newFriendSched',
friendHouseholdId
});
} else if (req.type === 'rejectFriendReq') {
await deleteFriendReq(req, user);
} else if (req.type === 'deleteFriend') {
Expand Down
11 changes: 4 additions & 7 deletions src/routes/invites/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,12 @@
if (response.status == 200) {
await invalidate('data:invite');
// send new friend's sched to you
// send new friend's sched to you and let them know that you're in each other's mutual circle now
await writeReq('/twilio', {
phone: $page.data.user.phone,
type: 'newFriendSched',
friendReqId
senderHouseholdId: reqSenderHouseholdId
});
// tell new friend that they're in your circle now
} else {
alert('Something went wrong with accepting this connection');
}
Expand Down Expand Up @@ -91,7 +89,6 @@
>
</p>
{/if}

{#each friendReqsInfo as household}
<div class="card">
<p class="household-name">{household.name}</p>
Expand All @@ -112,8 +109,8 @@
</div>
<div
class="btn-wrapper success w-half"
on:click={() => acceptFriendReq(household.reqId)}
on:keyup={() => acceptFriendReq(household.reqId)}
on:click={() => acceptFriendReq(household.reqId, household.id)}
on:keyup={() => acceptFriendReq(household.reqId, household.id)}
>
<AcceptIcon />
</div>
Expand Down

0 comments on commit d76040d

Please sign in to comment.