ModuleClientFunctions.cs 118 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CommonLibrary;
using Sungero.Company;
using Sungero.Content;
using Sungero.Core;
using Sungero.CoreEntities;
using Sungero.Domain.Client;
using Sungero.Reporting;
using Sungero.Workflow;

namespace Sungero.Docflow.Client
{
  public class ModuleFunctions
  {
    #region Замещение
    
    /// <summary>
    /// Имеет ли доступ по замещению.
    /// </summary>
    /// <param name="e">Аргументы карточки.</param>
    /// <param name="registrationGroup">Группа регистрации.</param>
    /// <param name="calculateIsSubstitute">Признак замещения.</param>
    /// <param name="calculateIsAdministrator">Признак администратора.</param>
    /// <param name="calculateIsUsed">Признак использования.</param>
    /// <param name="calculateHasDocuments">Признак наличия зарегистрированных документов.</param>
    /// <param name="documentRegister">Журнал.</param>
    /// <returns>True, если доступ имеется.</returns>
    public static bool CalculateParams(Sungero.Presentation.FormRefreshEventArgs e, IRegistrationGroup registrationGroup,
                                       bool calculateIsSubstitute, bool calculateIsAdministrator, bool calculateIsUsed, bool calculateHasDocuments,
                                       IDocumentRegister documentRegister)
    {
      var isSubstituteParamName = Constants.Module.IsSubstituteResponsibleEmployeeParamName;
      var isAdministratorParamName = Constants.Module.IsAdministratorParamName;
      var isUsedParamName = Constants.Module.IsUsedParamName;
      var hasDocumentsParamName = Constants.Module.HasRegisteredDocumentsParamName;
      bool isSubstituteParamValue;
      bool isAdministratorParamValue;
      var isSubstituteParamHasValue = e.Params.TryGetValue(isSubstituteParamName, out isSubstituteParamValue);
      var isAdministratorParamHasValue = e.Params.TryGetValue(isAdministratorParamName, out isAdministratorParamValue);

      // Получить старое значение параметра.
      if (calculateIsSubstitute && isSubstituteParamHasValue &&
          calculateIsAdministrator && isAdministratorParamHasValue)
        return isSubstituteParamValue || isAdministratorParamValue;
      
      if (calculateIsSubstitute && isSubstituteParamHasValue)
        return isSubstituteParamValue;
      
      if (calculateIsAdministrator && isAdministratorParamHasValue)
        return isAdministratorParamValue;
      
      bool isUsedParamValue;
      if (calculateIsUsed && e.Params.TryGetValue(isUsedParamName, out isUsedParamValue))
        return isUsedParamValue;
      
      bool hasDocumentsParamValue;
      if (calculateHasDocuments && e.Params.TryGetValue(hasDocumentsParamName, out hasDocumentsParamValue))
        return hasDocumentsParamValue;
      
      // Вычислить доступность на сервере, чтобы был один запрос.
      var result = Functions.Module.Remote.CalculateParams(registrationGroup, documentRegister);
      var access = Functions.Module.UnboxDictionary(result);
      var isSubstitute = access[isSubstituteParamName];
      var isAdministrator = access[isAdministratorParamName];
      var isUsed = access[isUsedParamName];
      var hasDocuments = access[hasDocumentsParamName];
      e.Params.AddOrUpdate(isSubstituteParamName, isSubstitute);
      e.Params.AddOrUpdate(isAdministratorParamName, isAdministrator);
      e.Params.AddOrUpdate(isUsedParamName, isUsed);
      e.Params.AddOrUpdate(hasDocumentsParamName, hasDocuments);
      
      if (calculateIsSubstitute && calculateIsAdministrator)
        return isSubstitute || isAdministrator;
      
      if (calculateIsSubstitute)
        return isSubstitute;
      
      if (calculateIsAdministrator)
        return isAdministrator;
      
      if (calculateIsUsed)
        return isUsed;
      
      if (calculateHasDocuments)
        return hasDocuments;
      
      return false;
    }
    
    /// <summary>
    /// Имеет ли доступ по замещению.
    /// </summary>
    /// <param name="e">Аргумент доступности.</param>
    /// <param name="documentRegister">Журнал.</param>
    /// <param name="calculateIsAdministrator">Признак администратора.</param>
    /// <returns>True, если доступ имеется.</returns>
    public static bool CalculateParams(Sungero.Domain.Client.CanExecuteActionArgs e, IDocumentRegister documentRegister, bool calculateIsAdministrator)
    {
      var isSubstituteParamName = Constants.Module.IsSubstituteResponsibleEmployeeParamName;
      var isAdministratorParamName = Constants.Module.IsAdministratorParamName;
      var isUsedParamName = Constants.Module.IsUsedParamName;
      var hasDocumentsParamName = Constants.Module.HasRegisteredDocumentsParamName;
      
      // Получить старое значение параметра.
      bool isSubstituteParamValue;
      bool isAdministratorParamValue;
      var isSubstituteParamHasValue = e.Params.TryGetValue(isSubstituteParamName, out isSubstituteParamValue);
      var isAdministratorParamHasValue = e.Params.TryGetValue(isAdministratorParamName, out isAdministratorParamValue);
      if (isSubstituteParamHasValue &&
          calculateIsAdministrator && isAdministratorParamHasValue)
        return isSubstituteParamValue || isAdministratorParamValue;
      
      // Вычислить доступность на сервере, чтобы был один запрос.
      var result = Functions.Module.Remote.CalculateParams(documentRegister.RegistrationGroup, documentRegister);
      var access = Functions.Module.UnboxDictionary(result);
      var isSubstitute = access[isSubstituteParamName];
      var isAdministrator = access[isAdministratorParamName];
      var isUsed = access[isUsedParamName];
      var hasDocuments = access[hasDocumentsParamName];
      e.Params.AddOrUpdate(isSubstituteParamName, isSubstitute);
      e.Params.AddOrUpdate(isAdministratorParamName, isAdministrator);
      e.Params.AddOrUpdate(isUsedParamName, isUsed);
      e.Params.AddOrUpdate(hasDocumentsParamName, hasDocuments);
      
      if (calculateIsAdministrator)
        return isSubstitute || isAdministrator;
      
      return isSubstitute;
    }
    
    #endregion
    
