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.
This commit is contained in:
i701 2024-12-21 00:24:29 +05:00
parent 1d6f4faf7e
commit 586c0e7210
4 changed files with 57 additions and 86 deletions

View File

@ -35,50 +35,32 @@ interface OmadaResponse {
};
}
async function fetchOmadaGroupProfiles(
omadacId: string,
siteId: string,
): Promise<OmadaResponse> {
if (!omadacId || !siteId) {
throw new Error("omadacId and siteId are required parameters");
async function fetchOmadaGroupProfiles(siteId: string): Promise<OmadaResponse> {
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<void> {
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}`);
}

View File

@ -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);
}

View File

@ -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({
</div>
</TableCaption>
<TableBody>
<TableBody className="">
<TableRow>
<TableCell>Total Devices</TableCell>
<TableCell className="text-right">{devices?.length}</TableCell>
<TableCell className="text-right text-xl">{devices?.length}</TableCell>
</TableRow>
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={1}>Total</TableCell>
<TableCell className="text-right">{total.toFixed(2)}</TableCell>
<TableRow className="">
<TableCell colSpan={1}>Total Due</TableCell>
<TableCell className="text-right text-3xl font-bold">{total.toFixed(2)}</TableCell>
</TableRow>
</TableFooter>
</Table>

View File

@ -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("-") : "";
};