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

Add method of supportsReadersOfType #686

Merged
merged 3 commits into from
May 14, 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
28 changes: 27 additions & 1 deletion android/src/main/java/com/stripeterminalreactnative/Mappers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import com.stripe.stripeterminal.external.models.ReaderInputOptions
import com.stripe.stripeterminal.external.models.ReaderInputOptions.ReaderInputOption
import com.stripe.stripeterminal.external.models.ReaderSettings
import com.stripe.stripeterminal.external.models.ReaderSoftwareUpdate
import com.stripe.stripeterminal.external.models.ReaderSupportResult
import com.stripe.stripeterminal.external.models.ReaderTextToSpeechStatus
import com.stripe.stripeterminal.external.models.ReceiptDetails
import com.stripe.stripeterminal.external.models.Refund
Expand Down Expand Up @@ -140,14 +141,33 @@ internal fun mapFromDeviceType(type: DeviceType): String {
DeviceType.STRIPE_S700_DEVKIT -> "stripeS700Devkit"
DeviceType.UNKNOWN -> "unknown"
DeviceType.VERIFONE_P400 -> "verifoneP400"
DeviceType.WISECUBE -> "wisecube"
DeviceType.WISECUBE -> "wiseCube"
DeviceType.WISEPAD_3 -> "wisePad3"
DeviceType.WISEPAD_3S -> "wisePad3s"
DeviceType.WISEPOS_E -> "wisePosE"
DeviceType.WISEPOS_E_DEVKIT -> "wisePosEDevkit"
}
}

internal fun mapToDeviceType(type: String): DeviceType? {
return when (type) {
"chipper1X" -> DeviceType.CHIPPER_1X
"chipper2X" -> DeviceType.CHIPPER_2X
"cotsDevice" -> DeviceType.COTS_DEVICE
"etna" -> DeviceType.ETNA
"stripeM2" -> DeviceType.STRIPE_M2
"stripeS700" -> DeviceType.STRIPE_S700
"stripeS700Devkit" -> DeviceType.STRIPE_S700_DEVKIT
"verifoneP400" -> DeviceType.VERIFONE_P400
"wiseCube" -> DeviceType.WISECUBE
"wisePad3" -> DeviceType.WISEPAD_3
"wisePad3s" -> DeviceType.WISEPAD_3S
"wisePosE" -> DeviceType.WISEPOS_E
"wisePosEDevkit" -> DeviceType.WISEPOS_E_DEVKIT
else -> null
}
Comment on lines +152 to +168

Choose a reason for hiding this comment

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

How do we keep this list up to date; i.e when there is a new device type on the android sdk, can we have a two way map; i.e also have a mapFromDeviceType if one does not exist already, because an exhaustive when with the android DeviceType enum model would result in a compilation error when there is a new DeviceType enum.
Also do we have tests for the Mappers?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

yes, there has a mapFromDeviceType, I think we need to sync manually when there is a new device type..

}

internal fun mapFromLocationStatus(status: LocationStatus): String {
return when (status) {
LocationStatus.NOT_SET -> "notSet"
Expand Down Expand Up @@ -730,3 +750,9 @@ fun mapFromCollectInputsResults(results: List<CollectInputsResult>): ReadableArr
}
}
}

