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( async function fetchOmadaGroupProfiles(siteId: string): Promise<OmadaResponse> {
omadacId: string, if (!siteId) {
siteId: string, throw new Error("siteId is a required parameter");
): Promise<OmadaResponse> {
if (!omadacId || !siteId) {
throw new Error("omadacId and siteId are required parameters");
} }
const timestamp: number = Date.now(); const baseUrl: string = process.env.OMADA_BASE_URL || "";
const baseUrl: string = "https://omada.sarlink.link"; const url: string = `${baseUrl}/api/v2/sites/${siteId}/setting/profiles/groups`;
const url: string = `${baseUrl}/${omadacId}/api/v2/sites/${siteId}/setting/profiles/groups?_t=${timestamp}`;
const headers: HeadersInit = { const headers: HeadersInit = {
accept: "application/json, text/plain, */*", "X-API-key": process.env.OMADA_PROXY_API_KEY || "",
"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",
}; };
try { try {
const response: Response = await fetch(url, { const response: Response = await fetch(url, {
method: "GET", method: "GET",
headers: headers, headers: headers,
credentials: "include",
}); });
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
const data: OmadaResponse = await response.json(); const data: OmadaResponse = await response.json();
if (data.errorCode !== 0) {
throw new Error(`Error fetching group profiles: ${data.msg}`);
}
console.log({ data });
return data; return data;
} catch (error) { } catch (error) {
console.error("Error fetching Omada group profiles:", error); console.error("Error fetching Omada group profiles:", error);
@ -89,27 +71,22 @@ async function fetchOmadaGroupProfiles(
export { fetchOmadaGroupProfiles, type MacAddress }; export { fetchOmadaGroupProfiles, type MacAddress };
export async function addDevicesToGroup({ export async function addDevicesToGroup({
omadacId,
siteId, siteId,
groupId, groupId,
newDevices, newDevices,
}: { }: {
omadacId?: string;
siteId?: string; siteId?: string;
groupId?: string; groupId?: string;
newDevices: MacAddress[]; newDevices: MacAddress[];
}): Promise<void> { }) {
if (!omadacId || !siteId || !groupId) { if (!siteId || !groupId) {
throw new Error("omadacId, siteId, and groupId are required parameters"); throw new Error("omadacId, siteId, and groupId are required parameters");
} }
try { try {
// Fetch the existing group profiles // Fetch the existing group profiles
const groupProfiles: OmadaResponse = await fetchOmadaGroupProfiles( const groupProfiles: OmadaResponse = await fetchOmadaGroupProfiles(siteId);
omadacId, console.log(groupProfiles);
siteId,
);
// Find the group profile with the specified groupId // Find the group profile with the specified groupId
const groupProfile: GroupProfile | undefined = const groupProfile: GroupProfile | undefined =
groupProfiles.result.data.find((profile) => profile.groupId === groupId); groupProfiles.result.data.find((profile) => profile.groupId === groupId);
@ -123,7 +100,7 @@ export async function addDevicesToGroup({
...(groupProfile.macAddressList || []), ...(groupProfile.macAddressList || []),
...newDevices, ...newDevices,
]; ];
console.log({ updatedMacAddressList });
// Prepare the request payload // Prepare the request payload
const requestBody = { const requestBody = {
name: groupProfile.name, name: groupProfile.name,
@ -139,38 +116,20 @@ export async function addDevicesToGroup({
domainNamePort: null, domainNamePort: null,
}; };
const timestamp: number = Date.now(); console.log(requestBody);
const baseUrl: string = "https://omada.sarlink.link"; const baseUrl = process.env.OMADA_BASE_URL || "";
const url: string = `${baseUrl}/${omadacId}/api/v2/sites/${siteId}/setting/profiles/groups/2/${groupId}?_t=${timestamp}`; const url: string = `${baseUrl}/api/v2/sites/${siteId}/setting/profiles/groups/2/${groupId}`;
const headers: HeadersInit = { const headers: HeadersInit = {
accept: "application/json, text/plain, */*", "X-API-key": process.env.OMADA_PROXY_API_KEY || "",
"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",
}; };
const response: Response = await fetch(url, { const response = await fetch(url, {
method: "PATCH", method: "PATCH",
headers: headers, headers: headers,
body: JSON.stringify(requestBody), body: JSON.stringify(requestBody),
}); });
console.log(response);
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }

View File

@ -2,6 +2,7 @@
import prisma from "@/lib/db"; import prisma from "@/lib/db";
import type { PaymentType } from "@/lib/types"; import type { PaymentType } from "@/lib/types";
import { formatMacAddress } from "@/lib/utils";
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { addDevicesToGroup } from "./omada-actions"; import { addDevicesToGroup } from "./omada-actions";
@ -60,7 +61,7 @@ export async function verifyPayment(data: VerifyPaymentType) {
const newDevices = payment?.devices.map((d) => { const newDevices = payment?.devices.map((d) => {
return { return {
name: d.name, name: d.name,
macAddress: d.mac, macAddress: formatMacAddress(d.mac),
}; };
}); });
if (json.success === true) { if (json.success === true) {
@ -73,17 +74,18 @@ export async function verifyPayment(data: VerifyPaymentType) {
paid: true, 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]"); revalidatePath("/payment[paymentId]");
return json; console.log(res);
return res;
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }

View File

@ -77,7 +77,7 @@ export default function DevicesToPay({
disabled={verifying} disabled={verifying}
onClick={async () => { onClick={async () => {
setVerifying(true); setVerifying(true);
const res = await verifyPayment({ await verifyPayment({
paymentId: payment?.id, paymentId: payment?.id,
benefName: user?.name ?? "", benefName: user?.name ?? "",
accountNo: user?.accNo ?? "", accountNo: user?.accNo ?? "",
@ -85,16 +85,16 @@ export default function DevicesToPay({
time: formatDate(new Date(payment?.createdAt || "")), time: formatDate(new Date(payment?.createdAt || "")),
}); });
setVerifying(false); setVerifying(false);
switch (true) { // switch (true) {
case res.success === true: // case res?.success === true:
toast.success(res.message); // toast.success(res.message);
break; // break;
case res.success === false: // case res.success === false:
toast.error(res.message); // toast.error(res.message);
break; // break;
default: // default:
toast.error("Unexpected error occurred."); // toast.error("Unexpected error occurred.");
} // }
}} }}
size={"lg"} className="mb-4"> size={"lg"} className="mb-4">
{verifying ? "Verifying..." : "Verify Payment"} {verifying ? "Verifying..." : "Verify Payment"}
@ -104,16 +104,16 @@ export default function DevicesToPay({
</div> </div>
</TableCaption> </TableCaption>
<TableBody> <TableBody className="">
<TableRow> <TableRow>
<TableCell>Total Devices</TableCell> <TableCell>Total Devices</TableCell>
<TableCell className="text-right">{devices?.length}</TableCell> <TableCell className="text-right text-xl">{devices?.length}</TableCell>
</TableRow> </TableRow>
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow className="">
<TableCell colSpan={1}>Total</TableCell> <TableCell colSpan={1}>Total Due</TableCell>
<TableCell className="text-right">{total.toFixed(2)}</TableCell> <TableCell className="text-right text-3xl font-bold">{total.toFixed(2)}</TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>

View File

@ -16,3 +16,13 @@ export const formatDate = (date: Date): string => {
return `${year}-${month}-${day} ${hours}:${minutes}`; 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("-") : "";
};