2025-08-21 15:24:40 +09:00
|
|
|
import { getErrorMessage } from "../../../common/utils/error.util";
|
2025-08-22 17:02:49 +09:00
|
|
|
import { Logger } from "nestjs-pino";
|
|
|
|
|
import { Injectable, NotFoundException, Inject } from "@nestjs/common";
|
2025-08-21 15:24:40 +09:00
|
|
|
import { Invoice, InvoiceList } from "@customer-portal/shared";
|
|
|
|
|
import { WhmcsConnectionService } from "./whmcs-connection.service";
|
|
|
|
|
import { WhmcsDataTransformer } from "../transformers/whmcs-data.transformer";
|
|
|
|
|
import { WhmcsCacheService } from "../cache/whmcs-cache.service";
|
|
|
|
|
import { WhmcsGetInvoicesParams } from "../types/whmcs-api.types";
|
2025-08-20 18:02:50 +09:00
|
|
|
|
|
|
|
|
export interface InvoiceFilters {
|
2025-08-23 18:02:05 +09:00
|
|
|
status?: "Paid" | "Unpaid" | "Cancelled" | "Overdue" | "Collections";
|
2025-08-20 18:02:50 +09:00
|
|
|
page?: number;
|
|
|
|
|
limit?: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class WhmcsInvoiceService {
|
|
|
|
|
constructor(
|
2025-08-22 17:02:49 +09:00
|
|
|
@Inject(Logger) private readonly logger: Logger,
|
2025-08-20 18:02:50 +09:00
|
|
|
private readonly connectionService: WhmcsConnectionService,
|
|
|
|
|
private readonly dataTransformer: WhmcsDataTransformer,
|
2025-08-22 17:02:49 +09:00
|
|
|
private readonly cacheService: WhmcsCacheService
|
2025-08-20 18:02:50 +09:00
|
|
|
) {}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get paginated invoices for a client with caching
|
|
|
|
|
*/
|
|
|
|
|
async getInvoices(
|
|
|
|
|
clientId: number,
|
|
|
|
|
userId: string,
|
2025-08-22 17:02:49 +09:00
|
|
|
filters: InvoiceFilters = {}
|
2025-08-20 18:02:50 +09:00
|
|
|
): Promise<InvoiceList> {
|
|
|
|
|
const { status, page = 1, limit = 10 } = filters;
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// Try cache first
|
2025-08-22 17:02:49 +09:00
|
|
|
const cached = await this.cacheService.getInvoicesList(userId, page, limit, status);
|
2025-08-20 18:02:50 +09:00
|
|
|
if (cached) {
|
2025-08-22 17:02:49 +09:00
|
|
|
this.logger.debug(`Cache hit for invoices: user ${userId}, page ${page}`);
|
2025-08-20 18:02:50 +09:00
|
|
|
return cached;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Calculate pagination for WHMCS API
|
|
|
|
|
const limitstart = (page - 1) * limit;
|
|
|
|
|
|
|
|
|
|
// Fetch from WHMCS API
|
|
|
|
|
const params: WhmcsGetInvoicesParams = {
|
2025-08-21 15:24:40 +09:00
|
|
|
userid: clientId, // WHMCS API uses 'userid' parameter, not 'clientid'
|
2025-08-20 18:02:50 +09:00
|
|
|
limitstart,
|
|
|
|
|
limitnum: limit,
|
2025-08-21 15:24:40 +09:00
|
|
|
orderby: "date",
|
|
|
|
|
order: "DESC",
|
2025-08-23 18:02:05 +09:00
|
|
|
...(status && { status: status as WhmcsGetInvoicesParams["status"] }),
|
2025-08-20 18:02:50 +09:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const response = await this.connectionService.getInvoices(params);
|
|
|
|
|
|
|
|
|
|
if (!response.invoices?.invoice) {
|
|
|
|
|
this.logger.warn(`No invoices found for client ${clientId}`);
|
|
|
|
|
return {
|
|
|
|
|
invoices: [],
|
|
|
|
|
pagination: {
|
|
|
|
|
page,
|
|
|
|
|
totalPages: 0,
|
|
|
|
|
totalItems: 0,
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Transform invoices (note: items are not included by GetInvoices API)
|
2025-08-21 15:24:40 +09:00
|
|
|
const invoices = response.invoices.invoice
|
2025-08-22 17:02:49 +09:00
|
|
|
.map(whmcsInvoice => {
|
2025-08-21 15:24:40 +09:00
|
|
|
try {
|
|
|
|
|
return this.dataTransformer.transformInvoice(whmcsInvoice);
|
|
|
|
|
} catch (error) {
|
2025-08-22 17:02:49 +09:00
|
|
|
this.logger.error(`Failed to transform invoice ${whmcsInvoice.id}`, {
|
|
|
|
|
error: getErrorMessage(error),
|
|
|
|
|
});
|
2025-08-21 15:24:40 +09:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.filter((invoice): invoice is Invoice => invoice !== null);
|
2025-08-20 18:02:50 +09:00
|
|
|
|
|
|
|
|
// Build result with pagination
|
2025-08-22 17:02:49 +09:00
|
|
|
this.logger.debug(`WHMCS GetInvoices Response Analysis for Client ${clientId}:`, {
|
|
|
|
|
totalresults: response.totalresults,
|
|
|
|
|
numreturned: response.numreturned,
|
|
|
|
|
startnumber: response.startnumber,
|
|
|
|
|
actualInvoicesReturned: invoices.length,
|
|
|
|
|
requestParams: {
|
|
|
|
|
userid: clientId,
|
|
|
|
|
limitstart,
|
|
|
|
|
limitnum: limit,
|
|
|
|
|
orderby: "date",
|
|
|
|
|
order: "DESC",
|
2025-08-21 15:24:40 +09:00
|
|
|
},
|
2025-08-22 17:02:49 +09:00
|
|
|
});
|
2025-08-20 18:02:50 +09:00
|
|
|
|
|
|
|
|
const totalItems = response.totalresults || 0;
|
|
|
|
|
const totalPages = Math.ceil(totalItems / limit);
|
|
|
|
|
|
|
|
|
|
const result: InvoiceList = {
|
|
|
|
|
invoices,
|
|
|
|
|
pagination: {
|
|
|
|
|
page,
|
|
|
|
|
totalPages,
|
|
|
|
|
totalItems,
|
|
|
|
|
nextCursor: page < totalPages ? (page + 1).toString() : undefined,
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Cache the result
|
2025-08-22 17:02:49 +09:00
|
|
|
await this.cacheService.setInvoicesList(userId, page, limit, status, result);
|
2025-08-20 18:02:50 +09:00
|
|
|
|
2025-08-22 17:02:49 +09:00
|
|
|
this.logger.log(`Fetched ${invoices.length} invoices for client ${clientId}, page ${page}`);
|
2025-08-20 18:02:50 +09:00
|
|
|
return result;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
this.logger.error(`Failed to fetch invoices for client ${clientId}`, {
|
|
|
|
|
error: getErrorMessage(error),
|
|
|
|
|
filters,
|
|
|
|
|
});
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get invoices with items (for subscription linking)
|
|
|
|
|
* This method fetches invoices and then enriches them with item details
|
|
|
|
|
*/
|
|
|
|
|
async getInvoicesWithItems(
|
|
|
|
|
clientId: number,
|
|
|
|
|
userId: string,
|
2025-08-22 17:02:49 +09:00
|
|
|
filters: InvoiceFilters = {}
|
2025-08-20 18:02:50 +09:00
|
|
|
): Promise<InvoiceList> {
|
|
|
|
|
try {
|
|
|
|
|
// First get the basic invoices list
|
|
|
|
|
const invoiceList = await this.getInvoices(clientId, userId, filters);
|
2025-08-21 15:24:40 +09:00
|
|
|
|
2025-08-20 18:02:50 +09:00
|
|
|
// For each invoice, fetch the detailed version with items
|
|
|
|
|
const invoicesWithItems = await Promise.all(
|
2025-08-22 17:02:49 +09:00
|
|
|
invoiceList.invoices.map(async invoice => {
|
2025-08-20 18:02:50 +09:00
|
|
|
try {
|
|
|
|
|
// Get detailed invoice with items
|
2025-08-22 17:02:49 +09:00
|
|
|
const detailedInvoice = await this.getInvoiceById(clientId, userId, invoice.id);
|
2025-08-20 18:02:50 +09:00
|
|
|
return detailedInvoice;
|
|
|
|
|
} catch (error) {
|
2025-08-21 15:24:40 +09:00
|
|
|
this.logger.warn(
|
|
|
|
|
`Failed to fetch details for invoice ${invoice.id}`,
|
2025-08-22 17:02:49 +09:00
|
|
|
getErrorMessage(error)
|
2025-08-21 15:24:40 +09:00
|
|
|
);
|
2025-08-20 18:02:50 +09:00
|
|
|
// Return the basic invoice if detailed fetch fails
|
|
|
|
|
return invoice;
|
|
|
|
|
}
|
2025-08-22 17:02:49 +09:00
|
|
|
})
|
2025-08-20 18:02:50 +09:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const result: InvoiceList = {
|
|
|
|
|
invoices: invoicesWithItems,
|
|
|
|
|
pagination: invoiceList.pagination,
|
|
|
|
|
};
|
|
|
|
|
|
2025-08-21 15:24:40 +09:00
|
|
|
this.logger.log(
|
2025-08-22 17:02:49 +09:00
|
|
|
`Fetched ${invoicesWithItems.length} invoices with items for client ${clientId}`
|
2025-08-21 15:24:40 +09:00
|
|
|
);
|
2025-08-20 18:02:50 +09:00
|
|
|
return result;
|
|
|
|
|
} catch (error) {
|
2025-08-22 17:02:49 +09:00
|
|
|
this.logger.error(`Failed to fetch invoices with items for client ${clientId}`, {
|
|
|
|
|
error: getErrorMessage(error),
|
|
|
|
|
filters,
|
|
|
|
|
});
|
2025-08-20 18:02:50 +09:00
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get individual invoice by ID with caching
|
|
|
|
|
*/
|
2025-08-22 17:02:49 +09:00
|
|
|
async getInvoiceById(clientId: number, userId: string, invoiceId: number): Promise<Invoice> {
|
2025-08-20 18:02:50 +09:00
|
|
|
try {
|
|
|
|
|
// Try cache first
|
|
|
|
|
const cached = await this.cacheService.getInvoice(userId, invoiceId);
|
|
|
|
|
if (cached) {
|
2025-08-22 17:02:49 +09:00
|
|
|
this.logger.debug(`Cache hit for invoice: user ${userId}, invoice ${invoiceId}`);
|
2025-08-20 18:02:50 +09:00
|
|
|
return cached;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Fetch from WHMCS API
|
|
|
|
|
const response = await this.connectionService.getInvoice(invoiceId);
|
|
|
|
|
|
|
|
|
|
if (!response.invoiceid) {
|
|
|
|
|
throw new NotFoundException(`Invoice ${invoiceId} not found`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Verify the invoice belongs to this client
|
|
|
|
|
const invoiceClientId = response.userid;
|
|
|
|
|
if (invoiceClientId !== clientId) {
|
|
|
|
|
throw new NotFoundException(`Invoice ${invoiceId} not found`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Transform invoice
|
|
|
|
|
const invoice = this.dataTransformer.transformInvoice(response);
|
|
|
|
|
|
|
|
|
|
// Validate transformation
|
|
|
|
|
if (!this.dataTransformer.validateInvoice(invoice)) {
|
|
|
|
|
throw new Error(`Invalid invoice data after transformation`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Cache the result
|
|
|
|
|
await this.cacheService.setInvoice(userId, invoiceId, invoice);
|
|
|
|
|
|
|
|
|
|
this.logger.log(`Fetched invoice ${invoiceId} for client ${clientId}`);
|
|
|
|
|
return invoice;
|
|
|
|
|
} catch (error) {
|
2025-08-22 17:02:49 +09:00
|
|
|
this.logger.error(`Failed to fetch invoice ${invoiceId} for client ${clientId}`, {
|
|
|
|
|
error: getErrorMessage(error),
|
|
|
|
|
});
|
2025-08-20 18:02:50 +09:00
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Invalidate cache for a specific invoice
|
|
|
|
|
*/
|
2025-08-22 17:02:49 +09:00
|
|
|
async invalidateInvoiceCache(userId: string, invoiceId: number): Promise<void> {
|
2025-08-20 18:02:50 +09:00
|
|
|
await this.cacheService.invalidateInvoice(userId, invoiceId);
|
2025-08-22 17:02:49 +09:00
|
|
|
this.logger.log(`Invalidated invoice cache for user ${userId}, invoice ${invoiceId}`);
|
2025-08-20 18:02:50 +09:00
|
|
|
}
|
|
|
|
|
}
|