fun mapFromReaderSupportResult(readerSupportResult: ReaderSupportResult): ReadableMap {
return nativeMapOf {
putBoolean("readerSupportResult", readerSupportResult.isSupported)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,45 @@ class StripeTerminalReactNativeModule(reactContext: ReactApplicationContext) :
cancelOperation(promise, collectInputsCancelable, "collectInputs")
}

@ReactMethod
@Suppress("unused")
fun supportsReadersOfType(params: ReadableMap, promise: Promise) {
val deviceTypeParams = requireParam(params.getString("deviceType")) {
"You must provide a deviceType"
}
val deviceType = requireParam(mapToDeviceType(deviceTypeParams)) {
"Unknown readerType: $deviceTypeParams"
}
val discoveryMethodParam = requireParam(params.getString("discoveryMethod")) {
"You must provide a discoveryMethod"
}
val discoveryMethod = requireParam(mapToDiscoveryMethod(discoveryMethodParam)) {
"Unknown discoveryMethod: $discoveryMethodParam"
}

val readerSupportResult = terminal.supportsReadersOfType(
deviceType,
when (discoveryMethod) {
DiscoveryMethod.BLUETOOTH_SCAN -> DiscoveryConfiguration.BluetoothDiscoveryConfiguration(
getInt(params, "timeout") ?: 0,
getBoolean(params, "simulated")
)
DiscoveryMethod.INTERNET -> DiscoveryConfiguration.InternetDiscoveryConfiguration(
isSimulated = getBoolean(params, "simulated")
)
DiscoveryMethod.USB -> DiscoveryConfiguration.UsbDiscoveryConfiguration(
getInt(params, "timeout") ?: 0,
getBoolean(params, "simulated")
)
DiscoveryMethod.HANDOFF -> DiscoveryConfiguration.HandoffDiscoveryConfiguration()
DiscoveryMethod.LOCAL_MOBILE -> DiscoveryConfiguration.LocalMobileDiscoveryConfiguration(
getBoolean(params, "simulated")
) }
)

promise.resolve(mapFromReaderSupportResult(readerSupportResult))
}

@ReactMethod
fun addListener(eventName: String?) {
// Set up any upstream listeners or background tasks as necessary
Expand Down
18 changes: 18 additions & 0 deletions ios/Mappers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,24 @@ class Mappers {
default: return "unknown"
}
}

class func mapToDeviceType(_ type: String) -> DeviceType? {
switch type {
case "appleBuiltIn": return DeviceType.appleBuiltIn
case "chipper1X": return DeviceType.chipper1X
case "chipper2X": return DeviceType.chipper2X
case "etna": return DeviceType.etna
case "stripeM2": return DeviceType.stripeM2
case "stripeS700": return DeviceType.stripeS700
case "stripeS700Devkit": return DeviceType.stripeS700DevKit
case "verifoneP400": return DeviceType.verifoneP400
case "wiseCube": return DeviceType.wiseCube
case "wisePad3": return DeviceType.wisePad3
case "wisePosE": return DeviceType.wisePosE
case "wisePosEDevkit": return DeviceType.wisePosEDevKit
default: return nil
}
}

class func mapToCartLineItem(_ cartLineItem: NSDictionary) -> CartLineItem? {
guard let displayName = cartLineItem["displayName"] as? String else { return nil }
Expand Down
5 changes: 5 additions & 0 deletions ios/StripeTerminalReactNative.m
Original file line number Diff line number Diff line change
Expand Up @@ -221,4 +221,9 @@ @interface RCT_EXTERN_MODULE(StripeTerminalReactNative, RCTEventEmitter)
rejecter: (RCTPromiseRejectBlock)reject
)

RCT_EXTERN_METHOD(
supportsReadersOfType:(NSDictionary *)params
resolver: (RCTPromiseResolveBlock)resolve
rejecter: (RCTPromiseRejectBlock)reject
)
@end
28 changes: 28 additions & 0 deletions ios/StripeTerminalReactNative.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,34 @@ class StripeTerminalReactNative: RCTEventEmitter, DiscoveryDelegate, BluetoothRe
}
}
}

@objc(supportsReadersOfType:resolver:rejecter:)
func supportsReadersOfType(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let invalidParams = Errors.validateRequiredParameters(params: params, requiredParams: ["deviceType", "discoveryMethod"])

if let invalidParams {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide \(invalidParams) parameters."))
return
}

let deviceTypeParam = params["deviceType"] as? String ?? ""
let simulated = params["simulated"] as? Bool ?? false
let discoveryMethod = params["discoveryMethod"] as? String
let deviceType = Mappers.mapToDeviceType(deviceTypeParam)
guard let deviceType else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide correct deviceType parameter."))
return
}
let result = Terminal.shared.supportsReaders(of: deviceType, discoveryMethod: Mappers.mapToDiscoveryMethod(discoveryMethod), simulated: simulated)
switch result {
case .success(_):
resolve(["readerSupportResult": true])
break
case .failure(let error):
resolve(["readerSupportResult": false])
break
}
}

