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(wallet/backend): add view card transactions endpoint #1661

Merged
merged 7 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions packages/wallet/backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,11 @@ export class App {
router.get('/cards/:cardId/details', isAuth, cardController.getCardDetails)
router.put('/cards/:cardId/lock', isAuth, cardController.lock)
router.put('/cards/:cardId/unlock', isAuth, cardController.unlock)
router.get(
'/cards/:cardId/transactions',
isAuth,
cardController.getCardTransactions
)
router.get('/cards/:cardId/pin', isAuth, cardController.getPin)
router.post('/cards/:cardId/change-pin', isAuth, cardController.changePin)

Expand Down
75 changes: 51 additions & 24 deletions packages/wallet/backend/src/card/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,25 @@ import {
ICardResponse,
ICardUnlockRequest
} from './types'
import { IGetTransactionsResponse } from '@wallet/shared/src'
import { validate } from '@/shared/validate'
import {
getCardsByCustomerSchema,
getCardDetailsSchema,
lockCardSchema,
unlockCardSchema,
getCardTransactionsSchema,
changePinSchema
} from './validation'

export interface ICardController {
getCardsByCustomer: Controller<ICardDetailsResponse[]>
getCardDetails: Controller<ICardResponse>
lock: Controller<ICardResponse>
unlock: Controller<ICardResponse>
getCardTransactions: Controller<IGetTransactionsResponse>
getPin: Controller<ICardResponse>
changePin: Controller<void>
lock: Controller<ICardResponse>
unlock: Controller<ICardResponse>
}

export class CardController implements ICardController {
Expand Down Expand Up @@ -68,34 +71,25 @@ export class CardController implements ICardController {
}
}

public lock = async (req: Request, res: Response, next: NextFunction) => {
public getCardTransactions = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { params, query, body } = await validate(lockCardSchema, req)
const userId = req.session.user.id
const { params, query } = await validate(getCardTransactionsSchema, req)
const { cardId } = params
const { reasonCode } = query
const requestBody: ICardLockRequest = body
const { pageSize, pageNumber } = query

const result = await this.cardService.lock(
const transactions = await this.cardService.getCardTransactions(
userId,
cardId,
reasonCode,
requestBody
pageSize,
pageNumber
)

res.status(200).json(toSuccessResponse(result))
} catch (error) {
next(error)
}
}

public unlock = async (req: Request, res: Response, next: NextFunction) => {
try {
const { params, body } = await validate(unlockCardSchema, req)
const { cardId } = params
const requestBody: ICardUnlockRequest = body

const result = await this.cardService.unlock(cardId, requestBody)

res.status(200).json(toSuccessResponse(result))
res.status(200).json(toSuccessResponse(transactions))
} catch (error) {
next(error)
}
Expand Down Expand Up @@ -133,4 +127,37 @@ export class CardController implements ICardController {
next(error)
}
}

public lock = async (req: Request, res: Response, next: NextFunction) => {
try {
const { params, query, body } = await validate(lockCardSchema, req)
const { cardId } = params
const { reasonCode } = query
const requestBody: ICardLockRequest = body

const result = await this.cardService.lock(
cardId,
reasonCode,
requestBody
)

res.status(200).json(toSuccessResponse(result))
} catch (error) {
next(error)
}
}

public unlock = async (req: Request, res: Response, next: NextFunction) => {
try {
const { params, body } = await validate(unlockCardSchema, req)
const { cardId } = params
const requestBody: ICardUnlockRequest = body

const result = await this.cardService.unlock(cardId, requestBody)

res.status(200).json(toSuccessResponse(result))
} catch (error) {
next(error)
}
}
}
13 changes: 13 additions & 0 deletions packages/wallet/backend/src/card/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
ICardResponse,
ICardUnlockRequest
} from './types'
import { IGetTransactionsResponse } from '@wallet/shared/src'
import { LockReasonCode } from '@wallet/shared/src'
import { NotFound } from '@shared/backend'

Expand All @@ -26,10 +27,22 @@ export class CardService {
): Promise<ICardDetailsResponse> {
const { cardId } = requestBody
await this.ensureWalletAddressExists(userId, cardId)
await this.ensureWalletAddressExists(userId, cardId)

return this.gateHubClient.getCardDetails(requestBody)
}

async getCardTransactions(
userId: string,
cardId: string,
pageSize?: number,
pageNumber?: number
): Promise<IGetTransactionsResponse> {
await this.ensureWalletAddressExists(userId, cardId)

return this.gateHubClient.getCardTransactions(cardId, pageSize, pageNumber)
}

async getPin(
userId: string,
requestBody: ICardDetailsRequest
Expand Down
10 changes: 10 additions & 0 deletions packages/wallet/backend/src/card/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ export const unlockCardSchema = z.object({
})
})

export const getCardTransactionsSchema = z.object({
params: z.object({
cardId: z.string()
}),
query: z.object({
pageSize: z.coerce.number().int().positive().optional(),
pageNumber: z.coerce.number().int().nonnegative().optional()
})
})

