57 lines
2.0 KiB
TypeScript
57 lines
2.0 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { AppError } from '../common/errors/app-error';
|
|
import { commandHash } from '../common/idempotency';
|
|
import { AccessStore } from '../identity/access.store';
|
|
import { recordAudit } from '../identity/audit';
|
|
import type { Principal } from '../identity/identity.types';
|
|
import { requireQuote } from './quote-lookup';
|
|
import type { QuoteResponseInput } from './quote.schemas';
|
|
import { presentQuote } from './quote-view';
|
|
|
|
@Injectable()
|
|
export class QuoteResponseStore {
|
|
constructor(private readonly access: AccessStore) {}
|
|
|
|
respond(actor: Principal, id: string, input: QuoteResponseInput) {
|
|
return this.access.mutate(actor, 'b2b.quote.manage', async (tx) => {
|
|
const quote = await requireQuote(tx, actor.organizationId, id);
|
|
const hash = commandHash(id, input.kind, input.note);
|
|
const replay = await tx.b2bQuoteResponse.findUnique({
|
|
where: {
|
|
organizationId_idempotencyKey: {
|
|
organizationId: actor.organizationId,
|
|
idempotencyKey: input.idempotencyKey,
|
|
},
|
|
},
|
|
});
|
|
if (replay) {
|
|
if (replay.requestHash !== hash)
|
|
throw new AppError('B2B_QUOTE_RESPONSE_REPLAY_CONFLICT');
|
|
return presentQuote(quote);
|
|
}
|
|
if (quote.response) throw new AppError('B2B_QUOTE_ALREADY_RESOLVED');
|
|
if (quote.expiresAt.getTime() <= Date.now())
|
|
throw new AppError('B2B_QUOTE_EXPIRED');
|
|
await tx.b2bQuoteResponse.create({
|
|
data: {
|
|
organizationId: actor.organizationId,
|
|
quoteId: id,
|
|
actorId: actor.userId,
|
|
kind: input.kind,
|
|
note: input.note,
|
|
idempotencyKey: input.idempotencyKey,
|
|
requestHash: hash,
|
|
},
|
|
});
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
`b2b_quote.${input.kind.toLowerCase()}`,
|
|
id,
|
|
);
|
|
return presentQuote(await requireQuote(tx, actor.organizationId, id));
|
|
});
|
|
}
|
|
}
|