70 lines
2.2 KiB
TypeScript
70 lines
2.2 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { AccessStore } from '../identity/access.store';
|
|
import { DatabaseService } from '../database/database.service';
|
|
import type { Principal } from '../identity/identity.types';
|
|
import { recordAudit } from '../identity/audit';
|
|
import { AppError } from '../common/errors/app-error';
|
|
import type { PageInput } from '../identity/identity.schemas';
|
|
import type { PricingInput } from './pricing.schema';
|
|
@Injectable()
|
|
export class PricingStore {
|
|
constructor(
|
|
private readonly db: DatabaseService,
|
|
private readonly access: AccessStore,
|
|
) {}
|
|
list(actor: Principal, page: PageInput) {
|
|
return this.db.pricingPolicy.findMany({
|
|
where: { organizationId: actor.organizationId },
|
|
take: page.limit,
|
|
skip: page.offset,
|
|
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
|
});
|
|
}
|
|
create(actor: Principal, input: PricingInput) {
|
|
return this.access.mutate(actor, 'pricing.manage', async (tx) => {
|
|
const policy = await tx.pricingPolicy.create({
|
|
data: { ...input, organizationId: actor.organizationId },
|
|
});
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
'pricing.created',
|
|
policy.id,
|
|
);
|
|
return policy;
|
|
});
|
|
}
|
|
status(actor: Principal, id: string, active: boolean) {
|
|
return this.access.mutate(actor, 'pricing.manage', async (tx) => {
|
|
const row = await tx.pricingPolicy.findFirst({
|
|
where: { id, organizationId: actor.organizationId },
|
|
});
|
|
if (!row) throw new AppError('PRICING_POLICY_NOT_FOUND');
|
|
if (active)
|
|
await tx.pricingPolicy.updateMany({
|
|
where: {
|
|
organizationId: actor.organizationId,
|
|
currency: row.currency,
|
|
countryCode: row.countryCode,
|
|
region: row.region,
|
|
active: true,
|
|
},
|
|
data: { active: false },
|
|
});
|
|
const updated = await tx.pricingPolicy.update({
|
|
where: { id },
|
|
data: { active },
|
|
});
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
'pricing.status.changed',
|
|
id,
|
|
);
|
|
return updated;
|
|
});
|
|
}
|
|
}
|