62 lines
2.2 KiB
TypeScript
62 lines
2.2 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 { presentPartnerOrder, requirePartnerOrder } from './partner-order-view';
|
|
import type { CancelPartnerOrderInput } from './partner-order.schemas';
|
|
import { activePartnerPayments } from './partner-payment-balance';
|
|
|
|
@Injectable()
|
|
export class PartnerOrderCancelStore {
|
|
constructor(private readonly access: AccessStore) {}
|
|
|
|
cancel(actor: Principal, id: string, input: CancelPartnerOrderInput) {
|
|
return this.access.mutate(actor, 'b2b.order.manage', async (tx) => {
|
|
const order = await requirePartnerOrder(tx, actor.organizationId, id);
|
|
const hash = commandHash(id, input.reason);
|
|
const replay = await tx.b2bPartnerOrderCancellation.findUnique({
|
|
where: {
|
|
organizationId_idempotencyKey: {
|
|
organizationId: actor.organizationId,
|
|
idempotencyKey: input.idempotencyKey,
|
|
},
|
|
},
|
|
});
|
|
if (replay) {
|
|
if (replay.requestHash !== hash)
|
|
throw new AppError('B2B_ORDER_CANCEL_REPLAY_CONFLICT');
|
|
return presentPartnerOrder(order);
|
|
}
|
|
if (order.cancellation) throw new AppError('B2B_ORDER_ALREADY_CANCELLED');
|
|
if (
|
|
await tx.b2bPartnerPayment.count({
|
|
where: activePartnerPayments(actor.organizationId, id),
|
|
})
|
|
)
|
|
throw new AppError('B2B_PAYMENT_CANCEL_BLOCKED');
|
|
await tx.b2bPartnerOrderCancellation.create({
|
|
data: {
|
|
orderId: id,
|
|
organizationId: actor.organizationId,
|
|
actorId: actor.userId,
|
|
reason: input.reason,
|
|
idempotencyKey: input.idempotencyKey,
|
|
requestHash: hash,
|
|
},
|
|
});
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
'b2b_order.cancelled',
|
|
id,
|
|
);
|
|
return presentPartnerOrder(
|
|
await requirePartnerOrder(tx, actor.organizationId, id),
|
|
);
|
|
});
|
|
}
|
|
}
|