func reader(_ reader: Reader, didReportAvailableUpdate update: ReaderSoftwareUpdate) {
sendEvent(withName: ReactNativeConstants.REPORT_AVAILABLE_UPDATE.rawValue, body: ["result": Mappers.mapFromReaderSoftwareUpdate(update) ?? [:]])
Expand Down
3 changes: 3 additions & 0 deletions src/StripeTerminalSdk.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ export interface StripeTerminalSdkType {
cancelReaderReconnection(): Promise<{
error?: StripeError;
}>;
supportsReadersOfType(
params: Reader.ReaderSupportParams
): Promise<Reader.ReaderSupportResult>;
}

export default StripeTerminalReactNative as StripeTerminalSdkType;
1 change: 1 addition & 0 deletions src/__tests__/__snapshots__/functions.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,6 @@ Object {
"setReaderSettings": [Function],
"setSimulatedCard": [Function],
"simulateReaderUpdate": [Function],
"supportsReadersOfType": [Function],
}
`;
17 changes: 17 additions & 0 deletions src/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -846,3 +846,20 @@ export async function cancelReaderReconnection(): Promise<{
}
}, 'cancelReaderReconnection')();
}

export async function supportsReadersOfType(
params: Reader.ReaderSupportParams
): Promise<Reader.ReaderSupportResult> {
return Logger.traceSdkMethod(async () => {
try {
const supportReaderResult = await StripeTerminalSdk.supportsReadersOfType(
params
);
return supportReaderResult;
} catch (error) {
return {
error: error as any,
};
}
}, 'supportsReadersOfType')();
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Object {
"setReaderSettings": [Function],
"setSimulatedCard": [Function],
"simulateReaderUpdate": [Function],
"supportsReadersOfType": [Function],
},
}
`;
19 changes: 19 additions & 0 deletions src/hooks/useStripeTerminal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
collectInputs,
cancelCollectInputs,
cancelReaderReconnection,
supportsReadersOfType,
} from '../functions';
import { StripeTerminalContext } from '../components/StripeTerminalContext';
import { useListener } from './useListener';
Expand Down Expand Up @@ -944,6 +945,23 @@ export function useStripeTerminal(props?: Props) {
return response;
}, [_isInitialized, setLoading]);

const _supportsReadersOfType = useCallback(
async (params: Reader.ReaderSupportParams) => {
if (!_isInitialized()) {
console.error(NOT_INITIALIZED_ERROR_MESSAGE);
throw Error(NOT_INITIALIZED_ERROR_MESSAGE);
}
setLoading(true);

const response = await supportsReadersOfType(params);

setLoading(false);

return response;
},
[_isInitialized, setLoading]
);

return {
initialize: _initialize,
discoverReaders: _discoverReaders,
Expand Down Expand Up @@ -984,6 +1002,7 @@ export function useStripeTerminal(props?: Props) {
collectInputs: _collectInputs,
cancelCollectInputs: _cancelCollectInputs,
cancelReaderReconnection: _cancelReaderReconnection,
supportsReadersOfType: _supportsReadersOfType,
emitter: emitter,
discoveredReaders,
connectedReader,
Expand Down
11 changes: 11 additions & 0 deletions src/types/Reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,15 @@ export namespace Reader {
export type ReaderSettingsParameters = {
textToSpeechViaSpeakers: boolean;
};

export type ReaderSupportParams = {
deviceType: DeviceType;
simulated?: boolean;
discoveryMethod: Reader.DiscoveryMethod;
};

export type ReaderSupportResult = {
error?: StripeError;
readerSupportResult: boolean;
};
}