export const changePinSchema = z.object({
params: z.object({
cardId: z.string()
Expand Down
30 changes: 28 additions & 2 deletions packages/wallet/backend/src/gatehub/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ import {
} from '@/gatehub/consts'
import axios, { AxiosError } from 'axios'
import { Logger } from 'winston'
import { IFRAME_TYPE, LockReasonCode } from '@wallet/shared/src'
import {
IFRAME_TYPE,
LockReasonCode,
IGetTransactionsResponse
} from '@wallet/shared/src'
import { BadRequest } from '@shared/backend'
import {
ICardDetailsResponse,
Expand All @@ -43,7 +47,6 @@ import {
ICardLockRequest,
ICardUnlockRequest
} from '@/card/types'

export class GateHubClient {
private clientIds = SANDBOX_CLIENT_IDS
private mainUrl = 'sandbox.gatehub.net'
Expand Down Expand Up @@ -377,6 +380,29 @@ export class GateHubClient {
return cardDetailsResponse
}

async getCardTransactions(
cardId: string,
pageSize?: number,
pageNumber?: number
): Promise<IGetTransactionsResponse> {
let url = `${this.apiUrl}/v1/cards/${cardId}/transactions`

const queryParams: string[] = []

if (pageSize !== undefined)
queryParams.push(`pageSize=${encodeURIComponent(pageSize.toString())}`)
if (pageNumber !== undefined)
queryParams.push(
`pageNumber=${encodeURIComponent(pageNumber.toString())}`
)

if (queryParams.length > 0) {
url += `?${queryParams.join('&')}`
}

return this.request<IGetTransactionsResponse>('GET', url)
}

async lockCard(
cardId: string,
reasonCode: LockReasonCode,
Expand Down
106 changes: 106 additions & 0 deletions packages/wallet/backend/tests/cards/controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import { CardController } from '@/card/controller'
import { BadRequest } from '@shared/backend'
import { ICardDetailsResponse, ICardResponse } from '@/card/types'
import { IGetTransactionsResponse } from '@wallet/shared/src'
import { AwilixContainer } from 'awilix'
import { Cradle } from '@/createContainer'
import { createApp, TestApp } from '@/tests/app'
Expand Down Expand Up @@ -35,6 +36,7 @@ describe('CardController', () => {
const mockCardService = {
getCardsByCustomer: jest.fn(),
getCardDetails: jest.fn(),
getCardTransactions: jest.fn(),
lock: jest.fn(),
unlock: jest.fn(),
getPin: jest.fn(),
Expand Down Expand Up @@ -217,6 +219,110 @@ describe('CardController', () => {
})
})

describe('getCardTransactions', () => {
it('should get card transactions successfully', async () => {
const next = jest.fn()

const mockedTransactions: IGetTransactionsResponse = {
data: [
{
id: 1,
transactionId: '78b34171-0a7c-4185-9fd5-7c5f366ed50b',
ghResponseCode: 'TRXNS',
cardScheme: 3,
type: 1,
createdAt: '2024-02-01T00:00:00.000Z',
txStatus: 'PROCESSING',
vaultId: 1,
cardId: 1,
refTransactionId: '',
responseCode: null,
transactionAmount: '1.1',
transactionCurrency: 'EUR',
billingAmount: '1.1',
billingCurrency: 'EUR',
terminalId: null,
wallet: 123,
transactionDateTime: '2024-02-01T00:00:00.000Z',
processDateTime: null
},
{
id: 2,
transactionId: '545b34171-0a7c-4185-9fd5-7c5f366e4566',
ghResponseCode: 'TRXNS',
cardScheme: 3,
type: 1,
createdAt: '2024-02-01T00:00:00.000Z',
txStatus: 'PROCESSING',
vaultId: 1,
cardId: 1,
refTransactionId: '',
responseCode: null,
transactionAmount: '1.1',
transactionCurrency: 'EUR',
billingAmount: '1.1',
billingCurrency: 'EUR',
terminalId: null,
wallet: 123,
transactionDateTime: '2024-02-01T00:00:00.000Z',
processDateTime: null
}
],
pagination: {
pageNumber: 1,
pageSize: 10,
totalRecords: 2,
totalPages: 1
}
}

mockCardService.getCardTransactions.mockResolvedValue(mockedTransactions)

req.params = { cardId: 'test-card-id' }
req.query = { pageSize: '10', pageNumber: '1' }

await cardController.getCardTransactions(req, res, next)

expect(mockCardService.getCardTransactions).toHaveBeenCalledWith(
userId,
'test-card-id',
10,
1
)
expect(res.statusCode).toBe(200)
expect(res._getJSONData()).toEqual({
success: true,
message: 'SUCCESS',
result: mockedTransactions
})
})
it('should return 400 if page size is invalid', async () => {
const next = jest.fn()

req.params = { cardId: 'test-card-id' }
// Invalid pageSize
req.query = { pageSize: '-1', pageNumber: '1' }

await cardController.getCardTransactions(req, res, (err) => {
next(err)
res.status(err.statusCode).json({
success: false,
message: err.message
})
})

expect(next).toHaveBeenCalled()
const error = next.mock.calls[0][0]
expect(error).toBeInstanceOf(BadRequest)
expect(error.message).toBe('Invalid input')
expect(res.statusCode).toBe(400)
expect(res._getJSONData()).toEqual({
success: false,
message: 'Invalid input'
})
})
})

describe('lock', () => {
it('should lock card successfully', async () => {
const next = jest.fn()
Expand Down
35 changes: 35 additions & 0 deletions packages/wallet/shared/src/types/card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,38 @@ export type LockReasonCode =
| 'IssuerRequestGeneral'
| 'IssuerRequestFraud'
| 'IssuerRequestLegal'

// Response for fetching card transactions
export interface ITransaction {
id: number
transactionId: string
ghResponseCode: string
cardScheme: number
type: number
createdAt: string
txStatus: string
vaultId: number
cardId: number
refTransactionId: string
responseCode: string | null
transactionAmount: string
transactionCurrency: string
billingAmount: string
billingCurrency: string
terminalId: string | null
wallet: number
transactionDateTime: string
processDateTime: string | null
}

export interface IPagination {
pageNumber: number
pageSize: number
totalPages: number
totalRecords: number
}

export interface IGetTransactionsResponse {
data: ITransaction[]
pagination: IPagination
}
Loading