    #region Диалог выдачи прав на вложения ShowDialogGrantAccessRightsFromTask и ShowDialogGrantAccessRightsFromAssignment
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения.
    /// </summary>
    /// <param name="assignment">Задание.</param>
    /// <param name="attachments">Вложения.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool? ShowDialogGrantAccessRights(IAssignmentBase assignment,
                                                    List<Domain.Shared.IEntity> attachments)
    {
      if (!attachments.Any() || assignment == null)
        return null;
      
      return ShowDialogGrantAccessRights(assignment.Task, attachments, new List<IRecipient>());
    }
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения для определенного действия.
    /// </summary>
    /// <param name="assignment">Задание.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="action">Действие, текст утверждения которого будет показан.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool ShowDialogGrantAccessRightsWithConfirmationDialog(IAssignmentBase assignment,
                                                                         List<Domain.Shared.IEntity> attachments,
                                                                         Domain.Shared.IActionInfo action)
    {
      return ShowDialogGrantAccessRightsWithConfirmationDialog(assignment.Task, attachments, new List<IRecipient>(), action);
    }
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения для определенного действия.
    /// </summary>
    /// <param name="assignment">Задание.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="action">Действие, текст утверждения которого будет показан.</param>
    /// <param name="dialogID">ИД диалога подтверждения.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool ShowDialogGrantAccessRightsWithConfirmationDialog(IAssignmentBase assignment,
                                                                         List<Domain.Shared.IEntity> attachments,
                                                                         Domain.Shared.IActionInfo action,
                                                                         string dialogID)
    {
      return ShowDialogGrantAccessRightsWithConfirmationDialog(assignment.Task, attachments, new List<IRecipient>(), action, dialogID);
    }
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения для соисполнителей.
    /// </summary>
    /// <param name="assignment">Задание.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="additionalAssignees">Список соисполнителей.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool? ShowDialogGrantAccessRights(IAssignmentBase assignment,
                                                    List<Domain.Shared.IEntity> attachments,
                                                    List<IRecipient> additionalAssignees)
    {
      if (!attachments.Any() || assignment == null)
        return null;
      
      return ShowDialogGrantAccessRights(assignment.Task, attachments, additionalAssignees);
    }
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения на определенное действие для соисполнителей.
    /// </summary>
    /// <param name="assignment">Задание.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="additionalAssignees">Соисполнители.</param>
    /// <param name="action">Действие, текст утверждения которого будет показан.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool ShowDialogGrantAccessRightsWithConfirmationDialog(IAssignmentBase assignment,
                                                                         List<Domain.Shared.IEntity> attachments,
                                                                         List<IRecipient> additionalAssignees,
                                                                         Domain.Shared.IActionInfo action)
    {
      return ShowDialogGrantAccessRightsWithConfirmationDialog(assignment.Task, attachments, additionalAssignees, action);
    }
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения на определенное действие для соисполнителей.
    /// </summary>
    /// <param name="assignment">Задание.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="additionalAssignees">Соисполнители.</param>
    /// <param name="action">Действие, текст утверждения которого будет показан.</param>
    /// <param name="dialogID">ИД диалога подтверждения.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool ShowDialogGrantAccessRightsWithConfirmationDialog(IAssignmentBase assignment,
                                                                         List<Domain.Shared.IEntity> attachments,
                                                                         List<IRecipient> additionalAssignees,
                                                                         Domain.Shared.IActionInfo action,
                                                                         string dialogID)
    {
      return ShowDialogGrantAccessRightsWithConfirmationDialog(assignment.Task,
                                                               attachments,
                                                               additionalAssignees,
                                                               action,
                                                               dialogID);
    }
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения.
    /// </summary>
    /// <param name="task">Задача.</param>
    /// <param name="attachments">Вложения.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool? ShowDialogGrantAccessRights(ITask task, List<Domain.Shared.IEntity> attachments)
    {
      return ShowDialogGrantAccessRights(task, attachments, new List<IRecipient>());
    }
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения для определенного действия.
    /// </summary>
    /// <param name="task">Задача.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="action">Действие, текст утверждения которого будет показан.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool ShowDialogGrantAccessRightsWithConfirmationDialog(ITask task,
                                                                         List<Domain.Shared.IEntity> attachments,
                                                                         Domain.Shared.IActionInfo action)
    {
      return ShowDialogGrantAccessRightsWithConfirmationDialog(task, attachments, null, action);
    }
    
    /// <summary>
    /// Создать диалог выдачи прав на вложения для определенного действия.
    /// </summary>
    /// <param name="task">Задача.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="action">Действие, текст утверждения которого будет показан.</param>
    /// <param name="dialogID">ИД диалога подтверждения.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool ShowDialogGrantAccessRightsWithConfirmationDialog(ITask task,
                                                                         List<Domain.Shared.IEntity> attachments,
                                                                         Domain.Shared.IActionInfo action,
                                                                         string dialogID)
    {
      return ShowDialogGrantAccessRightsWithConfirmationDialog(task, attachments, null, action, dialogID);
    }
    
    /// <summary>
    /// Показать диалог выдачи прав на вложения с запросом подтверждения.
    /// </summary>
    /// <param name="task">Задача.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="additionalAssignees">Дополнительные согласующие.</param>
    /// <param name="action">Действие, текст утверждения которого будет показан.</param>
    /// <param name="dialogID">ИД диалога подтверждения.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.</returns>
    [Public]
    public static bool ShowDialogGrantAccessRightsWithConfirmationDialog(ITask task,
                                                                         List<Domain.Shared.IEntity> attachments,
                                                                         List<IRecipient> additionalAssignees,
                                                                         Domain.Shared.IActionInfo action,
                                                                         string dialogID = "")
    {
      var giveRights = ShowDialogGrantAccessRights(task, attachments, additionalAssignees);
      
      // Если явно не нажата отмена, то либо доп. прав не нужно (диалога не было), либо права назначены через диалог.
      if (action == null)
        return giveRights != false;
      
      // Замена стандартного диалога подтверждения выполнения действия.
      if (giveRights == null)
        return ShowConfirmationDialog(action.ConfirmationMessage, null, null, dialogID);
      
      return giveRights.Value;
    }
    
    /// <summary>
    /// Показать диалог выдачи прав на вложения.
    /// </summary>
    /// <param name="task">Задача.</param>
    /// <param name="attachments">Вложения.</param>
    /// <param name="additionalAssignees">Дополнительные согласующие.</param>
    /// <returns>True, если был показан диалог (и не была нажата отмена).
    /// False, если была нажата отмена.
    /// Null, если диалог показан не был.</returns>
    [Public]
    public static bool? ShowDialogGrantAccessRights(ITask task,
                                                    List<Domain.Shared.IEntity> attachments,
                                                    List<IRecipient> additionalAssignees)
    {
      if (!attachments.Any() || task == null)
        return null;
      
      var participants = Functions.Module.Remote.GetTaskAssignees(task).ToList();
      if (!participants.Any())
        return null;
      
      if (additionalAssignees != null && additionalAssignees.Any())
        participants.AddRange(additionalAssignees);

      // Получаем только вложения, принадлежащие текущему заданию.
      // На остальные вложения проверять права не надо, т.к. скорее всего их добавил не текущий пользователь.
      var attachmentsWithoutAccessRights = Functions.Module.Remote.GetAttachmentsWithoutAccessRights(participants, attachments);
      if (attachmentsWithoutAccessRights.Any())
      {
        return Workflow.Client.ModuleFunctions.ShowDialogGrantAccessRights(participants, attachmentsWithoutAccessRights);
      }
      
      return null;
    }

    #endregion
    
    #region Вызов функций делопроизводства без явных зависимостей
    
    // Вызов remote функций в таком виде позволяет отказаться от зависимостей, оставив при этом работоспособность.
    
    /// <summary>
    /// Создать сопроводительное письмо.
    /// </summary>
    /// <param name="document">Документ, к которому создается сопроводительное письмо.</param>
    /// <returns>Письмо.</returns>
    [Public]
    public static IOfficialDocument CreateCoverLetter(IOfficialDocument document)
    {
      var letter = RecordManagement.PublicFunctions.OutgoingLetter.Remote.CreateCoverLetter(document);
      
      // Указать связь документов.
      letter.Relations.AddFrom(Constants.Module.CorrespondenceRelationName, document);
      return letter;
    }
    
    /// <summary>
    /// Создать поручение.
    /// </summary>
    /// <param name="document">Документ, по которому создается поручение.</param>
    /// <returns>Поручение.</returns>
    [Public]
    public virtual ITask CreateActionItemExecution(IOfficialDocument document)
    {
      return RecordManagement.PublicFunctions.Module.Remote.CreateActionItemExecution(document);
    }
    
    /// <summary>
    /// Создать поручение.
    /// </summary>
    /// <param name="document">Документ, по которому создается поручение.</param>
    /// <param name="parentAssignmentId">Id задания, от которого создается поручение.</param>
    /// <returns>Поручение.</returns>
    public virtual ITask CreateActionItemExecution(IOfficialDocument document, int parentAssignmentId)
    {
      return RecordManagement.PublicFunctions.Module.Remote.CreateActionItemExecution(document, parentAssignmentId);
    }
    
    /// <summary>
    /// Создать поручение.
    /// </summary>
    /// <param name="document">Документ, по которому создается поручение.</param>
    /// <param name="parentAssignmentId">Id задания, от которого создается поручение.</param>
    /// <param name="resolution">Текст резолюции.</param>
    /// <param name="assignedBy">Пользователь - автор резолюции.</param>
    /// <returns>Поручение.</returns>
    public virtual ITask CreateActionItemExecutionWithResolution(IOfficialDocument document, int parentAssignmentId, string resolution, Sungero.Company.IEmployee assignedBy)
    {
      return RecordManagement.PublicFunctions.Module.Remote.CreateActionItemExecutionWithResolution(document, parentAssignmentId, resolution, assignedBy);
    }
    
    /// <summary>
    /// Создать задачу на рассмотрение документа.
    /// </summary>
    /// <param name="document">Входящий документ.</param>
    /// <returns>Рассмотрение.</returns>
    public static ITask CreateDocumentReview(IOfficialDocument document)
    {
      return RecordManagement.PublicFunctions.Module.Remote.CreateDocumentReview(document);
    }
    
    #endregion
    
    #region Интеллектуальная обработка
    
    /// <summary>
    /// Показать настройки интеллектуальной обработки документов.
    /// </summary>
    public virtual void ShowSmartProcessingSettings()
    {
      var smartProcessingSettings = PublicFunctions.SmartProcessingSetting.GetSettings();
      smartProcessingSettings.Show();
    }
    
    /// <summary>
    /// Удалить параметр NeedValidateRegisterFormat.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="e">Аргумент действия.</param>
    public static void RemoveNeedValidateRegisterFormatParameter(IOfficialDocument document,
                                                                 Sungero.Domain.Client.ExecuteActionArgs e)
    {
      // Если документ в процессе верификации, то игнорировать изменение полей регистрационных данных.
      if (document.VerificationState == OfficialDocument.VerificationState.InProcess)
        e.Params.Remove(Constants.OfficialDocument.NeedValidateRegisterFormat);
    }
    
    #endregion
    
    #region Проверка параметров диалогов
    
    /// <summary>
    /// Проверить даты диалога отчета.
    /// </summary>
    /// <param name="args">Аргументы события нажатия на кнопку диалога.</param>
    /// <param name="dialogPeriodBegin">Параметр даты начала.</param>
    /// <param name="dialogPeriodEnd">Параметр даты конца.</param>
    [Public]
    public static void CheckReportDialogPeriod(CommonLibrary.InputDialogButtonClickEventArgs args,
                                               CommonLibrary.IDateDialogValue dialogPeriodBegin,
                                               CommonLibrary.IDateDialogValue dialogPeriodEnd)
    {
      var periodBegin = dialogPeriodBegin.Value;
      var periodEnd = dialogPeriodEnd.Value;
      
      CheckDialogPeriod(args, dialogPeriodBegin, dialogPeriodEnd, Sungero.Docflow.Resources.WrongPeriodReport);
      
      // Проверить даты на наличие календаря рабочего времени.
      var periodBeginNoCalendarError = Sungero.Docflow.PublicFunctions.Module.CheckDateByWorkCalendar(periodBegin);
      if (periodBegin.HasValue && !string.IsNullOrWhiteSpace(periodBeginNoCalendarError))
        args.AddError(periodBeginNoCalendarError, dialogPeriodBegin);
      
      var periodEndNoCalendarError = Sungero.Docflow.PublicFunctions.Module.CheckDateByWorkCalendar(periodEnd);
      if (periodEnd.HasValue && !string.IsNullOrWhiteSpace(periodEndNoCalendarError))
        args.AddError(periodEndNoCalendarError, dialogPeriodEnd);
    }
    
    /// <summary>
    /// Проверить даты диалога.
    /// </summary>
    /// <param name="args">Аргументы события нажатия на кнопку диалога.</param>
    /// <param name="dialogPeriodBegin">Параметр даты начала.</param>
    /// <param name="dialogPeriodEnd">Параметр даты конца.</param>
    [Public]
    public static void CheckDialogPeriod(CommonLibrary.InputDialogButtonClickEventArgs args,
                                         CommonLibrary.IDateDialogValue dialogPeriodBegin,
                                         CommonLibrary.IDateDialogValue dialogPeriodEnd)
    {
      CheckDialogPeriod(args, dialogPeriodBegin, dialogPeriodEnd, Sungero.Docflow.Resources.WrongPeriod);
    }
    
    /// <summary>
    /// Проверить даты диалога.
    /// </summary>
    /// <param name="args">Аргументы события нажатия на кнопку диалога.</param>
    /// <param name="dialogPeriodBegin">Параметр даты начала.</param>
    /// <param name="dialogPeriodEnd">Параметр даты конца.</param>
    /// <param name="wrongPeriodError">Текст ошибки о неверной дате.</param>
    private static void CheckDialogPeriod(CommonLibrary.InputDialogButtonClickEventArgs args,
                                          CommonLibrary.IDateDialogValue dialogPeriodBegin,
                                          CommonLibrary.IDateDialogValue dialogPeriodEnd,
                                          CommonLibrary.LocalizedString wrongPeriodError)
    {
      var periodBegin = dialogPeriodBegin.Value;
      var periodEnd = dialogPeriodEnd.Value;
      
      if (periodBegin.HasValue && periodEnd.HasValue &&
          periodEnd.Value < periodBegin.Value)
      {
        // Выделить оба поля в диалоге с одним текстом ошибки. Ошибки с одинаковыми текстами схлапываются в одну.
        args.AddError(wrongPeriodError, dialogPeriodBegin);
        args.AddError(wrongPeriodError, dialogPeriodEnd);
      }
    }
    
    /// <summary>
    /// Валидация даты по рабочему календарю.
    /// </summary>
    /// <param name="date">Дата.</param>
    /// <returns>Сообщения валидации, пустая строка при их отсутствии.</returns>
    [Public]
    public static string CheckDateByWorkCalendar(DateTime? date)
    {
      if (date == null)
        return string.Empty;
      
      if (!WorkingTime.GetAllCachedByYear(date.Value.Year).Any(c => c.Year == date.Value.Year))
        return Docflow.Resources.EmptyWorkingCalendarFormat(date.Value.Year);
      
      return string.Empty;
    }
    
    #endregion
    
    /// <summary>
    /// Валидация срока по рабочему календарю.
    /// </summary>
    /// <param name="deadline">Срок.</param>
    /// <returns>Сообщения валидации, пустая строка при их отсутствии.</returns>
    [Public]
    public static string CheckDeadlineByWorkCalendar(DateTime? deadline)
    {
      return CheckDeadlineByWorkCalendar(Users.Current, deadline);
    }
    
    /// <summary>
    /// Валидация срока по рабочему календарю конкретного пользователя.
    /// </summary>
    /// <param name="user">Пользователь.</param>
    /// <param name="deadline">Срок.</param>
    /// <returns>Сообщения валидации, пустая строка при их отсутствии.</returns>
    [Public]
    public static string CheckDeadlineByWorkCalendar(IUser user, DateTime? deadline)
    {
      if (deadline == null)
        return string.Empty;
      
      var checkDateError = CheckDateByWorkCalendar(deadline);
      if (!string.IsNullOrWhiteSpace(checkDateError))
        return checkDateError;
      
      // Срок задания дб рабочим днем.
      if (!deadline.Value.IsWorkingDay(user))
        return Docflow.Resources.ImpossibleSpecifyDeadlineToNotWorkingDay;
      
      // Срок задания дб рабочим временем.
      if (deadline.Value.HasTime() && !deadline.Value.IsWorkingTime(user))
        return Docflow.Resources.ImpossibleSpecifyDeadlineToNotWorkingTime;
      
      return string.Empty;
    }
    
    /// <summary>
    /// Создать задачу на ознакомление.
    /// </summary>
    /// <param name="document">Документ, который отправляется на ознакомление.</param>
    /// <returns>Задача на ознакомление.</returns>
    [Public]
    public static ITask CreateAcquaintanceTask(IOfficialDocument document)
    {
      return RecordManagement.PublicFunctions.Module.Remote.CreateAcquaintanceTask(document);
    }
    
    /// <summary>
    /// Показать диалог подтверждения выполнения без создания поручений.
    /// </summary>
    /// <param name="assignment">Задание, которое выполняется.</param>
    /// <param name="document">Документ.</param>
    /// <param name="e">Аргументы.</param>
    /// <returns>True, если диалог был, иначе false.</returns>
    public static bool ShowConfirmationDialogCreationActionItem(IAssignment assignment, IOfficialDocument document, Sungero.Workflow.Client.ExecuteResultActionArgs e)
    {
      var documentApprovalTask = ApprovalTasks.As(assignment.Task);
      var hasSubActionItem = Functions.Module.HasSubActionItems(assignment.Task, Workflow.Task.Status.InProcess);
      if (hasSubActionItem)
        return false;

      var dialogText = Resources.ExecuteWithoutCreatingActionItem;
      var dialog = Dialogs.CreateTaskDialog(dialogText, MessageType.Question);
      dialog.Buttons.AddYes();
      dialog.Buttons.Default = DialogButtons.Yes;
      var createActionItemButton = dialog.Buttons.AddCustom(Resources.CreateActionItem);
      dialog.Buttons.AddNo();
      
      var result = dialog.Show();
      if (result == DialogButtons.Yes)
        return true;
      
      if (result == DialogButtons.No || result == DialogButtons.Cancel)
        e.Cancel();
      
      var stages = Functions.ApprovalRuleBase.Remote.GetStages(documentApprovalTask.ApprovalRule, document, documentApprovalTask).Stages;
      var assignedBy = Sungero.Company.Employees.Null;
      
      // Автором резолюции вычислить адресата, либо подписывающего.
      if (stages.Any(s => s.StageType == Docflow.ApprovalRuleBaseStages.StageType.Review))
        assignedBy = documentApprovalTask.Addressee;
      else if (stages.Any(s => s.StageType == Docflow.ApprovalRuleBaseStages.StageType.Sign))
        assignedBy = documentApprovalTask.Signatory;
      
      var isExecutionAssignment = ApprovalExecutionAssignments.Is(assignment);
      var resolution = assignment.ActiveText;
      if (isExecutionAssignment)
        resolution = ApprovalExecutionAssignments.As(assignment).ResolutionText;
      
      assignment.Save();
      
      var actionItem = RecordManagement.ActionItemExecutionTasks.As(Functions.Module.CreateActionItemExecutionWithResolution(document, assignment.Id, resolution, assignedBy));
      
      if (actionItem != null)
      {
        actionItem.WaitForParentAssignment = true;
        actionItem.ShowModal();
      }

      hasSubActionItem = Functions.Module.HasSubActionItems(assignment.Task, Workflow.Task.Status.InProcess);
      if (hasSubActionItem)
        return true;
      
      var hasDraftSubActionItem = Functions.Module.HasSubActionItems(assignment.Task, Workflow.Task.Status.Draft);
      e.AddError(hasDraftSubActionItem ? Resources.AllCreatedActionItemsShouldBeStarted : Resources.CreatedActionItemExecutionNeeded);
      e.Cancel();
      return true;
    }
    
    /// <summary>
    /// Показать диалог подтверждения выполнения без отправки документа.
    /// </summary>
    /// <param name="assignment">Задание, которое выполняется.</param>
    /// <param name="collapsed">Схлопнутые типы заданий.</param>
    /// <param name="e">Аргументы.</param>
    /// <returns>True, если диалог был, иначе false.</returns>
    public static bool ShowConfirmationDialogSendToCounterparty(IAssignment assignment, System.Collections.Generic.IEnumerable<Enumeration?> collapsed,
                                                                Sungero.Workflow.Client.ExecuteResultActionArgs e)
    {
      var task = ApprovalTasks.As(assignment.Task);
      var document = task.DocumentGroup.OfficialDocuments.FirstOrDefault();
      
      var canSend = Functions.ApprovalSendingAssignment.CanSendToCounterparty(document);
      if (!canSend ||
          task.DeliveryMethod == null ||
          task.DeliveryMethod.Sid != Constants.MailDeliveryMethod.Exchange ||
          (collapsed != null && !collapsed.Any(c => c == ApprovalPrintingAssignmentCollapsedStagesTypesPr.StageType.Sending)) ||
          Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.LastVersionSended(document))
        return false;
      
      var dialog = Dialogs.CreateTaskDialog(Resources.ExecuteWithoutSendToCounterparty, MessageType.Warning);
      dialog.Buttons.AddYes();
      dialog.Buttons.Default = DialogButtons.Yes;
      var send = dialog.Buttons.AddCustom(ApprovalSendingAssignments.Info.Actions.SendViaExchangeService.LocalizedName);
      dialog.Buttons.AddNo();
      
      var result = dialog.Show();
      if (result == DialogButtons.Yes)
        return true;
      
      if (result == DialogButtons.No || result == DialogButtons.Cancel)
        e.Cancel();
      
      // Открываем диалог отправки.
      Functions.ApprovalSendingAssignment.SendToCounterparty(document, task);
      
      // Если отправка так и не была выполнена - отменяем выполнение.
      if (!Exchange.PublicFunctions.ExchangeDocumentInfo.Remote.LastVersionSended(document))
        e.Cancel();
      
      return true;
    }
    
    /// <summary>
    /// Показать диалог подтверждения выполнения.
    /// </summary>
    /// <param name="text">Текст.</param>
    /// <param name="description">Дополнительный текст.</param>
    /// <param name="title">Заголовок.</param>
    /// <param name="dialogID">ИД диалога подтверждения.</param>
    /// <returns>True, если запрос был подтвержден.</returns>
    /// <remarks>При указании dialogID в диалоге появляется флажок "Больше не спрашивать".</remarks>
    [Public]
    public static bool ShowConfirmationDialog(string text, string description, string title, string dialogID)
    {
      var confirmationDialog = Dialogs.CreateConfirmDialog(text, description, title);
      
      if (!string.IsNullOrWhiteSpace(dialogID))
        confirmationDialog.WithDontAskAgain(dialogID);
      return confirmationDialog.Show();
    }
    
    /// <summary>
    /// Проверка заблокированности сущности другими пользователями.
    /// </summary>
    /// <param name="entity">Сущность.</param>
    /// <returns>True, если сущность заблокирована.
    /// False, если сущность не заблокирована (или заблокирована пользователем, который выполняет действие).</returns>
    [Public]
    public static bool IsLockedByOther(Domain.Shared.IEntity entity)
    {
      var lockInfo = entity != null ? Locks.GetLockInfo(entity) : null;
      return lockInfo != null && lockInfo.IsLockedByOther;
    }
    
    /// <summary>
    /// Проверка заблокированности сущности текущим клиентом.
    /// </summary>
    /// <param name="entity">Сущность.</param>
    /// <returns>True, если сущность заблокирована.</returns>
    [Public]
    public static bool IsLockedByMe(Domain.Shared.IEntity entity)
    {
      var lockInfo = entity != null ? Locks.GetLockInfo(entity) : null;
      return lockInfo != null && lockInfo.IsLockedByMe;
    }
    
    /// <summary>
    /// Проверка заблокированности сущности.
    /// </summary>
    /// <param name="entity">Сущность.</param>
    /// <returns>True, если сущность заблокирована.</returns>
    [Public]
    public static bool IsLocked(Domain.Shared.IEntity entity)
    {
      var lockInfo = entity != null ? Locks.GetLockInfo(entity) : null;
      return lockInfo != null && lockInfo.IsLocked;
    }
    
    /// <summary>
    /// Проверка заблокированности сущности, с добавлением ошибки, если сущность заблокирована.
    /// </summary>
    /// <param name="entity">Сущность.</param>
    /// <param name="e">Аргументы события, в котором проверяется доступность сущности.</param>
    /// <returns>True, если сущность заблокирована.
    /// False, если сущность не заблокирована (или заблокирована пользователем, который выполняет действие).</returns>
    public static bool IsLockedByOther(Domain.Shared.IEntity entity, Domain.Client.ExecuteActionArgs e)
    {
      var lockInfo = entity != null ? Locks.GetLockInfo(entity) : null;
      var isLockedByOther = lockInfo != null && lockInfo.IsLockedByOther;
      
      if (isLockedByOther)
        e.AddError(lockInfo.LockedMessage);
      
      e.ClearMessageAfterAction = true;
      return isLockedByOther;
    }
    
    /// <summary>
    /// Проверка заблокированности любой версии.
    /// </summary>
    /// <param name="versions">Список версий документа.</param>
    /// <returns>True, если заблокирована хотя бы одна версия.</returns>
    [Public]
    public static bool VersionIsLocked(List<Sungero.Content.IElectronicDocumentVersions> versions)
    {
      foreach (var version in versions)
      {
        var lockInfo = version.Body != null ? Locks.GetLockInfo(version.Body) : null;
        var isLockedByOther = lockInfo != null && lockInfo.IsLocked;
        
        if (isLockedByOther)
          return true;
      }
      
      return false;
    }
    
    /// <summary>
    /// Показать список всех отчетов.
    /// </summary>
    public virtual void ShowAllReports()
    {
      Reports.ShowAll();
    }

    /// <summary>
    /// Показать настройки текущего пользователя.
    /// </summary>
    public virtual void ShowCurrentPersonalSettings()
    {
      var personalSettings = Docflow.PublicFunctions.PersonalSetting.GetPersonalSettings(null);
      if (personalSettings != null)
        personalSettings.Show();
      else
      {
        if (Sungero.Company.Employees.Current == null)
          Dialogs.ShowMessage(Resources.FailedGetSettingsForNonEmployee, MessageType.Error);
        else
          Dialogs.ShowMessage(Resources.FailedGetSettings, MessageType.Error);
      }
    }
    
    /// <summary>
    /// Запустить отчет "Лист согласования".
    /// </summary>
    /// <param name="document">Документ.</param>
    public virtual void RunApprovalSheetReport(IOfficialDocument document)
    {
      var hasSignatures = Functions.OfficialDocument.Remote.HasSignatureForApprovalSheetReport(document);
      if (!hasSignatures)
      {
        Dialogs.NotifyMessage(OfficialDocuments.Resources.DocumentIsNotSigned);
        return;
      }
      
      var report = Reports.GetApprovalSheetReport();
      report.Document = document;
      report.Open();
    }
    
    /// <summary>
    /// Запустить отчёт "Протокол эл. обмена".
    /// </summary>
    /// <param name="document">Документ.</param>
    public virtual void RunExchangeOrderReport(IOfficialDocument document)
    {
      var report = Reports.GetExchangeOrderReport();
      report.Entity = document;
      report.Open();
    }
    
    #region Подписание документа
    
    /// <summary>
    /// Утвердить документ.
    /// </summary>
    /// <param name="assignment">Задание с документом.</param>
    /// <param name="needStrongSign">Требуется квалифицированная электронная подпись.</param>
    /// <param name="eventArgs">Аргумент обработчика вызова.</param>
    [Obsolete("Используйте метод Functions.ApprovalSigningAssignment.ApproveDocument")]
    public virtual void ApproveDocument(IAssignment assignment, bool needStrongSign, Sungero.Domain.Client.ExecuteActionArgs eventArgs)
    {
      var task = ApprovalTasks.As(assignment.Task);
      if (task == null)
        return;
      
      var document = task.DocumentGroup.OfficialDocuments.Single();
      var addenda = task.AddendaGroup.OfficialDocuments.ToList();
      var performer = Company.Employees.As(assignment.Performer);
      var comment = string.IsNullOrWhiteSpace(assignment.ActiveText) ? string.Empty : assignment.ActiveText;
      
      this.ApproveDocument(document, addenda, performer, needStrongSign, comment, eventArgs);
    }
    
    /// <summary>
    /// Утвердить документ.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="addenda">Приложения.</param>
    /// <param name="substituted">За кого выполняется утверждение.</param>
    /// <param name="needStrongSign">Требуется квалифицированная электронная подпись.</param>
    /// <param name="comment">Комментарий.</param>
    /// <param name="eventArgs">Аргумент обработчика вызова.</param>
    public virtual void ApproveDocument(IOfficialDocument document, List<IOfficialDocument> addenda,
                                        Company.IEmployee substituted, bool needStrongSign, string comment,
                                        Sungero.Domain.Client.ExecuteActionArgs eventArgs)
    {
      var currentEmployee = Company.Employees.Current;
      var canSubstitutedApprove = Functions.OfficialDocument.Remote.CanSignByEmployee(document, substituted);
      var canCurrentEmployeeApprove = currentEmployee != null
        ? Functions.OfficialDocument.Remote.CanSignByEmployee(document, currentEmployee)
        : false;
      var signatory = canSubstitutedApprove && canCurrentEmployeeApprove
        ? substituted
        : currentEmployee;

      try
      {
        if (!Functions.Module.ApproveWithAddenda(document, addenda, null, signatory, false, needStrongSign, comment))
          eventArgs.AddError(ApprovalTasks.Resources.ToPerformNeedSignDocument);
      }
      catch (CommonLibrary.Exceptions.PlatformException ex)
      {
        if (!ex.IsInternal)
        {
          Logger.DebugFormat("Failed to approve document with addenda. Document id = '{0}' ", ex, document.Id);
          var message = ex.Message.Trim().EndsWith(".") ? ex.Message : string.Format("{0}.", ex.Message);
          eventArgs.AddError(message);
        }
        else
        {
          Logger.ErrorFormat("Failed to approve document with addenda. Document id = '{0}' ", ex, document.Id);
          throw;
        }
      }
    }
    
    /// <summary>
    /// Согласовать документ.
    /// </summary>
    /// <param name="assignment">Задание с документом.</param>
    /// <param name="endorse">Признак согласования документа, true - согласовать документ, false - не согласовывать.</param>
    /// <param name="needStrongSign">Требуется квалифицированная электронная подпись.</param>
    /// <param name="eventArgs">Аргумент обработчика вызова.</param>
    public virtual void EndorseDocument(IAssignment assignment,
                                        bool endorse, bool needStrongSign,
                                        Sungero.Domain.Client.ExecuteActionArgs eventArgs)
    {
      var approvalTask = ApprovalTasks.As(assignment.Task);
      var freeApprovalTask = FreeApprovalTasks.As(assignment.Task);
      
      if (approvalTask == null && freeApprovalTask == null)
        return;
      
      var performer = Company.Employees.As(assignment.Performer);
      // Добавить в комментарий ЭП результат выполнения задания, если пользователь ничего не указал.
      var comment = string.IsNullOrWhiteSpace(assignment.ActiveText) ? string.Empty : assignment.ActiveText;
      
      var document = approvalTask != null
        ? ElectronicDocuments.As(approvalTask.DocumentGroup.OfficialDocuments.Single())
        : freeApprovalTask.ForApprovalGroup.ElectronicDocuments.Single();
      
      // Получить документы из группы вложений "Приложения", исключая дубли и основной документ.
      var addenda = new List<IElectronicDocument>();
      if (approvalTask != null)
        addenda = Functions.Module.GetApprovalTaskAddendaForEndorse(assignment);
      else if (freeApprovalTask != null)
        addenda = Functions.Module.GetFreeApprovalTaskAddendaForEndorse(assignment);
      addenda = addenda.Where(x => x.Id != document.Id).Distinct().ToList();
      
      this.EndorseDocument(document, addenda, performer, endorse, needStrongSign, comment, eventArgs);
    }
    
    /// <summary>
    /// Получить документы для согласования из группы вложений "Приложения" задания задачи на согласование по регламенту.
    /// </summary>
    /// <param name="assignment">Задание.</param>
    /// <returns>Документы из группы вложений "Приложения" задания.</returns>
    public virtual List<IElectronicDocument> GetApprovalTaskAddendaForEndorse(IAssignment assignment)
    {
      if (ApprovalAssignments.Is(assignment))
        return ApprovalAssignments.As(assignment).AddendaGroup.OfficialDocuments.ToList<IElectronicDocument>();
      
      if (ApprovalManagerAssignments.Is(assignment))
        return ApprovalManagerAssignments.As(assignment).AddendaGroup.OfficialDocuments.ToList<IElectronicDocument>();
      
      if (ApprovalReviewAssignments.Is(assignment))
        return ApprovalReviewAssignments.As(assignment).AddendaGroup.OfficialDocuments.ToList<IElectronicDocument>();
      
      if (ApprovalReworkAssignments.Is(assignment))
        return ApprovalReworkAssignments.As(assignment).AddendaGroup.OfficialDocuments.ToList<IElectronicDocument>();
      
      if (ApprovalSigningAssignments.Is(assignment))
        return ApprovalSigningAssignments.As(assignment).AddendaGroup.OfficialDocuments.ToList<IElectronicDocument>();
      
      return new List<IElectronicDocument>();
    }
    
    /// <summary>
    /// Получить документы для согласования из группы вложений "Приложения" задания задачи на свободное согласование.
    /// </summary>
    /// <param name="assignment">Задание.</param>
    /// <returns>Документы из группы вложений "Приложения" задания.</returns>
    public virtual List<IElectronicDocument> GetFreeApprovalTaskAddendaForEndorse(IAssignment assignment)
    {
      if (FreeApprovalAssignments.Is(assignment))
        return FreeApprovalAssignments.As(assignment).AddendaGroup.ElectronicDocuments.ToList();
      
      return new List<IElectronicDocument>();
    }
    
    /// <summary>
    /// Согласовать документ.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="addenda">Приложения.</param>
    /// <param name="substituted">За кого выполняется утверждение.</param>
    /// <param name="endorse">Признак согласования документа, true - согласовать документ, false - не согласовывать.</param>
    /// <param name="needStrongSign">Требуется квалифицированная электронная подпись.</param>
    /// <param name="comment">Комментарий.</param>
    /// <param name="eventArgs">Аргумент обработчика вызова.</param>
    public virtual void EndorseDocument(IElectronicDocument document, List<IElectronicDocument> addenda, Company.IEmployee substituted, bool endorse, bool needStrongSign, string comment, Sungero.Domain.Client.ExecuteActionArgs eventArgs)
    {
      if (!document.HasVersions && !endorse)
        return;
      
      try
      {
        var isSigned = endorse ?
          this.EndorseWithAddenda(document, addenda, null, substituted, needStrongSign, comment) :
          Signatures.NotEndorse(document.LastVersion, null, comment, substituted);
        
        if (!isSigned)
          eventArgs.AddError(ApprovalTasks.Resources.ToPerformNeedSignDocument);
      }
      catch (CommonLibrary.Exceptions.PlatformException ex)
      {
        Logger.ErrorFormat("Failed to endorse document with addenda. Document id = '{0}' ", ex, document.Id);
        if (!ex.IsInternal)
        {
          var message = ex.Message.EndsWith(".") ? ex.Message : string.Format("{0}.", ex.Message);
          eventArgs.AddError(message);
        }
        else
          throw;
      }
    }
    
    /// <summary>
    /// Утвердить документ с приложениями.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="addenda">Приложения.</param>
    /// <param name="certificate">Сертификат (не передавать, чтобы оставить выбор пользователю).</param>
    /// <param name="substituted">За кого выполняется утверждение (не передавать, чтобы утвердить под текущим пользователем).</param>
    /// <param name="endorseWhenApproveFailed">Согласовать документ, если не удается выполнить утверждение.</param>
    /// <param name="needStrongSign">Требуется квалифицированная электронная подпись.</param>
    /// <param name="comment">Комментарий.</param>
    /// <returns>True, если сам документ был утверждён или не имеет версий. Факт подписания приложений неважен.</returns>
    [Public]
    public virtual bool ApproveWithAddenda(IOfficialDocument document, List<IOfficialDocument> addenda,
                                           ICertificate certificate, Company.IEmployee substituted,
                                           bool endorseWhenApproveFailed, bool needStrongSign, string comment)
    {
      var addendaHaveVersions = addenda != null && addenda.Any(a => a.HasVersions);
      if (!document.HasVersions && !addendaHaveVersions)
        return true;
      
      if (certificate == null && needStrongSign)
      {
        if (!this.TryGetUserCertificate(document, out certificate))
          return false;
      }
      
      try
      {
        var result = !document.HasVersions;
        if (document.HasVersions)
        {
          var canApprove = !Functions.OfficialDocument.Remote.GetApprovalValidationErrors(document, true).Any();
          if (canApprove)
          {
            var accountingDocument = AccountingDocumentBases.As(document);
            if (accountingDocument != null && accountingDocument.IsFormalized == true)
            {
              Functions.AccountingDocumentBase.GenerateDefaultSellerTitle(accountingDocument);
              Functions.AccountingDocumentBase.GenerateDefaultBuyerTitle(accountingDocument);
            }
            
            result = Signatures.Approve(document.LastVersion, certificate, comment, substituted);
          }
          else if (endorseWhenApproveFailed)
            result = Signatures.Endorse(document.LastVersion, certificate, comment, substituted);
        }
        
        // Если не удалось утвердить основной документ или приложений нет - приложения не трогаем.
        if (!result || addenda == null || !addenda.Any())
          return result;
        
        var addendaWithVersions = addenda.Where(a => a.HasVersions).ToList();
        if (!addendaWithVersions.Any())
          return result;
        
        var canBeApproved = new List<IOfficialDocument>();
        var canBeEndorsed = new List<IOfficialDocument>();
        foreach (var addendumDocument in addendaWithVersions)
        {
          var canApprove = !Functions.OfficialDocument.Remote.GetApprovalValidationErrors(addendumDocument, true).Any();
          if (canApprove)
            canBeApproved.Add(addendumDocument);
          else
            canBeEndorsed.Add(addendumDocument);
        }
        foreach (var addendumDocument in canBeApproved)
        {
          var addendumAccountingDocument = AccountingDocumentBases.As(addendumDocument);
          if (addendumAccountingDocument != null && addendumAccountingDocument.IsFormalized == true)
          {
            Functions.AccountingDocumentBase.GenerateDefaultSellerTitle(addendumAccountingDocument);
            Functions.AccountingDocumentBase.GenerateDefaultBuyerTitle(addendumAccountingDocument);
          }
        }
        if (canBeApproved.Any())
          Signatures.Approve(canBeApproved.Select(a => a.LastVersion), certificate, comment, substituted);
        if (canBeEndorsed.Any())
          Signatures.Endorse(canBeEndorsed.Select(a => a.LastVersion), certificate, comment, substituted);
        return result;
      }
      catch (Sungero.Domain.Shared.Exceptions.ChildEntityNotFoundException ex)
      {
        throw AppliedCodeException.Create(OfficialDocuments.Resources.SigningVersionWasDeleted, ex);
      }
    }
    
    /// <summary>
    /// Согласовать документ с приложениями.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="addenda">Приложения.</param>
    /// <param name="certificate">Сертификат (не передавать, чтобы оставить выбор пользователю).</param>
    /// <param name="substituted">За кого выполняется утверждение (не передавать, чтобы утвердить под текущим пользователем).</param>
    /// <param name="needStrongSign">Требуется квалифицированная электронная подпись.</param>
    /// <param name="comment">Комментарий.</param>
    /// <returns>True, если сам документ был согласован или не имеет версий. Факт согласования приложений неважен.</returns>
    [Public]
    public virtual bool EndorseWithAddenda(IElectronicDocument document, List<IElectronicDocument> addenda,
                                           ICertificate certificate, IUser substituted,
                                           bool needStrongSign, string comment)
    {
      var addendaHasVersions = addenda != null && addenda.Any(a => a.HasVersions);
      if (!document.HasVersions && !addendaHasVersions)
        return true;
      
      if (certificate == null && needStrongSign)
      {
        var officialDocument = OfficialDocuments.As(document);
        
        if (!this.TryGetUserCertificate(officialDocument, out certificate))
          return false;
      }
      
      try
      {
        var result = !document.HasVersions;
        if (document.HasVersions)
        {
          result = Signatures.Endorse(document.LastVersion, certificate, comment, substituted);
        }
        
        // Если не удалось согласовать основной документ или приложений нет - приложения не трогаем.
        if (!result || addenda == null || !addenda.Any())
          return result;
        
        var addendaWithVersions = addenda.Where(a => a.HasVersions).ToList();
        if (!addendaWithVersions.Any())
          return result;
        
        Signatures.Endorse(addendaWithVersions.Select(a => a.LastVersion), certificate, comment, substituted);
        return result;
      }
      catch (Sungero.Domain.Shared.Exceptions.ChildEntityNotFoundException ex)
      {
        throw AppliedCodeException.Create(OfficialDocuments.Resources.SigningVersionWasDeleted, ex);
      }
    }
    
    /// <summary>
    /// Получить сертификат пользователя для подписания.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="certificate">Сертификат для подписания.</param>
    /// <returns>True, если выбор произведен, false в случае отмены.</returns>
    private bool TryGetUserCertificate(IOfficialDocument document, out ICertificate certificate)
    {
      certificate = null;
      var certificates = PublicFunctions.Module.Remote.GetCertificates(document);
      var ourSigningReason = document.OurSigningReason;
      
      // Взять сертификат из основания подписания, если он подходит по критериям.
      // При рассмотрении адресатом поле "Основание" вернет сертификат подписавшего, а не рассматривающего, поэтому для рассмотрения автовыбор сертификата из "Основания" не делать.
      if (!CallContext.CalledFrom(ApprovalReviewAssignments.Info) &&
          ourSigningReason != null &&
          ourSigningReason.Certificate != null &&
          certificates.Contains(ourSigningReason.Certificate) &&
          Equals(ourSigningReason.Certificate.Owner, Employees.Current) &&
          !Functions.SignatureSetting.Remote.FormalizedPowerOfAttorneyIsExpired(ourSigningReason))
      {
        certificate = document.OurSigningReason.Certificate;
        return true;
      }
      
      if (certificates.Any())
      {
        var selectedCertificate = certificates.Count() > 1 ?
          certificates.ShowSelectCertificate() :
          certificates.First();
        if (selectedCertificate == null)
          return false;
        certificate = selectedCertificate;
      }
      return true;
    }
    
    #endregion
    
    #region Диалог добавления приложений из файлов

    /// <summary>
    /// Получить сообщение об успешном создании приложений из файлов.
    /// </summary>
    /// <param name="addendaCount">Количество приложений.</param>
    /// <returns>Сообщение об успешном создании приложений из файлов.</returns>
    public virtual string GetManyAddendumDialogSuccessfulNotify(int addendaCount)
    {
      var addendumName = Sungero.Docflow.Resources.AddendumNameForOneDocument;
      if (addendaCount > 1 && addendaCount < 5)
        addendumName = Sungero.Docflow.Resources.AddendumNameLessFiveDocument;
      else if (addendaCount >= 5)
        addendumName = Sungero.Docflow.Resources.AddendumNameForManyDocument;
      
      return Sungero.Docflow.OfficialDocuments.Resources.AddendaCreatedSuccesfullyFormat(addendaCount, addendumName);
    }
    
    /// <summary>
    /// Создать приложение к документу.
    /// </summary>
    /// <param name="addendumName">Имя документа.</param>
    /// <param name="leadingDocument">Ведущий документ.</param>
    /// <param name="addendumContent">Тело документа.</param>
    public virtual void CreateAddendum(string addendumName, IOfficialDocument leadingDocument, byte[] addendumContent)
    {
      var addendum = Functions.Addendum.Remote.Create();
      addendum.LeadingDocument = leadingDocument;
      var name = System.IO.Path.GetFileNameWithoutExtension(addendumName);
      if (addendum.State.Properties.Name.IsEnabled)
        addendum.Name = name;
      addendum.Subject = name;
      if (addendum.DocumentKind == null)
        addendum.DocumentKind = Functions.DocumentKind.GetAvailableDocumentKinds(typeof(Docflow.IAddendum)).FirstOrDefault();
      
      using (var fileStream = new System.IO.MemoryStream(addendumContent))
      {
        addendum.CreateVersionFrom(fileStream, System.IO.Path.GetExtension(addendumName));
        addendum.Save();
      }
      return;
    }
    
    /// <summary>
    /// Создать приложение к документу.
    /// </summary>
    /// <param name="addendumName">Имя документа.</param>
    /// <param name="leadingDocument">Ведущий документ.</param>
    /// <param name="stream">Тело документа.</param>
    public virtual void CreateAddendum(string addendumName, IOfficialDocument leadingDocument, System.IO.Stream stream)
    {
      var addendum = Functions.Addendum.Remote.Create();
      addendum.LeadingDocument = leadingDocument;
      var name = System.IO.Path.GetFileNameWithoutExtension(addendumName);
      if (addendum.State.Properties.Name.IsEnabled)
        addendum.Name = name;
      addendum.Subject = name;
      if (addendum.DocumentKind == null)
        addendum.DocumentKind = Functions.DocumentKind.GetAvailableDocumentKinds(typeof(Docflow.IAddendum)).FirstOrDefault();
      
      addendum.CreateVersionFrom(stream, System.IO.Path.GetExtension(addendumName));
      ((Domain.Shared.IExtendedEntity)addendum).Params[PublicConstants.Module.AddendumSourceFileNameParamName] = addendumName;
      addendum.Save();
      
      return;
    }
    
    /// <summary>
    /// Диалог массового добавления приложений из файлов.
    /// </summary>
    /// <param name="document">Документ, для которого создаются приложения.</param>
    public virtual void AddManyAddendumDialog(IOfficialDocument document)
    {
      var dialog = Dialogs.CreateInputDialog(Sungero.Docflow.OfficialDocuments.Resources.ManyAddendumDialogTitle);
      if (ClientApplication.ApplicationType == ApplicationType.Web)
        dialog.Width = 500;
      
      var progressBar = dialog.AddProgressBar();
      var extensions = Content.AssociatedApplications.GetAll()
        .Where(a => !Equals(a.Sid, Docflow.PublicConstants.Module.UnknownAppSid))
        .Select(a => a.Extension)
        .ToArray();
      
      // Все расширения отображаются единой строкой при выборе файлов при использовании метода WithFilter.
      // Значение параметра extension будет отображаться первым в списке расширений.
      var rowsCount = 10;
      var filesSelector = dialog.AddFileSelectMany(Sungero.Docflow.OfficialDocuments.Resources.DownloadFiles, false)
        .WithFilter(extensions.FirstOrDefault(), extensions)
        .WithRowsCount(rowsCount);
      var importButton = dialog.Buttons.AddCustom(Sungero.Docflow.OfficialDocuments.Resources.AddendumAddFiles);
      var cancelButton = dialog.Buttons.AddCustom(Sungero.Docflow.Resources.ExportDialog_Cancel);
      
      var successfullyCreatedAddendaCount = 0;
      importButton.IsEnabled = false;
      
      Action<CommonLibrary.InputDialogRefreshEventArgs> refresh = (b) =>
      {
        if (filesSelector.Value == null || !filesSelector.Value.Any())
          importButton.IsEnabled = false;
        else
          importButton.IsEnabled = true;
      };

      dialog.SetOnRefresh(refresh);
      dialog.SetOnButtonClick(b =>
                              {
                                if (b.Button == cancelButton)
                                  return;
                                if (b.Button == importButton && b.IsValid)
                                {
                                  var addendaCreatedSuccessfully = true;
                                  var errorList = new List<string>();
                                  progressBar.TotalValue = filesSelector.Value.Count();
                                  var filesCount = 0;
                                  
                                  try
                                  {
                                    foreach (var fileSelector in filesSelector.Value)
                                    {
                                      if (dialog.IsCanceled)
                                        break;
                                      progressBar.Value = ++filesCount;
                                      
                                      try
                                      {
                                        CreateAddendum(fileSelector.FileName, document, fileSelector.OpenReadStream());
                                        successfullyCreatedAddendaCount++;
                                      }
                                      catch (AppliedCodeException ae)
                                      {
                                        errorList.Add(ae.Message);
                                        addendaCreatedSuccessfully = false;
                                      }
                                      catch (Sungero.Domain.Shared.Validation.ValidationException ex)
                                      {
                                        Logger.ErrorFormat("AddManyAddendumDialog: {0}", ex, ex.Message);
                                        errorList.Add(ex.Message);
                                        addendaCreatedSuccessfully = false;
                                      }
                                      catch (Exception ex)
                                      {
                                        Logger.ErrorFormat("AddManyAddendumDialog: {0}", ex, ex.Message);
                                        errorList.Add(Sungero.Docflow.Resources.InternalServerError);
                                        addendaCreatedSuccessfully = false;
                                      }
                                    }
                                    
                                    if (addendaCreatedSuccessfully && successfullyCreatedAddendaCount > 0)
                                      Dialogs.NotifyMessage(Functions.Module.GetManyAddendumDialogSuccessfulNotify(successfullyCreatedAddendaCount));
                                    else
                                    {
                                      var errorMessage = string.Empty;
                                      if (successfullyCreatedAddendaCount > 0)
                                        errorMessage += Functions.Module.GetManyAddendumDialogSuccessfulNotify(successfullyCreatedAddendaCount);

                                      errorMessage += Sungero.Docflow.Resources.ErrorAddManyAddendumsFormat(successfullyCreatedAddendaCount > 0 ?
                                                                                                            Sungero.Docflow.Resources.ErrorAddManyAddendumsOther : string.Empty);
                                      foreach (var error in errorList.Distinct())
                                      {
                                        errorMessage += string.Format(Sungero.Docflow.Resources.ErrorList, error);
                                      }
                                      
                                      b.AddError(errorMessage, filesSelector);
                                      refresh.Invoke(null);
                                    }
                                  }
                                  catch (AppliedCodeException ae)
                                  {
                                    b.AddError(ae.Message);
                                  }
                                  catch (Exception ex)
                                  {
                                    Logger.ErrorFormat("AddManyAddendumDialog: {0}", ex, ex.Message);
                                    b.AddError(Sungero.Docflow.Resources.InternalServerError);
                                  }
                                  
                                  importButton.IsVisible = false;
                                  filesSelector.IsEnabled = false;
                                  cancelButton.Name = Resources.Dialog_Close;
                                }
                              });
      dialog.Show();
    }
    
    #endregion
    
    #region Выгрузка
    
    /// <summary>
    /// Запустить выгрузку документов с поиском документов.
    /// </summary>
    [Public]
    public static void ExportFinancialDocumentDialogWithSearch()
    {
      if (ClientApplication.ApplicationType == ApplicationType.Web)
        ExportDocumentDialogWithSearchInWeb(null, false);
    }
    
    /// <summary>
    /// Запустить поиск документов в финархиве.
    /// </summary>
    /// <returns>Ленивый запрос на отображение документов.</returns>
    [Public]
    public static IQueryable<IOfficialDocument> FinancialDocumentDialogSearch()
    {
      if (ClientApplication.ApplicationType == ApplicationType.Desktop)
        return ExportDocumentDialogWithSearch();
      else
        return ExportDocumentDialogWithSearchInWeb(null, true);
    }
    
    /// <summary>
    /// Запустить выгрузку документов из явно указанных.
    /// </summary>
    /// <param name="documents">Документы, которые надо выгрузить.</param>
    [Public]
    public static void ExportDocumentDialog(List<IOfficialDocument> documents)
    {
      if (ClientApplication.ApplicationType == ApplicationType.Web)
        ExportDocumentDialogWithSearchInWeb(documents, false);
    }
    
    /// <summary>
    /// Выгрузка документов в веб-клиенте.
    /// </summary>
    /// <param name="documentList">Список документов.</param>
    /// <param name="onlySearch">Признак "Только поиск". Если установлен в True, выгрузка проводиться не будет.</param>
    /// <returns>Кверик документов для выгрузки.</returns>
    [Public]
    public static IQueryable<IOfficialDocument> ExportDocumentDialogWithSearchInWeb(List<IOfficialDocument> documentList, bool onlySearch)
    {
      int zipModelFilesCount = 0;
      long zipModelFilesSumSize = 0;
      bool zipModelFilesExportError = false;
      string addErrorMessage = string.Empty;
      var totalForDownloadDialogText = string.Empty;
      var typeValueChanged = false;
      Docflow.Structures.Module.IExportDialogSearch filter = null;
      Structures.Module.ExportResult exportResult = null;
      var documents = documentList != null ? documentList.AsQueryable() : null;
      var documentCount = documents != null ? documents.Count() : 0;
      var canSearch = documents == null;
      IQueryable<IOfficialDocument> returned = null;
      var reportData = Structures.Module.AfterExportDialog.Create();
      reportData.PathToRoot = ".";
      reportData.Documents = new List<Structures.Module.ExportedDocument>();
      var documentsToPrepare = new List<int>();
      
      var isSingleExport = documentList != null && documentList.Count() == 1 &&
        (Contracts.IncomingInvoices.Is(documentList.FirstOrDefault()) ||
         Contracts.OutgoingInvoices.Is(documentList.FirstOrDefault()) ||
         !AccountingDocumentBases.Is(documentList.FirstOrDefault())) &&
        !Sungero.Contracts.ContractualDocuments.Is(documentList.FirstOrDefault());

      var search = canSearch;
      var start = !canSearch;
      var end = false;
      var step = 1;

      var dialog = Dialogs.CreateInputDialog(onlySearch ?
                                             Resources.ExportDialog_Search_Title :
                                             Resources.ExportDialog_Title);
      // Размеры подобраны на глаз.
      dialog.Height = canSearch ? (onlySearch ? 0 : 220) : 160;
      
      // Принудительно увеличиваем ширину диалога для корректного отображения кнопок.
      var fakeControl = dialog.AddString("123456789012345", false);
      fakeControl.IsVisible = false;
      
      dialog.HelpCode = onlySearch ? Constants.AccountingDocumentBase.HelpCodes.Search : Constants.AccountingDocumentBase.HelpCodes.Export;
      
      var type = dialog.AddSelect(Resources.ExportDialog_Format, true, Resources.ExportDialog_Format_Formalized)
        .From(Resources.ExportDialog_Format_Formalized, Resources.ExportDialog_Format_Print);

      var group = dialog.AddSelect(Resources.ExportDialog_Group, true, Resources.ExportDialog_Group_None)
        .From(Resources.ExportDialog_Group_None,
              Resources.ExportDialog_Group_Counterparty,
              Resources.ExportDialog_Group_DocumentType);
      var addAddendum = dialog.AddBoolean(Sungero.Docflow.Resources.ExportDialog_AddAddendum, true);
      
      var properties = AccountingDocumentBases.Info.Properties;
      var unit = dialog.AddSelect(properties.BusinessUnit.LocalizedName, !onlySearch, Company.BusinessUnits.Null);
      var counterparty = dialog.AddSelect(properties.Counterparty.LocalizedName, false, Parties.Counterparties.Null);
      
      var contract = dialog.AddSelect(Resources.ExportDialog_Search_Contract, false, Contracts.ContractualDocuments.Null)
        .Where(c => (unit.Value == null || Equals(c.BusinessUnit, unit.Value)) && (counterparty.Value == null || Equals(c.Counterparty, counterparty.Value)));

      var allowedKinds = new List<IDocumentKind>();
      
      var allowedAccountingDocumentKinds = Functions.DocumentKind.GetAvailableDocumentKinds(typeof(IAccountingDocumentBase))
        .Where(k => !Equals(k.DocumentType.DocumentTypeGuid, Constants.AccountingDocumentBase.IncomingInvoiceGuid) &&
               !Equals(k.DocumentType.DocumentTypeGuid, Constants.AccountingDocumentBase.OutgoingInvoiceGuid));
      allowedKinds.AddRange(allowedAccountingDocumentKinds);
      
      var allowedContractualDocumentKinds = Functions.DocumentKind.GetAvailableDocumentKinds(typeof(IContractualDocumentBase));
      allowedKinds.AddRange(allowedContractualDocumentKinds);
      allowedKinds = allowedKinds.OrderBy(k => k.Name).ToList();
      
      var kinds = dialog.AddSelectMany(Resources.ExportDialog_Search_DocumentKinds, false, Docflow.DocumentKinds.Null)
        .From(allowedKinds);
      var dateFrom = dialog.AddDate(Resources.ExportDialog_Search_DateFrom, false);
      var dateTo = dialog.AddDate(Resources.ExportDialog_Search_DateTo, false);
      
      var showDocs = dialog.Buttons.AddCustom(Resources.ExportDialog_Search_Show);
      var back = dialog.Buttons.AddCustom(Resources.ExportDialog_Back);
      back.IsVisible = canSearch;
      var next = dialog.Buttons.AddCustom(Resources.ExportDialog_StartExport);
      var cancel = dialog.Buttons.AddCustom(Resources.ExportDialog_Close);
      
      Action showAllDocuments = () => documents.Show();
      
      // Фильтрация договоров по НОР и контрагентам.
      unit.SetOnValueChanged(u =>
                             {
                               if (u.NewValue != null && contract.Value != null && !Equals(contract.Value.BusinessUnit, u.NewValue))
                                 contract.Value = null;
                             });
      counterparty.SetOnValueChanged(cp =>
                                     {
                                       if (cp.NewValue != null && contract.Value != null && !Equals(contract.Value.Counterparty, cp.NewValue))
                                         contract.Value = null;
                                     });
      contract.SetOnValueChanged(c =>
                                 {
                                   if (c.NewValue != null)
                                   {
                                     unit.Value = c.NewValue.BusinessUnit;
                                     counterparty.Value = c.NewValue.Counterparty;
                                   }
                                 });
      
      type.SetOnValueChanged(t =>
                             {
                               totalForDownloadDialogText = string.Empty;
                               typeValueChanged = true;
                             });
      
      #region Refresh
      
      Action<CommonLibrary.InputDialogRefreshEventArgs> refresh = (r) =>
      {
        if (!onlySearch)
        {
          if (search)
          {
            dialog.Text = Resources.ExportDialog_Step_SearchFormat(step);
            dialog.Text += Environment.NewLine;
          }
          else if (start)
          {
            dialog.Text = Resources.ExportDialog_Step_Config_WebFormat(step);
            dialog.Text += Environment.NewLine + Environment.NewLine;
            
            dialog.Text += Resources.ExportDialog_OpenDocumentsFormat(documentCount);
            
            dialog.Text += totalForDownloadDialogText;
            
            if (documentCount > Constants.AccountingDocumentBase.ExportedDocumentsCountMaxLimit && start && step == 1)
            {
              r.AddError(Resources.ExportDialog_Error_DocumentCountLimitFormat(Constants.AccountingDocumentBase.ExportedDocumentsCountMaxLimit));
            }
          }
          else if (end)
          {
            if (reportData.Documents.Any(d => !d.IsFaulted))
            {
              dialog.Text = Resources.ExportDialog_Step_End_WebFormat(step);
              dialog.Text += Environment.NewLine + Environment.NewLine;
              dialog.Text += Resources.ExportDialog_DocumentsSuccessfullyPreparedForDownload;
            }
            else if (reportData.Documents.Any(d => d.IsFaulted))
            {
              dialog.Text = Resources.ExportDialog_Step_End_Report_WebFormat(step);
              dialog.Text += Environment.NewLine + Environment.NewLine;
              dialog.Text += Resources.ExportDialog_CompletedNotExported;
            }
            
            dialog.Text += Environment.NewLine + Environment.NewLine;
            dialog.Text += Resources.ExportDialog_End_AllDocs_WebFormat(reportData.Documents.Count(d => !d.IsAddendum));
            dialog.Text += Environment.NewLine;
            dialog.Text += Resources.ExportDialog_End_FormalizedDocsFormat(reportData.Documents.Count(d => !d.IsAddendum && !d.IsFaulted && d.IsFormalized));
            dialog.Text += Environment.NewLine;
            dialog.Text += Resources.ExportDialog_End_NonformalizedDocsFormat(reportData.Documents.Count(d => !d.IsAddendum && !d.IsFaulted && !d.IsFormalized));
            if (reportData.Documents.Any(d => !d.IsAddendum && d.IsFaulted))
            {
              dialog.Text += Environment.NewLine;
              dialog.Text += Resources.ExportDialog_End_NotExportedDocs_WebFormat(reportData.Documents.Count(d => !d.IsAddendum && d.IsFaulted));
            }
            
            if (reportData.Documents.Any(d => d.IsAddendum))
            {
              dialog.Text += Environment.NewLine + Environment.NewLine;
              dialog.Text += Resources.ExportDialog_End_AllAddendumsFormat(reportData.Documents.Count(d => d.IsAddendum));
              dialog.Text += Environment.NewLine;
              dialog.Text += Resources.ExportDialog_End_FormalizedDocsFormat(reportData.Documents.Count(d => d.IsAddendum && !d.IsFaulted && d.IsFormalized));
              dialog.Text += Environment.NewLine;
              dialog.Text += Resources.ExportDialog_End_NonformalizedDocsFormat(reportData.Documents.Count(d => d.IsAddendum && !d.IsFaulted && !d.IsFormalized));
              if (reportData.Documents.Any(d => d.IsAddendum && d.IsFaulted))
              {
                dialog.Text += Environment.NewLine;
                dialog.Text += Resources.ExportDialog_End_NotExportedDocs_WebFormat(reportData.Documents.Count(d => d.IsAddendum && d.IsFaulted));
              }
            }
          }
        }
        
        group.IsVisible = start && !isSingleExport;
        type.IsVisible = start;
        addAddendum.IsVisible = start;
        group.IsEnabled = documentCount != 0 && documentCount <= Constants.AccountingDocumentBase.ExportedDocumentsCountMaxLimit;
        type.IsEnabled = documentCount != 0 && documentCount <= Constants.AccountingDocumentBase.ExportedDocumentsCountMaxLimit;
        
        unit.IsVisible = search;
        counterparty.IsVisible = search;
        dateFrom.IsVisible = search;
        dateTo.IsVisible = search;
        kinds.IsVisible = search;
        contract.IsVisible = search;
        showDocs.IsVisible = (search && onlySearch || start) && !isSingleExport;
        showDocs.IsEnabled = start ? documentCount != 0 : !end;
        
        next.IsVisible = !onlySearch;
        back.IsVisible = start && canSearch || end && reportData.Documents.All(d => d.IsFaulted);
        next.IsEnabled = start
          ? (documentCount != 0 && documentCount <= Constants.AccountingDocumentBase.ExportedDocumentsCountMaxLimit && (!zipModelFilesExportError || typeValueChanged))
          : (end ? reportData.Documents.Any(d => !d.IsFaulted) : true);
        
        back.Name = end ? Resources.ExportDialog_End_Report : Resources.ExportDialog_Back;
        next.Name = end ? Resources.ExportDialog_StartExport :
          Resources.ExportDialog_ConfigExport;
        cancel.Name = end ? Resources.ExportDialog_Close : Resources.ExportDialog_Cancel;
        showDocs.Name = search ? Resources.ExportDialog_Search_OnlySearch :
          (start ? Resources.ExportDialog_Search_Show : Resources.ExportDialog_End_Report);
      };
      
      dialog.SetOnRefresh(refresh);
      
      #endregion
      
      IZip zip = null;
      dialog.SetOnButtonClick(
        (h) =>
        {
          if (h.Button == next || h.Button == back || (h.Button == showDocs && !onlySearch))
            h.CloseAfterExecute = false;
          
          #region Экран с результатами выгрузки

          if (end && h.Button == next)
          {
            zip.Export();
          }
          else if (end && h.Button == back)
          {
            var now = Calendar.UserNow;
            var report = Functions.Module.GetFinArchiveExportReport(exportResult.ExportedDocuments, now);
            report.Open();
          }
          
          #endregion

          #region Экран параметров выгрузки
          
          if (start)
          {
            if (h.Button == next && h.IsValid)
            {
              typeValueChanged = false;
              var parameters = Structures.Module.ExportDialogParams
                .Create(group.Value == Resources.ExportDialog_Group_Counterparty,
                        group.Value == Resources.ExportDialog_Group_DocumentType,
                        type.Value == Resources.ExportDialog_Format_Print,
                        isSingleExport, addAddendum.Value.Value);
              var initialize = Structures.Module.AfterExportDialog
                .Create(string.Empty, string.Empty, Calendar.UserNow, new List<Structures.Module.ExportedDocument>());
              try
              {
                initialize = filter != null ?
                  Functions.Module.Remote.PrepareExportDocumentDialogDocuments(documentsToPrepare, parameters) :
                  Functions.Module.Remote.PrepareExportDocumentDialogDocuments(documentList.Select(x => x.Id).ToList(), parameters);
              }
              catch (Exception ex)
              {
                Logger.Error("Не удалось подготовить данные для выгрузки", ex);
                addErrorMessage = Resources.ExportDialog_Error_Client_NoReason_Web;
                h.AddError(addErrorMessage);
                return;
              }
              
              exportResult = Functions.Module.Remote.AfterExportDocumentDialogToWeb(initialize.Documents, parameters);
              
              zipModelFilesCount = exportResult.ZipModels.Count;
              zipModelFilesSumSize = exportResult.ZipModels.Sum(m => m.Size);
              
              if (zipModelFilesCount != 0)
              {
                var filesSumSize = (double)zipModelFilesSumSize / Constants.AccountingDocumentBase.ConvertMb;
                if (filesSumSize < 0.1)
                  filesSumSize = 0.1;

                totalForDownloadDialogText = Environment.NewLine + Environment.NewLine +
                  Resources.ExportDialog_TotalForDownloadFormat(zipModelFilesCount, filesSumSize.ToString("0.#"));
              }
              
              if (zipModelFilesCount > Constants.AccountingDocumentBase.ExportedFilesCountMaxLimit)
              {
                addErrorMessage = Resources.ExportDialog_Error_ExportedFilesLimitFormat(Constants.AccountingDocumentBase.ExportedFilesCountMaxLimit);
                h.AddError(addErrorMessage);
                zipModelFilesExportError = true;
                return;
              }
              else if (zipModelFilesSumSize > Constants.AccountingDocumentBase.ExportedFilesSizeMaxLimitMb * Constants.AccountingDocumentBase.ConvertMb)
              {
                addErrorMessage = Sungero.Docflow.Resources.ExportDialog_Error_ExportedSizeLimitFormat(Constants.AccountingDocumentBase.ExportedFilesSizeMaxLimitMb);
                h.AddError(addErrorMessage);
                zipModelFilesExportError = true;
                return;
              }
              
              if (exportResult.ZipModels != null && exportResult.ZipModels.Any() && exportResult.ExportedDocuments != null && exportResult.ExportedDocuments.Any())
              {
                try
                {
                  zip = Functions.Module.Remote.CreateZipFromZipModel(exportResult.ZipModels, exportResult.ExportedDocuments, initialize.RootFolder);
                }
                catch (Exception ex)
                {
                  Logger.Error("Не удалось подготовить zip-архив для выгрузки", ex);
                  addErrorMessage = Resources.ExportDialog_Error_Client_NoReason_Web;
                  h.AddError(addErrorMessage);
                  zipModelFilesExportError = true;
                  return;
                }
              }
              
              var result = exportResult.ExportedDocuments;
              if (result.Any())
              {
                var faultedDocuments = reportData.Documents.Where(d => d.IsFaulted).Select(d => d.Id);
                var addendaFaulted = result.Where(d => !d.IsFaulted && d.IsAddendum && d.LeadDocumentId != null && faultedDocuments.Contains(d.LeadDocumentId.Value));
                foreach (var addendum in addendaFaulted)
                {
                  addendum.IsFaulted = true;
                  addendum.Error = Resources.ExportDialog_Error_LeadDocumentNoVersion;
                }
                reportData.Documents.AddRange(result);
              }
              
              back.IsEnabled = true;
              end = true;
              step += 1;
              start = false;
              refresh.Invoke(null);
            }
            
            if (h.Button == back)
            {
              search = true;
              start = false;
              step -= 1;
              zipModelFilesCount = 0;
              zipModelFilesExportError = false;
              typeValueChanged = false;
              addErrorMessage = string.Empty;
              totalForDownloadDialogText = string.Empty;
              refresh.Invoke(null);
            }
            
            if (h.Button == showDocs)
            {
              if (!string.IsNullOrEmpty(addErrorMessage))
                h.AddError(addErrorMessage);
              
              showAllDocuments();
            }
          }
          
          #endregion
          
          #region Экран поиска
          
          if (search)
          {
            
            if ((h.Button == next || h.Button == showDocs) &&
                dateTo.Value != null && dateFrom.Value != null && dateTo.Value < dateFrom.Value)
            {
              h.AddError(Sungero.Docflow.Resources.ExportDialog_Error_WrongDatePeriod);
              return;
            }
            
            if (h.Button == cancel)
            {
              unit.IsRequired = false;
              return;
            }
            
            filter = Docflow.Structures.Module.ExportDialogSearch
              .Create(unit.Value, counterparty.Value, contract.Value, dateFrom.Value, dateTo.Value, kinds.Value.ToList());
            if (h.Button == showDocs)
              returned = Functions.Module.Remote.SearchByRequisites(filter);
            
            if (h.Button == next)
            {
              if (h.IsValid)
              {
                var newDocuments = Functions.Module.Remote.SearchByRequisites(filter);
                documents = newDocuments;
                documentCount = documents.Count();
                documentsToPrepare = newDocuments.Select(x => x.Id).ToList();
                search = false;
                start = true;
                step += 1;
                if (documentCount > Constants.AccountingDocumentBase.ExportedDocumentsCountMaxLimit)
                {
                  addErrorMessage = Resources.ExportDialog_Error_DocumentCountLimitFormat(Constants.AccountingDocumentBase.ExportedDocumentsCountMaxLimit);
                  h.AddError(addErrorMessage);
                }
                refresh.Invoke(null);
              }
            }
          }
          
          #endregion
          
        });
      dialog.Show();
      
      return returned;
    }
    
    /// <summary>
    /// Поиск документов в архиве.
    /// </summary>
    /// <returns>Кверик документов для выгрузки.</returns>
    private static IQueryable<IOfficialDocument> ExportDocumentDialogWithSearch()
    {
      Docflow.Structures.Module.IExportDialogSearch filter = null;
      IQueryable<IOfficialDocument> returned = null;

      var dialog = Dialogs.CreateInputDialog(Resources.ExportDialog_Search_Title);
      // Размеры подобраны на глаз.
      dialog.Height = 0;
      dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.Search;
      
      var properties = AccountingDocumentBases.Info.Properties;
      var unit = dialog.AddSelect(properties.BusinessUnit.LocalizedName, false, Company.BusinessUnits.Null);
      var counterparty = dialog.AddSelect(properties.Counterparty.LocalizedName, false, Parties.Counterparties.Null);
      
      var contract = dialog.AddSelect(Resources.ExportDialog_Search_Contract, false, Contracts.ContractualDocuments.Null)
        .Where(c => (unit.Value == null || Equals(c.BusinessUnit, unit.Value)) && (counterparty.Value == null || Equals(c.Counterparty, counterparty.Value)));

      var allowedKinds = new List<IDocumentKind>();
      
      var allowedAccountingDocumentKinds = Functions.DocumentKind.GetAvailableDocumentKinds(typeof(IAccountingDocumentBase))
        .Where(k => !Equals(k.DocumentType.DocumentTypeGuid, Constants.AccountingDocumentBase.IncomingInvoiceGuid) &&
               !Equals(k.DocumentType.DocumentTypeGuid, Constants.AccountingDocumentBase.OutgoingInvoiceGuid));
      allowedKinds.AddRange(allowedAccountingDocumentKinds);
      
      var allowedContractualDocumentKinds = Functions.DocumentKind.GetAvailableDocumentKinds(typeof(IContractualDocumentBase));
      allowedKinds.AddRange(allowedContractualDocumentKinds);
      allowedKinds = allowedKinds.OrderBy(k => k.Name).ToList();
      
      var kinds = dialog.AddSelectMany(Resources.ExportDialog_Search_DocumentKinds, false, Docflow.DocumentKinds.Null)
        .From(allowedKinds);
      var dateFrom = dialog.AddDate(Resources.ExportDialog_Search_DateFrom, false);
      var dateTo = dialog.AddDate(Resources.ExportDialog_Search_DateTo, false);
      
      var showDocs = dialog.Buttons.AddCustom(Resources.ExportDialog_Search_OnlySearch);
      var cancel = dialog.Buttons.AddCustom(Resources.ExportDialog_Cancel);
      
      // Фильтрация договоров по НОР и контрагентам.
      unit.SetOnValueChanged(u =>
                             {
                               if (u.NewValue != null && contract.Value != null && !Equals(contract.Value.BusinessUnit, u.NewValue))
                                 contract.Value = null;
                             });
      counterparty.SetOnValueChanged(cp =>
                                     {
                                       if (cp.NewValue != null && contract.Value != null && !Equals(contract.Value.Counterparty, cp.NewValue))
                                         contract.Value = null;
                                     });
      contract.SetOnValueChanged(c =>
                                 {
                                   if (c.NewValue != null)
                                   {
                                     unit.Value = c.NewValue.BusinessUnit;
                                     counterparty.Value = c.NewValue.Counterparty;
                                   }
                                 });
      
      dialog.SetOnButtonClick(
        (h) =>
        {
          #region Экран поиска
          if (h.Button == showDocs && dateTo.Value != null && dateFrom.Value != null && dateTo.Value < dateFrom.Value)
          {
            h.AddError(Sungero.Docflow.Resources.ExportDialog_Error_WrongDatePeriod);
            return;
          }
          
          if (h.Button == cancel)
          {
            unit.IsRequired = false;
            return;
          }
          
          filter = Docflow.Structures.Module.ExportDialogSearch
            .Create(unit.Value, counterparty.Value, contract.Value, dateFrom.Value, dateTo.Value, kinds.Value.ToList());
          if (h.Button == showDocs)
          {
            returned = Functions.Module.Remote.SearchByRequisites(filter);
          }
          #endregion
        });
      
      dialog.Show();
      
      return returned;
    }
    
    /// <summary>
    /// Проверить, приобретена ли лицензия на модуль Финансовый архив.
    /// </summary>
    /// <returns>True - если лицензия есть, иначе - false.</returns>
    [Public]
    public bool CheckFinancialArchiveLicense()
    {
      var moduleGuid = Constants.AccountingDocumentBase.FinancialArchiveUIGuid;
      if (!Sungero.Docflow.PublicFunctions.Module.Remote.IsModuleAvailableByLicense(moduleGuid))
      {
        Dialogs.NotifyMessage(Resources.NoFinancialArchiveLicense);
        return false;
      }
      return true;
    }
    
    #endregion
    
    #region Номенклатура дел
    
    /// <summary>
    /// Копирование номенклатуры дел на основании предыдущего периода.
    /// </summary>
    public virtual void CopyCaseFiles()
    {
      if (Users.Current.IsSystem != true &&
          !PublicFunctions.Module.Remote.IncludedInClerksRole())
      {
        Dialogs.ShowMessage(CaseFiles.Resources.CopyCaseFilesAccessMessage);
        return;
      }
      
      var copyStarted = this.ShowCaseFilesCopyDialog();
      if (copyStarted)
        Dialogs.NotifyMessage(CaseFiles.Resources.CopyCaseFilesNotifyMessage);
    }
    
    /// <summary>
    /// Показать диалог копирования номенклатуры.
    /// </summary>
    /// <returns>Копирование запущено: Да/Нет.</returns>
    public virtual bool ShowCaseFilesCopyDialog()
    {
      var dialog = Dialogs.CreateInputDialog(CaseFiles.Resources.CopyCaseFilesDialogTitle);
      dialog.HelpCode = Constants.CaseFile.CopyFilesDialogHelpCode;
      
      var targetYear = dialog.AddDate(CaseFiles.Resources.CopyCaseFilesDialogTargetYear, true,
                                      Calendar.Now.AddYears(1)).AsYear();
      var sourcePeriodStartDate = dialog.AddDate(CaseFiles.Resources.CopyCaseFilesDialogSourcePeriodStartDate, true,
                                                 Calendar.BeginningOfYear(Calendar.Today));
      var sourcePeriodEndDate = dialog.AddDate(CaseFiles.Resources.CopyCaseFilesDialogSourcePeriodEndDate, true,
                                               Calendar.EndOfYear(Calendar.Today));
      var defaultBusinessUnit = PublicFunctions.Module.GetDefaultBusinessUnit(Company.Employees.Current);
      var businessUnit = dialog.AddSelect(CaseFiles.Resources.CopyCaseFilesDialogBusinessUnit, false,
                                          defaultBusinessUnit);
      var department = dialog.AddSelect(CaseFiles.Resources.CopyCaseFilesDialogDepartment, false,
                                        Company.Departments.Null);
      if (defaultBusinessUnit != null)
        department.From(Company.PublicFunctions.BusinessUnit.Remote.GetAllDepartments(defaultBusinessUnit));
      
      var copyButton = dialog.Buttons.AddCustom(CaseFiles.Resources.CopyCaseFilesCopyButtonName);
      dialog.Buttons.Default = copyButton;
      dialog.Buttons.AddCancel();
      
      businessUnit.SetOnValueChanged((e) =>
                                     {
                                       department.Value = Company.Departments.Null;
                                       if (e.NewValue != null)
                                         department.From(Company.PublicFunctions.BusinessUnit.Remote.GetAllDepartments(e.NewValue));
                                       else
                                         department.From(Company.PublicFunctions.Department.Remote.GetVisibleDepartments());
                                     });
      
      dialog.SetOnRefresh((e) =>
                          {
                            copyButton.IsEnabled = true;
                            
                            // Если для исходного периода дата конца меньше даты начала,
                            // то кнопка "Создать" становится неактивной,
                            // а пользователю выводится соответствующее уведомление.
                            if (sourcePeriodStartDate.Value != null &&
                                sourcePeriodEndDate.Value != null &&
                                sourcePeriodEndDate.Value <= sourcePeriodStartDate.Value)
                            {
                              copyButton.IsEnabled = false;
                              e.AddError(CaseFiles.Resources.IncorrectDatesInSourcePeriod,
                                         sourcePeriodStartDate,
                                         sourcePeriodEndDate);
                              return;
                            }
                            
                            // Если год целевого периода меньше года исходного периода,
                            // то кнопка "Создать" становится неактивной,
                            // а пользователю выводится соответствующее уведомление.
                            if (sourcePeriodEndDate.Value != null &&
                                targetYear.Value != null &&
                                targetYear.Value.Value.Year < sourcePeriodEndDate.Value.Value.Year)
                            {
                              copyButton.IsEnabled = false;
                              e.AddError(CaseFiles.Resources.IncorrectTargetYear, targetYear);
                              return;
                            }
                          });
      
      var copyStarted = false;
      if (dialog.Show() == copyButton)
      {
        var targetPeriod = this.GetCaseFilesCopyDialogTargetPeriod(targetYear.Value.Value, null, null);
        var businessUnitId = businessUnit.Value != null ? businessUnit.Value.Id : -1;
        var departmentId = department.Value != null ? department.Value.Id : -1;
        Functions.CaseFile.Remote.CopyCaseFilesAsync(sourcePeriodStartDate.Value.Value,
                                                     sourcePeriodEndDate.Value.Value,
                                                     targetPeriod.DateFrom,
                                                     targetPeriod.DateTo,
                                                     businessUnitId,
                                                     departmentId);
        copyStarted = true;
      }
      
      return copyStarted;
    }
    
    /// <summary>
    /// Получить целевой период копирования номенклатуры.
    /// </summary>
    /// <param name="year">Год.</param>
    /// <param name="quarter">Квартал.</param>
    /// <param name="month">Месяц.</param>
    /// <returns>Структура дат с/по.</returns>
    /// <remarks>Параметры для квартала и месяца добавлены для удобства перекрытия.</remarks>
    /// <remarks>Расчёт периода в коробочном решении не зависит от квартала и месяца.</remarks>
    public virtual Structures.Module.DateTimePeriod GetCaseFilesCopyDialogTargetPeriod(DateTime year,
                                                                                       int? quarter,
                                                                                       int? month)
    {
      var period = Structures.Module.DateTimePeriod.Create();
      period.DateFrom = Calendar.BeginningOfYear(year);
      period.DateTo = Calendar.EndOfYear(year);
      return period;
    }
    
    #endregion
    
    #region Вызов отчетов
    
    /// <summary>
    /// Открыть отчет "Исполнительская дисциплина сотрудника".
    /// </summary>
    /// <param name="employeeId">Ид сотрудника.</param>
    /// <param name="periodBegin">Начало периода.</param>
    /// <param name="periodEnd">Конец периода.</param>
    [Public]
    public virtual void OpenEmployeeAssignmentsReport(int employeeId, DateTime periodBegin, DateTime periodEnd)
    {
      var report = Sungero.Docflow.Reports.GetEmployeeAssignmentsReport();

      report.Employee = Company.PublicFunctions.Module.Remote.GetEmployeeById(employeeId);
      report.PeriodBegin = periodBegin;
      report.PeriodEnd = periodEnd;
      report.Open();
    }
    
    /// <summary>
    /// Открыть отчет "Исполнительская дисциплина сотрудника".
    /// </summary>
    /// <param name="employeeid">Ид сотрудника.</param>
    /// <param name="periodbegin">Начало периода.</param>
    /// <param name="periodend">Конец периода.</param>
    [Hyperlink]
    public void OpenEmployeeAssignmentsReport(string employeeid, string periodbegin, string periodend)
    {
      int employeeId;
      if (!int.TryParse(employeeid, out employeeId))
      {
        Logger.ErrorFormat("OpenReport. Failed parse id {0}", employeeid);
        return;
      }
      
      DateTime periodBegin;
      if (!Calendar.TryParseDateTime(periodbegin, out periodBegin))
      {
        Logger.ErrorFormat("OpenReport. Failed parse period begin {0}", periodbegin);
        return;
      }
      
      DateTime periodEnd;
      if (!Calendar.TryParseDateTime(periodend, out periodEnd))
      {
        Logger.ErrorFormat("OpenReport. Failed parse period end {0}", periodend);
        return;
      }
      
      Functions.Module.OpenEmployeeAssignmentsReport(employeeId, periodBegin, periodEnd);
    }
    
    /// <summary>
    /// Открыть отчет "Исполнительская дисциплина по сотрудникам".
    /// </summary>
    /// <param name="businessUnit">Наша организация.</param>
    /// <param name="department">Подразделение.</param>
    /// <param name="businessUnitIds">Список ид НОР.</param>
    /// <param name="departmentIds">Список ид подразделений.</param>
    /// <param name="periodBegin">Начало периода.</param>
    /// <param name="periodEnd">Конец периода.</param>
    /// <param name="widgetParameter">Локализованное имя параметра-перечисления виджетов.</param>
    /// <param name="unwrap">Разворачивать подчиненные подразделения.</param>
    /// <param name="withSubstitution">Учитывать замещение.</param>
    /// <param name="sortByAssignmentCompletion">Сортировать по исполнительской дисциплине.</param>
    [Public]
    public virtual void OpenEmployeesAssignmentCompletionReport(IBusinessUnit businessUnit, IDepartment department, List<int> businessUnitIds,
                                                                List<int> departmentIds, DateTime periodBegin, DateTime periodEnd,
                                                                string widgetParameter, bool unwrap, bool withSubstitution, bool sortByAssignmentCompletion)
    {
      var report = Sungero.Docflow.Reports.GetEmployeesAssignmentCompletionReport();
      
      if (departmentIds.Any())
        report.DepartmentIds.AddRange(departmentIds.Select(d => (int?)d).ToList());

      if (businessUnitIds.Any())
        report.BusinessUnitIds.AddRange(businessUnitIds.Select(d => (int?)d).ToList());
      
      if (businessUnit != null)
        report.BusinessUnit = businessUnit;
      
      if (department != null)
        report.Department = department;
      
      report.PeriodBegin = periodBegin;
      report.PeriodEnd = periodEnd;
      report.Unwrap = unwrap;
      report.WidgetParameter = widgetParameter;
      report.WithSubstitution = withSubstitution;
      report.SortByAssignmentCompletion = sortByAssignmentCompletion;
      report.Open();
    }
    
    /// <summary>
    /// Открыть отчет "Исполнительская дисциплина по сотрудникам".
    /// </summary>
    /// <param name="businessunitid">Ид нашей организации.</param>
    /// <param name="departmentid">Ид подразделения.</param>
    /// <param name="periodbegin">Начало периода.</param>
    /// <param name="periodend">Конец периода.</param>
    /// <param name="unwrap">Разворачивать подчиненные подразделения.</param>
    [Hyperlink]
    public void OpenEmployeesAssignmentCompletionReport(string businessunitid, string departmentid, string periodbegin, string periodend, string unwrap)
    {
      int businessUnitId;
      if (!int.TryParse(businessunitid, out businessUnitId))
      {
        Logger.ErrorFormat("OpenEmployeesAssignmentCompletionReport. Failed parse business unit id {0}", businessunitid);
        return;
      }

      int departmentId;
      if (!int.TryParse(departmentid, out departmentId))
      {
        Logger.ErrorFormat("OpenEmployeesAssignmentCompletionReport. Failed parse department id {0}", departmentid);
        return;
      }
      
      DateTime periodBegin;
      if (!Calendar.TryParseDateTime(periodbegin, out periodBegin))
      {
        Logger.ErrorFormat("OpenEmployeesAssignmentCompletionReport. Failed parse period begin {0}", periodbegin);
        return;
      }
      
      DateTime periodEnd;
      if (!Calendar.TryParseDateTime(periodend, out periodEnd))
      {
        Logger.ErrorFormat("OpenEmployeesAssignmentCompletionReport. Failed parse period end {0}", periodend);
        return;
      }
      
      bool withUnwrap;
      if (!bool.TryParse(unwrap, out withUnwrap))
      {
        Logger.ErrorFormat("OpenEmployeesAssignmentCompletionReport. Failed parse unwrap {0}", unwrap);
        return;
      }
      
      var departmentIds = departmentId == 0 ? new List<int>() : new List<int>() { departmentId };
      
      var businessUnitIds = businessUnitId == 0 ? new List<int>() : new List<int>() { businessUnitId };
      
      var businessUnit = businessUnitId != 0 ?
        Company.PublicFunctions.BusinessUnit.Remote.GetBusinessUnit(businessUnitId) :
        Company.BusinessUnits.Null;
      
      var department = departmentId != 0 ?
        Company.PublicFunctions.Department.Remote.GetDepartment(departmentId) :
        Company.Departments.Null;
      
      Functions.Module.OpenEmployeesAssignmentCompletionReport(businessUnit, department, businessUnitIds, departmentIds, periodBegin, periodEnd, null, withUnwrap, true, true);
    }
    
    /// <summary>
    /// Открыть отчет "Исполнительская дисциплина по подразделениям".
    /// </summary>
    /// <param name="departmentIds">Ид подразделений.</param>
    /// <param name="periodBegin">Начало периода.</param>
    /// <param name="periodEnd">Конец периода.</param>
    /// <param name="widgetParameter">Локализованное имя параметра-перечисления виджетов.</param>
    /// <param name="unwrap">Разворачивать подчиненные подразделения.</param>
    /// <param name="withSubstitution">Учитывать замещение.</param>
    [Public]
    public virtual void OpenDepartmentsAssignmentCompletionReport(List<int> departmentIds, DateTime periodBegin, DateTime periodEnd, string widgetParameter, bool unwrap, bool withSubstitution)
    {
      var report = Sungero.Docflow.Reports.GetDepartmentsAssignmentCompletionReport();
      
      if (departmentIds.Any())
        report.DepartmentIds.AddRange(departmentIds.Select(d => (int?)d).ToList());
      report.PeriodBegin = periodBegin;
      report.PeriodEnd = periodEnd;
      report.Unwrap = unwrap;
      report.WidgetParameter = widgetParameter;
      report.WithSubstitution = withSubstitution;
      report.Open();
    }

    #endregion

    #region Сравнение документов

    /// <summary>
    /// Отобразить результат сравнения документов.
    /// </summary>
    /// <param name="comparisonInfoId">ИД справочника с результатом сравнения.</param>
    [Hyperlink(DisplayNameResource = "DocumentComparisonResults")]
    public void ShowDocumentComparisonResults(int comparisonInfoId)
    {
      var comparisonInfo = Functions.Module.Remote.GetDocumentComparisonInfoById(comparisonInfoId);
      if (comparisonInfo != null)
      {
        this.ShowDocumentComparisonResults(comparisonInfo);
      }
      else
      {
        Dialogs.NotifyMessage(Resources.ErrorWhileComparingDocuments);
        Logger.ErrorFormat("ShowDocumentComparisonResults. Document comparison info not found (cmpid={0}).", comparisonInfoId);
      }
    }
    
    /// <summary>
    /// Отобразить результат сравнения документов.
    /// </summary>
    /// <param name="comparisonInfo">Запись справочника с результатом сравнения.</param>
    public void ShowDocumentComparisonResults(IDocumentComparisonInfo comparisonInfo)
    {
      if (comparisonInfo.DifferencesCount.HasValue && comparisonInfo.DifferencesCount.Value > 0)
      {
        var resultPdfName = string.Format("{0}.{1}", comparisonInfo.Name, Constants.OfficialDocument.PdfExtension);
        comparisonInfo.ResultPdf.Open(resultPdfName);
      }
      else if (!string.IsNullOrEmpty(comparisonInfo.ErrorMessage))
      {
        Dialogs.NotifyMessage(string.Format("{0}{1}{2}{3}", comparisonInfo.ErrorMessage, Environment.NewLine, Environment.NewLine, comparisonInfo.Name));
      }
      else
      {
        Dialogs.NotifyMessage(string.Format("{0}{1}{2}{3}", Resources.NoDiffInDocuments, Environment.NewLine, Environment.NewLine, comparisonInfo.Name));
      }
    }
    
    /// <summary>
    /// Сформировать имя итогового документа с результатом сравнения.
    /// </summary>
    /// <param name="comparisonInfo">Запись справочника с результатом сравнения.</param>
    /// <returns>Строка с наименованием.</returns>
    [Public]
    public virtual string GetComparisonResultPdfName(Sungero.Docflow.IDocumentComparisonInfo comparisonInfo)
    {
      var firstDocument = ElectronicDocuments.GetAll(d => d.Id == comparisonInfo.FirstDocumentId).FirstOrDefault();
      var firstVersion = firstDocument.Versions.FirstOrDefault(v => v.Number == comparisonInfo.FirstVersionNumber);
      
      var secondDocument = ElectronicDocuments.GetAll(d => d.Id == comparisonInfo.SecondDocumentId).FirstOrDefault();
      var secondVersion = secondDocument.Versions.FirstOrDefault(v => v.Number == comparisonInfo.SecondVersionNumber);
      
      return this.GetComparisonResultPdfName(firstDocument, firstVersion.Number.Value, secondDocument, secondVersion.Number.Value);
    }
    
    /// <summary>
    /// Сформировать имя итогового документа с результатом сравнения.
    /// </summary>
    /// <param name="firstDocument">Документ с версией до изменения.</param>
    /// <param name="firstVersionNumber">Номер версии до изменения.</param>
    /// <param name="secondDocument">Документ с версией после изменения.</param>
    /// <param name="secondVersionNumber">Номер версии после изменения.</param>
    /// <returns>Строка с наименованием.</returns>
    [Public]
    public virtual string GetComparisonResultPdfName(IElectronicDocument firstDocument, int firstVersionNumber, IElectronicDocument secondDocument, int secondVersionNumber)
    {
      var resultName = Sungero.Docflow.Functions.Module.Remote.GetDocumentComparisonInfoName(firstDocument, firstVersionNumber, secondDocument, secondVersionNumber);
      return string.Format("{0}.{1}", resultName, Constants.OfficialDocument.PdfExtension);
    }
    
    /// <summary>
    /// Открыть тело документа.
    /// </summary>
    /// <param name="documentId">ИД документа.</param>
    /// <param name="versionNumber">Номер версии.</param>
    [Hyperlink(DisplayNameResource = "ShowDocumentVersion")]
    public void ShowDocumentVersion(int documentId, int versionNumber)
    {
      var document = Functions.Module.Remote.GetElectronicDocumentById(documentId);
      if (document != null)
      {
        var version = document.Versions.FirstOrDefault(v => v.Number == versionNumber);
        if (version != null)
          version.Open();
      }
    }
    
    #endregion
    
    /// <summary>
    /// Проверить, что документ зашифрован.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>True - если зашифрован.</returns>
    [Public]
    public virtual bool IsDocumentEncrypted(IElectronicDocument document)
    {
      // Переполучаем документ, чтобы данные были свежими.
      var currentDocument = Functions.Module.Remote.GetElectronicDocumentById(document.Id);
      return currentDocument.IsEncrypted;
    }
  }
}