Assist_Design/apps/bff/src/integrations/whmcs/services/whmcs-currency.service.ts

100 lines
2.8 KiB
TypeScript

import { Injectable, Inject, OnModuleInit } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { getErrorMessage } from "@bff/core/utils/error.util";
import { WhmcsConnectionOrchestratorService } from "../connection/services/whmcs-connection-orchestrator.service";
import type { WhmcsCurrenciesResponse, WhmcsCurrency } from "../types/whmcs-api.types";
@Injectable()
export class WhmcsCurrencyService implements OnModuleInit {
private defaultCurrency: WhmcsCurrency | null = null;
private currencies: WhmcsCurrency[] = [];
constructor(
@Inject(Logger) private readonly logger: Logger,
private readonly connectionService: WhmcsConnectionOrchestratorService
) {}
async onModuleInit() {
try {
await this.loadCurrencies();
} catch (error) {
this.logger.error("Failed to load WHMCS currencies on startup", {
error: getErrorMessage(error),
});
// Set fallback default
this.defaultCurrency = {
id: 1,
code: "JPY",
prefix: "¥",
suffix: "",
format: "1",
rate: "1.00000",
};
}
}
/**
* Get the default currency (first currency from WHMCS or JPY fallback)
*/
getDefaultCurrency(): WhmcsCurrency {
return (
this.defaultCurrency || {
id: 1,
code: "JPY",
prefix: "¥",
suffix: "",
format: "1",
rate: "1.00000",
}
);
}
/**
* Get all available currencies
*/
getAllCurrencies(): WhmcsCurrency[] {
return this.currencies;
}
/**
* Find currency by code
*/
getCurrencyByCode(code: string): WhmcsCurrency | null {
return this.currencies.find(c => c.code.toUpperCase() === code.toUpperCase()) || null;
}
/**
* Load currencies from WHMCS
*/
private async loadCurrencies(): Promise<void> {
try {
const response = (await this.connectionService.getCurrencies()) as WhmcsCurrenciesResponse;
if (response.result === "success" && response.currencies?.currency) {
this.currencies = response.currencies.currency;
// Set first currency as default (WHMCS typically returns the primary currency first)
this.defaultCurrency = this.currencies[0] || null;
this.logger.log(`Loaded ${this.currencies.length} currencies from WHMCS`, {
defaultCurrency: this.defaultCurrency?.code,
allCurrencies: this.currencies.map(c => c.code),
});
} else {
throw new Error("Invalid response from WHMCS GetCurrencies");
}
} catch (error) {
this.logger.error("Failed to load currencies from WHMCS", {
error: getErrorMessage(error),
});
throw error;
}
}
/**
* Refresh currencies from WHMCS (can be called manually if needed)
*/
async refreshCurrencies(): Promise<void> {
await this.loadCurrencies();
}
}