Skip to content

Commit

Permalink
idk
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderTsarapkine committed Feb 21, 2024
1 parent 0d8a453 commit feb097e
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 10 deletions.
23 changes: 23 additions & 0 deletions src/app/api/enqueue_calls/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

import { NextRequest} from "next/server";

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const workspaceSid = process.env.TWILIO_WORKSPACE_SID || '';
const workflowSid = process.env.TWILIO_WORKFLOW_SID;
const client = require('twilio')(accountSid, authToken);



export async function POST(req: NextRequest ) {
try {
const resp = await client.taskrouter.v1.workspaces(workspaceSid).tasks.create({
workflowSid,
});

return new Response(JSON.stringify(resp), { status: 200 });
} catch (error) {
return new Response("something went wrong", { status: 500});
}

}
14 changes: 14 additions & 0 deletions src/app/api/eventcallback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { NextRequest, NextResponse } from 'next/server';
import { twilioClient } from '@/lib/twilioClient';

export async function POST(req: NextRequest) {


console.log("RAAAAA")
// console.log(req)

const params = req.nextUrl.searchParams;
console.log(Array.from(params.entries()));

return new NextResponse(null, { status: 204, headers: { 'Content-Type': 'application/json' } });
}
6 changes: 6 additions & 0 deletions src/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
"use client"
import IncomingCallModal from "@/components/(dashboard)/tasks/IncomingCallModal";
import NotificationsCard from "@/components/appbar/NotificationsCard";

export default function Dashboard() {
return (
<main>
<h1>Dashboard</h1>
{/* <IncomingCallModal number="1234567890" acceptCall={() => {}} rejectCall={() => {}} /> */}
<NotificationsCard />
</main>
);
}
Expand Down
12 changes: 9 additions & 3 deletions src/app/dashboard/tasks/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { useState, useEffect } from 'react';
import { useSession } from "next-auth/react";
import { Button } from '@/components/ui/button';
import useCalls from '@/lib/hooks/useCalls';

