import { BadRequestException, Injectable } from '@nestjs/common' import { TspProviderBulkSendResultDto, TspProviderCorrectionSendPayloadDto, TspProviderCorrectionSendResponseDto, TspProviderGetResultDto, TspProviderOriginalSendPayloadDto, TspProviderRevokePayloadDto, TspProviderRevokeResponseDto, TspProviderSendItemResultDto, } from './dto/provider-switch.dto' import { NamaProviderSwitchAdapter } from './switch/nama/nama-provider.adapter' @Injectable() export class SalesInvoiceTspSwitchService { constructor(private readonly namaAdapter: NamaProviderSwitchAdapter) {} private resolveSwitch(providerCode: string) { const normalizedCode = providerCode.trim().toUpperCase() || '' let adapter: NamaProviderSwitchAdapter | null = null switch (normalizedCode) { case 'NAMA': adapter = this.namaAdapter } if (!adapter) { throw new BadRequestException( `${providerCode} برای ارسال انتخاب شده است که در حال حاضر پشتیبانی نمی شود.`, ) } return adapter } async send( payload: TspProviderOriginalSendPayloadDto, ): Promise { const adapter = this.resolveSwitch(payload.tsp_provider) return adapter.originalSend(payload) } async correction( payload: TspProviderCorrectionSendPayloadDto, ): Promise { const adapter = this.resolveSwitch(payload.tsp_provider) return adapter.correctionSend(payload) } async sendBulk( payloads: TspProviderOriginalSendPayloadDto[], ): Promise { const groupedByProvider = new Map() for (const payload of payloads) { const key = payload.tsp_provider?.trim().toUpperCase() || 'NAMA' const currentGroup = groupedByProvider.get(key) || [] currentGroup.push(payload) groupedByProvider.set(key, currentGroup) } const result: TspProviderBulkSendResultDto[] = [] for (const [providerCode, groupedPayloads] of groupedByProvider.entries()) { const adapter = this.resolveSwitch(providerCode) const providerResult = await adapter.sendBulk(groupedPayloads) result.push(...providerResult) } return result } async get( providerCode: string, invoiceId: string, tspToken: string, ): Promise { const adapter = this.resolveSwitch(providerCode) return await adapter.get(invoiceId, tspToken) } async revoke( payload: TspProviderRevokePayloadDto, ): Promise { const adapter = this.resolveSwitch(payload.tsp_provider) return adapter.revoke(payload) } }