using System.Collections.Generic;
using System.Linq;
using iRIS.Framework.Common.ExtensionMethods;
using iRIS.InsuranceCore.Code.InsuranceProductsDocumentsProviders;
using iRIS.InsuranceCore.Code.Link2;
using iRIS.InsuranceCore.Entities;
using iRIS.Printing.Code.Queries;
using iRIS.Printing.Entities;
Расскажи как происходит склейка печатных форм Kasko_Additional_Agreement и Kasko_Modification_Statement
Assistant
В приведённом вами коде класс KaskoLink2PrintDocumentsProvider осуществляет склейку печатных форм для документов и через метод . Давайте рассмотрим, как это работает подробно.
User
как мне добавить условие чтобы если это b2p партнер не склеивать кид и полис каско
The code you've provided is a C# implementation of a class named KaskoLink2PrintDocumentsProvider, which extends the functionality of Link2PrintDocumentsProvider. It appears to be part of a software system designed to handle printing documents for Kasko insurance policies, likely in a business or insurance context. Below, I'll summarize the key components and functionality of the code:
Key Constants
Link2KaskoPolicyCode: Represents the code for the Kasko insurance policy document.
AdditionalAgreementFormCode and ModificationStatementFormCode: Codes for additional agreement and modification statement forms related to Kasko insurance.
InvoicePolicyCode: Refers to the invoice document code for Kasko policies.
_kidPrintingFormCodes: An array containing codes for printing forms related to Kasko, likely for documents not tied to a specific policy.
Constructor
KaskoLink2PrintDocumentsProvider: Initializes the class with dependencies needed for querying printing stores and form information, as well as a collection of document availability checkers.
Methods
FindAvailablePrintDocumentPrintParameters: Responsible for finding and returning a list of parameters for available print documents based on provided Basket, Deal, and PrintDocumentFilter objects.
It filters the available printing data using methods that check for the document code and document type provided in the filter.
FilterByPrintingFormTypeCode: Determines if a given printing form matches a specified document type or if certain combining criteria are met (like combining KID and Kasko policy docs).
FilterByPrintingFormCode: Filters printing forms by the specific document code and handles logical conditions for excluding certain document combinations.
Combines additional agreements and modification statements when applicable.
SetPrintingGroupIfNeedCombineKidAndKaskoPolicy: Checks if certain forms need to be grouped together when printing. Adjusts the printing group identifiers for KID and Kasko policy documents if they need to be combined.
CombineAdditionalAgreementAndModificationStatement: Similar to the previous method, but specifically handles the combination of additional agreement and modification statement documents.
General Class Functionality
The main objective of the class is to determine which printing documents are available for a particular insurance deal and organize them based on various criteria, such as combining related documents and setting printing group identifiers.
The class relies on conditional logic to selectively filter and manipulate document data, ensuring that only the appropriate documents are flagged for printing based on user input and internal policy.
This class is a part of a larger system that likely involves multiple components interacting to provide a cohesive document generation and printing solution for insurance documents. The combination of LINQ queries and functional interfaces (IQueryPrintingStores, IQueryPrintingFormInfos, etc.) suggests this system is modular and designed to handle a variety of document types in a dynamic manner.
printingData: Кортеж, содержащий информацию о текущей печатной форме, включая PrintingStore, PrintingFormInfo, и PrintDocumentAvailabilityStatus.
printingDatas: Список кортежей с аналогичной информацией для всех доступных печатных форм.
Логика:
Проверка кода печатной формы: Метод сначала проверяет, является ли код текущей печатной формы ModificationStatementFormCode. Если нет, метод возвращает false, и дальнейшая обработка останавливается для этой формы.
Поиск формы AdditionalAgreementFormCode: Далее метод ищет печатную форму с кодом AdditionalAgreementFormCode в списке printingDatas. Это делается с помощью метода FirstOrDefault, который возвращает первый найденный элемент, соответствующий условию.
Проверка найденной формы: Если форма с AdditionalAgreementFormCode существует (modificationPrintingForm.PrintingForm != null), происходит следующее:
Устанавливается значение PrintingGroup равным 1 как для текущей, так и для найденной формы. Это может означать, что данные формы должны обрабатываться как единая группа при последующих процессах (например, печати или отображении).
Метод возвращает true, указывая на то, что соединение успешно выполнено.
Назначение:
Склейка этих форм может быть нужна для бизнес-логики, где документы Kasko_Additional_Agreement и Kasko_Modification_Statement должны обрабатываться совместно. Это может быть обусловлено требованием единообразной обработки или отображения на определённых этапах, таких как предварительный просмотр, печать или архивирование документов.
Пример использования
Когда система вызывает метод для фильтрации доступных печатных документов, она проходит через все доступные формы и применяет данные методы для определения, какие из них должны объединяться. Это помогает в динамическом управлении выводом документации, удовлетворяя определённым бизнес-требованиям, заложенным в логику приложения.
Чтобы добавить условие, которое предотвращает склейку документов KID и полиса Каско для B2P партнёров, вам нужно внести изменения в метод SetPrintingGroupIfNeedCombineKidAndKaskoPolicy. Предположим, что информация о том, является ли партнёр B2P, содержится в параметрах Basket, Deal или каком-либо ином объекте, доступном в вашем классе.
Вот пример того, как можно модифицировать метод, чтобы проверить условие для B2P партнёра и избежать склейки документов:
csharp
private bool SetPrintingGroupIfNeedCombineKidAndKaskoPolicy(
(PrintingStore PrintingStore, PrintingFormInfo PrintingForm, PrintDocumentAvailabilityStatus Status) printingData,
List<(PrintingStore PrintingStore, PrintingFormInfo PrintingForm, PrintDocumentAvailabilityStatus Status)> printingDatas,
Deal deal) // Добавим deal как параметр метода
{
if (!_kidPrintingFormCodes.Contains(printingData.PrintingForm.Code))
{
return false;
}
// Проверка является ли текущий партнер B2P
if (IsB2PPartner(deal))
{
return false; // Если это B2P партнер, не склеивать документы
}
var kaskoPrintingForm = printingDatas
.FirstOrDefault(x => x.PrintingForm.Code == Link2KaskoPolicyCode);
if (kaskoPrintingForm.PrintingForm != null
&& kaskoPrintingForm.Status.IsPreview)
{
printingData.PrintingStore.PrintingGroup = 1;
kaskoPrintingForm.PrintingStore.PrintingGroup = 1;
return true;
}
return false;
}
private bool IsB2PPartner(Deal deal)
{
// Реализуйте логику определения, является ли партнёр B2P
// Это может быть проверка на основании информации о партнере в объекте deal или basket
return deal.PartnerType == "B2P"; // Пример, замените на реальную логику
}
Объяснение
Изменение метода: Обновлена сигнатура метода SetPrintingGroupIfNeedCombineKidAndKaskoPolicy для добавления параметра Deal. Это позволяет использовать информацию о текущей сделке, чтобы определить тип партнёра.
Проверка на B2P: Добавлен метод IsB2PPartner, который реализует логику определения того, является ли партнёр B2P. Этот метод вызывается внутри SetPrintingGroupIfNeedCombineKidAndKaskoPolicy перед склейкой документов.
Условная логика: Если IsB2PPartner возвращает true, метод сразу возвращает false, что предотвращает изменение PrintingGroup и, соответственно, склейку документов KID и полиса Каско.
Обеспечение верной идентификации партнёров и корректной обработки документов зависит от правильной реализации метода IsB2PPartner. Убедитесь, что используете актуальную и точную информацию в Deal или других объектах для определения типа партнёра.