function formatTime(seconds: number) {
const days = Math.floor(seconds / (24 * 60 * 60));
Expand All @@ -24,6 +25,12 @@ export default function Tasks() {
const [activeTasks, setActiveTasks] = useState([]);
const { data: session } = useSession();

const { inCall, number, makeCall, setNumber, endCall } = useCalls({
email: session?.user?.email || '',
workerSid: session?.employeeNumber || '',
friendlyName: session?.user?.name || '',
});

useEffect(() => {
const fetchTasks = () => {
// fetch('/api/tasks')
Expand Down Expand Up @@ -60,8 +67,7 @@ export default function Tasks() {
</tr>
</thead>
<tbody>
{tasks && Array.isArray(tasks) && tasks
.filter((task: any) => task.reservation.reservationStatus === 'accepted' || task.reservation.reservationStatus === 'pending')
{activeTasks && Array.isArray(activeTasks) && activeTasks
.map((task: any) => (
<tr key={task.task.sid} >
<td>
Expand All @@ -76,7 +82,7 @@ export default function Tasks() {
{task.task.taskChannelUniqueName === 'voice' ? (
<Button
className="bg-[#334155] hover:bg-[#2D3A4C]/90 w-fit mr-2"
onClick={() => console.log('Call mode')}
onClick={() => console.log(task)}
>
Call
</Button>
Expand Down
43 changes: 43 additions & 0 deletions src/components/(dashboard)/tasks/IncomingCallModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { formatPhoneNumber } from '@/lib/utils';

export default function IncomingCallModal({
number,
acceptCall,
rejectCall,
}: {
number: string;
acceptCall: () => void;
rejectCall: () => void;
}) {
return (
<div className="fixed z-10 top-0 left-0 w-full h-full bg-black bg-opacity-50 flex justify-center items-center">
<div className="bg-white p-4 rounded-lg">
<section className="flex flex-col items-center justify-between p-8 gap-y-12">
<article className="flex flex-col gap-y-4 items-center">
<div className="text-xl font-medium text-[#6B7280]">
Incoming Call
</div>
<div className="text-4xl font-semibold">
{formatPhoneNumber(number)}
</div>
</article>

<article className="flex flex-row gap-x-10">
<button
className="w-[120px] h-12 border-2 border-[#6366f1] text-[#6366f1] rounded-[10px] hover:bg-[#6366f1] hover:text-white"
onClick={() => acceptCall()}
>
Accept Call
</button>
<button
className="w-[120px] h-12 rounded-[10px] hover:bg-black hover:text-white"
onClick={() => rejectCall()}
>
Reject Call
</button>
</article>
</section>
</div>
</div>
);
}
13 changes: 12 additions & 1 deletion src/components/appbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { signOut } from "next-auth/react";

import useCalls from "@/lib/hooks/useCalls";
import { useSession } from "next-auth/react";
import IncomingCallModal from "../(dashboard)/tasks/IncomingCallModal";

interface AppbarProps extends React.HTMLAttributes<HTMLDivElement> {
initials: string;
Expand All @@ -51,7 +52,16 @@ export default function Appbar({
}: AppbarProps) {
const { data: session, status } = useSession();

const { inCall, number, makeCall, setNumber, endCall } = useCalls({
const {
inCall,
number,
makeCall,
setNumber,
endCall,
incomingCall,
acceptCall,
rejectCall
} = useCalls({
email: session?.user?.email || '',
workerSid: session?.employeeNumber || '',
friendlyName: session?.user?.name || '',
Expand Down Expand Up @@ -143,6 +153,7 @@ export default function Appbar({
</DropdownMenu>
</div>
</div>
{incomingCall && (<IncomingCallModal number={number} acceptCall={acceptCall} rejectCall={rejectCall} />)}
</Menubar>
);
}
43 changes: 37 additions & 6 deletions src/lib/hooks/useCalls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,27 @@ export default function useCalls({
// };

const initializeDeviceListeners = () => {
console.log("11111111")
if (!device.current) return;

console.log("2222222")
device.current.on("registered", function () {
console.log("POPOP")
console.log("Twilio.Device Ready to make and receive calls!");
});

console.log("3333333")

console.log("device is", device.current)


device.current.on("error", function (error: { message: string }) {
console.log("Twilio.Device Error: " + error.message);
});

console.log("4444444")

device.current.on("incoming", (incomingCall: Call) => {
console.log("55555")
setIncomingCall(true);
setNumber(incomingCall.parameters.From);

Expand Down Expand Up @@ -168,6 +178,7 @@ export default function useCalls({
!initialized &&
workerSid !== undefined
) {
console.log("USEEFFECT," ,email)
checkEmail.current = email;
const initializeCalls = async () => {
await Promise.all([
Expand Down Expand Up @@ -220,22 +231,26 @@ export default function useCalls({
*/

const makeCall = async (number: string) => {
console.log("dpqpqpqppqpqpqpp ", device.current)
if (!device.current) return;

const params = {
// get the phone number to call from the DOM
To: number,
};

console.log("Making a call to", number);

const newCall = await device.current.connect({ params });

call.current = newCall;

// TODO uncomment when taskrouter impelemnted
// Turn agent activity status to reserved to prevent agent from receiving incoming calls
// const reservedActivity = agentActivities.current?.find(
// (activity) => activity.friendlyName === "Reserved"
// );
const reservedActivity = agentActivities.current?.find(
(activity) => activity.friendlyName === "Reserved"
);

console.log("ADASA", worker.current?.sid, reservedActivity);

// await fetch(
// `/api/workers/?workspaceSid=${process.env.NEXT_PUBLIC_WORKSPACE_SID}&workerSid=${worker.current?.sid}`,
Expand Down Expand Up @@ -334,18 +349,33 @@ export default function useCalls({
*
*/
async function initializeDevice(client: string) {
console.log("Initializing device", client)
const token = await fetch(
`${process.env.NEXT_PUBLIC_URL}/api/token?client=${client}`
`http://localhost:3000/api/token?client=${client}`
);

const value = await token.json();

console.log("VALUE IS ", value)

const device = new Device(value.token, {
logLevel: 1,
codecPreferences: [Call.Codec.Opus, Call.Codec.PCMU],
});

console.log("REGISTERING DEVICE")
console.log(device)

device.on('registered', () => {
console.log('sdfsddsfsdATT');
});

device.on('incoming', (connection) => {
console.log("BEING CALLED")
})

await device.register();
console.log("RAAAAA")
return device;
}

Expand Down Expand Up @@ -380,6 +410,7 @@ const initializeWorker = async (
const token = await tokenResponse.json();

const worker = new Worker(token);
console.log("WORKER IS", worker)
await timeout(1000); // For some reason, this is some much needed black magic
return worker;
} catch (e) {
Expand Down

0 comments on commit feb097e

Please sign in to comment.