Files
psp_panel/src/app/core/services/native-bridge.service.ts
T

117 lines
3.0 KiB
TypeScript
Raw Normal View History

import { inject, Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { Maybe } from '../models';
import { ToastService } from './toast.service';
interface INativeBridgeHost {
pay?: (amount: number, id: Maybe<string>) => unknown;
print?: (payload: INativePrintRequest) => unknown;
isEnabled?: () => boolean;
getUUID?: () => Maybe<string>;
}
export interface INativePayRequest {
amount: number;
id: Maybe<string>;
}
export interface INativePrintRequest {
title: string;
items: {
label: string;
value: string;
}[];
}
export interface INativeBridgeResult<T = unknown> {
success: boolean;
data?: T;
error?: string;
}
@Injectable({ providedIn: 'root' })
export class NativeBridgeService {
private readonly toastService = inject(ToastService);
private get host(): INativeBridgeHost | undefined {
const globalWindow = window as unknown as {
NativeBridge?: INativeBridgeHost;
};
return globalWindow.NativeBridge;
}
isEnabled(): boolean {
if (!this.host) return false;
const hostEnabled = this.host?.isEnabled;
if (typeof hostEnabled === 'function') {
try {
return !!hostEnabled();
} catch {
return false;
}
}
return !!environment.enableNativeBridge && !!this.host;
}
canPay(): boolean {
return this.isEnabled() && typeof this.host?.pay === 'function';
}
canPrint(): boolean {
return this.isEnabled() && typeof this.host?.print === 'function';
}
pay(request: INativePayRequest): any {
this.toastService.info({ text: 'در حال پردازش پرداخت...', life: 3000 });
const fn = this.host?.pay;
if (typeof fn !== 'function') {
this.toastService.error({ text: 'متاسفانه پرداخت امکان‌پذیر نیست.', life: 3000 });
return { success: false, error: 'متاسفانه پرداخت امکان‌پذیر نیست.' };
}
try {
fn(request.amount, request.id);
return { success: true };
// return { success: true, data: parsed ?? raw };
} catch (error) {
return { success: false, error: (error as Error).message };
}
}
print(request: INativePrintRequest): INativeBridgeResult {
return this.invokePrint(request);
}
private invokePrint(payload: INativePrintRequest): INativeBridgeResult {
const fn = this.host?.print;
if (typeof fn !== 'function') {
return { success: false, error: 'متاسفانه چاپ امکان‌پذیر نیست.' };
}
try {
fn(payload);
return { success: true };
} catch (error) {
return { success: false, error: 'متاسفانه چاپ امکان‌پذیر نیست.' };
}
}
getNativeDeviceId(): Maybe<string> {
return typeof this.host?.getUUID === 'function' ? this.host.getUUID!() : null;
}
private tryParse(value: unknown): unknown {
if (typeof value !== 'string') return value;
try {
return JSON.parse(value);
} catch {
return value;
}
}
}