Стабилизировать маржинальность номенклатуры

This commit is contained in:
2026-05-22 16:17:07 +03:00
parent f5d86d4bc1
commit 09c6d1aa0e
45 changed files with 2074 additions and 76 deletions
@@ -31,6 +31,7 @@ const COMPUTE_EXACT_INTENTS = new Set<AddressIntent>([
"inventory_purchase_documents_for_item",
"inventory_supplier_stock_overlap_as_of_date",
"inventory_sale_trace_for_item",
"inventory_margin_ranking_for_nomenclature",
"inventory_profitability_for_item",
"inventory_purchase_to_sale_chain",
"inventory_aging_by_purchase_date",
@@ -92,6 +93,7 @@ function defaultCapabilityId(intent: AddressIntent): string {
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -178,13 +180,17 @@ function resolveCapabilityEnabled(intent: AddressIntent): { enabled: boolean; re
intent === "inventory_purchase_provenance_for_item" ||
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain"
) {
if (intent === "inventory_profitability_for_item") {
if (intent === "inventory_profitability_for_item" || intent === "inventory_margin_ranking_for_nomenclature") {
return {
enabled: true,
reason: "inventory_profitability_route_enabled"
reason:
intent === "inventory_margin_ranking_for_nomenclature"
? "inventory_margin_ranking_route_enabled"
: "inventory_profitability_route_enabled"
};
}
if (intent === "inventory_purchase_to_sale_chain") {
@@ -284,6 +290,7 @@ export function resolveShadowRouteIntent(
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -149,6 +149,7 @@ export function isConfirmedBalanceIntent(intent: AddressIntent): boolean {
intent === "inventory_purchase_provenance_for_item" ||
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "open_contracts_confirmed_as_of_date" ||
@@ -1111,6 +1111,7 @@ function isInventoryTraceIntent(intent: AddressIntent): boolean {
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -1135,6 +1136,7 @@ function usesRecipeDefaultLimit(intent: AddressIntent): boolean {
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -1628,6 +1630,9 @@ function requiredFiltersByIntent(intent: AddressIntent): Array<keyof AddressFilt
) {
return ["item"];
}
if (intent === "inventory_margin_ranking_for_nomenclature") {
return ["period_from", "period_to"];
}
if (intent === "payables_confirmed_as_of_date") {
return ["as_of_date"];
}
@@ -2152,6 +2152,28 @@ function hasBidirectionalValueFlowComparisonSignal(text: string): boolean {
return hasIncomingCue && hasOutgoingCue && hasComparisonCue && (hasValueFlowCue || hasNetAmountCue);
}
function hasNomenclatureMarginRankingSignal(text: string): boolean {
const normalized = String(text ?? "").trim().toLowerCase();
if (!normalized) {
return false;
}
const hasNomenclatureCue =
/(?:номенклатур|товар|позици|ассортимент|sku|item|product|goods)/iu.test(normalized);
const hasRealizationCue =
/(?:реализован|реализац|продан|продаж|отгруж|41(?:[.,]0?1)?|90(?:[.,]\d{1,2})?|sales?|sold)/iu.test(
normalized
);
const hasMarginCue =
/(?:прибыл|марж|рентаб|наценк|себестоим|выручк|profit|margin|profitability|gross\s+spread|cogs)/iu.test(
normalized
);
const hasRankingCue =
/(?:высок|низк|топ|сам(?:ая|ый|ое|ые)|больш|меньш|ранж|рейтинг|high|low|top|rank|best|worst)/iu.test(
normalized
);
return hasNomenclatureCue && hasRealizationCue && hasMarginCue && hasRankingCue;
}
function hasVatPeriodInspectionBridgeSignal(text: string): boolean {
const normalized = String(text ?? "").trim().toLowerCase();
if (!/(?:ндс|vat)/iu.test(normalized)) {
@@ -2263,6 +2285,14 @@ function resolveUnicodeAddressIntentBridge(text: string): AddressIntentResolutio
);
}
if (hasNomenclatureMarginRankingSignal(normalized)) {
return unicodeBridgeResolution(
"inventory_margin_ranking_for_nomenclature",
"high",
"unicode_nomenclature_margin_ranking_bridge_signal_detected"
);
}
const hasOpenItemsAccountCue =
/(?:хвост|долг|незакрыт|вис)/iu.test(normalized) &&
/(?:сч(?:е|ё)т(?:а|у|ом|е|ов)?\s*(?:|#)?\s*(?:60|62|76)(?:[.,]\d{1,2})?|\b(?:60|62|76)(?:[.,]\d{1,2})?\b\s*сч(?:е|ё)т)/iu.test(
@@ -2034,6 +2034,7 @@ function isOrganizationScopedInventoryIntent(intent: AddressIntent): boolean {
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -2085,6 +2086,7 @@ function shouldDeferInventoryOrganizationClarification(
intent === "inventory_purchase_provenance_for_item" ||
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -2455,6 +2457,7 @@ function canAutoBroadenPeriodWindow(intent: AddressIntent, filters: AddressFilte
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -2467,6 +2470,7 @@ function shouldBoostAutoBroadenedLimit(intent: AddressIntent): boolean {
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -3132,6 +3136,9 @@ async function tryComposeLlmLimitedReply(input: {
if (process.env.VITEST === "true" || process.env.NODE_ENV === "test") {
return null;
}
if (input.intent === "inventory_margin_ranking_for_nomenclature" && input.category === "missing_anchor") {
return null;
}
if (!shouldUseLlmLimitedReply(input.category)) {
return null;
}
@@ -3206,6 +3213,13 @@ function composeLimitedReply(input: {
)
);
const missingAnchorPhrase = missingAnchorLabels.length > 0 ? missingAnchorLabels.join(", ") : "контрагент, договор, счет или период";
if (input.intent === "inventory_margin_ranking_for_nomenclature" && input.category === "missing_anchor") {
return [
"Для рейтинга прибыльности номенклатуры нужен период.",
"Могу посчитать по номенклатуре: выручку без НДС, себестоимость реализации, валовую прибыль и маржинальность.",
"Уточните период: месяц, квартал, год или весь доступный период."
].join("\n\n");
}
const heading =
input.category === "empty_match"
? pickDeterministicVariant(headingSeed, [
@@ -992,6 +992,17 @@ const BASE_RECIPES: AddressRecipeDefinition[] = [
account_scope_mode: "strict",
query_template: "inventory_trading_margin_proxy_profile"
},
{
recipe_id: "address_inventory_margin_ranking_for_nomenclature_v1",
intent: "inventory_margin_ranking_for_nomenclature",
purpose: "Rank realized nomenclature by bounded gross margin proxy for an explicit period using 41.01 purchase and sale document rows",
required_filters: ["period_from", "period_to"],
optional_filters: ["organization", "warehouse", "limit", "sort"],
default_limit: 800,
account_scope: ["41.01"],
account_scope_mode: "strict",
query_template: "inventory_margin_ranking_profile"
},
{
recipe_id: "address_inventory_purchase_to_sale_chain_v1",
intent: "inventory_purchase_to_sale_chain",
@@ -1928,6 +1939,7 @@ function maxLimitForIntent(intent: AddressIntent): number {
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_trading_margin_proxy_for_organization" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date" ||
@@ -2182,6 +2194,8 @@ export function buildAddressRecipePlan(
? buildInventoryPurchaseToSaleDocumentQuery(filters, resolvedLimit)
: recipe.query_template === "inventory_trading_margin_proxy_profile"
? buildInventoryPurchaseToSaleDocumentQuery(filters, resolvedLimit)
: recipe.query_template === "inventory_margin_ranking_profile"
? buildInventoryPurchaseToSaleDocumentQuery(filters, resolvedLimit)
: recipe.query_template === "inventory_purchase_to_sale_chain_profile"
? buildInventoryPurchaseToSaleDocumentQuery(filters, resolvedLimit)
: recipe.query_template === "inventory_aging_by_purchase_date_profile"
@@ -423,6 +423,7 @@ function isInventoryIntent(intent: AddressIntent | undefined): boolean {
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -438,6 +439,7 @@ function isInventoryDrilldownFrameIntent(intent: AddressIntent | undefined): boo
intent === "inventory_purchase_provenance_for_item" ||
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -449,6 +451,7 @@ function isInventoryLifecycleHistoryIntent(intent: AddressIntent | undefined): b
intent === "inventory_purchase_provenance_for_item" ||
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain"
);
@@ -798,11 +801,32 @@ export function hasInventoryPurchaseDateVatBridgeCue(text: string): boolean {
);
}
export function hasInventoryMarginRankingFollowupCue(text: string): boolean {
const normalized = textWithRepairedVariant(String(text ?? ""))
.toLowerCase()
.replace(/ё/g, "е");
if (!normalized.trim()) {
return false;
}
const wantsFoundRows =
/(?:покажи|показать|выведи|дай|раскрой|show|list|РїРѕРєР°РРё|показаССЊ|РІСведи|РґР°Р|раскроР)/iu.test(normalized) &&
/(?:найденн|строк|реализац|себестоимостн|баз|РЅР°Рденн|СЃССЂРѕРє|реализаС|себесСРѕРёРјРѕСЃСРЅ|баз)/iu.test(normalized) &&
/(?:себестоимостн|реализац|марж|прибыл|номенклатур|себесСРѕРёРјРѕСЃСРЅ|реализаС|марР|РїСЂРёР±СР»|номенклаС)/iu.test(normalized);
const account41Not01 =
/\b41(?:[.,]\d{1,2})?\b/iu.test(normalized) &&
/\b01(?:[.,]\d{1,2})?\b/iu.test(normalized) &&
/(?:\bне\b|вместо|а\s+не|not|instead|РЅРµ|вмесСРѕ|Р°\s+РЅРµ)/iu.test(normalized);
return wantsFoundRows || account41Not01;
}
export function hasAddressFollowupContextSignal(text: string): boolean {
const normalized = String(text ?? "").trim();
if (!normalized) {
return false;
}
if (hasInventoryMarginRankingFollowupCue(normalized)) {
return true;
}
if (
/(?:по\s+выбранному\s+объекту|по\s+этой\s+позиции|по\s+этому\s+товару|по\s+ней|по\s+нему|по\s+ним|for\s+selected\s+object|selected\s+object)/iu.test(
normalized
@@ -1115,6 +1139,7 @@ function mergeFollowupFilters(
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date" ||
@@ -1175,6 +1200,7 @@ function mergeFollowupFilters(
(intent === "inventory_purchase_provenance_for_item" ||
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date")
@@ -1412,6 +1438,7 @@ function mergeFollowupFilters(
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_supplier_stock_overlap_as_of_date" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date" ||
@@ -1424,6 +1451,9 @@ function mergeFollowupFilters(
const currentContractExplicit = toNonEmptyString(merged.contract);
const currentItemExplicit = toNonEmptyString(merged.item);
const currentAccountExplicit = toNonEmptyString(merged.account);
const currentAccountRefinesMarginDomain =
intent === "inventory_margin_ranking_for_nomenclature" &&
hasInventoryMarginRankingFollowupCue(userMessage);
const shouldSuppressGenericPeriodCarryover =
(Boolean(currentCounterpartyExplicit) &&
!isLowQualityCounterpartyAnchor(currentCounterpartyExplicit) &&
@@ -1432,7 +1462,7 @@ function mergeFollowupFilters(
!isLowQualityContractAnchor(currentContractExplicit) &&
currentContractExplicit !== previousContract) ||
(Boolean(currentItemExplicit) && currentItemExplicit !== previousItem) ||
(Boolean(currentAccountExplicit) && currentAccountExplicit !== previousAccount);
(Boolean(currentAccountExplicit) && currentAccountExplicit !== previousAccount && !currentAccountRefinesMarginDomain);
const vatRelativeMonthFollowup =
relativeMonthFromFollowupYear &&
(intent === "vat_payable_confirmed_as_of_date" ||
@@ -1488,6 +1518,22 @@ function mergeFollowupFilters(
reasons.push("period_from_followup_context");
}
if (
intent === "inventory_margin_ranking_for_nomenclature" &&
previousHasPeriod &&
hasInventoryMarginRankingFollowupCue(userMessage) &&
!hasExplicitPeriodInMessage &&
!hasExplicitCurrentDateInMessage
) {
if (previousPeriodFrom && merged.period_from !== previousPeriodFrom) {
merged.period_from = previousPeriodFrom;
}
if (previousPeriodTo && merged.period_to !== previousPeriodTo) {
merged.period_to = previousPeriodTo;
}
reasons.push("period_from_followup_context");
}
if (
!currentHasPeriod &&
previousHasPeriod &&
@@ -1563,6 +1609,7 @@ function resolveMissingRequiredFilters(intent: AddressIntent, filters: AddressFi
account_balance_snapshot: ["account", "as_of_date"],
documents_forming_balance: ["account", "as_of_date"],
inventory_on_hand_as_of_date: ["as_of_date"],
inventory_margin_ranking_for_nomenclature: ["period_from", "period_to"],
inventory_profitability_for_item: ["item"],
open_contracts_confirmed_as_of_date: ["as_of_date"],
payables_confirmed_as_of_date: ["as_of_date"],
@@ -1648,6 +1695,26 @@ function deriveIntentWithFollowupContext(
previousCounterpartyLaneActive && !hasExplicitInventoryItemReference;
const inventoryPurchaseDateVatBridge =
inventorySelectedObjectFollowup && hasInventoryPurchaseDateVatBridgeCue(normalizedMessage);
const marginRankingLineageActive =
sourceIntent === "inventory_margin_ranking_for_nomenclature" ||
fallbackIntent === "inventory_margin_ranking_for_nomenclature" ||
followupContext.root_intent === "inventory_margin_ranking_for_nomenclature";
if (
marginRankingLineageActive &&
hasInventoryMarginRankingFollowupCue(normalizedMessage) &&
(detectedIntent.intent === "unknown" ||
detectedIntent.intent === "account_balance_snapshot" ||
detectedIntent.intent === "documents_forming_balance" ||
detectedIntent.intent === "inventory_margin_ranking_for_nomenclature" ||
detectedIntent.intent === sourceIntent)
) {
return {
intent: "inventory_margin_ranking_for_nomenclature",
confidence: "low",
reasons: [...detectedIntent.reasons, "intent_adjusted_to_inventory_margin_ranking_followup_context"]
};
}
if (
inventoryPurchaseDateVatBridge &&
@@ -162,6 +162,73 @@ function inventoryProfitabilityPeriodLabel(options: InventoryComposeOptions, dep
return asOfDate ? `до ${deps.formatDateRu(asOfDate)}` : "по доступной выборке";
}
interface InventoryMarginRankingEntry {
item: string;
revenue: number;
costProxy: number;
spread: number;
marginPct: number | null;
saleQuantity: number;
purchaseQuantity: number;
saleDocuments: number;
purchaseDocuments: number;
}
function inventoryRowItemLabel(row: ComposeStageRow, deps: InventoryReplyDeps): string | null {
return deps.summarizeInventoryTraceRows([row]).item;
}
function buildInventoryMarginRankingEntries(rows: ComposeStageRow[], deps: InventoryReplyDeps): InventoryMarginRankingEntry[] {
const byItem = new Map<string, { item: string; saleRows: ComposeStageRow[]; purchaseRows: ComposeStageRow[] }>();
for (const row of rows) {
const item = inventoryRowItemLabel(row, deps);
if (!item) {
continue;
}
const key = item.trim().toLocaleLowerCase("ru");
const current = byItem.get(key) ?? { item, saleRows: [], purchaseRows: [] };
if (deps.isInventorySaleMovement(row)) {
current.saleRows.push(row);
}
if (deps.isInventoryPurchaseMovement(row)) {
current.purchaseRows.push(row);
}
byItem.set(key, current);
}
return Array.from(byItem.values())
.map((entry) => {
const revenue = sumInventoryRowAmount(entry.saleRows);
const costProxy = sumInventoryRowAmount(entry.purchaseRows);
const spread = revenue - costProxy;
return {
item: entry.item,
revenue,
costProxy,
spread,
marginPct: revenue > 0 ? (spread / revenue) * 100 : null,
saleQuantity: sumInventoryRowQuantity(entry.saleRows),
purchaseQuantity: sumInventoryRowQuantity(entry.purchaseRows),
saleDocuments: entry.saleRows.length,
purchaseDocuments: entry.purchaseRows.length
};
})
.filter((entry) => entry.revenue > 0 || entry.costProxy > 0);
}
function formatInventoryMarginRankingLine(
entry: InventoryMarginRankingEntry,
index: number,
deps: InventoryReplyDeps
): string {
return `${index + 1}. ${entry.item} — выручка ${deps.formatMoneyRub(entry.revenue)}, себестоимостная база ${deps.formatMoneyRub(
entry.costProxy
)}, валовая разница ${deps.formatMoneyRub(entry.spread)}, маржа ${formatInventoryPercent(
entry.marginPct,
deps.formatNumberWithDots
)}.`;
}
export function composeInventoryReply(
intent: AddressIntent,
rows: ComposeStageRow[],
@@ -548,6 +615,121 @@ export function composeInventoryReply(
: buildFactualSummaryReply(lines, buildConfirmedBalanceSemantics("medium", false));
}
if (intent === "inventory_margin_ranking_for_nomenclature") {
const entries = buildInventoryMarginRankingEntries(rows, deps);
const confirmedEntries = entries.filter((entry) => entry.revenue > 0 && entry.costProxy > 0);
const highMargin = [...confirmedEntries]
.sort((left, right) => right.spread - left.spread || (right.marginPct ?? -Infinity) - (left.marginPct ?? -Infinity))
.slice(0, 5);
const lowMargin = [...confirmedEntries]
.sort((left, right) => left.spread - right.spread || (left.marginPct ?? Infinity) - (right.marginPct ?? Infinity))
.slice(0, 5);
const salesWithoutCost = entries.filter((entry) => entry.revenue > 0 && entry.costProxy <= 0);
const purchasesWithoutSales = entries.filter((entry) => entry.costProxy > 0 && entry.revenue <= 0);
const periodLabel = inventoryProfitabilityPeriodLabel(options, deps);
const totalRevenue = entries.reduce((sum, entry) => sum + entry.revenue, 0);
const totalCostProxy = entries.reduce((sum, entry) => sum + entry.costProxy, 0);
const totalSpread = totalRevenue - totalCostProxy;
if (confirmedEntries.length === 0) {
const lines: string[] = [`За период ${periodLabel} рейтинг прибыльности номенклатуры построить нельзя.`];
const findings: string[] = [];
if (salesWithoutCost.length > 0) {
const salesCount = deps.formatNumberWithDots(salesWithoutCost.length);
const salesItemPhrase =
salesWithoutCost.length === 1 ? "1 номенклатурной позиции" : `${salesCount} номенклатурным позициям`;
findings.push(
`Есть реализация по ${salesItemPhrase}.`
);
findings.push(
salesWithoutCost.length === 1
? "Подтвержденной себестоимости реализации по этой позиции не найдено."
: "Подтвержденной себестоимости реализации по этим позициям не найдено."
);
findings.push("Поэтому валовую прибыль и маржинальность честно посчитать нельзя.");
}
if (purchasesWithoutSales.length > 0) {
const purchaseCount = deps.formatNumberWithDots(purchasesWithoutSales.length);
const purchaseItemPhrase =
purchasesWithoutSales.length === 1 ? "1 позиции" : `${purchaseCount} позициям`;
findings.push(
purchasesWithoutSales.length === 1
? `Есть себестоимостная база по ${purchaseItemPhrase}, но реализации по ней в периоде не найдено.`
: `Есть себестоимостная база по ${purchaseItemPhrase}, но реализации по ним в периоде не найдено.`
);
}
if (entries.length === 0) {
findings.push("В доступной выборке нет достаточных строк реализации и себестоимости по номенклатуре.");
}
appendInventoryBulletSection(lines, "Что нашлось:", findings);
lines.push(
`Вывод: за период ${periodLabel} нет достаточной базы для рейтинга «высокая / низкая прибыль» по номенклатуре.`
);
const nextActions: string[] = [];
if (salesWithoutCost.length > 0) {
nextActions.push("показать найденные реализации за этот период;");
}
if (purchasesWithoutSales.length > 0) {
nextActions.push("показать найденные строки себестоимостной базы за этот период;");
}
nextActions.push(
"расширить период до квартала или года;",
"попробовать строгий расчет по проводкам 90.01 / 90.02;",
"построить управленческий proxy по закупочным документам, если такой способ допустим для вашей проверки."
);
appendInventoryBulletSection(lines, "Что можно сделать дальше:", nextActions);
appendInventoryBulletSection(lines, "Граница ответа:", [
"Прибыльность номенклатуры считаю только когда есть реализация и подтвержденная себестоимость реализации.",
"Это не чистая прибыль компании и не замена закрытию месяца."
]);
return buildFactualSummaryReply(lines, buildConfirmedBalanceSemantics(entries.length > 0 ? "medium" : "weak", false));
}
const directAnswerLine =
confirmedEntries.length > 0
? `За период ${periodLabel} собран рейтинг реализованной номенклатуры по валовой маржинальности: выручка ${deps.formatMoneyRub(
totalRevenue
)}, себестоимостная база ${deps.formatMoneyRub(totalCostProxy)}, расчетная валовая разница ${deps.formatMoneyRub(
totalSpread
)}.`
: `За период ${periodLabel} не удалось подтвердить рейтинг прибыльности номенклатуры: нужны одновременно строки реализации и закупочного/себестоимостного следа по товарам.`;
const lines: string[] = [directAnswerLine];
if (highMargin.length > 0) {
appendInventorySection(
lines,
"Высокая валовая маржинальность:",
highMargin.map((entry, index) => formatInventoryMarginRankingLine(entry, index, deps))
);
}
if (lowMargin.length > 0) {
appendInventorySection(
lines,
"Низкая или отрицательная валовая маржинальность:",
lowMargin.map((entry, index) => formatInventoryMarginRankingLine(entry, index, deps))
);
}
const boundaryLines = [
"Это управленческий расчет валовой маржинальности по реализации и доступной себестоимостной базе, не чистая прибыль компании.",
"Для строгого бухгалтерского расчета нужны проводки 90.01 / 90.02 и закрытие себестоимости; этот ответ не подменяет закрытие месяца."
];
if (salesWithoutCost.length > 0) {
boundaryLines.push(
`По ${deps.formatNumberWithDots(salesWithoutCost.length)} позициям есть продажи, но нет подтвержденной себестоимости реализации — их нельзя честно ранжировать по прибыли.`
);
}
if (purchasesWithoutSales.length > 0) {
boundaryLines.push(
`По ${deps.formatNumberWithDots(purchasesWithoutSales.length)} позициям есть себестоимостная база без реализации в этом периоде.`
);
}
appendInventoryBulletSection(lines, "Граница ответа:", boundaryLines);
return buildFactualSummaryReply(
lines,
buildConfirmedBalanceSemantics(confirmedEntries.length > 0 ? "strong" : entries.length > 0 ? "medium" : "weak", confirmedEntries.length > 0)
);
}
if (intent === "inventory_profitability_for_item") {
const purchaseRows = rows.filter((row) => deps.isInventoryPurchaseMovement(row));
const saleRows = rows.filter((row) => deps.isInventorySaleMovement(row));
@@ -157,6 +157,7 @@ function isInventorySelectedObjectOrRootIntent(intent: string | null): boolean {
intent === "inventory_purchase_provenance_for_item" ||
intent === "inventory_purchase_documents_for_item" ||
intent === "inventory_sale_trace_for_item" ||
intent === "inventory_margin_ranking_for_nomenclature" ||
intent === "inventory_profitability_for_item" ||
intent === "inventory_purchase_to_sale_chain" ||
intent === "inventory_aging_by_purchase_date"
@@ -175,6 +176,18 @@ function isGenericCanonicalDriftIntent(intent: string | null): boolean {
);
}
function hasInventoryMarginRankingAccountCorrectionCue(text: string | null): boolean {
const value = String(text ?? "").toLowerCase();
if (!value.trim()) {
return false;
}
return (
/\b41(?:[.,]\d{1,2})?\b/iu.test(value) &&
/\b01(?:[.,]\d{1,2})?\b/iu.test(value) &&
/(?:\u0430\s+\u043d\u0435|\u043d\u0435|\u0432\u043c\u0435\u0441\u0442\u043e|not|instead)/iu.test(value)
);
}
function hasSameDateFollowupSignal(text: string | null): boolean {
return /(?:эту\s+же\s+дат(?:у|е|ой)|ту\s+же\s+дат(?:у|е|ой)|same\s+date)/iu.test(String(text ?? ""));
}
@@ -240,6 +253,12 @@ function shouldPreferRawFollowupMessage(
const hasInventoryFrameCarryover =
isInventorySelectedObjectOrRootIntent(previousIntent) ||
isInventorySelectedObjectOrRootIntent(rootIntent);
const hasInventoryMarginRankingCarryover =
previousIntent === "inventory_margin_ranking_for_nomenclature" ||
rootIntent === "inventory_margin_ranking_for_nomenclature";
const hasInventoryMarginRankingAccountCorrection =
hasInventoryMarginRankingCarryover &&
[rawMessage, canonicalMessage].some((message) => hasInventoryMarginRankingAccountCorrectionCue(message));
const hasDocumentCarryover =
previousIntent === "list_documents_by_counterparty" || previousIntent === "list_documents_by_contract";
@@ -263,6 +282,13 @@ function shouldPreferRawFollowupMessage(
return true;
}
if (
hasInventoryMarginRankingAccountCorrection &&
(intent === "account_balance_snapshot" || intent === "documents_forming_balance" || intent === "unknown")
) {
return true;
}
return (
(hasSelectedObjectInventorySignal(rawMessage) || hasInventoryItemCarryover) &&
(hasSelectedObjectInventoryActionCue(rawMessage) || hasShortInventoryPurchaseFollowupCue(rawMessage)) &&
@@ -34,6 +34,13 @@ function formatMissingAnchors(anchors: string[]): string {
}
function buildClarificationReply(binding: AssistantCapabilityRuntimeBindingContract): string {
if (binding.capability_contract_id === "inventory_inventory_margin_ranking_for_nomenclature") {
return [
"Для рейтинга прибыльности номенклатуры нужен период.",
"Могу посчитать по номенклатуре: выручку без НДС, себестоимость реализации, валовую прибыль и маржинальность.",
"Уточните период: месяц, квартал, год или весь доступный период."
].join("\n\n");
}
return [
"Нужно уточнение, чтобы не подставить неподтвержденный объект в расчет.",
`Не хватает: ${formatMissingAnchors(binding.missing_anchors)}.`,
@@ -161,6 +161,15 @@ function anchorSatisfied(requiredAnchor: string, providedAnchors: string[], debu
if (providedAnchors.includes(requiredAnchor)) {
return true;
}
if (requiredAnchor === "period") {
return (
(hasValue(filters?.period_from) && hasValue(filters?.period_to)) ||
hasValue(filters?.as_of_date) ||
providedAnchors.includes("period_from") ||
providedAnchors.includes("period_to") ||
providedAnchors.includes("as_of_date")
);
}
if (requiredAnchor === "item") {
return (
providedAnchors.includes("selected_object") ||
@@ -216,6 +216,7 @@ function isDetectedIntentAlignedWithTurnMeaning(
normalizedIntent === "inventory_purchase_provenance_for_item" ||
normalizedIntent === "inventory_purchase_documents_for_item" ||
normalizedIntent === "inventory_sale_trace_for_item" ||
normalizedIntent === "inventory_margin_ranking_for_nomenclature" ||
normalizedIntent === "inventory_profitability_for_item" ||
normalizedIntent === "inventory_purchase_to_sale_chain"
) {
@@ -276,7 +277,7 @@ function isExplicitMetadataDiscoveryTurn(
}
function isInventoryExactAddressIntent(intent: string | null): boolean {
return /^(?:inventory_purchase_provenance_for_item|inventory_purchase_documents_for_item|inventory_sale_trace_for_item|inventory_profitability_for_item|inventory_purchase_to_sale_chain|inventory_aging_by_purchase_date|inventory_on_hand_as_of_date)$/u.test(
return /^(?:inventory_purchase_provenance_for_item|inventory_purchase_documents_for_item|inventory_sale_trace_for_item|inventory_margin_ranking_for_nomenclature|inventory_profitability_for_item|inventory_purchase_to_sale_chain|inventory_aging_by_purchase_date|inventory_on_hand_as_of_date)$/u.test(
String(intent ?? "")
);
}
@@ -28,6 +28,7 @@ const ADDRESS_INTENTS_KEEP_ADDRESS_LANE = new Set([
"inventory_purchase_documents_for_item",
"inventory_supplier_stock_overlap_as_of_date",
"inventory_sale_trace_for_item",
"inventory_margin_ranking_for_nomenclature",
"inventory_profitability_for_item",
"inventory_purchase_to_sale_chain",
"inventory_aging_by_purchase_date",
@@ -41,6 +42,7 @@ const ADDRESS_INTENTS_ALLOW_STRICT_DEEP_INVESTIGATION_BYPASS = new Set([
"inventory_purchase_provenance_for_item",
"inventory_purchase_documents_for_item",
"inventory_sale_trace_for_item",
"inventory_margin_ranking_for_nomenclature",
"inventory_profitability_for_item",
"inventory_purchase_to_sale_chain"
]);
@@ -286,7 +288,7 @@ export function createAssistantRoutePolicy(deps) {
: null;
const semanticCanonicalRecommended = semanticExtractionContract?.apply_canonical_recommended !== false;
const llmSupportedDeepAddressIntentSignal = llmContractMode === "deep_analysis" &&
/^(?:inventory_purchase_provenance_for_item|inventory_purchase_documents_for_item|inventory_sale_trace_for_item|inventory_profitability_for_item|inventory_purchase_to_sale_chain)$/u.test(llmContractIntent ?? "") &&
/^(?:inventory_purchase_provenance_for_item|inventory_purchase_documents_for_item|inventory_sale_trace_for_item|inventory_margin_ranking_for_nomenclature|inventory_profitability_for_item|inventory_purchase_to_sale_chain)$/u.test(llmContractIntent ?? "") &&
semanticCanonicalRecommended;
const llmCanonicalEntitySignal = /(?:заказчик|поставщик|контрагент|компан|customer|supplier|counterparty|company|vendor|client)/iu.test(compactWhitespace(repairedInputMessage.toLowerCase()));
const llmCanonicalAppliedSignal = Boolean(llmPreDecomposeMeta?.applied) && llmContractMode !== "deep_analysis";
@@ -337,6 +337,18 @@ export const INVENTORY_CAPABILITY_CONTRACTS: readonly AssistantCapabilityContrac
answerObjectShape: "inventory_profitability_bundle",
bundleReusePolicy: "sale_trace_bundle_preferred"
}),
inventoryExactCapability({
capability_id: "inventory_inventory_margin_ranking_for_nomenclature",
intent_ids: ["inventory_margin_ranking_for_nomenclature"],
entry_modes: ["root_entry", "root_followup", "clarification_resume"],
transitions: ["T1", "T2", "T7"],
requiresFocusObject: false,
requiredAnchors: ["period"],
resultShape: "nomenclature_margin_ranking",
answerObjectShape: "inventory_margin_ranking",
bundleReusePolicy: "none",
scenarioFamilies: ["canonical", "colloquial", "account_41_correction"]
}),
inventoryExactCapability({
capability_id: "inventory_inventory_purchase_to_sale_chain",
intent_ids: ["inventory_purchase_to_sale_chain"],
@@ -47,6 +47,31 @@ export function createAssistantTransitionPolicy(deps) {
return deps.compactWhitespace(deps.repairAddressMojibake(String(value ?? "")).toLowerCase()).replace(/ё/g, "е");
}
function hasInventoryMarginRankingFollowupSignal(userMessage, alternateMessage = null, sourceIntentHint = null) {
if (sourceIntentHint !== "inventory_margin_ranking_for_nomenclature") {
return false;
}
return [userMessage, alternateMessage]
.filter((value) => deps.toNonEmptyString(value))
.map((value) =>
deps.compactWhitespace(deps.repairAddressMojibake(String(value ?? "")).toLowerCase()).replace(/ё/g, "е")
)
.some((normalized) => {
if (!normalized) {
return false;
}
const wantsFoundRows =
/(?:покажи|показать|выведи|дай|раскрой|show|list|РїРѕРєР°РРё|показаССЊ|РІСведи|РґР°Р|раскроР)/iu.test(normalized) &&
/(?:найденн|строк|реализац|себестоимостн|баз|РЅР°Рденн|СЃССЂРѕРє|реализаС|себесСРѕРёРјРѕСЃСРЅ|баз)/iu.test(normalized) &&
/(?:себестоимостн|реализац|марж|прибыл|номенклатур|себесСРѕРёРјРѕСЃСРЅ|реализаС|марР|РїСЂРёР±СР»|номенклаС)/iu.test(normalized);
const account41Not01 =
/\b41(?:[.,]\d{1,2})?\b/iu.test(normalized) &&
/\b01(?:[.,]\d{1,2})?\b/iu.test(normalized) &&
/(?:\bне\b|вместо|а\s+не|not|instead|РЅРµ|вмесСРѕ|Р°\s+РЅРµ)/iu.test(normalized);
return wantsFoundRows || account41Not01;
});
}
function hasSamePeriodReferenceCue(...values) {
return values
.map((value) => normalizeFollowupText(value))
@@ -760,6 +785,11 @@ export function createAssistantTransitionPolicy(deps) {
sourceIntentHint,
hasNavigationInventoryItemFocusHint
);
const inventoryMarginRankingFollowup = hasInventoryMarginRankingFollowupSignal(
userMessage,
alternateMessage,
sourceIntentHint
);
let inventoryShortFollowupPrimary =
(deps.isInventorySelectedObjectIntent(sourceIntentHint) || hasNavigationInventoryItemFocusHint) &&
deps.hasShortInventoryObjectFollowupSignal(userMessage);
@@ -796,6 +826,7 @@ export function createAssistantTransitionPolicy(deps) {
businessOverviewBoundaryFollowupPrimary ||
inventoryShortFollowupPrimary ||
inventoryPurchaseDateVatBridge ||
inventoryMarginRankingFollowup ||
explicitSummaryBundleReuseSignal ||
mcpDiscoveryOrganizationClarificationContinuation;
let hasAlternateFollowupSignal = deps.toNonEmptyString(alternateMessage)
@@ -805,6 +836,7 @@ export function createAssistantTransitionPolicy(deps) {
businessOverviewBoundaryFollowupAlternate ||
inventoryShortFollowupAlternate ||
inventoryPurchaseDateVatBridge ||
inventoryMarginRankingFollowup ||
explicitSummaryBundleReuseSignal ||
mcpDiscoveryOrganizationClarificationContinuation
: false;
@@ -862,6 +894,7 @@ export function createAssistantTransitionPolicy(deps) {
shortValueFlowRetargetAlternate ||
businessOverviewBoundaryFollowupPrimary ||
businessOverviewBoundaryFollowupAlternate ||
inventoryMarginRankingFollowup ||
deps.hasFollowupMarker(userMessage) ||
deps.hasReferentialPointer(userMessage) ||
(deps.toNonEmptyString(alternateMessage)
@@ -886,6 +919,7 @@ export function createAssistantTransitionPolicy(deps) {
shortValueFlowRetargetAlternate ||
businessOverviewBoundaryFollowupPrimary ||
businessOverviewBoundaryFollowupAlternate ||
inventoryMarginRankingFollowup ||
deps.hasFollowupMarker(userMessage) ||
deps.hasReferentialPointer(userMessage) ||
(deps.toNonEmptyString(alternateMessage)
@@ -1054,8 +1088,9 @@ export function createAssistantTransitionPolicy(deps) {
!inventoryShortFollowupPrimary &&
!inventoryShortFollowupAlternate &&
!businessOverviewBoundaryFollowupPrimary &&
!businessOverviewBoundaryFollowupAlternate &&
!foreignAccountingPivotOverInventory &&
!businessOverviewBoundaryFollowupAlternate &&
!inventoryMarginRankingFollowup &&
!foreignAccountingPivotOverInventory &&
!deps.hasFollowupMarker(userMessage) &&
!deps.hasReferentialPointer(userMessage) &&
(!deps.toNonEmptyString(alternateMessage)
@@ -1118,6 +1153,7 @@ export function createAssistantTransitionPolicy(deps) {
businessOverviewBoundaryFollowupPrimary ||
inventoryShortFollowupPrimary ||
inventoryPurchaseDateVatBridge ||
inventoryMarginRankingFollowup ||
explicitSummaryBundleReuseSignal ||
hasInventoryRootTemporalFollowupPrimary ||
mcpDiscoveryOrganizationClarificationContinuation;
@@ -1129,6 +1165,7 @@ export function createAssistantTransitionPolicy(deps) {
businessOverviewBoundaryFollowupAlternate ||
inventoryShortFollowupAlternate ||
inventoryPurchaseDateVatBridge ||
inventoryMarginRankingFollowup ||
explicitSummaryBundleReuseSignal ||
hasInventoryRootTemporalFollowupAlternate ||
mcpDiscoveryOrganizationClarificationContinuation
@@ -1151,6 +1188,7 @@ export function createAssistantTransitionPolicy(deps) {
shortValueFlowRetargetAlternate ||
businessOverviewBoundaryFollowupPrimary ||
businessOverviewBoundaryFollowupAlternate ||
inventoryMarginRankingFollowup ||
deps.hasFollowupMarker(userMessage) ||
deps.hasReferentialPointer(userMessage) ||
(deps.toNonEmptyString(alternateMessage)
@@ -22,6 +22,7 @@ const SUPPORTED_ADDRESS_INTENTS = new Set([
"inventory_purchase_documents_for_item",
"inventory_supplier_stock_overlap_as_of_date",
"inventory_sale_trace_for_item",
"inventory_margin_ranking_for_nomenclature",
"inventory_profitability_for_item",
"inventory_purchase_to_sale_chain",
"inventory_aging_by_purchase_date",
@@ -33,6 +33,7 @@ export type AddressIntent =
| "inventory_supplier_stock_overlap_as_of_date"
| "inventory_sale_trace_for_item"
| "inventory_trading_margin_proxy_for_organization"
| "inventory_margin_ranking_for_nomenclature"
| "inventory_profitability_for_item"
| "inventory_purchase_to_sale_chain"
| "inventory_aging_by_purchase_date"
@@ -203,6 +204,7 @@ export interface AddressRecipeDefinition {
| "inventory_supplier_stock_overlap_profile"
| "inventory_sale_trace_profile"
| "inventory_trading_margin_proxy_profile"
| "inventory_margin_ranking_profile"
| "inventory_profitability_profile"
| "inventory_purchase_to_sale_chain_profile"
| "inventory_aging_by_purchase_date_profile"