Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Terrasoft.Configuration
- {
- using System;
- using System.Collections.ObjectModel;
- using System.ComponentModel;
- using System.Collections.Specialized;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.CompilerServices;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Converters;
- using Terrasoft.Configuration;
- using Terrasoft.Common;
- using Terrasoft.Core;
- using Terrasoft.Core.DB;
- using Terrasoft.Core.Entities;
- using System.Linq;
- using Terrasoft.Configuration.BG_DocumentIntegration;
- using System.Threading.Tasks;
- public class SibDocumentIntegrationHelper
- {
- private UserConnection userConn;
- public readonly Guid sibStatus_UnderConsideration = SibConstantsCS.DocListInFinAppStatus.UnderConsideration;
- public readonly Guid fileType_file = SibConstantsCS.FileType.File;
- public Guid DocId = Guid.Empty;
- public Guid DocumentId = Guid.Empty;
- public bool IsDocument;
- //private DocListInFinApp docFinApp;
- public SibDocumentIntegrationHelper(UserConnection uc)
- {
- userConn = uc;
- }
- private IncomeRequest ParseIncomeRequest(string request)
- {
- IncomeRequest incomeRequest = JsonConvert.DeserializeObject<IncomeRequest>(request);
- return incomeRequest;
- }
- private OutcomeRequest ParseOutcomeRequest(string jsonData)
- {
- OutcomeRequest deserializedProduct = JsonConvert.DeserializeObject<OutcomeRequest>(jsonData);
- return deserializedProduct;
- }
- public bool CreatedFileFromRequest(string request, ref string err)
- {
- try
- {
- var data = ParseIncomeRequest(request);
- if (data.document == null)
- throw new Exception("В запросе отсутствует объект document");
- Guid docId = data.document.id;
- Guid guaranteeIntegrationId = data.document.guaranteeIntegrationId;
- bool updateSign = data.document.updateSign;
- bool isClientDocument = data.document.isClientDocument;
- if (updateSign == true)
- {
- this.UpdateSign(data.files);
- }
- else if (guaranteeIntegrationId.IsEmpty())//если привязка к заявке
- {
- if (docId.IsEmpty())
- throw new Exception("В запросе не передан идентификатор документа");
- DocListInFinApp doc = new DocListInFinApp(this.userConn) { UseAdminRights = false };
- Document doc2 = new Document(this.userConn) { UseAdminRights = false };
- if (doc.FetchFromDB(docId)) {
- docId = DocId = this.GetDocListInFinApp(docId);
- this.CreateFiles(data.files, docId);
- }
- else if (doc2.FetchFromDB(docId)) {
- docId = DocumentId = this.GetDocInFinApp(docId);
- this.CreateFilesForDocument(data.files, docId);
- }
- else {
- throw new Exception("По указанному id не найден ни один из возможных документов");
- }
- }
- else if (guaranteeIntegrationId.IsNotEmpty())//если привязка к интеграционной заявке
- {
- if (isClientDocument) {
- if (docId.IsEmpty())
- {
- docId = DocId = this.CreateDocListInFinAppInGuaranteeIntegration(guaranteeIntegrationId, data.document.code);
- } else
- {
- docId = DocId = this.GetDocListInFinAppInGuaranteeIntegration(guaranteeIntegrationId, docId);
- }
- this.CreateFiles(data.files, docId);
- } else {
- Guid documentId;
- if (docId.IsEmpty())
- {
- documentId = this.CreateDocumentInGuaranteeIntegration(guaranteeIntegrationId, data.document.code);
- }
- else
- {
- documentId = this.GetDocumentInGuaranteeIntegration(guaranteeIntegrationId, docId);
- }
- this.CreateFilesForDocument(data.files, documentId);
- DocumentId = documentId;
- }
- }
- //отправляем уведомление в ЛК
- //if (docFinApp != null)
- //{
- // Task.Factory.StartNew(() =>
- // {
- // this.SendMessageCabinetLK(this.userConn, docFinApp);
- // });
- //}
- return true;
- }
- catch (Exception ex)
- {
- err = ex.ToString();
- SibLogger.Error(err);
- return false;
- }
- }
- /// <summary>
- /// Создание пакета документов с привязкой к интеграционной заявке
- /// </summary>
- /// <param name="guaranteeIntegrationId">Интеграционная заявка</param>
- /// <param name="code">Код документа</param>
- /// <returns>Id созданного пакета документов</returns>
- private Guid CreateDocListInFinAppInGuaranteeIntegration(Guid guaranteeIntegrationId, string code)
- {
- RegDocumentType regDocType = new RegDocumentType(this.userConn) { UseAdminRights = false };
- if (!regDocType.FetchFromDB("SibCode", code, new string[] { "Id" }, false))
- throw new Exception("Код типа регистрационного документа не найден");
- DocListInFinApp docNew = new DocListInFinApp(this.userConn) { UseAdminRights = false };
- docNew.SetDefColumnValues();
- docNew.SibGuaranteeIntegrationId = guaranteeIntegrationId;
- docNew.DocumentId = regDocType.Id;
- docNew.SibIsActual = true;
- docNew.SibIsSignNeeded = true;
- docNew.SibIsArrived = true;
- docNew.IsRequired = true;
- docNew.Save(false);
- return docNew.Id;
- }
- /// <summary>
- /// Получение пакета документов в инетграционной заявке
- /// </summary>
- /// <param name="guaranteeIntegrationId">Интеграционная заявка</param>
- /// <param name="docListInFinAppId">Id пакета документов</param>
- /// <returns>Id найденного пакета документов</returns>
- private Guid GetDocListInFinAppInGuaranteeIntegration(Guid guaranteeIntegrationId, Guid docListInFinAppId)
- {
- DocListInFinApp doc = new DocListInFinApp(this.userConn) { UseAdminRights = false };
- if (doc.FetchFromDB(new Dictionary<string, object> {
- {"Id", docListInFinAppId},
- {"SibGuaranteeIntegration", guaranteeIntegrationId}
- })) {
- return doc.Id;
- } else
- {
- throw new Exception("Пакет документов " + docListInFinAppId + " не найден");
- }
- }
- /// <summary>
- /// Создание документа с привязкой к интеграционной заявке
- /// </summary>
- /// <param name="guaranteeIntegrationId">Интеграционная заявка</param>
- /// <param name="code">Код документа</param>
- /// <returns>Id созданного документа</returns>
- private Guid CreateDocumentInGuaranteeIntegration(Guid guaranteeIntegrationId, string code)
- {
- DocumentType docType = new DocumentType(this.userConn) { UseAdminRights = false };
- if (!docType.FetchFromDB("Code", code, new string[] { "Id" }, false))
- throw new Exception("Код типа документа не найден");
- Document docNew = new Document(this.userConn) { UseAdminRights = false };
- docNew.SetDefColumnValues();
- docNew.SibGuaranteeIntegrationId = guaranteeIntegrationId;
- docNew.TypeId = docType.Id;
- docNew.SibIsActual = true;
- docNew.SibIsSignNeeded = true;
- docNew.SibIsArrived = true;
- docNew.Save(false);
- return docNew.Id;
- }
- /// <summary>
- /// Получение документа в инетграционной заявке
- /// </summary>
- /// <param name="guaranteeIntegrationId">Интеграционная заявка</param>
- /// <param name="documentId">Id документа</param>
- /// <returns>Id найденного пакета документов</returns>
- private Guid GetDocumentInGuaranteeIntegration(Guid guaranteeIntegrationId, Guid documentId)
- {
- Document doc = new Document(this.userConn) { UseAdminRights = false };
- if (doc.FetchFromDB(new Dictionary<string, object> {
- {"Id", documentId},
- {"SibGuaranteeIntegration", guaranteeIntegrationId}
- }))
- {
- return doc.Id;
- }
- else
- {
- throw new Exception("Документ " + documentId + " не найден");
- }
- }
- /// <summary>
- /// Получение документа для загрузки файлов
- /// </summary>
- /// <param name="curDocId">Идентификатор текущего документа</param>
- /// <returns>Идентификатор документа</returns>
- private Guid GetDocListInFinApp(Guid curDocId)
- {
- DocListInFinAppFile existFiles = this.userConn.GetTypedEntityListByAnyColumn<DocListInFinAppFile>("DocListInFinApp", curDocId).FirstOrDefault();
- DocListInFinApp doc = new DocListInFinApp(this.userConn) { UseAdminRights = false };
- if (!doc.FetchFromDB(curDocId))
- throw new Exception("Ошибка! Не найден документ с идентификатором " + curDocId);
- if (doc.SibMainDocId.IsEmpty())
- throw new Exception("Ошибка! В документе с идентификатором " + curDocId + " отсутствует ссылка на основной документ.");
- //Проверяем соответствует ли код типа документа кодам 113, 114, 115
- //var typesDocList = new List<Guid>();
- //typesDocList.Add(Guid.Parse("54F40E24-6E91-4A0F-995D-E51A95A15B00")); //113
- //typesDocList.Add(Guid.Parse("B60480FF-6D9F-4F55-A224-9AB236A7CD0C")); //114
- //typesDocList.Add(Guid.Parse("4ED4BB41-9BCA-40DB-A8F2-FB2931AC6F45")); //115
- //Если соответствует одному из них, то сбрасываем признак Обязательный у остальных
- //Guid findType = typesDocList.Find(x => x == doc.DocumentId);
- //if (findType.IsNotEmpty())
- //{
- // typesDocList.Remove(findType);
- // this.DelRequiredFromDocs(doc, typesDocList);
- // docFinApp = doc;
- //}
- if (existFiles == null)
- {
- doc.SibIsArrived = true;
- doc.Save(false);
- return curDocId;
- }
- //находим текущую версию документа
- int maxVersion = 0;
- Select s = (Select)new Select(this.userConn)
- .Max("SibVersion").As("MaxVersion")
- .From("DocListInFinApp")
- .Where("SibMainDocId").IsEqual(Column.Parameter(doc.SibMainDocId));
- using (var dbExecutor = userConn.EnsureDBConnection())
- using (var reader = s.ExecuteReader(dbExecutor))
- if (reader.Read())
- maxVersion = reader.GetColumnValue<int>("MaxVersion");
- DocListInFinApp docNew = new DocListInFinApp(this.userConn) { UseAdminRights = false };
- docNew.SetDefColumnValues();
- docNew.Name = doc.Name;
- if (doc.FinApplicationId.IsNotEmpty())
- docNew.FinApplicationId = doc.FinApplicationId;
- if (doc.AgentContractId.IsNotEmpty())
- docNew.AgentContractId = doc.AgentContractId;
- if (doc.AppFormId.IsNotEmpty())
- docNew.AppFormId = doc.AppFormId;
- docNew.DocumentId = doc.DocumentId;
- var finap = userConn.GetTypedEntityById<FinApplication>(doc.FinApplicationId);
- docNew.SibSourceINN = finap.SibSourceINN;
- if (docNew.DocumentId == SibConstantsCS.RegDocumentType.StatementAppFormdocument &&
- finap.SourceId == SibConstantsCS.FinAppSource.TenderHub &&
- doc.SibStatusId == SibConstantsCS.DocListInFinAppStatus.Approved) {
- docNew.SibIsActual = false;
- docNew.Notes= "Дубль документа";
- }
- else {
- docNew.SibIsActual = true;
- doc.SibIsActual = false;
- doc.Save(false);
- }
- docNew.SibVersion = ++maxVersion;
- docNew.SibStatusId = sibStatus_UnderConsideration;
- docNew.SibIsSignNeeded = doc.SibIsSignNeeded;
- docNew.SibIsArrived = true;
- docNew.IsRequired = doc.IsRequired;
- docNew.SibMainDocId = doc.SibMainDocId;
- docNew.Save(false);
- return docNew.Id;
- }
- /// <summary>
- /// Получение документа для загрузки файлов
- /// </summary>
- /// <param name="curDocId">Идентификатор текущего документа</param>
- /// <returns>Идентификатор документа</returns>
- private Guid GetDocInFinApp(Guid curDocId)
- {
- DocumentFile existFiles = this.userConn.GetTypedEntityListByAnyColumn<DocumentFile>("Document", curDocId).FirstOrDefault();
- Document doc = new Document(this.userConn) { UseAdminRights = false };
- if (!doc.FetchFromDB(curDocId))
- throw new Exception("Ошибка! Не найден документ с идентификатором " + curDocId);
- if (doc.SibMainDocId.IsEmpty())
- throw new Exception("Ошибка! В документе с идентификатором " + curDocId + " отсутствует ссылка на основной документ.");
- if (existFiles == null)
- {
- doc.SibIsArrived = true;
- doc.Save(false);
- return curDocId;
- }
- //находим текущую версию документа
- int maxVersion = 0;
- Select s = (Select)new Select(this.userConn)
- .Max("SibVersion").As("MaxVersion")
- .From("Document")
- .Where("SibMainDocId").IsEqual(Column.Parameter(doc.SibMainDocId));
- using (var dbExecutor = userConn.EnsureDBConnection())
- using (var reader = s.ExecuteReader(dbExecutor))
- if (reader.Read())
- maxVersion = reader.GetColumnValue<int>("MaxVersion");
- Document docNew = new Document(this.userConn) { UseAdminRights = false };
- docNew.SetDefColumnValues();
- //docNew.Number = doc.Number;
- if (doc.FinApplicationId.IsNotEmpty())
- docNew.FinApplicationId = doc.FinApplicationId;
- if (doc.AgentContractId.IsNotEmpty())
- docNew.AgentContractId = doc.AgentContractId;
- docNew.TypeId = doc.TypeId;
- docNew.SibIsActual = true;
- docNew.SibVersion = ++maxVersion;
- docNew.SibStatusId = sibStatus_UnderConsideration;
- docNew.SibIsSignNeeded = doc.SibIsSignNeeded;
- docNew.SibIsArrived = true;
- docNew.SibIsRequired = doc.SibIsRequired;
- var finap = userConn.GetTypedEntityById<FinApplication>(doc.FinApplicationId);
- docNew.SibSourceINN = finap.SibSourceINN;
- docNew.SibMainDocId = doc.SibMainDocId;
- docNew.Save(false);
- doc.SibIsActual = false;
- doc.Save(false);
- return docNew.Id;
- }
- /// <summary>
- /// Проверка ЭЦП файлов и загрузка в зависимости от того, файл документ или файл пакета документа
- /// </summary>
- /// <param name="files">Массив файлов, в которые загружаеются ЭЦП</param>
- /// <returns></returns>
- private void UpdateSign(List<BG_DocumentIntegration.File> files)
- {
- foreach (var file in files)
- {
- if (file.id.IsEmpty())
- throw new Exception("Ошибка! В объекте file отсутствует поле Id.");
- if (file.sign == null)
- throw new Exception("Ошибка! Отсутствует поле sign.");
- DocumentFile documentFile = new DocumentFile(this.userConn) { UseAdminRights = false };
- DocListInFinAppFile docFile = new DocListInFinAppFile(this.userConn) { UseAdminRights = false };
- if (docFile.FetchFromDB("Id", file.id, new string[] { "Id", "DocListInFinApp" }, false))
- {
- CreateDocListInFinAppFile(file, docFile.DocListInFinAppId);
- } else if (documentFile.FetchFromDB("Id", file.id, new string[] { "Id", "Document" }, false))
- {
- CreateDocumentFile(file, documentFile.DocumentId);
- } else
- {
- throw new Exception("Ошибка! Не найден файл с идентификатором " + file.id);
- }
- }
- }
- /// <summary>
- /// Загрузка ЭЦП файла к пакету документа
- /// </summary>
- /// <param name="files">Массив файлов, в которые загружаеются ЭЦП</param>
- /// <param name="docListInFinAppId">Id пакета документов</param>
- /// <returns></returns>
- private void CreateDocListInFinAppFile(BG_DocumentIntegration.File file, Guid docListInFinAppId)
- {
- DocListInFinAppFile docSign = new DocListInFinAppFile(userConn) { UseAdminRights = false };
- if (docSign.FetchFromDB("SibDocListInFinAppFileForSign", file.id))
- {
- byte[] bytes2 = Convert.FromBase64String(file.sign);
- docSign.SetBytesValue("Data", bytes2);
- }
- else
- {
- docSign.SetDefColumnValues();
- docSign.TypeId = fileType_file;
- docSign.DocListInFinAppId = docListInFinAppId;
- docSign.SibIsSign = true;
- docSign.SibDocListInFinAppFileForSignId = file.id;
- docSign.Name = $"Подпись {file.name}.sig";
- byte[] bytes2 = Convert.FromBase64String(file.sign);
- docSign.SetBytesValue("Data", bytes2);
- }
- docSign.Save(false);
- }
- /// <summary>
- /// Загрузка ЭЦП файла к пакету документа
- /// </summary>
- /// <param name="files">Массив файлов, в которые загружаеются ЭЦП</param>
- /// <param name="docListInFinAppId">Id документа</param>
- /// <returns></returns>
- private void CreateDocumentFile(BG_DocumentIntegration.File file, Guid documentId)
- {
- DocumentFile docSign = new DocumentFile(userConn) { UseAdminRights = false };
- if (docSign.FetchFromDB("SibDocumentFileForSign", file.id))
- {
- byte[] bytes2 = Convert.FromBase64String(file.sign);
- docSign.SetBytesValue("Data", bytes2);
- }
- else
- {
- docSign.SetDefColumnValues();
- docSign.TypeId = fileType_file;
- docSign.DocumentId = documentId;
- docSign.SibIsSign = true;
- docSign.SibDocumentFileForSignId = file.id;
- docSign.Name = $"Подпись {file.name}.sig";
- byte[] bytes2 = Convert.FromBase64String(file.sign);
- docSign.SetBytesValue("Data", bytes2);
- }
- docSign.Save(false);
- }
- /// <summary>
- /// Создание файлов для пакета дкоументов
- /// </summary>
- /// <param name="files">Массив файлов</param>
- /// <param name="docId">Идентификатор пакета документов для загрузки файлов</param>
- /// <returns></returns>
- private void CreateFiles(List<BG_DocumentIntegration.File> files, Guid docId)
- {
- foreach (var file in files)
- {
- DocListInFinAppFile docFile = new DocListInFinAppFile(this.userConn) { UseAdminRights = false };
- docFile.SetDefColumnValues();
- docFile.TypeId = fileType_file;
- docFile.DocListInFinAppId = docId;
- docFile.Name = file.name;
- byte[] bytes = Convert.FromBase64String(file.data);
- docFile.SetBytesValue("Data", bytes);
- docFile.Save(false);
- if (file.sign != null)
- {
- DocListInFinAppFile docSign = new DocListInFinAppFile(this.userConn) { UseAdminRights = false };
- docSign.SetDefColumnValues();
- docSign.TypeId = fileType_file;
- docSign.DocListInFinAppId = docId;
- docSign.SibIsSign = true;
- docSign.SibDocListInFinAppFileForSignId = docFile.Id;
- docSign.Name = $"Подпись {file.name}.sig";
- byte[] bytes2 = Convert.FromBase64String(file.sign);
- docSign.SetBytesValue("Data", bytes2);
- docSign.Save(false);
- }
- }
- }
- /// <summary>
- /// Создание файлов для документа
- /// </summary>
- /// <param name="files">Массив файлов</param>
- /// <param name="documentId">Идентификатор документа </param>
- /// <returns></returns>
- private void CreateFilesForDocument(List<BG_DocumentIntegration.File> files, Guid documentId)
- {
- foreach (var file in files)
- {
- DocumentFile docFile = new DocumentFile(this.userConn) { UseAdminRights = false };
- docFile.SetDefColumnValues();
- docFile.TypeId = fileType_file;
- docFile.DocumentId = documentId;
- docFile.Name = file.name;
- byte[] bytes = Convert.FromBase64String(file.data);
- docFile.SetBytesValue("Data", bytes);
- docFile.Save(false);
- if (file.sign != null)
- {
- DocumentFile docSign = new DocumentFile(this.userConn) { UseAdminRights = false };
- docSign.SetDefColumnValues();
- docSign.TypeId = fileType_file;
- docSign.DocumentId = documentId;
- docSign.SibIsSign = true;
- docSign.SibDocumentFileForSignId = docFile.Id;
- docSign.Name = $"Подпись {file.name}.sig";
- byte[] bytes2 = Convert.FromBase64String(file.sign);
- docSign.SetBytesValue("Data", bytes2);
- docSign.Save(false);
- }
- }
- }
- /// <summary>
- /// Сбрасываем признак Обязательный у документов заданного типа
- /// </summary>
- /// <param name="doc">Текущий документ</param>
- /// <param name="typesDocList">Список типов документов для поиска</param>
- /// <returns></returns>
- private void DelRequiredFromDocs(DocListInFinApp doc, List<Guid> typesDocList)
- {
- if (doc.AppFormId.IsEmpty())
- return;
- foreach (Guid typeDocId in typesDocList)
- {
- DocListInFinApp finfDoc = userConn.GetTypedEntityListByAnyColumn<DocListInFinApp>("AppForm", doc.AppFormId)
- .FirstOrDefault(x => (x.SibIsActual == true && x.DocumentId.Equals(typeDocId)));
- if (finfDoc != null)
- {
- finfDoc.IsRequired = false;
- finfDoc.Save(false);
- }
- }
- }
- /// <summary>
- /// Получение массива файлов
- /// </summary>
- /// <param name="request">Текущий документ</param>
- /// <returns>Результат выполнения</returns>
- public string GetFileWithSign(string request)
- {
- try
- {
- var data = ParseOutcomeRequest(request);
- List<BG_DocumentIntegration.File> files = new List<BG_DocumentIntegration.File>();
- var ids = new List<string>();
- foreach (var file in data.files)
- {
- ids.Add(file.id.ToString());
- }
- var inIds = ids.ToArray();
- var esq = new EntitySchemaQuery(userConn.EntitySchemaManager, "DocListInFinAppFile");
- esq.AddAllSchemaColumns();
- var signColumn = esq.AddColumn("[DocListInFinAppFile:SibDocListInFinAppFileForSign:Id].Data");
- esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "Id", inIds));
- var entityCollection = esq.GetEntityCollection(userConn);
- foreach (var entity in entityCollection)
- {
- var file = new BG_DocumentIntegration.File();
- file.id = Guid.Parse(entity.PrimaryColumnValue.ToString().ToLower());
- file.name = entity.GetTypedColumnValue<string>("Name");
- file.data = Convert.ToBase64String(entity.GetBytesValue("Data"));
- var sign = entity.GetBytesValue(signColumn.Name);
- if (sign != null) file.sign = Convert.ToBase64String(sign);
- files.Add(file);
- }
- esq = new EntitySchemaQuery(userConn.EntitySchemaManager, "DocumentFile");
- esq.AddAllSchemaColumns();
- signColumn = esq.AddColumn("[DocumentFile:SibDocumentFileForSign:Id].Data");
- esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "Id", inIds));
- entityCollection = esq.GetEntityCollection(userConn);
- foreach (var entity in entityCollection)
- {
- var file = new BG_DocumentIntegration.File();
- file.id = Guid.Parse(entity.PrimaryColumnValue.ToString().ToLower());
- file.name = entity.GetTypedColumnValue<string>("Name");
- file.data = Convert.ToBase64String(entity.GetBytesValue("Data"));
- var sign = entity.GetBytesValue(signColumn.Name);
- if (sign != null) file.sign = Convert.ToBase64String(sign);
- files.Add(file);
- }
- var result = new { files = files };
- return JsonConvert.SerializeObject(result);
- }
- catch (Exception ex)
- {
- SibLogger.Error(ex.Message);
- return "Error:" + ex.ToString();
- }
- }
- /// <summary>
- /// Отправляем уведомление в очередь
- /// </summary>
- /// <param name="docFinApp">Идентификатор текущего документа</param>
- /// <returns></returns>
- private void SendMessageCabinetLK(UserConnection userConn, DocListInFinApp docFinApp)
- {
- try
- {
- //пытаемся получить номер заявки из документа
- Guid finAppId = docFinApp.FinApplicationId;
- if (finAppId.IsEmpty())
- {
- Guid appFormId = docFinApp.AppFormId;
- if (appFormId.IsEmpty())
- return;
- AppForm appForm = new AppForm(userConn) { UseAdminRights = false };
- if (!appForm.FetchFromDB("Id", appFormId, new string[] { "Id", "FinApplication" }, false))
- return;
- finAppId = appForm.FinApplicationId;
- if (finAppId.IsEmpty())
- return;
- }
- SibFinApplicationIntegrationHelper helper = new SibFinApplicationIntegrationHelper(userConn);
- string response = helper.GetFinApplicationJson(finAppId);
- if (response.IndexOf("Error") > -1 && response.IndexOf("Error") < 10)
- throw new Exception("Ошибка при сериализации заявки (Error while serializing request).");
- string err = "";
- SibRabbitMQ rabbitMQ = new SibRabbitMQ(userConn);
- try
- {
- response = JsonConvert.DeserializeObject(response).ToString();
- }
- catch { }
- if (!rabbitMQ.SendMessToRabbitMQ(response, finAppId, ref err))
- throw new Exception("Ошибка при уведомлении личного кабинета:\n" + err);
- }
- catch(Exception e)
- {
- SibLogger.Error(e.Message);
- }
- }
- public void CopyDocumentsToFinApplication(Guid guaranteeIntegrationId, Guid finApplicationId)
- {
- CopyFilesDocListInFinAppToFinApplication(guaranteeIntegrationId, finApplicationId);
- }
- public void CopyFilesDocListInFinAppToFinApplication(Guid guaranteeIntegrationId, Guid finApplicationId)
- {
- List<DocListInFinApp> otherEntitiesToCopy = new List<DocListInFinApp>() { };
- var docListInGIEntities = userConn.GetTypedEntityListByAnyColumn<DocListInFinApp>("SibGuaranteeIntegration", guaranteeIntegrationId);
- var docListInFinAppEntities = userConn.GetTypedEntityListByAnyColumn<DocListInFinApp>("FinApplication", finApplicationId);
- foreach (DocListInFinApp docListInGIEntity in docListInGIEntities)
- {
- DocListInFinApp docListInFinAppEntity = docListInFinAppEntities.Find(x => x.DocumentId == docListInGIEntity.DocumentId);
- if (docListInFinAppEntity != null)
- {
- int files = userConn.GetTypedEntityListByAnyColumn<DocListInFinAppFile>("DocListInFinApp", docListInFinAppEntity.Id).Count;
- if (files==0) {
- var guaranteeIntegration = userConn.GetTypedEntityById<SibGuaranteeIntegration>(guaranteeIntegrationId);
- docListInFinAppEntity.SibSourceINN = guaranteeIntegration.SourceINN;
- docListInFinAppEntity.Save(false);
- CopyFiles(docListInGIEntity.Id, docListInFinAppEntity.Id);
- SetIsArrivedInDocListInFinApp(docListInFinAppEntity.Id);
- }
- }
- else {
- otherEntitiesToCopy.Add(docListInGIEntity);
- }
- }
- foreach (var otherDocListEntity in otherEntitiesToCopy)
- {
- Guid newDocListId = CreateOtherDocListInFinApp(finApplicationId, otherDocListEntity.DocumentId);
- CopyFiles(otherDocListEntity.Id, newDocListId);
- }
- }
- private void SetIsArrivedInDocListInFinApp(Guid toDocListInFinAppId)
- {
- var docListInFinAppEsq = new EntitySchemaQuery(userConn.EntitySchemaManager, "DocListInFinApp");
- docListInFinAppEsq.AddAllSchemaColumns();
- Entity entity = docListInFinAppEsq.GetEntity(userConn, toDocListInFinAppId);
- entity.SetColumnValue("SibIsArrived", true);
- entity.Save(false);
- }
- private void CopyFiles(Guid fromDocListInFinAppId, Guid toDocListInFinAppId)
- {
- var update = new Update(userConn, "DocListInFinAppFile")
- .Set("DocListInFinAppId", Column.Parameter(toDocListInFinAppId))
- .Where("DocListInFinAppId")
- .IsEqual(Column.Parameter(fromDocListInFinAppId));
- update.Execute();
- }
- private Guid CreateOtherDocListInFinApp(Guid finApplicationId, Guid documentRegTypeId)
- {
- Guid regDocumentTypeId_other = Guid.Parse("2B96E940-11BA-475A-B0D2-8939029749B2");
- FinApplication finApp = new FinApplication(userConn) { UseAdminRights = false };
- if (!finApp.FetchFromDB("Id", finApplicationId, new string[] { "Id", "SibClientAppForm" }, false))
- throw new Exception("FinApplication " + finApplicationId + "not found");
- var select = new Select(userConn)
- .Column(Func.Count("Id"))
- .From("DocListInFinApp").WithHints(new NoLockHint())
- .Where("FinApplicationId").IsEqual(Column.Parameter(finApplicationId))
- .And("DocumentId").IsEqual(Column.Parameter(documentRegTypeId)) as Select;
- int countOthers = select.ExecuteScalar<int>();
- DocListInFinApp docListInFinApp = new DocListInFinApp(userConn);
- docListInFinApp.SetDefColumnValues();
- docListInFinApp.DocumentId = documentRegTypeId;
- docListInFinApp.FinApplicationId = finApplicationId;
- docListInFinApp.SibIsSignNeeded = true;
- docListInFinApp.IsRequired = false;
- docListInFinApp.SibIsArrived = true;
- docListInFinApp.SibIsSignCorrect = false;
- docListInFinApp.SibIsActual = true;
- docListInFinApp.SibIsVisibleToCabinet = true;
- docListInFinApp.SibStatusId = sibStatus_UnderConsideration;
- docListInFinApp.SibVersion = countOthers + 1;
- var finap = userConn.GetTypedEntityById<FinApplication>(finApplicationId);
- docListInFinApp.SibSourceINN = finap.SibSourceINN;
- if (finApp.SibClientAppFormId.IsNotEmpty())
- {
- docListInFinApp.AppFormId = finApp.SibClientAppFormId;
- }
- docListInFinApp.Save(false);
- return docListInFinApp.Id;
- }
- public T StartCopyDocListInFinApp<T>(Guid documentIdTo, Guid docFileIdFrom, ref string err, string entitySchemaName = null) where T : Entity
- {
- try
- {
- entitySchemaName = (entitySchemaName.IsNullOrEmpty()) ? typeof(T).Name : entitySchemaName;
- if (string.IsNullOrWhiteSpace(entitySchemaName))
- throw new Exception("Не передано Наименование схемы.");
- T result;
- var docFileFrom = userConn.GetTypedEntityById<T>(docFileIdFrom);
- List<string> excludingFile = new List<string>() { "Sib" + entitySchemaName + "ForSignId", entitySchemaName.Replace("File", string.Empty), "SibIsSign", "SibIsReUseDisabled" };
- EntitySchema objSchema = this.userConn.EntitySchemaManager.FindInstanceByName(entitySchemaName);
- Entity objEntity = objSchema.CreateEntity(this.userConn);
- objEntity.UseAdminRights = false;
- objEntity.SetDefColumnValues();
- SibStaticCommonHelper.CopyAllColumnsTo(docFileFrom, objEntity, excludingFile);
- objEntity.SetColumnValue("SibIsReUseDisabled", true);
- objEntity.SetColumnValue(excludingFile[1] + "Id", documentIdTo);
- if (docFileFrom.GetTypedColumnValue<bool>("SibIsSign"))
- {
- var fileForSignId = docFileFrom.GetTypedColumnValue<Guid>(excludingFile.First());
- var fileForSign = userConn.GetTypedEntityById<T>(fileForSignId);
- var hashFileForSign = fileForSign.GetTypedColumnValue<string>("SibHash");
- var fileExists = userConn.GetTypedEntityListByAnyColumns<T>(
- new Dictionary<string, object>
- {
- { excludingFile[1], documentIdTo },
- { "SibHash", hashFileForSign}
- })?.FirstOrDefault();
- if (fileExists != null)
- {
- objEntity.SetColumnValue("SibIsSign", true);
- objEntity.SetColumnValue(excludingFile.First(), fileExists.GetTypedColumnValue<Guid>("Id"));
- }
- else
- {
- var docFileForSign = StartCopyDocListInFinApp<T>(documentIdTo, docFileFrom.GetTypedColumnValue<Guid>(excludingFile.First()), ref err);
- if (docFileForSign != null)
- {
- objEntity.SetColumnValue("SibIsSign", true);
- objEntity.SetColumnValue(excludingFile.First(), docFileForSign.GetTypedColumnValue<Guid>("Id"));
- docFileForSign.SetColumnValue("SibIsReUseDisabled", false);
- docFileForSign.Save(false);
- }
- }
- }
- objEntity.Save(false);
- return (T)objEntity;
- }
- catch (Exception e)
- {
- err = e.ToString();
- SibLogger.Error(err);
- return null;
- }
- }
- }
- namespace BG_DocumentIntegration
- {
- public class Finapp
- {
- public string id { get; set; }
- public string registrynumber { get; set; }
- public string clientinn { get; set; }
- public string sourceinn { get; set; }
- }
- public class Appform
- {
- public string id { get; set; }
- public string inn { get; set; }
- }
- public class Document
- {
- public Guid id { get; set; }
- public bool updateSign { get; set; }
- public bool isnew { get; set; }
- public string type { get; set; }
- public string code { get; set; }
- public bool isClientDocument { get; set; }
- public Guid guaranteeIntegrationId { get; set; }
- }
- public class File
- {
- public Guid id { get; set; }
- public string name { get; set; }
- public string data { get; set; }
- public string sign { get; set; }
- }
- public class IncomeRequest
- {
- public Finapp finapp { get; set; }
- public Appform appform { get; set; }
- public Document document { get; set; }
- public List<File> files { get; set; }
- }
- public class OutcomeRequest
- {
- public List<File> files { get; set; }
- }
- //public class ResponseFile
- //{
- // public Guid Id_Old { get; set; }
- // public Guid Id_New { get; set; }
- //}
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement