Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.77 KB | None | 0 0
  1. namespace Terrasoft.Configuration
  2.  
  3. {
  4. using System;
  5. using System.Collections.ObjectModel;
  6. using System.ComponentModel;
  7. using System.Collections.Specialized;
  8. using System.Collections;
  9. using System.Collections.Generic;
  10. using System.Runtime.CompilerServices;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Converters;
  13. using Terrasoft.Configuration;
  14. using Terrasoft.Common;
  15. using Terrasoft.Core;
  16. using Terrasoft.Core.DB;
  17. using Terrasoft.Core.Entities;
  18. using System.Linq;
  19. using Terrasoft.Configuration.BG_DocumentIntegration;
  20. using System.Threading.Tasks;
  21.  
  22. public class SibDocumentIntegrationHelper
  23. {
  24. private UserConnection userConn;
  25.  
  26. public readonly Guid sibStatus_UnderConsideration = SibConstantsCS.DocListInFinAppStatus.UnderConsideration;
  27. public readonly Guid fileType_file = SibConstantsCS.FileType.File;
  28.  
  29. public Guid DocId = Guid.Empty;
  30. public Guid DocumentId = Guid.Empty;
  31.  
  32. public bool IsDocument;
  33. //private DocListInFinApp docFinApp;
  34.  
  35. public SibDocumentIntegrationHelper(UserConnection uc)
  36. {
  37. userConn = uc;
  38. }
  39.  
  40.  
  41. private IncomeRequest ParseIncomeRequest(string request)
  42. {
  43. IncomeRequest incomeRequest = JsonConvert.DeserializeObject<IncomeRequest>(request);
  44. return incomeRequest;
  45. }
  46.  
  47. private OutcomeRequest ParseOutcomeRequest(string jsonData)
  48. {
  49. OutcomeRequest deserializedProduct = JsonConvert.DeserializeObject<OutcomeRequest>(jsonData);
  50. return deserializedProduct;
  51. }
  52.  
  53.  
  54.  
  55. public bool CreatedFileFromRequest(string request, ref string err)
  56. {
  57. try
  58. {
  59. var data = ParseIncomeRequest(request);
  60. if (data.document == null)
  61. throw new Exception("В запросе отсутствует объект document");
  62.  
  63. Guid docId = data.document.id;
  64.  
  65. Guid guaranteeIntegrationId = data.document.guaranteeIntegrationId;
  66.  
  67. bool updateSign = data.document.updateSign;
  68. bool isClientDocument = data.document.isClientDocument;
  69.  
  70. if (updateSign == true)
  71. {
  72. this.UpdateSign(data.files);
  73. }
  74. else if (guaranteeIntegrationId.IsEmpty())//если привязка к заявке
  75. {
  76.  
  77. if (docId.IsEmpty())
  78. throw new Exception("В запросе не передан идентификатор документа");
  79.  
  80. DocListInFinApp doc = new DocListInFinApp(this.userConn) { UseAdminRights = false };
  81. Document doc2 = new Document(this.userConn) { UseAdminRights = false };
  82. if (doc.FetchFromDB(docId)) {
  83. docId = DocId = this.GetDocListInFinApp(docId);
  84. this.CreateFiles(data.files, docId);
  85. }
  86. else if (doc2.FetchFromDB(docId)) {
  87. docId = DocumentId = this.GetDocInFinApp(docId);
  88. this.CreateFilesForDocument(data.files, docId);
  89. }
  90. else {
  91. throw new Exception("По указанному id не найден ни один из возможных документов");
  92. }
  93.  
  94.  
  95. }
  96. else if (guaranteeIntegrationId.IsNotEmpty())//если привязка к интеграционной заявке
  97. {
  98.  
  99. if (isClientDocument) {
  100. if (docId.IsEmpty())
  101. {
  102. docId = DocId = this.CreateDocListInFinAppInGuaranteeIntegration(guaranteeIntegrationId, data.document.code);
  103. } else
  104. {
  105. docId = DocId = this.GetDocListInFinAppInGuaranteeIntegration(guaranteeIntegrationId, docId);
  106. }
  107. this.CreateFiles(data.files, docId);
  108. } else {
  109. Guid documentId;
  110. if (docId.IsEmpty())
  111. {
  112. documentId = this.CreateDocumentInGuaranteeIntegration(guaranteeIntegrationId, data.document.code);
  113. }
  114. else
  115. {
  116. documentId = this.GetDocumentInGuaranteeIntegration(guaranteeIntegrationId, docId);
  117. }
  118. this.CreateFilesForDocument(data.files, documentId);
  119. DocumentId = documentId;
  120. }
  121.  
  122.  
  123.  
  124.  
  125. }
  126.  
  127.  
  128.  
  129. //отправляем уведомление в ЛК
  130. //if (docFinApp != null)
  131. //{
  132. // Task.Factory.StartNew(() =>
  133. // {
  134. // this.SendMessageCabinetLK(this.userConn, docFinApp);
  135. // });
  136. //}
  137.  
  138. return true;
  139. }
  140. catch (Exception ex)
  141. {
  142. err = ex.ToString();
  143. SibLogger.Error(err);
  144. return false;
  145. }
  146. }
  147.  
  148. /// <summary>
  149. /// Создание пакета документов с привязкой к интеграционной заявке
  150. /// </summary>
  151. /// <param name="guaranteeIntegrationId">Интеграционная заявка</param>
  152. /// <param name="code">Код документа</param>
  153. /// <returns>Id созданного пакета документов</returns>
  154. private Guid CreateDocListInFinAppInGuaranteeIntegration(Guid guaranteeIntegrationId, string code)
  155. {
  156. RegDocumentType regDocType = new RegDocumentType(this.userConn) { UseAdminRights = false };
  157. if (!regDocType.FetchFromDB("SibCode", code, new string[] { "Id" }, false))
  158. throw new Exception("Код типа регистрационного документа не найден");
  159.  
  160.  
  161. DocListInFinApp docNew = new DocListInFinApp(this.userConn) { UseAdminRights = false };
  162. docNew.SetDefColumnValues();
  163. docNew.SibGuaranteeIntegrationId = guaranteeIntegrationId;
  164.  
  165.  
  166. docNew.DocumentId = regDocType.Id;
  167. docNew.SibIsActual = true;
  168. docNew.SibIsSignNeeded = true;
  169. docNew.SibIsArrived = true;
  170. docNew.IsRequired = true;
  171.  
  172. docNew.Save(false);
  173.  
  174.  
  175. return docNew.Id;
  176. }
  177.  
  178. /// <summary>
  179. /// Получение пакета документов в инетграционной заявке
  180. /// </summary>
  181. /// <param name="guaranteeIntegrationId">Интеграционная заявка</param>
  182. /// <param name="docListInFinAppId">Id пакета документов</param>
  183. /// <returns>Id найденного пакета документов</returns>
  184. private Guid GetDocListInFinAppInGuaranteeIntegration(Guid guaranteeIntegrationId, Guid docListInFinAppId)
  185. {
  186. DocListInFinApp doc = new DocListInFinApp(this.userConn) { UseAdminRights = false };
  187. if (doc.FetchFromDB(new Dictionary<string, object> {
  188. {"Id", docListInFinAppId},
  189. {"SibGuaranteeIntegration", guaranteeIntegrationId}
  190. })) {
  191. return doc.Id;
  192. } else
  193. {
  194. throw new Exception("Пакет документов " + docListInFinAppId + " не найден");
  195. }
  196. }
  197.  
  198.  
  199. /// <summary>
  200. /// Создание документа с привязкой к интеграционной заявке
  201. /// </summary>
  202. /// <param name="guaranteeIntegrationId">Интеграционная заявка</param>
  203. /// <param name="code">Код документа</param>
  204. /// <returns>Id созданного документа</returns>
  205. private Guid CreateDocumentInGuaranteeIntegration(Guid guaranteeIntegrationId, string code)
  206. {
  207. DocumentType docType = new DocumentType(this.userConn) { UseAdminRights = false };
  208. if (!docType.FetchFromDB("Code", code, new string[] { "Id" }, false))
  209. throw new Exception("Код типа документа не найден");
  210.  
  211.  
  212. Document docNew = new Document(this.userConn) { UseAdminRights = false };
  213. docNew.SetDefColumnValues();
  214. docNew.SibGuaranteeIntegrationId = guaranteeIntegrationId;
  215.  
  216.  
  217. docNew.TypeId = docType.Id;
  218. docNew.SibIsActual = true;
  219. docNew.SibIsSignNeeded = true;
  220. docNew.SibIsArrived = true;
  221.  
  222. docNew.Save(false);
  223.  
  224.  
  225. return docNew.Id;
  226. }
  227.  
  228. /// <summary>
  229. /// Получение документа в инетграционной заявке
  230. /// </summary>
  231. /// <param name="guaranteeIntegrationId">Интеграционная заявка</param>
  232. /// <param name="documentId">Id документа</param>
  233. /// <returns>Id найденного пакета документов</returns>
  234. private Guid GetDocumentInGuaranteeIntegration(Guid guaranteeIntegrationId, Guid documentId)
  235. {
  236. Document doc = new Document(this.userConn) { UseAdminRights = false };
  237. if (doc.FetchFromDB(new Dictionary<string, object> {
  238. {"Id", documentId},
  239. {"SibGuaranteeIntegration", guaranteeIntegrationId}
  240. }))
  241. {
  242. return doc.Id;
  243. }
  244. else
  245. {
  246. throw new Exception("Документ " + documentId + " не найден");
  247. }
  248. }
  249.  
  250.  
  251. /// <summary>
  252. /// Получение документа для загрузки файлов
  253. /// </summary>
  254. /// <param name="curDocId">Идентификатор текущего документа</param>
  255. /// <returns>Идентификатор документа</returns>
  256. private Guid GetDocListInFinApp(Guid curDocId)
  257. {
  258. DocListInFinAppFile existFiles = this.userConn.GetTypedEntityListByAnyColumn<DocListInFinAppFile>("DocListInFinApp", curDocId).FirstOrDefault();
  259.  
  260. DocListInFinApp doc = new DocListInFinApp(this.userConn) { UseAdminRights = false };
  261. if (!doc.FetchFromDB(curDocId))
  262. throw new Exception("Ошибка! Не найден документ с идентификатором " + curDocId);
  263.  
  264. if (doc.SibMainDocId.IsEmpty())
  265. throw new Exception("Ошибка! В документе с идентификатором " + curDocId + " отсутствует ссылка на основной документ.");
  266.  
  267.  
  268. //Проверяем соответствует ли код типа документа кодам 113, 114, 115
  269. //var typesDocList = new List<Guid>();
  270. //typesDocList.Add(Guid.Parse("54F40E24-6E91-4A0F-995D-E51A95A15B00")); //113
  271. //typesDocList.Add(Guid.Parse("B60480FF-6D9F-4F55-A224-9AB236A7CD0C")); //114
  272. //typesDocList.Add(Guid.Parse("4ED4BB41-9BCA-40DB-A8F2-FB2931AC6F45")); //115
  273.  
  274. //Если соответствует одному из них, то сбрасываем признак Обязательный у остальных
  275. //Guid findType = typesDocList.Find(x => x == doc.DocumentId);
  276. //if (findType.IsNotEmpty())
  277. //{
  278. // typesDocList.Remove(findType);
  279. // this.DelRequiredFromDocs(doc, typesDocList);
  280. // docFinApp = doc;
  281. //}
  282.  
  283. if (existFiles == null)
  284. {
  285. doc.SibIsArrived = true;
  286. doc.Save(false);
  287. return curDocId;
  288. }
  289.  
  290. //находим текущую версию документа
  291. int maxVersion = 0;
  292. Select s = (Select)new Select(this.userConn)
  293. .Max("SibVersion").As("MaxVersion")
  294. .From("DocListInFinApp")
  295. .Where("SibMainDocId").IsEqual(Column.Parameter(doc.SibMainDocId));
  296.  
  297. using (var dbExecutor = userConn.EnsureDBConnection())
  298. using (var reader = s.ExecuteReader(dbExecutor))
  299. if (reader.Read())
  300. maxVersion = reader.GetColumnValue<int>("MaxVersion");
  301.  
  302. DocListInFinApp docNew = new DocListInFinApp(this.userConn) { UseAdminRights = false };
  303. docNew.SetDefColumnValues();
  304. docNew.Name = doc.Name;
  305. if (doc.FinApplicationId.IsNotEmpty())
  306. docNew.FinApplicationId = doc.FinApplicationId;
  307. if (doc.AgentContractId.IsNotEmpty())
  308. docNew.AgentContractId = doc.AgentContractId;
  309. if (doc.AppFormId.IsNotEmpty())
  310. docNew.AppFormId = doc.AppFormId;
  311. docNew.DocumentId = doc.DocumentId;
  312.  
  313. var finap = userConn.GetTypedEntityById<FinApplication>(doc.FinApplicationId);
  314. docNew.SibSourceINN = finap.SibSourceINN;
  315.  
  316. if (docNew.DocumentId == SibConstantsCS.RegDocumentType.StatementAppFormdocument &&
  317. finap.SourceId == SibConstantsCS.FinAppSource.TenderHub &&
  318. doc.SibStatusId == SibConstantsCS.DocListInFinAppStatus.Approved) {
  319. docNew.SibIsActual = false;
  320. docNew.Notes= "Дубль документа";
  321. }
  322. else {
  323. docNew.SibIsActual = true;
  324. doc.SibIsActual = false;
  325. doc.Save(false);
  326. }
  327.  
  328. docNew.SibVersion = ++maxVersion;
  329. docNew.SibStatusId = sibStatus_UnderConsideration;
  330. docNew.SibIsSignNeeded = doc.SibIsSignNeeded;
  331. docNew.SibIsArrived = true;
  332. docNew.IsRequired = doc.IsRequired;
  333. docNew.SibMainDocId = doc.SibMainDocId;
  334. docNew.Save(false);
  335.  
  336. return docNew.Id;
  337. }
  338.  
  339. /// <summary>
  340. /// Получение документа для загрузки файлов
  341. /// </summary>
  342. /// <param name="curDocId">Идентификатор текущего документа</param>
  343. /// <returns>Идентификатор документа</returns>
  344. private Guid GetDocInFinApp(Guid curDocId)
  345. {
  346. DocumentFile existFiles = this.userConn.GetTypedEntityListByAnyColumn<DocumentFile>("Document", curDocId).FirstOrDefault();
  347.  
  348. Document doc = new Document(this.userConn) { UseAdminRights = false };
  349. if (!doc.FetchFromDB(curDocId))
  350. throw new Exception("Ошибка! Не найден документ с идентификатором " + curDocId);
  351.  
  352. if (doc.SibMainDocId.IsEmpty())
  353. throw new Exception("Ошибка! В документе с идентификатором " + curDocId + " отсутствует ссылка на основной документ.");
  354.  
  355. if (existFiles == null)
  356. {
  357. doc.SibIsArrived = true;
  358. doc.Save(false);
  359. return curDocId;
  360. }
  361.  
  362. //находим текущую версию документа
  363. int maxVersion = 0;
  364. Select s = (Select)new Select(this.userConn)
  365. .Max("SibVersion").As("MaxVersion")
  366. .From("Document")
  367. .Where("SibMainDocId").IsEqual(Column.Parameter(doc.SibMainDocId));
  368.  
  369. using (var dbExecutor = userConn.EnsureDBConnection())
  370. using (var reader = s.ExecuteReader(dbExecutor))
  371. if (reader.Read())
  372. maxVersion = reader.GetColumnValue<int>("MaxVersion");
  373.  
  374. Document docNew = new Document(this.userConn) { UseAdminRights = false };
  375. docNew.SetDefColumnValues();
  376. //docNew.Number = doc.Number;
  377. if (doc.FinApplicationId.IsNotEmpty())
  378. docNew.FinApplicationId = doc.FinApplicationId;
  379. if (doc.AgentContractId.IsNotEmpty())
  380. docNew.AgentContractId = doc.AgentContractId;
  381. docNew.TypeId = doc.TypeId;
  382. docNew.SibIsActual = true;
  383. docNew.SibVersion = ++maxVersion;
  384. docNew.SibStatusId = sibStatus_UnderConsideration;
  385. docNew.SibIsSignNeeded = doc.SibIsSignNeeded;
  386. docNew.SibIsArrived = true;
  387. docNew.SibIsRequired = doc.SibIsRequired;
  388.  
  389. var finap = userConn.GetTypedEntityById<FinApplication>(doc.FinApplicationId);
  390. docNew.SibSourceINN = finap.SibSourceINN;
  391.  
  392. docNew.SibMainDocId = doc.SibMainDocId;
  393. docNew.Save(false);
  394.  
  395. doc.SibIsActual = false;
  396. doc.Save(false);
  397.  
  398. return docNew.Id;
  399. }
  400.  
  401. /// <summary>
  402. /// Проверка ЭЦП файлов и загрузка в зависимости от того, файл документ или файл пакета документа
  403. /// </summary>
  404. /// <param name="files">Массив файлов, в которые загружаеются ЭЦП</param>
  405. /// <returns></returns>
  406. private void UpdateSign(List<BG_DocumentIntegration.File> files)
  407. {
  408. foreach (var file in files)
  409. {
  410. if (file.id.IsEmpty())
  411. throw new Exception("Ошибка! В объекте file отсутствует поле Id.");
  412. if (file.sign == null)
  413. throw new Exception("Ошибка! Отсутствует поле sign.");
  414.  
  415. DocumentFile documentFile = new DocumentFile(this.userConn) { UseAdminRights = false };
  416. DocListInFinAppFile docFile = new DocListInFinAppFile(this.userConn) { UseAdminRights = false };
  417. if (docFile.FetchFromDB("Id", file.id, new string[] { "Id", "DocListInFinApp" }, false))
  418. {
  419. CreateDocListInFinAppFile(file, docFile.DocListInFinAppId);
  420. } else if (documentFile.FetchFromDB("Id", file.id, new string[] { "Id", "Document" }, false))
  421. {
  422. CreateDocumentFile(file, documentFile.DocumentId);
  423. } else
  424. {
  425. throw new Exception("Ошибка! Не найден файл с идентификатором " + file.id);
  426. }
  427.  
  428.  
  429.  
  430.  
  431.  
  432.  
  433. }
  434. }
  435.  
  436. /// <summary>
  437. /// Загрузка ЭЦП файла к пакету документа
  438. /// </summary>
  439. /// <param name="files">Массив файлов, в которые загружаеются ЭЦП</param>
  440. /// <param name="docListInFinAppId">Id пакета документов</param>
  441. /// <returns></returns>
  442. private void CreateDocListInFinAppFile(BG_DocumentIntegration.File file, Guid docListInFinAppId)
  443. {
  444. DocListInFinAppFile docSign = new DocListInFinAppFile(userConn) { UseAdminRights = false };
  445.  
  446. if (docSign.FetchFromDB("SibDocListInFinAppFileForSign", file.id))
  447. {
  448. byte[] bytes2 = Convert.FromBase64String(file.sign);
  449. docSign.SetBytesValue("Data", bytes2);
  450. }
  451. else
  452. {
  453. docSign.SetDefColumnValues();
  454. docSign.TypeId = fileType_file;
  455. docSign.DocListInFinAppId = docListInFinAppId;
  456. docSign.SibIsSign = true;
  457. docSign.SibDocListInFinAppFileForSignId = file.id;
  458. docSign.Name = $"Подпись {file.name}.sig";
  459. byte[] bytes2 = Convert.FromBase64String(file.sign);
  460. docSign.SetBytesValue("Data", bytes2);
  461. }
  462.  
  463. docSign.Save(false);
  464. }
  465.  
  466. /// <summary>
  467. /// Загрузка ЭЦП файла к пакету документа
  468. /// </summary>
  469. /// <param name="files">Массив файлов, в которые загружаеются ЭЦП</param>
  470. /// <param name="docListInFinAppId">Id документа</param>
  471. /// <returns></returns>
  472. private void CreateDocumentFile(BG_DocumentIntegration.File file, Guid documentId)
  473. {
  474. DocumentFile docSign = new DocumentFile(userConn) { UseAdminRights = false };
  475.  
  476. if (docSign.FetchFromDB("SibDocumentFileForSign", file.id))
  477. {
  478. byte[] bytes2 = Convert.FromBase64String(file.sign);
  479. docSign.SetBytesValue("Data", bytes2);
  480. }
  481. else
  482. {
  483. docSign.SetDefColumnValues();
  484. docSign.TypeId = fileType_file;
  485. docSign.DocumentId = documentId;
  486. docSign.SibIsSign = true;
  487. docSign.SibDocumentFileForSignId = file.id;
  488. docSign.Name = $"Подпись {file.name}.sig";
  489. byte[] bytes2 = Convert.FromBase64String(file.sign);
  490. docSign.SetBytesValue("Data", bytes2);
  491. }
  492.  
  493. docSign.Save(false);
  494. }
  495.  
  496.  
  497. /// <summary>
  498. /// Создание файлов для пакета дкоументов
  499. /// </summary>
  500. /// <param name="files">Массив файлов</param>
  501. /// <param name="docId">Идентификатор пакета документов для загрузки файлов</param>
  502. /// <returns></returns>
  503. private void CreateFiles(List<BG_DocumentIntegration.File> files, Guid docId)
  504. {
  505. foreach (var file in files)
  506. {
  507. DocListInFinAppFile docFile = new DocListInFinAppFile(this.userConn) { UseAdminRights = false };
  508. docFile.SetDefColumnValues();
  509. docFile.TypeId = fileType_file;
  510. docFile.DocListInFinAppId = docId;
  511. docFile.Name = file.name;
  512. byte[] bytes = Convert.FromBase64String(file.data);
  513. docFile.SetBytesValue("Data", bytes);
  514. docFile.Save(false);
  515.  
  516. if (file.sign != null)
  517. {
  518. DocListInFinAppFile docSign = new DocListInFinAppFile(this.userConn) { UseAdminRights = false };
  519. docSign.SetDefColumnValues();
  520. docSign.TypeId = fileType_file;
  521. docSign.DocListInFinAppId = docId;
  522. docSign.SibIsSign = true;
  523. docSign.SibDocListInFinAppFileForSignId = docFile.Id;
  524. docSign.Name = $"Подпись {file.name}.sig";
  525. byte[] bytes2 = Convert.FromBase64String(file.sign);
  526. docSign.SetBytesValue("Data", bytes2);
  527. docSign.Save(false);
  528. }
  529. }
  530. }
  531.  
  532. /// <summary>
  533. /// Создание файлов для документа
  534. /// </summary>
  535. /// <param name="files">Массив файлов</param>
  536. /// <param name="documentId">Идентификатор документа </param>
  537. /// <returns></returns>
  538. private void CreateFilesForDocument(List<BG_DocumentIntegration.File> files, Guid documentId)
  539. {
  540. foreach (var file in files)
  541. {
  542. DocumentFile docFile = new DocumentFile(this.userConn) { UseAdminRights = false };
  543. docFile.SetDefColumnValues();
  544. docFile.TypeId = fileType_file;
  545. docFile.DocumentId = documentId;
  546. docFile.Name = file.name;
  547. byte[] bytes = Convert.FromBase64String(file.data);
  548. docFile.SetBytesValue("Data", bytes);
  549. docFile.Save(false);
  550.  
  551. if (file.sign != null)
  552. {
  553. DocumentFile docSign = new DocumentFile(this.userConn) { UseAdminRights = false };
  554. docSign.SetDefColumnValues();
  555. docSign.TypeId = fileType_file;
  556. docSign.DocumentId = documentId;
  557. docSign.SibIsSign = true;
  558. docSign.SibDocumentFileForSignId = docFile.Id;
  559. docSign.Name = $"Подпись {file.name}.sig";
  560. byte[] bytes2 = Convert.FromBase64String(file.sign);
  561. docSign.SetBytesValue("Data", bytes2);
  562. docSign.Save(false);
  563. }
  564. }
  565. }
  566.  
  567.  
  568. /// <summary>
  569. /// Сбрасываем признак Обязательный у документов заданного типа
  570. /// </summary>
  571. /// <param name="doc">Текущий документ</param>
  572. /// <param name="typesDocList">Список типов документов для поиска</param>
  573. /// <returns></returns>
  574. private void DelRequiredFromDocs(DocListInFinApp doc, List<Guid> typesDocList)
  575. {
  576. if (doc.AppFormId.IsEmpty())
  577. return;
  578.  
  579. foreach (Guid typeDocId in typesDocList)
  580. {
  581. DocListInFinApp finfDoc = userConn.GetTypedEntityListByAnyColumn<DocListInFinApp>("AppForm", doc.AppFormId)
  582. .FirstOrDefault(x => (x.SibIsActual == true && x.DocumentId.Equals(typeDocId)));
  583.  
  584. if (finfDoc != null)
  585. {
  586. finfDoc.IsRequired = false;
  587. finfDoc.Save(false);
  588. }
  589. }
  590. }
  591.  
  592.  
  593. /// <summary>
  594. /// Получение массива файлов
  595. /// </summary>
  596. /// <param name="request">Текущий документ</param>
  597. /// <returns>Результат выполнения</returns>
  598. public string GetFileWithSign(string request)
  599. {
  600. try
  601. {
  602. var data = ParseOutcomeRequest(request);
  603. List<BG_DocumentIntegration.File> files = new List<BG_DocumentIntegration.File>();
  604. var ids = new List<string>();
  605. foreach (var file in data.files)
  606. {
  607. ids.Add(file.id.ToString());
  608. }
  609. var inIds = ids.ToArray();
  610.  
  611. var esq = new EntitySchemaQuery(userConn.EntitySchemaManager, "DocListInFinAppFile");
  612. esq.AddAllSchemaColumns();
  613. var signColumn = esq.AddColumn("[DocListInFinAppFile:SibDocListInFinAppFileForSign:Id].Data");
  614. esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "Id", inIds));
  615. var entityCollection = esq.GetEntityCollection(userConn);
  616. foreach (var entity in entityCollection)
  617. {
  618. var file = new BG_DocumentIntegration.File();
  619. file.id = Guid.Parse(entity.PrimaryColumnValue.ToString().ToLower());
  620. file.name = entity.GetTypedColumnValue<string>("Name");
  621. file.data = Convert.ToBase64String(entity.GetBytesValue("Data"));
  622. var sign = entity.GetBytesValue(signColumn.Name);
  623. if (sign != null) file.sign = Convert.ToBase64String(sign);
  624. files.Add(file);
  625. }
  626.  
  627. esq = new EntitySchemaQuery(userConn.EntitySchemaManager, "DocumentFile");
  628. esq.AddAllSchemaColumns();
  629. signColumn = esq.AddColumn("[DocumentFile:SibDocumentFileForSign:Id].Data");
  630. esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "Id", inIds));
  631. entityCollection = esq.GetEntityCollection(userConn);
  632. foreach (var entity in entityCollection)
  633. {
  634. var file = new BG_DocumentIntegration.File();
  635. file.id = Guid.Parse(entity.PrimaryColumnValue.ToString().ToLower());
  636. file.name = entity.GetTypedColumnValue<string>("Name");
  637. file.data = Convert.ToBase64String(entity.GetBytesValue("Data"));
  638. var sign = entity.GetBytesValue(signColumn.Name);
  639. if (sign != null) file.sign = Convert.ToBase64String(sign);
  640. files.Add(file);
  641. }
  642.  
  643. var result = new { files = files };
  644. return JsonConvert.SerializeObject(result);
  645. }
  646. catch (Exception ex)
  647. {
  648. SibLogger.Error(ex.Message);
  649. return "Error:" + ex.ToString();
  650. }
  651. }
  652.  
  653.  
  654. /// <summary>
  655. /// Отправляем уведомление в очередь
  656. /// </summary>
  657. /// <param name="docFinApp">Идентификатор текущего документа</param>
  658. /// <returns></returns>
  659. private void SendMessageCabinetLK(UserConnection userConn, DocListInFinApp docFinApp)
  660. {
  661. try
  662. {
  663. //пытаемся получить номер заявки из документа
  664. Guid finAppId = docFinApp.FinApplicationId;
  665. if (finAppId.IsEmpty())
  666. {
  667. Guid appFormId = docFinApp.AppFormId;
  668. if (appFormId.IsEmpty())
  669. return;
  670.  
  671. AppForm appForm = new AppForm(userConn) { UseAdminRights = false };
  672. if (!appForm.FetchFromDB("Id", appFormId, new string[] { "Id", "FinApplication" }, false))
  673. return;
  674.  
  675. finAppId = appForm.FinApplicationId;
  676. if (finAppId.IsEmpty())
  677. return;
  678. }
  679.  
  680. SibFinApplicationIntegrationHelper helper = new SibFinApplicationIntegrationHelper(userConn);
  681. string response = helper.GetFinApplicationJson(finAppId);
  682. if (response.IndexOf("Error") > -1 && response.IndexOf("Error") < 10)
  683. throw new Exception("Ошибка при сериализации заявки (Error while serializing request).");
  684.  
  685. string err = "";
  686. SibRabbitMQ rabbitMQ = new SibRabbitMQ(userConn);
  687.  
  688. try
  689. {
  690. response = JsonConvert.DeserializeObject(response).ToString();
  691. }
  692. catch { }
  693.  
  694. if (!rabbitMQ.SendMessToRabbitMQ(response, finAppId, ref err))
  695. throw new Exception("Ошибка при уведомлении личного кабинета:\n" + err);
  696. }
  697. catch(Exception e)
  698. {
  699. SibLogger.Error(e.Message);
  700. }
  701. }
  702.  
  703. public void CopyDocumentsToFinApplication(Guid guaranteeIntegrationId, Guid finApplicationId)
  704. {
  705. CopyFilesDocListInFinAppToFinApplication(guaranteeIntegrationId, finApplicationId);
  706. }
  707.  
  708. public void CopyFilesDocListInFinAppToFinApplication(Guid guaranteeIntegrationId, Guid finApplicationId)
  709. {
  710. List<DocListInFinApp> otherEntitiesToCopy = new List<DocListInFinApp>() { };
  711.  
  712. var docListInGIEntities = userConn.GetTypedEntityListByAnyColumn<DocListInFinApp>("SibGuaranteeIntegration", guaranteeIntegrationId);
  713. var docListInFinAppEntities = userConn.GetTypedEntityListByAnyColumn<DocListInFinApp>("FinApplication", finApplicationId);
  714.  
  715. foreach (DocListInFinApp docListInGIEntity in docListInGIEntities)
  716. {
  717. DocListInFinApp docListInFinAppEntity = docListInFinAppEntities.Find(x => x.DocumentId == docListInGIEntity.DocumentId);
  718. if (docListInFinAppEntity != null)
  719. {
  720. int files = userConn.GetTypedEntityListByAnyColumn<DocListInFinAppFile>("DocListInFinApp", docListInFinAppEntity.Id).Count;
  721. if (files==0) {
  722. var guaranteeIntegration = userConn.GetTypedEntityById<SibGuaranteeIntegration>(guaranteeIntegrationId);
  723. docListInFinAppEntity.SibSourceINN = guaranteeIntegration.SourceINN;
  724. docListInFinAppEntity.Save(false);
  725.  
  726. CopyFiles(docListInGIEntity.Id, docListInFinAppEntity.Id);
  727. SetIsArrivedInDocListInFinApp(docListInFinAppEntity.Id);
  728. }
  729. }
  730. else {
  731. otherEntitiesToCopy.Add(docListInGIEntity);
  732. }
  733. }
  734.  
  735. foreach (var otherDocListEntity in otherEntitiesToCopy)
  736. {
  737. Guid newDocListId = CreateOtherDocListInFinApp(finApplicationId, otherDocListEntity.DocumentId);
  738. CopyFiles(otherDocListEntity.Id, newDocListId);
  739. }
  740. }
  741.  
  742. private void SetIsArrivedInDocListInFinApp(Guid toDocListInFinAppId)
  743. {
  744. var docListInFinAppEsq = new EntitySchemaQuery(userConn.EntitySchemaManager, "DocListInFinApp");
  745. docListInFinAppEsq.AddAllSchemaColumns();
  746. Entity entity = docListInFinAppEsq.GetEntity(userConn, toDocListInFinAppId);
  747. entity.SetColumnValue("SibIsArrived", true);
  748. entity.Save(false);
  749. }
  750.  
  751. private void CopyFiles(Guid fromDocListInFinAppId, Guid toDocListInFinAppId)
  752. {
  753. var update = new Update(userConn, "DocListInFinAppFile")
  754. .Set("DocListInFinAppId", Column.Parameter(toDocListInFinAppId))
  755. .Where("DocListInFinAppId")
  756. .IsEqual(Column.Parameter(fromDocListInFinAppId));
  757. update.Execute();
  758. }
  759.  
  760. private Guid CreateOtherDocListInFinApp(Guid finApplicationId, Guid documentRegTypeId)
  761. {
  762. Guid regDocumentTypeId_other = Guid.Parse("2B96E940-11BA-475A-B0D2-8939029749B2");
  763.  
  764. FinApplication finApp = new FinApplication(userConn) { UseAdminRights = false };
  765. if (!finApp.FetchFromDB("Id", finApplicationId, new string[] { "Id", "SibClientAppForm" }, false))
  766. throw new Exception("FinApplication " + finApplicationId + "not found");
  767.  
  768. var select = new Select(userConn)
  769. .Column(Func.Count("Id"))
  770. .From("DocListInFinApp").WithHints(new NoLockHint())
  771. .Where("FinApplicationId").IsEqual(Column.Parameter(finApplicationId))
  772. .And("DocumentId").IsEqual(Column.Parameter(documentRegTypeId)) as Select;
  773. int countOthers = select.ExecuteScalar<int>();
  774.  
  775.  
  776. DocListInFinApp docListInFinApp = new DocListInFinApp(userConn);
  777. docListInFinApp.SetDefColumnValues();
  778. docListInFinApp.DocumentId = documentRegTypeId;
  779. docListInFinApp.FinApplicationId = finApplicationId;
  780. docListInFinApp.SibIsSignNeeded = true;
  781. docListInFinApp.IsRequired = false;
  782. docListInFinApp.SibIsArrived = true;
  783. docListInFinApp.SibIsSignCorrect = false;
  784. docListInFinApp.SibIsActual = true;
  785. docListInFinApp.SibIsVisibleToCabinet = true;
  786. docListInFinApp.SibStatusId = sibStatus_UnderConsideration;
  787. docListInFinApp.SibVersion = countOthers + 1;
  788.  
  789. var finap = userConn.GetTypedEntityById<FinApplication>(finApplicationId);
  790. docListInFinApp.SibSourceINN = finap.SibSourceINN;
  791.  
  792. if (finApp.SibClientAppFormId.IsNotEmpty())
  793. {
  794. docListInFinApp.AppFormId = finApp.SibClientAppFormId;
  795. }
  796.  
  797. docListInFinApp.Save(false);
  798.  
  799. return docListInFinApp.Id;
  800. }
  801.  
  802. public T StartCopyDocListInFinApp<T>(Guid documentIdTo, Guid docFileIdFrom, ref string err, string entitySchemaName = null) where T : Entity
  803. {
  804. try
  805. {
  806. entitySchemaName = (entitySchemaName.IsNullOrEmpty()) ? typeof(T).Name : entitySchemaName;
  807.  
  808. if (string.IsNullOrWhiteSpace(entitySchemaName))
  809. throw new Exception("Не передано Наименование схемы.");
  810. T result;
  811.  
  812. var docFileFrom = userConn.GetTypedEntityById<T>(docFileIdFrom);
  813.  
  814. List<string> excludingFile = new List<string>() { "Sib" + entitySchemaName + "ForSignId", entitySchemaName.Replace("File", string.Empty), "SibIsSign", "SibIsReUseDisabled" };
  815.  
  816. EntitySchema objSchema = this.userConn.EntitySchemaManager.FindInstanceByName(entitySchemaName);
  817. Entity objEntity = objSchema.CreateEntity(this.userConn);
  818. objEntity.UseAdminRights = false;
  819. objEntity.SetDefColumnValues();
  820.  
  821. SibStaticCommonHelper.CopyAllColumnsTo(docFileFrom, objEntity, excludingFile);
  822. objEntity.SetColumnValue("SibIsReUseDisabled", true);
  823. objEntity.SetColumnValue(excludingFile[1] + "Id", documentIdTo);
  824.  
  825. if (docFileFrom.GetTypedColumnValue<bool>("SibIsSign"))
  826. {
  827. var fileForSignId = docFileFrom.GetTypedColumnValue<Guid>(excludingFile.First());
  828. var fileForSign = userConn.GetTypedEntityById<T>(fileForSignId);
  829. var hashFileForSign = fileForSign.GetTypedColumnValue<string>("SibHash");
  830.  
  831. var fileExists = userConn.GetTypedEntityListByAnyColumns<T>(
  832. new Dictionary<string, object>
  833. {
  834. { excludingFile[1], documentIdTo },
  835. { "SibHash", hashFileForSign}
  836. })?.FirstOrDefault();
  837. if (fileExists != null)
  838. {
  839. objEntity.SetColumnValue("SibIsSign", true);
  840. objEntity.SetColumnValue(excludingFile.First(), fileExists.GetTypedColumnValue<Guid>("Id"));
  841. }
  842. else
  843. {
  844. var docFileForSign = StartCopyDocListInFinApp<T>(documentIdTo, docFileFrom.GetTypedColumnValue<Guid>(excludingFile.First()), ref err);
  845. if (docFileForSign != null)
  846. {
  847. objEntity.SetColumnValue("SibIsSign", true);
  848. objEntity.SetColumnValue(excludingFile.First(), docFileForSign.GetTypedColumnValue<Guid>("Id"));
  849. docFileForSign.SetColumnValue("SibIsReUseDisabled", false);
  850. docFileForSign.Save(false);
  851. }
  852. }
  853. }
  854. objEntity.Save(false);
  855. return (T)objEntity;
  856. }
  857. catch (Exception e)
  858. {
  859. err = e.ToString();
  860. SibLogger.Error(err);
  861. return null;
  862. }
  863. }
  864.  
  865. }
  866.  
  867.  
  868. namespace BG_DocumentIntegration
  869. {
  870. public class Finapp
  871. {
  872. public string id { get; set; }
  873. public string registrynumber { get; set; }
  874. public string clientinn { get; set; }
  875. public string sourceinn { get; set; }
  876. }
  877.  
  878. public class Appform
  879. {
  880. public string id { get; set; }
  881. public string inn { get; set; }
  882. }
  883.  
  884. public class Document
  885. {
  886. public Guid id { get; set; }
  887. public bool updateSign { get; set; }
  888. public bool isnew { get; set; }
  889. public string type { get; set; }
  890. public string code { get; set; }
  891. public bool isClientDocument { get; set; }
  892. public Guid guaranteeIntegrationId { get; set; }
  893. }
  894.  
  895. public class File
  896. {
  897. public Guid id { get; set; }
  898. public string name { get; set; }
  899. public string data { get; set; }
  900. public string sign { get; set; }
  901. }
  902.  
  903. public class IncomeRequest
  904. {
  905. public Finapp finapp { get; set; }
  906. public Appform appform { get; set; }
  907. public Document document { get; set; }
  908. public List<File> files { get; set; }
  909. }
  910.  
  911. public class OutcomeRequest
  912. {
  913. public List<File> files { get; set; }
  914. }
  915.  
  916. //public class ResponseFile
  917. //{
  918. // public Guid Id_Old { get; set; }
  919. // public Guid Id_New { get; set; }
  920. //}
  921. }
  922. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement