Files
ISA-Frontend/libs/crm/data-access/src/lib/resources/customer-bon-check.resource.ts
Nino Righi 964a6026a0 Merged PR 2076: fix(common-data-access, crm-data-access): Improved Error handling, handling i...
fix(common-data-access, crm-data-access): Improved Error handling, handling invalidProperties errors corretly inside crm customer card area

Refs: #5528, #5529
2025-12-10 17:11:22 +00:00

90 lines
2.7 KiB
TypeScript

import { Injectable, inject, resource, signal, computed } from '@angular/core';
import { logger } from '@isa/core/logging';
import { CustomerBonRedemptionFacade } from '../facades/customer-bon-redemption.facade';
import { LoyaltyBonResponse } from '@generated/swagger/crm-api';
import { ResponseArgsError } from '@isa/common/data-access';
/**
* Resource for checking/validating Bon numbers.
*
* Provides reactive loading of Bon details for validation.
* Parameters can be updated via `params()` method to trigger validation.
*
* **Note:** Provide at component level, not root.
*/
@Injectable()
export class CustomerBonCheckResource {
readonly #bonFacade = inject(CustomerBonRedemptionFacade);
readonly #logger = logger(() => ({ context: 'CustomerBonCheckResource' }));
readonly #cardCode = signal<string | undefined>(undefined);
readonly #bonNr = signal<string | undefined>(undefined);
/**
* Resource that validates Bon based on current parameters.
*/
readonly resource = resource({
params: computed(() => ({
cardCode: this.#cardCode(),
bonNr: this.#bonNr(),
})),
loader: async ({
params,
abortSignal,
}): Promise<LoyaltyBonResponse | undefined> => {
const { cardCode, bonNr } = params;
if (!cardCode || !bonNr) {
return undefined;
}
this.#logger.debug('Checking Bon', () => ({ cardCode, bonNr }));
const response = await this.#bonFacade.checkBon(
{ cardCode, bonNr },
abortSignal,
);
this.#logger.debug('Bon checked', () => ({
bonNr,
found: !!response?.result,
hasInvalidProperties:
!!response?.invalidProperties &&
Object.keys(response.invalidProperties).length > 0,
}));
// Check for invalidProperties even when error is false
// Backend may return { error: false, invalidProperties: {...} } for validation issues
if (
response?.invalidProperties &&
Object.keys(response.invalidProperties).length > 0
) {
this.#logger.warn('Bon check has invalid properties', () => ({
bonNr,
invalidProperties: response.invalidProperties,
}));
throw new ResponseArgsError(response);
}
return response?.result;
},
defaultValue: undefined,
});
/**
* Update parameters to trigger Bon validation.
*/
params(params: { cardCode: string; bonNr: string }): void {
this.#cardCode.set(params.cardCode);
this.#bonNr.set(params.bonNr);
}
/**
* Reset the resource state.
*/
reset(): void {
this.#cardCode.set(undefined);
this.#bonNr.set(undefined);
}
}