68 lines
2.3 KiB
TypeScript
68 lines
2.3 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { AccessStore } from '../identity/access.store';
|
|
import type { Principal } from '../identity/identity.types';
|
|
import { AppError } from '../common/errors/app-error';
|
|
import { materialContribution } from './contribution-math';
|
|
import type { ContributionQuery } from './profitability.schemas';
|
|
@Injectable()
|
|
export class ProfitabilityStore {
|
|
constructor(private readonly access: AccessStore) {}
|
|
batch(actor: Principal, batchId: string, query: ContributionQuery) {
|
|
return this.access.mutate(
|
|
actor,
|
|
'profitability.read',
|
|
async (tx) => {
|
|
const snapshot = await tx.batchCostSnapshot.findFirst({
|
|
where: {
|
|
batchId,
|
|
organizationId: actor.organizationId,
|
|
sealedAt: { not: null },
|
|
batch: { status: 'COMPLETED' },
|
|
},
|
|
select: {
|
|
id: true,
|
|
batchId: true,
|
|
currency: true,
|
|
goodQuantity: true,
|
|
productionTotal: true,
|
|
packagingTotal: true,
|
|
total: true,
|
|
sealedAt: true,
|
|
batch: { select: { bom: { select: { variantId: true } } } },
|
|
},
|
|
});
|
|
if (!snapshot) throw new AppError('BATCH_COST_NOT_FOUND');
|
|
if (snapshot.currency !== query.currency)
|
|
throw new AppError('PROFITABILITY_CURRENCY');
|
|
return {
|
|
batchId,
|
|
variantId: snapshot.batch.bom.variantId,
|
|
costSnapshotId: snapshot.id,
|
|
sealedAt: snapshot.sealedAt,
|
|
basis: 'SEALED_BATCH_STANDARD_MATERIAL_COST',
|
|
currency: snapshot.currency,
|
|
goodQuantity: snapshot.goodQuantity,
|
|
unitNetPrice: query.unitNetPrice,
|
|
productionCost: snapshot.productionTotal.toFixed(2),
|
|
packagingCost: snapshot.packagingTotal.toFixed(2),
|
|
standardMaterialCost: snapshot.total.toFixed(2),
|
|
...materialContribution(
|
|
snapshot.total.toFixed(2),
|
|
snapshot.goodQuantity,
|
|
query.unitNetPrice,
|
|
),
|
|
excludedCostCategories: [
|
|
'LABOUR',
|
|
'OVERHEAD',
|
|
'FULFILLMENT',
|
|
'CHANNEL_FEES',
|
|
'MARKETING',
|
|
'FINANCE',
|
|
],
|
|
};
|
|
},
|
|
false,
|
|
);
|
|
}
|
|
}
|