Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: ORV2-1933 Cleanup PayBC Redirection Flow #1159

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions frontend/src/common/types/paymentTransaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

export type ApplicationDetails = {
applicationId: string;
transactionAmount: number;
}

export type PaymentTransaction = {
pgTransactionId: string;
pgApproved: number;
pgAuthCode: string;
pgCardType: string;
pgTransactionDate: string;
pgCvdId: number;
pgPaymentMethod: string;
pgMessageId: number;
pgMessageText: string;
transactionId: string;
totalTransactionAmount: number;
applicationDetails: Array<ApplicationDetails>;
};
zgong-gov marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@ const PAYMENT_API_BASE = `${VEHICLES_URL}/payment`;
export const PAYMENT_API_ROUTES = {
START: PAYMENT_API_BASE,
COMPLETE: PAYMENT_API_BASE,
GET: PAYMENT_API_BASE,
PAYMENT_GATEWAY: `payment-gateway`,
};
31 changes: 25 additions & 6 deletions frontend/src/features/permits/helpers/payment.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { PayBCPaymentDetails } from "../types/payment";
import { parseRedirectUriPath } from "../pages/Payment/PaymentRedirect";
import { Nullable } from "../../../common/types/common";
import { Nullable, RequiredOrNull } from "../../../common/types/common";
import {
PAYMENT_GATEWAY_METHODS,
PAYMENT_METHOD_TYPE_CODE,
Expand All @@ -12,6 +11,9 @@ import {
applyWhenNotNullable,
getDefaultRequiredVal,
} from "../../../common/helpers/util";
import { httpGETRequest } from "../../../common/apiManager/httpRequestHandler";
import { PAYMENT_API_ROUTES } from "../apiManager/endpoints/endpoints";
import { PaymentTransaction } from "../../../common/types/paymentTransaction";

/**
* Extracts PayBCPaymentDetails from the query parameters of a URL.
Expand All @@ -23,9 +25,6 @@ export const getPayBCPaymentDetails = (
params: URLSearchParams,
): PayBCPaymentDetails => {
// Extract the query parameters and assign them to the corresponding properties of PayBCPaymentDetails
const path = getDefaultRequiredVal("", params.get("path"));
const { trnApproved } = parseRedirectUriPath(path);

const payBCPaymentDetails: PayBCPaymentDetails = {
authCode: params.get("authCode"),
avsAddrMatch: getDefaultRequiredVal("", params.get("avsAddrMatch")),
Expand All @@ -36,7 +35,10 @@ export const getPayBCPaymentDetails = (
avsResult: getDefaultRequiredVal("", params.get("avsResult")),
cardType: getDefaultRequiredVal("", params.get("cardType")),
cvdId: applyWhenNotNullable((cvdId) => Number(cvdId), params.get("cvdId")),
trnApproved: trnApproved,
trnApproved: applyWhenNotNullable(
(approved) => Number(approved),
params.get("trnApproved"),
zgong-gov marked this conversation as resolved.
Show resolved Hide resolved
),
messageId: applyWhenNotNullable(
(messageId) => Number(messageId),
params.get("messageId"),
Expand Down Expand Up @@ -85,3 +87,20 @@ export const isValidTransaction = (
(!!transactionApproved && transactionApproved > 0)
);
};

/**
* Fetch payment information by transaction id.
* @param transactionId transaction id of the payment details to fetch
* @returns PaymentTransaction data as response, or null if fetch failed
*/
export const getPaymentByTransactionId = async (
transactionId?: string,
): Promise<RequiredOrNull<PaymentTransaction>> => {
try {
const url = `${PAYMENT_API_ROUTES.GET}/${transactionId}`;
const response = await httpGETRequest(url);
return response.data;
} catch (err) {
return null;
}
};
77 changes: 25 additions & 52 deletions frontend/src/features/permits/pages/Payment/PaymentRedirect.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { Navigate, useNavigate, useSearchParams } from "react-router-dom";

import { getPayBCPaymentDetails } from "../../helpers/payment";
import { getPayBCPaymentDetails, getPaymentByTransactionId } from "../../helpers/payment";
import { Loading } from "../../../../common/pages/Loading";
import { useCompleteTransaction, useIssuePermits } from "../../hooks/hooks";
import { getDefaultRequiredVal } from "../../../../common/helpers/util";
import { DATE_FORMATS, toUtc } from "../../../../common/helpers/formatDate";
import { hasPermitsActionFailed } from "../../helpers/permitState";
import { PaymentCardTypeCode } from "../../../../common/types/paymentMethods";
import { Nullable } from "../../../../common/types/common";
import {
APPLICATIONS_ROUTES,
ERROR_ROUTES,
Expand All @@ -20,40 +19,6 @@ import {
PayBCPaymentDetails,
} from "../../types/payment";

const PERMIT_ID_DELIM = ",";
const PATH_DELIM = "?";

const getPermitIdsArray = (permitIds?: Nullable<string>) => {
return getDefaultRequiredVal("", permitIds)
.split(PERMIT_ID_DELIM)
.filter((id) => id !== "");
};

export const parseRedirectUriPath = (path?: Nullable<string>) => {
const splitPath = path?.split(PATH_DELIM);
let permitIds = "";
let trnApproved = 0;
if (splitPath?.[0]) {
permitIds = splitPath[0];
}

if (splitPath?.[1]) {
trnApproved = parseInt(splitPath[1]?.split("=")?.[1]);
}

return { permitIds, trnApproved };
};

const exportPathFromSearchParams = (
params: URLSearchParams,
trnApproved: number,
) => {
const localParams = new URLSearchParams(params);
localParams.delete("path");
const updatedPath = localParams.toString();
return encodeURIComponent(`trnApproved=${trnApproved}&` + updatedPath);
};

/**
* React component that handles the payment redirect and displays the payment status.
* If the payment status is "Approved", it renders the SuccessPage component.
Expand All @@ -66,23 +31,17 @@ export const PaymentRedirect = () => {
const [searchParams] = useSearchParams();
const paymentDetails = getPayBCPaymentDetails(searchParams);
const transaction = mapTransactionDetails(paymentDetails);

const path = getDefaultRequiredVal("", searchParams.get("path"));
const { permitIds, trnApproved } = parseRedirectUriPath(path);
const transactionQueryString = exportPathFromSearchParams(
searchParams,
trnApproved,
);
const transactionId = getDefaultRequiredVal("", searchParams.get("ref2"));

const [applicationIds, setApplicationIds] = useState<string[] | []>([]);
const transactionQueryString = encodeURIComponent(searchParams.toString());
zgong-gov marked this conversation as resolved.
Show resolved Hide resolved

const { mutation: completeTransactionMutation, paymentApproved } =
useCompleteTransaction(
paymentDetails.messageText,
paymentDetails.trnApproved,
);

const { mutation: issuePermitsMutation, issueResults } = useIssuePermits();

const issueFailed = hasPermitsActionFailed(issueResults);

useEffect(() => {
Expand All @@ -97,24 +56,38 @@ export const PaymentRedirect = () => {
}, [paymentDetails.trnApproved]);

useEffect(() => {
if (issuedPermit.current === false) {
const permitIdsArray = getPermitIdsArray(permitIds);
const ids:string[] = [];
getPaymentByTransactionId(transactionId)
.then((response) => {
response?.applicationDetails?.forEach((application) => {
if (application?.applicationId) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we use a useQuery for this?

ids.push(application.applicationId)
}
})
}).finally(() => {
setApplicationIds(ids);
})

}, [transactionId]);

useEffect(() => {
if (applicationIds?.length > 0 && issuedPermit.current === false) {

if (permitIdsArray.length === 0) {
if (applicationIds?.length === 0) {
// permit ids should not be empty, if so then something went wrong
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line 74 and Line 76 are contradictory if checks. applicationIds?.length > 0 and applicationIds?.length === 0

navigate(ERROR_ROUTES.UNEXPECTED, { replace: true });
} else if (paymentApproved === true) {
// Payment successful, proceed to issue permit
issuePermitsMutation.mutate(permitIdsArray);
issuePermitsMutation.mutate(applicationIds);
issuedPermit.current = true;
} else if (paymentApproved === false) {
// Payment failed, redirect back to pay now page
navigate(APPLICATIONS_ROUTES.PAY(permitIdsArray[0], true), {
navigate(APPLICATIONS_ROUTES.PAY(applicationIds[0], true), {
replace: true,
});
}
}
}, [paymentApproved, permitIds]);
}, [paymentApproved, applicationIds]);

if (issueFailed) {
return <Navigate to={`${ERROR_ROUTES.UNEXPECTED}`} replace={true} />;
Expand Down
11 changes: 1 addition & 10 deletions vehicles/src/modules/payment/payment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,7 @@ export class PaymentService {
};

private queryHash = (transaction: Transaction) => {
const permitIds = transaction.permitTransactions.map(
(permitTransaction) => {
return permitTransaction.permit.permitId;
},
);
// Construct the URL with the transaction details for the payment gateway
const redirectUrl = permitIds
? `${process.env.PAYBC_REDIRECT}` + `?path=${permitIds.join(',')}`
: `${process.env.PAYBC_REDIRECT}`;

const redirectUrl = process.env.PAYBC_REDIRECT;
const date = new Date().toISOString().split('T')[0];

// There should be a better way of doing this which is not as rigid - something like
Expand Down
Loading