ДОМЕНЫ - ВОПРОСЫ - НДС: развести as-of и tax-period intent, ускорить и стабилизировать VAT source probe, починить M23 тесты

This commit is contained in:
2026-04-13 08:04:02 +03:00
parent f1ef5f9d3c
commit c4f87222a8
27 changed files with 1065 additions and 189 deletions
@@ -28,7 +28,8 @@ const COMPUTE_EXACT_INTENTS = new Set<AddressIntent>([
"documents_forming_balance",
"payables_confirmed_as_of_date",
"receivables_confirmed_as_of_date",
"vat_payable_confirmed_as_of_date"
"vat_payable_confirmed_as_of_date",
"vat_liability_confirmed_for_tax_period"
]);
const NAVIGATION_INTENTS = new Set<AddressIntent>([
"list_documents_by_counterparty",
@@ -66,6 +67,9 @@ function defaultCapabilityId(intent: AddressIntent): string {
if (intent === "vat_payable_confirmed_as_of_date") {
return "confirmed_vat_payable_as_of_date";
}
if (intent === "vat_liability_confirmed_for_tax_period") {
return "confirmed_vat_liability_for_tax_period";
}
if (intent === "list_payables_counterparties") {
return "payables_candidates_list";
}
@@ -110,6 +114,14 @@ function resolveCapabilityEnabled(intent: AddressIntent): { enabled: boolean; re
: "vat_payable_confirmed_route_disabled_by_flag"
};
}
if (intent === "vat_liability_confirmed_for_tax_period") {
return {
enabled: FEATURE_ASSISTANT_ROUTE_BALANCE_EXACT_V1,
reason: FEATURE_ASSISTANT_ROUTE_BALANCE_EXACT_V1
? "vat_liability_confirmed_tax_period_route_enabled"
: "vat_liability_confirmed_tax_period_route_disabled_by_flag"
};
}
if (intent === "list_payables_counterparties") {
return {
enabled: FEATURE_ASSISTANT_ROUTE_PAYABLES_HEURISTIC_V1,
@@ -932,6 +932,9 @@ function requiredFiltersByIntent(intent: AddressIntent): Array<keyof AddressFilt
if (intent === "vat_payable_confirmed_as_of_date") {
return ["as_of_date"];
}
if (intent === "vat_liability_confirmed_for_tax_period") {
return ["period_from", "period_to"];
}
if (
intent === "list_documents_by_counterparty" ||
intent === "bank_operations_by_counterparty" ||
@@ -1102,6 +1105,17 @@ export function extractAddressFilters(userMessage: string, intent: AddressIntent
}
}
}
if (intent === "vat_liability_confirmed_for_tax_period" && !periodRange.period_from && !periodRange.period_to) {
const periodToForQuarter = filters.period_to ?? vatAsOfDate ?? null;
if (periodToForQuarter) {
const quarterWindow = deriveQuarterWindowForDate(periodToForQuarter);
if (quarterWindow) {
filters.period_from = quarterWindow.period_from;
filters.period_to = quarterWindow.period_to;
warnings.push("period_derived_from_tax_quarter_for_confirmed_vat_liability");
}
}
}
if (isManagementProfileIntent && !filters.period_to && !filters.as_of_date) {
filters.period_to = new Date().toISOString().slice(0, 10);
@@ -602,6 +602,44 @@ function hasForecastTaxSignal(text: string): boolean {
return hasForecastLexeme && hasTaxLexeme;
}
function hasVatLiabilityConfirmedTaxPeriodSignal(text: string): boolean {
const hasVatLexeme = /(?:ндс|vat)/iu.test(text);
if (!hasVatLexeme) {
return false;
}
const hasPaymentCue =
/(?:к\s+уплате|надо|нужно|заплатить|уплатить|плат[её]ж|платежку|в\s+налогов|в\s+бюджет|должн[аы]?\s+заплатить)/iu.test(
text
);
if (!hasPaymentCue) {
return false;
}
const hasAsOfCue = /(?:на\s+дат|по\s+состоянию|на\s+конец|as\s+of)/iu.test(text);
if (hasAsOfCue) {
return false;
}
const hasTaxAuthorityCue = /(?:в\s+налогов|в\s+бюджет|декларац|налогов(?:ый|ую)\s+период)/iu.test(text);
const hasQuarterCue = /(?:\b[1-4]\s*(?:квартал|кв\.?)\b|квартал|кв\.?)/iu.test(text);
const hasZaPeriodCue =
/(?:за\s+(?:\d{4}|январ|феврал|март|апрел|май|июн|июл|август|сентябр|октябр|ноябр|декабр|квартал|кв\.?|месяц|год|период))/iu.test(
text
);
const hasExplicitDayDate =
/\b(?:\d{1,2}[./-]\d{1,2}[./-](?:\d{2}|\d{4})|(?:19|20)\d{2}[./-]\d{1,2}[./-]\d{1,2})\b/u.test(text);
const hasMonthYearNaCue =
/(?:на\s+(?:январ|феврал|март|апрел|май|июн|июл|август|сентябр|октябр|ноябр|декабр)\S*\s+(?:19|20)\d{2})/iu.test(
text
);
const hasHowMuchCue = /(?:сколько|скока|скок)/iu.test(text);
// "На март 2020" и конкретная дата без налогового контекста чаще означают as-of срез.
if (!hasTaxAuthorityCue && !hasZaPeriodCue && !hasQuarterCue && (hasMonthYearNaCue || hasExplicitDayDate)) {
return false;
}
return hasTaxAuthorityCue || hasZaPeriodCue || hasQuarterCue || (hasHowMuchCue && hasTaxAuthorityCue);
}
function hasVatPayableConfirmedSignal(text: string): boolean {
const hasVatLexeme = /(?:ндс|vat)/iu.test(text);
if (!hasVatLexeme) {
@@ -1503,6 +1541,14 @@ function hasAccountNumberAnchor(text: string): boolean {
export function resolveAddressIntent(userMessage: string): AddressIntentResolution {
const text = String(userMessage ?? "").trim().toLowerCase();
if (hasVatLiabilityConfirmedTaxPeriodSignal(text)) {
return {
intent: "vat_liability_confirmed_for_tax_period",
confidence: "high",
reasons: ["vat_liability_confirmed_tax_period_signal_detected"]
};
}
if (hasForecastTaxSignal(text)) {
return {
intent: "vat_payable_forecast",
@@ -297,6 +297,7 @@ export async function executeAddressMcpQuery(input: {
query: string;
limit: number;
account_scope?: string[];
timeout_ms?: number;
}): Promise<{
fetched_rows: number;
matched_rows: number;
@@ -306,7 +307,11 @@ export async function executeAddressMcpQuery(input: {
}> {
const endpoint = buildMcpUrl("/api/execute_query");
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), Math.max(300, ASSISTANT_MCP_TIMEOUT_MS));
const resolvedTimeoutMs =
typeof input.timeout_ms === "number" && Number.isFinite(input.timeout_ms)
? Math.max(300, Math.trunc(input.timeout_ms))
: Math.max(300, ASSISTANT_MCP_TIMEOUT_MS);
const timeout = setTimeout(() => controller.abort(), resolvedTimeoutMs);
try {
const response = await fetch(endpoint, {
method: "POST",
@@ -373,10 +378,15 @@ export async function executeAddressMcpMetadata(input: {
offset?: number;
sections?: string[];
extension_name?: string | null;
timeout_ms?: number;
}): Promise<AddressMcpMetadataRowsResult> {
const endpoint = buildMcpUrl("/api/get_metadata");
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), Math.max(300, ASSISTANT_MCP_TIMEOUT_MS));
const resolvedTimeoutMs =
typeof input.timeout_ms === "number" && Number.isFinite(input.timeout_ms)
? Math.max(300, Math.trunc(input.timeout_ms))
: Math.max(300, ASSISTANT_MCP_TIMEOUT_MS);
const timeout = setTimeout(() => controller.abort(), resolvedTimeoutMs);
try {
const body: Record<string, unknown> = {};
if (typeof input.filter === "string" && input.filter.trim().length > 0) {
@@ -39,6 +39,7 @@ const RESULT_SET_TYPE_BY_INTENT: Partial<Record<AddressIntent, AddressResultSetT
list_payables_counterparties: "counterparty_list",
payables_confirmed_as_of_date: "balance_snapshot",
vat_payable_confirmed_as_of_date: "balance_snapshot",
vat_liability_confirmed_for_tax_period: "balance_snapshot",
receivables_confirmed_as_of_date: "balance_snapshot",
list_receivables_counterparties: "counterparty_list",
list_contracts_by_counterparty: "contract_list",
@@ -27,7 +27,11 @@ import {
selectAddressRecipe,
type AddressRecipeExecutionPlan
} from "./addressRecipeCatalog";
import { executeAddressMcpMetadata, executeAddressMcpQuery } from "./addressMcpClient";
import {
executeAddressMcpMetadata,
executeAddressMcpQuery,
type AddressMcpMetadataRowsResult
} from "./addressMcpClient";
import { runAddressDecomposeStage, type AddressFollowupContext } from "./address_runtime/decomposeStage";
import { resolvePrimaryAnchor, refineAnchorFromRows, type AnchorResolutionDebug } from "./address_runtime/resolveStage";
import {
@@ -87,9 +91,15 @@ const ADDRESS_CONFIRMED_PAYABLES_MIN_LIMIT = 200;
const COUNTERPARTY_CATALOG_LOOKUP_LIMIT = 1000;
const COUNTERPARTY_CATALOG_CACHE_TTL_MS = 120_000;
const VAT_METADATA_PROBE_LIMIT = 100;
const VAT_SOURCE_PROBE_MAX_OBJECTS = 8;
const VAT_METADATA_PROBE_TYPES = ["РегистрНакопления", "РегистрСведений", "Документ"] as const;
const VAT_METADATA_PROBE_MASKS = ["ндс", "книгапродаж", "книгапокупок", "счетфактур", "вычет", "восстанов"] as const;
const VAT_SOURCE_PROBE_MAX_OBJECTS = 6;
const VAT_METADATA_PROBE_TYPES = ["РегистрНакопления", "Документ"] as const;
const VAT_METADATA_PROBE_MASKS = ["ндс", "книгапродаж", "книгапокупок", "счетфактур"] as const;
const VAT_METADATA_PROBE_CONCURRENCY = 4;
const VAT_METADATA_PROBE_TIMEOUT_MS = 800;
const VAT_METADATA_PROBE_RETRY_TIMEOUT_MS = 1_200;
const VAT_OBJECT_PROBE_CONCURRENCY = 4;
const VAT_OBJECT_PROBE_TIMEOUT_MS = 800;
const VAT_OBJECT_PROBE_FALLBACK_TIMEOUT_MS = 800;
const PARTY_ANCHOR_STOPWORDS = new Set([
"ооо",
"ао",
@@ -312,6 +322,76 @@ function extractVatMetadataObjects(rows: Array<Record<string, unknown>>): VatMet
return out;
}
function isVatMetadataObject(item: VatMetadataObject): boolean {
const source = `${item.fullName} ${item.synonym ?? ""}`.toLowerCase().replace(/ё/g, "е");
if (source.includes("ндфл")) {
return false;
}
return /(?:ндс|книгапокуп|книгапродаж|счет[\s-]?фактур)/iu.test(source);
}
function isAbortErrorMessage(error: string | null | undefined): boolean {
const normalized = String(error ?? "").toLowerCase();
if (!normalized) {
return false;
}
return normalized.includes("aborted") || normalized.includes("abort");
}
async function mapWithConcurrency<T, R>(
items: T[],
concurrency: number,
worker: (item: T, index: number) => Promise<R>
): Promise<R[]> {
if (items.length === 0) {
return [];
}
const boundedConcurrency = Math.max(1, Math.min(Math.trunc(concurrency), items.length));
const results = new Array<R>(items.length);
let nextIndex = 0;
const runners = Array.from({ length: boundedConcurrency }, async () => {
while (true) {
const currentIndex = nextIndex;
nextIndex += 1;
if (currentIndex >= items.length) {
break;
}
results[currentIndex] = await worker(items[currentIndex], currentIndex);
}
});
await Promise.all(runners);
return results;
}
async function executeVatMetadataProbeRequest(request: {
meta_type: string;
name_mask: string;
limit: number;
}): Promise<AddressMcpMetadataRowsResult> {
const firstAttempt = await executeAddressMcpMetadata({
...request,
timeout_ms: VAT_METADATA_PROBE_TIMEOUT_MS
});
if (!firstAttempt.error || !isAbortErrorMessage(firstAttempt.error)) {
return firstAttempt;
}
const retryLimit = Math.max(20, Math.min(request.limit, Math.trunc(request.limit / 2)));
const retryAttempt = await executeAddressMcpMetadata({
...request,
limit: retryLimit,
timeout_ms: VAT_METADATA_PROBE_RETRY_TIMEOUT_MS
});
if (!retryAttempt.error) {
return retryAttempt;
}
return {
...retryAttempt,
error: `${firstAttempt.error}; retry: ${retryAttempt.error}`
};
}
function scoreVatMetadataObject(item: VatMetadataObject): number {
const fullName = item.fullName.toLowerCase();
const synonym = String(item.synonym ?? "").toLowerCase();
@@ -340,8 +420,12 @@ function scoreVatMetadataObject(item: VatMetadataObject): number {
return score;
}
function buildVatObjectProbeQuery(object: VatMetadataObject, asOfExpr: string): string {
type VatObjectProbeMode = "latest" | "exists";
function buildVatObjectProbeQuery(object: VatMetadataObject, asOfExpr: string, mode: VatObjectProbeMode = "latest"): string {
const orderClause = mode === "latest" ? "\nУПОРЯДОЧИТЬ ПО\n Движения.Период УБЫВ" : "";
if (object.objectType === "document") {
const documentOrderClause = mode === "latest" ? "\nУПОРЯДОЧИТЬ ПО\n Док.Дата УБЫВ" : "";
return `
ВЫБРАТЬ ПЕРВЫЕ 1
Док.Дата КАК Период,
@@ -353,9 +437,8 @@ function buildVatObjectProbeQuery(object: VatMetadataObject, asOfExpr: string):
${object.fullName} КАК Док
ГДЕ
Док.Дата <= ${asOfExpr}
УПОРЯДОЧИТЬ ПО
Док.Дата УБЫВ
`.trim();
${documentOrderClause}
`.trim().replace(/\n{3,}/g, "\n\n");
}
return `
ВЫБРАТЬ ПЕРВЫЕ 1
@@ -368,9 +451,8 @@ function buildVatObjectProbeQuery(object: VatMetadataObject, asOfExpr: string):
${object.fullName} КАК Движения
ГДЕ
Движения.Период <= ${asOfExpr}
УПОРЯДОЧИТЬ ПО
Движения.Период УБЫВ
`.trim();
${orderClause}
`.trim().replace(/\n{3,}/g, "\n\n");
}
async function probeVatDirectSources(filters: AddressFilterSet): Promise<VatDirectSourceProbeSummary> {
@@ -409,18 +491,35 @@ async function probeVatDirectSources(filters: AddressFilterSet): Promise<VatDire
limit: VAT_METADATA_PROBE_LIMIT
}))
);
const metadataResponses = await Promise.all(metadataRequests.map((request) => executeAddressMcpMetadata(request)));
const metadataResponses = await mapWithConcurrency(
metadataRequests,
VAT_METADATA_PROBE_CONCURRENCY,
(request) => executeVatMetadataProbeRequest(request)
);
const metadataOutcomes = metadataResponses.map((response, index) => ({
request: metadataRequests[index],
response
}));
const successfulMetadataByType = new Map<string, number>();
const metadataErrors: string[] = [];
const metadataObjectsBuffer: VatMetadataObject[] = [];
for (const [index, response] of metadataResponses.entries()) {
const request = metadataRequests[index];
for (const { request, response } of metadataOutcomes) {
if (response.error) {
metadataErrors.push(`${request.meta_type}:${request.name_mask}:${response.error}`);
continue;
}
const currentSuccessCount = successfulMetadataByType.get(request.meta_type) ?? 0;
successfulMetadataByType.set(request.meta_type, currentSuccessCount + 1);
metadataObjectsBuffer.push(...extractVatMetadataObjects(response.rows));
}
for (const { request, response } of metadataOutcomes) {
if (response.error) {
if (isAbortErrorMessage(response.error) && (successfulMetadataByType.get(request.meta_type) ?? 0) > 0) {
continue;
}
metadataErrors.push(`${request.meta_type}:${request.name_mask}:${response.error}`);
}
}
const deduplicatedObjects = new Map<string, VatMetadataObject>();
for (const item of metadataObjectsBuffer) {
@@ -437,54 +536,79 @@ async function probeVatDirectSources(filters: AddressFilterSet): Promise<VatDire
}
}
const discoveredMetadataObjects = Array.from(deduplicatedObjects.values()).sort(
const discoveredMetadataObjects = Array.from(deduplicatedObjects.values())
.filter((item) => isVatMetadataObject(item))
.sort(
(a, b) => scoreVatMetadataObject(b) - scoreVatMetadataObject(a) || a.fullName.localeCompare(b.fullName, "ru")
);
const metadataObjects = discoveredMetadataObjects.slice(0, VAT_SOURCE_PROBE_MAX_OBJECTS);
const probeRows: VatDirectSourceProbeItem[] = [];
for (const object of metadataObjects) {
const probeQuery = buildVatObjectProbeQuery(object, asOfExpr);
const probeResult = await executeAddressMcpQuery({
query: probeQuery,
limit: 1
});
if (probeResult.error) {
probeRows.push({
const probeRows = await mapWithConcurrency(
metadataObjects,
VAT_OBJECT_PROBE_CONCURRENCY,
async (object): Promise<VatDirectSourceProbeItem> => {
let probeResult = await executeAddressMcpQuery({
query: buildVatObjectProbeQuery(object, asOfExpr, "latest"),
limit: 1,
timeout_ms: VAT_OBJECT_PROBE_TIMEOUT_MS
});
let fallbackUsed = false;
if (probeResult.error) {
if (isAbortErrorMessage(probeResult.error)) {
return {
fullName: object.fullName,
synonym: object.synonym,
objectType: object.objectType,
status: "error",
rowsFetched: probeResult.fetched_rows,
error: probeResult.error
};
}
const fallbackResult = await executeAddressMcpQuery({
query: buildVatObjectProbeQuery(object, asOfExpr, "exists"),
limit: 1,
timeout_ms: VAT_OBJECT_PROBE_FALLBACK_TIMEOUT_MS
});
if (!fallbackResult.error) {
probeResult = fallbackResult;
fallbackUsed = true;
} else {
return {
fullName: object.fullName,
synonym: object.synonym,
objectType: object.objectType,
status: "error",
rowsFetched: probeResult.fetched_rows,
error: `${probeResult.error}; fallback: ${fallbackResult.error}`
};
}
}
const firstRow = probeResult.raw_rows[0] ?? null;
const lastPeriod =
firstRow !== null
? valueAsString(
(firstRow as Record<string, unknown>).Период ?? (firstRow as Record<string, unknown>).period
).trim() || null
: null;
const sampleRegistrator =
firstRow !== null
? valueAsString(
(firstRow as Record<string, unknown>).Регистратор ??
(firstRow as Record<string, unknown>).registrator ??
(firstRow as Record<string, unknown>).Registrator
).trim() || null
: null;
return {
fullName: object.fullName,
synonym: object.synonym,
objectType: object.objectType,
status: "error",
status: probeResult.raw_rows.length > 0 ? "ok" : "empty",
rowsFetched: probeResult.fetched_rows,
error: probeResult.error
});
continue;
lastPeriod: fallbackUsed ? null : lastPeriod,
sampleRegistrator
};
}
const firstRow = probeResult.raw_rows[0] ?? null;
const lastPeriod =
firstRow !== null
? valueAsString((firstRow as Record<string, unknown>).Период ?? (firstRow as Record<string, unknown>).period).trim() ||
null
: null;
const sampleRegistrator =
firstRow !== null
? valueAsString(
(firstRow as Record<string, unknown>).Регистратор ??
(firstRow as Record<string, unknown>).registrator ??
(firstRow as Record<string, unknown>).Registrator
).trim() || null
: null;
probeRows.push({
fullName: object.fullName,
synonym: object.synonym,
objectType: object.objectType,
status: probeResult.raw_rows.length > 0 ? "ok" : "empty",
rowsFetched: probeResult.fetched_rows,
lastPeriod,
sampleRegistrator
});
}
);
const status: VatDirectSourceProbeSummary["status"] = metadataResponses.every((item) => item.error) ? "error" : "ok";
const allErrors = [
@@ -1106,7 +1230,8 @@ function isConfirmedBalanceIntent(intent: AddressIntent): boolean {
intent === "documents_forming_balance" ||
intent === "payables_confirmed_as_of_date" ||
intent === "receivables_confirmed_as_of_date" ||
intent === "vat_payable_confirmed_as_of_date"
intent === "vat_payable_confirmed_as_of_date" ||
intent === "vat_liability_confirmed_for_tax_period"
);
}
@@ -1942,6 +2067,8 @@ function buildLimitedOffers(input: {
offers.push("показать подтвержденный реестр открытой дебиторской задолженности на дату среза по 62/76");
} else if (input.intent === "vat_payable_confirmed_as_of_date") {
offers.push("показать подтвержденную сумму НДС к уплате на дату среза по счетам 68*");
} else if (input.intent === "vat_liability_confirmed_for_tax_period") {
offers.push("показать подтвержденный расчет НДС к уплате за налоговый период по книгам продаж/покупок");
} else if (input.intent === "payables_confirmed_as_of_date") {
offers.push("показать подтвержденный реестр открытых обязательств на дату среза по 60/76");
} else if (input.intent === "list_payables_counterparties") {
@@ -1996,7 +2123,8 @@ function buildLimitedIntentSignalLine(input: {
list_payables_counterparties: "Сигнал запроса: нужен ранжированный список кредиторов.",
receivables_confirmed_as_of_date: "Сигнал запроса: нужен подтвержденный срез дебиторской задолженности на дату.",
payables_confirmed_as_of_date: "Сигнал запроса: нужен подтвержденный срез обязательств к оплате на дату.",
vat_payable_confirmed_as_of_date: "Сигнал запроса: нужен подтвержденный срез НДС к уплате на дату."
vat_payable_confirmed_as_of_date: "Сигнал запроса: нужен подтвержденный срез НДС к уплате на дату.",
vat_liability_confirmed_for_tax_period: "Сигнал запроса: нужен подтвержденный расчет НДС к уплате за налоговый период."
};
const byShape: Partial<Record<AddressQueryShapeDetection["shape"], string>> = {
@@ -2201,6 +2329,8 @@ function buildLimitedExecutionResult(input: {
? "exact_receivables_mode_limited_response"
: input.intent.intent === "vat_payable_confirmed_as_of_date"
? "exact_vat_payable_mode_limited_response"
: input.intent.intent === "vat_liability_confirmed_for_tax_period"
? "exact_vat_tax_period_mode_limited_response"
: null;
const reasons =
exactLimitedReason && !reasonsWithConfirmedFallback.includes(exactLimitedReason)
@@ -2460,6 +2590,12 @@ export class AddressQueryService {
) {
baseReasons.push("confirmed_balance_exact_vat_payable_intent");
}
if (
intent.intent === "vat_liability_confirmed_for_tax_period" &&
!baseReasons.includes("confirmed_balance_exact_vat_tax_period_intent")
) {
baseReasons.push("confirmed_balance_exact_vat_tax_period_intent");
}
if (
requestedResultMode === "confirmed_balance" &&
recipeIntent === "open_items_by_counterparty_or_contract" &&
@@ -3519,14 +3655,17 @@ export class AddressQueryService {
const vatProbeRequired =
composeIntent === "vat_payable_confirmed_as_of_date" ||
composeIntent === "vat_liability_confirmed_for_tax_period" ||
(composeIntent === "vat_payable_forecast" && shouldProbeVatSourcesForForecast(userMessage));
const vatDirectSourceProbe = vatProbeRequired ? await probeVatDirectSources(executionFilters) : null;
const shouldEmphasizeNumbers =
composeIntent === "vat_payable_forecast" ||
composeIntent === "vat_payable_confirmed_as_of_date" ||
composeIntent === "vat_liability_confirmed_for_tax_period" ||
composeIntent === "payables_confirmed_as_of_date" ||
composeIntent === "receivables_confirmed_as_of_date";
const shouldUseRubCurrency = composeIntent === "vat_payable_forecast";
const shouldUseRubCurrency =
composeIntent === "vat_payable_forecast" || composeIntent === "vat_liability_confirmed_for_tax_period";
const factual = composeFactualReply(
composeIntent,
filteredRows,
@@ -3599,14 +3738,18 @@ export class AddressQueryService {
const exactConfirmedIntent =
(intent.intent === "payables_confirmed_as_of_date" && composeIntent === "payables_confirmed_as_of_date") ||
(intent.intent === "receivables_confirmed_as_of_date" && composeIntent === "receivables_confirmed_as_of_date") ||
(intent.intent === "vat_payable_confirmed_as_of_date" && composeIntent === "vat_payable_confirmed_as_of_date");
(intent.intent === "vat_payable_confirmed_as_of_date" && composeIntent === "vat_payable_confirmed_as_of_date") ||
(intent.intent === "vat_liability_confirmed_for_tax_period" &&
composeIntent === "vat_liability_confirmed_for_tax_period");
if (exactConfirmedIntent && factualResultSemantics.balance_confirmed !== true) {
const exactModeName =
intent.intent === "payables_confirmed_as_of_date"
? "payables"
: intent.intent === "receivables_confirmed_as_of_date"
? "receivables"
: "vat_payable";
: intent.intent === "vat_liability_confirmed_for_tax_period"
? "vat_tax_period"
: "vat_payable";
return buildLimitedExecutionResult({
mode,
shape,
@@ -3634,6 +3777,8 @@ export class AddressQueryService {
nextStep:
intent.intent === "vat_payable_confirmed_as_of_date"
? "specify as_of_date/organization or provide VAT settlement registers to prove exact VAT payable balance"
: intent.intent === "vat_liability_confirmed_for_tax_period"
? "specify tax period boundaries and ensure purchase/sales VAT books are available via MCP"
: "specify as_of_date/counterparty or enable detailed settlement registers for exact confirmed balance",
limitations: [`exact_${exactModeName}_mode_unconfirmed_output_blocked`],
reasons: [...baseReasons, `exact_${exactModeName}_mode_unconfirmed_output_blocked`],
@@ -498,6 +498,30 @@ __WHERE_CLAUSE__
Регистратор
`;
const VAT_LIABILITY_CONFIRMED_TAX_PERIOD_QUERY_TEMPLATE = `
ВЫБРАТЬ
ДАТАВРЕМЯ(2000, 1, 1, 0, 0, 0) КАК Период,
"VAT_BOOK_SALES" КАК Регистратор,
"68.02" КАК СчетДт,
"" КАК СчетКт,
СУММА(ЕСТЬNULL(Движения.НДС, 0)) КАК Сумма
ИЗ
РегистрНакопления.НДСЗаписиКнигиПродаж КАК Движения
__WHERE_CLAUSE__
ОБЪЕДИНИТЬ ВСЕ
ВЫБРАТЬ
ДАТАВРЕМЯ(2000, 1, 1, 0, 0, 0) КАК Период,
"VAT_BOOK_PURCHASES" КАК Регистратор,
"19" КАК СчетДт,
"" КАК СчетКт,
СУММА(ЕСТЬNULL(Движения.НДС, 0)) КАК Сумма
ИЗ
РегистрНакопления.НДСЗаписиКнигиПокупок КАК Движения
__WHERE_CLAUSE__
УПОРЯДОЧИТЬ ПО
Регистратор
`;
const BASE_RECIPES: AddressRecipeDefinition[] = [
{
recipe_id: "address_period_coverage_profile_v1",
@@ -600,6 +624,16 @@ const BASE_RECIPES: AddressRecipeDefinition[] = [
account_scope_mode: "strict",
query_template: "vat_payable_confirmed_as_of_balance_profile"
},
{
recipe_id: "address_vat_liability_confirmed_tax_period_v1",
intent: "vat_liability_confirmed_for_tax_period",
purpose: "Build confirmed VAT liability for tax period from purchase/sales VAT books",
required_filters: ["period_from", "period_to"],
optional_filters: ["organization"],
default_limit: 32,
account_scope_mode: "preferred",
query_template: "vat_liability_confirmed_tax_period_profile"
},
{
recipe_id: "address_contracts_by_counterparty_v1",
intent: "list_contracts_by_counterparty",
@@ -947,6 +981,7 @@ function maxLimitForIntent(intent: AddressIntent): number {
intent === "supplier_payouts_profile" ||
intent === "contract_usage_and_value" ||
intent === "vat_payable_forecast" ||
intent === "vat_liability_confirmed_for_tax_period" ||
intent === "list_contracts_by_counterparty" ||
intent === "list_documents_by_counterparty" ||
intent === "bank_operations_by_counterparty" ||
@@ -996,7 +1031,8 @@ export function buildAddressRecipePlan(
recipe.query_template === "document_section_profile" ||
recipe.query_template === "counterparty_roles_profile" ||
recipe.query_template === "contract_usage_profile" ||
recipe.query_template === "vat_payable_forecast_profile";
recipe.query_template === "vat_payable_forecast_profile" ||
recipe.query_template === "vat_liability_confirmed_tax_period_profile";
const baseLimit =
typeof filters.limit === "number" && Number.isFinite(filters.limit)
? Math.max(1, Math.min(maxLimit, Math.trunc(filters.limit)))
@@ -1091,6 +1127,11 @@ export function buildAddressRecipePlan(
.replaceAll("__VAT68_DT_MATCH__", buildAccountPrefixPredicate("Движения.СчетДт", VAT_PAYABLE_68_PREFIXES))
.replaceAll("__VAT19_DT_MATCH__", buildAccountPrefixPredicate("Движения.СчетДт", VAT_PAYABLE_19_PREFIXES))
.replaceAll("__VAT19_KT_MATCH__", buildAccountPrefixPredicate("Движения.СчетКт", VAT_PAYABLE_19_PREFIXES))
: recipe.query_template === "vat_liability_confirmed_tax_period_profile"
? VAT_LIABILITY_CONFIRMED_TAX_PERIOD_QUERY_TEMPLATE.replaceAll(
"__WHERE_CLAUSE__",
buildManagementWhereClause(filters, "Движения.Период")
)
: recipe.query_template === "vat_payable_confirmed_as_of_balance_profile"
? (() => {
const asOfExpr =
@@ -212,6 +212,9 @@ function emphasizeNumericTokens(line: string): string {
if (!line) {
return line;
}
const isDigit = (char: string): boolean => /\d/.test(char);
const isLetter = (char: string): boolean => /[A-Za-zА-Яа-яЁё]/.test(char);
const dateLikePunctuation = new Set([".", "-", "/", ":"]);
const chunks = line.split(/(`[^`]*`)/g);
return chunks
.map((chunk, index) => {
@@ -221,9 +224,23 @@ function emphasizeNumericTokens(line: string): string {
return chunk.replace(/\b-?(?:\d{1,3}(?:[.\s]\d{3})+|\d+)(?:[.,]\d+)?\b/g, (match, offset, source) => {
const before = offset > 0 ? source[offset - 1] : "";
const after = offset + match.length < source.length ? source[offset + match.length] : "";
const before2 = offset > 1 ? source[offset - 2] : "";
const after2 = offset + match.length + 1 < source.length ? source[offset + match.length + 1] : "";
if (before === "*" || after === "*") {
return match;
}
if (isLetter(before) || isLetter(after)) {
return match;
}
if (offset === 0 && (after === "." || after === ")")) {
return match;
}
if (dateLikePunctuation.has(before) && isDigit(before2)) {
return match;
}
if (dateLikePunctuation.has(after) && isDigit(after2)) {
return match;
}
return `**${match}**`;
});
})
@@ -2545,18 +2562,37 @@ export function composeFactualReply(
if (vatProbe && vatProbe.status === "ok") {
const nonEmptySources = vatProbe.probedSources.filter((item) => item.status === "ok").length;
const statusRank = (status: VatDirectSourceProbeItem["status"]): number =>
status === "ok" ? 0 : status === "empty" ? 1 : 2;
const orderedProbeRows = [...vatProbe.probedSources].sort(
(a, b) =>
statusRank(a.status) - statusRank(b.status) ||
a.fullName.localeCompare(b.fullName, "ru")
);
const nonErrorProbeRows = orderedProbeRows.filter((item) => item.status !== "error");
const visibleProbeRows = (nonErrorProbeRows.length > 0 ? nonErrorProbeRows : orderedProbeRows).slice(0, 6);
const erroredSources = vatProbe.probedSources.filter((item) => item.status === "error").length;
lines.push(
"",
"Покрытие VAT-источников через MCP:",
`- Найдено VAT-объектов: ${formatNumberWithDots(vatProbe.objectsTotal)} (документы: ${formatNumberWithDots(vatProbe.documentsTotal)}, регистры: ${formatNumberWithDots(vatProbe.registersTotal)}).`,
`- Прямых источников проверено: ${formatNumberWithDots(vatProbe.probedSources.length)}.`,
`- Источников с движениями до даты среза: ${formatNumberWithDots(nonEmptySources)}.`
`- Источников с движениями до даты среза: ${formatNumberWithDots(nonEmptySources)}.`,
`- Источников с ошибкой запроса: ${formatNumberWithDots(erroredSources)}.`
);
if (vatProbe.probedSources.length > 0) {
if (visibleProbeRows.length > 0) {
lines.push(
...vatProbe.probedSources.slice(0, 6).map((item, index) => {
...visibleProbeRows.map((item, index) => {
const name = item.synonym ? `${item.fullName} (${item.synonym})` : item.fullName;
return `${index + 1}. ${name} | ${formatVatProbeStatusRu(item.status)}${item.lastPeriod ? ` | последнее движение: ${item.lastPeriod}` : ""}`;
const extra =
item.status === "ok"
? item.lastPeriod
? ` | последнее движение: ${item.lastPeriod}`
: ""
: item.status === "error" && item.error
? ` | ошибка: ${item.error}`
: "";
return `${index + 1}. ${name} | ${formatVatProbeStatusRu(item.status)}${extra}`;
})
);
}
@@ -2632,6 +2668,77 @@ export function composeFactualReply(
};
}
if (intent === "vat_liability_confirmed_for_tax_period") {
const rowsByMarker = new Map<string, number>();
for (const row of rows) {
const marker = String(row.registrator ?? "").trim().toUpperCase();
if (!marker) {
continue;
}
const nextValue = (rowsByMarker.get(marker) ?? 0) + (row.amount ?? 0);
rowsByMarker.set(marker, nextValue);
}
const salesVat = rowsByMarker.get("VAT_BOOK_SALES") ?? 0;
const purchaseVat = rowsByMarker.get("VAT_BOOK_PURCHASES") ?? 0;
const netVat = salesVat - purchaseVat;
const vatToPay = Math.max(0, netVat);
const carryoverOrOverpayment = Math.max(0, -netVat);
const periodWindowLabel =
options.periodFrom && options.periodTo ? `${formatDateRu(options.periodFrom)}..${formatDateRu(options.periodTo)}` : null;
const formatConfirmedMoney = (value: number): string => (options.useRubCurrency ? formatMoneyRub(value) : formatMoney(value));
const vatProbe = options.vatDirectSourceProbe ?? null;
const lines = [
`Собран подтвержденный расчет НДС к уплате за налоговый период: ${formatConfirmedMoney(vatToPay)}.`,
`Налоговый период расчета: ${periodWindowLabel ?? "не задан (нужен явный период)"}.`,
`Потенциальный перенос/переплата: ${formatConfirmedMoney(carryoverOrOverpayment)}.`,
"Режим результата: подтвержденный расчет по регистрам книг продаж/покупок (tax-period mode, без surrogate-формулы 68/19).",
"",
"База расчета:",
`- Строк агрегата: ${formatNumberWithDots(rows.length)}.`,
`- НДС по книге продаж: ${formatConfirmedMoney(salesVat)}.`,
`- НДС по книге покупок (вычеты): ${formatConfirmedMoney(purchaseVat)}.`,
`- Нетто НДС (книга продаж - книга покупок): ${formatConfirmedMoney(netVat)}.`
];
if (vatProbe && vatProbe.status === "ok") {
const nonEmptySources = vatProbe.probedSources.filter((item) => item.status === "ok").length;
const erroredSources = vatProbe.probedSources.filter((item) => item.status === "error").length;
lines.push(
"",
"Покрытие VAT-источников через MCP:",
`- Найдено VAT-объектов: ${formatNumberWithDots(vatProbe.objectsTotal)} (документы: ${formatNumberWithDots(vatProbe.documentsTotal)}, регистры: ${formatNumberWithDots(vatProbe.registersTotal)}).`,
`- Прямых источников проверено: ${formatNumberWithDots(vatProbe.probedSources.length)}.`,
`- Источников с движениями до даты среза: ${formatNumberWithDots(nonEmptySources)}.`,
`- Источников с ошибкой запроса: ${formatNumberWithDots(erroredSources)}.`
);
if (vatProbe.errors.length > 0) {
lines.push(`- Ограничения probe: ${vatProbe.errors.slice(0, 2).join("; ")}.`);
}
lines.push("- Сумма расчета выше получена по книгам продаж/покупок; probe использован для контроля полноты VAT-источников.");
} else if (vatProbe && vatProbe.status === "error") {
lines.push("", "Покрытие VAT-источников через MCP: probe завершился ошибкой, проверьте доступность регистров книг продаж/покупок.");
}
if (rows.length === 0) {
lines.push(
"",
"За выбранный налоговый период не найдены строки книг продаж/покупок, поэтому подтвержденная сумма к уплате равна 0."
);
}
return {
responseType: "FACTUAL_SUMMARY",
text: joinLines(lines),
semantics: {
result_mode: "confirmed_balance",
evidence_strength: "strong",
balance_confirmed: true
}
};
}
if (intent === "vat_payable_confirmed_as_of_date") {
const asOfDate = resolvePayablesAsOfDate(options);
const confirmedRows = rows.filter((row) => {
@@ -74,6 +74,10 @@ function hasVatForecastCue(text: string): boolean {
return /(?:прогноз|forecast|прикин|оцен|план)/iu.test(String(text ?? ""));
}
function hasVatTaxPaymentCue(text: string): boolean {
return /(?:к\s+уплате|надо|нужно|заплатить|уплатить|плат[её]ж|в\s+налогов|в\s+бюджет)/iu.test(String(text ?? ""));
}
function hasDocumentSignal(text: string): boolean {
return /(?:док(?:и|умент|ументы|ументов|ументами)|docs?|documents?|doki|docy|doci)/iu.test(String(text ?? ""));
}
@@ -534,7 +538,12 @@ function mergeFollowupFilters(
const currentHasPeriod = hasExplicitPeriodWindow(merged);
const previousHasPeriod = hasExplicitPeriodWindow(previous);
if (intent === "vat_payable_forecast" && previousHasPeriod && hasFollowupSignal && !hasExplicitPeriodInMessage) {
if (
(intent === "vat_payable_forecast" || intent === "vat_liability_confirmed_for_tax_period") &&
previousHasPeriod &&
hasFollowupSignal &&
!hasExplicitPeriodInMessage
) {
const currentPeriodFrom = toNonEmptyString(merged.period_from);
const currentPeriodTo = toNonEmptyString(merged.period_to);
const todayIso = new Date().toISOString().slice(0, 10);
@@ -570,6 +579,7 @@ function resolveMissingRequiredFilters(intent: AddressIntent, filters: AddressFi
payables_confirmed_as_of_date: ["as_of_date"],
receivables_confirmed_as_of_date: ["as_of_date"],
vat_payable_confirmed_as_of_date: ["as_of_date"],
vat_liability_confirmed_for_tax_period: ["period_from", "period_to"],
list_documents_by_counterparty: ["counterparty"],
bank_operations_by_counterparty: ["counterparty"],
list_contracts_by_counterparty: ["counterparty"],
@@ -611,9 +621,11 @@ function deriveIntentWithFollowupContext(
const isVatFollowup = hasVatCue(normalizedMessage);
if (detectedIntent.intent === "unknown" && isVatFollowup) {
const vatIntent: AddressIntent = hasVatForecastCue(normalizedMessage)
? "vat_payable_forecast"
: "vat_payable_confirmed_as_of_date";
const vatIntent: AddressIntent = hasVatTaxPaymentCue(normalizedMessage)
? "vat_liability_confirmed_for_tax_period"
: hasVatForecastCue(normalizedMessage)
? "vat_payable_forecast"
: "vat_payable_confirmed_as_of_date";
return {
intent: vatIntent,
confidence: "low",
@@ -194,7 +194,8 @@ function inferAggregationProfile(intent: AddressIntent, shape: AddressQueryShape
intent === "documents_forming_balance" ||
intent === "payables_confirmed_as_of_date" ||
intent === "receivables_confirmed_as_of_date" ||
intent === "vat_payable_confirmed_as_of_date"
intent === "vat_payable_confirmed_as_of_date" ||
intent === "vat_liability_confirmed_for_tax_period"
) {
return "balance_snapshot";
}
@@ -3793,6 +3793,7 @@ const ADDRESS_INTENTS_KEEP_ADDRESS_LANE = new Set([
"contract_usage_overview",
"contract_usage_and_value",
"vat_payable_forecast",
"vat_liability_confirmed_for_tax_period",
"vat_payable_confirmed_as_of_date"
]);
export function resolveAssistantOrchestrationDecision(input) {
@@ -10,6 +10,7 @@ export type AddressIntent =
| "supplier_payouts_profile"
| "contract_usage_and_value"
| "vat_payable_forecast"
| "vat_liability_confirmed_for_tax_period"
| "vat_payable_confirmed_as_of_date"
| "list_contracts_by_counterparty"
| "list_open_contracts"
@@ -132,6 +133,7 @@ export interface AddressRecipeDefinition {
| "contract_value_profile"
| "contracts_by_counterparty_profile"
| "vat_payable_forecast_profile"
| "vat_liability_confirmed_tax_period_profile"
| "vat_payable_confirmed_as_of_balance_profile"
| "payables_confirmed_as_of_balance_profile"
| "receivables_confirmed_as_of_balance_profile";