From 586c0e7210eeedd1c2e1ce6b787de078a7f10659 Mon Sep 17 00:00:00 2001 From: i701 Date: Sat, 21 Dec 2024 00:24:29 +0500 Subject: [PATCH] Refactor Omada actions and enhance payment processing - Simplified fetchOmadaGroupProfiles function by removing unnecessary parameters and using environment variables for base URL and API key. - Improved error handling in fetchOmadaGroupProfiles to check for error codes in the response. - Updated addDevicesToGroup function to remove redundant parameters and streamline device addition logic. - Integrated formatMacAddress utility to ensure consistent MAC address formatting during payment verification. - Enhanced verifyPayment function to include device addition upon successful payment verification, with improved logging. - Refactored DevicesToPay component to clean up payment verification logic and improve UI responsiveness. These changes enhance the clarity and efficiency of device management and payment processing functionalities. --- actions/omada-actions.ts | 83 +++++++++-------------------------- actions/payment.ts | 18 ++++---- components/devices-to-pay.tsx | 32 +++++++------- lib/utils.ts | 10 +++++ 4 files changed, 57 insertions(+), 86 deletions(-) diff --git a/actions/omada-actions.ts b/actions/omada-actions.ts index 27245d6..0fa8cd1 100644 --- a/actions/omada-actions.ts +++ b/actions/omada-actions.ts @@ -35,50 +35,32 @@ interface OmadaResponse { }; } -async function fetchOmadaGroupProfiles( - omadacId: string, - siteId: string, -): Promise { - if (!omadacId || !siteId) { - throw new Error("omadacId and siteId are required parameters"); +async function fetchOmadaGroupProfiles(siteId: string): Promise { + if (!siteId) { + throw new Error("siteId is a required parameter"); } - const timestamp: number = Date.now(); - const baseUrl: string = "https://omada.sarlink.link"; - const url: string = `${baseUrl}/${omadacId}/api/v2/sites/${siteId}/setting/profiles/groups?_t=${timestamp}`; + const baseUrl: string = process.env.OMADA_BASE_URL || ""; + const url: string = `${baseUrl}/api/v2/sites/${siteId}/setting/profiles/groups`; const headers: HeadersInit = { - accept: "application/json, text/plain, */*", - "accept-language": "en-US,en;q=0.9", - cookie: "TPOMADA_SESSIONID=f30bf82348784089ba90740e59e4aa99", - "csrf-token": "fedc6283e9604372b402f82fdaeba0db", - priority: "u=1, i", - referer: baseUrl, - refresh: "manual", - "sec-ch-ua": '"Brave";v="131", "Chromium";v="131", "Not_A Brand";v="24"', - "sec-ch-ua-mobile": "?0", - "sec-ch-ua-platform": '"Linux"', - "sec-fetch-dest": "empty", - "sec-fetch-mode": "cors", - "sec-fetch-site": "same-origin", - "sec-gpc": "1", - "user-agent": - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", - "x-requested-with": "XMLHttpRequest", + "X-API-key": process.env.OMADA_PROXY_API_KEY || "", }; try { const response: Response = await fetch(url, { method: "GET", headers: headers, - credentials: "include", }); - if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data: OmadaResponse = await response.json(); + if (data.errorCode !== 0) { + throw new Error(`Error fetching group profiles: ${data.msg}`); + } + console.log({ data }); return data; } catch (error) { console.error("Error fetching Omada group profiles:", error); @@ -89,27 +71,22 @@ async function fetchOmadaGroupProfiles( export { fetchOmadaGroupProfiles, type MacAddress }; export async function addDevicesToGroup({ - omadacId, siteId, groupId, newDevices, }: { - omadacId?: string; siteId?: string; groupId?: string; newDevices: MacAddress[]; -}): Promise { - if (!omadacId || !siteId || !groupId) { +}) { + if (!siteId || !groupId) { throw new Error("omadacId, siteId, and groupId are required parameters"); } try { // Fetch the existing group profiles - const groupProfiles: OmadaResponse = await fetchOmadaGroupProfiles( - omadacId, - siteId, - ); - + const groupProfiles: OmadaResponse = await fetchOmadaGroupProfiles(siteId); + console.log(groupProfiles); // Find the group profile with the specified groupId const groupProfile: GroupProfile | undefined = groupProfiles.result.data.find((profile) => profile.groupId === groupId); @@ -123,7 +100,7 @@ export async function addDevicesToGroup({ ...(groupProfile.macAddressList || []), ...newDevices, ]; - + console.log({ updatedMacAddressList }); // Prepare the request payload const requestBody = { name: groupProfile.name, @@ -139,38 +116,20 @@ export async function addDevicesToGroup({ domainNamePort: null, }; - const timestamp: number = Date.now(); - const baseUrl: string = "https://omada.sarlink.link"; - const url: string = `${baseUrl}/${omadacId}/api/v2/sites/${siteId}/setting/profiles/groups/2/${groupId}?_t=${timestamp}`; + console.log(requestBody); + const baseUrl = process.env.OMADA_BASE_URL || ""; + const url: string = `${baseUrl}/api/v2/sites/${siteId}/setting/profiles/groups/2/${groupId}`; const headers: HeadersInit = { - accept: "application/json, text/plain, */*", - "accept-language": "en-US,en;q=0.9", - "content-type": "application/json;charset=UTF-8", - cookie: "TPOMADA_SESSIONID=f30bf82348784089ba90740e59e4aa99", - "csrf-token": "fedc6283e9604372b402f82fdaeba0db", - origin: baseUrl, - priority: "u=1, i", - referer: baseUrl, - refresh: "manual", - "sec-ch-ua": '"Brave";v="131", "Chromium";v="131", "Not_A Brand";v="24"', - "sec-ch-ua-mobile": "?0", - "sec-ch-ua-platform": '"Linux"', - "sec-fetch-dest": "empty", - "sec-fetch-mode": "cors", - "sec-fetch-site": "same-origin", - "sec-gpc": "1", - "user-agent": - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", - "x-requested-with": "XMLHttpRequest", + "X-API-key": process.env.OMADA_PROXY_API_KEY || "", }; - const response: Response = await fetch(url, { + const response = await fetch(url, { method: "PATCH", headers: headers, body: JSON.stringify(requestBody), }); - + console.log(response); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } diff --git a/actions/payment.ts b/actions/payment.ts index 29eb23e..b842ba8 100644 --- a/actions/payment.ts +++ b/actions/payment.ts @@ -2,6 +2,7 @@ import prisma from "@/lib/db"; import type { PaymentType } from "@/lib/types"; +import { formatMacAddress } from "@/lib/utils"; import { revalidatePath } from "next/cache"; import { addDevicesToGroup } from "./omada-actions"; @@ -60,7 +61,7 @@ export async function verifyPayment(data: VerifyPaymentType) { const newDevices = payment?.devices.map((d) => { return { name: d.name, - macAddress: d.mac, + macAddress: formatMacAddress(d.mac), }; }); if (json.success === true) { @@ -73,17 +74,18 @@ export async function verifyPayment(data: VerifyPaymentType) { paid: true, }, }), - addDevicesToGroup({ - groupId: process.env.OMADA_GROUP_ID, - omadacId: process.env.OMADA_CID, - siteId: process.env.OMADA_SITE_ID, - newDevices: newDevices || [], - }), ]); } + const res = await addDevicesToGroup({ + groupId: process.env.OMADA_GROUP_ID, + siteId: process.env.OMADA_SITE_ID, + newDevices: newDevices || [], + }); + revalidatePath("/payment[paymentId]"); - return json; + console.log(res); + return res; } catch (error) { console.error(error); } diff --git a/components/devices-to-pay.tsx b/components/devices-to-pay.tsx index 508aa24..23b1513 100644 --- a/components/devices-to-pay.tsx +++ b/components/devices-to-pay.tsx @@ -77,7 +77,7 @@ export default function DevicesToPay({ disabled={verifying} onClick={async () => { setVerifying(true); - const res = await verifyPayment({ + await verifyPayment({ paymentId: payment?.id, benefName: user?.name ?? "", accountNo: user?.accNo ?? "", @@ -85,16 +85,16 @@ export default function DevicesToPay({ time: formatDate(new Date(payment?.createdAt || "")), }); setVerifying(false); - switch (true) { - case res.success === true: - toast.success(res.message); - break; - case res.success === false: - toast.error(res.message); - break; - default: - toast.error("Unexpected error occurred."); - } + // switch (true) { + // case res?.success === true: + // toast.success(res.message); + // break; + // case res.success === false: + // toast.error(res.message); + // break; + // default: + // toast.error("Unexpected error occurred."); + // } }} size={"lg"} className="mb-4"> {verifying ? "Verifying..." : "Verify Payment"} @@ -104,16 +104,16 @@ export default function DevicesToPay({ - + Total Devices - {devices?.length} + {devices?.length} - - Total - {total.toFixed(2)} + + Total Due + {total.toFixed(2)} diff --git a/lib/utils.ts b/lib/utils.ts index e0d51a2..90fd3c7 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -16,3 +16,13 @@ export const formatDate = (date: Date): string => { return `${year}-${month}-${day} ${hours}:${minutes}`; }; + +export const formatMacAddress = (mac: string): string => { + const formatted = mac + .replace(/[^A-Fa-f0-9]/g, "") + .toUpperCase() + .match(/.{2}/g); + + // Provide a fallback if formatted is null + return formatted ? formatted.join("-") : ""; +};