ModuleServerFunctions.cs 478 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using CommonLibrary;
using NpoComputer.DCX.Common;
using Sungero.Company;
using Sungero.Content;
using Sungero.Core;
using Sungero.CoreEntities;
using Sungero.Docflow;
using Sungero.Domain.Shared;
using Sungero.Exchange.Structures.Module;
using Sungero.ExchangeCore;
using Sungero.Metadata;
using Sungero.Parties;
using Sungero.Workflow;
using Calendar = Sungero.Core.Calendar;
using DcxClient = NpoComputer.DCX.ClientApi.Client;
using ExchDocumentType = Sungero.Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType;
using FinancialFunction = Sungero.FinancialArchive.PublicFunctions;
using Signature = NpoComputer.DCX.Common.Signature;

namespace Sungero.Exchange.Server
{
  public class ModuleFunctions
  {
    #region Обработка сообщений из сервиса обмена

    #region Разбор сообщений из сервиса
    
    /// <summary>
    /// Обработка легких сообщений сервиса обмена.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    public virtual void SyncLiteMessages(ExchangeCore.IBusinessUnitBox businessUnitBox)
    {
      try
      {
        this.LogDebugFormat(businessUnitBox, "Execute SyncLiteMessages.");
        var currentIncomingId = Functions.Module.GetLastIncomingMessageId(businessUnitBox);
        var currentOutgoingId = Functions.Module.GetLastOutgoingMessageId(businessUnitBox);
        var lastIncomingId = string.Empty;
        var lastOutgoingId = string.Empty;
        
        // Если это первый запуск - явно вызываем синхронизацию контрагентов, у неё таймаут большой.
        if (string.IsNullOrWhiteSpace(currentIncomingId) && string.IsNullOrWhiteSpace(currentOutgoingId))
        {
          Exchange.PublicFunctions.Module.LogDebugFormat(businessUnitBox, "SyncLiteMessages. Is first execute job. Requeue counterparty sync.");
          ExchangeCore.PublicFunctions.Module.Remote.RequeueCounterpartySync();
        }
        
        var messages = this.GetLiteMessages(businessUnitBox, currentIncomingId, currentOutgoingId, out lastIncomingId, out lastOutgoingId);
        messages = this.FilterLiteMessages(businessUnitBox, messages);
        this.RunMessagesOnAsyncHandler(businessUnitBox, messages);
        this.UpdateLastMessageIds(businessUnitBox, currentIncomingId, currentOutgoingId, lastIncomingId, lastOutgoingId);
        this.RunOldMessagesOnAsyncHandler(businessUnitBox);
        this.LogDebugFormat(businessUnitBox, "Done SyncLiteMessages.");
      }
      catch (Exception ex)
      {
        this.LogErrorFormat(string.Format(ExchangeCore.BusinessUnitBoxes.Resources.BoxError,  businessUnitBox.Id), ex);
      }
    }
    
    /// <summary>
    /// Обработка легких исторических сообщений сервиса обмена.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    public virtual void SyncLiteHistoricalMessages(ExchangeCore.IBusinessUnitBox businessUnitBox)
    {
      try
      {
        this.LogDebugFormat(businessUnitBox, "Execute SyncLiteHistoricalMessages.");
        
        var downloadSession = ExchangeCore.PublicFunctions.BusinessUnitBox.GetHistoricalMessagesDownloadSessionInWork(businessUnitBox);
        if (downloadSession != null)
        {
          var messageQueueItemsCount = ExchangeCore.MessageQueueItems.GetAll(q => q.ProcessingStatus != ExchangeCore.MessageQueueItem.ProcessingStatus.Suspended &&
                                                                             Equals(q.RootBox, businessUnitBox) && q.DownloadSession.Id == downloadSession.Id)
            .Count();
          
          this.LogDebugFormat(businessUnitBox, "SyncLiteHistoricalMessages. Found download session. Queue items count: {0}, Session Id: {1}", messageQueueItemsCount, downloadSession.Id);
          
          var maxMessageQueueItemsCount = Sungero.Docflow.PublicFunctions.Module.Remote.GetDocflowParamsIntegerValue(Sungero.Docflow.PublicConstants.Module.HistoricalMessageQueueItemLimitParamName);
          if (maxMessageQueueItemsCount <= 0)
            maxMessageQueueItemsCount = Sungero.Docflow.PublicConstants.Module.HistoricalMessageQueueItemLimit;
          
          if (messageQueueItemsCount < maxMessageQueueItemsCount)
          {
            var lastIncomingId = downloadSession.LastIncomingMessageId;
            var lastOutgoingId = downloadSession.LastOutgoingMessageId;
            var messages = this.GetLiteMessages(businessUnitBox, lastIncomingId, lastOutgoingId, out lastIncomingId, out lastOutgoingId, downloadSession.PeriodBegin.ToUtcTime().Value);
            
            messages = messages.Where(m => m.TimeStamp.Date <= downloadSession.PeriodEnd.Value.Date).ToList();
            this.LogDebugFormat(businessUnitBox, "SyncLiteHistoricalMessages. Messages count: {0}, Session Id: {1}", messages.Count, downloadSession.Id);
            
            if (messages.Count == 0)
            {
              downloadSession = HistoricalMessagesDownloadSessions.Get(downloadSession.Id);
              downloadSession.DownloadingState = ExchangeCore.HistoricalMessagesDownloadSession.DownloadingState.Completed;
              downloadSession.LastMessageDate = downloadSession.PeriodEnd;
              downloadSession.LastIncomingMessageId = string.Empty;
              downloadSession.LastOutgoingMessageId = string.Empty;
              this.LogDebugFormat(businessUnitBox, "SyncLiteHistoricalMessages. Download complete. Session Id: {0}.", downloadSession.Id);
            }
            else
            {
              var lastMessageDate = messages.Last().TimeStamp;
              messages = this.FilterLiteMessages(businessUnitBox, messages);
              this.RunMessagesOnAsyncHandler(businessUnitBox, messages, downloadSession);
              
              downloadSession = HistoricalMessagesDownloadSessions.Get(downloadSession.Id);
              downloadSession.LastMessageDate = lastMessageDate;
              downloadSession.LastIncomingMessageId = lastIncomingId;
              downloadSession.LastOutgoingMessageId = lastOutgoingId;
              
              this.LogDebugFormat(businessUnitBox, "SyncLiteHistoricalMessages. Messages added to processing. Messages count: {0}. LastMessageDate: {1}. Session Id: {2}.",
                                  messages.Count(), downloadSession.LastMessageDate, downloadSession.Id);
            }
            
            downloadSession.Save();
          }
        }
        
        this.RunOldMessagesOnAsyncHandler(businessUnitBox, true);
        this.LogDebugFormat(businessUnitBox, "Done SyncLiteHistoricalMessages. Session Id: {0}.", downloadSession?.Id);
      }
      catch (Exception ex)
      {
        this.LogErrorFormat(string.Format(ExchangeCore.BusinessUnitBoxes.Resources.BoxError,  businessUnitBox.Id), ex);
      }
    }

    /// <summary>
    /// Обработка сообщений из сервиса обмена.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="lastIncomingId">Id входящего сообщения, с которого нужно начать обработку.</param>
    /// <param name="lastOutgoingId">Id исходящего сообщения, с которого нужно начать обработку.</param>
    [Obsolete("Используйте метод SyncLiteMessages.")]
    public virtual void SyncMessages(ExchangeCore.IBusinessUnitBox businessUnitBox, string lastIncomingId, string lastOutgoingId)
    {
      try
      {
        var client = GetClient(businessUnitBox);
        var lastIncomingEventId = string.Empty;
        var lastOutgoingEventId = string.Empty;
        
        var lastIncomingDefaultId = string.Empty;
        var lastOutgoingDefaultId = string.Empty;
        
        var existLastId = !string.IsNullOrWhiteSpace(lastIncomingId) || !string.IsNullOrWhiteSpace(lastOutgoingId);
        
        if (existLastId)
        {
          lastIncomingDefaultId = string.IsNullOrWhiteSpace(lastIncomingId) ? lastOutgoingId : lastIncomingId;
          lastOutgoingDefaultId = string.IsNullOrWhiteSpace(lastOutgoingId) ? lastIncomingId : lastOutgoingId;
        }
        
        this.LogDebugFormat(businessUnitBox, "Start receiving messages from the service.");
        var messages = (existLastId ? client.GetMessages(lastIncomingDefaultId, lastOutgoingDefaultId, out lastIncomingEventId, out lastOutgoingEventId) :
                        client.GetMessages(Calendar.Today.ToUtcTime().Value, out lastIncomingEventId, out lastOutgoingEventId)).ToList();
        this.LogDebugFormat(businessUnitBox, "Done receiving messages from the service. Count messages = '{0}'.", messages.Count);
        
        foreach (var message in messages)
        {
          // Добавление в очередь.
          this.CreateQueueItem(businessUnitBox, message);
        }
        
        if (!string.IsNullOrEmpty(lastIncomingEventId) && !Equals(lastIncomingEventId, lastIncomingId))
          this.UpdateLastIncomingMessageId(businessUnitBox, lastIncomingEventId);
        
        if (!string.IsNullOrEmpty(lastOutgoingEventId) && !Equals(lastOutgoingEventId, lastOutgoingId))
          this.UpdateLastOutgoingMessageId(businessUnitBox, lastOutgoingEventId);
        
        var queueItems = ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, businessUnitBox) &&
                                                               !Equals(q.ProcessingStatus, ExchangeCore.MessageQueueItem.ProcessingStatus.Suspended)).ToList();
        
        // Дозагрузка сообщений из очереди.
        this.LoadMessagesFromQueueItems(messages, queueItems, client);

        // Обработка сообщений из очереди.
        this.ProcessMessages(messages, queueItems, client);

        // Удаление из очереди обработанных сообщений.
        this.DeleteProcessedQueueItems(businessUnitBox, client);
      }
      catch (Exception ex)
      {
        Logger.ErrorFormat(ExchangeCore.BusinessUnitBoxes.Resources.BoxError, ex, businessUnitBox.Id);
      }
    }

    /// <summary>
    /// Получение легких сообщений с сервиса обмена.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="currentIncomingId">Id входящего сообщения (текущее значение в базе).</param>
    /// <param name="currentOutgoingId">Id исхожящего сообщения (текущее значение в базе).</param>
    /// <param name="lastIncomingId">Id входящего сообщения, на котором закончилась обработка.</param>
    /// <param name="lastOutgoingId">Id исходящего сообщения, на котором закончилась обработка.</param>
    /// <param name="startingDate">Дата начала загрузки сообщений.</param>
    /// <returns>Список легких сообщений DCX.</returns>
    private List<NpoComputer.DCX.Common.IMessage> GetLiteMessages(ExchangeCore.IBusinessUnitBox businessUnitBox,
                                                                  string currentIncomingId, string currentOutgoingId,
                                                                  out string lastIncomingId, out string lastOutgoingId,
                                                                  DateTime? startingDate = null)
    {
      this.LogDebugFormat(businessUnitBox, "Execute GetLiteMessages. Start receiving messages from the service.");
      
      var client = GetClient(businessUnitBox);
      var maxMessagesToLoading = this.GetMaxMessagesToLoading();
      lastIncomingId = string.Empty;
      lastOutgoingId = string.Empty;
      var currentIncomingDefaultId = string.Empty;
      var currentOutgoingDefaultId = string.Empty;
      var allMessages = new List<IMessage>();
      
      for (int i = 0; i < this.GetMaxAttemptsToReceiveMessages(); i++)
      {
        var existLastId = !string.IsNullOrWhiteSpace(currentIncomingId) || !string.IsNullOrWhiteSpace(currentOutgoingId);
        
        if (existLastId)
        {
          currentIncomingDefaultId = string.IsNullOrWhiteSpace(currentIncomingId) ? currentOutgoingId : currentIncomingId;
          currentOutgoingDefaultId = string.IsNullOrWhiteSpace(currentOutgoingId) ? currentIncomingId : currentOutgoingId;
        }

        var messages = existLastId ?
          client.GetLiteMessages(currentIncomingDefaultId, currentOutgoingDefaultId, out lastIncomingId, out lastOutgoingId).ToList() :
          client.GetLiteMessages(startingDate ?? Calendar.Today.ToUtcTime().Value, out lastIncomingId, out lastOutgoingId).ToList();
        
        allMessages.AddRange(messages);
        currentIncomingId = lastIncomingId;
        currentOutgoingId = lastOutgoingId;
        
        if (allMessages.Count >= maxMessagesToLoading || messages.Count == 0)
          break;
      }
      
      this.LogDebugFormat(businessUnitBox, "Done GetLiteMessages. Count messages: '{0}'.", allMessages.Count);

      return allMessages;
    }
    
    /// <summary>
    /// Отфильтровать легкие сообшения.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="messages">Сообщения.</param>
    /// <returns>Список отфильтрованных сообщений.</returns>
    public virtual List<NpoComputer.DCX.Common.IMessage> FilterLiteMessages(ExchangeCore.IBusinessUnitBox businessUnitBox, List<NpoComputer.DCX.Common.IMessage> messages)
    {
      return messages;
    }

    /// <summary>
    /// Запустить асинхронную обработку для сгруппированных элементов очереди сообщений.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="messages">Сообщения DCX.</param>
    /// <param name="downloadSession">Сессия исторической загрузки.</param>
    public void RunMessagesOnAsyncHandler(ExchangeCore.IBusinessUnitBox businessUnitBox, List<NpoComputer.DCX.Common.IMessage> messages,
                                          IHistoricalMessagesDownloadSession downloadSession = null)
    {
      this.LogDebugFormat(businessUnitBox, string.Format("Execute RunMessagesOnAsyncHandler. Messages count: '{0}'", messages.Count()));

      foreach (var messageGroup in messages.GroupBy(m => m.ParentServiceMessageId))
      {
        var asyncHandlerId = Guid.NewGuid().ToString();
        var notProcessedQueueItems = new List<ExchangeCore.IMessageQueueItem>();
        
        notProcessedQueueItems.AddRange(this.CreateLiteQueueItems(businessUnitBox, messageGroup.ToList(), asyncHandlerId, downloadSession));
        
        var rootMessageId = messageGroup.First().ParentServiceMessageId;
        notProcessedQueueItems.AddRange(this.FillExistingQueueItemsAsyncHandlerId(businessUnitBox, rootMessageId, asyncHandlerId));
        
        if (notProcessedQueueItems.Any())
        {
          var queueItemIds = string.Join(",", notProcessedQueueItems.Select(q => q.Id));
          this.ExecuteProcessMessagesAsyncHandler(asyncHandlerId, queueItemIds);
        }
      }
      
      this.LogDebugFormat(businessUnitBox, "Done RunMessagesOnAsyncHandler.");
    }
    
    /// <summary>
    /// Заполнить Ид асинхроного обработчика для существующих не обработанных элементов очереди сообщений.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="rootMessageId">Ид родительского сообщения.</param>
    /// <param name="asyncHandlerId">Ид асинхронного обработчика.</param>
    /// <returns>Список элементов очереди сообщений с обновленными Ид асинхронного обработчика.</returns>
    protected virtual List<IMessageQueueItem> FillExistingQueueItemsAsyncHandlerId(IBusinessUnitBox businessUnitBox, string rootMessageId, string asyncHandlerId)
    {
      this.LogDebugFormat(businessUnitBox, "Execute FillExistingQueueItemsAsyncHandlerId. RootMessageId: {0}, AsyncHandlerId: {1}", rootMessageId, asyncHandlerId);

      var notProcessedQueueItems = ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, businessUnitBox) &&
                                                                         string.Equals(q.RootMessageId, rootMessageId) &&
                                                                         q.ProcessingStatus != ExchangeCore.MessageQueueItem.ProcessingStatus.Suspended &&
                                                                         q.ProcessingStatus != ExchangeCore.MessageQueueItem.ProcessingStatus.Processed &&
                                                                         q.AsyncHandlerId == null).ToList();
      foreach (var queueItem in notProcessedQueueItems)
      {
        queueItem.AsyncHandlerId = asyncHandlerId;
        queueItem.Save();
        this.LogDebugFormat(businessUnitBox, "Done FillExistingQueueItemsAsyncHandlerId. Fill AsyncHandlerId {0} for old queue item with Id {1}", asyncHandlerId, queueItem.Id);
      }
      
      return notProcessedQueueItems;
    }
    
    /// <summary>
    /// Создать элементы очереди.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="messages">Сообщения DCX.</param>
    /// <param name="asyncHandlerId">Ид асинхронного обработчика.</param>
    /// <param name="downloadSession">Сессия исторической загрузки.</param>
    /// <returns>Список созданных элементов очереди сообщений.</returns>
    public List<IMessageQueueItem> CreateLiteQueueItems(ExchangeCore.IBusinessUnitBox businessUnitBox, List<NpoComputer.DCX.Common.IMessage> messages,
                                                        string asyncHandlerId, IHistoricalMessagesDownloadSession downloadSession = null)
    {
      this.LogDebugFormat(businessUnitBox, string.Format("Execute CreateLiteQueueItems. Messages count: '{0}'", messages.Count()));
      var createdQueueItems = new List<ExchangeCore.IMessageQueueItem>();
      foreach (var message in messages)
      {
        var queueItem = ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, businessUnitBox) && q.ExternalId == message.ServiceMessageId).FirstOrDefault();
        
        if (queueItem == null)
        {
          createdQueueItems.Add(this.CreateLiteQueueItem(businessUnitBox, message, asyncHandlerId, downloadSession));
        }
        else
        {
          if (downloadSession != null && queueItem.DownloadSession != null &&
              queueItem.ProcessingStatus != Sungero.ExchangeCore.MessageQueueItem.ProcessingStatus.Processed)
          {
            try
            {
              queueItem.DownloadSession = downloadSession;
              queueItem.IsManualRestart = false;
              queueItem.ProcessingStatus = Sungero.ExchangeCore.MessageQueueItem.ProcessingStatus.NotProcessed;
              queueItem.AsyncHandlerId = null;
              queueItem.Save();
              this.LogDebugFormat(queueItem, string.Format("CreateLiteQueueItems. Queue item download session was updated, message id {0}.", message.ServiceMessageId));
            }
            catch (Exception ex)
            {
              var logMessage = string.Format("CreateLiteQueueItems. Failed updating queue item download session, message id {0}. Error: {1}", message.ServiceMessageId, ex.Message);
              this.LogDebugFormat(queueItem, logMessage);
            }
          }
          else
            this.LogDebugFormat(businessUnitBox, string.Format("CreateLiteQueueItems. Message with id {0} already exists.", message.ServiceMessageId));
        }
      }
      this.LogDebugFormat(businessUnitBox, "Done CreateLiteQueueItems.");

      return createdQueueItems;
    }
    
    /// <summary>
    /// Обновить ид последних полученных сообщений.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="currentIncomingId">Id входящего сообщения (текущее значение в базе).</param>
    /// <param name="currentOutgoingId">Id исходящего сообщения (текущее значение в базе).</param>
    /// <param name="lastIncomingId">Id входящего сообщения, на котором закончилась обработка.</param>
    /// <param name="lastOutgoingId">Id исходящего сообщения, на котором закончилась обработка.</param>
    public void UpdateLastMessageIds(ExchangeCore.IBusinessUnitBox businessUnitBox,
                                     string currentIncomingId, string currentOutgoingId,
                                     string lastIncomingId, string lastOutgoingId)
    {
      this.LogDebugFormat(businessUnitBox, "Execute UpdateLastMessageIds.");
      
      if (!string.IsNullOrEmpty(lastIncomingId) && !Equals(lastIncomingId, currentIncomingId))
        this.UpdateLastIncomingMessageId(businessUnitBox, lastIncomingId);
      
      if (!string.IsNullOrEmpty(lastOutgoingId) && !Equals(lastOutgoingId, currentOutgoingId))
        this.UpdateLastOutgoingMessageId(businessUnitBox, lastOutgoingId);
      
      this.LogDebugFormat(businessUnitBox, "UpdateLastMessageIds. Done.");
    }
    
    /// <summary>
    /// Получить максимальное количество загружаемых сообщений за одно выполнение фонового процесса "Получение сообщений".
    /// </summary>
    /// <returns>Максимальное количество загружаемых сообщений.</returns>
    public virtual int GetMaxMessagesToLoading()
    {
      return Exchange.Constants.Module.MaxMessagesToLoading;
    }
    
    /// <summary>
    /// Получить максимальное количество попыток получения сообщений.
    /// </summary>
    /// <returns>Максимальное количество попыток получения сообщений.</returns>
    public virtual int GetMaxAttemptsToReceiveMessages()
    {
      return Exchange.Constants.Module.MaxAttemptsToReceiveMessages;
    }
    
    /// <summary>
    /// Запустить асинхронную обработку для созданных ранее элементов очереди сообщений.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="isHistoricalDownloading">Признак запуска асинхронного обработчика в контексте исторической загрузки.</param>
    public virtual void RunOldMessagesOnAsyncHandler(ExchangeCore.IBusinessUnitBox businessUnitBox, bool isHistoricalDownloading = false)
    {
      this.LogDebugFormat(businessUnitBox, "Execute RunOldMessagesOnAsyncHandler.");
      
      var queueItems = ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, businessUnitBox) && q.AsyncHandlerId == null &&
                                                             q.ProcessingStatus != ExchangeCore.MessageQueueItem.ProcessingStatus.Suspended &&
                                                             (q.DownloadSession != null) == isHistoricalDownloading);
      
      foreach (var queueItemGroup in queueItems.GroupBy(q => q.RootMessageId ?? q.ExternalId))
      {
        var orderedQueueItemIds = queueItemGroup.Select(q => q.Id).ToList();
        
        var queueItemIds = string.Join(",", orderedQueueItemIds);
        var asyncHandlerId = Guid.NewGuid().ToString();
        
        try
        {
          foreach (var queueItem in queueItemGroup)
          {
            queueItem.AsyncHandlerId = asyncHandlerId;
            queueItem.Save();
            this.LogDebugFormat(queueItem, "Save AsyncHandlerId to queueItem.");
          }
          
          this.ExecuteProcessMessagesAsyncHandler(asyncHandlerId, queueItemIds);
        }
        catch (Exception e)
        {
          this.LogDebugFormat(string.Format("RunOldMessagesOnAsyncHandler. AsyncHandlerId: '{0}', queueItemIds '{1}'. Error: {2}", asyncHandlerId, queueItemIds, e.Message));
        }
      }
      
      this.LogDebugFormat(businessUnitBox, "Done RunOldMessagesOnAsyncHandler.");
    }
    
    /// <summary>
    /// Обработка сообщений очереди.
    /// </summary>
    /// <param name="messages">Сообщения.</param>
    /// <param name="queueItems">Элементы очереди.</param>
    /// <param name="client">Клиент.</param>
    [Obsolete("Логика перенесена в асинхронный обработчик Sungero.Exchange.AsyncHandlers.ProcessMessages.")]
    protected virtual void ProcessMessages(List<IMessage> messages, List<IMessageQueueItem> queueItems, DcxClient client)
    {
      this.LogDebugFormat("Start process messages.");
      
      var queueItemsIds = queueItems.Select(q => q.Id).ToList();
      foreach (var message in messages)
      {
        if (message.HasErrors == true)
        {
          Logger.ErrorFormat("Message Id {0} not processed, service error {1}", message.ServiceMessageId, message.ErrorText);
          continue;
        }
        
        // Сообщение из сервиса.
        this.LogDebugFormat(message, "Start process message.");
        this.LogFullMessage(message);

        Transactions.Execute(
          () =>
          {
            var transactionQueueItems = ExchangeCore.MessageQueueItems.GetAll(q => queueItemsIds.Contains(q.Id)).ToList();
            if (this.ProcessMessage(message, transactionQueueItems, client))
            {
              var queueItem = transactionQueueItems.Single(x => x.ExternalId == message.ServiceMessageId);
              queueItem.ProcessingStatus = ExchangeCore.MessageQueueItem.ProcessingStatus.Processed;
              queueItem.Save();
              this.LogDebugFormat(message, "Message processed successfully.");
            }
            else
            {
              var queueItem = transactionQueueItems.SingleOrDefault(x => x.ExternalId == message.ServiceMessageId);
              if (queueItem != null)
              {
                queueItem.Retries += 1;
                queueItem.Save();
                this.LogDebugFormat(message, "Process message failed. Retries: '{0}'.", queueItem.Retries);
              }
            }
          });

        this.LogDebugFormat(message, "End process message.");
      }
      
      this.LogDebugFormat("End process messages.");
    }
    
    /// <summary>
    /// Добавление сообщений в очередь.
    /// </summary>
    /// <param name="businessUnitBoxId">ИД ящика НОР.</param>
    /// <param name="serviceMessageId">ИД Сообщение.</param>
    [Remote]
    public virtual void CreateQueueItem(int businessUnitBoxId, string serviceMessageId)
    {
      var businessUnitBox = BusinessUnitBoxes.Get(businessUnitBoxId);
      var client = GetClient(businessUnitBox);
      var serviceMessage = client.GetMessage(serviceMessageId);
      this.CreateQueueItem(businessUnitBox, serviceMessage);
      RequeueMessagesGet();
    }
    
    /// <summary>
    /// Получить ящик из сообщения.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик нашей организации.</param>
    /// <param name="message">Сообщение.</param>
    /// <returns>Ящик.</returns>
    protected virtual IBoxBase GetMessageBox(IBusinessUnitBox businessUnitBox, IMessage message)
    {
      if (message.Sender == null || message.Sender.Organization == null)
        return businessUnitBox;
      
      var organizationId = message.Sender.Organization.OrganizationId;
      bool isIncoming = organizationId != businessUnitBox.OrganizationId;
      var box = ExchangeCore.BoxBases.Null;
      if (isIncoming && message.ToDepartment != null && ExchangeCore.DepartmentBoxes
          .GetAll(x => x.ServiceId == message.ToDepartment.Id && x.Status == CoreEntities.DatabookEntry.Status.Active).Any())
        box = ExchangeCore.DepartmentBoxes.GetAll(x => x.ServiceId == message.ToDepartment.Id && x.Status == CoreEntities.DatabookEntry.Status.Active)
          .Single();
      else if (!isIncoming && message.FromDepartment != null && ExchangeCore.DepartmentBoxes
               .GetAll(x => x.ServiceId == message.FromDepartment.Id && x.Status == CoreEntities.DatabookEntry.Status.Active).Any())
        box = ExchangeCore.DepartmentBoxes.GetAll(x => x.ServiceId == message.FromDepartment.Id && x.Status == CoreEntities.DatabookEntry.Status.Active)
          .Single();
      else
        box = businessUnitBox;
      
      return box;
    }
    
    /// <summary>
    /// Добавление сообщений в очередь.
    /// </summary>
    /// <param name="businessUnitBox">Ящик НОР.</param>
    /// <param name="message">Сообщение.</param>
    protected virtual void CreateQueueItem(IBusinessUnitBox businessUnitBox, IMessage message)
    {
      if (ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, businessUnitBox) && q.ExternalId == message.ServiceMessageId).Any())
        return;
      
      var queueItem = ExchangeCore.MessageQueueItems.Create();
      queueItem.ExternalId = message.ServiceMessageId;
      queueItem.Box = this.GetMessageBox(businessUnitBox, message);
      queueItem.RootBox = businessUnitBox;
      queueItem.ProcessingStatus = ExchangeCore.MessageQueueItem.ProcessingStatus.NotProcessed;
      queueItem.Created = Calendar.Now;
      queueItem.Name = message.ServiceMessageId;
      
      if (!message.HasErrors)
      {
        var organizationId = message.Sender.Organization.OrganizationId;
        bool isIncoming = organizationId != businessUnitBox.OrganizationId;
        queueItem.CounterpartyExternalId = isIncoming ? organizationId : message.Receiver.Organization.OrganizationId;
      }
      
      if (message.HasErrors)
      {
        var note = string.Format("{0}{1}{2}", queueItem.Note, Environment.NewLine, message.ErrorText);
        if (note.Length > 1000)
          note = note.Substring(0, 1000);
        queueItem.Note = note;
      }
      
      foreach (var primary in message.PrimaryDocuments)
      {
        var itemDocument = queueItem.Documents.AddNew();
        itemDocument.ExternalId = primary.ServiceEntityId;
        itemDocument.Type = ExchangeCore.MessageQueueItemDocuments.Type.Primary;
      }

      foreach (var reglament in message.ReglamentDocuments)
      {
        var itemDocument = queueItem.Documents.AddNew();
        itemDocument.ExternalId = reglament.ServiceEntityId;
        itemDocument.Type = ExchangeCore.MessageQueueItemDocuments.Type.Reglament;
      }

      queueItem.Save();
      this.LogDebugFormat(message, queueItem, businessUnitBox, "CreateQueueItem. Add message to queue item.");
    }
    
    /// <summary>
    /// Добавление легкого сообщения в очередь.
    /// </summary>
    /// <param name="businessUnitBox">Ящик НОР.</param>
    /// <param name="message">Сообщение.</param>
    /// <param name="asyncHanderId">Ид асинхронного обработчика.</param>
    /// <param name="downloadSession">Сессия исторической загрузки.</param>
    /// <returns>Созданный элемент очереди.</returns>
    protected virtual IMessageQueueItem CreateLiteQueueItem(IBusinessUnitBox businessUnitBox, IMessage message, string asyncHanderId,
                                                            IHistoricalMessagesDownloadSession downloadSession = null)
    {
      this.LogDebugFormat(message, businessUnitBox, "Execute CreateLiteQueueItem.");
      var queueItem = ExchangeCore.MessageQueueItems.Create();
      queueItem.ExternalId = message.ServiceMessageId;
      queueItem.RootMessageId = message.ParentServiceMessageId;
      queueItem.IsRootMessage = message.IsRoot;
      queueItem.Box = this.GetMessageBox(businessUnitBox, message);
      queueItem.RootBox = businessUnitBox;
      queueItem.ProcessingStatus = ExchangeCore.MessageQueueItem.ProcessingStatus.NotProcessed;
      queueItem.Created = Calendar.Now;
      queueItem.Name = message.ServiceMessageId;
      queueItem.AsyncHandlerId = asyncHanderId;
      queueItem.DownloadSession = downloadSession;
      
      if (message.HasErrors)
      {
        var note = string.Format("{0}{1}{2}", queueItem.Note, Environment.NewLine, message.ErrorText);
        if (note.Length > 1000)
          note = note.Substring(0, 1000);
        queueItem.Note = note;
      }

      queueItem.Save();
      this.LogDebugFormat(message, queueItem, businessUnitBox, "Done CreateLiteQueueItem. Queue item created successfully.");
      
      return queueItem;
    }
    
    /// <summary>
    /// Запустить асинхронную обработку элементов очереди сообщений.
    /// </summary>
    /// <param name="asyncHandlerId">Ид асинхронного обработчика.</param>
    /// <param name="queueItemIds">Ид элементов очереди сообщений.</param>
    protected virtual void ExecuteProcessMessagesAsyncHandler(string asyncHandlerId, string queueItemIds)
    {
      var processMessagesHandler = Sungero.Exchange.AsyncHandlers.ProcessMessages.Create();
      processMessagesHandler.QueueItemIds = queueItemIds;
      processMessagesHandler.AsyncHandlerId = asyncHandlerId;
      processMessagesHandler.ExecuteAsync();
      this.LogDebugFormat(string.Format("ExecuteProcessMessagesAsyncHandler. AsyncHandlerId: '{0}', queueItemIds '{1}'.", asyncHandlerId, queueItemIds));
    }

    /// <summary>
    /// Дозагрузка сообщений из очереди.
    /// </summary>
    /// <param name="messages">Сообщения.</param>
    /// <param name="queueItems">Элементы очереди.</param>
    /// <param name="client">Клиент.</param>
    [Obsolete("При рефакторинге отказались от этого метода.")]
    protected virtual void LoadMessagesFromQueueItems(List<IMessage> messages, List<IMessageQueueItem> queueItems, DcxClient client)
    {
      var addedItems = queueItems.Where(x => messages.All(c => c.ServiceMessageId != x.ExternalId) &&
                                        !Equals(x.ProcessingStatus, ExchangeCore.MessageQueueItem.ProcessingStatus.Processed))
        .ToList();
      
      this.LogDebugFormat(string.Format("LoadMessagesFromQueueItems. Added queue items count: {0}.", addedItems.Count));
      
      foreach (var queueItem in addedItems)
      {
        var added = Transactions.Execute(
          () =>
          {
            var message = client.GetMessage(queueItem.ExternalId);
            if (message != null)
              messages.Add(message);
            else
            {
              queueItem.ProcessingStatus = ExchangeCore.MessageQueueItem.ProcessingStatus.Processed;
              queueItem.Save();
              Logger.DebugFormat("Exchange. Not found service message with Id = '{0}'.", queueItem.ExternalId);
            }
          });
        if (!added)
        {
          Transactions.Execute(
            () => { ExchangeCore.PublicFunctions.QueueItemBase.QueueItemOnError(queueItem, Resources.GetMessageFailed); });
          this.LogDebugFormat(queueItem, Resources.GetMessageFailed);
        }
      }
    }
    
    /// <summary>
    /// Удалить обработанные элементы очереди.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <param name="client">Dcx клиент.</param>
    [Obsolete("Используйте DeleteProcessedQueueItem для каждого элемента очереди.")]
    protected virtual void DeleteProcessedQueueItems(IBusinessUnitBox businessUnitBox, DcxClient client)
    {
      var processedQueueItems = ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, businessUnitBox))
        .Where(q => Equals(q.ProcessingStatus, ExchangeCore.MessageQueueItem.ProcessingStatus.Processed))
        .ToList();
      foreach (var queueItem in processedQueueItems)
      {
        Transactions.Execute(
          () =>
          {
            var useRetry = false;
            var itemDocuments = queueItem.Documents.Select(d => d.ExternalId).ToList();
            var documentInfos = ExchangeDocumentInfos
              .GetAll(i => Equals(i.RootBox, businessUnitBox)
                      && Equals(i.ServiceMessageId, queueItem.ExternalId)
                      && itemDocuments.Contains(i.ServiceDocumentId)
                      && i.Document != null)
              .ToList();

            foreach (var documentInfo in documentInfos)
            {
              var canSendDeliveryConfirmation = true;
              try
              {
                canSendDeliveryConfirmation = client.CanSendDeliveryConfirmation(documentInfo.ServiceDocumentId, documentInfo.ServiceMessageId);
              }
              catch (Exception ex)
              {
                useRetry = true;
                this.LogDebugFormat(documentInfo, "Error while getting document from the service to generate delivery confirmation: {0}.", ex.Message);
              }
              
              if (!canSendDeliveryConfirmation && !useRetry)
                FixReceiptNotification(documentInfo, string.Empty, false);
            }

            if (!useRetry)
              ExchangeCore.MessageQueueItems.Delete(queueItem);
          });
      }
    }
    
    /// <summary>
    /// Удалить обработанный элемент очереди.
    /// </summary>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="client">Dcx клиент.</param>
    public virtual void DeleteProcessedQueueItem(IMessageQueueItem queueItem, NpoComputer.DCX.ClientApi.Client client)
    {
      this.LogDebugFormat(queueItem, "Execute DeleteProcessedQueueItem");
      queueItem = ExchangeCore.MessageQueueItems.GetAll(q => q.Id == queueItem.Id).Single();
      if (queueItem.ProcessingStatus != ExchangeCore.MessageQueueItem.ProcessingStatus.Processed)
        return;
      
      Transactions.Execute(
        () =>
        {
          var useRetry = false;
          var itemDocuments = queueItem.Documents.Select(d => d.ExternalId).ToList();
          var documentInfos = ExchangeDocumentInfos
            .GetAll(i => Equals(i.RootBox, queueItem.RootBox)
                    && Equals(i.ServiceMessageId, queueItem.ExternalId)
                    && itemDocuments.Contains(i.ServiceDocumentId)
                    && i.Document != null)
            .ToList();

          foreach (var documentInfo in documentInfos)
          {
            var canSendDeliveryConfirmation = true;
            try
            {
              canSendDeliveryConfirmation = client.CanSendDeliveryConfirmation(documentInfo.ServiceDocumentId, documentInfo.ServiceMessageId);
            }
            catch (Exception ex)
            {
              useRetry = true;
              this.LogDebugFormat(documentInfo, "Error while getting document from the service to generate delivery confirmation: {0}.", ex.Message);
            }
            
            if (!canSendDeliveryConfirmation && !useRetry)
              FixReceiptNotification(documentInfo, string.Empty, false);
          }

          if (!useRetry)
          {
            ExchangeCore.MessageQueueItems.Delete(queueItem);
            this.LogDebugFormat(queueItem, "Deleted processed queueItem");
          }
        });
      this.LogDebugFormat(queueItem, "Done DeleteProcessedQueueItem.");
    }
    
    /// <summary>
    /// Получить id последнего входящего сообщения.
    /// </summary>
    /// <param name="box">Ящик.</param>
    /// <returns>Id сообщения.</returns>
    [Public, Remote]
    public virtual string GetLastIncomingMessageId(ExchangeCore.IBusinessUnitBox box)
    {
      var key = string.Format(Constants.Module.LastBoxIncomingMessageId, box.Id);
      var command = string.Format(Queries.Module.GetLastMessageId, key);
      try
      {
        var executionResult = Docflow.PublicFunctions.Module.ExecuteScalarSQLCommand(command);
        var result = string.Empty;
        if (!(executionResult is DBNull) && executionResult != null)
          result = executionResult.ToString();
        this.LogDebugFormat(box, "Get messages. Last incoming message id in DB is {0}", result);
        return result;
      }
      catch (Exception ex)
      {
        this.LogDebugFormat(box, "Error while getting incoming message id. No messages in box. {0}", ex);
        return string.Empty;
      }
    }
    
    /// <summary>
    /// Получить id последнего исходящего сообщения.
    /// </summary>
    /// <param name="box">Ящик.</param>
    /// <returns>Id сообщения.</returns>
    [Public, Remote]
    public virtual string GetLastOutgoingMessageId(ExchangeCore.IBusinessUnitBox box)
    {
      var key = string.Format(Constants.Module.LastBoxOutgoingMessageId, box.Id);
      var command = string.Format(Queries.Module.GetLastMessageId, key);
      try
      {
        var executionResult = Docflow.PublicFunctions.Module.ExecuteScalarSQLCommand(command);
        var result = string.Empty;
        if (!(executionResult is DBNull) && executionResult != null)
          result = executionResult.ToString();
        this.LogDebugFormat(box, "Get messages. Last outgoing message id in DB is {0}", result);
        return result;
      }
      catch (Exception ex)
      {
        this.LogDebugFormat(box, "Error while getting outgoing message id. No messages in box. {0}", ex);
        return string.Empty;
      }
    }
    
    /// <summary>
    /// Обновить id полученного входящего сообщения.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="incomingMessageId">Новый id.</param>
    [Public, Remote]
    public virtual void UpdateLastIncomingMessageId(ExchangeCore.IBusinessUnitBox box, string incomingMessageId)
    {
      var key = string.Format(Constants.Module.LastBoxIncomingMessageId, box.Id);
      
      Docflow.PublicFunctions.Module.ExecuteSQLCommandFormat(Queries.Module.UpdateLastMessageId, new[] { key, incomingMessageId });
      this.LogDebugFormat(box, "Last box incoming message id is set to {0}", incomingMessageId);
    }
    
    /// <summary>
    /// Обновить id полученного исходящего сообщения.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="outgoingMessageId">Новый id.</param>
    [Public, Remote]
    public virtual void UpdateLastOutgoingMessageId(ExchangeCore.IBusinessUnitBox box, string outgoingMessageId)
    {
      var key = string.Format(Constants.Module.LastBoxOutgoingMessageId, box.Id);
      
      Docflow.PublicFunctions.Module.ExecuteSQLCommandFormat(Queries.Module.UpdateLastMessageId, new[] { key, outgoingMessageId });
      this.LogDebugFormat(box, "Last box outgoing message id is set to {0}", outgoingMessageId);
    }

    #endregion

    #region Обработка легкого сообщения
    
    /// <summary>
    /// Обработать легкий элемент очереди сообщений.
    /// </summary>
    /// <param name="queueItem">Элемент очереди сообщений.</param>
    /// <param name="asyncHandlerId">Ид ассинхронного события.</param>
    /// <param name="client">Dcx клиент.</param>
    /// <returns>True - если элемент очереди обработался успешно или не требует обработки, иначе - false.</returns>
    public virtual bool ProcessMessageLiteQueueItem(IMessageQueueItem queueItem, string asyncHandlerId, NpoComputer.DCX.ClientApi.Client client)
    {
      this.LogDebugFormat(queueItem, "Execute ProcessMessageLiteQueueItem.");
      
      try
      {
        if (!this.NeedSkipMessageQueueItemProcessing(queueItem, client, asyncHandlerId))
        {
          var message = this.GetMessageFromQueueItem(queueItem, client);
          // Удаляем элемент очереди, когда на сервисе отсутствует сообщение.
          if (message == null)
          {
            Sungero.ExchangeCore.MessageQueueItems.Delete(queueItem);
            this.LogDebugFormat(queueItem, "Not found service message with Id = '{0}'.", queueItem.ExternalId);
            return false;
          }
          
          if (!this.IsMessageValid(message, queueItem))
            return false;
          
          this.LogFullMessage(message);
          this.FillQueueItem(queueItem, message);
          
          if (!this.ProcessMessageQueueItem(client, message, queueItem))
            return false;
        }
        
        this.DeleteProcessedQueueItem(queueItem, client);
        return true;
      }
      catch (Exception ex)
      {
        this.LogErrorFormat(queueItem, "Process message`s lite queue item has error.", ex);
        return false;
      }
      finally
      {
        this.LogDebugFormat(queueItem, "Done ProcessMessageLiteQueueItem.");
      }
    }

    /// <summary>
    /// Получить сообщение из сервиса обмена.
    /// </summary>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="client">Dcx клиент.</param>
    /// <returns>Сообщение.</returns>
    public virtual NpoComputer.DCX.Common.IMessage GetMessageFromQueueItem(IMessageQueueItem queueItem, NpoComputer.DCX.ClientApi.Client client)
    {
      NpoComputer.DCX.Common.IMessage message = null;
      try
      {
        message = client.GetMessage(queueItem.ExternalId);
      }
      catch (Exception ex)
      {
        Transactions.Execute(() =>
                             {
                               queueItem.ProcessingStatus = ExchangeCore.QueueItemBase.ProcessingStatus.Error;
                               queueItem.Note = Resources.GetMessageFailed;
                               queueItem.Save();
                             });
        this.LogErrorFormat(queueItem, "GetMessageFromQueueItem. An error occurred while getting the message from service.", ex);
        message = new NpoComputer.DCX.Common.Message();
        message.HasErrors = true;
        message.ErrorText = ex.Message;
      }
      return message;
    }

    /// <summary>
    /// Обработать элемент очереди сообщений.
    /// </summary>
    /// <param name="client">Клиент DCX.</param>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    /// <param name="queueItem">Элемент очереди сообщений.</param>
    /// <returns>True - если обработка успешна, иначе - false.</returns>
    public virtual bool ProcessMessageQueueItem(NpoComputer.DCX.ClientApi.Client client, NpoComputer.DCX.Common.IMessage message, IMessageQueueItem queueItem)
    {
      this.LogDebugFormat(queueItem, "Execute ProcessMessageQueueItem.");
      bool processMessageSuccess = true;

      var result = Transactions.Execute(
        () => {
          if (this.ProcessMessage(message, queueItem, client))
          {
            var transactionQueueItem = ExchangeCore.MessageQueueItems.GetAll(q => q.Id == queueItem.Id).Single();
            transactionQueueItem.ProcessingStatus = ExchangeCore.MessageQueueItem.ProcessingStatus.Processed;
            transactionQueueItem.Save();
            this.LogDebugFormat(transactionQueueItem, "Message processed successfully.");
          }
          else
            processMessageSuccess = false;
        });

      if (!result || !processMessageSuccess)
      {
        this.LogDebugFormat(queueItem, "Process message failed.");
        return false;
      }
      this.LogDebugFormat(queueItem, "Done ProcessMessageQueueItem.");
      return true;
    }

    /// <summary>
    /// Добавить документы из сообщения к элементу очереди синхронизации сообщений.
    /// </summary>
    /// <param name="queueItem">Элементу очереди синхронизации сообщений.</param>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    public virtual void FillQueueItem(IMessageQueueItem queueItem, NpoComputer.DCX.Common.IMessage message)
    {
      this.LogDebugFormat(queueItem, "Execute FillQueueItem.");

      if (!message.HasErrors)
      {
        var organizationId = message.Sender.Organization.OrganizationId;
        bool isIncoming = organizationId != queueItem.RootBox.OrganizationId;
        queueItem.CounterpartyExternalId = isIncoming ? organizationId : message.Receiver.Organization.OrganizationId;
      }
      
      foreach (var primary in message.PrimaryDocuments)
      {
        if (!queueItem.Documents.Any(d => d.ExternalId == primary.ServiceEntityId &&
                                     Equals(d.Type, ExchangeCore.MessageQueueItemDocuments.Type.Primary)))
        {
          var itemDocument = queueItem.Documents.AddNew();
          itemDocument.ExternalId = primary.ServiceEntityId;
          itemDocument.Type = ExchangeCore.MessageQueueItemDocuments.Type.Primary;
        }
      }

      foreach (var reglament in message.ReglamentDocuments)
      {
        if (!queueItem.Documents.Any(d => d.ExternalId == reglament.ServiceEntityId &&
                                     Equals(d.Type, ExchangeCore.MessageQueueItemDocuments.Type.Reglament)))
        {
          var itemDocument = queueItem.Documents.AddNew();
          itemDocument.ExternalId = reglament.ServiceEntityId;
          itemDocument.Type = ExchangeCore.MessageQueueItemDocuments.Type.Reglament;
        }
      }

      if (queueItem.State.IsChanged)
        queueItem.Save();

      this.LogDebugFormat(queueItem, "Done FillQueueItem.");
    }

    /// <summary>
    /// Проверить, нужно ли пропустить обработку элемента очереди сообщений.
    /// </summary>
    /// <param name="queueItem">Элемент очереди сообщений.</param>
    /// <param name="client">Клиент DCX.</param>
    /// <param name="asyncHandlerId">Ид асинхронного обработчика.</param>
    /// <returns>True - если требуется пропустить обработку элемента очереди сообщений, иначе - false.</returns>
    public virtual bool NeedSkipMessageQueueItemProcessing(IMessageQueueItem queueItem, NpoComputer.DCX.ClientApi.Client client, string asyncHandlerId)
    {
      if (queueItem.ProcessingStatus == ExchangeCore.MessageQueueItem.ProcessingStatus.Suspended ||
          queueItem.ProcessingStatus == ExchangeCore.MessageQueueItem.ProcessingStatus.Processed ||
          !string.Equals(queueItem.AsyncHandlerId, asyncHandlerId))
      {
        this.LogDebugFormat(queueItem, "Skip queueItem: AsyncHandlerId: '{0}', ProcessingStatus: '{1}'. AsyncHandlerId: {2}.",
                            queueItem.AsyncHandlerId, queueItem.ProcessingStatus, asyncHandlerId);
        
        return true;
      }
      
      return false;
    }

    /// <summary>
    /// Проверить сообщение из сервиса обмена на наличие ошибок.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    /// <param name="queueItem">Связанный элемент очереди сообщений.</param>
    /// <returns>True - если сообщение без ошибок, иначе - false.</returns>
    public virtual bool IsMessageValid(NpoComputer.DCX.Common.IMessage message, IMessageQueueItem queueItem)
    {
      if (message.HasErrors == true)
      {
        this.LogDebugFormat(queueItem, "Message Id {0} not processed, service error {1}", message.ServiceMessageId, message.ErrorText);
        return false;
      }

      return true;
    }
    
    /// <summary>
    /// Проверить, обработано ли корневое сообщение для элемента очереди сообщений.
    /// </summary>
    /// <param name="queueItem">Элемент очереди сообщений.</param>
    /// <returns>True - если корневое сообщение обработано, либо текущее является корневым, иначе - false.</returns>
    public virtual bool IsRootMessageQueueItemProcessed(IMessageQueueItem queueItem)
    {
      this.LogDebugFormat(queueItem, "Execute IsRootMessageQueueItemProcessed");
      var rootMessageNotProcessed = Sungero.ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, queueItem.RootBox) &&
                                                                                  string.Equals(q.RootMessageId, queueItem.RootMessageId) && q.IsRootMessage == true &&
                                                                                  q.ProcessingStatus != ExchangeCore.MessageQueueItem.ProcessingStatus.Processed).Any();
      
      if (!rootMessageNotProcessed || queueItem.IsRootMessage == true)
        return true;
      
      return false;
    }

    #endregion
    
    #region Обработка одного сообщения

    /// <summary>
    /// Обработать сообщение.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Обрабатываемый элемент очереди.</param>
    /// <param name="client">Клиент.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    public virtual bool ProcessMessage(NpoComputer.DCX.Common.IMessage message, IMessageQueueItem queueItem, NpoComputer.DCX.ClientApi.Client client)
    {
      var queueItems = ExchangeCore.MessageQueueItems.GetAll(q => q.Id == queueItem.Id).ToList();
      return this.ProcessMessage(message, queueItems, client);
    }
    
    /// <summary>
    /// Обработать сообщение.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItems">Обрабатываемые элементы очереди.</param>
    /// <param name="client">Клиент.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    public virtual bool ProcessMessage(NpoComputer.DCX.Common.IMessage message, List<IMessageQueueItem> queueItems, NpoComputer.DCX.ClientApi.Client client)
    {
      var queueItem = queueItems.Single(x => x.ExternalId == message.ServiceMessageId);
      var box = this.GetMessageBox(queueItem.RootBox, message);
      var businessUnitBox = queueItem.RootBox;
      
      this.LogDebugFormat(message, queueItem, businessUnitBox, "Execute ProcessMessage.");
      
      var organizationId = message.Sender.Organization.OrganizationId;
      var isIncoming = true;
      
      // Обрабатываем исходящие сообщения для поддержки параллельных действий.
      if (organizationId == businessUnitBox.OrganizationId)
      {
        organizationId = message.Receiver.Organization.OrganizationId;
        isIncoming = false;
      }
      
      var sender = Parties.Counterparties.GetAll(c => c.ExchangeBoxes.Any(e => Equals(e.OrganizationId, organizationId) && Equals(businessUnitBox, e.Box))).SingleOrDefault();
      if (sender == null)
      {
        /* Список контактов с сервиса для СБИСа всегда пустой, но для автоматического создания КА
         * необходимо сохранить сообщение в очереди, чтобы оно не потерялось, а также сохранить информацию
         * о КА для последующей синхронизации в RX.
         */
        if (!message.PrimaryDocuments.Any() && message.ReglamentDocuments.All(d => d.DocumentType == ReglamentDocumentType.InvoiceConfirmation ||
                                                d.DocumentType == ReglamentDocumentType.Receipt ||
                                                d.DocumentType == ReglamentDocumentType.InvoiceReceipt)
                                       && client.CanSynchronizeContacts)
        {
          this.ProcessInvoiceConfirmation(message, queueItem, organizationId, businessUnitBox);
          this.ProcessReceiptNotice(message, queueItem, null, isIncoming, businessUnitBox);
          return true;
        }
        else if (!client.CanSynchronizeContacts)
        {
          this.AddCounterpartyQueueItem(businessUnitBox, organizationId);
        }
        
        this.LogDebugFormat(message, queueItem, businessUnitBox, "Unknown counterparty with OrganizationId: '{0}'. It is necessary to synchronize counterparties.", organizationId);
        return false;
      }
      
      if (message.PrimaryDocuments.Any() && message.PrimaryDocuments.Any(x => x.DocumentType == DocumentType.RevocationOffer))
      {
        var processed = this.ProcessAnnulmentOrCancellation(message, queueItems, sender, isIncoming, box);
        if (!message.ReglamentDocuments.Any() && message.PrimaryDocuments.All(x => x.DocumentType == DocumentType.RevocationOffer))
          return processed;
      }
      
      if (!message.IsReply)
      {
        return this.ProcessNewMessage(message, queueItem, box, businessUnitBox, sender, organizationId, isIncoming);
      }
      else
      {
        return this.ProcessReplyMessage(message, queueItem, queueItems, client, box, businessUnitBox, sender, organizationId, isIncoming);
      }
    }

    /// <summary>
    /// Добавить контрагента из сообщения в очередь синхронизации.
    /// </summary>
    /// <param name="businessUnitBox">Абонентский ящик НОР.</param>
    /// <param name="organizationId">ИД организации контрагента.</param>
    protected virtual void AddCounterpartyQueueItem(IBusinessUnitBox businessUnitBox, string organizationId)
    {
      this.LogDebugFormat(businessUnitBox, "Execute AddCounterpartyQueueItem.");
      if (!CounterpartyQueueItems.GetAll(c => c.ExternalId == organizationId && Equals(c.Box, businessUnitBox)).Any())
      {
        var counterpartyQueueItem = CounterpartyQueueItems.Create();
        counterpartyQueueItem.ExternalId = organizationId;
        counterpartyQueueItem.Box = businessUnitBox;
        counterpartyQueueItem.RootBox = businessUnitBox;
        counterpartyQueueItem.ProcessingStatus = ExchangeCore.CounterpartyQueueItem.ProcessingStatus.NotProcessed;
        counterpartyQueueItem.Save();
        this.LogDebugFormat(businessUnitBox, "Create queue item for counterparty OrganizationId {0}.", organizationId);
      }
    }
    
    /// <summary>
    /// Обработать новое сообщение.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="box">Ящик, на который получено сообщение.</param>
    /// <param name="businessUnitBox">Ящик нашей организации.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="organizationId">Идентификатор отправителя в сервисе обмена.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessNewMessage(IMessage message, IMessageQueueItem queueItem, IBoxBase box,
                                             IBusinessUnitBox businessUnitBox, ICounterparty sender,
                                             string organizationId, bool isIncoming)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessNewMessage.");
      if (isIncoming && message.ReglamentDocuments.Any(x => x.DocumentType == NpoComputer.DCX.Common.ReglamentDocumentType.DeliveryFailureNotification))
      {
        return this.ProcessDeliveryFailureNotification(message, box);
      }

      if (message.PrimaryDocuments.Any())
      {
        if (Functions.Module.IsMessageWithUnsupportedDocuments(message))
        {
          this.LogDebugFormat(message, queueItem, box, "Message contains unsupported documents.");
          // Некоторые документы не поддерживаются в системе.
          return this.ProcessMessageWithUnsupportedDocuments(message, sender, isIncoming, box);
        }
        else
        {
          // Создание новых документов.
          var processed = this.ProcessNewIncomingMessage(message, queueItem, sender, isIncoming, box);
          
          // Загрузка сервисных документов.
          return processed && this.ProcessInvoiceConfirmation(message, queueItem, organizationId, businessUnitBox);
        }
      }
      else
      {
        // Обработка ИОП.
        return this.ProcessReceiptNotice(message, queueItem, sender, isIncoming, businessUnitBox);
      }

      // Не смогли обработать - пропускаем и помечаем как обработанное.
      this.LogDebugFormat(message, queueItem, box, "Message processing was skipped. Message is marked as processed.");
      
      return true;
    }

    /// <summary>
    /// Обработать ответное сообщение.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="queueItems">Прочие необработанные элементы очереди.</param>
    /// <param name="client">Клиент.</param>
    /// <param name="box">Ящик, на который получено сообщение.</param>
    /// <param name="businessUnitBox">Ящик нашей организации.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="organizationId">Идентификатор отправителя в сервисе обмена.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessReplyMessage(IMessage message,
                                               IMessageQueueItem queueItem, List<IMessageQueueItem> queueItems, DcxClient client, IBoxBase box,
                                               IBusinessUnitBox businessUnitBox, ICounterparty sender, string organizationId, bool isIncoming)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessReplyMessage.");
      var historyComment = string.Format("{0}|{1}", sender.Name, businessUnitBox.ExchangeService.Name);
      var historyOperation = new Enumeration(isIncoming ? Constants.Module.Exchange.GetAnswer : Constants.Module.Exchange.SendAnswer);
      
      var processResult = true;
      
      // TODO: Shishkov_AI. Убрать обработку УОПа и ИОПа на УОП, т.к. это было актуально только для СБИС и сейчас этих служебных документов нет.
      // см. новость https://n.sbis.ru/news/853d0065-ee05-453f-afe8-12970b29f053
      // Обработка УОП.
      if (message.ReglamentDocuments.Any(r => r.DocumentType == ReglamentDocumentType.NotificationReceipt))
        processResult = this.ProcessNoteReceipt(message, queueItem, sender, isIncoming, businessUnitBox);
      
      // Подпись неформализованного документа.
      if (message.PrimaryDocuments.Any(x => x.SignStatus == NpoComputer.DCX.Common.SignStatus.Signed &&
                                       x.DocumentType == NpoComputer.DCX.Common.DocumentType.Nonformalized &&
                                       message.Signatures.Any(s => s.DocumentId == x.ServiceEntityId)) && processResult)
        processResult = this.ProcessNonformalizedSign(message, queueItem, client, box, sender, isIncoming, historyOperation, historyComment) && processResult;

      // Отказ в подписании.
      if (message.ReglamentDocuments.Any(r => r.DocumentType == ReglamentDocumentType.AmendmentRequest ||
                                         r.DocumentType == ReglamentDocumentType.InvoiceAmendmentRequest ||
                                         r.DocumentType == ReglamentDocumentType.Rejection) && processResult)
        processResult = this.ProcessReject(message, queueItem, isIncoming, box, historyOperation, historyComment);
      
      // Обработка ИОП.
      if (message.ReglamentDocuments.Any(r => r.DocumentType == ReglamentDocumentType.Receipt ||
                                         r.DocumentType == ReglamentDocumentType.InvoiceReceipt ||
                                         r.DocumentType == ReglamentDocumentType.NotificationOnReceiptOfNotificationReceipt) && processResult)
        processResult = this.ProcessReceiptNotice(message, queueItem, sender, isIncoming, businessUnitBox) && processResult;

      // Обработка ИОП на УОП.
      if (message.ReglamentDocuments.Any(r => r.DocumentType == ReglamentDocumentType.NotificationOnReceiptOfNotificationReceipt) && processResult)
        processResult = this.ProcessReceiptOfNoteReceipt(message, queueItem, sender, isIncoming, businessUnitBox) && processResult;

      // Обработка подтверждения доставки.
      if (message.ReglamentDocuments.Any(r => r.DocumentType == ReglamentDocumentType.InvoiceConfirmation) && processResult)
        processResult = this.ProcessInvoiceConfirmation(message, queueItem, organizationId, businessUnitBox) && processResult;
      
      // Титулы формализованных документов и подпись на СЧФ СБИС.
      if ((message.ReglamentDocuments.Any(x => this.GetSupportedReglamentDocumentTypes().Contains(x.DocumentType)) ||
           (message.PrimaryDocuments.Any(d => d.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfSeller) &&
            businessUnitBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis)) && processResult)
        processResult = this.ProcessFormalizedSign(message, queueItem, queueItems, isIncoming, box, historyOperation, historyComment) && processResult;
      
      // Если все регламентные документы в сообщении не поддерживаются - пропускаем и удаляем из очереди.
      if (message.ReglamentDocuments.All(x => !this.GetSupportedReglamentDocumentTypes().Contains(x.DocumentType)) &&
          !message.ReglamentDocuments.Any(x => this.GetSupportedServiceDocumentTypes().Contains(x.DocumentType)))
      {
        this.LogDebugFormat(message, queueItem, box, "Message processing was skipped. Message is marked as processed.");
        processResult = true;
      }
      
      return processResult;
    }
    
    #endregion

    #region Обработка ошибочных и непринимаемых сообщений

    /// <summary>
    /// Обработка ошибок подписания из диадока.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessDeliveryFailureNotification(IMessage message, IBoxBase box)
    {
      this.LogDebugFormat(message, box, "Execute ProcessDeliveryFailureNotification.");
      var parentMessageId = message.ReglamentDocuments.First(x => x.DocumentType == NpoComputer.DCX.Common.ReglamentDocumentType.DeliveryFailureNotification).ParentServiceEntityId;
      var rootBox = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);
      var exchangeDocumentInfo = ExchangeDocumentInfos.GetAll().Where(x => Equals(x.RootBox, rootBox) &&
                                                                      x.ServiceMessageId == parentMessageId).FirstOrDefault();
      
      if (exchangeDocumentInfo != null && exchangeDocumentInfo.Document != null)
      {
        var tracking = exchangeDocumentInfo.Document.Tracking.Where(x => x.ExternalLinkId == exchangeDocumentInfo.Id).FirstOrDefault();
        
        var performer = tracking != null
          ? tracking.DeliveredTo
          : ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(box, exchangeDocumentInfo.Counterparty, new List<IExchangeDocumentInfo>() { exchangeDocumentInfo });
        
        this.SendCannotDeliveryDocumentTask(exchangeDocumentInfo, performer, box);

        exchangeDocumentInfo.Document.ExchangeState = null;
        exchangeDocumentInfo.ExchangeState = null;
        exchangeDocumentInfo.Document.ExternalApprovalState = null;
        
        if (tracking != null)
        {
          // HACK: нельзя удалять запись выдачи с действием "Согласование с контрагентом", но любую другую можно.
          tracking.Action = Docflow.OfficialDocumentTracking.Action.Delivery;
          exchangeDocumentInfo.Document.Tracking.Remove(tracking);
        }
        
        exchangeDocumentInfo.Document.Save();
        exchangeDocumentInfo.Save();
        ExchangeDocumentInfos.Delete(exchangeDocumentInfo);
      }

      return true;
    }

    /// <summary>
    /// Отправка задачи о том, что документ не был доставлен КА, т.к. подпись не прошла проверку.
    /// </summary>
    /// <param name="exchangeDocumentInfo">Информация о документе.</param>
    /// <param name="performer">Исполнитель задания.</param>
    /// <param name="box">Абонентский ящик, на который получено сообщение.</param>
    protected virtual void SendCannotDeliveryDocumentTask(IExchangeDocumentInfo exchangeDocumentInfo, IEmployee performer, IBoxBase box)
    {
      var needReceive = ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box);
      if (needReceive)
      {
        var task = Workflow.SimpleTasks.Create();
        task.NeedsReview = false;
        var step = task.RouteSteps.AddNew();
        step.AssignmentType = Workflow.SimpleTask.AssignmentType.Notice;
        step.Performer = performer;

        this.GrantAccessRightsForUpperBoxResponsibles(exchangeDocumentInfo.Document, box);
        task.Attachments.Add(exchangeDocumentInfo.Document);

        var hyperlink = Hyperlinks.Get(exchangeDocumentInfo.Document);

        task.ActiveText =
          Resources.CannotDeliveryDocumentToCounterpartyFormat(hyperlink, ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box).Name);
        task.Subject = CutText(Resources.ErrorSendingDocumentToCounterpartyFormat(exchangeDocumentInfo.Document.Name),
                               task.Info.Properties.Subject.Length);
        task.Start();
      }
    }

    /// <summary>
    /// Обработать входящее сообщение, в котором содержатся только неподдерживаемые документы.
    /// </summary>
    /// <param name="message">Сообщение сервиса обмена.</param>
    /// <param name="sender">Контрагент-отправитель.</param>
    /// <param name="isIncoming">True - от контрагента, false - наше.</param>
    /// <param name="box">Ящик.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessMessageWithUnsupportedDocuments(IMessage message, ICounterparty sender, bool isIncoming, IBoxBase box)
    {
      this.LogDebugFormat(message, box, "Execute ProcessMessageWithUnsupportedDocuments.");
      var queueItem = MessageQueueItems.GetAll(q => q.ExternalId == message.ServiceMessageId && q.Box.Id == box.Id).FirstOrDefault();
      
      var needReceive = ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box);
      if (needReceive && isIncoming && queueItem != null && queueItem.DownloadSession == null)
      {
        var simpleTask = Sungero.Workflow.SimpleTasks.Create();
        var dateWithUTC = Sungero.Docflow.PublicFunctions.Module.GetDateWithUTCLabel(message.TimeStamp);
        simpleTask.Subject = Resources.NoticeSubjectFormat(sender, ExchangeCore.PublicFunctions.BoxBase.GetBusinessUnit(box), dateWithUTC,
                                                           ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box));
        simpleTask.Subject = CutText(simpleTask.Subject, simpleTask.Info.Properties.Subject.Length);
        simpleTask.ThreadSubject = Sungero.Exchange.Resources.NoticeThreadSubject;
        simpleTask.ActiveText = this.GenerateActiveTextFromUnsupportedDocuments(message.PrimaryDocuments, sender, isIncoming, box, message.TimeStamp, true);
        
        var step = simpleTask.RouteSteps.AddNew();
        step.AssignmentType = Workflow.SimpleTask.AssignmentType.Notice;
        step.Performer = ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(box, sender, null);
        
        simpleTask.Save();
        simpleTask.Start();
      }

      return true;
    }

    /// <summary>
    /// Сгенерировать текст по полученным формализованным документам, для заполнения задачи/задания.
    /// </summary>
    /// <param name="documents">Список формализованных документов.</param>
    /// <param name="sender">Контрагент.</param>
    /// <param name="isIncoming">Входящее сообщение.</param>
    /// <param name="box">Ящик.</param>
    /// <param name="messageDate">Время сообщения.</param>
    /// <param name="allUnsupported">Признак, что все документы не поддерживаемые.</param>
    /// <returns>Сгенерированный текст.</returns>
    protected virtual string GenerateActiveTextFromUnsupportedDocuments(IEnumerable<IDocument> documents, ICounterparty sender, bool isIncoming,
                                                                        IBoxBase box, DateTime messageDate, bool allUnsupported)
    {
      var documentList = new System.Text.StringBuilder();
      var documentNames = string.Empty;
      var otherDocuments = false;
      foreach (var document in documents)
      {
        var isXml = System.IO.Path.GetExtension(document.FileName).TrimStart('.').ToLower() == "xml";
        var generatedName = isXml ? GenerateUnsupportedDocumentName(document) : string.Empty;
        // Если имя не сформировалось, значит, пришел необработанный нами вид документа.
        if (!string.IsNullOrEmpty(generatedName))
          documentList.AppendLine(Resources.FormalizedDocumentNameFormat(generatedName));
        else
          otherDocuments = true;
      }
      
      if (!string.IsNullOrEmpty(documentList.ToString()))
      {
        // Добавить информацию о том, что пришли и другие документы.
        if (otherDocuments)
          documentList.AppendLine(Resources.OtherDocuments);
        
        documentNames = Resources.DocumentsListFormat(documentList);
      }
      
      if (allUnsupported)
        documentNames += this.ProcessBoundedDocuments(documents, null, isIncoming, box);

      documentNames += string.Format("{0}{0}", Environment.NewLine);
      
      var counterPartyLink = Hyperlinks.Get(sender);
      if (isIncoming)
        documentNames += Resources.ReceiptNeededActiveTextFormat(counterPartyLink, messageDate.ToShortDateString(), messageDate.ToShortTimeString());
      else
        documentNames += Resources.ReceiptNeededOutgoingActiveTextFormat(counterPartyLink, messageDate.ToShortDateString(), messageDate.ToShortTimeString());
      documentNames += Environment.NewLine;
      
      var exchangeService = ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box);
      return Resources.NoticeActiveTextFormat(documentNames, Resources.LinkToPersonalDataFormat(exchangeService.Name, exchangeService.LogonUrl));
    }

    /// <summary>
    /// Получить наименование формализованного документа, полученного из сервиса обмена.
    /// </summary>
    /// <param name="document">Документ из сервиса обмена.</param>
    /// <returns>Наименование, если получилось сформировать, иначе - пустая строка.</returns>
    private static string GenerateUnsupportedDocumentName(IDocument document)
    {
      System.Xml.Linq.XDocument xdoc;
      try
      {
        xdoc = System.Xml.Linq.XDocument.Load(new System.IO.MemoryStream(document.Content));
      }
      catch (Exception e)
      {
        Logger.ErrorFormat("Exchange. Failed to load XML: {0}", e.Message);
        return string.Empty;
      }
      
      RemoveNamespaces(xdoc);
      var documentType = string.Empty;
      var documentNumber = string.Empty;
      var documentDate = string.Empty;
      
      var fileElement = xdoc.Element("Файл");
      if (fileElement == null)
        return string.Empty;
      
      var docElement = fileElement.Element("Документ");
      if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.Act)
      {
        var actInfo = docElement.Element("СвАктИ");
        documentType = GetAttributeValueByName(actInfo, "НаимПервДок");
        documentNumber = GetAttributeValueByName(actInfo, "НомАкт");
        documentDate = GetAttributeValueByName(actInfo, "ДатаАкт");
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.Waybill)
      {
        var waybillInfo = docElement.Element("СвТНО");
        documentType = GetAttributeValueByName(waybillInfo, "НаимПервДок");
        
        var waybill = waybillInfo.Element("ТН");
        documentNumber = GetAttributeValueByName(waybill, "НомТН");
        documentDate = GetAttributeValueByName(waybill, "ДатаТН");
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.Invoice ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferDopSeller ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfSeller ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfDopSeller)
      {
        var invoiceInfo = docElement.Element("СвСчФакт");
        documentNumber = GetAttributeValueByName(invoiceInfo, "НомерСчФ");
        documentDate = GetAttributeValueByName(invoiceInfo, "ДатаСчФ");
        documentType = GetAttributeValueByName(docElement, "НаимДокОпр");
        if (string.IsNullOrEmpty(documentType))
          documentType = "Счет-фактура";
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.InvoiceCorrection ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferDopCorrectionSeller ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfCorrectionSeller ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfDopCorrectionSeller)
      {
        var invoiceCorrectionInfo = docElement.Element("СвКСчФ");
        documentNumber = GetAttributeValueByName(invoiceCorrectionInfo, "НомерКСчФ");
        documentDate = GetAttributeValueByName(invoiceCorrectionInfo, "ДатаКСчФ");
        documentType = GetAttributeValueByName(docElement, "НаимДокОпр");
        if (string.IsNullOrEmpty(documentType))
          documentType = "Корректировочный счет-фактура";
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.InvoiceCorrectionRevision ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferDopCorrectionRevisionSeller ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfCorrectionRevisionSeller ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfDopCorrectionRevisionSeller)
      {
        var invoiceCorrectionRevisionInfo = docElement.Element("СвКСчФ").Element("ИспрКСчФ");
        documentNumber = GetAttributeValueByName(invoiceCorrectionRevisionInfo, "НомИспрКСчФ");
        documentDate = GetAttributeValueByName(invoiceCorrectionRevisionInfo, "ДатаИспрКСчФ");
        documentType = GetAttributeValueByName(docElement, "НаимДокОпр");
        if (string.IsNullOrEmpty(documentType))
          documentType = "Исправление корректировочного счета-фактуры";
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.InvoiceRevision ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferDopRevisionSeller ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfRevisionSeller ||
               document.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfDopRevisionSeller)
      {
        var invoiceRevisionInfo = docElement.Element("СвСчФакт").Element("ИспрСчФ");
        documentNumber = GetAttributeValueByName(invoiceRevisionInfo, "НомИспрСчФ");
        documentDate = GetAttributeValueByName(invoiceRevisionInfo, "ДатаИспрСчФ");
        documentType = GetAttributeValueByName(docElement, "НаимДокОпр");
        if (string.IsNullOrEmpty(documentType))
          documentType = "Исправление счета-фактуры";
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.GoodsTransferSeller)
      {
        var goodsTransferSellerInfo = docElement.Element("СвДокПТПрКроме").Element("СвДокПТПр");
        documentNumber = GetAttributeValueByName(goodsTransferSellerInfo.Element("ИдентДок"), "НомДокПТ");
        documentDate = GetAttributeValueByName(goodsTransferSellerInfo.Element("ИдентДок"), "ДатаДокПТ");
        documentType = GetAttributeValueByName(goodsTransferSellerInfo.Element("НаимДок"), "НаимДокОпр");
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.GoodsTransferRevisionSeller)
      {
        var goodsTransferRevisionSellerInfo = docElement.Element("СвДокПТПрКроме").Element("СвДокПТПр");
        documentNumber = GetAttributeValueByName(goodsTransferRevisionSellerInfo.Element("ИспрДокПТ"), "НомДокПТ");
        documentDate = GetAttributeValueByName(goodsTransferRevisionSellerInfo.Element("ИспрДокПТ"), "ДатаДокПТ");
        documentType = GetAttributeValueByName(goodsTransferRevisionSellerInfo.Element("НаимДок"), "НаимДокОпр");
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.WorksTransferSeller)
      {
        var worksTransferSellerInfo = docElement.Element("СвДокПРУ");
        documentNumber = GetAttributeValueByName(worksTransferSellerInfo.Element("ИдентДок"), "НомДокПРУ");
        documentDate = GetAttributeValueByName(worksTransferSellerInfo.Element("ИдентДок"), "ДатаДокПРУ");
        documentType = GetAttributeValueByName(worksTransferSellerInfo.Element("НаимДок"), "НаимДокОпр");
      }
      else if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.WorksTransferRevisionSeller)
      {
        var generalTransferRevisionSellerInfo = docElement.Element("СвДокПРУ");
        documentNumber = GetAttributeValueByName(generalTransferRevisionSellerInfo.Element("ИспрДокПРУ"), "НомИспрДокПРУ");
        documentDate = GetAttributeValueByName(generalTransferRevisionSellerInfo.Element("ИспрДокПРУ"), "ДатаИспрДокПРУ");
        documentType = GetAttributeValueByName(generalTransferRevisionSellerInfo.Element("НаимДок"), "НаимДокОпр");
      }
      else
      {
        return string.Empty;
      }
      
      return Resources.FormalizedDocumentTemplateNameFormat(documentType, documentNumber, documentDate);
    }

    #endregion

    #region Обработка сообщения с новыми документами
    
    #region Процессинг сообщения с новыми документами

    /// <summary>
    /// Добавить в информацию о документе сессию исторической загрузки.
    /// </summary>
    /// <param name="documentInfo">Информация о документе.</param>
    /// <param name="session">Сессия исторической загрузки.</param>
    protected virtual void ExchangeDocumentInfoSetSession(IExchangeDocumentInfo documentInfo, Sungero.ExchangeCore.IHistoricalMessagesDownloadSession session)
    {
      this.LogDebugFormat(documentInfo, "Execute ExchangeDocumentInfoSetSession.");
      documentInfo = ExchangeDocumentInfos.Get(documentInfo.Id);
      documentInfo.DownloadSession = session;
      documentInfo.Save();
    }
    
    /// <summary>
    /// Обработать новое входящее сообщение.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="isIncoming">True - от контрагента, false - наше.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessNewIncomingMessage(IMessage message, IMessageQueueItem queueItem, ICounterparty sender, bool isIncoming, IBoxBase box)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessNewIncomingMessage.");
      var infos = new List<IExchangeDocumentInfo>();
      var processedDocumentTypes = this.GetSupportedPrimaryDocumentTypes();
      IExchangeDocumentInfo info = null;

      // Обработка документов в сообщении.
      var processingDocuments = message.PrimaryDocuments.Where(x => processedDocumentTypes.Contains(x.DocumentType.Value)).ToList();
      foreach (var processingDocument in processingDocuments)
      {
        if (this.NeedCreateDocumentFromNewIncomingMessage(message, processingDocument, sender, isIncoming, box))
        {
          var serviceCounterpartyId = isIncoming ? message.Sender.Organization.OrganizationId : message.Receiver.Organization.OrganizationId;
          var exchangeDocument = this.GetOrCreateNewExchangeDocument(processingDocument, sender, serviceCounterpartyId, isIncoming, message.TimeStamp, box);
          this.SignDocumentFromNewIncomingMessage(message, exchangeDocument, processingDocument, box);
          info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, processingDocument.ServiceEntityId);
          
          if (exchangeDocument.LastVersion.PublicBody.Size == 0)
            Docflow.PublicFunctions.Module.GeneratePublicBodyForExchangeDocument(exchangeDocument, info.VersionId.Value, exchangeDocument.ExchangeState);
          infos.Add(info);
        }
        
        if (queueItem.DownloadSession != null)
        {
          info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, processingDocument.ServiceEntityId);
          if (info != null && info.DownloadSession == null)
            this.ExchangeDocumentInfoSetSession(info, queueItem.DownloadSession);
        }
        
      }
      
      return this.ProcessDocumentsFromNewIncomingMessage(message, queueItem, infos, processingDocuments, sender, isIncoming, box);
    }

    /// <summary>
    /// Обработать документы, созданные из сообщения.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="infos">Информация по обработанным документам.</param>
    /// <param name="processingDocuments">Обрабатываемые документы.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="isIncoming">True - от контрагента, false - наше.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessDocumentsFromNewIncomingMessage(IMessage message, IMessageQueueItem queueItem, List<IExchangeDocumentInfo> infos,
                                                                  List<IDocument> processingDocuments, ICounterparty sender, bool isIncoming, IBoxBase box)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessDocumentsFromNewIncomingMessage.");
      // Если не создано ни одного документа - завершаем обработку.
      var documents = infos.Where(i => i.Document != null).Select(i => i.Document).ToList();
      if (!documents.Any())
      {
        queueItem.ProcessingStatus = ExchangeCore.MessageQueueItem.ProcessingStatus.Processed;
        queueItem.Save();
        return true;
      }
      
      this.FillCounterpartyDataFromNewMessage(message, infos, documents, sender, isIncoming);
      
      foreach (var doc in documents)
        this.GrantAccessRightsForUpperBoxResponsibles(doc, box);

      var exchangeTaskActiveTextBoundedDocuments = this.ProcessBoundedDocuments(processingDocuments, documents, isIncoming, box);

      var needReceive = this.NeedReceiveDocumentProcessingTask(box, message);
      if (needReceive && queueItem.DownloadSession == null)
        return this.StartExchangeTask(message, infos, sender, isIncoming, box, exchangeTaskActiveTextBoundedDocuments);

      return true;
    }

    /// <summary>
    /// Проверка, что нужно заносить документы в систему.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="document">Обрабатываемый документ.</param>
    /// <param name="sender">Контрагент по документу.</param>
    /// <param name="isIncoming">True - от контрагента, false - наше.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <returns>True - если нужно создавать документ, иначе - false.</returns>
    /// <remarks>Создает информацию по документу, если тот будет загружен позже.</remarks>
    protected virtual bool NeedCreateDocumentFromNewIncomingMessage(IMessage message, IDocument document, ICounterparty sender, bool isIncoming, IBoxBase box)
    {
      if (document.RevocationStatus == NpoComputer.DCX.Common.RevocationStatus.RevocationAccepted)
        return false;
      
      // Если документ может быть подписан, то создаем инфо, чтобы потом найти сообщение и подпись.
      if (!isIncoming && document.DocumentType == DocumentType.Nonformalized &&
          (document.SignStatus == NpoComputer.DCX.Common.SignStatus.Waiting ||
           document.SignStatus == NpoComputer.DCX.Common.SignStatus.None))
      {
        var withoutDoc = GetOrCreateExchangeInfoWithoutDocument(document, sender, message.Receiver.Organization.OrganizationId, isIncoming, message.TimeStamp, box);
        withoutDoc.Save();
        return false;
      }

      // Не грузим отправленные и не подписанные сообщения, кроме формализованных документов.
      if (!isIncoming && document.SignStatus != NpoComputer.DCX.Common.SignStatus.Signed &&
          document.DocumentType == DocumentType.Nonformalized)
        return false;
      
      // Не грузим сообщения с отказом.
      if (document.SignStatus == NpoComputer.DCX.Common.SignStatus.Rejected)
        return false;

      // Если документ нами и отправлен - задачу отправлять уже не надо.
      var info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, document.ServiceEntityId);
      if (!isIncoming && info != null)
        return false;
      
      return true;
    }

    /// <summary>
    /// Подписать документ из сервиса обмена.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="signedDocument">Подписываемый документ.</param>
    /// <param name="serviceDocument">Документ в сервисе обмена.</param>
    /// <param name="box">Абонентский ящик.</param>
    protected virtual void SignDocumentFromNewIncomingMessage(IMessage message, IOfficialDocument signedDocument, IDocument serviceDocument, IBoxBase box)
    {
      var info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, serviceDocument.ServiceEntityId);
      this.LogDebugFormat(info, "Execute SignDocumentFromNewIncomingMessage.");
      var signatures = message.Signatures.Where(x => x.DocumentId == serviceDocument.ServiceEntityId);
      var addedThumbprints = Signatures.Get(signedDocument.LastVersion)
        .Where(s => s.SignCertificate != null)
        .Select(x => x.SignCertificate.Thumbprint);
      var accountDocument = Docflow.AccountingDocumentBases.As(signedDocument);
      foreach (var signature in signatures)
      {
        var certificateInfo = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(signature.Content);
        var signatoryInfo = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(certificateInfo.SubjectInfo);
        
        var signatureIsAlreadyAdded = addedThumbprints.Any(x => x.Equals(certificateInfo.Thumbprint));
        if (!signatureIsAlreadyAdded)
        {
          this.SignDocument(info, signature, signedDocument.LastVersion, signatoryInfo, message.TimeStamp);

          if (accountDocument != null)
          {
            var lastSignature = this.GetLastDocumentSignature(accountDocument);
            accountDocument.SellerSignatureId = lastSignature.Id;
          }
        }
      }
    }
    
    /// <summary>
    /// Обработка связанных документов.
    /// </summary>
    /// <param name="documents">Документы сервиса обмена.</param>
    /// <param name="officialDocuments">Документы в RX.</param>
    /// <param name="fromCounterparty">True, если документы от контрагента.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <returns>Текст с информацией о связанных документах.</returns>
    protected virtual string ProcessBoundedDocuments(IEnumerable<IDocument> documents, IList<IOfficialDocument> officialDocuments,
                                                     bool fromCounterparty, IBoxBase box)
    {
      this.LogDebugFormat(box, "Execute ProcessBoundedDocuments.");
      officialDocuments = officialDocuments ?? new List<IOfficialDocument>();

      var bounds = new List<string>();
      foreach (var document in documents.Where(x => x.BoundDocuments != null))
        bounds.AddRange(document.BoundDocuments.Select(x => x.DocumentId));

      bounds = bounds.Distinct().ToList();

      var links = new List<string>();
      var hasBound = false;
      foreach (var bound in bounds)
      {
        var info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, bound);
        if (info != null && info.Document != null)
        {
          var relatedDocs = info.Document.Relations.GetRelatedFrom(Constants.Module.SimpleRelationRelationName);
          
          if (officialDocuments.Any())
          {
            foreach (var offdoc in officialDocuments.Where(x => !Equals(x, info.Document)).Where(x => relatedDocs.All(d => !Equals(d, x))))
            {
              if (Docflow.AccountingDocumentBases.Is(offdoc) && Docflow.AccountingDocumentBases.As(offdoc).IsAdjustment == true)
                continue;
              
              this.AddRelations(offdoc, info);
            }
            info.Document.Save();
          }
          hasBound = true;
          var link = Hyperlinks.Get(info.Document);
          if (!officialDocuments.Contains(info.Document))
            links.Add(link);
        }
      }
      
      if (hasBound)
      {
        var text = fromCounterparty ?
          Resources.NoticeCounterpartyBoundDocument :
          Resources.NoticeOurBoundDocument;
        if (links.Any())
        {
          var separator = string.Format(", {0}", Environment.NewLine);
          var allLinks = Environment.NewLine + string.Join(separator, links);
          text = fromCounterparty ?
            Resources.NoticeCounterpartyBoundDocumentWithLinksFormat(allLinks) :
            Resources.NoticeOurBoundDocumentWithLinksFormat(allLinks);
        }
        return string.Format("{0}{0}{1}", Environment.NewLine, text);
      }

      return string.Empty;
    }
    
    /// <summary>
    /// Выдать права на документ ответственным за вышестоящие абонентские ящики.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="box">Абонентский ящик.</param>
    protected virtual void GrantAccessRightsForUpperBoxResponsibles(IOfficialDocument document, IBoxBase box)
    {
      var boxes = new List<IBoxBase>() { box };
      if (!ExchangeCore.BusinessUnitBoxes.Is(box))
      {
        var departmentBox = ExchangeCore.DepartmentBoxes.As(box);
        boxes.Add(departmentBox.RootBox);
        
        ExchangeCore.IBoxBase parentBox = departmentBox.ParentBox;
        while (!ExchangeCore.BusinessUnitBoxes.Is(parentBox))
        {
          departmentBox = ExchangeCore.DepartmentBoxes.As(parentBox);
          boxes.Add(departmentBox);
          parentBox = departmentBox.ParentBox;
        }
      }
      
      var responsibles = new List<Sungero.Company.IEmployee>();
      foreach (var currentBox in boxes)
      {
        if (currentBox.Responsible != null)
          responsibles.Add(currentBox.Responsible);
        
        var info = Functions.ExchangeDocumentInfo.GetLastDocumentInfo(document);
        var computedResponsible = ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(currentBox, info.Counterparty, new List<Exchange.IExchangeDocumentInfo>() { info });
        if (computedResponsible != null && !responsibles.Contains(computedResponsible))
          responsibles.Add(computedResponsible);
        
        var allCompanies = Docflow.PublicFunctions.OfficialDocument.GetCounterparties(document);
        if (allCompanies != null)
        {
          var companies = allCompanies.Where(c => Parties.CompanyBases.Is(c));
          responsibles.AddRange(companies.Where(c => Parties.CompanyBases.As(c).Responsible != null).Select(c => Parties.CompanyBases.As(c).Responsible));
        }
      }
      
      foreach (var responsible in responsibles)
      {
        if (!document.AccessRights.IsGrantedDirectly(DefaultAccessRightsTypes.FullAccess, responsible))
          document.AccessRights.Grant(responsible, DefaultAccessRightsTypes.FullAccess);
      }

      document.AccessRights.Save();
    }
    
    /// <summary>
    /// Заполнить подписывающего и основание со стороны контрагента.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="infos">Информация по обработанным документам.</param>
    /// <param name="documents">Документы сервиса обмена.</param>
    /// <param name="counterparty">Отправитель.</param>
    /// <param name="isIncoming">True - от контрагента, false - наше.</param>
    /// <remarks>Если сообщение исходящее, то подписывающий и основание со стороны контрагента не заполняются.</remarks>
    protected virtual void FillCounterpartyDataFromNewMessage(IMessage message, List<IExchangeDocumentInfo> infos,
                                                              List<IOfficialDocument> documents, ICounterparty counterparty, bool isIncoming)
    {
      this.LogDebugFormat(message, "Execute FillCounterpartyDataFromNewMessage.");
      
      // Если сообщение исходящее, то заполнять подписывающего и основание со стороны контрагента не надо.
      if (!isIncoming)
        return;
      
      foreach (var doc in documents)
      {
        var info = infos.FirstOrDefault(x => x.Document != null && Equals(doc, x.Document));
        this.FillCounterpartySignatoryAndSigningReason(message, info.ServiceDocumentId, doc, counterparty);
      }
    }
    
    /// <summary>
    /// Заполнить подписывающего и основание со стороны контрагента для ответа по документу.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="serviceDocumentId">ИД документа в сервисе обмена.</param>
    /// <param name="document">Документ сервиса обмена.</param>
    /// <param name="counterparty">Отправитель.</param>
    /// <param name="isIncoming">True - от контрагента, false - наше.</param>
    /// <remarks>Если сообщение исходящее и не является ответом, то подписывающий и основание со стороны контрагента не заполняются.</remarks>
    protected virtual void FillCounterpartyDataFromReplyMessage(IMessage message, string serviceDocumentId,
                                                                IOfficialDocument document, ICounterparty counterparty, bool isIncoming)
    {
      this.LogDebugFormat(message, "Execute FillCounterpartyDataFromReplyMessage.");
      
      // Если сообщение исходящее, то заполнять подписывающего и основание со стороны контрагента не надо.
      if (!isIncoming)
        return;
      
      this.FillCounterpartySignatoryAndSigningReason(message, serviceDocumentId, document, counterparty);
    }
    
    /// <summary>
    /// Заполнить подписывающего и основание со стороны контрагента в отдельном документе.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="serviceDocumentId">ИД документа в сервисе обмена.</param>
    /// <param name="doc">Документ сервиса обмена.</param>
    /// <param name="counterparty">Отправитель.</param>
    /// <remarks>Поля должны заполняться только при работе с входящими документами или с ответами на исходящие.</remarks>
    protected virtual void FillCounterpartySignatoryAndSigningReason(IMessage message, string serviceDocumentId,
                                                                     IOfficialDocument doc, ICounterparty counterparty)
    {
      this.LogDebugFormat(message, "Execute FillCounterpartySignatoryAndSigningReason.");
      
      var signature = message.Signatures.Where(x => x.DocumentId == serviceDocumentId).FirstOrDefault();
      if (signature != null)
      {
        var certificateInfo = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(signature.Content);
        var signatoryName = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(certificateInfo.SubjectInfo);
        var signatory = Parties.PublicFunctions.Contact.GetContactByName(signatoryName, counterparty);
        
        if (signatory != null)
          Sungero.Docflow.PublicFunctions.OfficialDocument.FillCounterpartySignatory(doc, signatory);
        
        // Заполнить основание со стороны контрагента по формату: "<Основание подписания> (<Подписант>)".
        var signingReason = string.Empty;
        var unifiedRegNumber = signature.FormalizedPoAUnifiedRegNumber;
        // Если подписали по МЧД, то взять её номер.
        if (!string.IsNullOrWhiteSpace(unifiedRegNumber))
          signingReason = string.Format(Exchange.Resources.CounterpartyPowerOfAttorney, unifiedRegNumber, signatoryName);
        
        // Если МЧД нет и документ формализованный, то получить информацию об основании из xml.
        if (string.IsNullOrWhiteSpace(signingReason))
        {
          if (message.IsReply)
            signingReason = this.GetSigningReasonFromReglamentDocumentXml(message, serviceDocumentId, doc, signatoryName);
          else
            signingReason = this.GetSigningReasonFromPrimaryDocumentXml(message, serviceDocumentId, doc, signatoryName);
        }
        
        // Если не удалось получить основание, то заполняем - "Должностные обязанности".
        if (string.IsNullOrWhiteSpace(signingReason))
          signingReason = SignatureSettings.Resources.DutiesDisplayNameFormat(signatoryName);
        
        Sungero.Docflow.PublicFunctions.OfficialDocument.FillCounterpartySigningReason(doc, signingReason);
        doc.Save();
      }
    }
    
    /// <summary>
    /// Получить основание подписания из XML основного документа.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="serviceDocumentId">ИД документа в сервисе обмена.</param>
    /// <param name="doc">Документ сервиса обмена.</param>
    /// <param name="signatoryName">Имя подписывающего.</param>
    /// <returns>Основание контрагента, если не получилось найти, то пустая строка.</returns>
    protected virtual string GetSigningReasonFromPrimaryDocumentXml(IMessage message, string serviceDocumentId, IOfficialDocument doc, string signatoryName)
    {
      var processingDocument = message.PrimaryDocuments.Where(x => x.ServiceEntityId == serviceDocumentId).FirstOrDefault();
      
      if (processingDocument == null || !AccountingDocumentBases.Is(doc) || AccountingDocumentBases.As(doc).IsFormalized != true)
        return string.Empty;
      
      var xdoc = System.Xml.Linq.XDocument.Load(new System.IO.MemoryStream(processingDocument.Content));
      var documentInfo = xdoc.Element("Файл").Element("Документ");
      var signingReason = this.GetSigningReasonFromXml(documentInfo);
      if (!string.IsNullOrWhiteSpace(signingReason))
        return Sungero.Exchange.Resources.SigningReasonDisplayValueFormat(signingReason, signatoryName);
      
      return string.Empty;
    }
    
    /// <summary>
    /// Получить основание подписания из XML регламентного документа.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="serviceDocumentId">ИД документа в сервисе обмена.</param>
    /// <param name="doc">Документ сервиса обмена.</param>
    /// <param name="signatoryName">Имя подписывающего.</param>
    /// <returns>Основание контрагента, если не получилось найти, то пустая строка.</returns>
    protected virtual string GetSigningReasonFromReglamentDocumentXml(IMessage message, string serviceDocumentId, IOfficialDocument doc, string signatoryName)
    {
      // Рассматриваем регламентные документы, т.к. работаем с титулами, которые есть только у формализованных документов.
      var processingDocument = message.ReglamentDocuments.Where(x => x.ServiceEntityId == serviceDocumentId).FirstOrDefault();
      
      if (processingDocument == null || !AccountingDocumentBases.Is(doc) || AccountingDocumentBases.As(doc).IsFormalized != true)
        return string.Empty;
      
      var xdoc = System.Xml.Linq.XDocument.Load(new System.IO.MemoryStream(processingDocument.Content));
      var documentInfo = xdoc.Element("Файл").Element("ИнфПок");
      // Для актов и накладных в старом формате (ДПТ, ДПРР) информация о документе находится в другом элементе.
      if (documentInfo == null)
        documentInfo = xdoc.Element("Файл").Element("Документ");
      var signingReason = this.GetSigningReasonFromXml(documentInfo);
      if (!string.IsNullOrWhiteSpace(signingReason))
        return Sungero.Exchange.Resources.SigningReasonDisplayValueFormat(signingReason, signatoryName);
      
      return string.Empty;
    }
    
    /// <summary>
    /// Получить основание подписания из XML-документа.
    /// </summary>
    /// <param name="documentInfo">Элемент с информацией о документе.</param>
    /// <returns>Основание. Если не смогли получить, то пустая строка.</returns>
    protected virtual string GetSigningReasonFromXml(XElement documentInfo)
    {
      if (documentInfo == null)
        return string.Empty;
      
      // Попытаться получить основание подписания из атрибута с основанием полномочий.
      var signatoryInfo = documentInfo.Element("Подписант");
      if (signatoryInfo != null)
      {
        var signingReason = GetAttributeValueByName(signatoryInfo, "ОснПолн");
        if (!string.IsNullOrWhiteSpace(signingReason))
          return signingReason;
        
        signingReason = GetAttributeValueByName(signatoryInfo, "ОснПолнПодп");
        if (!string.IsNullOrWhiteSpace(signingReason))
          return signingReason;
      }
      
      return string.Empty;
    }
    
    private static IExchangeDocumentInfo GetOrCreateExchangeInfoWithoutDocument(IDocument document, ICounterparty sender, string serviceCounterpartyId,
                                                                                bool isIncoming, DateTime messageDate, IBoxBase box)
    {
      var info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, document.ServiceEntityId);
      if (info != null)
        return info;
      
      var newInfo = ExchangeDocumentInfos.Create();
      newInfo.Box = box;
      newInfo.RootBox = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);
      newInfo.ServiceDocumentId = document.ServiceEntityId;
      newInfo.MessageType = isIncoming ? Exchange.ExchangeDocumentInfo.MessageType.Incoming : Exchange.ExchangeDocumentInfo.MessageType.Outgoing;
      newInfo.ServiceMessageId = document.ServiceMessageId;
      newInfo.Counterparty = sender;
      newInfo.ServiceCounterpartyId = serviceCounterpartyId;
      newInfo.MessageDate = ToTenantTime(messageDate);
      newInfo.NeedSign = document.NeedSign;
      return newInfo;
    }
    
    /// <summary>
    /// Связать документы типом связи "Прочие".
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="relatedExchangeDocumentInfo">Информация о связываемом документе обмена.</param>
    public virtual void AddRelations(IOfficialDocument document, IExchangeDocumentInfo relatedExchangeDocumentInfo)
    {
      document.Relations.AddFromOrUpdate(Constants.Module.SimpleRelationRelationName, null, relatedExchangeDocumentInfo.Document);
      document.Save();
    }
    
    #endregion

    #region Создание и заполнение документа

    /// <summary>
    /// Получить или создать документ из сервиса обмена.
    /// </summary>
    /// <param name="document">Документ из сообщения.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="serviceCounterpartyId">Id контрагента в сервисе обмена.</param>
    /// <param name="isIncoming">Признак документа от контрагента.</param>
    /// <param name="messageDate">Дата сообщения.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <returns>Документ RX.</returns>
    protected virtual IOfficialDocument GetOrCreateNewExchangeDocument(IDocument document, ICounterparty sender, string serviceCounterpartyId,
                                                                       bool isIncoming, DateTime messageDate, IBoxBase box)
    {
      var exchangeDoc = Docflow.OfficialDocuments.Null;
      
      var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, document.ServiceEntityId);
      
      if (exchangeDocumentInfo != null)
        exchangeDoc = exchangeDocumentInfo.Document;
      
      if (exchangeDoc == null)
      {
        var documentFullName = CommonLibrary.FileUtils.NormalizeFileName(document.FileName);
        var documentName = System.IO.Path.GetFileNameWithoutExtension(documentFullName).TrimEnd('.');
        documentName = Functions.Module.GetValidFileName(documentName);
        var newInfo = GetOrCreateExchangeInfoWithoutDocument(document, sender, serviceCounterpartyId, isIncoming, messageDate, box);
        var convertedDocument = document as NpoComputer.DCX.Common.Document;
        var documentComment = string.IsNullOrEmpty(document.Comment) ? string.Empty : Resources.DocumentCommentFormat(document.Comment).ToString();

        if (string.IsNullOrEmpty(documentName))
          documentName = documentFullName;
        var taxDocumentClassifierCode = string.Empty;
        var functionUTD = string.Empty;

        // Неформализованный документ.
        if (document.DocumentType == DocumentType.Nonformalized)
          exchangeDoc = this.CreateExchangeDocument(newInfo, sender, box, documentName, documentComment);
        else
        {
          var taxDocumentClassifier = GetTaxDocumentClassifier(document);
          taxDocumentClassifierCode = taxDocumentClassifier.TaxDocumentClassifierCode;
          functionUTD = taxDocumentClassifier.TaxDocumentClassifierFunction;
        }

        // Товарная накладная.
        if (document.DocumentType == DocumentType.Waybill &&
            taxDocumentClassifierCode != Constants.Module.TaxDocumentClassifier.GoodsTransferSeller &&
            taxDocumentClassifierCode != Constants.Module.TaxDocumentClassifier.UniversalTransferDocumentSeller)
        {
          var waybill = FinancialFunction.Module.CreateWaybillDocument(documentComment, box, sender, newInfo);
          
          var documentInfo = this.GetInfoFromXML(document, sender);
          
          SetDocumentTotalAmount(waybill, documentInfo);
          
          exchangeDoc = waybill;
        }

        // Cчет-фактура.
        if (document.DocumentType == DocumentType.Invoice ||
            document.DocumentType == DocumentType.InvoiceCorrection ||
            document.DocumentType == DocumentType.InvoiceCorrectionRevision ||
            document.DocumentType == DocumentType.InvoiceRevision ||
            document.DocumentType == DocumentType.GeneralTransferSchfSeller ||
            document.DocumentType == DocumentType.GeneralTransferSchfCorrectionSeller ||
            document.DocumentType == DocumentType.GeneralTransferSchfCorrectionRevisionSeller ||
            document.DocumentType == DocumentType.GeneralTransferSchfRevisionSeller)
        {
          exchangeDoc = this.CreateTaxInvoice(convertedDocument, newInfo, sender, isIncoming, box);
        }

        // Акт.
        if (document.DocumentType == DocumentType.Act &&
            taxDocumentClassifierCode != Constants.Module.TaxDocumentClassifier.WorksTransferSeller &&
            taxDocumentClassifierCode != Constants.Module.TaxDocumentClassifier.UniversalTransferDocumentSeller)
        {
          var statement = FinancialFunction.Module.CreateContractStatementDocument(documentComment, box, sender, newInfo);
          
          var documentInfo = this.GetInfoFromXML(document, sender);
          
          SetDocumentTotalAmount(statement, documentInfo);
          
          exchangeDoc = statement;
        }

        // Универсальный передаточный документ.
        var universalDocumentTaxInvoiceAndBasicTypes = new List<NpoComputer.DCX.Common.DocumentType>()
        {
          DocumentType.GeneralTransferSchfDopSeller,
          DocumentType.GeneralTransferSchfDopRevisionSeller,
          DocumentType.GeneralTransferSchfDopCorrectionSeller,
          DocumentType.GeneralTransferSchfDopCorrectionRevisionSeller
        };
        var universalDocumentBasicTypes = new List<NpoComputer.DCX.Common.DocumentType>()
        {
          DocumentType.GeneralTransferDopSeller,
          DocumentType.GeneralTransferDopRevisionSeller,
          DocumentType.GeneralTransferDopCorrectionSeller,
          DocumentType.GeneralTransferDopCorrectionRevisionSeller
        };
        
        var isUTD155ByXmlContent = taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.UniversalTransferDocumentSeller155 &&
          functionUTD == Constants.Module.FunctionUTDDop;
        
        var isUTDByXmlContent = taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.UniversalTransferDocumentSeller &&
          functionUTD == Constants.Module.FunctionUTDDop;
        
        var isUTDCorrectionByXmlContent = taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.UniversalCorrectionDocumentSeller &&
          functionUTD == Constants.Module.FunctionUTDDopCorrection;
        
        if (universalDocumentTaxInvoiceAndBasicTypes.Contains(document.DocumentType.Value) ||
            universalDocumentBasicTypes.Contains(document.DocumentType.Value) ||
            isUTD155ByXmlContent || isUTDByXmlContent || isUTDCorrectionByXmlContent)
        {
          exchangeDoc = this.CreateUniversalTransferDocument(convertedDocument, newInfo, sender, box, universalDocumentTaxInvoiceAndBasicTypes);
        }
        
        // ДПРР.
        if (document.DocumentType == DocumentType.WorksTransferSeller ||
            document.DocumentType == DocumentType.WorksTransferRevisionSeller ||
            taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.WorksTransferSeller)
        {
          exchangeDoc = this.CreateContractStatementDocument(convertedDocument, newInfo, sender, box);
        }
        
        // ДПТ.
        if (document.DocumentType == DocumentType.GoodsTransferSeller ||
            document.DocumentType == DocumentType.GoodsTransferRevisionSeller ||
            taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.GoodsTransferSeller)
        {
          exchangeDoc = this.CreateWaybillDocument(convertedDocument, newInfo, sender, box);
        }

        if (isIncoming)
          exchangeDoc.ExternalApprovalState = Docflow.OfficialDocument.ExternalApprovalState.Signed;
        else
          exchangeDoc.InternalApprovalState = Docflow.OfficialDocument.InternalApprovalState.Signed;
        
        newInfo.Document = exchangeDoc;
        
        if (ExchangeCore.DepartmentBoxes.Is(box))
          exchangeDoc.Department = ExchangeCore.PublicFunctions.BoxBase.GetDepartment(box);
        
        // Сбрасываем статус эл. обмена, чтобы при создании версии не сбрасывался статус согласования с КА.
        exchangeDoc.ExchangeState = null;

        this.CreateExchangeDocumentVersion(convertedDocument, newInfo, exchangeDoc, sender, isIncoming, box, documentFullName);
        
        newInfo.Save();
      }
      
      return exchangeDoc;
    }

    /// <summary>
    /// Создать накладную.
    /// </summary>
    /// <param name="document">Документ из сервиса обмена.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="sender">Контрагент-отправитель.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <returns>Созданный документ.</returns>
    protected virtual IOfficialDocument CreateWaybillDocument(Document document, IExchangeDocumentInfo info, ICounterparty sender, IBoxBase box)
    {
      var documentInfo = this.GetInfoFromXML(document, sender);
      var waybill = FinancialFunction.Module.CreateWaybillDocument(documentInfo.Comment, box, sender, info);
      waybill.LeadingDocument = documentInfo.Contract;
      waybill.FormalizedServiceType = Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer;

      if (documentInfo.IsRevision)
        waybill.IsRevision = true;

      SetDocumentTotalAmount(waybill, documentInfo);

      if (!string.IsNullOrEmpty(documentInfo.DocumentNumber))
        document.FormalizedNumber = documentInfo.DocumentNumber;

      DateTime parsedDate;
      if (!string.IsNullOrEmpty(documentInfo.DocumentDate) &&
          TryParseDate(documentInfo, out parsedDate))
        document.FormalizedDate = parsedDate;
      return waybill;
    }

    /// <summary>
    /// Создать акт.
    /// </summary>
    /// <param name="document">Документ из сервиса обмена.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="sender">Контрагент-отправитель.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <returns>Созданный документ.</returns>
    protected virtual IOfficialDocument CreateContractStatementDocument(Document document, IExchangeDocumentInfo info, ICounterparty sender,
                                                                        IBoxBase box)
    {
      var documentInfo = this.GetInfoFromXML(document, sender);
      var statement = FinancialFunction.Module.CreateContractStatementDocument(documentInfo.Comment, box, sender, info);
      statement.LeadingDocument = documentInfo.Contract;
      statement.FormalizedServiceType = Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer;

      if (documentInfo.IsRevision)
        statement.IsRevision = true;

      SetDocumentTotalAmount(statement, documentInfo);

      if (!string.IsNullOrEmpty(documentInfo.DocumentNumber))
        document.FormalizedNumber = documentInfo.DocumentNumber;

      DateTime parsedDate;
      if (!string.IsNullOrEmpty(documentInfo.DocumentDate) &&
          TryParseDate(documentInfo, out parsedDate))
        document.FormalizedDate = parsedDate;

      if (!info.NeedSign.Value)
        statement.LifeCycleState = Docflow.OfficialDocument.LifeCycleState.Active;
      return statement;
    }

    /// <summary>
    /// Создать УПД.
    /// </summary>
    /// <param name="document">Документ из сервиса обмена.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="sender">Контрагент-отправитель.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <param name="universalDocumentTaxInvoiceAndBasicTypes">Тип документа обмена.</param>
    /// <returns>Созданный документ.</returns>
    protected virtual IOfficialDocument CreateUniversalTransferDocument(Document document, IExchangeDocumentInfo info, ICounterparty sender,
                                                                        IBoxBase box, List<DocumentType> universalDocumentTaxInvoiceAndBasicTypes)
    {
      var documentInfo = this.GetInfoFromXML(document, sender);
      var accounting = universalDocumentTaxInvoiceAndBasicTypes.Contains(document.DocumentType.Value)
        ? FinancialFunction.Module.CreateUniversalTaxInvoiceAndBasic(documentInfo.Comment, box, sender, documentInfo.IsAdjustment, documentInfo.Corrected,
                                                                     info)
        : FinancialFunction.Module.CreateUniversalBasic(documentInfo.Comment, box, sender, documentInfo.IsAdjustment, documentInfo.Corrected, info);

      if (documentInfo.IsRevision)
        accounting.IsRevision = true;

      if (documentInfo.Function != null)
        accounting.FormalizedFunction = documentInfo.Function;

      if (documentInfo.СorrectionRevisionParentDocument != null)
        accounting.Relations.Add(Constants.Module.SimpleRelationRelationName, documentInfo.СorrectionRevisionParentDocument);

      SetDocumentTotalAmount(accounting, documentInfo);

      if (!string.IsNullOrEmpty(documentInfo.DocumentNumber))
        document.FormalizedNumber = documentInfo.DocumentNumber;

      DateTime parsedDate;
      if (!string.IsNullOrEmpty(documentInfo.DocumentDate) &&
          TryParseDate(documentInfo, out parsedDate))
        document.FormalizedDate = parsedDate;

      if (!info.NeedSign.Value)
        accounting.LifeCycleState = Docflow.OfficialDocument.LifeCycleState.Active;
      return accounting;
    }

    /// <summary>
    /// Создать счет-фактуру.
    /// </summary>
    /// <param name="document">Документ из сервиса обмена.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="sender">Контрагент-отправитель.</param>
    /// <param name="isIncoming">True, если счет-фактура полученный, иначе - выставленный.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <returns>Созданный документ.</returns>
    protected virtual IOfficialDocument CreateTaxInvoice(Document document, IExchangeDocumentInfo info, ICounterparty sender, bool isIncoming,
                                                         IBoxBase box)
    {
      var documentInfo = this.GetInfoFromXML(document, sender);
      Docflow.IAccountingDocumentBase accounting = null;
      if (isIncoming)
        accounting = FinancialFunction.Module.CreateIncomingTaxInvoiceDocument(documentInfo.Comment, box, sender, documentInfo.IsAdjustment,
                                                                               documentInfo.Corrected, info);
      else
        accounting = FinancialFunction.Module.CreateOutgoingTaxInvoiceDocument(documentInfo.Comment, box, sender, documentInfo.IsAdjustment,
                                                                               documentInfo.Corrected, info);

      if (documentInfo.IsRevision)
        accounting.IsRevision = true;

      if (documentInfo.Function != null)
        accounting.FormalizedFunction = documentInfo.Function;

      if (documentInfo.СorrectionRevisionParentDocument != null)
        accounting.Relations.Add(Constants.Module.SimpleRelationRelationName, documentInfo.СorrectionRevisionParentDocument);

      if (document.DocumentType == DocumentType.GeneralTransferSchfSeller ||
          document.DocumentType == DocumentType.GeneralTransferSchfCorrectionSeller ||
          document.DocumentType == DocumentType.GeneralTransferSchfCorrectionRevisionSeller ||
          document.DocumentType == DocumentType.GeneralTransferSchfRevisionSeller)
        accounting.FormalizedServiceType = Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer;

      SetDocumentTotalAmount(accounting, documentInfo);

      if (!string.IsNullOrEmpty(documentInfo.DocumentNumber))
        document.FormalizedNumber = documentInfo.DocumentNumber;

      DateTime parsedDate;
      if (!string.IsNullOrEmpty(documentInfo.DocumentDate) &&
          TryParseDate(documentInfo, out parsedDate))
        document.FormalizedDate = parsedDate;
      return accounting;
    }

    /// <summary>
    /// Создать документ обмена.
    /// </summary>
    /// <param name="info">Информация о документе.</param>
    /// <param name="counterparty">Контрагент.</param>
    /// <param name="box">Ящик обмена.</param>
    /// <param name="fileName">Имя файла.</param>
    /// <param name="comment">Комментарий.</param>
    /// <returns>Созданный документ.</returns>
    protected virtual IOfficialDocument CreateExchangeDocument(IExchangeDocumentInfo info, ICounterparty counterparty, IBoxBase box,
                                                               string fileName, string comment)
    {
      var exchangeDoc = Docflow.ExchangeDocuments.Create();
      
      if (fileName.Length > exchangeDoc.Info.Properties.Name.Length)
        fileName = fileName.Substring(0, exchangeDoc.Info.Properties.Name.Length);
      
      if (!string.IsNullOrEmpty(comment) && comment.Length > exchangeDoc.Info.Properties.Note.Length)
        comment = comment.Substring(0, exchangeDoc.Info.Properties.Note.Length);
      
      exchangeDoc.Name = fileName;
      exchangeDoc.Subject = fileName;
      exchangeDoc.Note = comment;
      exchangeDoc.BusinessUnit = ExchangeCore.PublicFunctions.BoxBase.GetBusinessUnit(box);
      exchangeDoc.BusinessUnitBox = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);
      exchangeDoc.Counterparty = counterparty;
      
      return exchangeDoc;
    }

    /// <summary>
    /// Создать версию документа.
    /// </summary>
    /// <param name="document">Документ из сервиса обмена.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="exchangeDoc">Документ в RX.</param>
    /// <param name="sender">Контрагент-отправитель.</param>
    /// <param name="isIncoming">True, если документ входящий, иначе - false.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <param name="documentFullName">Полное имя документа.</param>
    protected virtual void CreateExchangeDocumentVersion(Document document, IExchangeDocumentInfo info, IOfficialDocument exchangeDoc,
                                                         ICounterparty sender, bool isIncoming, IBoxBase box, string documentFullName)
    {
      using (var memory = new System.IO.MemoryStream(document.Content))
      {
        IElectronicDocumentVersions version = null;
        // Выключить error-логирование при доступе к зашифрованной версии.
        AccessRights.SuppressSecurityEvents(
          () =>
          {
            // Создать версию. Сохранить в версию.
            exchangeDoc.CreateVersion();
            version = exchangeDoc.LastVersion;
            version.Body.Write(memory);
          });
        version.AssociatedApplication = GetOrCreateAssociatedApplicationByDocumentName(documentFullName);
        info.VersionId = version.Id;
        var accountingDoc = Docflow.AccountingDocumentBases.As(exchangeDoc);
        if (accountingDoc != null && accountingDoc.IsFormalized == true)
        {
          accountingDoc.BusinessUnitBox = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);
          var isRegistered =
            Docflow.PublicFunctions.OfficialDocument.TryExternalRegister(accountingDoc, document.FormalizedNumber,
                                                                         document.FormalizedDate);

          accountingDoc.SellerTitleId = version.Id;
          accountingDoc.Subject = string.Empty;

          if (FinancialArchive.Waybills.Is(accountingDoc) ||
              FinancialArchive.ContractStatements.Is(accountingDoc) ||
              FinancialArchive.UniversalTransferDocuments.Is(accountingDoc))
            version.Note = FinancialArchive.Resources.SellerTitleVersionNote;

          if (exchangeDoc.DocumentKind.NumberingType == Docflow.DocumentKind.NumberingType.NotNumerable || !isRegistered)
          {
            if (document.DocumentType == DocumentType.Invoice ||
                document.DocumentType == DocumentType.InvoiceRevision ||
                document.DocumentType == DocumentType.GeneralTransferSchfSeller ||
                document.DocumentType == DocumentType.GeneralTransferSchfRevisionSeller)
              exchangeDoc.Note = Sungero.Exchange.Resources.TaxInvoiceFormat(document.FormalizedNumber, document.FormalizedDateString) +
                Environment.NewLine + exchangeDoc.Note;
            else if (document.DocumentType == DocumentType.InvoiceCorrection ||
                     document.DocumentType == DocumentType.InvoiceCorrectionRevision ||
                     document.DocumentType == DocumentType.GeneralTransferSchfCorrectionSeller ||
                     document.DocumentType == DocumentType.GeneralTransferSchfCorrectionRevisionSeller)
              exchangeDoc.Note =
                Sungero.Exchange.Resources.TaxInvoiceCorrectionFormat(document.FormalizedNumber, document.FormalizedDateString) +
                Environment.NewLine + exchangeDoc.Note;
            else
              exchangeDoc.Note =
                Sungero.Exchange.Resources.IncomingNotNumeratedDocumentNoteFormat(document.FormalizedDateString,
                                                                                  document.FormalizedNumber) +
                Environment.NewLine + exchangeDoc.Note;
          }
        }

        MarkDocumentAsSended(info, exchangeDoc, sender, isIncoming, box, document.SignStatus);

        exchangeDoc.Save();

        this.GrantAccessRightsForUpperBoxResponsibles(exchangeDoc, box);
      }
    }

    private static void CreateVersionFromExchangeDocument(IOfficialDocument document, IDocument exchangeDocument, IAssociatedApplication application)
    {
      using (var memory = new System.IO.MemoryStream(exchangeDocument.Content))
      {
        // Выключить error-логирование при доступе к зашифрованной версии.
        AccessRights.SuppressSecurityEvents(
          () =>
          {
            // Создать версию. Сохранить в версию.
            document.CreateVersion();
            var version = document.LastVersion;
            version.Body.Write(memory);
            version.AssociatedApplication = application;
            document.Save();
          });
      }
    }
    
    private static void SetDocumentTotalAmount(IAccountingDocumentBase document, FormalizedDocumentXML documentInfo)
    {
      if (!string.IsNullOrEmpty(documentInfo.CurrencyCode))
      {
        var currency = Commons.Currencies.GetAll().Where(x => x.NumericCode == documentInfo.CurrencyCode).FirstOrDefault();
        
        if (currency != null)
        {
          document.Currency = currency;
          document.TotalAmount = documentInfo.TotalAmount;
        }
      }
    }
    
    private static bool TryParseDate(FormalizedDocumentXML documentInfo, out DateTime parsedDate)
    {
      var datePattern = "dd.MM.yyyy";
      var dateStyle = System.Globalization.DateTimeStyles.None;
      return DateTime.TryParseExact(documentInfo.DocumentDate, datePattern, null, dateStyle, out parsedDate);
    }

    /// <summary>
    /// Получить информацию из xml тела документа.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="sender">Контрагент.</param>
    /// <returns>Информацию из xml тела документа.</returns>
    protected virtual FormalizedDocumentXML GetInfoFromXML(IDocument document, ICounterparty sender)
    {
      var xdoc = System.Xml.Linq.XDocument.Load(new System.IO.MemoryStream(document.Content));
      RemoveNamespaces(xdoc);
      var documentComment = string.IsNullOrEmpty(document.Comment) ? string.Empty : Resources.DocumentCommentFormat(document.Comment).ToString();
      var corrected = Docflow.AccountingDocumentBases.Null;
      var contract = Docflow.ContractualDocumentBases.Null;
      var correctionRevisionParentDocument = Docflow.AccountingDocumentBases.Null;
      var documentNumber = string.Empty;
      var documentDate = string.Empty;
      var correctedDocumentNumber = string.Empty;
      var correctedDocumentDate = string.Empty;
      var currencyCode = string.Empty;
      var totalAmount = string.Empty;
      double totalAmountNumeric = 0;
      
      var comment = documentComment;
      if (!string.IsNullOrEmpty(comment) && document.DocumentType != DocumentType.Invoice)
        comment += Environment.NewLine;
      
      // Функция документа, для УПД\УКД.
      Enumeration? function = null;
      
      var isAdjustment = false;
      
      // Признак того, что это исправление (но не исправление корректировки, это отдельный тип).
      var isRevision = false;
      
      // А это любое исправление для галочки в документе.
      var isAnyRevision = false;
      
      // Определяем КНД документа для уточнения его типа.
      var taxDocumentClassifierCode = GetTaxDocumentClassifier(document).TaxDocumentClassifierCode;
      
      // Если пришел с типом старого акта, а в теле КНД от УПД, заносим как УПД.
      var isUTDDop = taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.UniversalTransferDocumentSeller &&
        (document.DocumentType == DocumentType.Act || document.DocumentType == DocumentType.Waybill);
      var isRevisionUTDDop = isUTDDop && xdoc.Descendants("ИспрСчФ").Any();
      if (document.DocumentType == DocumentType.Invoice ||
          document.DocumentType == DocumentType.GeneralTransferSchfSeller ||
          document.DocumentType == DocumentType.GeneralTransferSchfDopSeller ||
          document.DocumentType == DocumentType.GeneralTransferDopSeller ||
          (isUTDDop && !isRevisionUTDDop))
      {
        var taxInvoiceInfo = xdoc.Element("Файл").Element("Документ").Element("СвСчФакт");
        documentNumber = GetAttributeValueByName(taxInvoiceInfo, "НомерСчФ");
        documentDate = GetAttributeValueByName(taxInvoiceInfo, "ДатаСчФ");
        
        currencyCode = GetAttributeValueByName(taxInvoiceInfo, "КодОКВ");
        var totalAmountElement = xdoc.Element("Файл").Element("Документ").Element("ТаблСчФакт").Element("ВсегоОпл");
        totalAmount = GetAttributeValueByName(totalAmountElement, "СтТовУчНалВсего");
        
        if (document.DocumentType == DocumentType.GeneralTransferSchfSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.Schf;
        if (document.DocumentType == DocumentType.GeneralTransferSchfDopSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.SchfDop;
        if (document.DocumentType == DocumentType.GeneralTransferDopSeller || isUTDDop)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.Dop;
      }

      if (document.DocumentType == DocumentType.InvoiceCorrection ||
          document.DocumentType == DocumentType.GeneralTransferSchfCorrectionSeller ||
          document.DocumentType == DocumentType.GeneralTransferSchfDopCorrectionSeller ||
          document.DocumentType == DocumentType.GeneralTransferDopCorrectionSeller)
      {
        var taxInvoiceInfo = xdoc.Element("Файл").Element("Документ").Element("СвКСчФ");
        documentNumber = GetAttributeValueByName(taxInvoiceInfo, "НомерКСчФ");
        documentDate = GetAttributeValueByName(taxInvoiceInfo, "ДатаКСчФ");
        var correctedTaxInvoiceInfo = taxInvoiceInfo.Element("СчФ");
        correctedDocumentNumber = GetAttributeValueByName(correctedTaxInvoiceInfo, "НомерСчФ");
        correctedDocumentDate = GetAttributeValueByName(correctedTaxInvoiceInfo, "ДатаСчФ");
        comment += Resources.TaxInvoiceToFormat(correctedDocumentNumber, correctedDocumentDate);
        
        isAdjustment = true;
        
        if (document.DocumentType == DocumentType.GeneralTransferSchfCorrectionSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.Schf;
        if (document.DocumentType == DocumentType.GeneralTransferSchfDopCorrectionSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.SchfDop;
        if (document.DocumentType == DocumentType.GeneralTransferDopCorrectionSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.Dop;
      }
      
      if (document.DocumentType == DocumentType.InvoiceCorrectionRevision ||
          document.DocumentType == DocumentType.GeneralTransferSchfCorrectionRevisionSeller ||
          document.DocumentType == DocumentType.GeneralTransferSchfDopCorrectionRevisionSeller ||
          document.DocumentType == DocumentType.GeneralTransferDopCorrectionRevisionSeller)
      {
        var taxInvoiceInfo = xdoc.Element("Файл").Element("Документ").Element("СвКСчФ");
        documentNumber = GetAttributeValueByName(taxInvoiceInfo, "НомерКСчФ");
        documentDate = GetAttributeValueByName(taxInvoiceInfo, "ДатаКСчФ");
        var correctedTaxInvoiceInfo = taxInvoiceInfo.Element("ИспрКСчФ");
        correctedDocumentNumber = GetAttributeValueByName(correctedTaxInvoiceInfo, "НомИспрКСчФ");
        correctedDocumentDate = GetAttributeValueByName(correctedTaxInvoiceInfo, "ДатаИспрКСчФ");
        comment += Resources.TaxInvoiceRevisionFormat(correctedDocumentNumber, correctedDocumentDate);

        isAdjustment = true;
        isAnyRevision = true;
        
        if (document.DocumentType == DocumentType.GeneralTransferSchfCorrectionRevisionSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.Schf;
        if (document.DocumentType == DocumentType.GeneralTransferSchfDopCorrectionRevisionSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.SchfDop;
        if (document.DocumentType == DocumentType.GeneralTransferDopCorrectionRevisionSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.Dop;
      }
      
      if (document.DocumentType == DocumentType.InvoiceRevision ||
          document.DocumentType == DocumentType.GeneralTransferSchfRevisionSeller ||
          document.DocumentType == DocumentType.GeneralTransferSchfDopRevisionSeller ||
          document.DocumentType == DocumentType.GeneralTransferDopRevisionSeller ||
          isRevisionUTDDop)
      {
        var taxInvoiceInfo = xdoc.Element("Файл").Element("Документ").Element("СвСчФакт");
        var revisionTaxInvoiceInfo = taxInvoiceInfo.Element("ИспрСчФ");

        // Если это исправление, то номер должен быть как у первичного СФ.
        documentNumber = GetAttributeValueByName(taxInvoiceInfo, "НомерСчФ");
        documentDate = GetAttributeValueByName(taxInvoiceInfo, "ДатаСчФ");
        
        // В примечание запишем номер и дату исправления.
        var initialDocumentNumber = GetAttributeValueByName(revisionTaxInvoiceInfo, "НомИспрСчФ");
        var initialDocumentDate = GetAttributeValueByName(revisionTaxInvoiceInfo, "ДатаИспрСчФ");
        
        comment += Resources.TaxInvoiceRevisionFormat(initialDocumentNumber, initialDocumentDate);

        currencyCode = GetAttributeValueByName(taxInvoiceInfo, "КодОКВ");
        var totalAmountElement = xdoc.Element("Файл").Element("Документ").Element("ТаблСчФакт").Element("ВсегоОпл");
        totalAmount = GetAttributeValueByName(totalAmountElement, "СтТовУчНалВсего");
        
        isRevision = true;
        isAnyRevision = true;
        
        if (document.DocumentType == DocumentType.GeneralTransferSchfRevisionSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.Schf;
        if (document.DocumentType == DocumentType.GeneralTransferSchfDopRevisionSeller)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.SchfDop;
        if (document.DocumentType == DocumentType.GeneralTransferDopRevisionSeller || isRevisionUTDDop)
          function = Docflow.AccountingDocumentBase.FormalizedFunction.Dop;
      }
      
      var isGoodsTransferSeller = taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.GoodsTransferSeller;
      var isRevisionGoodsTransferSeller = xdoc.Descendants("ИспрДокПТ").Any();
      
      // Проверка типа документа по КНД, т.к. из Диадока приходит ДПТ с типом торг-12.
      if (document.DocumentType == DocumentType.GoodsTransferSeller || (isGoodsTransferSeller && !isRevisionGoodsTransferSeller))
      {
        var goodsTransferSellerInfo =
          xdoc.Element("Файл").Element("Документ").Element("СвДокПТПрКроме").Element("СвДокПТПр").Element("ИдентДок");
        documentNumber = GetAttributeValueByName(goodsTransferSellerInfo, "НомДокПТ");
        documentDate = GetAttributeValueByName(goodsTransferSellerInfo, "ДатаДокПТ");
        
        var currencyCodeElement = xdoc.Element("Файл").Element("Документ").Element("СвДокПТПрКроме").Element("СвДокПТПр").Element("ДенИзм");
        currencyCode = GetAttributeValueByName(currencyCodeElement, "КодОКВ");
        var totalAmountElement = xdoc.Element("Файл").Element("Документ").Element("СвДокПТПрКроме").Element("СодФХЖ2").Element("Всего");
        totalAmount = GetAttributeValueByName(totalAmountElement, "СтУчНДСВс");
      }

      if (document.DocumentType == DocumentType.GoodsTransferRevisionSeller || (isGoodsTransferSeller && isRevisionGoodsTransferSeller))
      {
        var goodsTransferSellerInfo =
          xdoc.Element("Файл").Element("Документ").Element("СвДокПТПрКроме").Element("СвДокПТПр");
        var goodsTransferRevisionSellerInfo = goodsTransferSellerInfo.Element("ИспрДокПТ");
        
        var initialDocumentNumber = GetAttributeValueByName(goodsTransferRevisionSellerInfo, "НомИспрДокПТ");
        var initialDocumentDate = GetAttributeValueByName(goodsTransferRevisionSellerInfo, "ДатаИспрДокПТ");
        
        documentNumber = GetAttributeValueByName(goodsTransferSellerInfo.Element("ИдентДок"), "НомДокПТ");
        documentDate = GetAttributeValueByName(goodsTransferSellerInfo.Element("ИдентДок"), "ДатаДокПТ");
        
        comment += Resources.TaxInvoiceRevisionFormat(initialDocumentNumber, initialDocumentDate);
        
        var currencyCodeElement = xdoc.Element("Файл").Element("Документ").Element("СвДокПТПрКроме").Element("СвДокПТПр").Element("ДенИзм");
        currencyCode = GetAttributeValueByName(currencyCodeElement, "КодОКВ");
        var totalAmountElement = xdoc.Element("Файл").Element("Документ").Element("СвДокПТПрКроме").Element("СодФХЖ2").Element("Всего");
        totalAmount = GetAttributeValueByName(totalAmountElement, "СтУчНДСВс");
        
        isRevision = true;
        isAnyRevision = true;
      }
      
      var isWorksTransferSeller = taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.WorksTransferSeller;
      var isRevisionWorksTransferSeller = xdoc.Descendants("ИспрДокПРУ").Any();
      
      // Проверка типа документа по КНД, т.к. из Диадока приходит ДПРР с типом акт старого формата.
      if (document.DocumentType == DocumentType.WorksTransferSeller || (isWorksTransferSeller && !isRevisionWorksTransferSeller))
      {
        var worksTransferSellerInfo =
          xdoc.Element("Файл").Element("Документ").Element("СвДокПРУ").Element("ИдентДок");
        documentNumber = GetAttributeValueByName(worksTransferSellerInfo, "НомДокПРУ");
        documentDate = GetAttributeValueByName(worksTransferSellerInfo, "ДатаДокПРУ");
        
        var currencyCodeElement = xdoc.Element("Файл").Element("Документ").Element("СвДокПРУ").Element("ДенИзм");
        currencyCode = GetAttributeValueByName(currencyCodeElement, "КодОКВ");
        var totalAmountElement = xdoc.Element("Файл").Element("Документ").Element("СвДокПРУ").Element("СодФХЖ1").Element("ОписРабот");
        totalAmount = GetAttributeValueByName(totalAmountElement, "СтУчНДСИт");
      }
      
      if (document.DocumentType == DocumentType.WorksTransferRevisionSeller || (isWorksTransferSeller && isRevisionWorksTransferSeller))
      {
        var worksTransferSellerInfo =
          xdoc.Element("Файл").Element("Документ").Element("СвДокПРУ");
        var worksTransferRevisionSellerInfo = worksTransferSellerInfo.Element("ИспрДокПРУ");
        
        var initialDocumentNumber = GetAttributeValueByName(worksTransferRevisionSellerInfo, "НомИспрДокПРУ");
        var initialDocumentDate = GetAttributeValueByName(worksTransferRevisionSellerInfo, "ДатаИспрДокПРУ");
        
        documentNumber = GetAttributeValueByName(worksTransferSellerInfo.Element("ИдентДок"), "НомДокПРУ");
        documentDate = GetAttributeValueByName(worksTransferSellerInfo.Element("ИдентДок"), "ДатаДокПРУ");
        comment += Resources.TaxInvoiceRevisionFormat(initialDocumentNumber, initialDocumentDate);
        
        var currencyCodeElement = xdoc.Element("Файл").Element("Документ").Element("СвДокПРУ").Element("ДенИзм");
        currencyCode = GetAttributeValueByName(currencyCodeElement, "КодОКВ");
        var totalAmountElement = xdoc.Element("Файл").Element("Документ").Element("СвДокПРУ").Element("СодФХЖ1").Element("ОписРабот");
        totalAmount = GetAttributeValueByName(totalAmountElement, "СтУчНДСИт");
        
        isRevision = true;
        isAnyRevision = true;
      }
      
      // Проверка типа документа по КНД, т.к. из Диадока приходит ДПТ с типом торг-12.
      if (document.DocumentType == DocumentType.Waybill && taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.Waybill)
      {
        var waybillTotalAmountInfo = xdoc.Element("Файл").Element("Документ").Element("СвТНО")
          .Element("ТН").Element("Таблица").Element("ВсегоНакл");
        
        currencyCode = Constants.Module.RoubleCurrencyCode;
        totalAmount = GetAttributeValueByName(waybillTotalAmountInfo, "СумУчНДСВс");
      }
      
      // Проверка типа документа по КНД, т.к. из Диадока приходит ДПРР с типом акт старого формата.
      if (document.DocumentType == DocumentType.Act && taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.Act)
      {
        var actTotalAmountInfo = xdoc.Element("Файл").Element("Документ").Element("СвАктИ").Element("ОписРабот");
        
        currencyCode = Constants.Module.RoubleCurrencyCode;
        totalAmount = GetAttributeValueByName(actTotalAmountInfo, "СумУчНДСИт");
      }
      
      var parentDocument = Docflow.AccountingDocumentBases.Null;
      if (isAdjustment || isRevision)
      {
        var parentDocumentInfo = Sungero.Exchange.ExchangeDocumentInfos.GetAll()
          .Where(x => x.ServiceDocumentId == document.ParentServiceEntityId && Equals(x.Counterparty, sender))
          .FirstOrDefault();

        if (parentDocumentInfo != null && parentDocumentInfo.Document != null)
        {
          parentDocument = Sungero.Docflow.AccountingDocumentBases.As(parentDocumentInfo.Document);
        }
        else if (!string.IsNullOrEmpty(correctedDocumentNumber))
        {
          var datePattern = "dd.MM.yyyy";
          var dateStyle = System.Globalization.DateTimeStyles.None;
          DateTime parsedCorrectedDocumentDate;
          if (!string.IsNullOrEmpty(correctedDocumentDate) &&
              DateTime.TryParseExact(correctedDocumentDate, datePattern, null, dateStyle, out parsedCorrectedDocumentDate))
          {
            parentDocument = Sungero.Docflow.AccountingDocumentBases.GetAll()
              .Where(x => x.RegistrationNumber == correctedDocumentNumber &&
                     x.RegistrationDate == parsedCorrectedDocumentDate && Equals(x.Counterparty, sender))
              .FirstOrDefault();
          }
        }
      }

      if (isAdjustment)
      {
        // Исправление корректировки корректирует первоначальный документ, между корректировкой и исправлением корректировки связь с типом "Прочие".
        if (parentDocument != null &&
            (document.DocumentType == DocumentType.InvoiceCorrectionRevision ||
             document.DocumentType == DocumentType.GeneralTransferSchfCorrectionRevisionSeller ||
             document.DocumentType == DocumentType.GeneralTransferSchfDopCorrectionRevisionSeller ||
             document.DocumentType == DocumentType.GeneralTransferDopCorrectionRevisionSeller))
        {
          correctionRevisionParentDocument = parentDocument;
          corrected = correctionRevisionParentDocument.Corrected;
        }
        else
        {
          corrected = parentDocument;
        }
        
        if (corrected != null)
          contract = corrected.LeadingDocument;
        
        if (corrected != null &&
            document.DocumentType != DocumentType.InvoiceCorrectionRevision &&
            document.DocumentType != DocumentType.GeneralTransferSchfCorrectionRevisionSeller &&
            document.DocumentType != DocumentType.GeneralTransferSchfDopCorrectionRevisionSeller &&
            document.DocumentType != DocumentType.GeneralTransferDopCorrectionRevisionSeller)
          comment = documentComment;
      }
      
      if (isRevision && parentDocument != null)
        contract = parentDocument.LeadingDocument;
      
      if (!string.IsNullOrEmpty(totalAmount) && !string.IsNullOrEmpty(currencyCode))
      {
        // Если распарсить не получилось, валюту не указываем в документе.
        if (!double.TryParse(totalAmount, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out totalAmountNumeric))
          currencyCode = string.Empty;
      }
      
      return Structures.Module.FormalizedDocumentXML.Create(documentNumber, documentDate, isAdjustment, comment, corrected, contract,
                                                            correctionRevisionParentDocument, currencyCode, totalAmountNumeric, isAnyRevision, function);
    }
    
    private static Sungero.Exchange.Structures.Module.ITaxDocumentClassifier GetTaxDocumentClassifier(IDocument document)
    {
      return GetTaxDocumentClassifierByContent(new System.IO.MemoryStream(document.Content));
    }

    /// <summary>
    /// Получить КНД по содержимому документа.
    /// </summary>
    /// <param name="content">Содержимое документа.</param>
    /// <returns>КНД.</returns>
    [Public]
    public static Sungero.Exchange.Structures.Module.ITaxDocumentClassifier GetTaxDocumentClassifierByContent(System.IO.Stream content)
    {
      var xdoc = System.Xml.Linq.XDocument.Load(content);
      RemoveNamespaces(xdoc);
      // Определяем КНД документа для уточнения его типа.
      var documentSection = xdoc.Element("Файл").Element("Документ");
      var taxDocumentClassifierCode = GetAttributeValueByName(documentSection, "КНД");
      var functionUTD = string.Empty;
      
      if (taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.UniversalTransferDocumentSeller ||
          taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.UniversalTransferDocumentSeller155 ||
          taxDocumentClassifierCode == Constants.Module.TaxDocumentClassifier.UniversalCorrectionDocumentSeller)
      {
        functionUTD = GetAttributeValueByName(documentSection, "Функция");
      }
      return TaxDocumentClassifier.Create(taxDocumentClassifierCode, functionUTD);
    }

    /// <summary>
    /// Получить печатную форму из сервиса обмена.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="versionId">Версия документа.</param>
    /// <returns>Признак успешности загрузки печатной формы из сервиса обмена.</returns>
    [Public]
    public virtual bool GeneratePublicBodyFromService(IOfficialDocument document, int versionId)
    {
      var documentInfo = Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.GetExDocumentInfoFromVersion(document, versionId);
      if (documentInfo == null)
        return false;
      
      var client = ExchangeCore.PublicFunctions.BusinessUnitBox.GetPublicClient(documentInfo.RootBox) as NpoComputer.DCX.ClientApi.Client;
      var printedForm = client.GetDocumentPrintedForm(documentInfo.ServiceMessageId, documentInfo.ServiceDocumentId);
      
      if (printedForm != null)
      {
        using (var memory = new System.IO.MemoryStream(printedForm))
        {
          // Выключить error-логирование при доступе к зашифрованной версии.
          AccessRights.SuppressSecurityEvents(
            () =>
            {
              var version = document.Versions.FirstOrDefault(ver => Equals(ver.Id, versionId));
              version.PublicBody.Write(memory);
              version.AssociatedApplication = Content.AssociatedApplications.GetByExtension("pdf");
              document.Save();
            });
        }
        return true;
      }
      
      return false;
    }
    
    #endregion

    #region Отправка задач

    /// <summary>
    /// Стартовать задачу на обработку.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="infos">Информация по обработке документов.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="isIncoming">True - от контрагента, false - наше.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="exchangeTaskActiveTextBoundedDocuments">Часть ActiveText для формирования задачи на обработку для связанных документов.</param>
    /// <returns>Признак успешности отправки задачи.</returns>
    protected virtual bool StartExchangeTask(IMessage message, List<IExchangeDocumentInfo> infos, ICounterparty sender,
                                             bool isIncoming, IBoxBase box, string exchangeTaskActiveTextBoundedDocuments)
    {
      var task = this.CreateExchangeTask(message, infos, sender, isIncoming, box, exchangeTaskActiveTextBoundedDocuments);
      if (task != null)
      {
        if (task.Started == null)
          task.Start();
        return true;
      }

      return false;
    }
    
    /// <summary>
    /// Создать задачу на обработку входящих документов эл. обмена.
    /// </summary>
    /// <param name="infos">Информация по документам.</param>
    /// <param name="counterparty">КА из сервиса обмена.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <param name="incomeDate">Дата получения.</param>
    /// <param name="mainProcessingTask">Главная задача.</param>
    /// <returns>Задача на обработку входящих документов эл. обмена.</returns>
    public IExchangeDocumentProcessingTask CreateExchangeTask(List<IExchangeDocumentInfo> infos, ICounterparty counterparty,
                                                              IBoxBase box, DateTime incomeDate, ITask mainProcessingTask)
    {
      
      var task = mainProcessingTask == null ?
        Sungero.Exchange.ExchangeDocumentProcessingTasks.Create() :
        Sungero.Exchange.ExchangeDocumentProcessingTasks.CreateAsSubtask(mainProcessingTask);
      
      task.Box = box;
      task.Counterparty = counterparty;
      task.ExchangeService = ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box);
      task.Assignee = ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(box, counterparty, infos);
      task.Deadline = Sungero.ExchangeCore.PublicFunctions.BoxBase.GetProcessingTaskDeadline(box, task.Assignee);
      task.IncomeDate = incomeDate;
      var isIncoming = infos.FirstOrDefault().MessageType == Exchange.ExchangeDocumentInfo.MessageType.Incoming;
      task.IsIncoming = isIncoming;
      
      // Если задача не ответственному за текущий ящик, сообщить об этом исполнителю.
      if (Equals(box.Routing, ExchangeCore.DepartmentBox.Routing.BoxResponsible) && !Equals(task.Assignee, box.Responsible) && ExchangeCore.DepartmentBoxes.Is(box))
      {
        var departmentBox = ExchangeCore.DepartmentBoxes.As(box);
        var department = departmentBox.Department;
        var departmentName = department != null ? department.Name : departmentBox.ServiceName;
        
        if (box.Status == ExchangeCore.BoxBase.Status.Closed)
          task.ActiveText = ExchangeDocumentProcessingTasks.Resources.DocumentSentToClosedBoxFormat(departmentName);
        else
          task.ActiveText = ExchangeDocumentProcessingTasks.Resources.DocumentSentToAnotherResponsibleFormat(departmentName);
        
        task.ActiveText += Environment.NewLine;
      }
      
      using (Sungero.Core.CultureInfoExtensions.SwitchTo(TenantInfo.Culture))
        task.Subject = this.GenerateExchangeTaskSubject(task);
      task.Save();
      return task;
    }

    /// <summary>
    /// Создать задачу на обработку.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="infos">Информация по документам, созданным из сообщения, по которому формируется задача.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="isIncoming">True - от контрагента, false - наше.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="exchangeTaskActiveTextBoundedDocuments">Часть ActiveText для формирования задачи на обработку для связанных документов.</param>
    /// <returns>Задача.</returns>
    protected virtual IExchangeDocumentProcessingTask CreateExchangeTask(IMessage message, List<IExchangeDocumentInfo> infos,
                                                                         ICounterparty sender, bool isIncoming, IBoxBase box, string exchangeTaskActiveTextBoundedDocuments)
    {
      var infosForSend = new List<IExchangeDocumentInfo>();
      ITask mainProcessingTask = null;
      IExchangeDocumentProcessingTask parentTask = ExchangeDocumentProcessingTasks.Null;
      foreach (var info in infos)
      {
        var documentGuid = info.Document.GetEntityMetadata().GetOriginal().NameGuid;
        parentTask = ExchangeDocumentProcessingTasks.GetAll()
          .Where(t => t.AttachmentDetails.Any(att => att.AttachmentId == info.Document.Id && att.EntityTypeGuid == documentGuid))
          .FirstOrDefault();
        
        if (parentTask == null)
          infosForSend.Add(info);
        else if (mainProcessingTask == null)
          mainProcessingTask = parentTask.MainTask;
      }
      
      if (!infosForSend.Any())
        return ExchangeDocumentProcessingTasks.As(mainProcessingTask) ?? parentTask;
      
      var task = this.CreateExchangeTask(infos, sender, box, message.TimeStamp, mainProcessingTask);
      task.Save();
      
      var text = string.Empty;
      if (!isIncoming)
        text = ExchangeDocumentProcessingTasks.Resources.OutcomingDocumentProcessingTaskActiveTextFormat(ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box));
      else
        text = ExchangeDocumentProcessingTasks.Resources.TaskActiveText;
      
      if (task.ActiveText != string.Empty)
      {
        text += Environment.NewLine;
        text += Environment.NewLine;
        text += task.ActiveText;
      }
      task.ActiveText = text;
      
      var needSign = new List<Docflow.IOfficialDocument>();
      var signed = new List<Docflow.IOfficialDocument>();
      var dontNeedSign = new List<Docflow.IOfficialDocument>();
      foreach (var info in infos.Where(i => i.Document != null))
      {
        var exchangeDocument = info.Document;
        var processingDocument = message.PrimaryDocuments.Single(d => d.ServiceEntityId == info.ServiceDocumentId);
        if (processingDocument.SignStatus == NpoComputer.DCX.Common.SignStatus.Waiting)
        {
          if (isIncoming)
            needSign.Add(exchangeDocument);
          else
            dontNeedSign.Add(exchangeDocument);
        }
        else if (processingDocument.SignStatus == NpoComputer.DCX.Common.SignStatus.Signed)
          signed.Add(exchangeDocument);
        else
          dontNeedSign.Add(exchangeDocument);
      }
      
      foreach (var doc in needSign)
      {
        task.NeedSigning.All.Add(doc);
      }
      
      foreach (var doc in signed)
      {
        if (isIncoming)
        {
          var hyperlink = Hyperlinks.Get(doc);
          task.ActiveText += Environment.NewLine;
          task.ActiveText += Environment.NewLine;
          task.ActiveText += ExchangeDocumentProcessingTasks.Resources.DocumentIsSignedByUsFormat(hyperlink);
        }
        else
        {
          var hyperlink = Hyperlinks.Get(doc);
          task.ActiveText += Environment.NewLine;
          task.ActiveText += Environment.NewLine;
          task.ActiveText += Resources.DocumentIsSignedByBothSidesFormat(hyperlink);
        }
        
        task.DontNeedSigning.All.Add(doc);
      }

      var processedDocumentTypes = this.GetSupportedPrimaryDocumentTypes();
      var processingDocuments = message.PrimaryDocuments.Where(x => processedDocumentTypes.Contains(x.DocumentType.Value));
      var rejected = processingDocuments.Where(d => d.SignStatus == SignStatus.Rejected).ToList();
      if (rejected.Any())
      {
        task.ActiveText += Environment.NewLine;
        task.ActiveText += Environment.NewLine;
        
        var documents = string.Join(", ", rejected.Select(r => r.FileName));
        if (rejected.Count == 1)
          task.ActiveText += ExchangeDocumentProcessingTasks.Resources.DocumentIsRejectedByUsFormat(documents);
        else
          task.ActiveText += ExchangeDocumentProcessingTasks.Resources.DocumentsIsRejectedByUsFormat(documents);
      }
      
      foreach (var doc in dontNeedSign)
      {
        task.DontNeedSigning.All.Add(doc);
      }
      
      if (mainProcessingTask == null)
        task.ActiveText += exchangeTaskActiveTextBoundedDocuments;
      else
      {
        task.ActiveText += Environment.NewLine;
        task.ActiveText += Environment.NewLine;
        task.ActiveText += Sungero.Exchange.Resources.AdditionalDocumentSend;
        foreach (var additionalDocument in infosForSend.Select(d => d.Document))
        {
          task.ActiveText += Environment.NewLine;
          task.ActiveText += Hyperlinks.Get(additionalDocument);
        }
      }
      
      // Обработка формализованных документов в сообщении.
      var formalizedDocuments = message.PrimaryDocuments.Where(x => !processedDocumentTypes.Contains(x.DocumentType.Value));
      if (formalizedDocuments.Any())
      {
        task.ActiveText += System.Environment.NewLine;
        task.ActiveText += System.Environment.NewLine;
        task.ActiveText += this.GenerateActiveTextFromUnsupportedDocuments(formalizedDocuments, sender, isIncoming, box, message.TimeStamp, false);
      }
      
      task.Save();
      return task;
    }
    
    private string GenerateExchangeTaskSubject(IExchangeDocumentProcessingTask task)
    {
      var businessUnit = ExchangeCore.PublicFunctions.BoxBase.GetBusinessUnit(task.Box);
      var subject = string.Empty;
      var dateWithUTC = Sungero.Docflow.PublicFunctions.Module.GetDateWithUTCLabel(task.IncomeDate.Value);
      subject = task.IsIncoming == true ?
        ExchangeDocumentProcessingTasks.Resources.TaskSubjectFormat(task.Counterparty, businessUnit, dateWithUTC, task.ExchangeService) :
        ExchangeDocumentProcessingTasks.Resources.TaskSubjectFormat(businessUnit, task.Counterparty, dateWithUTC, task.ExchangeService);
      subject = CutText(subject, task.Info.Properties.Subject.Length);
      return subject;
    }

    /// <summary>
    /// Отправлять задания/уведомления ответственному.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="message">Сообщение.</param>
    /// <returns>Признак отправки задания ответственному за ящик/контрагента.</returns>
    protected virtual bool NeedReceiveDocumentProcessingTask(IBoxBase box, IMessage message)
    {
      return ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box);
    }
    
    #endregion

    #endregion

    #region Обработка ответов от контрагентов
    
    #region Обработка подписания

    /// <summary>
    /// Обработать пришедшие подписи к неформализованным документам.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="client">Клиент к сервису обмена.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="sender">Контрагент.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="historyOperation">Операция истории - мы подписали или КА подписал.</param>
    /// <param name="historyComment">Комментарий к операции истории.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessNonformalizedSign(IMessage message, IMessageQueueItem queueItem, DcxClient client, IBoxBase box,
                                                    ICounterparty sender, bool isIncoming, Enumeration historyOperation, string historyComment)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessNonformalizedSign.");
      foreach (var document in message.PrimaryDocuments.Where(x => x.SignStatus == NpoComputer.DCX.Common.SignStatus.Signed &&
                                                              x.DocumentType == NpoComputer.DCX.Common.DocumentType.Nonformalized))
      {
        var doc = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, document.ServiceEntityId);
        
        var sign = message.Signatures.FirstOrDefault(x => x.DocumentId == document.ServiceEntityId);
        if (sign == null)
        {
          this.LogDebugFormat(message, queueItem, box, "Message not contain a signature.");
          return false;
        }
        
        var certificateInfo = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(sign.Content);
        var signatoryInfo = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(certificateInfo.SubjectInfo);
        
        // Пропускаем документы, которые были отправлены нами через личный кабинет сервиса обмена, а также документы без подписи.
        if (doc == null)
        {
          if (this.CanProcessMessageLater(message, queueItem, ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box), document.ServiceEntityId))
          {
            this.LogDebugFormat(message, document, "Document not found for received signature.");
            return false;
          }
          
          continue;
        }
        
        // Когда контрагент прислал нам подпись, а у нас нет документа - нужно немного магии с сообщениями.
        if (doc.Document == null)
        {
          // Загружаем первичное сообщение для создания документа, который не был создан сразу.
          doc = this.LoadDocumentWithSecondSign(message, doc, document, client, sender, isIncoming, box);
        }

        var sentVersion = doc.Document.Versions.FirstOrDefault(x => x.Id == doc.VersionId);
        var newDocumentHash = document.Content.GetMD5Hash();
        var versionIsChanged = false;
        
        if (sentVersion != null && (newDocumentHash == Docflow.PublicFunctions.OfficialDocument.GetVersionBodyHash(doc.Document, sentVersion)))
        {
          // Прикрепление к неизмененной версии.
          var signatures = message.Signatures.Where(x => x.DocumentId == document.ServiceEntityId);
          var addedThumbprints = Signatures.Get(sentVersion)
            .Where(s => s.SignCertificate != null)
            .Select(x => x.SignCertificate.Thumbprint);
          foreach (var signature in signatures)
          {
            certificateInfo = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(signature.Content);
            var signatureIsAlreadyAdded = addedThumbprints.Any(x => x.Equals(certificateInfo.Thumbprint));
            if (!signatureIsAlreadyAdded)
            {
              signatoryInfo = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(certificateInfo.SubjectInfo);
              this.SignDocument(doc, signature, sentVersion, signatoryInfo, message.TimeStamp);
            }
          }
        }
        else
        {
          var outMessage = client.GetMessage(doc.ServiceMessageId);
          
          if (outMessage != null)
          {
            var ourSign = outMessage.Signatures.FirstOrDefault(x => x.DocumentId == document.ServiceEntityId);
            var ourCertificateInfo = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(ourSign.Content);
            
            var application = GetOrCreateAssociatedApplicationByDocumentName(document.FileName);
            CreateVersionFromExchangeDocument(doc.Document, document, application);
            
            var originalVersion = doc.Document.LastVersion;
            
            // Прикрепляем нашу подпись как внешнюю.
            var ourSignatoryInfo = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(ourCertificateInfo.SubjectInfo);
            this.SignDocument(doc, ourSign, originalVersion, ourSignatoryInfo, outMessage.TimeStamp);
            
            // Прикрепляем подпись контрагента.
            this.SignDocument(doc, sign, originalVersion, signatoryInfo, message.TimeStamp);
            
            sentVersion = originalVersion;
            doc.VersionId = originalVersion.Id;
            doc.Save();
            
            versionIsChanged = true;
          }
        }
        
        this.ProcessSharedSign(doc.Document, doc, isIncoming, box, sentVersion, signatoryInfo, versionIsChanged, historyOperation, historyComment, true);
        this.FillCounterpartyDataFromReplyMessage(message, doc.ServiceDocumentId, doc.Document, sender, isIncoming);
      }
      
      return true;
    }
    
    /// <summary>
    /// Обработать пришедшие титулы к формализованным документам.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="queueItems">Все элементы очереди.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="historyOperation">Операция истории - мы подписали или КА подписал.</param>
    /// <param name="historyComment">Комментарий к операции истории.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessFormalizedSign(IMessage message, IMessageQueueItem queueItem, List<IMessageQueueItem> queueItems,
                                                 bool isIncoming, IBoxBase box, Enumeration historyOperation, string historyComment)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessFormalizedSign.");
      // Обработка титулов покупателей.
      foreach (var document in message.ReglamentDocuments.Where(x => this.GetSupportedReglamentDocumentTypes().Contains(x.DocumentType)))
      {
        if (!this.ProcessFormalizedTitlesAndSigns(message, queueItem, queueItems, isIncoming, box, historyOperation, historyComment,
                                                  document.RootServiceEntityId, document.ServiceEntityId, document.Content))
          return false;
      }
      
      // Загрузка ответной подписи на СЧФ для СБИС.
      if (queueItem.RootBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis)
      {
        foreach (var document in message.PrimaryDocuments.Where(d => d.SignStatus == NpoComputer.DCX.Common.SignStatus.Signed && d.DocumentType == NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfSeller))
        {
          if (!this.ProcessFormalizedTitlesAndSigns(message, queueItem, queueItems, isIncoming, box, historyOperation, historyComment,
                                                    document.ServiceEntityId, document.ServiceEntityId, null))
            return false;
        }
      }
      
      return true;
    }
    
    /// <summary>
    /// Обработать пришедшие титулы к формализованным документам и ответные подписи на СЧФ из СБИСа.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="queueItems">Все элементы очереди.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="historyOperation">Операция истории - мы подписали или КА подписал.</param>
    /// <param name="historyComment">Комментарий к операции истории.</param>
    /// <param name="rootServiceDocumentId">Ид родительского документа на сервисе.</param>
    /// <param name="serviceDocumentId">Ид документа на сервисе.</param>
    /// <param name="reglamentDocumentContent">Контент титула.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessFormalizedTitlesAndSigns(IMessage message, IMessageQueueItem queueItem, List<IMessageQueueItem> queueItems,
                                                           bool isIncoming, IBoxBase box, Enumeration historyOperation, string historyComment,
                                                           string rootServiceDocumentId, string serviceDocumentId, byte[] reglamentDocumentContent)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessFormalizedTitlesAndSigns.");
      var doc = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, rootServiceDocumentId);
      if (doc == null)
      {
        var documentInService = message.PrimaryDocuments.FirstOrDefault(d => d.ServiceEntityId == rootServiceDocumentId);
        
        if (documentInService != null && documentInService.BuyerAcceptanceStatus == NpoComputer.DCX.Common.BuyerAcceptanceStatus.Rejected)
          return true;
        
        // Если документ ещё в очереди, обработаем позже.
        if (this.CanProcessMessageLater(message, queueItem, ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box), rootServiceDocumentId))
        {
          this.LogDebugFormat(queueItem, "Document not found for received signature: ServiceEntityId: '{0}', RootServiceEntityId '{1}'.",
                              serviceDocumentId, rootServiceDocumentId);
          return false;
        }
        
        this.LogDebugFormat(message, queueItem, box, "Exit ProcessFormalizedTitlesAndSigns.");
        
        return true;
      }
      
      // Документ был подписан в RX, заканчиваем обработку.
      if ((doc.OutgoingStatus == Exchange.ExchangeDocumentInfo.OutgoingStatus.Signed ||
           doc.OutgoingStatus == Exchange.ExchangeDocumentInfo.OutgoingStatus.Rejected &&
           doc.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Rejected) &&
          doc.ReceiverSignId != null)
      {
        this.LogDebugFormat(message, queueItem, box, "Document with serviceDocumentId = '{0}' contains a signature.", doc.ServiceDocumentId);
        return true;
      }
      
      var sign = message.Signatures.FirstOrDefault(x => x.DocumentId == serviceDocumentId);
      if (sign == null)
      {
        this.LogDebugFormat(message, queueItem, box, "Message not contain a signature for document with id = '{0}'.", serviceDocumentId);
        return false;
      }
      
      var primaryDocument = message.PrimaryDocuments.FirstOrDefault(d => d.ServiceEntityId == rootServiceDocumentId);
      if (primaryDocument != null && primaryDocument.BuyerAcceptanceStatus != null)
        doc.BuyerAcceptanceStatus = this.GetBuyerAcceptanceStatus(primaryDocument);
      
      var x509certificate = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(sign.Content);
      var signatoryInfo = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(x509certificate.SubjectInfo);
      
      if (doc.Document != null)
      {
        var formalizedDocument = Sungero.Docflow.AccountingDocumentBases.As(doc.Document);
        if (formalizedDocument != null && reglamentDocumentContent != null)
        {
          using (var memory = new System.IO.MemoryStream(reglamentDocumentContent))
          {
            // Выключить error-логирование при доступе к зашифрованной версии.
            AccessRights.SuppressSecurityEvents(
              () =>
              {
                formalizedDocument.CreateVersion();
                var version = formalizedDocument.LastVersion;
                version.AssociatedApplication = GetOrCreateAssociatedApplicationByDocumentName("file.xml");
                version.Note = FinancialArchive.Resources.BuyerTitleVersionNote;
                formalizedDocument.BuyerTitleId = version.Id;
                version.Body.Write(memory);
                formalizedDocument.Save();
              });
          }
        }

        this.SignDocument(doc, sign, doc.Document.LastVersion, signatoryInfo, message.TimeStamp);
        if (formalizedDocument != null)
        {
          var lastSignature = this.GetLastDocumentSignature(formalizedDocument);
          formalizedDocument.BuyerSignatureId = lastSignature.Id;
        }
        
        var sentVersion = doc.Document.Versions.FirstOrDefault(x => x.Id == doc.VersionId);
        
        if (doc.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Rejected)
        {
          this.ProcessSharedReject(doc, doc.Document, isIncoming, box, sign.Content, historyOperation, historyComment, string.Empty, string.Empty, true);
        }
        else
        {
          this.ProcessSharedSign(doc.Document, doc, isIncoming, box, doc.Document.LastVersion, signatoryInfo, false, historyOperation, historyComment, true);
          this.FillCounterpartyDataFromReplyMessage(message, serviceDocumentId, formalizedDocument, formalizedDocument.Counterparty, isIncoming);
        }
      }

      return true;
    }

    /// <summary>
    /// Обработать подписание документа - как из RX, так и из веба.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="info">Инфошка документа.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="signedVersion">Реально подписанная версия (на случай как раз изменения отправленной версии).</param>
    /// <param name="signatoryInfo">Информация о подписавшем для задач уведомления. Будет пустой, если вызвано из действия "Подписать и отправить".</param>
    /// <param name="sentVersionIsChanged">Признак того, что версия была изменена в RX после отправки (не должно существовать?).</param>
    /// <param name="historyOperation">Операция - подписали мы или контрагент.</param>
    /// <param name="historyComment">Комментарий к операции в истории.</param>
    /// <param name="isAgent">Признак вызова из фонового процесса. Иначе - пользователем в RX.</param>
    protected virtual void ProcessSharedSign(IOfficialDocument document, IExchangeDocumentInfo info, bool isIncoming, IBoxBase box,
                                             IElectronicDocumentVersions signedVersion, string signatoryInfo, bool sentVersionIsChanged,
                                             Enumeration historyOperation, string historyComment, bool isAgent)
    {
      this.LogDebugFormat(info, "Execute ProcessSharedSign.");
      var notSigned = info.OutgoingStatus != Exchange.ExchangeDocumentInfo.OutgoingStatus.Signed;
      var exchangeService = ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box);
      var needReceive = ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box);
      if (!isIncoming && notSigned)
      {
        var responsible = ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(info.Box, info.Counterparty, new List<IExchangeDocumentInfo>() { info });
        if (isAgent && needReceive && info.DownloadSession == null)
          this.CreateNoticeAfterOurSigning(document, box, true, false, string.Empty);
        
        info.OutgoingStatus = Exchange.ExchangeDocumentInfo.OutgoingStatus.Signed;
        
        using (Sungero.Core.CultureInfoExtensions.SwitchTo(TenantInfo.Culture))
        {
          var tracking = document.Tracking.AddNew();
          tracking.Action = Docflow.OfficialDocumentTracking.Action.Sending;
          tracking.DeliveredTo = Company.Employees.Current ?? responsible;
          tracking.IsOriginal = true;
          tracking.ReturnDeadline = null;
          tracking.Note = Resources.SendSignToCounterpartyFormat(exchangeService.Name);
          tracking.ExternalLinkId = info.Id;
        }
      }
      
      var detailedOperation = new Enumeration(Constants.Module.Exchange.DetailedSign);
      if (isIncoming)
        document.ExternalApprovalState = Docflow.OfficialDocument.ExternalApprovalState.Signed;
      else
        document.InternalApprovalState = Docflow.OfficialDocument.InternalApprovalState.Signed;

      var externalApprovalInTracking = document.Tracking.Where(x => x.Action == Docflow.OfficialDocumentTracking.Action.Endorsement
                                                               && !x.ReturnResult.HasValue && x.ExternalLinkId == info.Id);
      foreach (var trackingString in externalApprovalInTracking)
      {
        trackingString.ReturnResult = Docflow.OfficialDocumentTracking.ReturnResult.Signed;
        
        // Логика по прекращению согласования (контроль возврата и т.д.), уведомление ответственному.
        if (isAgent)
          this.SendDocumentReplyNotice(box, trackingString, signedVersion.Number, sentVersionIsChanged, true, signatoryInfo, false, exchangeService.Name, string.Empty);
      }
      
      document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Signed;
      info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Signed;
      
      if (notSigned)
        document.History.Write(historyOperation, detailedOperation, historyComment, signedVersion.Number);

      // Добавление в очередь генерации PublicBody после диалогового подписания происходит в методах SendBuyerTitle
      // и SendAnswerToNonformalizedDocument, здесь только синхронная агентская генерация.
      var accountingDocument = Docflow.AccountingDocumentBases.As(document);
      if (isAgent)
      {
        if (accountingDocument != null && accountingDocument.IsFormalized == true)
          Docflow.PublicFunctions.Module.Remote.GeneratePublicBodyForFormalizedDocument(accountingDocument, signedVersion.Id, accountingDocument.ExchangeState);
        else
          Docflow.PublicFunctions.Module.Remote.GeneratePublicBodyForNonformalizedDocument(document, signedVersion.Id);
      }
      document.Save();
      info.Save();
    }
    
    /// <summary>
    /// Создать и отправить задачу на обработку подписанного обеими сторонами документа.
    /// </summary>
    /// <param name="message">Сообщение сервиса обмена.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    protected virtual void SendSignedDocumentProcessingTask(IMessage message, IExchangeDocumentInfo info, ICounterparty sender, IBoxBase box)
    {
      var task = this.CreateExchangeTask(new List<IExchangeDocumentInfo>() { info }, sender, info.Box, info.MessageDate.Value, null);

      var text = string.Empty;
      text = ExchangeDocumentProcessingTasks.Resources.TaskActiveText;
      if (task.ActiveText != string.Empty)
      {
        text += Environment.NewLine;
        text += Environment.NewLine;
        text += task.ActiveText;
      }

      task.ActiveText = text;

      var hyperlink = Hyperlinks.Get(info.Document);
      task.ActiveText += Environment.NewLine;
      task.ActiveText += Environment.NewLine;
      task.ActiveText += Resources.DocumentIsSignedByBothSidesFormat(hyperlink);

      task.ActiveText += this.ProcessBoundedDocuments(message.PrimaryDocuments, new List<Docflow.IOfficialDocument>() { info.Document }, false, box);

      this.GrantAccessRightsForUpperBoxResponsibles(info.Document, box);
      task.DontNeedSigning.All.Add(info.Document);

      task.Save();
      task.Start();
    }
    
    /// <summary>
    /// Обработка подписи по документу, который еще не был загружен.
    /// </summary>
    /// <param name="message">Сообщение с подписью.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="document">Документ из сервиса обмена.</param>
    /// <param name="client">Клиент DCX.</param>
    /// <param name="sender">Отправитель.</param>
    /// <param name="isIncoming">True, если сообщение входящее, иначе - false.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <returns>Информация о документе с обновлением.</returns>
    protected virtual IExchangeDocumentInfo LoadDocumentWithSecondSign(IMessage message, IExchangeDocumentInfo info, IDocument document, DcxClient client,
                                                                       ICounterparty sender, bool isIncoming, IBoxBase box)
    {
      this.LogDebugFormat(info, "Execute LoadDocumentWithSecondSign.");
      var firstMessage = client.GetMessage(info.ServiceMessageId);
      var firstDocument = firstMessage.PrimaryDocuments.SingleOrDefault(d => d.ServiceEntityId == info.ServiceDocumentId);

      var serviceCounterpartyId = string.Empty;
      if (!isIncoming)
        serviceCounterpartyId = message.Sender.Organization.OrganizationId;
      else
        serviceCounterpartyId = message.Receiver.Organization.OrganizationId;

      info.Document = this.GetOrCreateNewExchangeDocument(firstDocument, sender, serviceCounterpartyId, !isIncoming, firstMessage.TimeStamp, box);

      // Переполучаем инфошку, она меняется.
      info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, document.ServiceEntityId);

      // Копипаста подписания при получении нового сообщения.
      var signature = firstMessage.Signatures.FirstOrDefault(x => x.DocumentId == firstDocument.ServiceEntityId);
      if (signature != null)
      {
        var x509certificate = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(signature.Content);
        var signInfo = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(x509certificate.SubjectInfo);
        this.SignDocument(info, signature, info.Document.LastVersion, signInfo, firstMessage.TimeStamp);
      }

      // Отправить задачу на обработку подписанного обеими сторонами документа.
      var needReceive = ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box) && Exchange.PublicFunctions.ExchangeDocumentInfo.NeedReceiveTask(info);
      if (needReceive && info.DownloadSession == null)
      {
        this.SendSignedDocumentProcessingTask(message, info, sender, box);
      }

      return info;
    }

    /// <summary>
    /// Подписать документ.
    /// </summary>
    /// <param name="info">Информация о подписываемой версии.</param>
    /// <param name="sign">Подпись.</param>
    /// <param name="version">Версия, которую подписывают.</param>
    /// <param name="signatoryName">Имя подписывающего.</param>
    /// <param name="date">Дата подписи, на случай если её нет в подписи и не получается выполнить импорт легально.</param>
    /// <remarks>В случае если подпись без даты, которая в Sungero обязательна, будет выполнена попытка проставить подпись
    /// хоть как-нибудь. Подпись после этого будет отображаться как невалидная, но она хотя бы будет.
    /// Валидная подпись останется только в сервисе обмена.</remarks>
    protected virtual void SignDocument(IExchangeDocumentInfo info, Signature sign,
                                        IElectronicDocumentVersions version, string signatoryName, DateTime date)
    {
      this.LogDebugFormat(info, "Execute SignDocument.");
      var entity = (Domain.Shared.IExtendedEntity)info.Document;
      entity.Params[ExchangeCore.PublicConstants.BoxBase.JobRunned] = true;

      try
      {
        var unsignedAdditionalInfo = Docflow.PublicFunctions.Module.FormatUnsignedAttribute(Docflow.PublicConstants.Module.UnsignedAdditionalInfoKeyFPoA, sign.FormalizedPoAUnifiedRegNumber);
        Signatures.Import(info.Document, SignatureType.Approval, signatoryName, sign.Content, date, unsignedAdditionalInfo, version);
      }
      catch (Exception ex)
      {
        this.LogDebugFormat(info, "Can't import signature on document, error: {0}", ex);
      }
      
      entity.Params[ExchangeCore.PublicConstants.BoxBase.JobRunned] = false;
      
      var fromCounterparty = GetClient(info.RootBox).OurSubscriber.BoxId != sign.SignerBoxId;
      
      var signature = Signatures.Get(version)
        .Where(s => s.IsExternal == true && s.SignCertificate != null)
        .OrderByDescending(x => x.Id)
        .FirstOrDefault();
      
      if (signature != null)
      {
        if (info.MessageType == Exchange.ExchangeDocumentInfo.MessageType.Incoming ? fromCounterparty : !fromCounterparty)
          info.SenderSignId = signature.Id;
        else
          info.ReceiverSignId = signature.Id;
        info.Save();
      }
      else
      {
        this.LogDebugFormat(info, "Can't find signature on document with version id: '{0}'", version.Id);
      }
    }

    #endregion

    #region Обработка отказа в подписании

    /// <summary>
    /// Обработать документы с отказом в подписании.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="box">Ящик.</param>
    /// <param name="historyOperation">Операция истории - мы отказали или нам отказали.</param>
    /// <param name="historyComment">Комментарий - кто и кому.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessReject(IMessage message, IMessageQueueItem queueItem, bool isIncoming, IBoxBase box,
                                         Enumeration historyOperation, string historyComment)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessReject.");
      foreach (var reglamentDoc in message.ReglamentDocuments.Where(x => x.DocumentType == ReglamentDocumentType.AmendmentRequest ||
                                                                    x.DocumentType == ReglamentDocumentType.InvoiceAmendmentRequest ||
                                                                    x.DocumentType == ReglamentDocumentType.Rejection))
      {
        var primaryDocument = message.PrimaryDocuments.FirstOrDefault(x => x.ServiceEntityId == reglamentDoc.ParentServiceEntityId);
        
        if (primaryDocument == null)
          continue;
        
        var doc = Docflow.OfficialDocuments.Null;

        var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, primaryDocument.ServiceEntityId);
        
        if (exchangeDocumentInfo != null)
          doc = exchangeDocumentInfo.Document;
        
        this.LogDebugFormat(message, reglamentDoc, "Processing the invoice amendment request (or rejection).");
        if (exchangeDocumentInfo == null &&
            this.CanProcessMessageLater(message, queueItem, ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box), reglamentDoc.RootServiceEntityId))
        {
          this.LogDebugFormat(message, reglamentDoc, "Document info not found for received invoice amendment request (or rejection): RootServiceEntityId: '{0}'.", reglamentDoc.RootServiceEntityId);
          return false;
        }
        
        // Уведомление об уточнении.
        if (reglamentDoc.DocumentType == ReglamentDocumentType.InvoiceAmendmentRequest &&
            exchangeDocumentInfo != null && !exchangeDocumentInfo.ServiceDocuments.Any(d => d.DocumentId == reglamentDoc.ServiceEntityId))
        {
          this.LogDebugFormat(exchangeDocumentInfo, "Saving invoice amendment request.");
          this.SaveRejectToDocumentInfo(message, exchangeDocumentInfo, reglamentDoc,
                                        isIncoming, Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReject);
        }
        
        // Отказ в подписании.
        if ((reglamentDoc.DocumentType == ReglamentDocumentType.AmendmentRequest || reglamentDoc.DocumentType == ReglamentDocumentType.Rejection) &&
            exchangeDocumentInfo != null && !exchangeDocumentInfo.ServiceDocuments.Any(d => d.DocumentId == reglamentDoc.ServiceEntityId))
        {
          this.LogDebugFormat(exchangeDocumentInfo, "Saving rejection.");
          this.SaveRejectToDocumentInfo(message, exchangeDocumentInfo, reglamentDoc,
                                        isIncoming, Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Reject);
        }
        
        // Пропускаем документы, которые были отправлены нами через личный кабинет сервиса обмена.
        // Или по которым был отправлен автоматический отказ.
        if (doc == null || exchangeDocumentInfo.OutgoingStatus == Exchange.ExchangeDocumentInfo.OutgoingStatus.Rejected)
        {
          this.LogDebugFormat(exchangeDocumentInfo, "Document not found or received rejection for document.");
          // Инфошка без документа - признак того, что ждали подписи. Больше она не нужна.
          if (exchangeDocumentInfo != null && doc == null)
          {
            ExchangeDocumentInfos.Delete(exchangeDocumentInfo);
            this.LogDebugFormat(exchangeDocumentInfo, "Document info deleted.");
          }
          
          return true;
        }
        
        var signature = message.Signatures.Where(x => x.DocumentId.Equals(reglamentDoc.ServiceEntityId, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        if (reglamentDoc.DocumentType == ReglamentDocumentType.InvoiceAmendmentRequest)
          this.ProcessSharedInvoiceReject(exchangeDocumentInfo, doc, isIncoming, exchangeDocumentInfo.Box, signature.Content, historyOperation, historyComment, primaryDocument.Comment, primaryDocument.Comment, true);
        else
          this.ProcessSharedReject(exchangeDocumentInfo, doc, isIncoming, exchangeDocumentInfo.Box, signature.Content, historyOperation, historyComment, primaryDocument.Comment, primaryDocument.Comment, true);
      }

      return true;
    }

    /// <summary>
    /// Общий для агентов и UI код обработки "уведомления об уточнении" при подписании.
    /// </summary>
    /// <param name="info">Информация о документе в сервисе обмена.</param>
    /// <param name="document">Документ.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="box">Ящик.</param>
    /// <param name="signature">Подпись для уведомлений ответственного.</param>
    /// <param name="historyOperation">Операция истории - отправка отказа или пришедший от КА отказ.</param>
    /// <param name="historyComment">Комментарий истории, обычно перечисляются участники операции.</param>
    /// <param name="serviceComment">Комментарий, пришедший из сервиса. Для уведомлений ответственного.</param>
    /// <param name="rejectNotice">Причина отказа.</param>
    /// <param name="isAgent">Признак вызова из фонового процесса. False используется для вызова из UI.</param>
    protected virtual void ProcessSharedInvoiceReject(IExchangeDocumentInfo info, IOfficialDocument document,
                                                      bool isIncoming, IBoxBase box, byte[] signature,
                                                      Enumeration historyOperation, string historyComment, string serviceComment,
                                                      string rejectNotice, bool isAgent)
    {
      this.LogDebugFormat(info, "Execute ProcessSharedInvoiceReject.");
      var isRejected = info.InvoiceState == Exchange.ExchangeDocumentInfo.InvoiceState.Rejected;
      var needReceive = ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box);
      if (!isIncoming && !isRejected && isAgent && needReceive && info.DownloadSession == null)
        this.CreateNoticeAfterOurSigning(document, box, false, true, serviceComment);
      
      if (!isRejected)
        info.InvoiceState = Exchange.ExchangeDocumentInfo.InvoiceState.Rejected;
      
      info.Save();
      
      // TODO Zamerov: Карточка не обновляется 46758.
      // Помечаем свойство изменившимся, чтобы отработало перестроение местонахождения при сохранении.
      document.LocationState = document.LocationState;
      
      var sentVersion = document.Versions.FirstOrDefault(x => x.Id == info.VersionId);
      if (isIncoming && isAgent)
      {
        var externalApprovalInTracking = document.Tracking.Where(x => !x.ReturnResult.HasValue && x.ExternalLinkId == info.Id
                                                                 && (x.Action == Docflow.OfficialDocumentTracking.Action.Sending || x.Action == Docflow.OfficialDocumentTracking.Action.Endorsement));
        var x509certificate = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(signature);
        var signatoryInfo = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(x509certificate.SubjectInfo);
        foreach (var trackingString in externalApprovalInTracking)
          this.SendDocumentReplyNotice(box, trackingString, sentVersion.Number, false, false, signatoryInfo, true, ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box).Name, serviceComment);
      }
      
      if (!string.IsNullOrEmpty(rejectNotice) && !isRejected)
        document.Note += string.IsNullOrEmpty(document.Note) ? Resources.RejectInvoiceNoticeFormat(rejectNotice) : Environment.NewLine + Resources.RejectInvoiceNoticeFormat(rejectNotice);
      
      var maxLength = document.Info.Properties.Note.Length;
      if (!string.IsNullOrEmpty(document.Note) && document.Note.Length > maxLength)
        document.Note = CutText(document.Note, maxLength);
      
      if (!isRejected)
      {
        var detailedOperation = new Enumeration(Constants.Module.Exchange.DetailedInvoiceReject);
        document.History.Write(historyOperation, detailedOperation, historyComment, sentVersion.Number);
      }
      
      document.Save();
    }

    /// <summary>
    /// Общий для агентов и UI код обработки "отказа" при подписании.
    /// </summary>
    /// <param name="info">Информация о документе в сервисе обмена.</param>
    /// <param name="document">Документ.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="box">Ящик.</param>
    /// <param name="signature">Подпись для уведомлений ответственного.</param>
    /// <param name="historyOperation">Операция истории - отправка отказа или пришедший от КА отказ.</param>
    /// <param name="historyComment">Комментарий истории, обычно перечисляются участники операции.</param>
    /// <param name="serviceComment">Комментарий, пришедший из сервиса. Для уведомлений ответственного.</param>
    /// <param name="rejectNotice">Причина отказа.</param>
    /// <param name="isAgent">Признак вызова из фонового процесса. False используется для вызова из UI.</param>
    protected virtual void ProcessSharedReject(IExchangeDocumentInfo info, IOfficialDocument document, bool isIncoming,
                                               IBoxBase box, byte[] signature,
                                               Enumeration historyOperation, string historyComment,
                                               string serviceComment, string rejectNotice, bool isAgent)
    {
      this.LogDebugFormat(info, "Execute ProcessSharedReject.");
      // Признак того, а можно ли "отказать" по документу в текущей его версии. Если нет - то обновляем только инфошку, документ не трогаем.
      var lastDocumentInfo = Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.GetLastDocumentInfo(document);
      info = ExchangeDocumentInfos.Get(info.Id);
      var canSendAnswer = lastDocumentInfo != null && lastDocumentInfo.Id == info.Id;
      var isRejected = info.OutgoingStatus == Exchange.ExchangeDocumentInfo.OutgoingStatus.Rejected;
      var needReceive = ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box);
      var responsible = ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(box, info.Counterparty, new List<IExchangeDocumentInfo>() { info });
      if (!isIncoming && !isRejected)
      {
        if (isAgent && needReceive && info.DownloadSession == null)
          this.CreateNoticeAfterOurSigning(document, box, false, false, serviceComment);
        
        if (info != null)
          info.OutgoingStatus = Exchange.ExchangeDocumentInfo.OutgoingStatus.Rejected;
        
        using (Sungero.Core.CultureInfoExtensions.SwitchTo(TenantInfo.Culture))
        {
          var tracking = document.Tracking.AddNew();
          tracking.Action = Docflow.OfficialDocumentTracking.Action.Sending;
          tracking.DeliveredTo = Company.Employees.Current ?? responsible;
          tracking.IsOriginal = true;
          tracking.ReturnDeadline = null;
          tracking.Note = Resources.SendRejectToCounterpartyFormat(ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box).Name);
          tracking.ExternalLinkId = info.Id;
        }
      }
      
      // Отказ по счёт-фактуре в СО связан с отправкой уточнения и поэтому не должен делать её устаревшей.
      var isTaxInvoice = FinancialArchive.IncomingTaxInvoices.Is(document) || FinancialArchive.OutgoingTaxInvoices.Is(document);
      if (canSendAnswer && !isTaxInvoice)
        Docflow.PublicFunctions.OfficialDocument.SetObsolete(document, false);
      
      var detailedOperation = new Enumeration(Constants.Module.Exchange.DetailedReject);
      
      this.SetRejectStates(document, info, isIncoming, canSendAnswer, isTaxInvoice);
      info.Save();
      
      var externalApprovalInTracking = document.Tracking.Where(x => x.Action == Docflow.OfficialDocumentTracking.Action.Endorsement
                                                               && !x.ReturnResult.HasValue && x.ExternalLinkId == info.Id);
      
      var x509Certificate = Docflow.PublicFunctions.Module.GetSignatureCertificateInfo(signature);
      var signatoryInfo = Docflow.PublicFunctions.Module.GetCertificateSignatoryName(x509Certificate.SubjectInfo);
      
      var rejectedVersion = info.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Rejected
        ? document.LastVersion
        : document.Versions.FirstOrDefault(x => x.Id == info.VersionId);
      
      foreach (var trackingString in externalApprovalInTracking)
      {
        trackingString.ReturnResult = Docflow.OfficialDocumentTracking.ReturnResult.NotSigned;
        
        // Логика по прекращению согласования (контроль возврата и т.д.), уведомление ответственному.
        if (isAgent)
          this.SendDocumentReplyNotice(box, trackingString, rejectedVersion.Number, false, false, signatoryInfo, false, ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box).Name, serviceComment);
      }
      
      // Генерация PDF.
      this.GeneratePublicBody(document, rejectedVersion, isAgent);

      if (!string.IsNullOrEmpty(rejectNotice) && !isRejected)
        document.Note += string.IsNullOrEmpty(document.Note) ? Resources.RejectNoticeFormat(rejectNotice) : Environment.NewLine + Resources.RejectNoticeFormat(rejectNotice);
      
      var maxLength = document.Info.Properties.Note.Length;
      if (!string.IsNullOrEmpty(document.Note) && document.Note.Length > maxLength)
        document.Note = CutText(document.Note, maxLength);
      
      if (!isRejected)
        document.History.Write(historyOperation, detailedOperation, historyComment, rejectedVersion.Number);
      
      document.Save();
    }

    /// <summary>
    /// Установить статусы документа при отказе.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="isIncoming">True, если сообщение входящее, иначе - false.</param>
    /// <param name="canSendAnswer">Признак смены статуса отказа по документу.</param>
    /// <param name="isTaxInvoice">True, если документ счет-фактура, иначе - false.</param>
    protected virtual void SetRejectStates(IOfficialDocument document, IExchangeDocumentInfo info, bool isIncoming, bool canSendAnswer, bool isTaxInvoice)
    {
      if (isIncoming)
      {
        if (canSendAnswer)
        {
          document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Rejected;
          document.ExternalApprovalState = Docflow.OfficialDocument.ExternalApprovalState.Unsigned;
        }

        info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Rejected;
      }
      else
      {
        if (info.OutgoingStatus == Exchange.ExchangeDocumentInfo.OutgoingStatus.Rejected)
        {
          if (canSendAnswer)
            document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Rejected;

          info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Rejected;
        }
        else
        {
          if (canSendAnswer)
            document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Obsolete;

          info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Obsolete;
        }

        // Отказ по счёт-фактуре в СО не должен прерывать внутреннее согласование.
        if (canSendAnswer && !isTaxInvoice)
          document.InternalApprovalState = Docflow.OfficialDocument.InternalApprovalState.Aborted;
      }
    }
    
    /// <summary>
    /// Добавить служебный документ с отказом в подписании.
    /// </summary>
    /// <param name="message">Сообщение с отказом в подписании.</param>
    /// <param name="info">Информация о документе.</param>
    /// <param name="document">Служебный документ.</param>
    /// <param name="isIncoming">True, если сообщение входящее, иначе - false.</param>
    /// <param name="serviceDocumentType">Тип служебного документа.</param>
    protected virtual void SaveRejectToDocumentInfo(IMessage message, IExchangeDocumentInfo info, IReglamentDocument document,
                                                    bool isIncoming, Enumeration serviceDocumentType)
    {
      this.LogDebugFormat(info, "Execute SaveRejectToDocumentInfo.");
      var serviceDoc = info.ServiceDocuments.AddNew();
      serviceDoc.DocumentId = document.ServiceEntityId;
      serviceDoc.ParentDocumentId = document.ParentServiceEntityId;
      serviceDoc.CounterpartyId = isIncoming ? message.Sender.Organization.OrganizationId : message.Receiver.Organization.OrganizationId;
      serviceDoc.DocumentType = serviceDocumentType;
      serviceDoc.Date = ToTenantTime(document.DateTime ?? message.TimeStamp);
      serviceDoc.Body = document.Content;
      var sign = message.Signatures.Single(s => s.DocumentId == serviceDoc.DocumentId);
      serviceDoc.Sign = sign.Content;
      serviceDoc.FormalizedPoAUnifiedRegNo = sign.FormalizedPoAUnifiedRegNumber;
      info.Save();
    }
    
    /// <summary>
    /// Сгенерировать PublicBody документа.
    /// </summary>
    /// <param name="documentId">ИД документа.</param>
    [Public, Remote]
    public virtual void GeneratePublicBody(int documentId)
    {
      var document = Docflow.OfficialDocuments.Get(documentId);
      if (document != null)
        this.GeneratePublicBodyAsync(document);
    }
    
    /// <summary>
    /// Сгенерировать PublicBody документа.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="sentVersion">Версия документа для генерации PublicBody.</param>
    /// <param name="isAgent">True - генерация синхронная из фонового процесса, иначе - постановка в очередь.</param>
    protected virtual void GeneratePublicBody(IOfficialDocument document, IElectronicDocumentVersions sentVersion, bool isAgent)
    {
      var accountingDocument = Docflow.AccountingDocumentBases.As(document);
      if (accountingDocument != null && accountingDocument.IsFormalized == true)
      {
        foreach (var accVersion in accountingDocument.Versions)
        {
          // Генерация PDF синхронная, если вызвана из агента и наоборот.
          if (isAgent)
            Docflow.PublicFunctions.Module.Remote.GeneratePublicBodyForFormalizedDocument(accountingDocument, accVersion.Id,
                                                                                          accountingDocument.ExchangeState);
          else
          {
            Docflow.PublicFunctions.Module.GenerateTempPublicBodyForExchangeDocument(accountingDocument, accVersion.Id);
            Exchange.PublicFunctions.Module.EnqueueXmlToPdfBodyConverter(accountingDocument, accVersion.Id, accountingDocument.ExchangeState);
          }
        }
      }
      else
      {
        // Генерация PDF синхронная, если вызвана из агента и наоборот.
        if (isAgent)
          Docflow.PublicFunctions.Module.Remote.GeneratePublicBodyForNonformalizedDocument(document, sentVersion.Id);
        else
        {
          Docflow.PublicFunctions.Module.GenerateTempPublicBodyForExchangeDocument(document, sentVersion.Id);
          Exchange.PublicFunctions.Module.EnqueueXmlToPdfBodyConverter(document, sentVersion.Id, document.ExchangeState);
        }
      }
    }
    
    /// <summary>
    /// Асинхронно сгенерировать PublicBody последней версии документа.
    /// </summary>
    /// <param name="document">Документ.</param>
    protected virtual void GeneratePublicBodyAsync(IOfficialDocument document)
    {
      var version = document.LastVersion;
      if (Exchange.ExchangeDocumentInfos.GetAll().Any(x => Equals(x.Document, document) && x.VersionId == version.Id) ||
          (AccountingDocumentBases.Is(document) && AccountingDocumentBases.As(document).IsFormalized == true))
      {
        Docflow.PublicFunctions.Module.GenerateTempPublicBodyForExchangeDocument(document, version.Id);
        Exchange.PublicFunctions.Module.EnqueueXmlToPdfBodyConverter(document, version.Id, document.ExchangeState);
      }
    }

    #endregion

    #region Уведомления по отказу и подписанию

    /// <summary>
    /// Создать уведомление, если документ был подписан или отправлен отказ нами из сервиса обмена.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="signed">Признак подписания. False - если в подписании было отказано.</param>
    /// <param name="isInvoiceAmendmentRequest">Отправлено уточнение по СФ или УПД.</param>
    /// <param name="reason">Комментарий.</param>
    private void CreateNoticeAfterOurSigning(IOfficialDocument document, IBoxBase box, bool signed, bool isInvoiceAmendmentRequest, string reason)
    {
      var docGuid = document.GetEntityMetadata().GetOriginal().NameGuid;
      var info = Functions.ExchangeDocumentInfo.GetLastDocumentInfo(document);
      var boxResponsible = ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(box, info.Counterparty, new List<IExchangeDocumentInfo>() { info });
      
      var documentProcessingTask = ExchangeDocumentProcessingTasks.GetAll()
        .Where(t => t.AttachmentDetails.Any(att => att.AttachmentId == document.Id && att.EntityTypeGuid == docGuid))
        .FirstOrDefault();
      var documentProcessingPerformers =
        Sungero.Workflow.Assignments.GetAll()
        .Where(a => Equals(a.Task, documentProcessingTask))
        .Select(a => a.Performer);
      
      var performers = new List<IUser>();
      performers.AddRange(documentProcessingPerformers);
      performers.Add(boxResponsible);
      if (Contracts.ContractualDocuments.Is(document))
        performers.Add(Contracts.ContractualDocuments.As(document).ResponsibleEmployee);
      
      var task = Workflow.SimpleTasks.Null;
      if (documentProcessingTask != null)
        task = Workflow.SimpleTasks.CreateAsSubtask(documentProcessingTask);
      else
        task = Workflow.SimpleTasks.Create();
      
      task.AssignmentType = Workflow.SimpleTask.AssignmentType.Notice;
      task.NeedsReview = false;
      
      // При создании подзадачи в нее копируются все вложения.
      var docs = task.AllAttachments.Where(d => !Equals(d, document)).ToList();
      foreach (var doc in docs)
        task.Attachments.Remove(doc);
      
      this.GrantAccessRightsForUpperBoxResponsibles(document, box);
      if (!task.AllAttachments.Where(d => Equals(d, document)).Any())
        task.Attachments.Add(document);
      
      performers = performers.Where(x => x != null).Distinct().ToList();
      foreach (var performer in performers)
      {
        var step = task.RouteSteps.AddNew();
        step.AssignmentType = task.AssignmentType;
        step.Performer = performer;
        step.Deadline = null;
      }
      
      var link = Hyperlinks.Get(document);
      if (signed)
      {
        task.Subject = Resources.SignNoticeSubjectObsoleteFormat(document.Name);
        task.Subject = Sungero.Exchange.Resources.DocumentSignedThreadSubject;
        task.ActiveText = Resources.SignNoticeActiveTextObsoleteFormat(link);
      }
      else
      {
        if (isInvoiceAmendmentRequest)
        {
          task.ThreadSubject = Resources.AmendmentNoticeSubjectObsolete;
          task.Subject = string.Format(Sungero.Exchange.Resources.TaskSubjectTemplate, task.ThreadSubject, document.Name);
          task.ActiveText = Resources.AmendmentNoticeActiveTextObsoleteFormat(link);
        }
        else
        {
          task.ThreadSubject = Resources.RejectNoticeSubjectObsolete;
          task.Subject = string.Format(Sungero.Exchange.Resources.TaskSubjectTemplate, task.ThreadSubject, document.Name);
          task.ActiveText = Resources.RejectNoticeActiveTextObsoleteFormat(link);
        }

        if (!string.IsNullOrEmpty(reason))
          task.ActiveText += Environment.NewLine + Resources.DocumentCommentFormat(reason);
      }

      task.Subject = CutText(task.Subject, task.Info.Properties.Subject.Length);
      
      task.Save();
      task.Start();
    }

    /// <summary>
    /// Создать уведомление о получении ответа от контрагента.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="trackingLine">Строка выдачи.</param>
    /// <param name="signed">Признак подписания. True - если документ подписан контрагентом, иначе - false.</param>
    /// <param name="obsolete">Признак, что документ был отозван нами в сервисе обмена.</param>
    /// <param name="isInvoiceAmendmentRequest">Признак, что отправлено уточнение по СФ или УПД.</param>
    /// <param name="performers">Список пользователей, кому будет отправлено уведомление.</param>
    /// <param name="activeText">Текст уведомления.</param>
    protected virtual void CreateDocumentReplyNotice(IBoxBase box, IOfficialDocumentTracking trackingLine, bool signed, bool obsolete,
                                                     bool isInvoiceAmendmentRequest, List<IUser> performers, string activeText)
    {
      var task = Workflow.SimpleTasks.Null;
      var document = trackingLine.OfficialDocument;
      var docGuid = document.GetEntityMetadata().GetOriginal().NameGuid;
      var parentTask = ExchangeDocumentProcessingTasks.GetAll()
        .Where(t => t.AttachmentDetails.Any(att => att.AttachmentId == document.Id && att.EntityTypeGuid == docGuid))
        .FirstOrDefault();
      
      if (trackingLine.ReturnTask != null)
      {
        task = Workflow.SimpleTasks.CreateAsSubtask(trackingLine.ReturnTask);
        performers.Add(trackingLine.ReturnTask.Author);
      }
      else if (parentTask != null)
      {
        // Подзадача к заданию на обработку, при отзыве формализованного документа в сервисе обмена нашей НОР.
        task = Workflow.SimpleTasks.CreateAsSubtask(parentTask);
      }
      else
      {
        task = Workflow.SimpleTasks.Create();
      }
      
      task.AssignmentType = Workflow.SimpleTask.AssignmentType.Notice;
      task.NeedsReview = false;
      
      this.GrantAccessRightsForUpperBoxResponsibles(trackingLine.OfficialDocument, box);      
      if (!task.AllAttachments.Where(d => Equals(d, trackingLine.OfficialDocument)).Any())
        task.Attachments.Add(trackingLine.OfficialDocument);
      
      performers.Add(trackingLine.DeliveredTo);
      performers = performers.Distinct().ToList();
      foreach (var performer in performers)
      {
        var step = task.RouteSteps.AddNew();
        step.Performer = performer;
        step.AssignmentType = Workflow.SimpleTask.AssignmentType.Notice;
        step.Deadline = null;
      }

      if (obsolete)
        task.ThreadSubject = string.Format(Resources.RevocationNoticeOurSubjectTerminate);
      else if (isInvoiceAmendmentRequest)
        task.ThreadSubject = string.Format(Resources.AmendedDocumentSubject);
      else if (signed)
        task.ThreadSubject = string.Format(Resources.AssignDocumentSubject);
      else
        task.ThreadSubject = string.Format(Resources.RejectDocumentSubject);
      
      task.Subject = string.Format(Sungero.Exchange.Resources.TaskSubjectTemplate, task.ThreadSubject, trackingLine.OfficialDocument.Name);
      task.Subject = CutText(task.Subject, task.Info.Properties.Subject.Length);
      
      task.ActiveText = activeText;
      
      task.Save();
      task.Start();
    }

    /// <summary>
    /// Отправить уведомление ответственному о поступлении ответа от контрагента.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="trackingString">Строка выдачи.</param>
    /// <param name="versionNumber">Версия документа.</param>
    /// <param name="versionIsChanged">Признак того, что версия была изменена.</param>
    /// <param name="signed">Признак подписания. True - если документ подписан контрагентом, иначе - false.</param>
    /// <param name="signatoryInfo">Информация о контрагенте.</param>
    /// <param name="isInvoiceAmendmentRequest">Отправлено уточнение по СФ или УПД.</param>
    /// <param name="serviceName">Наименование сервиса обмена.</param>
    /// <param name="comment">Комментарии контрагента.</param>
    protected virtual void SendDocumentReplyNotice(IBoxBase box, IOfficialDocumentTracking trackingString, int? versionNumber,
                                                   bool versionIsChanged, bool signed, string signatoryInfo,
                                                   bool isInvoiceAmendmentRequest, string serviceName, string comment)
    {
      var performers = new List<IUser>();
      var activeText = string.Empty;
      var docHyperlink = Hyperlinks.Get(trackingString.OfficialDocument);
      var info = Functions.ExchangeDocumentInfo.GetLastDocumentInfo(trackingString.OfficialDocument);
      var boxResponsible = ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(box, info.Counterparty, new List<IExchangeDocumentInfo>() { info });
      
      activeText = FillDocumentReplyNoticeTexts(versionNumber, versionIsChanged, signed, signatoryInfo, isInvoiceAmendmentRequest, activeText, comment, serviceName, docHyperlink);

      performers.Add(boxResponsible);
      
      if (trackingString.ReturnTask != null)
      {
        // Агент автоматически выполняет задание на контроль возврата и процесс идет дальше.
        var returnAssignments = Docflow.ApprovalCheckReturnAssignments.GetAll().Where(x => Equals(x.Task, trackingString.ReturnTask) && x.Status == Workflow.Assignment.Status.InProcess).ToList();
        
        if (returnAssignments.Any())
        {
          var isMainDocument = Docflow.ApprovalTasks.As(trackingString.ReturnTask).DocumentGroup.OfficialDocuments.Contains(trackingString.OfficialDocument);
          
          if (isMainDocument)
          {
            // Разделено установка признака AutoReturned и выполнение заданий, т.к. при большом количестве исполнителей схема успевает начать свою рассылку.
            foreach (var assignment in returnAssignments)
            {
              assignment.ActiveText = activeText;
              assignment.AutoReturned = true;
              assignment.Save();
            }
          }
          
          foreach (var assignment in returnAssignments)
          {
            if (isMainDocument)
            {
              var completeResult = signed ? Docflow.ApprovalCheckReturnAssignment.Result.Signed : Docflow.ApprovalCheckReturnAssignment.Result.NotSigned;
              assignment.Complete(completeResult);
            }
            
            performers.Add(assignment.Performer);
          }
          
          // Если не подписано, уведомляем всех кто согласовывал и подписывал документ (логика из задачи).
          if (!signed)
            performers.AddRange(Docflow.PublicFunctions.ApprovalTask.GetAllApproversAndSignatories(Docflow.ApprovalTasks.As(trackingString.ReturnTask)));
          
          performers = performers.Distinct().ToList();
        }
      }
      
      if (ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box) && info.DownloadSession == null)
        this.CreateDocumentReplyNotice(box, trackingString, signed, false, isInvoiceAmendmentRequest, performers, activeText);
    }

    private static string FillDocumentReplyNoticeTexts(int? versionNumber, bool versionIsChanged, bool signed, string signatoryInfo,
                                                       bool isInvoiceAmendmentRequest, string activeText, string comment,
                                                       string serviceName, string documentHyperlink)
    {
      if (signed)
      {
        activeText = string.Format(Resources.AssignDocumentVersion, documentHyperlink, versionNumber, serviceName) +
          Environment.NewLine +
          string.Format(Resources.AssignDocumentBy, signatoryInfo);

        if (versionIsChanged)
          activeText += Environment.NewLine + Resources.DocumentHasChangedAfterSendToCounterpartyFormat(versionNumber);
      }

      if (isInvoiceAmendmentRequest)
      {
        activeText = string.Format(Resources.AmendedDocumentVersion, documentHyperlink, versionNumber.Value);
        activeText += Environment.NewLine;
        activeText += string.Format(Resources.AmendedDocumentBy, signatoryInfo);

        if (!string.IsNullOrEmpty(comment))
        {
          activeText += Environment.NewLine;
          activeText += string.Format(Resources.RejectDocumentComment, comment);
        }
      }

      if (!signed && !isInvoiceAmendmentRequest)
      {
        activeText = string.Format(Resources.RejectDocumentVersion, documentHyperlink, versionNumber.Value);
        activeText += Environment.NewLine;
        activeText += string.Format(Resources.RejectDocumentBy, signatoryInfo);

        if (!string.IsNullOrEmpty(comment))
        {
          activeText += Environment.NewLine;
          activeText += string.Format(Resources.RejectDocumentComment, comment);
        }
      }

      return activeText;
    }
    
    #endregion
    
    #region Обработка аннулирования и отзыва

    /// <summary>
    /// Обработать сообщение об аннулировании или отзыве документа.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItems">Все элементы очереди.</param>
    /// <param name="sender">Контрагент.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessAnnulmentOrCancellation(IMessage message, List<IMessageQueueItem> queueItems,
                                                          ICounterparty sender, bool isIncoming, IBoxBase box)
    {
      this.LogDebugFormat(message, box, "Execute ProcessAnnulmentOrCancellation.");
      var result = false;
      var exchangeService = ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box);
      var fromCounterparty = isIncoming && !message.IsReply || !isIncoming && message.IsReply;

      foreach (var document in message.PrimaryDocuments.Where(x => x.DocumentType == NpoComputer.DCX.Common.DocumentType.RevocationOffer).ToList())
      {
        var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, document.ParentServiceEntityId);
        
        // Если нет инфошки и нет документа в очереди - считаем обработанным.
        // Если для исходящего сообщения есть инфо, но нет документа (случай отправленного от нас неформализованного документа с требованием подписи) - считаем обработанным.
        // Ну или инфошка почему то уже с признаком обработанности - тогда тоже считаем обработанным и пропускаем.
        var isNonformalizedOutgoingDocumentCancellation = !isIncoming && exchangeDocumentInfo != null && exchangeDocumentInfo.Document == null;
        if (exchangeDocumentInfo == null ||
            exchangeDocumentInfo.RevocationStatus == Exchange.ExchangeDocumentInfo.RevocationStatus.Revoked ||
            isNonformalizedOutgoingDocumentCancellation)
        {
          var fetchQueueItems = ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box)) &&
                                                                      q.ProcessingStatus != ExchangeCore.MessageQueueItem.ProcessingStatus.Processed);
          if (fetchQueueItems.Any(q => q.Documents.Any(d => d.ExternalId == document.ParentServiceEntityId &&
                                                       d.Type == ExchangeCore.MessageQueueItemDocuments.Type.Primary)))
          {
            this.LogDebugFormat(message, box, "Document not found for received annulment or cancellation, RootServiceEntityId '{0}'.", document.ParentServiceEntityId);
            result = false;
            continue;
          }
          this.LogDebugFormat(message, box, "Exit ProcessAnnulmentOrCancellation.");
          result = true;
        }
        
        // Не шлём уведомления по уже аннулированному или еще не полученному документу.
        if (exchangeDocumentInfo != null &&
            exchangeDocumentInfo.Document != null && exchangeDocumentInfo.RevocationStatus != Exchange.ExchangeDocumentInfo.RevocationStatus.Revoked)
        {
          var version = exchangeDocumentInfo.Document.Versions.SingleOrDefault(v => v.Id == exchangeDocumentInfo.VersionId);
          var versionNumber = version == null ? null : version.Number;
          var comment = fromCounterparty ? string.Format("{0}|{1}", sender.Name, exchangeService.Name) : exchangeService.Name;
          var isAnnulment = document.SignStatus != NpoComputer.DCX.Common.SignStatus.None;
          
          // Запись служебной информации в инфошку.
          if (!exchangeDocumentInfo.ServiceDocuments.Any(d => d.DocumentId == document.ServiceEntityId))
          {
            var serviceDoc = exchangeDocumentInfo.ServiceDocuments.AddNew();
            serviceDoc.DocumentId = document.ServiceEntityId;
            serviceDoc.ParentDocumentId = document.ParentServiceEntityId;
            serviceDoc.CounterpartyId = isIncoming ? message.Sender.Organization.OrganizationId : message.Receiver.Organization.OrganizationId;
            serviceDoc.DocumentType = isAnnulment
              ? Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Annulment
              : Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Cancellation;
            serviceDoc.Date = ToTenantTime(document.Date == DateTime.MinValue ? message.TimeStamp : document.Date);
            serviceDoc.Body = document.Content;
            var signature = message.Signatures.Single(s => s.DocumentId == serviceDoc.DocumentId);
            serviceDoc.Sign = signature.Content;
            serviceDoc.FormalizedPoAUnifiedRegNo = signature.FormalizedPoAUnifiedRegNumber;
            exchangeDocumentInfo.Save();
          }

          if (isAnnulment)
          {
            this.ProcessAnnulment(exchangeDocumentInfo, document, isIncoming, fromCounterparty, versionNumber, comment);
          }
          else
          {
            this.ProcessCancellation(exchangeDocumentInfo, document, fromCounterparty, box, versionNumber, comment);
          }
          
          // Штамп об аннулировании или отзыве проставляем на каждую версию.
          var accountingDocument = Docflow.AccountingDocumentBases.As(exchangeDocumentInfo.Document);
          if (accountingDocument != null && accountingDocument.IsFormalized == true)
          {
            this.LogDebugFormat(exchangeDocumentInfo, "Execute GeneratePublicBodyForFormalizedDocument for annulment.");
            foreach (var accountVersion in accountingDocument.Versions)
              Docflow.PublicFunctions.Module.Remote.GeneratePublicBodyForFormalizedDocument(accountingDocument, accountVersion.Id, accountingDocument.ExchangeState);
          }
          else
          {
            this.LogDebugFormat(exchangeDocumentInfo, "Execute GeneratePublicBodyForNonformalizedDocument for annulment.");
            Docflow.PublicFunctions.Module.Remote.GeneratePublicBodyForNonformalizedDocument(exchangeDocumentInfo.Document, version.Id);
          }
          result = true;
        }
        
        // Если такой документ уже занесён, то пришла вторая подпись, заносим и её.
        if (exchangeDocumentInfo != null && exchangeDocumentInfo.ServiceDocuments
            .Any(d => d.DocumentId == document.ServiceEntityId && d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Annulment))
        {
          this.LogDebugFormat(exchangeDocumentInfo, "Execute processing answer for annulment.");
          var serviceDoc = exchangeDocumentInfo.ServiceDocuments.Single(d => d.DocumentId == document.ServiceEntityId &&
                                                                        d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Annulment);
          var sign = message.Signatures.SingleOrDefault(s => s.DocumentId == document.ServiceEntityId);
          
          // Если подпись найдена - то это подписание, записываем.
          if (sign != null && !Enumerable.SequenceEqual(serviceDoc.Sign, sign.Content))
          {
            serviceDoc.SecondSign = sign.Content;
            serviceDoc.SecondFormalizedPoAUnifiedRegNo = sign.FormalizedPoAUnifiedRegNumber;
            exchangeDocumentInfo.Save();
          }
          else if (message.ReglamentDocuments.Any(r => (r.DocumentType == ReglamentDocumentType.AmendmentRequest || r.DocumentType == ReglamentDocumentType.Rejection) && r.ParentServiceEntityId == document.ServiceEntityId))
          {
            // Вариант с отказом в аннулировании.
            var annulment = message.ReglamentDocuments.Single(r => (r.DocumentType == ReglamentDocumentType.AmendmentRequest || r.DocumentType == ReglamentDocumentType.Rejection) && r.ParentServiceEntityId == document.ServiceEntityId);
            this.SaveRejectToDocumentInfo(message, exchangeDocumentInfo, annulment,
                                          isIncoming, Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Reject);
          }
        }
      }

      return result;
    }

    /// <summary>
    /// Обработать аннулирование.
    /// </summary>
    /// <param name="info">Информация о документе в сервисе обмена.</param>
    /// <param name="document">Документ.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="fromCounterparty">Признак авторства запроса на аннулирование.</param>
    /// <param name="versionNumber">Номер версии, которую аннулируют.</param>
    /// <param name="comment">Комментарий в истории документа.</param>
    protected virtual void ProcessAnnulment(IExchangeDocumentInfo info, IDocument document, bool isIncoming, bool fromCounterparty,
                                            int? versionNumber, string comment)
    {
      this.LogDebugFormat(info, "Execute ProcessAnnulment.");
      // Признак того, а можно ли "аннулировать" документ в текущей его версии. Если нет - то обновляем только инфошку, документ не трогаем.
      var canSendAnswer = Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.GetLastDocumentInfo(info.Document) == info;
      
      if (document.SignStatus != NpoComputer.DCX.Common.SignStatus.None)
      {
        // Аннулирование.
        if (document.SignStatus == NpoComputer.DCX.Common.SignStatus.Signed)
        {
          if (ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(info.Box) && info.DownloadSession == null)
            this.CreateRevocationTask(info, fromCounterparty, document.Comment, true, false);
          if (canSendAnswer)
          {
            Docflow.PublicFunctions.OfficialDocument.SetObsolete(info.Document, true);
            info.Document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Terminated;
            info.Document.ExternalApprovalState = null;
          }
          info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Terminated;
          var operation = new Enumeration(fromCounterparty ? Constants.Module.Exchange.ObsoletedByCounterparty : Constants.Module.Exchange.ObsoleteOur);
          info.Document.History.Write(operation, operation, comment, versionNumber);
          info.Document.Save();
          info.Save();
        }
        
        // Запрос на аннулирование обрабатывается только входящий.
        if (document.SignStatus == NpoComputer.DCX.Common.SignStatus.Waiting && ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(info.Box) &&
            info.DownloadSession == null)
        {
          // Задание на аннулирование, если нет задания в работе.
          if (info.RevocationTask == null || info.RevocationTask.Status != Workflow.Task.Status.InProcess)
          {
            if (isIncoming)
              this.CreateRevocationTask(info, fromCounterparty, document.Comment, true, true);
            else
              this.CreateRequestedAnnulmentNotice(info, document.Comment);
          }
        }
        
        if (document.SignStatus == NpoComputer.DCX.Common.SignStatus.Rejected)
        {
          // Передумали подписывать - откатываем статус подписания.
          info.RevocationStatus = Exchange.ExchangeDocumentInfo.RevocationStatus.None;
          info.Save();
        }
      }
    }

    /// <summary>
    /// Обработать отзыв.
    /// </summary>
    /// <param name="info">Информация о документе в сервисе обмена.</param>
    /// <param name="document">Документ.</param>
    /// <param name="fromCounterparty">Признак авторства отзыва.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="versionNumber">Номер версии, которую отозвали.</param>
    /// <param name="comment">Комментарий в истории документа.</param>
    protected virtual void ProcessCancellation(IExchangeDocumentInfo info, IDocument document, bool fromCounterparty,
                                               IBoxBase box, int? versionNumber, string comment)
    {
      this.LogDebugFormat(info, "Execute ProcessCancellation.");
      // Признак того, а можно ли "отозвать" документ в текущей его версии. Если нет - то обновляем только инфошку, документ не трогаем.
      var canSendAnswer = Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.GetLastDocumentInfo(info.Document) == info;
      
      // Изменяем статус документа заранее, чтобы правильно обработать контроль возврата.
      if (canSendAnswer)
      {
        Docflow.PublicFunctions.OfficialDocument.SetObsolete(info.Document, false);
        info.Document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Obsolete;
        info.Document.ExternalApprovalState = null;
        info.Document.Save();
      }
      
      // Отзыв.
      var tracking = info.Document.Tracking.FirstOrDefault(x => x.ExternalLinkId == info.Id);
      if (tracking != null)
      {
        var docHyperlink = Hyperlinks.Get(tracking.OfficialDocument);
        var activeText = Resources.RevocationNoticeOurActiveTextTerminateFormat(docHyperlink).ToString();
        var performers = new List<IUser>();
        
        if (tracking.ReturnTask != null)
        {
          // Агент автоматически выполняет задание на контроль возврата и процесс идет дальше.
          var returnAssignments = Docflow.ApprovalCheckReturnAssignments.GetAll().Where(x => Equals(x.Task, tracking.ReturnTask) && x.Status == Workflow.Assignment.Status.InProcess).ToList();
          
          if (returnAssignments.Any())
          {
            // Разделено установка признака AutoReturned и выполнение заданий, т.к. при большом количестве исполнителей схема успевает начать свою рассылку.
            foreach (var assignment in returnAssignments)
            {
              assignment.ActiveText = Resources.CheckReturnRevocationResult;
              assignment.AutoReturned = true;
              assignment.Save();
            }
            
            foreach (var assignment in returnAssignments)
            {
              var completeResult = Docflow.ApprovalCheckReturnAssignment.Result.NotSigned;
              assignment.Complete(completeResult);
              performers.Add(assignment.Performer);
            }
          }
          
          performers.AddRange(Docflow.PublicFunctions.ApprovalTask.GetAllApproversAndSignatories(Docflow.ApprovalTasks.As(tracking.ReturnTask)));
        }
        
        // Отправить уведомление ответственному за а/я.
        var boxResponsible = ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(box, info.Counterparty,
                                                                                                        new List<IExchangeDocumentInfo>() { info });
        
        performers.Add(boxResponsible);
        performers = performers.Distinct().ToList();
        
        if (!string.IsNullOrEmpty(document.Comment))
        {
          activeText += Environment.NewLine;
          activeText += string.Format(Resources.DocumentComment, document.Comment);
        }
        
        var exchangeService = ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box);
        if (ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box) && info.DownloadSession == null)
          this.CreateDocumentReplyNotice(box, tracking, false, true, false, performers, activeText);
        
        tracking.ReturnResult = Docflow.OfficialDocumentTracking.ReturnResult.NotSigned;
        tracking.Note = Resources.RevocationTrackingNoteFormat(exchangeService.Name);
      }
      else
      {
        if (ExchangeCore.PublicFunctions.BoxBase.NeedReceiveTask(box) && info.DownloadSession == null)
          this.CreateRevocationTask(info, fromCounterparty, document.Comment, false, false);
      }

      var operation = new Enumeration(fromCounterparty ? Constants.Module.Exchange.TerminatedByCounterparty : Constants.Module.Exchange.TerminateOur);
      info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Obsolete;
      info.Document.History.Write(operation, operation, comment, versionNumber);
      info.Document.Save();
      info.Save();
    }

    /// <summary>
    /// Создать черновик задачи об аннулировании/отзыве документа.
    /// </summary>
    /// <param name="info">Информация о документе обмена.</param>
    /// <param name="createAssignments">True, если надо отправить задания, false - уведомления.</param>
    /// <returns>Черновик задачи.</returns>
    protected virtual ISimpleTask CreateRevocationDraftTask(IExchangeDocumentInfo info, bool createAssignments)
    {
      var docGuid = info.Document.GetEntityMetadata().GetOriginal().NameGuid;
      var parentTask = ExchangeDocumentProcessingTasks.GetAll()
        .Where(t => t.AttachmentDetails.Any(att => att.AttachmentId == info.Document.Id && att.EntityTypeGuid == docGuid))
        .FirstOrDefault();
      var task = Workflow.SimpleTasks.Null;
      
      if (parentTask != null)
        task = Workflow.SimpleTasks.CreateAsSubtask(parentTask);
      else if (info.RevocationTask != null)
        task = Workflow.SimpleTasks.CreateAsSubtask(info.RevocationTask);
      else
        task = Workflow.SimpleTasks.Create();
      
      var asgType = createAssignments ? Workflow.SimpleTask.AssignmentType.Assignment : Workflow.SimpleTask.AssignmentType.Notice;
      task.AssignmentType = asgType;
      
      // При создании подзадачи в нее копируются все вложения.
      var docs = task.AllAttachments.Where(d => !Equals(d, info.Document)).ToList();
      foreach (var doc in docs)
        task.Attachments.Remove(doc);
      
      this.GrantAccessRightsForUpperBoxResponsibles(info.Document, info.Box);
      if (!task.AllAttachments.Where(d => Equals(d, info.Document)).Any())
        task.Attachments.Add(info.Document);
      
      var performers = this.GetRevocationTaskPerformers(info, parentTask);

      performers = performers.Where(p => p != null).Distinct().ToList();
      
      if (!performers.Any())
        performers.Add(ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(info.Box, info.Counterparty, new List<IExchangeDocumentInfo>() { info }));
      
      foreach (var performer in performers)
      {
        var step = task.RouteSteps.AddNew();
        step.Performer = performer;
        step.AssignmentType = asgType;
        if (!createAssignments)
          step.Deadline = null;
        
        // Задание со сроком в 2 рабочих дня.
        if (createAssignments)
          step.Deadline = Calendar.Now.AddWorkingHours(performer, 16);
      }
      task.NeedsReview = false;
      
      return task;
    }
    
    /// <summary>
    /// Создать и стартовать задачу об аннулировании/отзыве контрагентом.
    /// </summary>
    /// <param name="info">Информация о документе обмена.</param>
    /// <param name="fromCounterparty">Аннулирование пришло от контрагента.</param>
    /// <param name="reason">Причина аннулирования/отзыва.</param>
    /// <param name="isAnnulment">True - если аннулирован, false - если отозван.</param>
    /// <param name="createAssignments">True, если надо отправить задания, false - уведомления.</param>
    /// <remarks>Еще обновляется статус и ИД задачи на аннулирование в инфошке.</remarks>
    protected virtual void CreateRevocationTask(IExchangeDocumentInfo info, bool fromCounterparty, string reason, bool isAnnulment, bool createAssignments)
    {
      var task = this.CreateRevocationDraftTask(info, createAssignments);

      if (createAssignments)
        this.FillTaskAssignmentText(info, task, reason);
      else if (isAnnulment)
        this.FillTaskAnnulmentNoticeText(info, fromCounterparty, task, reason);
      else
        this.FillTaskCancellationNoticeText(info, fromCounterparty, task, reason);
      
      task.Subject = CutText(task.Subject, task.Info.Properties.Subject.Length);
      task.Save();
      task.Start();

      // Обновить статус документа.
      info.RevocationStatus = createAssignments ?
        Exchange.ExchangeDocumentInfo.RevocationStatus.Waiting :
        Exchange.ExchangeDocumentInfo.RevocationStatus.Revoked;

      // Если было создано задание - запишем задачку, чтобы не пересоздавать их на каждый чих.
      if (createAssignments)
        info.RevocationTask = task;

      info.Save();
    }
    
    /// <summary>
    /// Отправить уведомление об аннулировании документа нашей организацией.
    /// </summary>
    /// <param name="info">Информация о документе обмена.</param>
    /// <param name="reason">Причина аннулирования/отзыва.</param>
    protected virtual void CreateRequestedAnnulmentNotice(IExchangeDocumentInfo info, string reason)
    {
      var task = this.CreateRevocationDraftTask(info, false);

      this.FillTaskRequestedAnnulmentText(info, task);
      
      this.FillTaskRevocationReason(task, reason);
      task.Subject = CutText(task.Subject, task.Info.Properties.Subject.Length);
      task.Save();
      task.Start();
    }
    
    /// <summary>
    /// Заполнить тему и текст задания на обработку аннулирования.
    /// </summary>
    /// <param name="info">Информация о документе обмена.</param>
    /// <param name="task">Задача на аннулирование документа.</param>
    /// <param name="reason">Причина аннулирования/отзыва.</param>
    protected virtual void FillTaskAssignmentText(IExchangeDocumentInfo info, ISimpleTask task, string reason)
    {
      var link = Hyperlinks.Get(info.Document);
      
      task.Subject = Resources.RevocationNoticeSubjectInProcessFormat(info.Document.Name);
      task.ThreadSubject = Sungero.Exchange.Resources.RevocationTaskThreadSubjectInProcess;
      task.ActiveText = Resources.RevocationNoticeActiveTextInProcessFormat(link);
      this.FillTaskRevocationReason(task, reason);
      
      var service = ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(info.Box);
      task.ActiveText += Environment.NewLine;
      task.ActiveText += Environment.NewLine;
      task.ActiveText +=
        Resources.RevocationNoticeInProcessCommentFormat(service.Info.Properties.ExchangeProvider.GetLocalizedValue(service.ExchangeProvider),
                                                         service.LogonUrl);
    }
    
    /// <summary>
    /// Заполнить тему и текст уведомления об аннулировании.
    /// </summary>
    /// <param name="info">Информация о документе обмена.</param>
    /// <param name="fromCounterparty">Аннулирование пришло от контрагента.</param>
    /// <param name="task">Задача на аннулирование документа.</param>
    /// <param name="reason">Причина аннулирования/отзыва.</param>
    protected virtual void FillTaskAnnulmentNoticeText(IExchangeDocumentInfo info, bool fromCounterparty, ISimpleTask task, string reason)
    {
      var link = Hyperlinks.Get(info.Document);
      task.ThreadSubject = fromCounterparty
        ? Resources.RevocationNoticeSubjectObsolete
        : Resources.RevocationNoticeOurSubjectObsolete;
      task.Subject = string.Format(Sungero.Exchange.Resources.TaskSubjectTemplate, task.ThreadSubject, info.Document.Name);
      
      task.ActiveText = fromCounterparty
        ? Resources.RevocationNoticeActiveTextObsoleteFormat(link)
        : Resources.RevocationNoticeOurActiveTextObsoleteFormat(link);
      
      this.FillTaskRevocationReason(task, reason);
    }
    
    /// <summary>
    /// Заполнить тему и текст уведомления об отказе.
    /// </summary>
    /// <param name="info">Информация о документе обмена.</param>
    /// <param name="fromCounterparty">Аннулирование пришло от контрагента.</param>
    /// <param name="task">Задача на аннулирование документа.</param>
    /// <param name="reason">Причина аннулирования/отзыва.</param>
    protected virtual void FillTaskCancellationNoticeText(IExchangeDocumentInfo info, bool fromCounterparty, ISimpleTask task, string reason)
    {
      var link = Hyperlinks.Get(info.Document);
      task.ThreadSubject = fromCounterparty
        ? Resources.RevocationNoticeSubjectTerminate
        : Resources.RevocationNoticeOurSubjectTerminate;
      task.Subject = string.Format(Sungero.Exchange.Resources.TaskSubjectTemplate, task.ThreadSubject, info.Document.Name);
      
      task.ActiveText = fromCounterparty
        ? Resources.RevocationNoticeActiveTextTerminateFormat(link)
        : Resources.RevocationNoticeOurActiveTextTerminateFormat(link);
      
      this.FillTaskRevocationReason(task, reason);
    }
    
    /// <summary>
    /// Заполнить тему и текст уведомления о запросе на аннулирование.
    /// </summary>
    /// <param name="info">Информация о документе обмена.</param>
    /// <param name="task">Задача на аннулирование документа.</param>
    protected virtual void FillTaskRequestedAnnulmentText(IExchangeDocumentInfo info, ISimpleTask task)
    {
      var link = Hyperlinks.Get(info.Document);
      
      task.Subject = Resources.RequestedAnnulmentNoticeSubjectInProcessFormat(info.Document.Name);
      task.ThreadSubject = Sungero.Exchange.Resources.RevocationTaskThreadSubjectRequestedAnnulment;
      task.ActiveText = Resources.RevocationNoticeActiveTextRequestedAnnulmentFormat(link);
    }
    
    /// <summary>
    /// Заполнить причину аннулирования/отказа.
    /// </summary>
    /// <param name="task">Задача на аннулирование документа.</param>
    /// <param name="reason">Причина аннулирования/отзыва.</param>
    protected virtual void FillTaskRevocationReason(ISimpleTask task, string reason)
    {
      if (!string.IsNullOrWhiteSpace(reason))
      {
        task.ActiveText += Environment.NewLine;
        task.ActiveText += Resources.RevocationNoticeReasonFormat(reason);
      }
    }

    /// <summary>
    /// Получить исполнителей задачи об аннулировании/отзыве контрагентом.
    /// </summary>
    /// <param name="info">Информация о документе.</param>
    /// <param name="parentTask">Основная задача.</param>
    /// <returns>Исполнители.</returns>
    protected virtual List<IRecipient> GetRevocationTaskPerformers(IExchangeDocumentInfo info, IExchangeDocumentProcessingTask parentTask)
    {
      var performers = new List<IRecipient>();
      if (parentTask != null)
      {
        // Ответственный за ящик.
        performers.Add(
          ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(info.Box, info.Counterparty, new List<IExchangeDocumentInfo>() { info }));

        // Исполнители заданий на обработку.
        var assignmentPerformers = ExchangeDocumentProcessingAssignments.GetAll(a => Equals(a.Task, parentTask)).Select(a => a.Performer);
        performers.AddRange(assignmentPerformers);

        // Ответственный за договорной документ.
        var contract = Contracts.ContractualDocuments.As(info.Document);
        if (contract != null && contract.ResponsibleEmployee != null)
          performers.Add(contract.ResponsibleEmployee);
      }
      else
      {
        // Ответственный за возврат из выдачи.
        var tracking = info.Document.Tracking.FirstOrDefault(t => t.ExternalLinkId.ToString() == info.ServiceDocumentId);
        if (tracking != null && tracking.DeliveredTo != null)
          performers.Add(tracking.DeliveredTo);

        // Кто подготовил документ.
        if (info.Document.PreparedBy != null)
          performers.Add(info.Document.PreparedBy);

        // Ответственный за договорной документ (или автор).
        var contract = Contracts.ContractualDocuments.As(info.Document);
        if (contract != null)
        {
          if (contract.ResponsibleEmployee != null)
            performers.Add(contract.ResponsibleEmployee);
          else
            performers.Add(contract.Author);
        }
      }

      return performers;
    }
    
    #endregion

    #region Обработка ИОП

    /// <summary>
    /// Проверить сообщение на наличие подтверждений получения\отправки.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="counterpartyId">Контрагент, от которого получено сообщение. Ожидается сервисный контрагент.</param>
    /// <param name="box">Ящик, через который получено.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessInvoiceConfirmation(IMessage message, IMessageQueueItem queueItem, string counterpartyId, IBusinessUnitBox box)
    {
      this.LogDebugFormat(message, queueItem, box, "Execute ProcessInvoiceConfirmation.");
      foreach (var confirmation in message.ReglamentDocuments.Where(d => d.DocumentType == ReglamentDocumentType.InvoiceConfirmation))
      {
        var info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, confirmation.RootServiceEntityId);
        if (info != null && !info.ServiceDocuments.Any(d => d.DocumentId == confirmation.ServiceEntityId))
        {
          var document = info.ServiceDocuments.AddNew();
          if (confirmation.ParentServiceEntityId == info.ServiceDocumentId)
            document.DocumentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IConfirmation;
          else
          {
            switch (confirmation.ParentReglamentDocumentType)
            {
              case ReglamentDocumentType.AmendmentRequest:
              case ReglamentDocumentType.InvoiceAmendmentRequest:
                document.DocumentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IRjConfirmation;
                break;
              case ReglamentDocumentType.InvoiceReceipt:
              case ReglamentDocumentType.Receipt:
                document.DocumentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IRConfirmation;
                break;
              default:
                document.DocumentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.BTConfirmation;
                break;
            }
          }
          
          document.DocumentId = confirmation.ServiceEntityId;
          document.ParentDocumentId = confirmation.ParentServiceEntityId;
          document.CounterpartyId = counterpartyId;
          document.Date = ToTenantTime(confirmation.DateTime ?? message.TimeStamp);
          document.Body = confirmation.Content;
          document.Sign = message.Signatures.Single(s => s.DocumentId == document.DocumentId).Content;
          info.Save();
        }
        
        if (info == null && this.CanProcessMessageLater(message, queueItem, box, confirmation.RootServiceEntityId))
        {
          this.LogDebugFormat(message, confirmation, "Document info not found for received InvoiceConfirmation: RootServiceEntityId: '{0}'.", confirmation.RootServiceEntityId);
          return false;
        }
      }

      return true;
    }

    /// <summary>
    /// Обработка ИОП.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="sender">Контрагент.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessReceiptNotice(IMessage message, IMessageQueueItem queueItem, ICounterparty sender,
                                                bool isIncoming, IBusinessUnitBox businessUnitBox)
    {
      this.LogDebugFormat(message, queueItem, businessUnitBox, "Execute ProcessReceiptNotice.");
      foreach (var document in message.ReglamentDocuments.Where(d => d.DocumentType == ReglamentDocumentType.Receipt ||
                                                                d.DocumentType == ReglamentDocumentType.InvoiceReceipt))
      {
        var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(businessUnitBox, document.RootServiceEntityId);
        if (exchangeDocumentInfo != null)
        {
          if (!exchangeDocumentInfo.ServiceDocuments.Any(d => d.DocumentId == document.ServiceEntityId) ||
              businessUnitBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis)
          {
            var parent = exchangeDocumentInfo.ServiceDocuments.SingleOrDefault(d => d.DocumentId == document.ParentServiceEntityId);
            if (parent == null && document.ParentServiceEntityId != document.RootServiceEntityId)
            {
              this.LogDebugFormat(message, document, "Service document not found for received Receipt: ParentServiceEntityId: '{0}'.", document.ParentServiceEntityId);
              return false;
            }
            
            Enumeration? documentType = null;
            if (document.DocumentType == ReglamentDocumentType.InvoiceReceipt)
            {
              if (parent == null && document.ParentServiceEntityId == exchangeDocumentInfo.ServiceDocumentId)
                documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReceipt;
              
              if (parent != null)
              {
                if (parent.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReject)
                  documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IRReceipt;
                if (parent.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IConfirmation)
                  documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.ICReceipt;
                if (parent.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IRConfirmation)
                  documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IRCReceipt;
                if (parent.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.NoteReceipt)
                  documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.RNoteReceipt;
              }
            }
            if (document.DocumentType == ReglamentDocumentType.Receipt)
            {
              var parentServiceEntity = exchangeDocumentInfo.ServiceDocuments.FirstOrDefault(d => d.DocumentId == document.ParentServiceEntityId);
              if (parentServiceEntity != null)
              {
                documentType = (parentServiceEntity.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IConfirmation) ?
                  Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.ICReceipt :
                  Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt;
              }
              else
                documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt;
            }
            
            var serviceDoc = exchangeDocumentInfo.ServiceDocuments.FirstOrDefault(d => d.DocumentType == documentType) ?? exchangeDocumentInfo.ServiceDocuments.AddNew();
            serviceDoc.DocumentId = document.ServiceEntityId;
            serviceDoc.ParentDocumentId = document.ParentServiceEntityId;
            serviceDoc.CounterpartyId = isIncoming ? message.Sender.Organization.OrganizationId : message.Receiver.Organization.OrganizationId;
            serviceDoc.DocumentType = documentType;
            serviceDoc.Date = ToTenantTime(document.DateTime ?? message.TimeStamp);
            serviceDoc.Body = document.Content;
            var signature = message.Signatures.Single(s => s.DocumentId == serviceDoc.DocumentId);
            serviceDoc.Sign = signature.Content;
            serviceDoc.FormalizedPoAUnifiedRegNo = signature.FormalizedPoAUnifiedRegNumber;

            exchangeDocumentInfo.Save();
            
            // Если получили ИОП на сам документ - надо записать в историю.
            if (serviceDoc.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReceipt ||
                serviceDoc.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt)
            {
              exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(businessUnitBox, document.ParentServiceEntityId);
              if (exchangeDocumentInfo != null && exchangeDocumentInfo.Document != null &&
                  exchangeDocumentInfo.DeliveryConfirmationStatus != Exchange.ExchangeDocumentInfo.DeliveryConfirmationStatus.Sent)
              {
                var senderName = string.Empty;
                if (sender != null)
                  senderName = sender.Name;
                else if (message.Sender != null && message.Sender.Organization != null)
                  senderName = message.Sender.Organization.Name;
                else
                  senderName = Sungero.Exchange.Resources.NoneCounterparty;
                var historyComment = string.Format("{0}|{1}", senderName, businessUnitBox.ExchangeService.Name);
                
                var detailedOperation = new Enumeration(isIncoming ? Constants.Module.Exchange.GetReadMark : Constants.Module.Exchange.SendReadMark);
                var sentVersion = exchangeDocumentInfo.Document.Versions.FirstOrDefault(x => x.Id == exchangeDocumentInfo.VersionId);
                exchangeDocumentInfo.Document.History.Write(detailedOperation, detailedOperation, historyComment, sentVersion.Number);
                if (this.FixReceiptNotificationForSbis(exchangeDocumentInfo) || exchangeDocumentInfo.RootBox.ExchangeService.ExchangeProvider != ExchangeCore.ExchangeService.ExchangeProvider.Sbis)
                  exchangeDocumentInfo.DeliveryConfirmationStatus = Exchange.ExchangeDocumentInfo.DeliveryConfirmationStatus.Sent;
                exchangeDocumentInfo.Save();
              }
            }
          }
        }
        
        if (exchangeDocumentInfo == null && this.CanProcessMessageLater(message, queueItem, businessUnitBox, document.RootServiceEntityId))
        {
          this.LogDebugFormat(message, document, "Document info not found for received Receipt: ParentServiceEntityId: '{0}'.", document.ParentServiceEntityId);
          return false;
        }
      }
      
      return true;
    }
    
    /// <summary>
    /// Обработка УОП.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="sender">Контрагент.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessNoteReceipt(IMessage message, IMessageQueueItem queueItem, ICounterparty sender,
                                              bool isIncoming, IBusinessUnitBox businessUnitBox)
    {
      this.LogDebugFormat(message, queueItem, businessUnitBox, "Execute ProcessNoteReceipt.");
      foreach (var document in message.ReglamentDocuments.Where(d => d.DocumentType == ReglamentDocumentType.NotificationReceipt))
      {
        var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(businessUnitBox, document.RootServiceEntityId);
        if (exchangeDocumentInfo != null)
        {
          var documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.NoteReceipt;
          var serviceDoc = exchangeDocumentInfo.ServiceDocuments.FirstOrDefault(d => d.DocumentType == documentType) ?? exchangeDocumentInfo.ServiceDocuments.AddNew();
          serviceDoc.DocumentId = document.ServiceEntityId;
          serviceDoc.ParentDocumentId = document.ParentServiceEntityId;
          serviceDoc.CounterpartyId = isIncoming ? message.Sender.Organization.OrganizationId : message.Receiver.Organization.OrganizationId;
          serviceDoc.DocumentType = documentType;
          serviceDoc.Date = ToTenantTime(document.DateTime ?? message.TimeStamp);
          serviceDoc.Body = document.Content;
          serviceDoc.Sign = message.Signatures.Single(s => s.DocumentId == serviceDoc.DocumentId).Content;

          exchangeDocumentInfo.Save();
          
          // Записать в историю.
          this.ProcessRecordHistory(document, isIncoming, sender, documentType, businessUnitBox);
        }
        
        if (exchangeDocumentInfo == null && this.CanProcessMessageLater(message, queueItem, businessUnitBox, document.RootServiceEntityId))
        {
          this.LogDebugFormat(message, document, "Document info not found for received NotificationReceipt: RootServiceEntityId: '{0}'.", document.RootServiceEntityId);
          return false;
        }
      }
      
      return true;
    }
    
    /// <summary>
    /// Обработка ИОП на УОП.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Элемент очереди.</param>
    /// <param name="sender">Контрагент.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="businessUnitBox">Абонентский ящик.</param>
    /// <returns>Признак успешности обработки сообщения.</returns>
    protected virtual bool ProcessReceiptOfNoteReceipt(IMessage message, IMessageQueueItem queueItem, ICounterparty sender,
                                                       bool isIncoming, IBusinessUnitBox businessUnitBox)
    {
      this.LogDebugFormat(message, queueItem, businessUnitBox, "Execute ProcessReceiptOfNoteReceipt");
      foreach (var document in message.ReglamentDocuments.Where(d => d.DocumentType == ReglamentDocumentType.NotificationOnReceiptOfNotificationReceipt))
      {
        var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(businessUnitBox, document.RootServiceEntityId);
        if (exchangeDocumentInfo != null)
        {
          var documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.RNoteReceipt;
          var serviceDoc = exchangeDocumentInfo.ServiceDocuments.FirstOrDefault(d => d.DocumentType == documentType) ?? exchangeDocumentInfo.ServiceDocuments.AddNew();
          serviceDoc.DocumentId = document.ServiceEntityId;
          serviceDoc.ParentDocumentId = document.ParentServiceEntityId;
          serviceDoc.CounterpartyId = isIncoming ? message.Sender.Organization.OrganizationId : message.Receiver.Organization.OrganizationId;
          serviceDoc.DocumentType = documentType;
          serviceDoc.Date = ToTenantTime(document.DateTime ?? message.TimeStamp);
          serviceDoc.Body = document.Content;
          var signature = message.Signatures.Single(s => s.DocumentId == serviceDoc.DocumentId);
          serviceDoc.Sign = signature.Content;
          serviceDoc.FormalizedPoAUnifiedRegNo = signature.FormalizedPoAUnifiedRegNumber;
          serviceDoc.GeneratedName = document.FileName;
          serviceDoc.StageId = document.DocflowStageId;
          exchangeDocumentInfo.Save();
          
          // Записать в историю.
          this.ProcessRecordHistory(document, isIncoming, sender, documentType, businessUnitBox);
        }
        
        if (exchangeDocumentInfo == null)
        {
          if (this.CanProcessMessageLater(message, queueItem, businessUnitBox, document.RootServiceEntityId))
          {
            this.LogDebugFormat(message, document, "Acknowledgment receipt not found for received receipt notification: RootServiceEntityId: '{0}'.", document.RootServiceEntityId);
            return false;
          }
        }
      }
      
      return true;
    }
    
    protected virtual void ProcessRecordHistory(NpoComputer.DCX.Common.IReglamentDocument document, bool isIncoming, ICounterparty sender, Sungero.Core.Enumeration documentType, IBusinessUnitBox businessUnitBox)
    {
      var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(businessUnitBox, document.ParentServiceEntityId);
      if (exchangeDocumentInfo != null && exchangeDocumentInfo.Document != null &&
          exchangeDocumentInfo.DeliveryConfirmationStatus != Exchange.ExchangeDocumentInfo.DeliveryConfirmationStatus.Sent)
      {
        var historyComment = string.Format("{0}|{1}", sender.Name, businessUnitBox.ExchangeService.Name);
        var operation = new Enumeration(isIncoming ? Constants.Module.Exchange.GetRNoteReceiptReadMark : Constants.Module.Exchange.SendRNoteReceiptReadMark);
        
        if (documentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.NoteReceipt)
          operation = new Enumeration(isIncoming ? Constants.Module.Exchange.GetNoteReceiptReadMark : Constants.Module.Exchange.SendNoteReceiptReadMark);
        
        var detailedOperation = new Enumeration(isIncoming ? Constants.Module.Exchange.GetReadMark : Constants.Module.Exchange.SendReadMark);
        
        var sentVersion = exchangeDocumentInfo.Document.Versions.FirstOrDefault(x => x.Id == exchangeDocumentInfo.VersionId);
        exchangeDocumentInfo.Document.History.Write(operation, detailedOperation, historyComment, sentVersion.Number);
        
        if (this.FixReceiptNotificationForSbis(exchangeDocumentInfo))
          exchangeDocumentInfo.DeliveryConfirmationStatus = Exchange.ExchangeDocumentInfo.DeliveryConfirmationStatus.Sent;
        exchangeDocumentInfo.Save();
      }
    }

    /// <summary>
    /// Проверить признак получения ИОПа и отправки УОПа для Sbis.
    /// </summary>
    /// <param name="info">Информация о документе обмена.</param>
    /// <returns>Признак получения ИОПа и отправки УОПа для Sbis.</returns>
    [Remote]
    public virtual bool FixReceiptNotificationForSbis(Exchange.IExchangeDocumentInfo info)
    {
      if (info.RootBox.ExchangeService.ExchangeProvider != ExchangeCore.ExchangeService.ExchangeProvider.Sbis)
      {
        return false;
      }
      
      var docs = ExchangeDocumentInfos.GetAll()
        .Where(x => Equals(x.RootBox, info.RootBox) && x.Document != null &&
               x.ServiceDocuments.Any(d => (d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReceipt ||
                                            d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt) && d.Date != null) &&
               x.ServiceDocuments.Any(d => d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.NoteReceipt && d.Date != null));
      return docs != null;
    }
    
    #endregion
    
    #region Обновление статусов по полученным ответам

    /// <summary>
    /// Обработать документ как отправленный - как из RX, так и из веба.
    /// </summary>
    /// <param name="info">Инфошка документа в сервисе.</param>
    /// <param name="document">Документ.</param>
    /// <param name="receiver">Контрагент.</param>
    /// <param name="isIncoming">Признак входящего сообщения.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="signStatus">Текущий статус документа - не подписывается, ожидает подписи, подписан двумя сторонами.</param>
    private static void MarkDocumentAsSended(IExchangeDocumentInfo info, IOfficialDocument document, ICounterparty receiver,
                                             bool isIncoming, IBoxBase box, SignStatus? signStatus)
    {
      if (!isIncoming)
        using (Sungero.Core.CultureInfoExtensions.SwitchTo(TenantInfo.Culture))
      {
        AddTrackingRecordInfo(info, document, signStatus != SignStatus.None);
      }
      
      if (signStatus == SignStatus.Waiting)
      {
        if (isIncoming)
        {
          document.ExchangeState = Docflow.OfficialDocument.ExchangeState.SignRequired;
          if (info != null)
            info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.SignRequired;
        }
        else
        {
          document.ExchangeState = Docflow.OfficialDocument.ExchangeState.SignAwaited;
          if (info != null)
            info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.SignAwaited;
        }
      }
      else if (signStatus == SignStatus.Signed)
      {
        document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Signed;
        if (info != null)
        {
          info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Signed;
        }
      }
      else
      {
        if (isIncoming)
        {
          document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Received;
          if (info != null)
            info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Received;
        }
        else
        {
          document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Sent;
          if (info != null)
            info.ExchangeState = Exchange.ExchangeDocumentInfo.ExchangeState.Sent;
        }
      }
      
      if (!isIncoming)
      {
        var sendDocument = new Enumeration(Constants.Module.Exchange.SendDocument);
        document.History.Write(sendDocument, sendDocument, string.Format("{0}|{1}", receiver.Name, ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box).Name), document.LastVersion.Number);
      }
      
      document.Save();
      info.Save();
    }

    /// <summary>
    /// Добавить запись выдачи в документе и установить статус согласования с КА.
    /// </summary>
    /// <param name="info">Информация о документе в сервисе обмена.</param>
    /// <param name="document">Документ.</param>
    /// <param name="needSign">Признак требования подписания.</param>
    private static void AddTrackingRecordInfo(IExchangeDocumentInfo info, IOfficialDocument document, bool needSign)
    {
      var tracking = document.Tracking.AddNew();
      if (needSign)
      {
        document.ExternalApprovalState = Sungero.Docflow.OfficialDocument.ExternalApprovalState.OnApproval;
        document.ExchangeState = Docflow.OfficialDocument.ExchangeState.SignAwaited;
        tracking.Action = Docflow.OfficialDocumentTracking.Action.Endorsement;
      }
      else
      {
        tracking.Action = Docflow.OfficialDocumentTracking.Action.Sending;
        document.ExchangeState = Docflow.OfficialDocument.ExchangeState.Sent;
        tracking.ReturnDeadline = null;
      }
      
      tracking.IsOriginal = true;
      tracking.DeliveredTo = Company.Employees.Current ??
        ExchangeCore.PublicFunctions.BoxBase.Remote.GetExchangeDocumentResponsible(info.Box, info.Counterparty, new List<IExchangeDocumentInfo>() { info });
      tracking.Note = Exchange.Resources.SendToCounterpartyNoteFormat(ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(info.Box));
      tracking.ExternalLinkId = info.Id;
    }
    
    #endregion
    
    #endregion
    
    #region Служебные методы обработки сообщений из сервиса обмена

    private static NpoComputer.DCX.ClientApi.Client GetClient(IBusinessUnitBox box)
    {
      var client = ExchangeCore.PublicFunctions.BusinessUnitBox.GetPublicClient(box) as NpoComputer.DCX.ClientApi.Client;
      if (client == null)
        throw AppliedCodeException.Create("Ошибка при создании клиента.");
      
      return client;
    }

    /// <summary>
    /// Проверка необходимости сохранения сообщения в очереди.
    /// </summary>
    /// <param name="message">Сообщение.</param>
    /// <param name="queueItem">Текущий элемент очереди, чтобы игнорировать его при поиске других элементов.</param>
    /// <param name="box">Головной ящик.</param>
    /// <param name="rootServiceDocumentId">ИД основного документа.</param>
    /// <returns>True, если сообщение еще можно обработать. False, если сообщение уже не нужно.</returns>
    protected virtual bool CanProcessMessageLater(IMessage message, IMessageQueueItem queueItem, IBusinessUnitBox box, string rootServiceDocumentId)
    {
      // Если документ уже аннулировали, то принимать ничего уже не надо.
      var root = message.PrimaryDocuments.FirstOrDefault(d => d.ServiceEntityId == rootServiceDocumentId);
      if (root != null && root.RevocationStatus == RevocationStatus.RevocationAccepted)
        return false;
      
      // Если документ не лежит в очереди - сообщение больше не нужно.
      if (!ExchangeCore.MessageQueueItems.GetAll(q => Equals(q.RootBox, box) &&
                                                 !Equals(q, queueItem) &&
                                                 q.ProcessingStatus != ExchangeCore.MessageQueueItem.ProcessingStatus.Processed &&
                                                 q.Documents.Any(d => d.ExternalId == rootServiceDocumentId)).Any())
        return false;
      
      return true;
    }
    
    /// <summary>
    /// Получить ссылку на документ в вебе.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>Ссылка на документ в вебе.</returns>
    [Public, Remote]
    public static string GetDocumentHyperlink(Docflow.IOfficialDocument document)
    {
      var docInfo = Functions.ExchangeDocumentInfo.GetLastDocumentInfo(document);
      if (docInfo == null)
        return string.Empty;
      
      try
      {
        var client = GetClient(docInfo.RootBox);
        return client.GetDocumentUri(docInfo.ServiceMessageId, docInfo.ServiceDocumentId).ToString();
      }
      catch (AppliedCodeException)
      {
        throw;
      }
      catch (Exception ex)
      {
        Log.Exception(ex);
      }
      return string.Empty;
    }
    
    /// <summary>
    /// Получить ссылку на документ в вебе.
    /// </summary>
    /// <param name="messageQueueItem">Элемент очереди сообщений.</param>
    /// <returns>Ссылка на документ в вебе.</returns>
    [Public, Remote]
    public static string GetDocumentHyperlink(IMessageQueueItem messageQueueItem)
    {
      try
      {
        var client = GetClient(messageQueueItem.RootBox);

        // Для формирования ссылки СБИС достаточно ИД сообщения.
        if (Equals(messageQueueItem.RootBox.ExchangeService.ExchangeProvider, ExchangeCore.ExchangeService.ExchangeProvider.Sbis))
          return client.GetDocumentUri(string.Empty, messageQueueItem.ExternalId).ToString();

        // Для регламентных документов запрашиваем информацию из сервиса.
        var message = client.GetMessage(messageQueueItem.ExternalId);
        var document = message.PrimaryDocuments.FirstOrDefault();
        if (document != null)
        {
          // Формирование ссылки для уведомления об аннулировании.
          if (document.DocumentType == NpoComputer.DCX.Common.DocumentType.RevocationOffer &&
              message.ParentServiceMessageId != null &&
              document.ParentServiceEntityId != null)
            return client.GetDocumentUri(message.ParentServiceMessageId, document.ParentServiceEntityId).ToString();
          
          return client.GetDocumentUri(document.ServiceMessageId, document.ServiceEntityId).ToString();
        }
        else
        {
          // Если в сообщении только сервисные документы, ищем основной документ и его сообщение.
          var reglamentDocument = message.ReglamentDocuments.FirstOrDefault();
          return reglamentDocument != null ? client.GetDocumentUri(message.ParentServiceMessageId, reglamentDocument.RootServiceEntityId).ToString() : string.Empty;
        }
      }
      catch (AppliedCodeException)
      {
        throw;
      }
      catch (Exception ex)
      {
        Log.Exception(ex);
      }
      
      return string.Empty;
    }

    /// <summary>
    /// Привести дату к тенантному времени.
    /// </summary>
    /// <param name="datetime">Дата, пришедшая из МКДО.</param>
    /// <returns>Дата во времени тенанта.</returns>
    private static DateTime ToTenantTime(DateTime datetime)
    {
      return Docflow.PublicFunctions.Module.ToTenantTime(datetime);
    }
    
    /// <summary>
    /// Получить список поддерживаемых основных типов документов.
    /// </summary>
    /// <returns>Список типов.</returns>
    protected virtual List<DocumentType> GetSupportedPrimaryDocumentTypes()
    {
      return new List<NpoComputer.DCX.Common.DocumentType>()
      {
        DocumentType.Nonformalized,
        DocumentType.Waybill,
        DocumentType.Invoice,
        DocumentType.InvoiceCorrection,
        DocumentType.InvoiceCorrectionRevision,
        DocumentType.InvoiceRevision,
        DocumentType.Act,
        DocumentType.GeneralTransferSchfSeller,
        DocumentType.GeneralTransferSchfRevisionSeller,
        DocumentType.GeneralTransferSchfDopSeller,
        DocumentType.GeneralTransferSchfDopRevisionSeller,
        DocumentType.GeneralTransferSchfDopCorrectionSeller,
        DocumentType.GeneralTransferSchfDopCorrectionRevisionSeller,
        DocumentType.GeneralTransferSchfCorrectionSeller,
        DocumentType.GeneralTransferSchfCorrectionRevisionSeller,
        DocumentType.GeneralTransferDopSeller,
        DocumentType.GeneralTransferDopRevisionSeller,
        DocumentType.GeneralTransferDopCorrectionSeller,
        DocumentType.GeneralTransferDopCorrectionRevisionSeller,
        DocumentType.WorksTransferSeller,
        DocumentType.WorksTransferRevisionSeller,
        DocumentType.GoodsTransferSeller,
        DocumentType.GoodsTransferRevisionSeller
      };
    }
    
    /// <summary>
    /// Получить список поддерживаемых регламентных типов документов.
    /// </summary>
    /// <returns>Список типов.</returns>
    protected virtual List<ReglamentDocumentType> GetSupportedReglamentDocumentTypes()
    {
      return new List<NpoComputer.DCX.Common.ReglamentDocumentType>()
      {
        ReglamentDocumentType.ActClientTitle,
        ReglamentDocumentType.WaybillBuyerTitle,
        ReglamentDocumentType.GeneralTransferBuyer,
        ReglamentDocumentType.GeneralTransferCorrectionBuyer,
        ReglamentDocumentType.GoodsTransferBuyer,
        ReglamentDocumentType.WorksTransferBuyer
      };
    }
    
    /// <summary>
    /// Получить список поддерживаемых регламентных типов документов.
    /// </summary>
    /// <returns>Список типов.</returns>
    protected virtual List<ReglamentDocumentType> GetSupportedServiceDocumentTypes()
    {
      return new List<NpoComputer.DCX.Common.ReglamentDocumentType>()
      {
        ReglamentDocumentType.AmendmentRequest,
        ReglamentDocumentType.InvoiceAmendmentRequest,
        ReglamentDocumentType.Rejection,
        ReglamentDocumentType.Receipt,
        ReglamentDocumentType.InvoiceReceipt,
        ReglamentDocumentType.InvoiceConfirmation,
        ReglamentDocumentType.NotificationReceipt,
        ReglamentDocumentType.NotificationOnReceiptOfNotificationReceipt
      };
    }
    
    private static string GetAttributeValueByName(System.Xml.Linq.XElement element, string attributeName)
    {
      var attribute = element.Attribute(attributeName);
      return attribute == null ? string.Empty : attribute.Value;
    }

    /// <summary>
    /// Получить или создать приложение-обработчик для документа.
    /// </summary>
    /// <param name="documentName">Имя документа.</param>
    /// <returns>Приложение-обработчик.</returns>
    [Public, Remote(IsPure = true)]
    public static Sungero.Content.IAssociatedApplication GetOrCreateAssociatedApplicationByDocumentName(string documentName)
    {
      // Определить приложение-обработчик. Если его нет - создать.
      var documentFullName = CommonLibrary.FileUtils.NormalizeFileName(documentName);
      var ext = System.IO.Path.GetExtension(documentFullName).TrimStart('.').ToLower();
      var application = Content.AssociatedApplications.GetByExtension(ext);
      
      // Если разрешения у файла нет, то использовать unknown.
      if (string.IsNullOrWhiteSpace(ext))
        application = Sungero.Content.AssociatedApplications.GetAll()
          .SingleOrDefault(x => x.Sid == Docflow.PublicConstants.Module.UnknownAppSid);
      if (application == null)
      {
        application = Content.AssociatedApplications.Create();
        application.Extension = ext;
        using (Sungero.Core.CultureInfoExtensions.SwitchTo(TenantInfo.Culture))
          application.Name = Resources.AssociatedApplicationFormat(ext);
        application.MonitoringType = Content.AssociatedApplication.MonitoringType.ByProcessAndWindow;
        application.FilesType = Content.FilesTypes.GetAll().FirstOrDefault(f => f.Name == Docflow.Resources.Initialize_FileTypes_Other) ??
          Content.FilesTypes.GetAll().FirstOrDefault();
        application.Save();
        
        Functions.Module.LogDebugFormat(string.Format("Associated application \"{0}\" has been created", ext));
      }
      
      return application;
    }

    /// <summary>
    /// Получить последнюю подпись для документа.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>Подпись.</returns>
    protected virtual ISignature GetLastDocumentSignature(IOfficialDocument document)
    {
      var version = document.LastVersion;
      if (version == null)
        return null;
      
      return Signatures.Get(version).Where(x => x.SignCertificate != null).OrderByDescending(x => x.Id).FirstOrDefault();
    }
    
    /// <summary>
    /// Проверить, что сообщение содержит документы неподдерживаемого типа.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    /// <returns>True, если содержит, иначе False.</returns>
    public virtual bool IsMessageWithUnsupportedDocuments(NpoComputer.DCX.Common.IMessage message)
    {
      return message.PrimaryDocuments.All(x => (!this.GetSupportedPrimaryDocumentTypes().Contains(x.DocumentType.Value) ||
                                                (x.DocumentType == DocumentType.Nonformalized && x.IsUnknownDocumentType == true)));
    }
    
    #endregion

    #endregion

    #region Отправка документов и ответов по документам
    
    #region Подготовка и отправка сообщений

    /// <summary>
    /// Отправить ответ.
    /// </summary>
    /// <param name="documents">Документы.</param>
    /// <param name="counterparty">Контрагент.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <param name="certificate">Сертификат.</param>
    /// <param name="isAgent">Признак вызова из фонового процесса. Иначе - пользователем в RX.</param>
    [Remote, Public]
    public void SendAnswers(List<Docflow.IOfficialDocument> documents, Parties.ICounterparty counterparty, Sungero.ExchangeCore.IBusinessUnitBox box,
                            ICertificate certificate, bool isAgent)
    {
      if (!documents.Any())
        return;
      
      if (HasNotApprovedDocuments(documents.ToArray()))
        throw AppliedCodeException.Create(Resources.SendCounterpartyNotApproved);
      
      foreach (var document in documents)
      {
        var signature = this.GetDocumentSignature(document, certificate);
        if (signature == null)
          throw AppliedCodeException.Create(Resources.SendCounterpartyNotApproved);
      }
      
      foreach (var document in documents)
      {
        try
        {
          Docflow.PublicFunctions.OfficialDocument.SendAnswer(document, box, counterparty, certificate, isAgent);
          
          var info = Functions.ExchangeDocumentInfo.GetIncomingExDocumentInfo(document);
          var sendSignOperation = new Enumeration(Constants.Module.Exchange.SendAnswer);
          var comment = string.Format("{0}|{1}", counterparty.Name, box.ExchangeService.Name);
          
          if (info.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Rejected)
          {
            var signature = this.GetDocumentSignature(document, certificate);
            this.ProcessSharedReject(info, document, false, box, signature.Body, sendSignOperation, comment, string.Empty, string.Empty, false);
          }
          else
            this.ProcessSharedSign(document, info, false, box, document.LastVersion, string.Empty, false, sendSignOperation, comment, false);
        }
        catch (AppliedCodeException)
        {
          throw;
        }
        catch (Exception ex)
        {
          throw AppliedCodeException.Create(ex.Message, ex);
        }
      }
    }

    /// <summary>
    /// Отправить ответ на пакет документов.
    /// </summary>
    /// <param name="documents">Документы пакета.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <param name="certificate">Сертификат.</param>
    /// <param name="isAgent">Признак вызова из фонового процесса. Иначе - пользователем в RX.</param>
    [Obsolete("Теперь функция не актуальна, т.к. реализована поддержка частичного подписания.")]
    public virtual void SendAnswerDocumentsPackage(List<Docflow.IOfficialDocument> documents, Sungero.ExchangeCore.IBusinessUnitBox box,
                                                   ICertificate certificate, bool isAgent)
    {
      var client = GetClient(box);
      var reglamentDocuments = new List<NpoComputer.DCX.Common.IReglamentDocument>();
      var signatures = new List<NpoComputer.DCX.Common.Signature>();
      var serviceCounterpartyId = string.Empty;
      var serviceMessageId = string.Empty;
      var sentDocuments = new Dictionary<int, IOfficialDocument>();
      
      foreach (var document in documents)
      {
        var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetIncomingExDocumentInfo(document);
        serviceCounterpartyId = exchangeDocumentInfo.ServiceCounterpartyId;
        serviceMessageId = exchangeDocumentInfo.ServiceMessageId;

        var signature = this.GetDocumentSignature(document, certificate);
        signatures.Add(CreateExchangeDocumentSignature(box,
                                                       exchangeDocumentInfo.ExternalBuyerTitleId ?? exchangeDocumentInfo.ServiceDocumentId,
                                                       signature.Body, signature.FormalizedPoAUnifiedRegNumber));
        
        exchangeDocumentInfo.ReceiverSignId = signature.Id;
        exchangeDocumentInfo.Save();
        
        var accountingDocument = AccountingDocumentBases.As(document);
        
        // У СФ ИД титула будет пустым всегда.
        if (accountingDocument != null && accountingDocument.BuyerTitleId != null)
        {
          sentDocuments.Add(accountingDocument.BuyerTitleId.Value, document);
          var version = accountingDocument.Versions.Single(v => v.Id == accountingDocument.BuyerTitleId);
          byte[] receipt;
          using (var memory = new System.IO.MemoryStream())
          {
            version.Body.Read().CopyTo(memory);
            receipt = memory.ToArray();
          }
          
          accountingDocument.BuyerSignatureId = signature.Id;
          
          var docWithCertificate = Structures.Module.ReglamentDocumentWithCertificate.Create(FinancialArchive.Resources.BuyerTitleVersionNote, receipt,
                                                                                             certificate, signature.Body, exchangeDocumentInfo.ServiceDocumentId,
                                                                                             box, accountingDocument, exchangeDocumentInfo.ServiceMessageId, null, null,
                                                                                             exchangeDocumentInfo.ServiceCounterpartyId, false,
                                                                                             exchangeDocumentInfo, false, null, null);
          
          var type = NpoComputer.DCX.Common.ReglamentDocumentType.WaybillBuyerTitle;
          
          if (accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer)
            type = NpoComputer.DCX.Common.ReglamentDocumentType.WorksTransferBuyer;
          
          if (accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Act)
            type = NpoComputer.DCX.Common.ReglamentDocumentType.ActClientTitle;
          
          if (accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer)
            type = NpoComputer.DCX.Common.ReglamentDocumentType.GoodsTransferBuyer;
          
          if (accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer)
            type = accountingDocument.IsAdjustment == true ?
              NpoComputer.DCX.Common.ReglamentDocumentType.GeneralTransferCorrectionBuyer :
              NpoComputer.DCX.Common.ReglamentDocumentType.GeneralTransferBuyer;
          
          var serviceDocument = this.CreateReglamentExchangeServiceDocument(docWithCertificate, type);
          reglamentDocuments.Add(serviceDocument);
        }
        else
          sentDocuments.Add(exchangeDocumentInfo.VersionId.Value, document);
      }
      
      try
      {
        this.SendMessage(new List<NpoComputer.DCX.Common.IDocument>(),
                         reglamentDocuments, signatures, client, null, serviceCounterpartyId, box, serviceMessageId);
      }
      catch (Exception ex)
      {
        throw AppliedCodeException.Create(ex.Message, ex);
      }
      
      foreach (var document in sentDocuments)
      {
        if (isAgent)
        {
          Docflow.PublicFunctions.Module.GeneratePublicBodyForExchangeDocument(document.Value, document.Key, Docflow.OfficialDocument.ExchangeState.Signed);
        }
        else
        {
          Docflow.PublicFunctions.Module.GenerateTempPublicBodyForExchangeDocument(document.Value, document.Key);
          Functions.Module.EnqueueXmlToPdfBodyConverter(document.Value, document.Key, Docflow.OfficialDocument.ExchangeState.Signed);
        }
      }
    }
    
    /// <summary>
    /// Отправить ответ на неформализованный документ.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="counterparty">Контрагент.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <param name="certificate">Сертификат.</param>
    /// <param name="isAgent">Признак вызова из фонового процесса. Иначе - пользователем в RX.</param>
    [Public]
    public virtual void SendAnswerToNonformalizedDocument(Docflow.IOfficialDocument document, Parties.ICounterparty counterparty,
                                                          ExchangeCore.IBusinessUnitBox box, ICertificate certificate, bool isAgent)
    {
      var client = GetClient(box);
      var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetIncomingExDocumentInfo(document);
      
      // Нет информации об обмене по последней версии.
      if (exchangeDocumentInfo == null)
        return;
      
      var parentDocumentId = exchangeDocumentInfo.ServiceDocumentId;
      if (string.IsNullOrEmpty(parentDocumentId))
        return;
      
      var signature = this.GetDocumentSignature(document, certificate);
      if (signature == null)
        throw AppliedCodeException.Create(Resources.SendCounterpartyAddendaNotSigned);
      
      if (exchangeDocumentInfo.NeedSign == true)
      {
        // Если документ требовал подписания, проверяем - не подписан/отказан он в вебе.
        var allowedAnswers = client.GetAllowedAnswers(exchangeDocumentInfo.ServiceDocumentId, exchangeDocumentInfo.ServiceMessageId, null);
        if (!allowedAnswers.CanSendSign)
          return;
      }
      else
      {
        // Не отправляем подписи по документам, которые не требовали подписания.
        return;
      }
      
      var dcxSign = CreateExchangeDocumentSignature(box, parentDocumentId, signature.Body, signature.FormalizedPoAUnifiedRegNumber);

      try
      {
        var sentMessage = this.SendMessage(new List<NpoComputer.DCX.Common.IDocument>(),
                                           new List<NpoComputer.DCX.Common.IReglamentDocument>(),
                                           new List<NpoComputer.DCX.Common.Signature>() { dcxSign }, client, counterparty, exchangeDocumentInfo.ServiceCounterpartyId, box, exchangeDocumentInfo.ServiceMessageId);
        exchangeDocumentInfo.ReceiverSignId = signature.Id;
        exchangeDocumentInfo.Save();
        
        var needUpdateSign = box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis && !string.IsNullOrEmpty(signature.FormalizedPoAUnifiedRegNumber);
        
        if (needUpdateSign)
        {
          var patсhedSignature = sentMessage.Signatures.Single(s => string.Equals(s.DocumentId, parentDocumentId));
          Docflow.PublicFunctions.Module.SetDataSignature(document, signature.Id, patсhedSignature.Content);
        }
        
        if (isAgent)
        {
          Docflow.PublicFunctions.Module.GeneratePublicBodyForExchangeDocument(document, exchangeDocumentInfo.VersionId.Value, Docflow.OfficialDocument.ExchangeState.Signed);
        }
        else
        {
          Docflow.PublicFunctions.Module.GenerateTempPublicBodyForExchangeDocument(document, exchangeDocumentInfo.VersionId.Value);
          Functions.Module.EnqueueXmlToPdfBodyConverter(document, exchangeDocumentInfo.VersionId.Value, Docflow.OfficialDocument.ExchangeState.Signed);
        }
        
        this.LogDebugFormat(exchangeDocumentInfo, "Send answer to nonformalized document.");
      }
      catch (Exception ex)
      {
        throw AppliedCodeException.Create(ex.Message, ex);
      }
    }

    /// <summary>
    /// Отправить титул покупателя для накладной или акта.
    /// </summary>
    /// <param name="waybill">Накладная или акт.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="certificate">Сертификат.</param>
    /// <param name="isAgent">Признак вызова из фонового процесса. False используется для вызова из UI.</param>
    [Public]
    public virtual void SendBuyerTitle(Docflow.IAccountingDocumentBase waybill, ExchangeCore.IBusinessUnitBox box, ICertificate certificate, bool isAgent)
    {
      if (box == null)
        throw AppliedCodeException.Create(Resources.BoxIsNotValid);
      
      if (certificate == null)
        throw AppliedCodeException.Create(Resources.CertificateNotFound);
      
      var docsWithCertificate = Structures.Module.ReglamentDocumentWithCertificate.Create();
      var externalDocumentInfo = Functions.ExchangeDocumentInfo.GetIncomingExDocumentInfo(waybill);
      try
      {
        if (externalDocumentInfo == null)
          return;
        
        var version = waybill.Versions.Single(v => v.Id == waybill.BuyerTitleId);
        byte[] receipt;
        var documentName = string.Empty;
        using (var memory = new System.IO.MemoryStream())
        {
          version.Body.Read().CopyTo(memory);
          receipt = memory.ToArray();
          try
          {
            var encoding = Encoding.GetEncoding(1251);
            var title = XDocument.Parse(encoding.GetString(receipt));
            documentName = title.Element("Файл").Attribute("ИдФайл").Value + ".xml";
          }
          catch (Exception ex)
          {
            Logger.Error("Can't parse document name from xml", ex);
          }
        }
        
        var sign = Signatures.Get(version)
          .FirstOrDefault(s => s.SignCertificate != null && s.SignCertificate.Thumbprint == certificate.Thumbprint);
        var signBody = sign.GetDataSignature();
        var unifiedRegistrationNumber = Docflow.PublicFunctions.Module.GetUnsignedAttribute(sign, Docflow.PublicConstants.Module.UnsignedAdditionalInfoKeyFPoA);
        
        waybill.BuyerSignatureId = sign.Id;
        externalDocumentInfo.ReceiverSignId = sign.Id;
        externalDocumentInfo.Save();
        
        docsWithCertificate = Structures.Module.ReglamentDocumentWithCertificate.Create(string.IsNullOrEmpty(documentName) ? FinancialArchive.Resources.BuyerTitleVersionNote : documentName,
                                                                                        receipt, certificate, signBody, externalDocumentInfo.ServiceDocumentId,
                                                                                        box, waybill, externalDocumentInfo.ServiceMessageId, null, null,
                                                                                        externalDocumentInfo.ServiceCounterpartyId, false,
                                                                                        externalDocumentInfo, false, null, unifiedRegistrationNumber);
      }
      catch (Exception ex)
      {
        if (ex is CommonLibrary.Exceptions.PlatformException)
          throw;
        
        throw AppliedCodeException.Create(Resources.ErrorWhileSendingDocToCounterparty, ex);
      }
      
      // По идее, разницы у титулов на уровне тел нет, пока сделаем просто перебором.
      var type = NpoComputer.DCX.Common.ReglamentDocumentType.WaybillBuyerTitle;
      var exchangeService = waybill.BusinessUnitBox.ExchangeService.ExchangeProvider;
      
      if (waybill.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer &&
          exchangeService != ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
        type = NpoComputer.DCX.Common.ReglamentDocumentType.WorksTransferBuyer;
      
      if (waybill.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Act ||
          exchangeService == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc &&
          waybill.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer)
        type = NpoComputer.DCX.Common.ReglamentDocumentType.ActClientTitle;
      
      if (waybill.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer &&
          exchangeService != ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
        type = NpoComputer.DCX.Common.ReglamentDocumentType.GoodsTransferBuyer;
      
      if (waybill.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer)
        type = waybill.IsAdjustment == true ?
          NpoComputer.DCX.Common.ReglamentDocumentType.GeneralTransferCorrectionBuyer :
          NpoComputer.DCX.Common.ReglamentDocumentType.GeneralTransferBuyer;
      
      this.SendServiceDocument(new List<Structures.Module.ReglamentDocumentWithCertificate> { docsWithCertificate }, box, type);
      
      if (isAgent)
      {
        Docflow.PublicFunctions.Module.GeneratePublicBodyForExchangeDocument(waybill, waybill.BuyerTitleId.Value, Docflow.OfficialDocument.ExchangeState.Signed);
      }
      else
      {
        Docflow.PublicFunctions.Module.GenerateTempPublicBodyForExchangeDocument(waybill, waybill.BuyerTitleId.Value);
        Functions.Module.EnqueueXmlToPdfBodyConverter(waybill, waybill.BuyerTitleId.Value, Docflow.OfficialDocument.ExchangeState.Signed);
      }
    }

    /// <summary>
    /// Отправить уведомления об уточнении документов.
    /// </summary>
    /// <param name="signedDocuments">Подписанные уведомления об уточнении.</param>
    /// <param name="receiver">Получатель уведомления.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="note">Комментарий.</param>
    [Remote]
    public void SendAmendmentRequest(List<Structures.Module.ReglamentDocumentWithCertificate> signedDocuments, Parties.ICounterparty receiver,
                                     ExchangeCore.IBoxBase box, string note)
    {
      var operation = new Enumeration(Constants.Module.Exchange.SendAnswer);
      var comment = string.Format("{0}|{1}", receiver.Name, ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(box).Name);
      
      var businessUnitBox = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);

      // Для счетов-фактур и УПД тип служебного документа в сервисе другой.
      var invoiceDocuments = signedDocuments.Where(d => d.IsInvoiceFlow).ToList();
      
      // Отправляем одним сообщением УОУ на комплект документов из СБИС.
      var packageProcessingSbis = signedDocuments.Count > 1 && businessUnitBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis;
      if (packageProcessingSbis)
        this.SendServiceDocument(signedDocuments,
                                 ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box), ReglamentDocumentType.InvoiceAmendmentRequest);

      if (!packageProcessingSbis && invoiceDocuments.Any())
        this.SendServiceDocument(invoiceDocuments,
                                 ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box), ReglamentDocumentType.InvoiceAmendmentRequest);
      
      foreach (var document in invoiceDocuments)
      {
        var doc = document.LinkedDocument;
        var info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, document.ParentDocumentId);
        this.ProcessSharedInvoiceReject(info, doc, false, box, document.Signature, operation, comment, string.Empty, note, false);
      }
      
      var notInvoiceDocuments = signedDocuments.Where(d => !d.IsInvoiceFlow).ToList();
      var reglamentDocumentType = businessUnitBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc ?
        ReglamentDocumentType.Rejection : ReglamentDocumentType.AmendmentRequest;
      if (!packageProcessingSbis && notInvoiceDocuments.Any())
        this.SendServiceDocument(notInvoiceDocuments,
                                 ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box), reglamentDocumentType);
      
      foreach (var document in notInvoiceDocuments)
      {
        var doc = document.LinkedDocument;
        var info = Functions.ExchangeDocumentInfo.GetExDocumentInfoByExternalId(box, document.ParentDocumentId);
        this.ProcessSharedReject(info, doc, false, box, document.Signature, operation, comment, string.Empty, note, false);
      }
    }

    /// <summary>
    /// Отправить извещения о получении документов.
    /// </summary>
    /// <param name="signedDocuments">Подписанные извещения о получении.</param>
    /// <param name="box">Абонентский ящик.</param>
    [Remote]
    public virtual void SendDeliveryConfirmation(List<Structures.Module.ReglamentDocumentWithCertificate> signedDocuments, ExchangeCore.IBusinessUnitBox box)
    {
      this.LogDebugFormat(box, "Execute SendDeliveryConfirmation.");
      // Нельзя разделять по типам служебок для СБИС, потому что не будет работать отправка комплектов формализованный + неформализованный.
      if (box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis)
        this.SendServiceDocument(signedDocuments, box, NpoComputer.DCX.Common.ReglamentDocumentType.InvoiceReceipt);
      else
      {
        // Для счетов-фактур и УПД тип служебного документа в сервисе другой.
        var invoiceDocuments = signedDocuments.Where(d => d.IsInvoiceFlow).ToList();
        if (invoiceDocuments.Any())
          this.SendServiceDocument(invoiceDocuments, box, NpoComputer.DCX.Common.ReglamentDocumentType.InvoiceReceipt);
        
        var notInvoiceDocuments = signedDocuments.Where(d => !d.IsInvoiceFlow).ToList();
        if (notInvoiceDocuments.Any())
          this.SendServiceDocument(notInvoiceDocuments, box, NpoComputer.DCX.Common.ReglamentDocumentType.Receipt);
      }

      var rootReceipts = signedDocuments.Where(d => d.IsRootDocumentReceipt == true);
      foreach (var receipt in rootReceipts)
      {
        var comment = string.Format("{0}|{1}", receipt.Info.Counterparty.Name, box.ExchangeService.Name);
        this.FixReceiptNotification(receipt.Info, comment, true);
      }
      
      RequeueMessagesGet();
    }

    /// <summary>
    /// Отправить служебные документы сервиса обмена.
    /// </summary>
    /// <param name="signedDocuments">Коллекция подписанных документов.</param>
    /// <param name="box">Ящик.</param>
    /// <param name="documentType">Тип документа.</param>
    protected virtual void SendServiceDocument(List<ReglamentDocumentWithCertificate> signedDocuments, IBusinessUnitBox box, ReglamentDocumentType documentType)
    {
      var client = GetClient(box);
      var processedMessagesId = new List<string>();
      
      // Для СБИС хранится составной ParentDocumentId, первая часть которого - ИД сообщения, вторая - ИД документа.
      // ИОПы необходимо отправлять одним сообщением на весь комплект документов.
      foreach (var serviceDocuments in signedDocuments.GroupBy(d => d.ParentDocumentId.Split('#').First()))
      {
        var document = serviceDocuments.First();
        var serviceDocumentsToSend = new List<NpoComputer.DCX.Common.IReglamentDocument>();
        var serviceDocumentsSigns = new List<NpoComputer.DCX.Common.Signature>();
        
        foreach (var reglamentDocument in serviceDocuments)
        {
          var currentDocumentType = documentType;
          var serviceDocument = this.CreateReglamentExchangeServiceDocument(reglamentDocument, currentDocumentType);
          serviceDocumentsToSend.Add(serviceDocument);
          
          var sign = CreateExchangeDocumentSignature(box, serviceDocument.ServiceEntityId,
                                                     reglamentDocument.Signature, reglamentDocument.FormalizedPoAUnifiedRegNumber);

          serviceDocumentsSigns.Add(sign);
          this.LogDebugFormat(reglamentDocument.Info, "Execute SendServiceDocument. Prepare service document with DocumentType = {0}, LinkedDocumentId = {1}.",
                              reglamentDocument.ReglamentDocumentType, reglamentDocument.LinkedDocument.Id);
        }
        var isBuyerTitle = this.GetSupportedReglamentDocumentTypes().Contains(documentType);
        
        try
        {
          var sentMessage = this.SendMessage(new List<NpoComputer.DCX.Common.IDocument>(),
                                             serviceDocumentsToSend, serviceDocumentsSigns, client, null, document.ServiceCounterpartyId, box, document.ServiceMessageId);
          
          this.LogDebugFormat(document.Info, serviceDocumentsToSend, "Execute SendServiceDocument. Send service document: ServiceCounterpartyId = {0}.", document.ServiceCounterpartyId);
          
          var needUpdateSign = box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis && isBuyerTitle &&
            signedDocuments.Any(d => !string.IsNullOrEmpty(d.FormalizedPoAUnifiedRegNumber));
          if (needUpdateSign)
          {
            var signedDocument = signedDocuments.First();
            var patсhedSignature = sentMessage.Signatures.Single(s => string.Equals(s.DocumentId, signedDocument.Info.ExternalBuyerTitleId));
            Docflow.PublicFunctions.Module.SetDataSignature(signedDocument.LinkedDocument, (int)signedDocument.Info.ReceiverSignId, patсhedSignature.Content);
          }
        }
        catch (NpoComputer.DCX.Common.Exceptions.WorkflowViolationException ex)
        {
          if (documentType == ReglamentDocumentType.InvoiceReceipt || documentType == ReglamentDocumentType.Receipt)
          {
            var innerExceptionText = ex.InnerException != null
              ? string.Format("{0}. ", ex.InnerException.Message)
              : string.Empty;
            var reglamentDocumentTypeValue = document.ReglamentDocumentType.HasValue ? document.ReglamentDocumentType.Value.Value : string.Empty;
            var debugText = string.Format("{0}Receipt notice with Name = '{1}', ReglamentDocumentType = '{2}', ParentDocumentId = '{3}' already sent. " +
                                          "Start the job of receiving messages from the exchange service.",
                                          innerExceptionText, document.Name, reglamentDocumentTypeValue, document.ParentDocumentId);
            this.LogDebugFormat(debugText);
          }
          else if (isBuyerTitle)
          {
            this.LogDebugFormat(ex.Message);
            throw AppliedCodeException.Create(Resources.OneOrMoreDocumentAlreadyProcessing);
          }
          else
            throw;
        }
        catch (Exception e)
        {
          if (documentType == ReglamentDocumentType.InvoiceReceipt || documentType == ReglamentDocumentType.Receipt)
          {
            this.LogDebugFormat(e.ToString());
          }
          else
            throw;
        }
      }
    }
    
    /// <summary>
    /// Отправить пакет служебных документов сервиса обмена.
    /// </summary>
    /// <param name="signedDocuments">Коллекция подписанных документов.</param>
    /// <param name="box">Ящик.</param>
    /// <param name="documentType">Тип документа.</param>
    [Obsolete("Теперь функция не актуальна, т.к. реализована поддержка частичного подписания.")]
    protected virtual void SendPackageServiceDocuments(List<ReglamentDocumentWithCertificate> signedDocuments, IBusinessUnitBox box, ReglamentDocumentType documentType)
    {
      var client = GetClient(box);
      var serviceDocuments = new List<NpoComputer.DCX.Common.IReglamentDocument>();
      var signatures = new List<NpoComputer.DCX.Common.Signature>();
      var serviceCounterpartyId = signedDocuments.First().ServiceCounterpartyId;
      var serviceMessageId = signedDocuments.First().ServiceMessageId;

      foreach (var document in signedDocuments)
      {
        var serviceDoc = this.CreateReglamentExchangeServiceDocument(document, documentType);
        serviceDocuments.Add(serviceDoc);
        signatures.Add(CreateExchangeDocumentSignature(box, serviceDoc.ServiceEntityId, document.Signature, null));
        Logger.Debug(string.Format("Prepare receipt notification with ExchangeDocumentInfoId = {0}, DocumentType = {1}, LinkedDocumentId = {2}, ServiceMessageId = {3}",
                                   document.Info.Id, document.ReglamentDocumentType, document.LinkedDocument.Id, document.ServiceMessageId));
      }
      
      try
      {
        this.SendMessage(new List<NpoComputer.DCX.Common.IDocument>(), serviceDocuments, signatures,
                         client, null, serviceCounterpartyId, box, serviceMessageId);
        
        foreach (var document in signedDocuments)
          Logger.Debug(string.Format("Send receipt notification: ServiceCounterpartyId = {0}, ParentDocumentId = {1}, ServiceMessageId = {2}",
                                     document.ServiceCounterpartyId, document.ParentDocumentId, document.ServiceMessageId));
      }
      catch (Exception e)
      {
        throw e;
      }
    }

    /// <summary>
    /// Создать сообщение в сервис обмена.
    /// </summary>
    /// <param name="primaryDocuments">Список основных документов.</param>
    /// <param name="reglamentDocuments">Список регламентных документов.</param>
    /// <param name="signs">Список подписей.</param>
    /// <param name="client">Клиент.</param>
    /// <param name="receiver">Получатель.</param>
    /// <param name="serviceCounterpartyId">Внешний ИД контрагента.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="parentServiceMessageId">ИД сообщения, для которого отправляется ответ.</param>
    /// <returns>Результат отправки.</returns>
    protected NpoComputer.DCX.Common.Message CreateMessage(List<IDocument> primaryDocuments, List<IReglamentDocument> reglamentDocuments,
                                                           List<Signature> signs, DcxClient client, ICounterparty receiver, string serviceCounterpartyId, IBusinessUnitBox box,
                                                           string parentServiceMessageId)
    {
      if (serviceCounterpartyId == string.Empty)
      {
        var receiverLine = receiver.ExchangeBoxes.Where(x => Equals(x.Box, box) && x.IsDefault == true).SingleOrDefault();
        if (receiverLine == null)
          throw AppliedCodeException.Create(string.Format("Для контрагента c ИД {0} не установлена связь через указанный абонентский ящик с ИД {1}.", receiver.Id, box.Id));
        serviceCounterpartyId = receiverLine.OrganizationId;
      }
      
      var counterpartyBoxId = client.GetContact(serviceCounterpartyId).Organization.BoxId;
      
      var message = new NpoComputer.DCX.Common.Message()
      {
        IsReply = !string.IsNullOrEmpty(parentServiceMessageId),
        ParentServiceMessageId = parentServiceMessageId,
        PrimaryDocuments = primaryDocuments,
        ReglamentDocuments = reglamentDocuments,
        Signatures = signs.ToList(),
        Receiver = new NpoComputer.DCX.Common.Subscriber()
        {
          BoxId = counterpartyBoxId
        }
      };
      
      return message;
    }
    
    /// <summary>
    /// Отправить сообщение в сервис обмена.
    /// </summary>
    /// <param name="primaryDocuments">Список основных документов.</param>
    /// <param name="reglamentDocuments">Список регламентных документов.</param>
    /// <param name="signs">Список подписей.</param>
    /// <param name="client">Клиент.</param>
    /// <param name="receiver">Получатель.</param>
    /// <param name="serviceCounterpartyId">Внешний ИД контрагента.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="parentServiceMessageId">ИД сообщения, для которого отправляется ответ.</param>
    /// <returns>Результат отправки.</returns>
    protected virtual SentMessage SendMessage(List<IDocument> primaryDocuments, List<IReglamentDocument> reglamentDocuments,
                                              List<Signature> signs, DcxClient client, ICounterparty receiver, string serviceCounterpartyId, IBusinessUnitBox box,
                                              string parentServiceMessageId)
    {
      var message = this.CreateMessage(primaryDocuments, reglamentDocuments, signs, client, receiver, serviceCounterpartyId, box, parentServiceMessageId);
      
      return client.SendMessage(message);
    }
    
    /// <summary>
    /// Отправить сообщение в сервис обмена c УОП.
    /// </summary>
    /// <param name="primaryDocuments">Список основных документов.</param>
    /// <param name="reglamentDocuments">Список регламентных документов.</param>
    /// <param name="signs">Список подписей.</param>
    /// <param name="client">Клиент.</param>
    /// <param name="receiver">Получатель.</param>
    /// <param name="serviceCounterpartyId">Внешний ИД контрагента.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="parentServiceMessageId">ИД сообщения, для которого отправляется ответ.</param>
    /// <param name="document">Документ, для которого отправляется ответ.</param>
    /// <returns>Результат отправки.</returns>
    protected virtual SentMessage SendMessageWithServiceDocument(List<IDocument> primaryDocuments, List<IReglamentDocument> reglamentDocuments,
                                                                 List<Signature> signs, DcxClient client, ICounterparty receiver, string serviceCounterpartyId, IBusinessUnitBox box,
                                                                 string parentServiceMessageId, Docflow.IOfficialDocument document)
    {
      var message = this.CreateMessage(primaryDocuments, reglamentDocuments, signs, client, receiver, serviceCounterpartyId, box, parentServiceMessageId);
      
      if (string.IsNullOrEmpty(serviceCounterpartyId))
      {
        var receiverLine = receiver.ExchangeBoxes.Where(x => Equals(x.Box, box) && x.IsDefault == true).SingleOrDefault();
        if (receiverLine == null)
          throw AppliedCodeException.Create(string.Format("Для контрагента c ИД {0} не установлена связь через указанный абонентский ящик с ИД {1}.", receiver.Id, box.Id));
        
        serviceCounterpartyId = receiverLine.OrganizationId;
      }
      
      var counterpartyBoxId = client.GetContact(serviceCounterpartyId).Organization.BoxId;
      
      if (receiver != null && message.IsReply)
      {
        var cert = box.CertificateReceiptNotifications;
        var counterpartyBox = receiver.ExchangeBoxes.First(b => b.OrganizationId == counterpartyBoxId);
        if (counterpartyBox != null && counterpartyBox.Box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis)
          this.PrepareReplyMessage(message, cert, client, primaryDocuments, box, document);
      }
      
      return client.SendMessage(message);
    }
    
    /// <summary>
    /// Подготовить ответное сообщение к отправке на сервис.
    /// В методе генерируются служебные документы для отправки на сервис результатов подписания документов сообщения.
    /// Служебки генерируются только при наличии установленного сертификата для подписания.
    /// </summary>
    /// <param name="outcomeReplyMessage">Сообщение, которое будет отправлено на сервис.</param>
    /// <param name="certificate">Исходящее ответное сообщение из справочника.</param>
    /// <param name="client">Клиент.</param>
    /// <param name="documents">Список документов.</param>
    /// <param name="box">Яшик нашего абонента.</param>
    /// <param name="document">Основной документ.</param>
    private void PrepareReplyMessage(IMessage outcomeReplyMessage, ICertificate certificate, DcxClient client, List<NpoComputer.DCX.Common.IDocument> documents, IBusinessUnitBox box, IOfficialDocument document)
    {
      var exchangeDocumentInfo = Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.GetIncomingExDocumentInfo(document);
      if (certificate == null)
        return;
      else
        Logger.DebugFormat("No signing certificate found. ServiceMessageId = {0}", outcomeReplyMessage.ServiceMessageId);
      
      var signerInfo = NpoComputer.DCX.Common.SignerInfo.CreateFromSignature(certificate.X509Certificate);
      foreach (var sign in outcomeReplyMessage.Signatures)
        sign.SignerInfo = signerInfo;
      
      var documentsForSign = client.PrepareReplyMessage(outcomeReplyMessage, signerInfo);
      
      var documentsToSave = new List<Structures.Module.ReglamentDocumentWithCertificate>();
      foreach (var documentForSign in documentsForSign)
      {
        if (documentForSign is NpoComputer.DCX.Common.IReglamentDocument)
        {
          var doc = (NpoComputer.DCX.Common.IReglamentDocument)documentForSign;
          Logger.DebugFormat("PrepareReplyMessage. ServiceEntityId = {0}, ServiceMessageId = {1}", doc.ServiceEntityId, outcomeReplyMessage.ServiceMessageId);
          var documentPriority = new Dictionary<string, byte[]>();
          documentPriority.Add(doc.ServiceEntityId, doc.Content);
          var signs = ExternalSignatures.Sign(certificate, documentPriority);
          
          // TODO Использовать конструктор в прикладной CreateExchangeDocumentSignature.
          var sign = new NpoComputer.DCX.Common.Signature
          {
            DocumentId = doc.ServiceEntityId,
            Content = signs[doc.ServiceEntityId],
            SignerInfo = signerInfo
          };
          
          outcomeReplyMessage.Signatures.Add(sign);
          
          if (doc.DocumentType == ReglamentDocumentType.NotificationReceipt)
          {
            var type = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.NoteReceipt;
            
            var docWithCertificate = Structures.Module.ReglamentDocumentWithCertificate.Create(documentForSign.FileName, documentForSign.Content,
                                                                                               certificate, sign.Content, documentForSign.ParentServiceEntityId,
                                                                                               box, document, null, documentForSign.ServiceEntityId, null,
                                                                                               exchangeDocumentInfo.ServiceCounterpartyId, false,
                                                                                               exchangeDocumentInfo, false, type, null);

            var isSendJobEnabled = PublicFunctions.Module.Remote.IsJobEnabled(PublicConstants.Module.SendSignedReceiptNotificationsId);
            this.SaveDeliveryConfirmationSigns(new List<Structures.Module.ReglamentDocumentWithCertificate> { docWithCertificate });
            
            var info = docWithCertificate.Info;
            
            var serviceDocument = info.ServiceDocuments.FirstOrDefault(d => d.DocumentType == docWithCertificate.ReglamentDocumentType);
            serviceDocument.CounterpartyId = docWithCertificate.ServiceCounterpartyId;
            serviceDocument.DocumentId = docWithCertificate.ServiceDocumentId;
            serviceDocument.ParentDocumentId = docWithCertificate.ParentDocumentId;
            serviceDocument.StageId = doc.DocflowStageId;
            serviceDocument.Date = doc.DateTime;
            info.Save();
          }
        }
      }
    }

    /// <summary>
    /// Отправить документ в сервис обмена.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="addenda">Приложения.</param>
    /// <param name="receiver">Получатель.</param>
    /// <param name="box">Абонентский ящик отправителя.</param>
    /// <param name="certificate">Сертификат, которым подписаны документы.</param>
    /// <param name="needSign">Требовать подписание от контрагента.</param>
    /// <param name="comment">Комментарий к сообщению в сервисе.</param>
    [Remote, Public]
    public virtual void SendDocuments(Sungero.Docflow.IOfficialDocument document, List<Sungero.Docflow.IOfficialDocument> addenda,
                                      Parties.ICounterparty receiver, ExchangeCore.IBusinessUnitBox box, ICertificate certificate, bool needSign, string comment)
    {
      if (HasNotApprovedDocuments(document, addenda))
        throw AppliedCodeException.Create(Resources.SendCounterpartyNotApproved);
      
      var signatures = new List<NpoComputer.DCX.Common.Signature>();
      
      Func<IOfficialDocument, bool> isNeedSign = (d) =>
      {
        var accountingDocument = AccountingDocumentBases.As(d);
        if (accountingDocument == null)
          return needSign;
        
        var isTaxInvoice = accountingDocument.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Schf;
        var isOutgoingInvoice = Contracts.OutgoingInvoices.Is(d);
        return needSign && !isTaxInvoice && !isOutgoingInvoice;
      };
      
      var primaryDocuments = new List<NpoComputer.DCX.Common.IDocument>();
      primaryDocuments.Add(Functions.Module.CreatePrimaryExchangeServiceDocument(document, needSign, comment));
      foreach (var doc in addenda)
      {
        // Для СБИС нельзя на часть документов комплекта запросить подпись, а на остальные не запрашивать.
        primaryDocuments.Add(Functions.Module.CreatePrimaryExchangeServiceDocument(doc,
                                                                                   box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis ? needSign : isNeedSign(doc),
                                                                                   string.Empty));
      }
      
      var documents = new List<Sungero.Docflow.IOfficialDocument>() { document };
      documents.AddRange(addenda);
      foreach (var doc in documents)
      {
        if (!doc.AccessRights.CanUpdate() || !doc.AccessRights.CanSendByExchange())
          throw AppliedCodeException.Create(Resources.SendCounterpartyAddendaNotRightFormat(doc.Name));
        
        var signature = this.GetDocumentSignature(doc, certificate);
        if (signature == null)
          throw AppliedCodeException.Create(Resources.SendCounterpartyAddendaNotSigned);
      }
      foreach (var doc in documents)
      {
        var signature = this.GetDocumentSignature(doc, certificate);
        var dcxSign = CreateExchangeDocumentSignature(box, doc.Id.ToString(), signature.Body, signature.FormalizedPoAUnifiedRegNumber);
        signatures.Add(dcxSign);
      }
      var client = GetClient(box);
      var sentMessage = this.SendMessage(primaryDocuments, new List<NpoComputer.DCX.Common.IReglamentDocument>(), signatures, client, receiver, string.Empty, box, string.Empty);
      
      foreach (var ids in sentMessage.DocumentIds)
      {
        var doc = documents.Where(x => x.Id.ToString() == ids.LocalId).Single();
        /* Для основного документа признак Требуется подписание заполяется переданным в метод параметром.
         * Для приложений дополнительно проверить требование подписи.
         * Не требуется подпись для счет-фактур и исх. счетов.
         * Исключение СБИС - подпись на счет-фактуру требуется.
         */
        var isPrimaryDocument = doc.Id == document.Id;
        var needSignSentDocument = isPrimaryDocument || box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis ? needSign : isNeedSign(doc);
        doc.DeliveryMethod = Docflow.PublicFunctions.MailDeliveryMethod.Remote.GetExchangeDeliveryMethod();
        
        var info = SaveExternalDocumentInfo(doc, ids.ServiceId, sentMessage.ServiceMessageId, needSignSentDocument, receiver, box);
        var signature = this.GetDocumentSignature(doc, certificate);
        info.SenderSignId = signature.Id;
        
        var needUpdateSign = box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis && !string.IsNullOrEmpty(signature.FormalizedPoAUnifiedRegNumber);
        if (needUpdateSign)
        {
          var patсhedSignature = sentMessage.Signatures.Single(s => string.Equals(s.DocumentId, doc.Id.ToString()));
          Docflow.PublicFunctions.Module.SetDataSignature(doc, signature.Id, patсhedSignature.Content);
        }
        
        var accountingDoc = Docflow.AccountingDocumentBases.As(doc);
        
        if (accountingDoc != null)
          accountingDoc.BusinessUnitBox = box;
        
        if (accountingDoc != null && accountingDoc.IsFormalized == true)
        {
          accountingDoc.ExchangeState = needSignSentDocument ? Docflow.OfficialDocument.ExchangeState.SignAwaited : Docflow.OfficialDocument.ExchangeState.Sent;
          accountingDoc.SellerSignatureId = this.GetDocumentSignature(accountingDoc, certificate).Id;
          Docflow.PublicFunctions.Module.GenerateTempPublicBodyForExchangeDocument(accountingDoc, accountingDoc.SellerTitleId.Value);
          Functions.Module.EnqueueXmlToPdfBodyConverter(accountingDoc, accountingDoc.SellerTitleId.Value, accountingDoc.ExchangeState);
        }
        else
        {
          Docflow.PublicFunctions.Module.GenerateTempPublicBodyForExchangeDocument(doc, info.VersionId.Value);
          Functions.Module.EnqueueXmlToPdfBodyConverter(doc, info.VersionId.Value, doc.ExchangeState);
        }
        MarkDocumentAsSended(info, doc, receiver, false, box, needSignSentDocument ? SignStatus.Waiting : SignStatus.None);
      }
    }

    /// <summary>
    /// Сохранить ИД документа в сервисе обмена.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="serviceId">ИД в сервисе обмена.</param>
    /// <param name="messageId">ИД сообщения.</param>
    /// <param name="needSign">Признак требования подписания.</param>
    /// <param name="counterparty">Контрагент - получатель.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <returns>ExternalLink.</returns>
    protected static IExchangeDocumentInfo SaveExternalDocumentInfo(IOfficialDocument document, string serviceId, string messageId, bool needSign,
                                                                    ICounterparty counterparty, IBusinessUnitBox box)
    {
      var newInfo = ExchangeDocumentInfos.Create();
      
      newInfo.Document = document;
      newInfo.Box = box;
      newInfo.RootBox = box;
      newInfo.ServiceDocumentId = serviceId;
      newInfo.MessageType = Exchange.ExchangeDocumentInfo.MessageType.Outgoing;
      newInfo.ServiceMessageId = messageId;
      newInfo.Counterparty = counterparty;
      newInfo.MessageDate = Calendar.Now;
      newInfo.NeedSign = needSign;
      newInfo.VersionId = document.LastVersion.Id;
      
      newInfo.Save();
      return newInfo;
    }

    /// <summary>
    /// Получить подпись документа.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="certificate">Сертификат.</param>
    /// <returns>Подпись.</returns>
    protected virtual Structures.Module.Signature GetDocumentSignature(IOfficialDocument document, ICertificate certificate)
    {
      var version = document.LastVersion;
      if (version == null)
        return null;
      
      var keyFPoA = Docflow.PublicConstants.Module.UnsignedAdditionalInfoKeyFPoA + Docflow.PublicConstants.Module.UnsignedAdditionalInfoSeparator.KeyValue;
      var signature = Signatures.Get(version).Where(x => x.IsValid && x.SignCertificate != null)
        .Where(x => x.SignCertificate.Thumbprint.Equals(certificate.Thumbprint, StringComparison.InvariantCultureIgnoreCase))
        .OrderByDescending(x => !string.IsNullOrEmpty(x.UnsignedAdditionalInfo) && x.UnsignedAdditionalInfo.Contains(keyFPoA))
        .ThenByDescending(x => x.Id)
        .FirstOrDefault();
      
      if (signature == null)
        return null;
      
      var unifiedRegistrationNumber = Docflow.PublicFunctions.Module.GetUnsignedAttribute(signature, Docflow.PublicConstants.Module.UnsignedAdditionalInfoKeyFPoA);
      
      return Structures.Module.Signature.Create(signature.GetDataSignature(), signature.Id, unifiedRegistrationNumber);
    }

    /// <summary>
    /// Создать новый основной документ из документа RX.
    /// </summary>
    /// <param name="document">Документ RX.</param>
    /// <param name="needSign">Требуется подписание.</param>
    /// <param name="comment">Комментарий.</param>
    /// <returns>Основной документ сервиса обмена.</returns>
    public virtual NpoComputer.DCX.Common.IDocument CreatePrimaryExchangeServiceDocument(IOfficialDocument document, bool needSign, string comment)
    {
      byte[] content;
      using (var memory = new System.IO.MemoryStream())
      {
        using (var sourceStream = document.LastVersion.Body.Read())
          sourceStream.CopyTo(memory);
        content = memory.ToArray();
      }
      
      var documentName = Functions.Module.GetExchangeDocumentName(document);
      documentName = Functions.Module.GetValidFileName(documentName);
      var fileName = string.Format("{0}.{1}", documentName, document.LastVersion.BodyAssociatedApplication.Extension);
      fileName = CommonLibrary.FileUtils.NormalizeFileName(fileName);
      
      return new NpoComputer.DCX.Common.Document()
      {
        ServiceEntityId = document.Id.ToString(),
        DocumentType = Functions.Module.GetDCXDocumentType(document),
        FileName = fileName,
        Content = content,
        NeedSign = needSign,
        Comment = comment,
        Date = document.DocumentDate.Value
      };
    }
    
    /// <summary>
    /// Получить имя документа для отправки в сервис обмена.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>Имя документа для отправки в сервис обмена.</returns>
    public virtual string GetExchangeDocumentName(IOfficialDocument document)
    {
      var extensionLength = document.LastVersion.BodyAssociatedApplication.Extension.Length;
      var documentNameMaxLength = Constants.Module.ExchangeDocumentMaxLength - extensionLength - 2;
      var documentName = document.Name;
      if (documentName.Length > documentNameMaxLength)
        documentName = string.Format("{0}~", document.Name.Substring(0, documentNameMaxLength));
      return documentName;
    }

    /// <summary>
    /// Создать подпись для документа обмена.
    /// </summary>
    /// <param name="box">Наш абонентский ящик.</param>
    /// <param name="documentId">ИД документа.</param>
    /// <param name="signature">Подпись.</param>
    /// <param name="formalizedPoAUnifiedRegNumber">Единый регистрационный номер эл. доверенности.</param>
    /// <returns>Подпись сервиса обмена.</returns>
    protected static Signature CreateExchangeDocumentSignature(IBusinessUnitBox box, string documentId, byte[] signature, string formalizedPoAUnifiedRegNumber)
    {
      string formalizedPoALink = null;
      string formalizedPoALinkTitle = null;
      
      if (box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis && !string.IsNullOrEmpty(formalizedPoAUnifiedRegNumber))
      {
        var serviceFormalizedPoA = box.FormalizedPoAInfos.Where(p => string.Equals(formalizedPoAUnifiedRegNumber, p.UnifiedRegistrationNumber)).SingleOrDefault();
        formalizedPoALink = serviceFormalizedPoA != null ? serviceFormalizedPoA.Url : Functions.Module.GetFormalizedPoALink(formalizedPoAUnifiedRegNumber);
        formalizedPoALinkTitle = serviceFormalizedPoA != null ? serviceFormalizedPoA.Description : Functions.Module.GetFormalizedPoALinkTitle(formalizedPoAUnifiedRegNumber);
      }
      
      return new NpoComputer.DCX.Common.Signature()
      {
        Content = signature,
        DocumentId = documentId,
        FormalizedPoAUnifiedRegNumber = formalizedPoAUnifiedRegNumber,
        FormalizedPoALink = formalizedPoALink,
        FormalizedPoALinkTitle = formalizedPoALinkTitle
      };
    }

    /// <summary>
    /// Создать новый регламентный документ из временного документа.
    /// </summary>
    /// <param name="document">Временный документ.</param>
    /// <param name="documentType">Тип регламентного документа.</param>
    /// <returns>Регламентный документ сервиса обмена.</returns>
    public virtual NpoComputer.DCX.Common.ReglamentDocument CreateReglamentExchangeServiceDocument(
      Sungero.Exchange.Structures.Module.ReglamentDocumentWithCertificate document,
      NpoComputer.DCX.Common.ReglamentDocumentType documentType)
    {
      var documentId = this.GetReglamentDocumentId(document, documentType);
      var stageId = this.GetReglamentDocumentStageId(document, documentType);

      if (string.IsNullOrEmpty(documentId))
        documentId = Guid.NewGuid().ToString();
      
      return new NpoComputer.DCX.Common.ReglamentDocument()
      {
        ServiceEntityId = documentId,
        DocumentType = documentType,
        FileName = document.Name,
        ParentServiceEntityId = document.ParentDocumentId,
        Content = document.Content,
        DocflowStageId = stageId
      };
    }
    
    /// <summary>
    /// Получить ИД регламентного документа на сервисе.
    /// </summary>
    /// <param name="document">Регламентный документ.</param>
    /// <param name="documentType">Тип регламентного документа.</param>
    /// <returns>ИД регламентного документа на сервисе.</returns>
    protected virtual string GetReglamentDocumentId(ReglamentDocumentWithCertificate document, ReglamentDocumentType documentType)
    {
      return this.GetSupportedReglamentDocumentTypes().Contains(documentType) ? document.Info.ExternalBuyerTitleId : document.ServiceDocumentId;
    }
    
    /// <summary>
    /// Получить ИД этапа регламентного документа на сервисе.
    /// </summary>
    /// <param name="document">Регламентный документ.</param>
    /// <param name="documentType">Тип регламентного документа.</param>
    /// <returns>ИД этапа регламентного документа на сервисе.</returns>
    protected virtual string GetReglamentDocumentStageId(ReglamentDocumentWithCertificate document, ReglamentDocumentType documentType)
    {
      return this.GetSupportedReglamentDocumentTypes().Contains(documentType) ? document.Info.StageId : document.ServiceDocumentStageId;
    }
    
    /// <summary>
    /// Получить тип документа в DCX.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>Тип документа в DCX.</returns>
    public virtual NpoComputer.DCX.Common.DocumentType GetDCXDocumentType(IOfficialDocument document)
    {
      var documentType = NpoComputer.DCX.Common.DocumentType.Nonformalized;
      var accounting = Docflow.AccountingDocumentBases.As(document);
      
      if (accounting != null && accounting.FormalizedServiceType != null)
      {
        var exchangeService = accounting.BusinessUnitBox.ExchangeService.ExchangeProvider;
        if (accounting.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Act)
          documentType = DocumentType.Act;
        if (accounting.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer)
        {
          if (accounting.IsAdjustment == true)
          {
            if (accounting.IsRevision == true)
            {
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Schf)
                if (exchangeService == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
                  documentType = DocumentType.InvoiceCorrectionRevision;
                else
                  documentType = DocumentType.GeneralTransferSchfCorrectionRevisionSeller;
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.SchfDop)
                documentType = DocumentType.GeneralTransferSchfDopCorrectionRevisionSeller;
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Dop)
                documentType = DocumentType.GeneralTransferDopCorrectionRevisionSeller;
            }
            else
            {
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Schf)
                if (exchangeService == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
                  documentType = DocumentType.InvoiceCorrection;
                else
                  documentType = DocumentType.GeneralTransferSchfCorrectionSeller;
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.SchfDop)
                documentType = DocumentType.GeneralTransferSchfDopCorrectionSeller;
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Dop)
                documentType = DocumentType.GeneralTransferDopCorrectionSeller;
            }
          }
          else
          {
            if (accounting.IsRevision == true)
            {
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Schf)
                if (exchangeService == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
                  documentType = DocumentType.InvoiceRevision;
                else
                  documentType = DocumentType.GeneralTransferSchfRevisionSeller;
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.SchfDop)
                documentType = DocumentType.GeneralTransferSchfDopRevisionSeller;
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Dop)
                documentType = DocumentType.GeneralTransferDopRevisionSeller;
            }
            else
            {
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Schf)
                if (exchangeService == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
                  documentType = DocumentType.Invoice;
                else
                  documentType = DocumentType.GeneralTransferSchfSeller;
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.SchfDop)
                documentType = DocumentType.GeneralTransferSchfDopSeller;
              if (accounting.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Dop)
                documentType = DocumentType.GeneralTransferDopSeller;
            }
          }
        }
        if (accounting.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer)
          if (exchangeService == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
            documentType = DocumentType.Waybill;
          else
            documentType = accounting.IsRevision == true ? DocumentType.GoodsTransferRevisionSeller : DocumentType.GoodsTransferSeller;
        if (accounting.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Invoice)
        {
          if (accounting.IsAdjustment == true)
          {
            if (accounting.IsRevision == true)
              documentType = DocumentType.InvoiceCorrectionRevision;
            else
              documentType = DocumentType.InvoiceCorrection;
          }
          else
          {
            if (accounting.IsRevision == true)
              documentType = DocumentType.InvoiceRevision;
            else
              documentType = DocumentType.Invoice;
          }
        }
        if (accounting.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Waybill)
          documentType = DocumentType.Waybill;
        if (accounting.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer)
          if (exchangeService == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
            documentType = DocumentType.Act;
          else
            documentType = accounting.IsRevision == true ? DocumentType.WorksTransferRevisionSeller : DocumentType.WorksTransferSeller;
      }
      return documentType;
    }
    
    #endregion

    #region Генерация титула
    
    /// <summary>
    /// Сгенерировать титул покупателя.
    /// </summary>
    /// <param name="statement">Документ.</param>
    /// <param name="buyerTitle">Структура с данными для генерации титула.</param>
    [Public]
    public virtual void GenerateBuyerTitle(Docflow.IAccountingDocumentBase statement, Docflow.Structures.AccountingDocumentBase.IBuyerTitle buyerTitle)
    {
      if (statement.IsFormalized != true)
        return;
      
      byte[] sellerTitle;
      using (var memory = new System.IO.MemoryStream())
      {
        statement.Versions.Single(v => v.Id == statement.SellerTitleId).Body.Read().CopyTo(memory);
        sellerTitle = memory.ToArray();
      }
      
      var exchangeInfo = Functions.ExchangeDocumentInfo.GetIncomingExDocumentInfo(statement);
      if (exchangeInfo == null)
        return;
      
      var client = GetClient(ExchangeCore.PublicFunctions.BoxBase.GetRootBox(exchangeInfo.Box));
      
      var title = new NpoComputer.DCX.Common.BuyerTitle();
      title.AcceptanceDate = buyerTitle.AcceptanceDate.Value;
      title.OrganizationName = statement.BusinessUnit.LegalName;
      title.ActOfDisagreement = this.GetActOfDisagreementText(buyerTitle);
      title.SignResult = this.GetBuyerTitleSignResult(buyerTitle);
      title.Signer.FirstName = buyerTitle.Signatory.Person.FirstName;
      title.Signer.LastName = buyerTitle.Signatory.Person.LastName;
      title.Signer.MiddleName = buyerTitle.Signatory.Person.MiddleName;
      title.Signer.JobTitle = this.GetBuyerSignatoryJobTitle(buyerTitle);
      title.Signer.TIN = statement.BusinessUnit.TIN;
      title.Signer.SignerPowers = Functions.Module.GetSignerPowers(buyerTitle.SignatoryPowers);
      title.Signer.PowersBase = buyerTitle.SignatoryPowersBase;
      
      title.SellerTitle = sellerTitle;
      if (statement.IsAdjustment == true)
      {
        title.DocumentTypeNamedId = statement.IsRevision == true ? Constants.Module.DocumentTypeNamedId.UniversalCorrectionDocumentRevision
          : Constants.Module.DocumentTypeNamedId.UniversalCorrectionDocument;
        title.DocumentVersion = Constants.Module.UCDVersion;
      }
      
      if (buyerTitle.Consignee != null)
      {
        title.Consignee = new Consignee();
        title.Consignee.FirstName = buyerTitle.Consignee.Person.FirstName;
        title.Consignee.LastName = buyerTitle.Consignee.Person.LastName;
        title.Consignee.MiddleName = buyerTitle.Consignee.Person.MiddleName;
        title.Consignee.JobTitle = this.GetBuyerConsigneeJobTitle(buyerTitle);
        title.Consignee.PowersBase = buyerTitle.ConsigneePowersBase;
        
        this.FillAttorney(title.Consignee, buyerTitle.ConsigneePowerOfAttorney, buyerTitle.ConsigneeOtherReason);
      }
      
      FileFromService xml = null;
      
      var signResultAccepted = buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Accepted;
      
      if (statement.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer)
      {
        title.OperationContent = signResultAccepted ? "Результаты работ (оказанных услуг) приняты без претензий" : title.ActOfDisagreement;
        this.LogDebugFormat(exchangeInfo, "Start GenerateWorksTransferXmlForBuyer.");
        xml = client.GenerateWorksTransferXmlForBuyer(title, exchangeInfo.ServiceMessageId, exchangeInfo.ServiceDocumentId);
      }
      
      if (statement.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Act)
      {
        title.OperationContent = signResultAccepted ? "Услуги оказаны в полном объеме" : title.ActOfDisagreement;
        this.LogDebugFormat(exchangeInfo, "Start GenerateActXmlForBuyer.");
        xml = client.GenerateActXmlForBuyer(title, exchangeInfo.ServiceMessageId, exchangeInfo.ServiceDocumentId);
      }
      
      if (statement.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer &&
          statement.FormalizedFunction != Docflow.AccountingDocumentBase.FormalizedFunction.Schf)
      {
        if (statement.IsAdjustment != true)
          title.OperationContent = string.IsNullOrEmpty(buyerTitle.ActOfDisagreement) ? this.GetBuyerAcceptanceStatusText(buyerTitle) : title.ActOfDisagreement;
        else
          title.OperationContent = "С изменением стоимости согласен";
        
        this.LogDebugFormat(exchangeInfo, "Start {0}.", statement.IsAdjustment == true ? "GenerateUniversalTransferCorrectionDocumentXmlForBuyer" : "GenerateUniversalTransferDocumentXmlForBuyer");
        xml = statement.IsAdjustment == true ?
          client.GenerateUniversalTransferCorrectionDocumentXmlForBuyer(title, exchangeInfo.ServiceMessageId, exchangeInfo.ServiceDocumentId) :
          client.GenerateUniversalTransferDocumentXmlForBuyer(title, exchangeInfo.ServiceMessageId, exchangeInfo.ServiceDocumentId);
      }
      
      if (statement.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer)
      {
        title.OperationContent = signResultAccepted ? "Перечисленные в документе ценности приняты без претензий" : title.ActOfDisagreement;
        this.LogDebugFormat(exchangeInfo, "Start GenerateGoodsTransferXmlForBuyer.");
        xml = client.GenerateGoodsTransferXmlForBuyer(title, exchangeInfo.ServiceMessageId, exchangeInfo.ServiceDocumentId);
      }
      
      if (statement.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Waybill)
      {
        title.OperationContent = signResultAccepted ? "Товары переданы" : title.ActOfDisagreement;
        this.LogDebugFormat(exchangeInfo, "Start GenerateTorg12XmlForBuyer.");
        xml = client.GenerateTorg12XmlForBuyer(title, exchangeInfo.ServiceMessageId, exchangeInfo.ServiceDocumentId);
      }
      
      if (xml != null)
      {
        using (var memory = new System.IO.MemoryStream(xml.Content))
        {
          if (!HasUnsignedBuyerTitle(statement))
          {
            // При создании версии чистится статус эл. обмена, восстанавливаем его.
            var exchangeState = statement.ExchangeState;
            statement.CreateVersion();
            statement.ExchangeState = exchangeState;
          }
          
          var version = statement.LastVersion;
          version.AssociatedApplication = GetOrCreateAssociatedApplicationByDocumentName("file.xml");
          version.Note = FinancialArchive.Resources.BuyerTitleVersionNote;
          statement.BuyerTitleId = version.Id;
          statement.OurSignatory = buyerTitle.Signatory;
          statement.OurSigningReason = buyerTitle.SignatureSetting;
          version.Body.Write(memory);
          statement.Save();
        }
        
        // Сохранить ИД титула покупателя и ИД этапа. ID передается для СБИС, для SD и Диадок - пустое значение.
        exchangeInfo = ExchangeDocumentInfos.Get(exchangeInfo.Id);
        exchangeInfo.ExternalBuyerTitleId = xml.ServiceDocumentId;
        exchangeInfo.StageId = xml.StageId;
        
        if (statement.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer && statement.IsAdjustment != true)
          exchangeInfo.BuyerAcceptanceStatus = buyerTitle.BuyerAcceptanceStatus;
        exchangeInfo.Save();
      }
    }
    
    /// <summary>
    /// Получить текст разногласий.
    /// </summary>
    /// <param name="buyerTitle">Титул покупателя.</param>
    /// <returns>Текст разногласий.</returns>
    protected virtual string GetActOfDisagreementText(Docflow.Structures.AccountingDocumentBase.IBuyerTitle buyerTitle)
    {
      var actOfDisagreementText = !string.IsNullOrEmpty(buyerTitle.ActOfDisagreement) ? ": " + buyerTitle.ActOfDisagreement : string.Empty;
      if (buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.PartiallyAccepted)
        return "Принято с разногласиями" + actOfDisagreementText;
      else if (buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Rejected)
        return "Не принято" + actOfDisagreementText;
      else
        return string.Empty;
    }
    
    /// <summary>
    /// Получить текст расшифровки кода итога.
    /// </summary>
    /// <param name="buyerTitle">Титул покупателя.</param>
    /// <returns>Текст расшифровки кода итога.</returns>
    protected virtual string GetBuyerAcceptanceStatusText(Docflow.Structures.AccountingDocumentBase.IBuyerTitle buyerTitle)
    {
      if (buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Accepted)
        return "Товары (работы, услуги, права) приняты без расхождений (претензий)";
      else if (buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.PartiallyAccepted)
        return "Товары (работы, услуги, права) приняты с расхождениями (претензией)";
      else if (buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Rejected)
        return "Товары (работы, услуги, права) не приняты";

      return string.Empty;
    }
    
    /// <summary>
    /// Получить результат приемки для титула покупателя.
    /// </summary>
    /// <param name="buyerTitle">Титул покупателя.</param>
    /// <returns>Результат приемки в DCX.</returns>
    protected virtual SignResult GetBuyerTitleSignResult(Docflow.Structures.AccountingDocumentBase.IBuyerTitle buyerTitle)
    {
      if (buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Accepted)
        return SignResult.Signed;
      else if (buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.PartiallyAccepted)
        return SignResult.SignedWithAct;
      else if (buyerTitle.BuyerAcceptanceStatus == Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Rejected)
        return SignResult.NotAccepted;
      
      throw AppliedCodeException.Create(string.Format("Unsupported BuyerAcceptanceStatus: '{0}'.", buyerTitle.BuyerAcceptanceStatus));
    }
    
    /// <summary>
    /// Получить наименование должности грузополучателя для титула покупателя.
    /// </summary>
    /// <param name="buyerTitle">Титул покупателя.</param>
    /// <returns>Наименование должности.</returns>
    public virtual string GetBuyerConsigneeJobTitle(Docflow.Structures.AccountingDocumentBase.IBuyerTitle buyerTitle)
    {
      if (buyerTitle == null)
        return null;
      
      var signatoryJobTitle = this.GetBuyerSignatoryJobTitle(buyerTitle);
      var consigneeJobTitle = buyerTitle.Consignee.JobTitle != null ? buyerTitle.Consignee.JobTitle.Name : null;
      return Docflow.PublicFunctions.Module.CutText(buyerTitle.Signatory == buyerTitle.Consignee ? signatoryJobTitle : consigneeJobTitle,
                                                    Docflow.PublicConstants.AccountingDocumentBase.JobTitleMaxLength);
    }
    
    /// <summary>
    /// Получить наименование должности подписанта для титула покупателя.
    /// </summary>
    /// <param name="buyerTitle">Титул покупателя.</param>
    /// <returns>Наименование должности.</returns>
    public virtual string GetBuyerSignatoryJobTitle(Docflow.Structures.AccountingDocumentBase.IBuyerTitle buyerTitle)
    {
      if (buyerTitle == null)
        return null;
      
      var settingJobTitle = buyerTitle.SignatureSetting != null && buyerTitle.SignatureSetting.JobTitle != null ? buyerTitle.SignatureSetting.JobTitle.Name : null;
      var signatoryJobTitle = buyerTitle.Signatory.JobTitle != null ? buyerTitle.Signatory.JobTitle.Name : null;
      return Docflow.PublicFunctions.Module.CutText(settingJobTitle != null ? settingJobTitle : signatoryJobTitle,
                                                    Docflow.PublicConstants.AccountingDocumentBase.JobTitleMaxLength);
    }
    
    /// <summary>
    /// Заполнить информацию о подписанте.
    /// </summary>
    /// <param name="title">Титул покупателя.</param>
    /// <param name="consignee">Подписывающий.</param>
    /// <param name="powerOfAttorney">Доверенность.</param>
    /// <param name="otherReason">Основание подписания.</param>
    [Obsolete("Используйте метод FillAttorney без параметра Титул покупателя.")]
    protected virtual void FillAttorney(BuyerTitle title, Consignee consignee, IPowerOfAttorneyBase powerOfAttorney, string otherReason)
    {
      this.FillAttorney(consignee, powerOfAttorney, otherReason);
    }
    
    /// <summary>
    /// Заполнить информацию о подписанте.
    /// </summary>
    /// <param name="consignee">Подписывающий.</param>
    /// <param name="powerOfAttorney">Доверенность.</param>
    /// <param name="otherReason">Основание подписания.</param>
    protected virtual void FillAttorney(Consignee consignee, IPowerOfAttorneyBase powerOfAttorney, string otherReason)
    {
      if (consignee == null)
        return;
      
      if (powerOfAttorney != null)
      {
        consignee.PowersBase = Docflow.SignatureSettings.Info.Properties.Reason.GetLocalizedValue(Docflow.SignatureSetting.Reason.PowerOfAttorney);
        
        var number = string.Empty;
        if (Docflow.FormalizedPowerOfAttorneys.Is(powerOfAttorney))
          number = Docflow.FormalizedPowerOfAttorneys.As(powerOfAttorney).UnifiedRegistrationNumber;
        else
          number = powerOfAttorney.RegistrationNumber;
        
        if (!string.IsNullOrWhiteSpace(number))
          consignee.PowersBase += Docflow.OfficialDocuments.Resources.Number + number;
        
        if (powerOfAttorney.RegistrationDate != null)
          consignee.PowersBase += Docflow.OfficialDocuments.Resources.DateFrom + powerOfAttorney.RegistrationDate.Value.ToString("d");
      }
      else if (!string.IsNullOrWhiteSpace(otherReason))
        consignee.PowersBase = otherReason;
    }

    /// <summary>
    /// Заполнить информацию о подписанте.
    /// </summary>
    /// <param name="consignee">Подписывающий.</param>
    /// <param name="signatureSetting">Право подписи.</param>
    protected virtual void FillSignerPowersBase(Consignee consignee, Docflow.ISignatureSetting signatureSetting)
    {
      if (consignee == null || signatureSetting == null)
        return;
      
      consignee.PowersBase = Docflow.PublicFunctions.Module.GetPowersBase(signatureSetting);
    }
    
    /// <summary>
    /// Проверка наличия неподписанного титула покупателя.
    /// </summary>
    /// <param name="statement">Документ.</param>
    /// <returns>Признак наличия неподписанного титула покупателя.</returns>
    [Public, Remote]
    public static bool HasUnsignedBuyerTitle(Docflow.IAccountingDocumentBase statement)
    {
      if (statement.BuyerTitleId != null)
      {
        var existingBuyerTitle = statement.Versions.Where(x => x.Id == statement.BuyerTitleId).FirstOrDefault();
        if (existingBuyerTitle != null && !Signatures.Get(existingBuyerTitle).Any())
          return true;
      }
      
      return false;
    }
    
    /// <summary>
    /// Проверка, запрошено ли УОУ контрагентом.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>True, если запрошено УОУ.</returns>
    [Public, Remote, Obsolete("Теперь функция не актуальна, т.к. реализована поддержка частичного подписания.")]
    public virtual bool IsInvoiceAmendmentRequest(IOfficialDocument document)
    {
      var documentInfo = Sungero.Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.GetLastDocumentInfo(document);
      if (documentInfo == null)
        return false;
      
      var serviceDocuments = documentInfo.ServiceDocuments
        .Where(x => x.Date != null && (x.DocumentType == ExchDocumentType.Reject || x.DocumentType == ExchDocumentType.IReject))
        .OrderByDescending(x => x.Date);
      return serviceDocuments.Any();
    }
    
    /// <summary>
    /// Проверка возможности отправки ответной подписи по документу.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>True - если можно отправить подпись, иначе  - false.</returns>
    [Public, Remote]
    public virtual bool CanSendSign(IOfficialDocument document)
    {
      var documentInfo = Sungero.Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.GetLastDocumentInfo(document);
      if (documentInfo == null)
        return false;
      
      var client = GetClient(documentInfo.RootBox);
      var allowedAnswers = client.GetAllowedAnswers(documentInfo.ServiceDocumentId, documentInfo.ServiceMessageId, documentInfo.ExternalBuyerTitleId);
      return allowedAnswers.CanSendSign;
    }
    
    /// <summary>
    /// Получить область полномочий.
    /// </summary>
    /// <param name="authority">Полномочие.</param>
    /// <returns>Область полномочий.</returns>
    public virtual NpoComputer.DCX.Common.SignerPowers GetSignerPowers(string authority)
    {
      if (authority == Docflow.AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_SignSchf)
        return SignerPowers.InvoiceSigner;
      
      if (authority == Docflow.AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_Register)
        return SignerPowers.PersonDocumentedOperation;
      
      if (authority == Docflow.AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_Deal)
        return SignerPowers.PersonMadeOperation;
      
      if (authority == Docflow.AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_DealAndRegister)
        return SignerPowers.MadeAndSignOperation;
      
      if (authority == Docflow.AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_SignSchfAndRegister)
        return SignerPowers.ResponsibleForOperationAndSignerForInvoice;
      
      if (authority == Docflow.AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_Other)
        return SignerPowers.Other;
      
      throw AppliedCodeException.Create(Sungero.Exchange.Resources.NotFoundAuthority);
    }
    
    #endregion
    
    #region Генерация извещений о получении
    
    /// <summary>
    /// Получить сгенерированные извещения о получении.
    /// </summary>
    /// <param name="documentInfos">Информация о документах МКДО.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="certificate">Сертификат для подписания ИОП.</param>
    /// <param name="generateServiceDocuments">Сгенерировать ИОП.</param>
    /// <returns>Извещения о получении и сертификат, которым они должны быть подписаны.</returns>
    [Remote]
    public virtual System.Collections.Generic.List<Structures.Module.ReglamentDocumentWithCertificate> GetGeneratedDeliveryConfirmationDocuments(List<Exchange.IExchangeDocumentInfo> documentInfos,
                                                                                                                                                 ExchangeCore.IBusinessUnitBox box, ICertificate certificate, bool generateServiceDocuments)
    {
      if (certificate == null)
        throw AppliedCodeException.Create(Resources.CertificateNotFound);
      
      this.LogDebugFormat(box, "Execute GetGeneratedDeliveryConfirmationDocuments.");
      var processedMessagesId = new List<string>();
      var client = GetClient(box);
      var documents = new List<Structures.Module.ReglamentDocumentWithCertificate>();
      foreach (var docInfo in documentInfos)
      {
        this.LogDebugFormat(docInfo, "Execute GetGeneratedDeliveryConfirmationDocuments. Processing document info.");
        var documentInfo = ExchangeDocumentInfos.Get(docInfo.Id);
        
        // Удаляем ранее сгенерированные ИОП, если они сгенерированы под другой сертификат.
        if (generateServiceDocuments)
        {
          var serviceDocsList = documentInfo.ServiceDocuments.Where(d => d.Date == null && !Equals(certificate, d.Certificate) && d.Sign == null).ToList();
          foreach (var serviceDoc in serviceDocsList)
          {
            documentInfo.ServiceDocuments.Remove(serviceDoc);
            this.LogDebugFormat(documentInfo, "Execute GetGeneratedDeliveryConfirmationDocuments. Delete old receipts for info.");
          }
          documentInfo.Save();
        }
        
        var isInvoiceFlow = Functions.Module.IsInvoiceFlowDocument(documentInfo.Document);
        // Извещение о получении документа.
        if (documentInfo.MessageType == Exchange.ExchangeDocumentInfo.MessageType.Incoming &&
            !documentInfo.ServiceDocuments.Any(d => (d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReceipt ||
                                                     d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt) && d.Date != null))
        {
          var documentType = isInvoiceFlow ?
            Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReceipt :
            Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt;
          var generated = documentInfo.ServiceDocuments
            .FirstOrDefault(d => d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReceipt ||
                            d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt);
          
          byte[] content = null;
          string name = string.Empty;
          byte[] signature = null;
          var serviceDocumentId = string.Empty;
          var serviceDocumentStageId = string.Empty;
          var receipts = new List<IReglamentDocument>();
          if (generated == null && generateServiceDocuments)
          {
            var canSendDeliveryConfirmation = false;
            try
            {
              canSendDeliveryConfirmation = client.CanSendDeliveryConfirmation(documentInfo.ServiceDocumentId, documentInfo.ServiceMessageId);
              this.LogDebugFormat(documentInfo, "Execute GetGeneratedDeliveryConfirmationDocuments. CanSendDeliveryConfirmation = '{0}' for info.", canSendDeliveryConfirmation);
            }
            catch (Exception ex)
            {
              this.LogDebugFormat(documentInfo, "Execute GetGeneratedDeliveryConfirmationDocuments. Error while getting document from the service to generate delivery confirmation: {0}.",
                                  ex.Message);
            }
            
            // Для СБИС хранится составной ServiceDocumentId, первая часть которого - ИД сообщения, вторая - ИД документа.
            // ИОПы необходимо отправлять одним сообщением на весь комплект документов.
            if (canSendDeliveryConfirmation && !processedMessagesId.Contains(documentInfo.ServiceDocumentId.Split('#').First()))
              receipts = this.GetReglamentDocuments(documentInfo, certificate, client);
          }
          else if (generated != null && Equals(generated.Certificate, certificate))
          {
            this.LogDebugFormat(documentInfo, "Execute GetGeneratedDeliveryConfirmationDocuments. Get reglament documents from system for info.");
            content = generated.Body;
            name = generated.GeneratedName;
            signature = generated.Sign;
            serviceDocumentId = generated.DocumentId;
            serviceDocumentStageId = generated.StageId;
          }
          
          if (content != null)
          {
            var serviceDocument = Structures.Module.ReglamentDocumentWithCertificate.Create(name, content, certificate, signature, documentInfo.ServiceDocumentId,
                                                                                            box, documentInfo.Document,
                                                                                            documentInfo.ServiceMessageId, serviceDocumentId, serviceDocumentStageId,
                                                                                            documentInfo.ServiceCounterpartyId, true, documentInfo, isInvoiceFlow,
                                                                                            documentType, null);
            documents.Add(serviceDocument);
          }
          
          if (receipts.Any())
          {
            foreach (var receipt in receipts)
            {
              // Получить тип служебного документа заново, т.к. по комплектам СБИСа ИОПы приходят пачкой на одну инфошку из комплекта.
              var rootDocumentInfo = documentInfos.Where(info => Equals(info.ServiceDocumentId, receipt.RootServiceEntityId)).FirstOrDefault();
              if (rootDocumentInfo != null)
                isInvoiceFlow = Functions.Module.IsInvoiceFlowDocument(rootDocumentInfo.Document);
              if (receipt.DocumentType == ReglamentDocumentType.Receipt)
                documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt;
              if (receipt.DocumentType == ReglamentDocumentType.InvoiceReceipt)
                documentType = Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReceipt;
              
              content = receipt.Content;
              name = receipt.FileName;
              serviceDocumentId = receipt.ServiceEntityId;
              serviceDocumentStageId = receipt.DocflowStageId;
              
              this.LogDebugFormat(documentInfo,
                                  "Execute GetGeneratedDeliveryConfirmationDocuments. Generate receipt notification with DocumentType = {0}, ServiceCounterpartyId = {1}, ServiceEntityId = {2}, serviceDocumentStageId = {3}.",
                                  documentType, documentInfo.ServiceCounterpartyId, serviceDocumentId, serviceDocumentStageId);
              
              var parentDocumentInfo = documentInfos.Where(i => i.ServiceDocumentId == receipt.ParentServiceEntityId).FirstOrDefault();
              // Для письма СБИС есть 2 сущности: текстовое сообщение в XML и тело документа.
              // Текстовое сообщение не загружается в RX, но на него сервис генерирует ИОП.
              if (parentDocumentInfo != null)
              {
                var serviceDocument = Structures.Module.ReglamentDocumentWithCertificate.Create(name, content, certificate, signature, parentDocumentInfo.ServiceDocumentId, box, parentDocumentInfo.Document,
                                                                                                parentDocumentInfo.ServiceMessageId, serviceDocumentId, serviceDocumentStageId, parentDocumentInfo.ServiceCounterpartyId,
                                                                                                true, parentDocumentInfo, isInvoiceFlow, documentType, null);
                documents.Add(serviceDocument);
              }
            }
          }
        }
        processedMessagesId.Add(documentInfo.ServiceDocumentId.Split('#').First());
      }
      return documents;
    }
    
    /// <summary>
    /// Получить служебные документы с сервиса обмена.
    /// </summary>
    /// <param name="documentInfo">Информация о документе обмена.</param>
    /// <param name="certificate">Сертификат.</param>
    /// <param name="client">Клиент.</param>
    /// <returns>Список служебных документов.</returns>
    private List<IReglamentDocument> GetReglamentDocuments(IExchangeDocumentInfo documentInfo, ICertificate certificate, DcxClient client)
    {
      this.LogDebugFormat(documentInfo, "Execute GetReglamentDocuments. Try get reglament documents from service for info.");
      bool isDocflowFinished = false;
      var dcxDocument = new NpoComputer.DCX.Common.Document();
      dcxDocument.ServiceMessageId = documentInfo.ServiceMessageId;
      dcxDocument.ServiceEntityId = documentInfo.ServiceDocumentId;
      dcxDocument.DocumentType = NpoComputer.DCX.Common.DocumentType.Nonformalized;
      var accountingDocument = Docflow.AccountingDocumentBases.As(documentInfo.Document);
      
      if (accountingDocument != null)
      {
        var exchangeService = accountingDocument.BusinessUnitBox.ExchangeService.ExchangeProvider;
        
        if (accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer &&
            exchangeService != ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
          dcxDocument.DocumentType = NpoComputer.DCX.Common.DocumentType.WorksTransferSeller;
        
        if (accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Act ||
            exchangeService == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc &&
            accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer)
          dcxDocument.DocumentType = NpoComputer.DCX.Common.DocumentType.Act;
        
        if (accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer &&
            exchangeService != ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
          dcxDocument.DocumentType = NpoComputer.DCX.Common.DocumentType.GoodsTransferSeller;
        
        if (accountingDocument.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer)
          dcxDocument.DocumentType = accountingDocument.IsAdjustment == true ?
            NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfDopCorrectionSeller :
            NpoComputer.DCX.Common.DocumentType.GeneralTransferSchfDopSeller;
      }
      
      var signerInfo = NpoComputer.DCX.Common.SignerInfo.CreateFromSignature(certificate.X509Certificate);
      return client.GetNextReglamentDocuments(dcxDocument, signerInfo, out isDocflowFinished);
    }
    
    /// <summary>
    /// Сгенерировать уведомление об уточнении.
    /// </summary>
    /// <param name="documents">Документы.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="note">Комментарий.</param>
    /// <param name="throwError">Не гасить ошибку.</param>
    /// <param name="certificate">Сертификат для подписания УОУ.</param>
    /// <param name="sendInvoiceAmendmentRequest">True для УОУ, False для отказа.</param>
    /// <returns>Уведомления об уточнении и сертификат, которым они должны быть подписаны.</returns>
    [Remote]
    public virtual List<Structures.Module.ReglamentDocumentWithCertificate> GenerateAmendmentRequestDocuments(List<Docflow.IOfficialDocument> documents,
                                                                                                              ExchangeCore.IBoxBase box, string note,
                                                                                                              bool throwError, ICertificate certificate,
                                                                                                              bool sendInvoiceAmendmentRequest)
    {
      if (box == null)
        throw AppliedCodeException.Create(Resources.BoxIsNotValid);
      
      if (certificate == null)
        throw AppliedCodeException.Create(Resources.CertificateNotFound);
      
      var docsWithCertificates = new List<Structures.Module.ReglamentDocumentWithCertificate>();
      foreach (var document in documents)
      {
        bool packageProcessing = false;
        try
        {
          var externalDocumentInfo = Functions.ExchangeDocumentInfo.GetIncomingExDocumentInfo(document);
          if (externalDocumentInfo == null)
            continue;
          
          var client = GetClient(ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box));
          var allowedAnswers = client.GetAllowedAnswers(externalDocumentInfo.ServiceDocumentId, externalDocumentInfo.ServiceMessageId, externalDocumentInfo.ExternalBuyerTitleId);
          
          // Убеждаемся, что можно отправить хоть что-то.
          if (!allowedAnswers.CanSendInvoiceAmendmentRequest && !allowedAnswers.CanSendAmendmentRequest)
            throw AppliedCodeException.Create(Resources.AnswerIsAlreadySent);
          
          // Если нельзя отправить УОУ - отправляем отказ и наоборот.
          var isInvoiceAmendmentRequest = sendInvoiceAmendmentRequest;
          if (isInvoiceAmendmentRequest && !allowedAnswers.CanSendInvoiceAmendmentRequest)
            isInvoiceAmendmentRequest = false;
          if (!isInvoiceAmendmentRequest && !allowedAnswers.CanSendAmendmentRequest)
            isInvoiceAmendmentRequest = true;
          
          var receipts = new List<NpoComputer.DCX.Common.IReglamentDocument>();
          var rootBox = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);
          var packageDocumentsExchangeInfos = GetPackageDocumentsExchangeInfos(externalDocumentInfo.ServiceMessageId);
          var documentIds = documents.Select(d => d.Id);
          packageDocumentsExchangeInfos = packageDocumentsExchangeInfos.Where(info => documentIds.Contains(info.Document.Id)).ToList();
          var invoiceExchangeInfoIds = new List<int>();
          if (rootBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis &&
              packageDocumentsExchangeInfos.Count > 1)
          {
            var tempDocs = new List<NpoComputer.DCX.Common.IDocument>();
            foreach (IExchangeDocumentInfo info in packageDocumentsExchangeInfos)
            {
              var allowedAnswersSbis = client.GetAllowedAnswers(info.ServiceDocumentId, info.ServiceMessageId, info.ExternalBuyerTitleId);
              if (allowedAnswersSbis.CanSendAmendmentRequest || allowedAnswersSbis.CanSendInvoiceAmendmentRequest)
              {
                tempDocs.Add(new NpoComputer.DCX.Common.Document()
                             {
                               ServiceMessageId = info.ServiceMessageId,
                               ServiceEntityId = info.ServiceDocumentId
                             });
                if (allowedAnswersSbis.CanSendInvoiceAmendmentRequest == true)
                  invoiceExchangeInfoIds.Add(info.Id);
              }
            }
            // Для Сбиса передаем сразу сертификат, чтобы не искать в хранилище по отпечатку.
            receipts = client.GenerateInvoiceAmendmentRequestsForPackage(tempDocs, certificate.X509Certificate, note);
            packageProcessing = true;
          }
          else
          {
            var tempDoc = new NpoComputer.DCX.Common.Document()
            {
              ServiceMessageId = externalDocumentInfo.ServiceMessageId,
              ServiceEntityId = externalDocumentInfo.ServiceDocumentId
            };

            // Для Сбиса передаем сразу сертификат, чтобы не искать в хранилище по отпечатку.
            // Для Сбиса генерируем всегда только уведомление об уточнении, т.к. нет разделения между отказом и уведомлением об уточнении.
            if (externalDocumentInfo.RootBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis)
              receipts.Add(client.GenerateInvoiceAmendmentRequest(tempDoc, certificate.X509Certificate, note));
            else
            {
              if (isInvoiceAmendmentRequest)
                receipts.Add(client.GenerateInvoiceAmendmentRequest(tempDoc, certificate.Thumbprint, note));
              else
                receipts.Add(client.GenerateAmendmentRequest(tempDoc, note, certificate.Thumbprint));
            }
          }
          
          foreach (NpoComputer.DCX.Common.IReglamentDocument receipt in receipts)
          {
            var exchangeDocumentInfo = ExchangeDocumentInfos.GetAll().Where(i => i.ServiceDocumentId == receipt.ParentServiceEntityId && Equals(i.RootBox, box)).First();
            var exchangeDocument = OfficialDocuments.Get(exchangeDocumentInfo.Document.Id);
            var formalizedPoA = Docflow.PublicFunctions.OfficialDocument.GetFormalizedPoA(exchangeDocument, Employees.Current, certificate);
            
            if (packageProcessing)
              isInvoiceAmendmentRequest = invoiceExchangeInfoIds.Contains(exchangeDocumentInfo.Id);
            var documentType = isInvoiceAmendmentRequest ? Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReject : Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Reject;
            var doc = Structures.Module.ReglamentDocumentWithCertificate.Create(receipt.FileName, receipt.Content, certificate,
                                                                                null, exchangeDocumentInfo.ServiceDocumentId,
                                                                                ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box),
                                                                                exchangeDocument, exchangeDocumentInfo.ServiceMessageId, receipt.ServiceEntityId, receipt.DocflowStageId,
                                                                                exchangeDocumentInfo.ServiceCounterpartyId, false,
                                                                                exchangeDocumentInfo, isInvoiceAmendmentRequest, documentType, formalizedPoA?.UnifiedRegistrationNumber);
            docsWithCertificates.Add(doc);
          }
        }
        catch (AppliedCodeException ex)
        {
          // Гасить исключение, если операция недоступна в сервисе.
          if (ex.Message != Resources.AnswerIsAlreadySent || throwError)
            throw;
        }
        catch (Exception ex)
        {
          if (ex is CommonLibrary.Exceptions.PlatformException)
            throw;
          
          throw AppliedCodeException.Create(Resources.AmendmentRequestError);
        }
        
        if (packageProcessing)
          break;
      }
      return docsWithCertificates;
    }
    
    /// <summary>
    /// Сгенерировать извещение о получении на служебный документ.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="documentInfo">Информация.</param>
    /// <param name="client">Dcx клиент.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <param name="documentType">Тип служебного документа, на который генерируется ИОП.</param>
    /// <param name="certificate">Сертификат.</param>
    /// <param name="reglamentDocumentType">Тип служебного документа, который будет сгенерирован.</param>
    /// <param name="generateServiceDocuments">Перегенерировать ИОП.</param>
    /// <returns>Извещение о получении на служебный документ.</returns>
    protected virtual ReglamentDocumentWithCertificate GenerateInvoiceServiceDeliveryConfirmation(IOfficialDocument document,
                                                                                                  IExchangeDocumentInfo documentInfo, DcxClient client, IBusinessUnitBox box, Enumeration documentType,
                                                                                                  ICertificate certificate, Enumeration reglamentDocumentType, bool generateServiceDocuments)
    {
      var parentServiceDocument = documentInfo.ServiceDocuments.First(d => d.DocumentType == documentType);
      var generatedDocument = documentInfo.ServiceDocuments.FirstOrDefault(d => d.DocumentType == reglamentDocumentType);
      byte[] content = null;
      var name = string.Empty;
      byte[] signature = null;
      var serviceDocumentId = string.Empty;
      var serviceDocumentStageId = string.Empty;
      if (generatedDocument == null && generateServiceDocuments)
      {
        // Для Сбиса передаем сразу сертификат, чтобы не искать в хранилище по отпечатку.
        var receipt = box.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Sbis ?
          client.GenerateInvoiceDeliveryConfirmation(parentServiceDocument.DocumentId, certificate.X509Certificate, documentInfo.ServiceDocumentId, documentInfo.ServiceMessageId) :
          client.GenerateInvoiceDeliveryConfirmation(parentServiceDocument.DocumentId, certificate.Thumbprint, documentInfo.ServiceDocumentId, documentInfo.ServiceMessageId);
        content = receipt.Content;
        name = receipt.FileName;
        serviceDocumentId = receipt.ServiceEntityId;
        serviceDocumentStageId = receipt.DocflowStageId;
        Logger.DebugFormat("Generate receipt notification with ExchangeDocumentInfoId = {0}, DocumentType = {1}, CounterpartyId = {2}," +
                           " ParentDocumentId = {3} LinkedDocumentId = {4}, ServiceMessageId = {5}, serviceDocumentId = {6}, serviceDocumentStageId = {7}",
                           documentInfo.Id, reglamentDocumentType, parentServiceDocument.CounterpartyId, parentServiceDocument.DocumentId,
                           document.Id, documentInfo.ServiceMessageId, serviceDocumentId, serviceDocumentStageId);
      }
      else if (generatedDocument != null && Equals(generatedDocument.Certificate, certificate))
      {
        content = generatedDocument.Body;
        name = generatedDocument.GeneratedName;
        signature = generatedDocument.Sign;
      }

      return content != null ?
        Structures.Module.ReglamentDocumentWithCertificate.Create(name, content, certificate, signature, parentServiceDocument.DocumentId, box, document,
                                                                  documentInfo.ServiceMessageId, serviceDocumentId, serviceDocumentStageId, parentServiceDocument.CounterpartyId, false, documentInfo,
                                                                  true, reglamentDocumentType, null)
        : null;
    }
    
    #endregion

    #region Отправка документов через диалог

    /// <summary>
    /// Формирование вспомогательной информации о документе для отправки контрагенту.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>Структура с дополнительной информацией.</returns>
    [Remote(IsPure = true)]
    public virtual Structures.Module.SendToCounterpartyInfo GetInfoForSendToCounterparty(Docflow.IOfficialDocument document)
    {
      var result = Structures.Module.SendToCounterpartyInfo.Create();
      if (document == null)
        return result;
      
      result.CanApprove = !Docflow.PublicFunctions.OfficialDocument.Remote.GetApprovalValidationErrors(document, true).Any();
      result.HasApprovalSignature = !HasNotApprovedDocuments(document);
      
      var businessUnit = document.BusinessUnit;
      result.HasError = false;
      result.Counterparties = new List<Parties.ICounterparty>();
      
      var exchangeDocumentInfo = Functions.ExchangeDocumentInfo.GetIncomingExDocumentInfo(document);
      result.IsSignedByCounterparty = Docflow.PublicFunctions.OfficialDocument.Remote.CanSendAnswer(document);
      result.BuyerAcceptanceStatus = exchangeDocumentInfo?.BuyerAcceptanceStatus;

      // Нельзя отправлять уже отправленные формализованные документы.
      var accountingDocument = Docflow.AccountingDocumentBases.As(document);
      if (accountingDocument != null && accountingDocument.IsFormalized == true)
      {
        var lastDocumentInfo = Functions.ExchangeDocumentInfo.GetLastDocumentInfo(document);
        if (lastDocumentInfo != null && lastDocumentInfo.MessageType == Exchange.ExchangeDocumentInfo.MessageType.Outgoing)
        {
          result.Error = Exchange.Resources.DocumentIsAlreadySentToCounterparty;
          result.HasError = true;
          return result;
        }
      }
      
      DocumentAllowedAnswer documentAllowedAnswer = null;
      if (document.Versions.Count > 1 && exchangeDocumentInfo != null)
      {
        var hasSign = Signatures.Get(document.Versions.OrderBy(v => v.Number).First()).Any(x => x.SignatureType == SignatureType.Approval && x.IsExternal == true);
        if (hasSign)
        {
          var firstBox = ExchangeCore.PublicFunctions.BusinessUnitBox.Remote.GetConnectedBoxes()
            .Where(a => Equals(a, exchangeDocumentInfo.RootBox)).SingleOrDefault();
          if (firstBox != null)
          {
            var client = GetClient(firstBox);
            documentAllowedAnswer = client.GetAllowedAnswers(exchangeDocumentInfo.ServiceDocumentId, exchangeDocumentInfo.ServiceMessageId, exchangeDocumentInfo.ExternalBuyerTitleId);
            result.NeedRejectFirstVersion = documentAllowedAnswer.CanSendAmendmentRequest;
          }
        }
      }
      
      result = this.FillCounterpartyInfo(document, businessUnit, result);
      if (result.HasError)
        return result;

      var allBoxes = GetAllExchangeBoxesToCounterparty(document, result.Counterparties);
      result.Boxes = allBoxes
        .Where(b => b.ConnectionStatus == ExchangeCore.BusinessUnitBox.ConnectionStatus.Connected)
        .ToList();
      if (!result.Boxes.Any())
      {
        if (!allBoxes.Any())
          result.Error = Resources.BoxesNotFound;
        else
          result.Error = Resources.BoxesNotConnected;
        
        result.HasError = true;
        return result;
      }
      
      result = this.FillSignByCounterparty(document, exchangeDocumentInfo, result, businessUnit, documentAllowedAnswer);
      
      if (result.AnswerIsSent)
        return result;
      
      result = this.FillAddendaInfo(document, result);

      if (result.DefaultBox != null && (result.HasApprovalSignature || result.IsSignedByCounterparty))
      {
        try
        {
          result.Certificates = this.GetDocumentCertificatesToBox(document, result.DefaultBox);
        }
        catch (AppliedCodeException ex)
        {
          result.Error = ex.Message;
          result.HasError = true;
          return result;
        }
        
        result.IsSignedByUs = result.Certificates.Certificates.Any();
      }
      else
      {
        result.Certificates = Structures.Module.DocumentCertificatesInfo
          .Create(new List<ICertificate>(), result.CanApprove, new List<ICertificate>());
        result.IsSignedByUs = false;
      }
      
      return result;
    }

    /// <summary>
    /// Заполнить варианты отправки ответа контрагенту.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="exchangeDocumentInfo">Информация о документе.</param>
    /// <param name="result">Вспомогательная информация о документе для отправки контрагенту.</param>
    /// <param name="businessUnit">Наша организация.</param>
    /// <param name="documentAllowedAnswers">Допустимые варианты подписания/отказа/УОУ на документ.</param>
    /// <returns>Информация о документе с вариантами отправки ответа контрагенту.</returns>
    protected virtual SendToCounterpartyInfo FillSignByCounterparty(IOfficialDocument document,
                                                                    IExchangeDocumentInfo exchangeDocumentInfo, SendToCounterpartyInfo result,
                                                                    IBusinessUnit businessUnit, NpoComputer.DCX.Common.DocumentAllowedAnswer documentAllowedAnswers)
    {
      if (result.IsSignedByCounterparty)
      {
        try
        {
          result.DefaultBox = ExchangeCore.PublicFunctions.BusinessUnitBox.Remote.GetConnectedBoxes()
            .Where(a => Equals(a, exchangeDocumentInfo.RootBox)).SingleOrDefault();
          if (result.DefaultBox == null)
            throw AppliedCodeException.Create(Resources.BoxIsNotValid);

          result.ParentDocumentId = exchangeDocumentInfo.ServiceDocumentId;
          if (documentAllowedAnswers == null)
          {
            var client = GetClient(result.DefaultBox);
            documentAllowedAnswers = client.GetAllowedAnswers(exchangeDocumentInfo.ServiceDocumentId, exchangeDocumentInfo.ServiceMessageId, exchangeDocumentInfo.ExternalBuyerTitleId);
          }
          result.CanSendSignAsAnswer = documentAllowedAnswers.CanSendSign;
          result.CanSendAmendmentRequestAsAnswer = documentAllowedAnswers.CanSendAmendmentRequest;
          result.CanSendInvoiceAmendmentRequestAsAnswer = documentAllowedAnswers.CanSendInvoiceAmendmentRequest;
          result.AnswerIsSent = !result.CanSendAmendmentRequestAsAnswer && !result.CanSendSignAsAnswer && !result.CanSendInvoiceAmendmentRequestAsAnswer;
        }
        catch (AppliedCodeException ex)
        {
          result.Error = ex.Message;
          result.HasError = true;
          return result;
        }
      }
      else
      {
        var businessUnitOrder = businessUnit ?? Company.PublicFunctions.BusinessUnit.Remote.GetBusinessUnit(Company.Employees.Current);
        if (Docflow.AccountingDocumentBases.Is(document) && Docflow.AccountingDocumentBases.As(document).IsFormalized == true)
          result.DefaultBox = Docflow.AccountingDocumentBases.As(document).BusinessUnitBox;
        if (result.DefaultBox == null)
          result.DefaultBox = result.Boxes
            .OrderByDescending(x => Equals(x.BusinessUnit, businessUnitOrder))
            .First();
      }

      return result;
    }

    /// <summary>
    /// Заполнить вспомогательную информацию о приложениях, которые будут отправлены с основным.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="result">Вспомогательная информация о документе для отправки контрагенту.</param>
    /// <returns>Информация о документе и его приложениях для отправки контрагенту.</returns>
    protected virtual SendToCounterpartyInfo FillAddendaInfo(IOfficialDocument document, SendToCounterpartyInfo result)
    {
      var addenda = document.Relations
        .GetRelated().Union(document.Relations.GetRelatedFrom()).Distinct()
        .Select(e => Docflow.OfficialDocuments.As(e))
        .Where(d => d != null && d.HasVersions && d.AccessRights.CanUpdate() && d.AccessRights.CanSendByExchange()).ToList();

      result.Addenda = new List<Exchange.Structures.Module.AddendumInfo>();
      foreach (var addendum in addenda)
      {
        var addendumInfo = new Exchange.Structures.Module.AddendumInfo();
        addendumInfo.Addendum = addendum;

        var exchangeDocInfo = Functions.ExchangeDocumentInfo.GetIncomingExDocumentInfo(addendum);
        
        addendumInfo.BuyerAcceptanceStatus = exchangeDocInfo?.BuyerAcceptanceStatus;
        
        if (result.IsSignedByCounterparty)
        {
          if (!addendum.HasVersions)
            continue;

          if (exchangeDocInfo == null || exchangeDocInfo.NeedSign != true)
            continue;

          // Нельзя отвечать на документы, которые не требуют от нас подписания.
          if (addendum.ExchangeState != Docflow.OfficialDocument.ExchangeState.SignRequired)
            continue;
        }
        else
        {
          if (exchangeDocInfo != null && addendum.Versions.Count > 1)
            addendumInfo.NeedRejectFirstVersion = true;

          // Нельзя отправлять документы, у которых есть какой-то статус МКДО, они или пришли нам или уже ушли от нас.
          if (addendum.ExchangeState != null)
            continue;
        }

        result.Addenda.Add(addendumInfo);
      }

      result.HasAddendaToSend = result.Addenda.Any();
      return result;
    }

    /// <summary>
    /// Заполнить информацию о контрагентах.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="businessUnit">Наша организация.</param>
    /// <param name="result">Информация о документе для отправки контрагенту.</param>
    /// <returns>Информация о документе с данными о контрагентах.</returns>
    protected virtual SendToCounterpartyInfo FillCounterpartyInfo(IOfficialDocument document, IBusinessUnit businessUnit, SendToCounterpartyInfo result)
    {
      var allBusinessUnitCounterparties = Parties.PublicFunctions.Counterparty.Remote.GetExchangeCounterparty(businessUnit);
      var documentCounterparties = Functions.ExchangeDocumentInfo.GetDocumentCounterparties(document);
      var hasDocumentCounterparties = documentCounterparties != null && documentCounterparties.Any();

      if (hasDocumentCounterparties)
      {
        // В основном в документах 1 контрагент, работаем как раньше.
        if (documentCounterparties.Count < 2)
          result.DefaultCounterparty = documentCounterparties.FirstOrDefault();
        else
        {
          documentCounterparties = allBusinessUnitCounterparties.Intersect(documentCounterparties).ToList();

          // Если после фильтрации кто-то остался - он по умолчанию.
          if (documentCounterparties.Count < 2)
            result.DefaultCounterparty = documentCounterparties.FirstOrDefault();
        }
      }

      if (result.DefaultCounterparty != null)
      {
        result.Counterparties.Add(result.DefaultCounterparty);

        var parties = result.DefaultCounterparty.ExchangeBoxes
          .Where(x => Equals(x.Status, Parties.CounterpartyExchangeBoxes.Status.Active) && x.IsDefault == true);

        if (businessUnit != null)
          parties = parties.Where(x => Equals(x.Box.BusinessUnit, businessUnit));

        if (!parties.Any())
        {
          if (!result.IsSignedByCounterparty)
            result.Error = Resources.NeedSetExchangeForCounterparty;
          else
            result.Error = Resources.NoExchangeThroughThisService;

          result.HasError = true;
        }
      }
      else if (hasDocumentCounterparties)
      {
        result.Counterparties.AddRange(documentCounterparties);
      }
      else
      {
        result.Counterparties.AddRange(allBusinessUnitCounterparties);
      }

      return result;
    }

    /// <summary>
    /// Получить сертификаты для подписания документов, которые будут отправлены через сервис обмена.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="box">Абонентский ящик обмена.</param>
    /// <returns>Информация о сертификатах.</returns>
    [Remote(IsPure = true)]
    public virtual Structures.Module.DocumentCertificatesInfo GetDocumentCertificatesToBox(Docflow.IOfficialDocument document, ExchangeCore.IBusinessUnitBox box)
    {
      var version = document.LastVersion;
      var signatures = Signatures.Get(version).Where(s => s.IsExternal != true && s.IsValid && s.SignCertificate != null).ToList();
      var allowedCertificates = new List<ICertificate>();
      var allowedCertificatesThumbprints = new List<Structures.Module.Certificate>();
      
      var allCertificates = Certificates.GetAll().ToList();
      var currentUserCertificates = allCertificates.Where(x => Equals(x.Owner, Users.Current) && x.Enabled == true).ToList();
      var canSign = currentUserCertificates.Any();

      if (box.HasExchangeServiceCertificates == true)
      {
        var exchangeCertificates = box.ExchangeServiceCertificates.Select(x => x.Certificate).ToList();
        
        signatures = signatures.Where(s => exchangeCertificates.Any(x => x.Thumbprint.Equals(s.SignCertificate.Thumbprint, StringComparison.InvariantCultureIgnoreCase))).ToList();
      }
      
      allowedCertificatesThumbprints = signatures.GroupBy(s => s.Signatory)
        .Select(x => x.OrderByDescending(s => Equals(s.SignatureType, SignatureType.Approval))
                .ThenByDescending(s => s.SigningDate)
                .First())
        .OrderByDescending(s => Equals(s.SignatureType, SignatureType.Approval))
        .ThenByDescending(s => s.SigningDate)
        .Select(s => Structures.Module.Certificate.Create(s.SignCertificate.Thumbprint, s.Signatory))
        .ToList();
      
      foreach (var cert in allowedCertificatesThumbprints)
      {
        var existCert = allCertificates.FirstOrDefault(x => x.Thumbprint.Equals(cert.Thumbprint, StringComparison.InvariantCultureIgnoreCase) && Equals(x.Owner, cert.Owner));
        
        if (existCert != null)
          allowedCertificates.Add(existCert);
      }
      
      allowedCertificates = allowedCertificates.Distinct().ToList();
      
      return Structures.Module.DocumentCertificatesInfo.Create(allowedCertificates, canSign, currentUserCertificates);
    }

    /// <summary>
    /// Получить подключенные ящики сервисов обмена для отправки документа контрагентам.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="counterparties">Контрагенты.</param>
    /// <returns>Список подключенных ящиков сервисов обмена.</returns>
    [Remote(IsPure = true)]
    public static List<ExchangeCore.IBusinessUnitBox> GetConnectedExchangeBoxesToCounterparty(Docflow.IOfficialDocument document, List<Parties.ICounterparty> counterparties)
    {
      return GetAllExchangeBoxesToCounterparty(document, counterparties)
        .Where(b => b.ConnectionStatus == ExchangeCore.BusinessUnitBox.ConnectionStatus.Connected)
        .ToList();
    }

    /// <summary>
    /// Получить все ящики сервисов обмена для отправки документа контрагентам.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="counterparties">Контрагенты.</param>
    /// <returns>Список всех ящиков сервисов обмена.</returns>
    [Remote(IsPure = true)]
    public static List<ExchangeCore.IBusinessUnitBox> GetAllExchangeBoxesToCounterparty(Docflow.IOfficialDocument document, List<Parties.ICounterparty> counterparties)
    {
      var boxes = counterparties.SelectMany(c => c.ExchangeBoxes
                                            .Where(b => b.Status == Parties.CounterpartyExchangeBoxes.Status.Active && b.IsDefault == true)
                                            .Select(b => b.Box)).ToList();
      
      boxes = boxes.Distinct().Where(x => x.Status == Sungero.CoreEntities.DatabookEntry.Status.Active).ToList();
      if (document.BusinessUnit != null)
        boxes = boxes.Where(x => Equals(x.BusinessUnit, document.BusinessUnit)).ToList();
      
      return boxes;
    }

    private static bool HasNotApprovedDocuments(IOfficialDocument document, List<IOfficialDocument> documents)
    {
      var notSigned = HasNotApprovedDocuments(document);
      if (notSigned)
        return true;
      
      return HasNotApprovedDocuments(documents.ToArray());
    }

    private static bool HasNotApprovedDocuments(IOfficialDocument document)
    {
      return HasNotApprovedDocuments(new[] { document });
    }

    private static bool HasNotApprovedDocuments(params IOfficialDocument[] documents)
    {
      foreach (var document in documents)
      {
        var signed = Signatures.Get(document.LastVersion)
          .Any(s => s.SignatureType == SignatureType.Approval && s.IsExternal != true && s.IsValid);
        if (!signed)
          return true;
      }
      return false;
    }

    #endregion
    
    #endregion
    
    #region Отправка извещений о получении
    
    /// <summary>
    /// Получить список информации о документах, для которых требуется отправить ИОП.
    /// </summary>
    /// <param name="box">Абонентский ящик нашей организации.</param>
    /// <param name="skip">Количество пропускаемых записей.</param>
    /// <param name="take">Количество получаемых записей.</param>
    /// <param name="withoutGenerated">True, если хотим получить только инфошки, по которым ещё надо выполнить генерацию ИОП.</param>
    /// <returns>Информация о документах, для которых требуется отправить ИОП.</returns>
    [Public, Remote(IsPure = true)]
    public List<IExchangeDocumentInfo> GetDocumentInfosWithoutReceiptNotificationPart(Sungero.ExchangeCore.IBusinessUnitBox box,
                                                                                      int skip, int take, bool withoutGenerated)
    {
      var documentInfos = this.GetDocumentInfosWithoutReceiptNotification(box, withoutGenerated).ToList();
      // Получить инфошки по сообщениям для обработки служебных документов сообщений целиком(одновременная отправка ИОПов на комплект. СБИС).
      var messagesIds = documentInfos.Select(d => d.ServiceMessageId).Distinct().Skip(skip).Take(take).ToList();
      documentInfos = documentInfos.Where(info => messagesIds.Contains(info.ServiceMessageId)).ToList();
      
      // Рассчитываем, что объем данных, запрошенных в take, будет небольшой.
      var documentIds = documentInfos.Select(d => d.Document.Id).Distinct().ToList();
      var availableIds = Docflow.OfficialDocuments.GetAll(d => documentIds.Contains(d.Id)).Select(d => d.Id).ToList();
      return documentInfos.Where(i => availableIds.Contains(i.Document.Id)).ToList();
    }

    /// <summary>
    /// Получить список информации о документах, для которых требуется отправить ИОП.
    /// </summary>
    /// <param name="box">Абонентский ящик нашей организации.</param>
    /// <param name="withoutGenerated">True, если хотим получить только инфошки, по которым ещё надо выполнить генерацию ИОП.</param>
    /// <returns>Информация о документах, для которых требуется отправить ИОП.</returns>
    [Public]
    public IQueryable<IExchangeDocumentInfo> GetDocumentInfosWithoutReceiptNotification(Sungero.ExchangeCore.IBusinessUnitBox box, bool withoutGenerated)
    {
      var certificate = box.CertificateReceiptNotifications;
      var documentInfos = ExchangeDocumentInfos.GetAll()
        .Where(x => Equals(x.RootBox, box) && x.Document != null &&
               (!x.ServiceDocuments.Any(d => (d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.IReceipt ||
                                              d.DocumentType == Exchange.ExchangeDocumentInfoServiceDocuments.DocumentType.Receipt) &&
                                        (withoutGenerated ? d.Certificate == certificate : d.Date != null)) &&
                x.DeliveryConfirmationStatus == null));
      
      return documentInfos;
    }

    /// <summary>
    /// Определить, отправлены ли служебные документы.
    /// </summary>
    /// <param name="documentInfos">Список информации о документах обмена.</param>
    /// <returns>True - если документы не отправлены, иначе - false.</returns>
    [Remote(IsPure = true)]
    public bool IsReglamentDocumentsNotSent(List<IExchangeDocumentInfo> documentInfos)
    {
      var documentInfoIds = documentInfos.Select(i => i.ServiceDocumentId).ToList();
      return ExchangeDocumentInfos.GetAll(info => documentInfoIds.Contains(info.ServiceDocumentId))
        .Any(info => !Equals(info.DeliveryConfirmationStatus, Exchange.ExchangeDocumentInfo.DeliveryConfirmationStatus.Sent));
    }
    
    /// <summary>
    /// Получить список документов, для которых требуется отправить ИОП.
    /// </summary>
    /// <param name="box">Абонентский ящик нашей организации.</param>
    /// <returns>Список документов, для которых требуется отправить ИОП.</returns>
    [Remote]
    public IQueryable<Content.IElectronicDocument> GetDocumentsWithoutReceiptNotification(Sungero.ExchangeCore.IBusinessUnitBox box)
    {
      return this.GetDocumentInfosWithoutReceiptNotification(box, false).Select(d => d.Document);
    }
    
    /// <summary>
    /// Проставить признак получения ИОПа.
    /// </summary>
    /// <param name="info">Информация о документе МКДО.</param>
    /// <param name="comment">Комментарий.</param>
    /// <param name="sent">Была ли реальная отправка или отправка не требуется.</param>
    [Remote]
    public virtual void FixReceiptNotification(Exchange.IExchangeDocumentInfo info, string comment, bool sent)
    {
      var operation = new Enumeration(Constants.Module.Exchange.SendReadMark);
      this.LogDebugFormat(info, "Execute FixReceiptNotification.");
      info = Exchange.ExchangeDocumentInfos.GetAll(i => i.Id == info.Id).SingleOrDefault();
      if (info != null && info.DeliveryConfirmationStatus != Exchange.ExchangeDocumentInfo.DeliveryConfirmationStatus.Sent)
      {
        if (sent)
        {
          var version = info.Document.Versions.Where(v => v.Id == info.VersionId).Single();
          info.Document.History.Write(operation, operation, comment, version.Number);
          var client = GetClient(info.RootBox);
          if (!client.CanSendDeliveryConfirmation(info.ServiceDocumentId, info.ServiceMessageId))
          {
            info.DeliveryConfirmationStatus = Exchange.ExchangeDocumentInfo.DeliveryConfirmationStatus.Sent;
            this.LogDebugFormat(info, "Execute FixReceiptNotification. Receipts successfully sent.");
          }
        }
        else
        {
          info.DeliveryConfirmationStatus = Exchange.ExchangeDocumentInfo.DeliveryConfirmationStatus.NotRequired;
          this.LogDebugFormat(info, "Execute FixReceiptNotification. Receipts not sent.");
        }
        info.Save();
      }
    }
    
    /// <summary>
    /// Проставить признак получения ИОПа.
    /// </summary>
    /// <param name="documentInfos">Информация о документах МКДО.</param>
    /// <param name="comment">Комментарий.</param>
    [Remote]
    public virtual void FixReceiptNotification(List<Exchange.IExchangeDocumentInfo> documentInfos, string comment)
    {
      foreach (var info in documentInfos)
        this.FixReceiptNotification(info, comment, false);
    }
    
    /// <summary>
    /// Создать задачу на отправку извещений о получении документов.
    /// </summary>
    /// <param name="box">Абонентский ящик нашей организации.</param>
    /// <returns>Задача на отправку извещений о получении документов.</returns>
    [Remote, Public]
    public IReceiptNotificationSendingTask CreateReceiptNotificationSendingTask(Sungero.ExchangeCore.IBusinessUnitBox box)
    {
      var task = Sungero.Exchange.ReceiptNotificationSendingTasks.Create();
      task.Box = box;
      task.Subject = CutText(Sungero.Exchange.ReceiptNotificationSendingTasks.Resources.TaskSubjectFormat(box.Name), task.Info.Properties.Subject.Length);
      task.ActiveText = Sungero.Exchange.ReceiptNotificationSendingTasks.Resources.TaskActiveTextFormat(box.ExchangeService.Name);
      task.MaxDeadline = Calendar.Now.AddWorkingHours(box.Responsible, 4);
      task.Save();
      return task;
    }
    
    /// <summary>
    /// Сохранить служебные документы, которые будут подписаны.
    /// </summary>
    /// <param name="documentsToSign">Сервисный документ, сертификат, которым он должен быть подписан и подпись.</param>
    [Remote]
    public virtual void SaveDeliveryConfirmationSigns(List<Structures.Module.ReglamentDocumentWithCertificate> documentsToSign)
    {
      foreach (var doc in documentsToSign)
      {
        var info = ExchangeDocumentInfos.Get(doc.Info.Id);
        if (Locks.GetLockInfo(info).IsLockedByOther)
          continue;
        
        var serviceDocument = info.ServiceDocuments.FirstOrDefault(d => d.DocumentType == doc.ReglamentDocumentType);
        if (serviceDocument == null)
        {
          serviceDocument = info.ServiceDocuments.AddNew();
          serviceDocument.DocumentType = doc.ReglamentDocumentType;
        }
        serviceDocument.DocumentId = doc.ServiceDocumentId;
        serviceDocument.ParentDocumentId = doc.ParentDocumentId;
        serviceDocument.Sign = doc.Signature;
        serviceDocument.Certificate = doc.Certificate;
        serviceDocument.Body = doc.Content;
        serviceDocument.GeneratedName = doc.Name;
        serviceDocument.StageId = doc.ServiceDocumentStageId;
        serviceDocument.FormalizedPoAUnifiedRegNo = doc.FormalizedPoAUnifiedRegNumber;
        info.Save();
      }
    }
    
    #endregion

    #region Общие сервисные методы

    /// <summary>
    /// Создать элемент очереди конвертации версий документов.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="versionId">ИД версии документа.</param>
    /// <param name="exchangeStatus">Статус обмена.</param>
    [Public]
    public void EnqueueXmlToPdfBodyConverter(Sungero.Docflow.IOfficialDocument document, int versionId, Enumeration? exchangeStatus)
    {
      var queueItem = ExchangeCore.BodyConverterQueueItems.Create();
      queueItem.Document = document;
      queueItem.VersionId = versionId;
      queueItem.ExchangeState = exchangeStatus;
      queueItem.ProcessingStatus = ExchangeCore.MessageQueueItem.ProcessingStatus.NotProcessed;
      queueItem.Save();
    }

    /// <summary>
    /// Убрать пространства имен.
    /// </summary>
    /// <param name="document">Документ.</param>
    [Public]
    public static void RemoveNamespaces(System.Xml.Linq.XDocument document)
    {
      foreach (var rootElements in document.Root.Descendants())
      {
        var attributesWithNamespace = rootElements.Attributes().Where(x => x.IsNamespaceDeclaration).ToList();
        foreach (var attributeWithNamespace in attributesWithNamespace)
          attributeWithNamespace.Remove();
      }
      foreach (var element in document.Descendants().Where(x => x.Name.NamespaceName.Any()).ToList())
        element.Name = element.Name.LocalName;
    }

    /// <summary>
    /// Обрезать длинную строку.
    /// </summary>
    /// <param name="text">Строка.</param>
    /// <param name="maxLength">Максимальная длина строки.</param>
    /// <returns>Строка указанной длины.</returns>
    [Public]
    public static string CutText(string text, int maxLength)
    {
      if (text.Length > maxLength)
        return Sungero.Exchange.Resources.Ellipsis_CutTextFormat(text.Substring(0, maxLength - 1));
      
      return text;
    }

    /// <summary>
    /// Проверка фонового процесса.
    /// </summary>
    /// <param name="id">Id фонового процесса.</param>
    /// <returns>Включен ли фоновый процесс.</returns>
    [Public, Remote]
    public static bool IsJobEnabled(string id)
    {
      var isJobEnabled = false;
      AccessRights.AllowRead(
        () =>
        {
          var guid = Guid.Parse(id);
          var job = CoreEntities.Jobs.GetAll(x => Equals(x.JobId, guid)).FirstOrDefault();
          isJobEnabled = job != null && job.Status == Sungero.CoreEntities.DatabookEntry.Status.Active;
        });
      return isJobEnabled;
    }
    
    /// <summary>
    /// Запустить фоновый процесс "Электронный обмен. Получение сообщений".
    /// </summary>
    [Public, Remote]
    public static void RequeueMessagesGet()
    {
      Jobs.GetMessages.Enqueue();
    }
    
    /// <summary>
    /// Запустить фоновый процесс "Электронный обмен. Получение исторических сообщений из сервисов обмена".
    /// </summary>
    [Public, Remote]
    public static void RequeueGetHistoricalMessages()
    {
      Jobs.GetHistoricalMessages.Enqueue();
    }
    
    /// <summary>
    /// Запустить фоновый процесс "Электронный обмен. Преобразование документов в PDF".
    /// </summary>
    [Public, Remote]
    public static void RequeueBodyConverterJob()
    {
      Jobs.BodyConverterJob.Enqueue();
    }
    
    /// <summary>
    /// Запустить фоновый процесс "Электронный обмен. Создание извещений о получении документов".
    /// </summary>
    [Public, Remote]
    public static void RequeueGenerateServiceDocuments()
    {
      Jobs.CreateReceiptNotifications.Enqueue();
    }
    
    /// <summary>
    /// Запустить фоновый процесс "Электронный обмен. Отправка извещений о получении документов".
    /// </summary>
    [Public, Remote]
    public static void RequeueSendSignedReceiptNotifications()
    {
      Jobs.SendSignedReceiptNotifications.Enqueue();
    }

    /// <summary>
    /// Заменить спец. символы и зарезервированные слова.
    /// </summary>
    /// <param name="name">Имя файла без расширения.</param>
    /// <returns>Преобразованное имя файла.</returns>
    [Public, Remote]
    public virtual string GetValidFileName(string name)
    {
      var replacement = "_";
      var normalizedName = name.Trim();
      
      if (string.IsNullOrEmpty(normalizedName))
        normalizedName = replacement;

      var specialWordsPattern = @"^(CON|PRN|AUX|CLOCK\$|NUL|COM0|COM1|COM2|COM3|COM4|COM5|COM6|COM7|COM8|COM9|LPT0|LPT1|LPT2|LPT3|LPT4|LPT5|LPT6|LPT7|LPT8|LPT9)(\.+|\.*$)";
      normalizedName = System.Text.RegularExpressions.Regex.Replace(normalizedName, specialWordsPattern, replacement, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

      var specialSimbolPattern = @"\\|\/|\:|\*|\?|\<|\>|\||\'|""";
      normalizedName = System.Text.RegularExpressions.Regex.Replace(normalizedName, specialSimbolPattern, replacement);

      normalizedName = System.Text.RegularExpressions.Regex.Replace(normalizedName, @"\.$", replacement);

      this.LogDebugFormat(string.Format("Normalize File Name {0} To {1}", name, normalizedName));
      return normalizedName;
    }

    /// <summary>
    /// Получить сертификаты.
    /// </summary>
    /// <param name="owner">Владелец сертификата.</param>
    /// <returns>Список сертификатов.</returns>
    [Remote]
    public virtual IQueryable<ICertificate> GetCertificates(IUser owner)
    {
      return Certificates.GetAll().Where(x => Equals(x.Owner, owner) && x.Enabled == true);
    }

    /// <summary>
    /// Получить список с информацией по документам обмена.
    /// </summary>
    /// <param name="serviceMessageId">Ид сообщения.</param>
    /// <returns>Список с информацией по документам обмена.</returns>
    [Public, Remote]
    public static List<IExchangeDocumentInfo> GetPackageDocumentsExchangeInfos(string serviceMessageId)
    {
      return ExchangeDocumentInfos.GetAll().Where(d => d.ServiceMessageId == serviceMessageId &&
                                                  d.MessageType.Value == Sungero.Exchange.ExchangeDocumentInfo.MessageType.Incoming).ToList();
    }

    /// <summary>
    /// Определить наличие прав у пользователя на документы комплекта.
    /// </summary>
    /// <param name="exchangeDocumentsInfos">Список информации по документам обмена.</param>
    /// <returns>True - если есть права на все документы комплекта, иначе - false.</returns>
    [Public, Remote]
    public static bool HasRightsToPackageExchangeDocuments(List<IExchangeDocumentInfo> exchangeDocumentsInfos)
    {
      var documentsIds = exchangeDocumentsInfos.Select(d => d.Document.Id).ToArray();
      var packageDocuments = Docflow.OfficialDocuments.GetAll(d => documentsIds.Contains(d.Id));
      if (packageDocuments.Count() != exchangeDocumentsInfos.Count())
        return false;
      foreach (var document in packageDocuments)
      {
        if (!document.AccessRights.CanUpdate())
          return false;
      }
      return true;
    }

    /// <summary>
    /// Проверка накопленных ошибок обмена.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    public virtual void RunExchangeCheckup(ExchangeCore.IBusinessUnitBox box)
    {
      var poisonedMessagePeriodBegin = Calendar.Now.AddDays(-Constants.Module.PoisonedMessagePeriod);
      var poisonedQueueItemsCount = MessageQueueItems.GetAll().Where(q => Equals(q.Box, box) && q.Created != null && q.Created < poisonedMessagePeriodBegin &&
                                                                     q.ProcessingStatus != Sungero.ExchangeCore.MessageQueueItem.ProcessingStatus.Suspended &&
                                                                     q.DownloadSession == null).Count();
      if (poisonedQueueItemsCount > 0)
        this.LogErrorFormat(box, "Business unit box contains {0} poisoned messages.", poisonedQueueItemsCount);

      var counterpartyExternalIds = CounterpartyQueueItems.GetAll(c => Equals(c.Box, box) && c.MatchingTask != null).Select(q => q.ExternalId).ToList();
      var counterpartyConflict = MessageQueueItems.GetAll().Where(q => Equals(q.Box, box) && q.CounterpartyExternalId != null && q.CounterpartyExternalId != string.Empty &&
                                                                  counterpartyExternalIds.Contains(q.CounterpartyExternalId) &&
                                                                  q.ProcessingStatus != Sungero.ExchangeCore.MessageQueueItem.ProcessingStatus.Suspended &&
                                                                  q.DownloadSession == null);
      var counterpartyConflictCount = counterpartyConflict.Count();
      if (counterpartyConflictCount > 0)
        this.LogErrorFormat(box, "{0} messages with unresolved counterparty conflicts for business unit box.", counterpartyConflictCount);
      
      var suspendedQueueItemsCount = MessageQueueItems.GetAll().Where(q => Equals(q.Box, box) &&
                                                                      Equals(q.ProcessingStatus, ExchangeCore.MessageQueueItem.ProcessingStatus.Suspended) &&
                                                                      q.DownloadSession == null).Count();
      if (suspendedQueueItemsCount > 0)
        this.LogDebugFormat(box, "Business unit box contains {0} suspended messages.", suspendedQueueItemsCount);
    }
    
    /// <summary>
    /// Получить статус приемки.
    /// </summary>
    /// <param name="primaryDocument">Документ сообщения.</param>
    /// <returns>Статус приемки.</returns>
    public Enumeration? GetBuyerAcceptanceStatus(NpoComputer.DCX.Common.IDocument primaryDocument)
    {
      switch (primaryDocument.BuyerAcceptanceStatus)
      {
        case NpoComputer.DCX.Common.BuyerAcceptanceStatus.Accepted:
          return Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Accepted;

        case NpoComputer.DCX.Common.BuyerAcceptanceStatus.PartiallyAccepted:
          return Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.PartiallyAccepted;

        case NpoComputer.DCX.Common.BuyerAcceptanceStatus.Rejected:
          return Exchange.ExchangeDocumentInfo.BuyerAcceptanceStatus.Rejected;

        default:
          return null;
      }
    }

    /// <summary>
    /// Получить ссылку на эл. доверенность в сервисе.
    /// </summary>
    /// <param name="unifiedRegistrationNumber">Единый рег. № эл. доверенности.</param>
    /// <returns>Ссылка на эл. доверенность в сервисе.</returns>
    public virtual string GetFormalizedPoALink(string unifiedRegistrationNumber)
    {
      return PublicConstants.Module.DefaultFormalizedPoALink;
    }

    /// <summary>
    /// Получить текстовое описание ссылки на эл. доверенность.
    /// </summary>
    /// <param name="unifiedRegistrationNumber">Единый рег. № эл. доверенности.</param>
    /// <returns>Текстовое описание ссылки на эл. доверенность.</returns>
    public virtual string GetFormalizedPoALinkTitle(string unifiedRegistrationNumber)
    {
      return Resources.SbisFormalizedPoALinkTitleFormat(unifiedRegistrationNumber);
    }

    #endregion
    
    #region Конвертация в pdf
    
    /// <summary>
    /// Запуск асинхронного обработчика конвертации в pdf.
    /// </summary>
    /// <param name="queueItem">Элемент очереди конвертации pdf.</param>
    public virtual void ExecuteConvertDocumentToPdfAsyncHandler(IBodyConverterQueueItem queueItem)
    {
      var asyncHandlerId = Guid.NewGuid().ToString();
      queueItem.AsyncHandlerId = asyncHandlerId;
      queueItem.Save();
      
      var convertDocumentToPdfHandler = Sungero.Exchange.AsyncHandlers.ConvertExchangeDocumentToPdf.Create();
      convertDocumentToPdfHandler.QueueItemId = queueItem.Id;
      convertDocumentToPdfHandler.AsyncHandlerId = asyncHandlerId;
      convertDocumentToPdfHandler.ExecuteAsync();
      this.LogDebugFormat(string.Format("ExecuteConvertDocumentToPdfAsyncHandler. QueueItemId: '{0}' AsyncHandlerId: '{1}'.", queueItem.Id, asyncHandlerId));
    }
    #endregion
    
    #region Управление загрузкой исторических сообщений.
    
    /// <summary>
    /// Запустить загрузку исторических сообщений.
    /// </summary>
    /// <param name="businessUnitBoxId">ИД абонентского ящика.</param>
    /// <param name="periodBegin">Начало периода.</param>
    /// <param name="periodEnd">Конец периода.</param>
    /// <returns>Информация о созданной сессии загрузки исторических сообщений.</returns>
    [Public(WebApiRequestType = RequestType.Post)]
    public virtual string RunHistoricalDownload(int businessUnitBoxId, DateTime periodBegin, DateTime periodEnd)
    {
      this.ValidateCreateHistoricalDownloadSessionData(businessUnitBoxId, periodBegin, periodEnd);
      
      var downloadSession = this.CreateHistoricalDownloadSession(businessUnitBoxId, periodBegin, periodEnd);
      
      return ExchangeCore.PublicFunctions.HistoricalMessagesDownloadSession.GetMainInfo(downloadSession);
    }
    
    /// <summary>
    /// Прекратить загрузку исторических сообщений.
    /// </summary>
    /// <param name="businessUnitBoxId">ИД абонентского ящика.</param>
    /// <returns>Информация о прекращенной сессии загрузки исторических сообщений.</returns>
    [Public(WebApiRequestType = RequestType.Post)]
    public virtual string AbortHistoricalDownload(int businessUnitBoxId)
    {
      this.ValidateAbortHistoricalDownloadSessionData(businessUnitBoxId);
      
      var downloadSession = this.AbortHistoricalDownloadSession(businessUnitBoxId);
      
      return downloadSession != null ? this.GetHistoricalDownloadSessionInfo(downloadSession.Id) : string.Empty;
    }

    /// <summary>
    /// Проверить данные для создания сессии загрузки исторических сообщений.
    /// </summary>
    /// <param name="businessUnitBoxId">ИД абонентского ящика.</param>
    /// <param name="periodBegin">Начало периода.</param>
    /// <param name="periodEnd">Конец периода.</param>
    public virtual void ValidateCreateHistoricalDownloadSessionData(int businessUnitBoxId, DateTime periodBegin, DateTime periodEnd)
    {
      if (!BusinessUnitBoxes.GetAll().Where(b => b.Id == businessUnitBoxId).Any())
        throw AppliedCodeException.Create(Sungero.Exchange.Resources.BusinessUnitBoxNotFoundFormat(businessUnitBoxId));
      
      var businessUnitBox = BusinessUnitBoxes.Get(businessUnitBoxId);
      
      if (businessUnitBox.Status != CoreEntities.DatabookEntry.Status.Active)
        throw AppliedCodeException.Create(Sungero.Exchange.Resources.BusinessUnitBoxClosedFormat(businessUnitBoxId));
      
      var downloadSessionInWork = ExchangeCore.PublicFunctions.BusinessUnitBox.GetHistoricalMessagesDownloadSessionInWork(businessUnitBox);
      
      if (downloadSessionInWork != null)
        throw AppliedCodeException.Create(Sungero.Exchange.Resources.HistoricalDownloadSessionAlreadyExistFormat(businessUnitBoxId));
      
      if (periodBegin > periodEnd || periodEnd > Calendar.Today || periodBegin > Calendar.Today)
        throw AppliedCodeException.Create(Sungero.Exchange.Resources.InvalidDatePeriodHistoricalDownloading);
    }
    
    /// <summary>
    /// Проверить данные для прекращения сессии загрузки исторических сообщений.
    /// </summary>
    /// <param name="businessUnitBoxId">ИД абонентского ящика.</param>
    public virtual void ValidateAbortHistoricalDownloadSessionData(int businessUnitBoxId)
    {
      if (!BusinessUnitBoxes.GetAll().Where(b => b.Id == businessUnitBoxId).Any())
        throw AppliedCodeException.Create(Sungero.Exchange.Resources.BusinessUnitBoxNotFoundFormat(businessUnitBoxId));
      
      var businessUnitBox = BusinessUnitBoxes.Get(businessUnitBoxId);
      var downloadSessionInWork = ExchangeCore.PublicFunctions.BusinessUnitBox.GetHistoricalMessagesDownloadSessionInWork(businessUnitBox);
      
      if (downloadSessionInWork == null)
        throw AppliedCodeException.Create(Sungero.Exchange.Resources.NotFoundActiveHistoricalMessagesDownloadSessionFormat(businessUnitBoxId));
    }

    /// <summary>
    /// Создать сессию загрузки исторических сообщений.
    /// </summary>
    /// <param name="businessUnitBoxId">ИД абонентского ящика.</param>
    /// <param name="periodBegin">Начало периода.</param>
    /// <param name="periodEnd">Конец периода.</param>
    /// <returns>Созданная сессия загрузки исторических сообщений.</returns>
    public virtual IHistoricalMessagesDownloadSession CreateHistoricalDownloadSession(int businessUnitBoxId, DateTime periodBegin, DateTime periodEnd)
    {
      var businessUnitBox = BusinessUnitBoxes.Get(businessUnitBoxId);
      var downloadSessionInWork = ExchangeCore.PublicFunctions.BusinessUnitBox.GetHistoricalMessagesDownloadSessionInWork(businessUnitBox);
      
      if (downloadSessionInWork != null)
        throw AppliedCodeException.Create(Sungero.Exchange.Resources.HistoricalDownloadSessionAlreadyExistFormat(businessUnitBoxId));
      
      var downloadSession = HistoricalMessagesDownloadSessions.Create();
      downloadSession.BusinessUnitBox = businessUnitBox;
      downloadSession.PeriodBegin = periodBegin;
      downloadSession.PeriodEnd = periodEnd;
      downloadSession.DownloadingState = ExchangeCore.HistoricalMessagesDownloadSession.DownloadingState.InWork;
      downloadSession.Save();
      
      return downloadSession;
    }
    
    /// <summary>
    /// Прекратить сессию загрузки исторических сообщений.
    /// </summary>
    /// <param name="businessUnitBoxId">ИД абонентского ящика.</param>
    /// <returns>Прекращенная сессия загрузки исторических сообщений.</returns>
    public virtual IHistoricalMessagesDownloadSession AbortHistoricalDownloadSession(int businessUnitBoxId)
    {
      var businessUnitBox = BusinessUnitBoxes.Get(businessUnitBoxId);
      var downloadSession = ExchangeCore.PublicFunctions.BusinessUnitBox.GetHistoricalMessagesDownloadSessionInWork(businessUnitBox);
      
      if (downloadSession != null)
      {
        downloadSession.DownloadingState = ExchangeCore.HistoricalMessagesDownloadSession.DownloadingState.Aborted;
        downloadSession.Save();
      }
      
      return downloadSession;
    }

    /// <summary>
    /// Получить сессии загрузки исторических сообщений по абонентскому ящику.
    /// </summary>
    /// <param name="businessUnitBoxId">Ид абонентского ящика.</param>
    /// <returns>Список Ид сессий загрузки исторических сообщений по абонентскому ящику.</returns>
    [Public(WebApiRequestType = RequestType.Get)]
    public virtual List<int> GetHistoricalDownloadSessions(int businessUnitBoxId)
    {
      return HistoricalMessagesDownloadSessions.GetAll(s => s.BusinessUnitBox.Id == businessUnitBoxId)
        .Select(s => s.Id)
        .OrderBy(s => s)
        .ToList();
    }

    /// <summary>
    /// Получить активные сессии загрузки исторических сообщений.
    /// </summary>
    /// <returns>Список Ид активных сессий загрузки исторических сообщений.</returns>
    [Public(WebApiRequestType = RequestType.Get)]
    public virtual List<int> GetActiveHistoricalDownloadSessions()
    {
      return HistoricalMessagesDownloadSessions.GetAll(s => s.DownloadingState == ExchangeCore.HistoricalMessagesDownloadSession.DownloadingState.InWork)
        .Select(s => s.Id)
        .OrderBy(s => s)
        .ToList();
    }
    
    /// <summary>
    /// Получить информацию о сессии загрузки исторических сообщений.
    /// </summary>
    /// <param name="downloadSessionId">ИД сессии загрузки исторических сообщений.</param>
    /// <returns>Информация о сессии загрузки исторических сообщений.</returns>
    [Public(WebApiRequestType = RequestType.Get)]
    public virtual string GetHistoricalDownloadSessionInfo(int downloadSessionId)
    {
      var downloadSession = HistoricalMessagesDownloadSessions.GetAll().Where(s => s.Id == downloadSessionId).SingleOrDefault();
      
      if (downloadSession == null)
        return string.Empty;
      
      var sessionMainInfo = ExchangeCore.PublicFunctions.HistoricalMessagesDownloadSession.GetMainInfo(downloadSession);
      var sessionAdditionalInfo = ExchangeCore.PublicFunctions.HistoricalMessagesDownloadSession.GetAdditionalInfo(downloadSession);

      return string.Format("{0} {1}", sessionMainInfo, sessionAdditionalInfo);
    }
    
    #endregion

    #region Логирование

    /// <summary>
    /// Записать в лог полную информацию о содержимом сообщения из сервиса обмена.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    public virtual void LogFullMessage(NpoComputer.DCX.Common.IMessage message)
    {
      this.LogMessage(message);
      this.LogMessagePrimaryDocuments(message);
      this.LogMessageReglamentDocuments(message);
      this.LogMessageSignatures(message);
    }
    
    /// <summary>
    /// Записать в лог общую информацию о сообщении из сервиса обмена.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    public virtual void LogMessage(NpoComputer.DCX.Common.IMessage message)
    {
      this.LogDebugFormat(message, "Service message: IsReply: '{0}', IsIncoming: '{1}', Sender: '{2}', Receiver: '{3}', ParentServiceMessageId: '{4}'.",
                          message.IsReply, message.IsIncome, message.Sender == null ? string.Empty : message.Sender.BoxId,
                          message.Receiver == null ? string.Empty : message.Receiver.BoxId, message.ParentServiceMessageId);
      
      var fromDepartment = message.FromDepartment;
      if (fromDepartment == null)
        this.LogDebugFormat(message, "Service message: property FromDepartment is null.");
      else
        this.LogDebugFormat(message, "Service message: FromDepartment: Name:  '{0}', Id:  '{1}', Kpp:  '{2}', ParentDepartmentId:  '{3}'.",
                            fromDepartment.Name, fromDepartment.Id, fromDepartment.Kpp, fromDepartment.ParentDepartmentId);
      
      var intoDepartment = message.ToDepartment;
      if (intoDepartment == null)
        this.LogDebugFormat(message, "Service message: property ToDepartment is null.");
      else
        this.LogDebugFormat(message, "Service message: ToDepartment: Name:  '{0}', Id:  '{1}', Kpp:  '{2}', ParentDepartmentId:  '{3}'.",
                            intoDepartment.Name, intoDepartment.Id, intoDepartment.Kpp, intoDepartment.ParentDepartmentId);
      
    }
    
    /// <summary>
    /// Записать в лог информацию о документах сообщения из сервиса обмена.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    public virtual void LogMessagePrimaryDocuments(NpoComputer.DCX.Common.IMessage message)
    {
      foreach (var primaryDocument in message.PrimaryDocuments)
      {
        this.LogDebugFormat(message, primaryDocument, "Primary document: NeedSign: '{0}', SignStatus: '{1}', NeedReceipt: '{2}', RevocationStatus: '{3}', ParentServiceEntityId: '{4}'.",
                            primaryDocument.NeedSign, primaryDocument.SignStatus, primaryDocument.NeedReceipt, primaryDocument.RevocationStatus, primaryDocument.ParentServiceEntityId);
        
        this.LogDebugFormat(message, primaryDocument, "Primary document: NonformalizedKind: '{0}', IsUnknownDocumentType: '{1}', Comment: '{2}', Date: '{3}', IsLegitimate: '{4}', Card: '{5}',  GlobalDocumentId: '{6}'.",
                            primaryDocument.NonformalizedKind, primaryDocument.IsUnknownDocumentType, primaryDocument.Comment, primaryDocument.Date, primaryDocument.IsLegitimate, primaryDocument.Card,
                            primaryDocument.GlobalDocumentId);
        
        if (primaryDocument.DocumentType != DocumentType.Nonformalized)
          this.LogDebugFormat(message, primaryDocument, "Primary document: FileName: '{0}'.", primaryDocument.FileName);
        
        this.LogDebugFormat(message, primaryDocument, "Primary document: BoundDocuments: '{0}'.", string.Join(", ",  primaryDocument.BoundDocuments.Select(x => x.DocumentId).ToList()));
        
        // Метаданные.
        foreach (var item in primaryDocument.Metadata)
        {
          this.LogDebugFormat(message, primaryDocument, "Metadata: Key = '{0}', Value = '{1}'.", item.Key, item.Value);
        }
      }
    }
    
    /// <summary>
    /// Записать в лог информацию о служебных документах сообщения из сервиса.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    public virtual void LogMessageReglamentDocuments(NpoComputer.DCX.Common.IMessage message)
    {
      foreach (var reglamentDocument in message.ReglamentDocuments)
      {
        this.LogDebugFormat(message, reglamentDocument, "Reglament document:  Type: '{0}', FileName: '{1}', DateTime: '{2}'.", reglamentDocument.DocumentType, reglamentDocument.FileName, reglamentDocument.DateTime);
        
        this.LogDebugFormat(message, reglamentDocument, "Reglament document:  Type: '{0}', RootServiceEntityId: '{1}', ParentServiceEntityId: '{2}'.",
                            reglamentDocument.DocumentType, reglamentDocument.RootServiceEntityId, reglamentDocument.ParentServiceEntityId);
      }
    }
    
    /// <summary>
    /// Записать в лог информацию о подписи из сообщения.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    public virtual void LogMessageSignatures(NpoComputer.DCX.Common.IMessage message)
    {
      foreach (var signature in message.Signatures)
      {
        this.LogDebugFormat(message, "Signature:  DocumentId: '{0}', SignerBoxId: '{1}'.", signature.DocumentId, signature.SignerBoxId);
      }
    }
    
    /// <summary>
    /// Получить строку с префиксом Exchange.
    /// </summary>
    /// <param name="text">Сообщение.</param>
    /// <param name="paramsInformation">Строка с параметрами.</param>
    /// <returns>Строка с префиксом Exchange.</returns>
    public virtual string ExchangeLogPattern(string text, string paramsInformation)
    {
      if (string.IsNullOrEmpty(paramsInformation))
        return string.Format("Exchange. {0}", text);
      
      return string.Format("Exchange. {0} {1}", text, paramsInformation);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="text">Сообщение.</param>
    [Public]
    public virtual void LogDebugFormat(string text)
    {
      var format = this.ExchangeLogPattern(text, null);
      Logger.Debug(format);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="documentId">Ид документа.</param>
    /// <param name="versionId">Ид версии.</param>
    /// <param name="text">Сообщение.</param>
    [Public]
    public virtual void LogDebugFormat(int documentId, int versionId, string text)
    {
      var documentInformation = string.Format("DocumentId: '{0}', VersionId: '{1}'.", documentId, versionId);
      var format = this.ExchangeLogPattern(text, documentInformation);
      Logger.Debug(format);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="text">Сообщение.</param>
    [Public]
    public virtual void LogDebugFormat(ExchangeCore.IBoxBase box, string text)
    {
      this.LogDebugFormat(box, text, string.Empty);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="documentInfo">Информация о документе обмена.</param>
    /// <param name="text">Сообщение.</param>
    [Public]
    public virtual void LogDebugFormat(IExchangeDocumentInfo documentInfo, string text)
    {
      this.LogDebugFormat(documentInfo, text, string.Empty);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="queueItem">Элемент очереди конвертации тел документов.</param>
    /// <param name="text">Сообщение.</param>
    [Public]
    public virtual void LogDebugFormat(ExchangeCore.IBodyConverterQueueItem queueItem, string text)
    {
      this.LogDebugFormat(queueItem, text, string.Empty);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="queueItem">Элемент очереди синхронизации контрагентов.</param>
    /// <param name="text">Сообщение.</param>
    [Public]
    public virtual void LogDebugFormat(ExchangeCore.ICounterpartyQueueItem queueItem, string text)
    {
      this.LogDebugFormat(queueItem, text, string.Empty);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="queueItem">Элемент очереди синхронизации сообщений.</param>
    /// <param name="text">Сообщение.</param>
    [Public]
    public virtual void LogDebugFormat(ExchangeCore.IMessageQueueItem queueItem, string text)
    {
      this.LogDebugFormat(queueItem, text, string.Empty);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(ExchangeCore.IBoxBase box, string logFormat, params object[] args)
    {
      var boxInformation = string.Format("Box: DisplayValue: '{0}', Id: '{1}'.", box?.DisplayValue, box?.Id);
      var format = this.ExchangeLogPattern(logFormat, boxInformation);
      Logger.DebugFormat(format, args);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(NpoComputer.DCX.Common.IMessage message, string logFormat, params object[] args)
    {
      var messageInformation = string.Format("ServiceMessageId: '{0}'.", message?.ServiceMessageId);
      var format = this.ExchangeLogPattern(logFormat, messageInformation);
      Logger.DebugFormat(format, args);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    /// <param name="primaryDocument">Документ сообщения.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(NpoComputer.DCX.Common.IMessage message, NpoComputer.DCX.Common.IDocument primaryDocument, string logFormat, params object[] args)
    {
      var primaryDocumentInformation = string.Format("ServiceMessageId: '{0}'. Primary document: Type: '{1}', ServiceEntityId: '{2}'.",
                                                     message?.ServiceMessageId, primaryDocument?.DocumentType, primaryDocument?.ServiceEntityId);
      var format = this.ExchangeLogPattern(logFormat, primaryDocumentInformation);
      Logger.DebugFormat(format, args);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    /// <param name="reglamentDocument">Служебный документ сообщения.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(NpoComputer.DCX.Common.IMessage message, NpoComputer.DCX.Common.IReglamentDocument reglamentDocument, string logFormat, params object[] args)
    {
      var reglamentDocumentInformation = string.Format("ServiceMessageId: '{0}'. Reglament document: Type: '{1}, ServiceEntityId: '{2}'.",
                                                       message?.ServiceMessageId, reglamentDocument?.DocumentType, reglamentDocument?.ServiceEntityId);
      var format = this.ExchangeLogPattern(logFormat, reglamentDocumentInformation);
      Logger.DebugFormat(format, args);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="queueItem">Элемент очереди синхронизации сообщений.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(ExchangeCore.IMessageQueueItem queueItem, string logFormat, params object[] args)
    {
      var queueItemInformation = string.Format("MessageQueueItem: Id: '{0}', ExternalId: '{1}', RootMessageId: '{2}',  IsRootMessage: '{3}', AsyncHandlerId: '{4}', SessionId: '{5}'.",
                                               queueItem?.Id, queueItem?.ExternalId, queueItem?.RootMessageId, queueItem?.IsRootMessage, queueItem?.AsyncHandlerId, queueItem?.DownloadSession?.Id);
      var format = this.ExchangeLogPattern(logFormat, queueItemInformation);
      Logger.DebugFormat(format, args);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    /// <param name="queueItem">Элемент очереди синхронизации сообщений.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(NpoComputer.DCX.Common.IMessage message, IMessageQueueItem queueItem, ExchangeCore.IBoxBase box, string logFormat, params object[] args)
    {
      var paramsInformation = string.Format("ServiceMessageId: '{0}'. ParentServiceMessageId: '{1}'. MessageQueueItem: Id: '{2}', IsRootMessage: '{3}', AsyncHandlerId: '{4}', SessionId: '{5}'. BoxId: '{6}'.",
                                            message?.ServiceMessageId, message?.ParentServiceMessageId, queueItem?.Id, queueItem?.IsRootMessage, queueItem?.AsyncHandlerId, queueItem?.DownloadSession?.Id, box?.Id);
      
      var format = this.ExchangeLogPattern(logFormat, paramsInformation);
      Logger.DebugFormat(format, args);
    }

    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="message">Сообщение из сервиса обмена.</param>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(NpoComputer.DCX.Common.IMessage message, ExchangeCore.IBoxBase box, string logFormat, params object[] args)
    {
      var paramsInformation = string.Format("ServiceMessageId: '{0}'. BoxId: '{1}'.",
                                            message?.ServiceMessageId, box?.Id);
      
      var format = this.ExchangeLogPattern(logFormat, paramsInformation);
      Logger.DebugFormat(format, args);
    }

    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="documentInfo">Информация о документе обмена.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(IExchangeDocumentInfo documentInfo, string logFormat, params object[] args)
    {
      var serviceMessageId = documentInfo?.ServiceMessageId;
      var serviceDocumentId = documentInfo?.ServiceDocumentId;
      var exchangeDocumentInfoId = documentInfo?.Id;
      var documentId = documentInfo?.Document?.Id;
      
      var paramsInformation = string.Format("ExchangeDocumentInfo: Id: '{0}', ServiceMessageId: '{1}', ServiceDocumentId: '{2}', DocumentId: '{3}'.",
                                            exchangeDocumentInfoId, serviceMessageId, serviceDocumentId, documentId);

      var format = this.ExchangeLogPattern(logFormat, paramsInformation);
      
      Logger.DebugFormat(format, args);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="queueItem">Элемент очереди конвертации тел документов.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(ExchangeCore.IBodyConverterQueueItem queueItem, string logFormat, params object[] args)
    {
      var queueItemInformation = string.Format("BodyConverterQueueItem: Id: '{0}', DocumentId: '{1}'.", queueItem?.Id, queueItem?.Document?.Id);
      var format = this.ExchangeLogPattern(logFormat, queueItemInformation);
      Logger.DebugFormat(format, args);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="queueItem">Элемент очереди синхронизации контрагентов.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(ExchangeCore.ICounterpartyQueueItem queueItem, string logFormat, params object[] args)
    {
      var queueItemInformation = string.Format("CounterpartyQueueItem: Id: '{0}', ExternalId: '{1}', RootBoxId: '{2}'.", queueItem?.Id, queueItem?.ExternalId, queueItem?.RootBox?.Id);
      var format = this.ExchangeLogPattern(logFormat, queueItemInformation);
      Logger.DebugFormat(format, args);
    }
    
    /// <summary>
    /// Записать сообщение в лог.
    /// </summary>
    /// <param name="documentInfo">Информация о документе обмена.</param>
    /// <param name="reglamentDocuments">Служебные документы сообщения.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogDebugFormat(IExchangeDocumentInfo documentInfo, List<NpoComputer.DCX.Common.IReglamentDocument> reglamentDocuments, string logFormat, params object[] args)
    {
      foreach (var reglamentDocument in reglamentDocuments)
      {
        var serviceMessageId = documentInfo?.ServiceMessageId;
        var serviceDocumentId = documentInfo?.ServiceDocumentId;
        var exchangeDocumentInfoId = documentInfo?.Id;
        var documentId = documentInfo?.Document?.Id;
        
        var paramsInformation = string.Format("ExchangeDocumentInfo: Id: '{0}', ServiceMessageId: '{1}', ServiceDocumentId: '{2}', DocumentId: '{3}'. " +
                                              "Reglament document:  DocumentType: '{4}', RootServiceEntityId: '{5}', ParentServiceEntityId: '{6}'.",
                                              exchangeDocumentInfoId, serviceMessageId, serviceDocumentId, documentId,
                                              reglamentDocument.DocumentType, reglamentDocument.RootServiceEntityId, reglamentDocument.ParentServiceEntityId);

        var format = this.ExchangeLogPattern(logFormat, paramsInformation);
        Logger.DebugFormat(format, args);
      }
    }
    
    /// <summary>
    /// Записать сообщение об ошибке в лог.
    /// </summary>
    /// <param name="text">Сообщение.</param>
    [Public]
    public virtual void LogErrorFormat(string text)
    {
      var format = this.ExchangeLogPattern(text, null);
      Logger.Error(format);
    }
    
    /// <summary>
    /// Записать сообщение об ошибке в лог.
    /// </summary>
    /// <param name="text">Сообщение.</param>
    /// <param name="ex">Исключение.</param>
    [Public]
    public virtual void LogErrorFormat(string text, System.Exception ex)
    {
      var format = this.ExchangeLogPattern(text, null);
      Logger.Error(format, ex);
    }
    
    /// <summary>
    /// Записать сообщение об ошибке в лог.
    /// </summary>
    /// <param name="documentId">Ид документа.</param>
    /// <param name="versionId">Ид версии.</param>
    /// <param name="text">Сообщение.</param>
    /// <param name="ex">Исключение.</param>
    [Public]
    public virtual void LogErrorFormat(int documentId, int versionId, string text, System.Exception ex)
    {
      var documentInformation = string.Format("DocumentId: '{0}', VersionId: '{1}'.", documentId, versionId);
      var format = this.ExchangeLogPattern(text, documentInformation);
      Logger.Error(format, ex);
    }
    
    /// <summary>
    ///  Записать сообщение об ошибке в лог.
    /// </summary>
    /// <param name="box">Абонентский ящик.</param>
    /// <param name="logFormat">Формат строки.</param>
    /// <param name="args">Аргументы.</param>
    public virtual void LogErrorFormat(ExchangeCore.IBoxBase box, string logFormat, params object[] args)
    {
      var paramsInformation = string.Format("BoxId: '{0}'.", box?.Id);
      
      var format = this.ExchangeLogPattern(logFormat, paramsInformation);
      Logger.ErrorFormat(format, args);
    }

    /// <summary>
    /// Записать сообщение об ошибке в лог.
    /// </summary>
    /// <param name="queueItem">Элемент очереди синхронизации сообщений.</param>
    /// <param name="text">Сообщение.</param>
    /// <param name="ex">Исключение.</param>
    public virtual void LogErrorFormat(ExchangeCore.IMessageQueueItem queueItem, string text, System.Exception ex)
    {
      var queueItemInformation = string.Format("MessageQueueItem: Id: '{0}', ExternalId: '{1}', RootMessageId: '{2}', IsRootMessage: '{3}', AsyncHandlerId: '{4}', SessionId: '{5}'.",
                                               queueItem?.Id, queueItem?.ExternalId, queueItem?.RootMessageId, queueItem?.IsRootMessage, queueItem?.AsyncHandlerId, queueItem?.DownloadSession?.Id);
      var format = this.ExchangeLogPattern(text, queueItemInformation);
      Logger.Error(format, ex);
    }
    
    #endregion
  }
}