Whatsapp service updates

This commit is contained in:
Darren Clarke 2024-05-16 18:22:10 +02:00
parent e22a8e8d98
commit 3da103c010
16 changed files with 151 additions and 36 deletions

View file

@ -112,3 +112,16 @@ export const deleteAction = async ({ entity, table, id }: DeleteActionArgs) => {
export const selectAllAction = async (table: keyof Database) => {
return db.selectFrom(table).selectAll().execute();
};
type SelectOneArgs = {
table: keyof Database;
id: string;
};
export const selectOneAction = async ({ table, id }: SelectOneArgs) => {
return db
.selectFrom(table)
.selectAll()
.where("id", "=", id)
.executeTakeFirst();
};

View file

@ -22,6 +22,7 @@ export const Detail: FC<DetailProps> = ({ service, row }) => {
[service]: { entity, table, displayName, displayFields: fields },
} = serviceConfig;
const id = row.id as string;
const token = row.token as string;
const deleteAction = generateDeleteAction({ entity, table });
const router = useRouter();
const { almostBlack } = colors;
@ -76,7 +77,9 @@ export const Detail: FC<DetailProps> = ({ service, row }) => {
name={field.name}
label={field.label}
getValue={field.getValue}
id={row["id"] as string}
refreshInterval={field.refreshInterval}
token={token}
verified={row.verified as boolean}
helperText={field.helperText}
/>
)}

View file

@ -1,5 +1,10 @@
import { FC } from "react";
import { Box } from "@mui/material";
export const Home: FC = () => {
return <h1>Home</h1>;
return (
<Box sx={{ p: 3, fontSize: 30, fontWeight: "bold", textAlign: "center" }}>
Overview
</Box>
);
};

View file

@ -6,7 +6,8 @@ import { colors } from "../styles/theme";
type QRCodeProps = {
name: string;
label: string;
id: string;
token: string;
verified: boolean;
helperText?: string;
getValue?: (id: string) => Promise<string>;
refreshInterval?: number;
@ -15,7 +16,8 @@ type QRCodeProps = {
export const QRCode: FC<QRCodeProps> = ({
name,
label,
id,
token,
verified,
helperText,
getValue,
refreshInterval,
@ -24,19 +26,19 @@ export const QRCode: FC<QRCodeProps> = ({
const { white } = colors;
useEffect(() => {
if (getValue && refreshInterval) {
if (!verified && getValue && refreshInterval) {
const interval = setInterval(async () => {
const result = await getValue(id);
const result = await getValue(token);
setValue(result);
}, refreshInterval);
}, refreshInterval * 1000);
return () => clearInterval(interval);
}
}, [getValue, refreshInterval]);
return (
return !verified ? (
<Box sx={{ backgroundColor: white, m: 2 }}>
<QRCodeInternal value={value} />
<Box>{helperText}</Box>
</Box>
);
) : null;
};

View file

@ -1,8 +1,12 @@
import { ServiceConfig } from "../lib/service";
// import { generateSelectOneAction } from "../lib/actions";
const getQRCode = async (id: string) => {
console.log("Getting QR code");
return "xya"; // "2hVSc9OT18wbo60WLKlVrd5KqQqYZWdH+kVlRYlrnZcKbjbzwcL4ybkS1/jGaN5bLafX9ZaR829xyhQ=";
const getQRCode = async (token: string) => {
const url = `/api/whatsapp/bots/${token}`;
const result = await fetch(url, { cache: "no-store" });
const { qr } = await result.json();
return qr ?? "";
};
export const whatsappConfig: ServiceConfig = {
@ -71,7 +75,7 @@ export const whatsappConfig: ServiceConfig = {
size: 4,
getValue: getQRCode,
helperText: "Go ahead, scan it",
refreshInterval: 5,
refreshInterval: 15,
},
],
listColumns: [

View file

@ -4,6 +4,7 @@ import {
updateAction,
deleteAction,
selectAllAction,
selectOneAction,
} from "../actions/service";
import { FieldDescription, Entity } from "./service";
@ -70,3 +71,14 @@ export function generateSelectAllAction(table: keyof Database) {
return selectAllAction(table);
};
}
type GenerateSelectOneArgs = {
table: keyof Database;
id: string;
};
export function generateSelectOneAction({ table, id }: GenerateSelectOneArgs) {
return async () => {
return selectOneAction({ table, id });
};
}

View file

@ -23,7 +23,7 @@ export type FieldDescription = {
name: string;
label: string;
kind?: "text" | "phone" | "select" | "multi" | "qrcode";
getValue?: (id: string) => Promise<string>;
getValue?: (token: string) => Promise<string>;
refreshInterval?: number;
getOptions?: (formState: any) => Promise<SelectOption[]>;
autogenerated?: "token";
@ -70,15 +70,21 @@ export class Service {
return NextResponse.json(row);
}
async registerBot({
params: { service, token },
}: ServiceParams): Promise<NextResponse> {
return NextResponse.error() as any;
}
async sendMessage(
req: NextRequest,
{ params: { service, token } }: ServiceParams,
): Promise<NextResponse> {
const message = await req.json();
const json = await req.json();
const worker = await getWorkerUtils();
await worker.addJob(`${service}/send-${service}-message`, {
token,
message,
...json,
});
return NextResponse.json({ response: "ok" });
@ -88,7 +94,9 @@ export class Service {
req: NextRequest,
{ params: { service, token } }: ServiceParams,
): Promise<NextResponse> {
console.log("INTO receiveMessage");
const message = await req.json();
console.log({ message });
const worker = await getWorkerUtils();
await worker.addJob(`${service}/receive-${service}-message`, {
token,

View file

@ -1,3 +1,35 @@
import { Service } from "./service";
import { NextResponse } from "next/server";
import { db } from "bridge-common";
import { revalidatePath } from "next/cache";
import { Service, ServiceParams } from "./service";
export class Whatsapp extends Service {}
export class Whatsapp extends Service {
async getBot({ params: { token } }: ServiceParams) {
const row = await db
.selectFrom("WhatsappBot")
.selectAll()
.where("token", "=", token as string)
.executeTakeFirstOrThrow();
const id = row.id;
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}`;
const result = await fetch(url, { cache: "no-store" });
console.log({ result1: result });
const json = await result.json();
await db
.updateTable("WhatsappBot")
.set({ verified: json.verified })
.where("id", "=", id)
.execute();
revalidatePath(`/whatsapp/${id}`);
if (!json.verified) {
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}/register`;
const result = await fetch(url, { method: "POST", cache: "no-store" });
console.log({ result2: result });
}
return NextResponse.json(json);
}
}