OfficialDocumentSharedFunctions.cs 71.2 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Sungero.Company;
using Sungero.Content;
using Sungero.Core;
using Sungero.CoreEntities;
using Sungero.Docflow.DocumentKind;
using Sungero.Docflow.OfficialDocument;
using Sungero.Domain.Shared;

namespace Sungero.Docflow.Shared
{
  partial class OfficialDocumentFunctions
  {
    
    #region Регистрация
    
    /// <summary>
    /// Получить ИД ведущего документа.
    /// </summary>
    /// <returns>ИД документа либо 0.</returns>
    public virtual int GetLeadDocumentId()
    {
      return _obj.LeadingDocument != null ? _obj.LeadingDocument.Id : 0;
    }
    
    /// <summary>
    /// Получить номер ведущего документа.
    /// </summary>
    /// <returns>Номер документа либо пустая строка.</returns>
    public virtual string GetLeadDocumentNumber()
    {
      // Виртуальная функция. Переопределено в потомках.
      return string.Empty;
    }
    
    /// <summary>
    /// Зарегистрировать документ.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="documentRegister">Журнал.</param>
    /// <param name="registrationDate">Дата.</param>
    /// <param name="registrationNumber">Номер регистрации.</param>
    /// <param name="numberReservation">Признак резервирования.</param>
    /// <param name="needSaveDocument">Признак необходимости сохранения документа.</param>
    [Public]
    public static void RegisterDocument(IOfficialDocument document, IDocumentRegister documentRegister,
                                        DateTime? registrationDate, string registrationNumber, bool? numberReservation, bool needSaveDocument)
    {
      // Определить новый статус документа.
      var registrationState = RegistrationState.Registered;
      if (documentRegister == null && !registrationDate.HasValue)
        registrationState = RegistrationState.NotRegistered;
      else if (numberReservation ?? false)
        registrationState = RegistrationState.Reserved;
      
      // Установить новый статус документа.
      document.RegistrationState = registrationState;
      
      // Обновить регистрационные данные.
      document.DocumentRegister = documentRegister;
      document.RegistrationDate = registrationDate;
      document.RegistrationNumber = registrationNumber;
      FillCaseFileAndDeliveryMethod(document, documentRegister);
      
      // Для регистрируемых документов завершить верификацию.
      if (document.RegistrationState == RegistrationState.Registered && document.VerificationState == VerificationState.InProcess &&
          document.DocumentKind.NumberingType == Docflow.DocumentKind.NumberingType.Registrable)
        document.VerificationState = VerificationState.Completed;
      
      if (needSaveDocument)
        document.Save();
    }
    
    /// <summary>
    /// Заполнить дело и способ доставки.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="documentRegister">Журнал регистрации.</param>
    [Public]
    public static void FillCaseFileAndDeliveryMethod(IOfficialDocument document, IDocumentRegister documentRegister)
    {
      // Определить дело и способ доставки.
      var caseFile = CaseFiles.Null;
      var deliveryMethod = MailDeliveryMethods.Null;
      var direction = documentRegister != null ? documentRegister.DocumentFlow : null;
      var personalSetting = Docflow.PublicFunctions.PersonalSetting.GetPersonalSettings(null);
      if (personalSetting != null)
      {
        if (direction == Docflow.DocumentRegister.DocumentFlow.Incoming)
        {
          caseFile = personalSetting.IncomingCaseFile;
          deliveryMethod = personalSetting.IncomingDeliveryMethod;
        }
        if (direction == Docflow.DocumentRegister.DocumentFlow.Outgoing)
        {
          caseFile = personalSetting.OutgoingCaseFile;
          deliveryMethod = personalSetting.OutgoingDeliveryMethod;
        }
        if (direction == Docflow.DocumentRegister.DocumentFlow.Inner)
        {
          caseFile = personalSetting.InnerCaseFile;
          deliveryMethod = personalSetting.InnerDeliveryMethod;
        }
      }
      
      // Дело должно быть действующим, период - актуальным. Иначе дело не указываем.
      if (!(caseFile != null &&
            caseFile.Status == CoreEntities.DatabookEntry.Status.Active &&
            caseFile.StartDate <= Calendar.UserToday &&
            Calendar.UserToday <= (caseFile.EndDate ?? DateTime.MaxValue)))
        caseFile = null;
      
      // Установить значения реквизитов в документе.
      if (document.CaseFile == null && caseFile != null)
      {
        document.CaseFile = caseFile;
        document.PlacedToCaseFileDate = Calendar.UserToday;
      }
      
      var outgoingDocument = OutgoingDocumentBases.As(document);
      if (outgoingDocument != null && outgoingDocument.IsManyAddressees == true)
      {
        var addressees = outgoingDocument.Addressees.Where(a => a.DeliveryMethod == null);
        foreach (var addressee in addressees)
          addressee.DeliveryMethod = deliveryMethod;
      }
      else if (document.DeliveryMethod == null)
        document.DeliveryMethod = deliveryMethod;
    }
    
    /// <summary>
    /// Проверять рег. номер на уникальность.
    /// </summary>
    /// <returns>True - проверять, False - не проверять.</returns>
    public virtual bool CheckRegistrationNumberUnique()
    {
      return true;
    }
    
    /// <summary>
    /// Получить описание для диалога отмены регистрации.
    /// </summary>
    /// <param name="settingType">Тип настройки.</param>
    /// <returns>Описание.</returns>
    public virtual string GetCancelRegistrationDialogDescription(Enumeration? settingType)
    {
      var description = Docflow.Resources.CancelRegistrationDescription;
      if (settingType == Docflow.RegistrationSetting.SettingType.Reservation)
        return Docflow.Resources.CancelReservationDescription;
      
      if (settingType == Docflow.RegistrationSetting.SettingType.Numeration)
        return Docflow.Resources.CancelNumberingDescription;
      
      return Docflow.Resources.CancelRegistrationDescription;
    }
    
    #endregion
    
    #region Validation
    
    /// <summary>
    /// Установить обязательность свойств в зависимости от заполненных данных.
    /// </summary>
    public virtual void SetRequiredProperties()
    {
      _obj.State.Properties.BusinessUnit.IsRequired = _obj.Info.Properties.BusinessUnit.IsRequired ||
        (_obj.DocumentKind != null && _obj.DocumentKind.NumberingType != NumberingType.NotNumerable);

      _obj.State.Properties.Department.IsRequired = _obj.Info.Properties.Department.IsRequired ||
        (_obj.DocumentKind != null && _obj.DocumentKind.NumberingType != NumberingType.NotNumerable);

      _obj.State.Properties.Subject.IsRequired = _obj.Info.Properties.Subject.IsRequired ||
        (_obj.DocumentKind != null &&
         (_obj.DocumentKind.NumberingType == NumberingType.Registrable ||
          _obj.DocumentKind.GenerateDocumentName == true));
      
      _obj.State.Properties.DocumentRegister.IsRequired = _obj.RegistrationState != RegistrationState.NotRegistered;
      
      _obj.State.Properties.RegistrationDate.IsRequired = _obj.RegistrationState != RegistrationState.NotRegistered;
    }
    
    #endregion
    
    #region История

    /// <summary>
    /// Получить операцию истории "Регистрация".
    /// </summary>
    /// <returns>Операция Регистрация.</returns>
    [PublicAttribute]
    public static string GetRegistrationOperation()
    {
      return Constants.OfficialDocument.Operation.Registration;
    }
    
    #endregion
    
    #region Работа с закладкой "Выдача"
    
    /// <summary>
    /// Получить удаленные строки выдачи.
    /// </summary>
    /// <param name="entity">Документ.</param>
    /// <returns>Удаленная выдача.</returns>
    public static System.Collections.Generic.IEnumerable<IOfficialDocumentTracking> GetDeletedTrackingRecords(IOfficialDocument entity)
    {
      var deletedTrackingRecords = entity.State.Properties.Tracking.Deleted;
      
      var deletedRecords = deletedTrackingRecords
        .Where(l => l.ReturnTask != null &&
               l.ReturnTask.Status == Sungero.Workflow.Task.Status.InProcess &&
               l.ReturnTask.Info.Name == CheckReturnTasks.Info.Name);
      var records = entity.Tracking
        .Where(l => l.ReturnTask != null &&
               l.ReturnTask.Status == Sungero.Workflow.Task.Status.InProcess &&
               l.ReturnTask.Info.Name == CheckReturnTasks.Info.Name &&
               l.ReturnDeadline == null &&
               CheckReturnTasks.As(l.ReturnTask).Deadline != l.ReturnDeadline);
      return (IEnumerable<IOfficialDocumentTracking>)deletedRecords.Concat(records);
    }
    
    /// <summary>
    /// Получить строки выдачи с измененным сотрудником.
    /// </summary>
    /// <param name="entity">Документ.</param>
    /// <returns>Выдача с измененным сотрудником.</returns>
    public static System.Collections.Generic.IEnumerable<IOfficialDocumentTracking> GetTrackingRecordsWithEmployeeChanged(IOfficialDocument entity)
    {
      var changedRecords = entity.State.Properties.Tracking.Changed;
      return (IEnumerable<IOfficialDocumentTracking>)changedRecords
        .Where(l => l.ReturnTask != null && l.ReturnTask.Info.Name == CheckReturnTasks.Info.Name &&
               !Equals(CheckReturnTasks.As(l.ReturnTask).Assignee, l.DeliveredTo));
    }
    
    /// <summary>
    /// Получить строки выдачи с задачами, которые необходимо выполнить.
    /// </summary>
    /// <param name="entity">Документ.</param>
    /// <returns>Возвращенная выдача.</returns>
    public static System.Collections.Generic.IEnumerable<IOfficialDocumentTracking> GetChangedTrackingRecordsWithTasksInProcess(IOfficialDocument entity)
    {
      var changedRecords = entity.State.Properties.Tracking.Changed;
      return (IEnumerable<IOfficialDocumentTracking>)changedRecords
        .Where(l => l.ReturnTask != null &&
               l.ReturnTask.Status == Sungero.Workflow.Task.Status.InProcess &&
               l.ReturnDate != null && l.ExternalLinkId == null);
    }
    
    /// <summary>
    /// Получить строки выдачи с измененным сроком возврата.
    /// </summary>
    /// <param name="entity">Документ.</param>
    /// <returns>Выдача с измененным сроком.</returns>
    public static System.Collections.Generic.IEnumerable<IOfficialDocumentTracking> GetTrackingRecordsWithDeadlineChanged(IOfficialDocument entity)
    {
      return entity.Tracking.Where(l => l.ReturnTask != null &&
                                   l.ReturnTask.Status == Sungero.Workflow.Task.Status.InProcess &&
                                   l.ReturnTask.Info.Name == CheckReturnTasks.Info.Name &&
                                   l.ReturnDeadline != null &&
                                   CheckReturnTasks.As(l.ReturnTask).Deadline != l.ReturnDeadline);
    }

    #endregion

    #region Получение списка журналов регистрации по документу
    
    /// <summary>
    /// Получить отфильтрованные журналы регистрации по документу.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>Журналы по документу.</returns>
    public static List<int> GetDocumentRegistersByDocument(IOfficialDocument document)
    {
      var settingType = GetSettingType(document);
      return GetDocumentRegistersIdsByDocument(document, settingType);
    }
    
    /// <summary>
    ///  Получить отфильтрованные журналы регистрации по документу.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="settingType">Тип регистрации.</param>
    /// <returns>Журналы.</returns>
    [Public, Obsolete("Используйте метод GetDocumentRegistersIdsByDocument.")]
    public static List<IDocumentRegister> GetDocumentRegistersByDocument(IOfficialDocument document, Enumeration? settingType)
    {
      var emptyList = new List<IDocumentRegister>();
      var documentKind = document.DocumentKind;
      if (documentKind == null)
        return emptyList;
      
      var isClerk = document.AccessRights.CanRegister();
      if (!isClerk || settingType == Docflow.RegistrationSetting.SettingType.Numeration)
      {
        var setting = PublicFunctions.Module.Remote.GetRegistrationSettings(settingType, document.BusinessUnit, documentKind, document.Department).FirstOrDefault();
        return setting != null ? new List<IDocumentRegister> { setting.DocumentRegister } : emptyList;
      }
      
      return Functions.DocumentRegister.Remote.GetDocumentRegistersByParams(document.DocumentKind, document.BusinessUnit, document.Department, settingType, true);
    }
    
    /// <summary>
    ///  Получить ИД отфильтрованных журналов регистрации по документу.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <param name="settingType">Тип регистрации.</param>
    /// <returns>Журналы.</returns>
    [Public]
    public static List<int> GetDocumentRegistersIdsByDocument(IOfficialDocument document, Enumeration? settingType)
    {
      var emptyList = new List<int>();
      var documentKind = document.DocumentKind;
      if (documentKind == null)
        return emptyList;
      
      var isClerk = document.AccessRights.CanRegister();
      if (!isClerk || settingType == Docflow.RegistrationSetting.SettingType.Numeration)
      {
        var setting = PublicFunctions.Module.Remote.GetRegistrationSettings(settingType, document.BusinessUnit, documentKind, document.Department).FirstOrDefault();
        return setting != null ? new List<int> { setting.DocumentRegister.Id } : emptyList;
      }
      
      return Functions.DocumentRegister.Remote.GetDocumentRegistersIdsByParams(document.DocumentKind, document.BusinessUnit, document.Department, settingType, true);
    }
    
    /// <summary>
    /// Имеются ли подходящие журналы регистрации по документу.
    /// </summary>
    /// <param name="settingType">Тип регистрации.</param>
    /// <returns>True - если есть подходящие журналы.</returns>
    [Public]
    public virtual bool HasDocumentRegistersByDocument(Enumeration? settingType)
    {
      if (_obj.DocumentKind == null)
        return false;
      
      var isClerk = _obj.AccessRights.CanRegister();
      if (!isClerk || settingType == Docflow.RegistrationSetting.SettingType.Numeration)
        return PublicFunctions.Module.Remote.GetRegistrationSettings(settingType, _obj.BusinessUnit, _obj.DocumentKind, _obj.Department).Any();
      
      return Functions.DocumentRegister.Remote.HasDocumentRegistersByParams(_obj.DocumentKind, _obj.BusinessUnit, _obj.Department, settingType, true);
    }
    
    /// <summary>
    /// Проверить возможность изменения реквизитов или отмены регистрации.
    /// </summary>
    /// <returns>True, если операции можно выполнить.</returns>
    /// <remarks>Только для регистрируемых журналов.</remarks>
    [Public]
    public virtual bool CanChangeRequisitesOrCancelRegistration()
    {
      // Разрешаем сначала изменить реквизиты с очисткой журнала, а потом отменить регистрацию.
      if (_obj.DocumentRegister == null)
        return true;
      
      // Разрешаем, если это резервирование.
      if (_obj.RegistrationState == Docflow.OfficialDocument.RegistrationState.Reserved)
        return true;
      
      // Только для регистрируемых журналов.
      if (_obj.DocumentRegister.RegisterType != Docflow.DocumentRegister.RegisterType.Registration)
        return true;
      
      return _obj.AccessRights.CanRegister() && Employees.AllRecipientIds.Contains(_obj.DocumentRegister.RegistrationGroup.Id);
    }
    
    /// <summary>
    /// Получить тип настроек.
    /// </summary>
    /// <param name="document">Документ.</param>
    /// <returns>Тип настроек.</returns>
    public static Enumeration? GetSettingType(IOfficialDocument document)
    {
      if (document.DocumentKind.NumberingType == Docflow.DocumentKind.NumberingType.Numerable)
        return Docflow.RegistrationSetting.SettingType.Numeration;
      else
        return document.RegistrationState == RegistrationState.Registered ?
          Docflow.RegistrationSetting.SettingType.Registration :
          Docflow.RegistrationSetting.SettingType.Reservation;
    }
    
    #endregion
    
    #region Отображение панели реквизитов
    
    /// <summary>
    /// Обновить карточку документа.
    /// </summary>
    public virtual void RefreshDocumentForm()
    {
      // Тип нумерации.
      var isNumerable = (_obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Numerable) || _obj.ExchangeState.HasValue;
      var isNotifiable = (_obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Registrable) || _obj.ExchangeState.HasValue;
      
      // Параметры формы.
      var formParams = ((IExtendedEntity)_obj).Params;
      var repeatRegister = formParams.ContainsKey(Sungero.Docflow.Constants.OfficialDocument.RepeatRegister) &&
        (bool)formParams[Sungero.Docflow.Constants.OfficialDocument.RepeatRegister];
      
      // Показывать ли свойства.
      var needShow = Functions.OfficialDocument.NeedShowRegistrationPane(_obj, isNotifiable || isNumerable);
      Functions.OfficialDocument.ChangeRegistrationPaneVisibility(_obj, needShow, repeatRegister);
      
      var isNotRegistered = repeatRegister || _obj.RegistrationState == RegistrationState.NotRegistered;
      
      Functions.OfficialDocument.ChangeDocumentPropertiesAccess(_obj, isNotRegistered, repeatRegister);
      
      // Показывать ли основание подписания.
      Functions.OfficialDocument.ChangeOurSigningReasonVisibility(_obj);
    }
    
    /// <summary>
    /// Признак необходимости отображения панели регистрации.
    /// </summary>
    /// <param name="additionalCondition">Дополнительное условие при наследовании.</param>
    /// <returns>True, если надо показать панель.</returns>
    public virtual bool NeedShowRegistrationPane(bool additionalCondition)
    {
      // Параметры формы.
      var showParam = false;
      var formParams = ((IExtendedEntity)_obj).Params;
      if (formParams.ContainsKey(Sungero.Docflow.Constants.OfficialDocument.ShowParam))
        showParam = (bool)formParams[Sungero.Docflow.Constants.OfficialDocument.ShowParam];
      else
      {
        var showRegPane = Functions.PersonalSetting.Remote.GetShowRegistrationPaneParam(null);
        var onVerification = _obj.VerificationState == Docflow.OfficialDocument.VerificationState.InProcess;
        showParam = showRegPane && additionalCondition ||
          onVerification ||
          Functions.OfficialDocument.DefaultRegistrationPaneVisibility(_obj);
        formParams[Sungero.Docflow.Constants.OfficialDocument.ShowParam] = showParam;
      }

      return showParam;
    }
    
    /// <summary>
    /// Сменить доступность реквизитов документа.
    /// </summary>
    /// <param name="isEnabled">True, если свойства должны быть доступны.</param>
    /// <param name="repeatRegister">Перерегистрация.</param>
    public virtual void ChangeDocumentPropertiesAccess(bool isEnabled, bool repeatRegister)
    {
      if (_obj.VerificationState == VerificationState.InProcess && this.IsNumerationSucceed())
      {
        this.EnableRequisitesForVerification();
      }
      else
      {
        var isNotifiable = _obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Registrable;
        var canRegister = _obj.AccessRights.CanRegister();
        var properties = _obj.State.Properties;
        var projectIsRequired = _obj.Info.Properties.Project.IsRequired || _obj.DocumentKind != null && _obj.DocumentKind.ProjectsAccounting == true;
        properties.Name.IsEnabled = _obj.DocumentKind == null || (!_obj.DocumentKind.GenerateDocumentName.Value && isEnabled);
        properties.DocumentKind.IsEnabled = isEnabled && !repeatRegister;
        properties.Subject.IsEnabled = isEnabled;
        properties.Project.IsVisible = projectIsRequired;
        
        // Наша организация должна переключаться во всех наследниках.
        properties.BusinessUnit.IsEnabled = isEnabled;
        
        // При перерегистрации НОР недоступна, если в журнале есть разрез по НОР или в формате номера журнала есть код НОР.
        var documentRegister = _obj.DocumentRegister;
        var businessUnitCodeIncludedInNumber = repeatRegister && documentRegister != null &&
          documentRegister.NumberFormatItems.Any(n => n.Element == DocumentRegisterNumberFormatItems.Element.BUCode);
        var businessUnitSectionIncludedInRegister = repeatRegister && documentRegister != null &&
          documentRegister.NumberingSection == Docflow.DocumentRegister.NumberingSection.BusinessUnit;
        properties.BusinessUnit.IsEnabled = isEnabled && !businessUnitCodeIncludedInNumber && !businessUnitSectionIncludedInRegister;
        
        // При перерегистрации подразделение недоступно, если в журнале есть разрез по подразделению или в формате номера журнала есть код подразделения.
        var departmentCodeIncludedInNumber = repeatRegister && documentRegister != null &&
          documentRegister.NumberFormatItems.Any(n => n.Element == DocumentRegisterNumberFormatItems.Element.DepartmentCode);
        var departmentSectionIncludedInRegister = repeatRegister && documentRegister != null &&
          documentRegister.NumberingSection == Docflow.DocumentRegister.NumberingSection.Department;
        properties.Department.IsEnabled = isEnabled && !departmentCodeIncludedInNumber && !departmentSectionIncludedInRegister;
        
        // При перерегистрации контрагент недоступен, если в формате номера журнала есть код контрагента.
        var counterpartyCodeIncludedInNumber = repeatRegister && documentRegister != null &&
          documentRegister.NumberFormatItems.Any(n => n.Element == DocumentRegisterNumberFormatItems.Element.CPartyCode);
        this.ChangeCounterpartyPropertyAccess(isEnabled, counterpartyCodeIncludedInNumber);
        
        // "Подготовил" доступно только регистраторам указанного документопотока.
        properties.Assignee.IsEnabled = canRegister;
        
        // Проверить, что поле "Исполнитель" присутствует на карточке, т.к. код ниже содержит запрос на СП.
        if (properties.Assignee.IsVisible)
        {
          // Для зарегистрированных документов "Исполнитель" должно быть доступно только группе регистрации.
          if (canRegister && isNotifiable && _obj.AccessRights.CanUpdate() && _obj.RegistrationState == RegistrationState.Registered &&
              documentRegister != null && documentRegister.RegistrationGroup != null)
          {
            // Парамсы формы.
            var formParams = ((IExtendedEntity)_obj).Params;
            var canChange = formParams.ContainsKey(Constants.OfficialDocument.CanChangeAssignee);
            if (canChange)
              canChange = (bool)formParams[Constants.OfficialDocument.CanChangeAssignee];
            else
            {
              canChange = Functions.OfficialDocument.Remote.CanChangeAssignee(_obj);
              formParams[Constants.OfficialDocument.CanChangeAssignee] = canChange;
            }
            
            properties.Assignee.IsEnabled = canChange;
          }
        }
      }
      
      this.EnableRegistrationNumberAndDate();
    }
    
    /// <summary>
    /// Создать кеш параметров.
    /// </summary>
    [Public]
    public virtual void CreateParamsCache()
    {
      var parameters = Functions.OfficialDocument.Remote.GetOfficialDocumentParams(_obj);
      
      var formParams = ((IExtendedEntity)_obj).Params;
      
      if (parameters.HasReservationSetting.HasValue)
        formParams[Sungero.Docflow.Constants.OfficialDocument.HasReservationSetting] = parameters.HasReservationSetting;
      
      if (parameters.HasNumerationSetting.HasValue)
        formParams[Sungero.Docflow.Constants.OfficialDocument.HasNumerationSetting] = parameters.HasNumerationSetting;
      
      if (parameters.CanChangeAssignee.HasValue)
        formParams[Constants.OfficialDocument.CanChangeAssignee] = parameters.CanChangeAssignee;
      
      if (parameters.NeedShowRegistrationPane.HasValue)
      {
        var isNumerable = (_obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Numerable) || _obj.ExchangeState.HasValue;
        var isNotifiable = (_obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Registrable) || _obj.ExchangeState.HasValue;
        var additionalCondition = isNotifiable || isNumerable;
        
        formParams[Sungero.Docflow.Constants.OfficialDocument.ShowParam] = (bool)parameters.NeedShowRegistrationPane && additionalCondition ||
          _obj.VerificationState == Docflow.OfficialDocument.VerificationState.InProcess ||
          Functions.OfficialDocument.DefaultRegistrationPaneVisibility(_obj);
      }
    }
    
    /// <summary>
    /// Сменить доступность поля Контрагент.
    /// </summary>
    /// <param name="isEnabled">Признак доступности поля. TRUE - поле доступно.</param>
    /// <param name="counterpartyCodeInNumber">Признак вхождения кода контрагента в формат номера. TRUE - входит.</param>
    public virtual void ChangeCounterpartyPropertyAccess(bool isEnabled, bool counterpartyCodeInNumber)
    {
      var enabledState = !(_obj.InternalApprovalState == Docflow.OfficialDocument.InternalApprovalState.OnApproval ||
                           _obj.InternalApprovalState == Docflow.OfficialDocument.InternalApprovalState.PendingSign ||
                           _obj.InternalApprovalState == Docflow.OfficialDocument.InternalApprovalState.Signed);
      this.ChangeCounterpartyPropertyAccess(isEnabled, counterpartyCodeInNumber, enabledState);
    }
    
    /// <summary>
    /// Сменить доступность поля Контрагент. Доступность зависит от статуса.
    /// </summary>
    /// <param name="isEnabled">Признак доступности поля. TRUE - поле доступно.</param>
    /// <param name="counterpartyCodeInNumber">Признак вхождения кода контрагента в формат номера. TRUE - входит.</param>
    /// <param name="enabledState">Признак доступности поля в зависимости от статуса.</param>
    public virtual void ChangeCounterpartyPropertyAccess(bool isEnabled, bool counterpartyCodeInNumber, bool enabledState)
    {
      // Виртуальная функция. Переопределено в потомках.
    }
    
    /// <summary>
    /// Изменить отображение панели регистрации.
    /// </summary>
    /// <param name="needShow">Признак отображения.</param>
    /// <param name="repeatRegister">Признак повторной регистрации\изменения реквизитов.</param>
    public virtual void ChangeRegistrationPaneVisibility(bool needShow, bool repeatRegister)
    {
      // Документопоток.
      var direction = _obj.DocumentKind != null ? _obj.DocumentKind.DocumentFlow : null;
      var isIncomingDirection = direction == DocumentFlow.Incoming;
      var isOutgoingDirection = direction == DocumentFlow.Outgoing;
      var isInnerDirection = direction == DocumentFlow.Inner;
      var isContractDirection = direction == DocumentFlow.Contracts;
      
      // Тип нумерации.
      var isNumerable = _obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Numerable;
      var isNotifiable = _obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Registrable;
      var isNotNumerable = !isNumerable && !isNotifiable;

      // Есть права на регистрацию.
      var canRegister = _obj.AccessRights.CanRegister();
      
      // Поля Дело и Дата помещения в дело д.б. недоступны,
      // если в формате номера журнала есть индекс дела и документ зарегистрирован(пронумерован).
      // Делопроизводитель должен иметь возможность сменить дело и дату помещения в дело при изменении реквизитов регистрации.
      var caseFileIncludedInNumber = _obj.DocumentRegister != null &&
        _obj.DocumentRegister.NumberFormatItems.Any(n => n.Element == DocumentRegisterNumberFormatItems.Element.CaseFile);
      var alreadyRegistered = _obj.RegistrationState == Sungero.Docflow.OfficialDocument.RegistrationState.Registered;
      var caseFileEnabled = canRegister && (!(caseFileIncludedInNumber && alreadyRegistered) || repeatRegister);
      
      var properties = _obj.State.Properties;
      
      properties.DeliveryMethod.IsEnabled = !isNotNumerable && canRegister;
      properties.DeliveryMethod.IsVisible = needShow && !isInnerDirection && !isContractDirection;
      
      properties.DocumentRegister.IsEnabled = repeatRegister;
      properties.DocumentRegister.IsVisible = needShow && !isNumerable;
      
      properties.CaseFile.IsEnabled = caseFileEnabled;
      properties.CaseFile.IsVisible = needShow;

      properties.PlacedToCaseFileDate.IsEnabled = caseFileEnabled;
      properties.PlacedToCaseFileDate.IsVisible = needShow;

      properties.RegistrationNumber.IsEnabled = repeatRegister;
      properties.RegistrationNumber.IsVisible = needShow;
      
      properties.RegistrationDate.IsEnabled = repeatRegister;
      properties.RegistrationDate.IsVisible = needShow;
      
      properties.LifeCycleState.IsEnabled = true;
      properties.LifeCycleState.IsVisible = needShow;

      properties.RegistrationState.IsVisible = needShow && isNotifiable;

      properties.InternalApprovalState.IsEnabled = true;
      properties.InternalApprovalState.IsVisible = (isOutgoingDirection || isInnerDirection || isContractDirection) && needShow;

      properties.ExternalApprovalState.IsEnabled = true;
      properties.ExternalApprovalState.IsVisible = isContractDirection && needShow;
      
      properties.ExecutionState.IsEnabled = true;
      properties.ExecutionState.IsVisible = (isIncomingDirection || isInnerDirection) && needShow;

      properties.ControlExecutionState.IsEnabled = true;
      properties.ControlExecutionState.IsVisible = (isIncomingDirection || isInnerDirection) && needShow;
      
      properties.LocationState.IsVisible = needShow && !string.IsNullOrWhiteSpace(_obj.LocationState);
      
      properties.Tracking.IsEnabled = isNumerable || (isNotifiable && canRegister);
      
      // Статус верификации.
      properties.VerificationState.IsVisible = needShow && Docflow.PublicFunctions.SmartProcessingSetting.SmartProcessingIsEnabled();
    }
    
    /// <summary>
    /// Поведение панели по умолчанию.
    /// </summary>
    /// <returns>True, если панель должна быть отображена при создании документа.</returns>
    public virtual bool DefaultRegistrationPaneVisibility()
    {
      // Тип нумерации.
      var isNumerable = _obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Numerable;
      var isNotifiable = _obj.DocumentKind != null && _obj.DocumentKind.NumberingType == NumberingType.Registrable;
      
      // Есть права на регистрацию.
      var canRegister = _obj.AccessRights.CanRegister();
      
      return (canRegister && isNotifiable) || isNumerable;
    }
    
    /// <summary>
    /// Изменить отображение основания подписания.
    /// </summary>
    public virtual void ChangeOurSigningReasonVisibility()
    {
      var formParams = ((IExtendedEntity)_obj).Params;
      
      if (formParams.ContainsKey(Sungero.Docflow.Constants.OfficialDocument.ShowOurSigningReasonParam))
        _obj.State.Properties.OurSigningReason.IsVisible = this.GetShowOurSigningReasonParam();
    }
    
    /// <summary>
    /// Получить значение параметра, отвечающего за показ/скрытие основания подписания документа.
    /// </summary>
    /// <returns>True - если нужно показать основание подписания документа.</returns>
    public virtual bool GetShowOurSigningReasonParam()
    {
      var formParams = ((IExtendedEntity)_obj).Params;
      
      if (formParams.ContainsKey(Sungero.Docflow.Constants.OfficialDocument.ShowOurSigningReasonParam))
        return (bool)formParams[Sungero.Docflow.Constants.OfficialDocument.ShowOurSigningReasonParam];
      
      return false;
    }
    
    #endregion
    
    #region Жизненный цикл
    
    /// <summary>
    /// Обновить жизненный цикл документа.
    /// </summary>
    /// <param name="registrationState">Статус регистрации.</param>
    /// <param name="approvalState">Статус согласования.</param>
    /// <param name="counterpartyApprovalState">Статус согласования с контрагентом.</param>
    public virtual void UpdateLifeCycle(Enumeration? registrationState,
                                        Enumeration? approvalState,
                                        Enumeration? counterpartyApprovalState)
    {
      // Не проверять статусы для пустых параметров.
      if (_obj == null || _obj.DocumentKind == null)
        return;
      
      var direction = _obj.DocumentKind.DocumentFlow;
      var currentState = _obj.LifeCycleState;
      var lifeCycleMustByActive = IsLifeCycleMustBeActive(direction, approvalState, counterpartyApprovalState);
      
      // Если регистрация была отменена, а документ действующий согласно функции - ставим статус в разработке.
      if (currentState == LifeCycleState.Active &&
          registrationState == RegistrationState.NotRegistered &&
          _obj.State.Properties.RegistrationState.OriginalValue != registrationState &&
          _obj.State.Properties.RegistrationState.OriginalValue != null &&
          lifeCycleMustByActive)
        _obj.LifeCycleState = Docflow.OfficialDocument.LifeCycleState.Draft;

      // Документ должен быть в разработке (или null) и зарегистрирован.
      if ((currentState != null && currentState != Docflow.OfficialDocument.LifeCycleState.Draft) ||
          registrationState != Docflow.OfficialDocument.RegistrationState.Registered)
        return;
      
      if (lifeCycleMustByActive)
        _obj.LifeCycleState = Docflow.OfficialDocument.LifeCycleState.Active;
    }
    
    /// <summary>
    /// Проверка необходимости установки статуса Действующий для документопотока.
    /// </summary>
    /// <param name="direction">Документопоток.</param>
    /// <param name="approvalState">Статус согласования.</param>
    /// <param name="counterpartyApprovalState">Статус согласования с контрагентом.</param>
    /// <returns>Признак необходимости смены ЖЦ документа на действующий.</returns>
    public static bool IsLifeCycleMustBeActive(Enumeration? direction, Enumeration? approvalState, Enumeration? counterpartyApprovalState)
    {
      // Входящие и исходящие документы должны быть действующими.
      if (direction == Docflow.DocumentKind.DocumentFlow.Outgoing ||
          direction == Docflow.DocumentKind.DocumentFlow.Incoming)
        return true;

      // Внутренние документы необходимо подписать.
      if (direction == Docflow.DocumentKind.DocumentFlow.Inner &&
          (approvalState == Docflow.OfficialDocument.InternalApprovalState.Signed ||
           approvalState == Docflow.Memo.InternalApprovalState.Reviewed))
        return true;
      
      // Договорные документы необходимо подписать у нас и у контрагента.
      if (direction == Docflow.DocumentKind.DocumentFlow.Contracts &&
          counterpartyApprovalState == Docflow.OfficialDocument.ExternalApprovalState.Signed &&
          approvalState == Docflow.OfficialDocument.InternalApprovalState.Signed)
        return true;
      
      return false;
    }
    
    /// <summary>
    /// Изменение состояния документа для ненумеруемых документов.
    /// </summary>
    public virtual void SetLifeCycleState()
    {
      var documentKind = _obj.DocumentKind;
      var isNotNumerable = documentKind != null &&
        documentKind.NumberingType == Docflow.DocumentKind.NumberingType.NotNumerable;
      var isAutoNumerable = documentKind != null &&
        documentKind.NumberingType == Docflow.DocumentKind.NumberingType.Numerable &&
        documentKind.AutoNumbering == true;
      var isDraft = _obj.LifeCycleState == null ||
        _obj.LifeCycleState == Docflow.OfficialDocument.LifeCycleState.Draft;
      
      // Документ ненумеруемого или автонумеруемого вида сделать действующим, если раньше был черновиком.
      if ((isNotNumerable || isAutoNumerable) && isDraft)
        _obj.LifeCycleState = LifeCycleState.Active;
      
      // Для нумеруемого или регистрируемого сделать черновиком. Кроме автонумеруемых.
      if (!isNotNumerable && !isDraft && !isAutoNumerable)
        _obj.LifeCycleState = LifeCycleState.Draft;
    }
    
    /// <summary>
    /// Сменить тип документа на недействующий.
    /// </summary>
    /// <param name="isActive">True, если документ действующий.</param>
    [Public]
    public virtual void SetObsolete(bool isActive)
    {
      _obj.LifeCycleState = LifeCycleState.Obsolete;
    }
    
    /// <summary>
    /// Проверяет, является ли документ недействующим.
    /// </summary>
    /// <param name="lifeCycleState">Статус ЖЦ.</param>
    /// <returns>Признак того, является ли документ недействующим.</returns>
    public virtual bool IsObsolete(Enumeration? lifeCycleState)
    {
      return lifeCycleState == Docflow.OfficialDocument.LifeCycleState.Obsolete;
    }
    
    /// <summary>
    /// Проверяет, является ли документ недействующим.
    /// </summary>
    /// <returns>Признак того, является ли документ недействующим.</returns>
    [Public]
    public virtual bool IsObsolete()
    {
      return _obj.LifeCycleState == Docflow.OfficialDocument.LifeCycleState.Obsolete;
    }
    
    #endregion
    
    #region Получение свойств документа
    
    /// <summary>
    /// Получение группы документа.
    /// </summary>
    /// <returns>Группа документа.</returns>
    [Public]
    public virtual IDocumentGroupBase GetDocumentGroup()
    {
      return _obj.DocumentGroup;
    }
    
    /// <summary>
    /// Получение контрагентов по документу.
    /// </summary>
    /// <returns>Контрагенты.</returns>
    [Public]
    public virtual List<Parties.ICounterparty> GetCounterparties()
    {
      return null;
    }
    
    /// <summary>
    /// Получить код контрагента.
    /// </summary>
    /// <returns>Код контрагента либо пустая строка.</returns>
    [Public]
    public virtual string GetCounterpartyCode()
    {
      // Виртуальная функция. Переопределено в потомках.
      if (this.GetCounterparties() == null)
        return string.Empty;
      var counterparty = this.GetCounterparties().FirstOrDefault();
      var counterpartyCode = counterparty == null ? string.Empty : counterparty.Code;
      return counterpartyCode;
    }
    
    /// <summary>
    /// Получить ответственного за документ.
    /// </summary>
    /// <returns>Пользователь, ответственный за документ.</returns>
    [Public]
    public virtual Sungero.Company.IEmployee GetDocumentResponsibleEmployee()
    {
      return Employees.As(_obj.Author);
    }
    
    /// <summary>
    /// Получить подписывающего по умолчанию.
    /// </summary>
    /// <param name="signatories">Список подписывающих с приоритетом.</param>
    /// <returns>Подписывающий по умолчанию.</returns>
    [Obsolete("Используйте метод GetDefaultSignatory().")]
    public virtual Sungero.Company.IEmployee GetDefaultSignatory(List<Docflow.Structures.SignatureSetting.Signatory> signatories)
    {
      if (!signatories.Any())
        return null;
      
      var maxPriority = signatories.Max(sign => sign.Priority);
      var signatoriesMaxPriority = signatories.Where(s => s.Priority == maxPriority);
      var employeeMaxPriorityCount = signatoriesMaxPriority.Select(e => e.EmployeeId).Distinct().Count();
      if (employeeMaxPriorityCount == 1)
      {
        var defaultSignatoryId = signatoriesMaxPriority.Select(s => s.EmployeeId).FirstOrDefault();
        var defaultSignatory = Employees.Get(defaultSignatoryId);
        return defaultSignatory;
      }
      return null;
    }
    
    /// <summary>
    /// Получить группу регистрации.
    /// </summary>
    /// <returns>Список групп регистрации.</returns>
    [Public]
    public virtual Docflow.IRegistrationGroup GetRegistrationGroup()
    {
      if (_obj.DocumentRegister != null &&
          _obj.DocumentRegister.RegistrationGroup != null &&
          _obj.DocumentRegister.RegistrationGroup.Status == Sungero.CoreEntities.DatabookEntry.Status.Active)
        return _obj.DocumentRegister.RegistrationGroup;
      
      return Docflow.RegistrationGroups.Null;
    }
    
    /// <summary>
    /// Получить адресатов.
    /// </summary>
    /// <returns>Список адресатов.</returns>
    [Public]
    public virtual List<Company.IEmployee> GetAddressees()
    {
      // Виртуальная функция. Переопределено в потомках.
      return new List<Company.IEmployee>();
    }
    
    /// <summary>
    /// Получить список адресатов с электронной почтой для отправки письма.
    /// </summary>
    /// <returns>Список адресатов.</returns>
    [Public]
    public virtual List<Structures.OfficialDocument.IEmailAddressee> GetEmailAddressees()
    {
      return new List<Structures.OfficialDocument.IEmailAddressee>();
    }
    
    /// <summary>
    /// Получить проект из документа.
    /// </summary>
    /// <returns>Проект, указанный в карточке документа.</returns>
    [Public]
    public virtual IProjectBase GetProject()
    {
      return _obj.Project;
    }
    
    /// <summary>
    /// Получить основание подписания со стороны контрагента.
    /// </summary>
    /// <returns>Основание подписания со стороны контрагента.</returns>
    [Public]
    public virtual string GetCounterpartySigningReason()
    {
      return string.Empty;
    }
    
    #endregion
    
    #region Заполнение свойств документа
    
    /// <summary>
    /// Заполнить подписывающего.
    /// </summary>
    /// <param name="signatory">Подписывающий со стороны контрагента.</param>
    [Public]
    public virtual void FillCounterpartySignatory(Parties.IContact signatory)
    {
      // Виртуальная функция. Переопределено в потомках.
    }
    
    /// <summary>
    /// Заполнить основание со стороны контрагента.
    /// </summary>
    /// <param name="signingReason">Основание контрагента.</param>
    [Public]
    public virtual void FillCounterpartySigningReason(string signingReason)
    {
      // Виртуальная функция. Переопределено в потомках.
    }
    
    /// <summary>
    /// Заполнить свойство "Ведущий документ" в зависимости от типа документа.
    /// </summary>
    /// <param name="leadingDocument">Ведущий документ.</param>
    /// <remarks>Используется при смене типа.</remarks>
    [Public]
    public virtual void FillLeadingDocument(IOfficialDocument leadingDocument)
    {
      return;
    }
    
    /// <summary>
    /// Заполнить оргструктуру.
    /// </summary>
    public void FillOrganizationStructure()
    {
      // Заполнить нашу организацию.
      if (_obj.BusinessUnit == null && _obj.State.Properties.BusinessUnit.IsVisible)
        _obj.BusinessUnit = Functions.Module.GetDefaultBusinessUnit(Company.Employees.Current);

      // Заполнить подразделение.
      var employee = Company.Employees.Current;
      if (_obj.Department == null)
      {
        var department = Company.Departments.Null;
        var settings = Functions.PersonalSetting.GetPersonalSettings(employee);
        // Из настроек.
        if (settings != null)
          department = settings.Department;
        
        // По оргструктуре.
        if (department == null && employee != null)
          department = employee.Department;

        _obj.Department = department;
      }
      
      // Заполнить "Подготовил".
      if (_obj.PreparedBy == null)
        _obj.PreparedBy = employee;
    }
    
    /// <summary>
    /// Заполнить имя документа.
    /// </summary>
    [Public]
    public virtual void FillName()
    {
      var documentKind = _obj.DocumentKind;
      
      if (documentKind != null && !documentKind.GenerateDocumentName.Value && _obj.Name == Docflow.Resources.DocumentNameAutotext)
        _obj.Name = string.Empty;
      
      if (documentKind == null || !documentKind.GenerateDocumentName.Value)
        return;
      
      _obj.Name = this.GetGeneratedDocumentName();
    }
    
    /// <summary>
    /// Получить автоматически сформированное имя документа.
    /// </summary>
    /// <returns>Имя документа.</returns>
    [Public]
    public virtual string GetGeneratedDocumentName()
    {
      var documentKind = _obj.DocumentKind;
      var name = string.Empty;
      
      /* Имя в формате:
        <Вид документа> №<номер> от <дата> "<содержание>".
       */
      using (TenantInfo.Culture.SwitchTo())
      {
        if (!string.IsNullOrWhiteSpace(_obj.RegistrationNumber))
          name += OfficialDocuments.Resources.Number + _obj.RegistrationNumber;
        
        if (_obj.RegistrationDate != null)
          name += OfficialDocuments.Resources.DateFrom + _obj.RegistrationDate.Value.ToString("d");
        
        if (!string.IsNullOrWhiteSpace(_obj.Subject))
          name += " \"" + _obj.Subject + "\"";
      }
      
      if (string.IsNullOrWhiteSpace(name))
      {
        if (_obj.VerificationState == null)
          name = Docflow.Resources.DocumentNameAutotext;
        else
          name = _obj.DocumentKind.ShortName;
      }
      else if (documentKind != null)
      {
        name = documentKind.ShortName + name;
      }
      
      name = Functions.Module.TrimSpecialSymbols(name);
      
      return Functions.OfficialDocument.AddClosingQuote(name, _obj);
    }
    
    /// <summary>
    /// Добавить закрывающую кавычку для имени.
    /// </summary>
    /// <param name="name">Имя.</param>
    /// <param name="document">Документ.</param>
    /// <returns>Результирующая строка.</returns>
    [Public]
    public static string AddClosingQuote(string name, IOfficialDocument document)
    {
      return name.Length > document.Info.Properties.Name.Length ?
        name.Substring(0, document.Info.Properties.Name.Length - 1) + "\"" :
        name;
    }

    /// <summary>
    /// Добавить закрывающую кавычку для содержания.
    /// </summary>
    /// <param name="subject">Содержание.</param>
    /// <param name="document">Документ.</param>
    /// <returns>Результирующая строка.</returns>
    [Public]
    public static string AddClosingQuoteToSubject(string subject, IOfficialDocument document)
    {
      return subject.Length > document.Info.Properties.Subject.Length ?
        subject.Substring(0, document.Info.Properties.Subject.Length - 1) + "\"" :
        subject;
    }

    /// <summary>
    /// Заполнить обязательные свойства для документа.
    /// </summary>
    /// <param name="properties">Свойства.</param>
    [Public]
    public virtual void FillRequiredProperties(System.Collections.Generic.IDictionary<string, object> properties)
    {
      this.FillOrganizationStructure();

      if (properties.ContainsKey(_obj.Info.Properties.Name.Name))
      {
        var nameValue = (string)properties[_obj.Info.Properties.Name.Name];
        this.FillDocumentNamePropertyByGenerateSetting(nameValue);
      }
    }
    
    /// <summary>
    /// Заполнить свойство, содержащее имя документа, в зависимости от настройки генерации имени.
    /// </summary>
    /// <param name="name">Имя документа.</param>
    [Public]
    public virtual void FillDocumentNamePropertyByGenerateSetting(string name)
    {
      if (_obj.DocumentKind.GenerateDocumentName.Value)
        _obj.Subject = name;
      else
        _obj.Name = name;
    }
    #endregion
    
    #region Генерация PDF с отметкой об ЭП
    
    /// <summary>
    /// Получить сообщение об ошибке для неподдерживаемых форматов.
    /// </summary>
    /// <param name="extension">Расширение.</param>
    /// <returns>Результат преобразования.</returns>
    public virtual Sungero.Docflow.Structures.OfficialDocument.СonversionToPdfResult GetExtensionValidationError(string extension)
    {
      var result = Sungero.Docflow.Structures.OfficialDocument.СonversionToPdfResult.Create();
      result.HasErrors = true;
      result.ErrorTitle = OfficialDocuments.Resources.ConvertionErrorTitleBase;
      result.ErrorMessage = OfficialDocuments.Resources.ExtensionNotSupportedFormat(extension.ToUpper());
      return result;
    }
    
    #endregion
    
    /// <summary>
    /// Обработать добавление документа как основного вложения в задачу.
    /// </summary>
    /// <param name="task">Задача.</param>
    /// <remarks>Только для задач, создаваемых пользователем вручную.</remarks>
    [Public]
    public virtual void DocumentAttachedInMainGroup(Sungero.Workflow.ITask task)
    {
      
    }
    
    /// <summary>
    /// Определить необходимость защиты от редактирования ведущего документа.
    /// </summary>
    /// <returns>True - нужно. False - иначе.</returns>
    [Public]
    public virtual bool NeedDisableLeadingDocument()
    {
      var needDisableByRegistration = this.NeedDisablePropertyByRegistration();
      if (needDisableByRegistration != null)
        return needDisableByRegistration == true;
      
      // При изменении рег.данных разрешено менять ведущий документ у журналов без разреза по ведущему.
      var leadingNumberIncludedInNumber = _obj.DocumentRegister != null &&
        (_obj.DocumentRegister.NumberFormatItems.Any(n => n.Element == Docflow.DocumentRegisterNumberFormatItems.Element.LeadingNumber) ||
         _obj.DocumentRegister.NumberingSection == Docflow.DocumentRegister.NumberingSection.LeadingDocument);
      
      return leadingNumberIncludedInNumber;
    }
    
    /// <summary>
    /// Определить необходимость защиты от редактирования НОР.
    /// </summary>
    /// <returns>True - нужно. False - не нужно.</returns>
    [Public]
    public virtual bool NeedDisableBusinessUnit()
    {
      var needDisableByRegistration = this.NeedDisablePropertyByRegistration();
      if (needDisableByRegistration != null)
        return needDisableByRegistration == true;
      
      // При изменении рег.данных разрешено менять НОР у журналов без разреза по НОР.
      var businessUnitIncludedInNumber = _obj.DocumentRegister != null &&
        (_obj.DocumentRegister.NumberFormatItems.Any(n => n.Element == Docflow.DocumentRegisterNumberFormatItems.Element.BUCode) ||
         _obj.DocumentRegister.NumberingSection == Docflow.DocumentRegister.NumberingSection.BusinessUnit);
      
      return businessUnitIncludedInNumber;
    }
    
    /// <summary>
    /// Определить необходимость защиты от редактирования подразделения.
    /// </summary>
    /// <returns>True - нужно. False - не нужно.</returns>
    [Public]
    public virtual bool NeedDisableDepartment()
    {
      var needDisableByRegistration = this.NeedDisablePropertyByRegistration();
      if (needDisableByRegistration != null)
        return needDisableByRegistration == true;
      
      // При изменении рег.данных разрешено менять подразделение у журналов без разреза по подразделению.
      var departmentIncludedInNumber = _obj.DocumentRegister != null &&
        (_obj.DocumentRegister.NumberFormatItems.Any(n => n.Element == Docflow.DocumentRegisterNumberFormatItems.Element.DepartmentCode) ||
         _obj.DocumentRegister.NumberingSection == Docflow.DocumentRegister.NumberingSection.Department);
      
      return departmentIncludedInNumber;
    }
    
    /// <summary>
    /// Определить необходимость защиты от редактирования свойства в зависимости от регистрации документа.
    /// </summary>
    /// <returns>True - нужно. False - иначе.  Null - невозможно окончательно определить.</returns>
    [Public]
    public virtual bool? NeedDisablePropertyByRegistration()
    {
      // Запрещено менять, если нет прав.
      if (!_obj.AccessRights.CanUpdate())
        return true;
      
      // Разрешено менять для не зарегистрированных документов.
      var isNotRegistered = _obj.RegistrationState == Sungero.Docflow.OfficialDocument.RegistrationState.NotRegistered;
      if (isNotRegistered)
        return false;
      
      // Определить смену типа.
      var documentKindOriginalValue = _obj.State.Properties.DocumentKind.OriginalValue;
      var isDocumentTypeChange = documentKindOriginalValue != null &&
        !documentKindOriginalValue.DocumentType.Equals(_obj.DocumentKind.DocumentType);
      
      // Разрешено менять во время регистрации незарегистрированного документа, перерегистрации автонумеруемых или смены типа.
      // Также разрешено менять, когда верификация в процессе.
      var registrationStateOriginalValue = _obj.State.Properties.RegistrationState.OriginalValue;
      var verificationStateOriginalValue = _obj.State.Properties.VerificationState.OriginalValue;
      if (registrationStateOriginalValue == null || registrationStateOriginalValue == Sungero.Docflow.OfficialDocument.RegistrationState.NotRegistered ||
          _obj.DocumentKind.AutoNumbering == true || isDocumentTypeChange ||
          verificationStateOriginalValue == Docflow.OfficialDocument.VerificationState.InProcess)
        return false;
      
      // Запрещено менять значение свойства для зарегистрированных, кроме случаев изменения рег.данных и смены типа.
      var formParams = ((Sungero.Domain.Shared.IExtendedEntity)_obj).Params;
      var repeatRegister = formParams.ContainsKey(Sungero.Docflow.Constants.OfficialDocument.RepeatRegister) &&
        (bool)formParams[Sungero.Docflow.Constants.OfficialDocument.RepeatRegister];
      if (!repeatRegister)
        return true;
      
      return null;
    }
    
    /// <summary>
    /// Получить документы, связанные типом связи "Приложение".
    /// </summary>
    /// <returns>Документы, связанные типом связи "Приложение".</returns>
    [Public]
    public virtual List<IOfficialDocument> GetAddenda()
    {
      return _obj.Relations.GetRelated(Docflow.Constants.Module.AddendumRelationName)
        .Where(x => OfficialDocuments.Is(x))
        .Select(x => OfficialDocuments.As(x))
        .Where(x => !Docflow.PublicFunctions.OfficialDocument.IsObsolete(x))
        .ToList();
    }
    
    /// <summary>
    /// Добавить связанные документы в группу вложения.
    /// </summary>
    /// <param name="group">Группа вложения задачи.</param>
    [Public]
    public virtual void AddRelatedDocumentsToAttachmentGroup(Sungero.Workflow.Interfaces.IWorkflowEntityAttachmentGroup group)
    {
      // Виртуальная функция. Переопределено в потомках.
    }
    
    /// <summary>
    /// Удалить связанные документы из группы вложения.
    /// </summary>
    /// <param name="group">Группа вложения задачи.</param>
    [Public]
    public virtual void RemoveRelatedDocumentsFromAttachmentGroup(Sungero.Workflow.Interfaces.IWorkflowEntityAttachmentGroup group)
    {
      // Виртуальная функция. Переопределено в потомках.
    }
    
    /// <summary>
    /// Копировать список проектов из ведущего документа.
    /// </summary>
    /// <param name="mainDocument">Ведущий документ.</param>
    /// <param name="document">Документ.</param>
    [Public]
    public static void CopyProjects(IOfficialDocument mainDocument, IOfficialDocument document)
    {
      if (document.DocumentKind != null &&
          document.DocumentKind.ProjectsAccounting == true &&
          mainDocument.DocumentKind != null &&
          mainDocument.DocumentKind.ProjectsAccounting == true)
        document.Project = mainDocument.Project;
    }
    
    /// <summary>
    /// Признак необходимости очистки поля Проект.
    /// </summary>
    /// <param name="e">Аргументы смены вида документа.</param>
    /// <returns>True - нужно очистить, false - не нужно.</returns>
    public virtual bool NeedClearProject(Sungero.Docflow.Shared.OfficialDocumentDocumentKindChangedEventArgs e)
    {
      // Если в выбранном виде документа не установлен признак "Вести учет по проектам" - нужно очистить проект.
      return e.NewValue == null || e.NewValue.ProjectsAccounting != true;
    }
    
    /// <summary>
    /// Проверить право на удаление документа.
    /// </summary>
    /// <returns>True, если есть права, иначе - false.</returns>
    [Public]
    public bool CheckDeleteEntityAccessRights()
    {
      // Для автонумеруемых типов документов разрешить удаление документа согласно правам доступа.
      var isAutoNumerableDocument = _obj.DocumentKind != null &&
        (_obj.DocumentKind.AutoNumbering ?? false) &&
        _obj.DocumentKind.NumberingType == Docflow.DocumentKind.NumberingType.Numerable;
      
      // Для пронумерованных документов, находящихся в процессе верификации,
      // разрешить удаление документа согласно правам доступа.
      var isDocumentInProcessVerificationStateAndNumbered = _obj.RegistrationState == RegistrationState.Registered &&
        _obj.DocumentKind.NumberingType == Docflow.DocumentKind.NumberingType.Numerable &&
        _obj.VerificationState == Docflow.OfficialDocument.VerificationState.InProcess;
      
      return _obj.AccessRights.CanUpdate() && (isAutoNumerableDocument ||
                                               _obj.RegistrationState != RegistrationState.Reserved &&
                                               _obj.RegistrationState != RegistrationState.Registered ||
                                               isDocumentInProcessVerificationStateAndNumbered);
    }
    
    /// <summary>
    /// Очистка НОР для ненумеруемых документов.
    /// </summary>
    /// <param name="documentKind">Вид документа.</param>
    public void ClearBusinessUnit(IDocumentKind documentKind)
    {
      if (documentKind != null && documentKind.NumberingType == Docflow.DocumentKind.NumberingType.NotNumerable &&
          _obj.BusinessUnit != null && !ExchangeDocuments.Is(_obj) && !_obj.State.Properties.BusinessUnit.IsVisible)
        _obj.BusinessUnit = null;
    }
    
    /// <summary>
    /// Проверка на то, что документ является проектным.
    /// </summary>
    /// <returns>True - если документ проектный, иначе - false.</returns>
    [Public, Obsolete("Используйте метод IsProjectDocument(List<int>)")]
    public virtual bool IsProjectDocument()
    {
      return this.IsProjectDocument(new List<int>());
    }
    
    /// <summary>
    /// Проверка на то, что документ является проектным.
    /// </summary>
    /// <param name="leadingDocumentIds">ИД ведущих документов.</param>
    /// <returns>True - если документ проектный, иначе - false.</returns>
    [Public]
    public virtual bool IsProjectDocument(List<int> leadingDocumentIds)
    {
      return _obj.Project != null && _obj.DocumentKind.ProjectsAccounting.Value;
    }
    
    /// <summary>
    /// Получить признак возможности подписания документа при заблокированной карточке.
    /// </summary>
    /// <returns>Признак возможности подписания документа при заблокированной карточке.</returns>
    public virtual bool CanSignLockedDocument()
    {
      var hasCallContext = CallContext.CalledFrom(ApprovalSigningAssignments.Info) || CallContext.CalledFrom(ApprovalReviewAssignments.Info);
      var hasParams = ((Domain.Shared.IExtendedEntity)_obj).Params.ContainsKey(Constants.OfficialDocument.CanSignLockedDocument);
      return hasCallContext || hasParams;
    }
    
    /// <summary>
    /// Получить признак возможности удаления версии документа.
    /// </summary>
    /// <param name="versionNumber">Номер версии.</param>
    /// <returns>Признак возможности удаления версии документа.</returns>
    [Public]
    public virtual bool CanDeleteVersion(int? versionNumber)
    {
      return Docflow.PublicFunctions.OfficialDocument.Remote.HasAcquaintanceTasks(_obj, versionNumber, true, true);
    }
    
    /// <summary>
    /// Получить признак возможности скрытия версии документа.
    /// </summary>
    /// <param name="versionNumber">Номер версии.</param>
    /// <returns>Признак возможности скрытия версии документа.</returns>
    [Public]
    public virtual bool CanHideVersion(int? versionNumber)
    {
      return Docflow.PublicFunctions.OfficialDocument.Remote.HasAcquaintanceTasks(_obj, versionNumber, false, false);
    }
    
    #region Интеллектуальная обработка
    
    /// <summary>
    /// Проверка, поддерживается ли режим верификации для документа.
    /// </summary>
    /// <returns>True - если поддерживается, иначе - false.</returns>
    [Public]
    public virtual bool IsVerificationModeSupported()
    {
      return false;
    }
    
    /// <summary>
    /// Определить, пронумерован ли документ.
    /// </summary>
    /// <returns>True - документ успешно пронумерован, False - иначе.</returns>
    /// <remarks>Если документ зарегистрирован, а не пронумерован, то вернет false.</remarks>
    [Public]
    public virtual bool IsNumerationSucceed()
    {
      return _obj.RegistrationState == RegistrationState.Registered &&
        (_obj.DocumentKind == null || _obj.DocumentKind.NumberingType == Sungero.Docflow.DocumentKind.NumberingType.Numerable) &&
        _obj.DocumentRegister != null;
    }
    
    /// <summary>
    /// Разблокировать реквизиты для верификации после нумерации.
    /// </summary>
    [Public]
    public virtual void EnableRequisitesForVerification()
    {
      if (_obj.VerificationState == VerificationState.InProcess &&
          this.IsNumerationSucceed() &&
          Functions.OfficialDocument.CanChangeRequisitesOrCancelRegistration(_obj) &&
          _obj.AccessRights.CanUpdate())
      {
        var properties = _obj.State.Properties;
        properties.Name.IsEnabled = _obj.DocumentKind == null || !_obj.DocumentKind.GenerateDocumentName.Value;
        properties.DocumentKind.IsEnabled = true;
        properties.Subject.IsEnabled = true;
        properties.BusinessUnit.IsEnabled = true;
        properties.Department.IsEnabled = true;
        
        this.ChangeCounterpartyPropertyAccess(true);
        properties.Assignee.IsEnabled = true;
        
        properties.DeliveryMethod.IsEnabled = true;
        properties.CaseFile.IsEnabled = true;
        properties.PlacedToCaseFileDate.IsEnabled = true;
      }
    }
    
    /// <summary>
    /// Сделать доступными рег. номер и рег. дату незарегистрированного документа регистрируемого вида в процессе верификации.
    /// </summary>
    public virtual void EnableRegistrationNumberAndDate()
    {
      if (_obj.DocumentKind == null || _obj.DocumentKind.NumberingType == Sungero.Docflow.DocumentKind.NumberingType.NotNumerable)
        return;
      
      var isRegistrable = _obj.DocumentKind.NumberingType == Sungero.Docflow.DocumentKind.NumberingType.Registrable;
      var isNumerable = _obj.DocumentKind.NumberingType == Sungero.Docflow.DocumentKind.NumberingType.Numerable;
      var properties = _obj.State.Properties;
      if (isNumerable ||
          isRegistrable && _obj.RegistrationState == Docflow.OfficialDocument.RegistrationState.NotRegistered)
      {
        properties.RegistrationNumber.IsEnabled = true;
        properties.RegistrationDate.IsEnabled = true;
      }
    }
    
    /// <summary>
    /// Сменить доступность поля Контрагент.
    /// </summary>
    /// <param name="isEnabled">Признак доступности поля. TRUE - поле доступно.</param>
    public virtual void ChangeCounterpartyPropertyAccess(bool isEnabled)
    {
      // Виртуальная функция. Переопределено в потомках.
    }
    
    /// <summary>
    /// Проверка, заполнены ли обязательные и псевдообязательные свойства.
    /// </summary>
    /// <returns>True - если обязательные и псевдообязательные свойства не заполнены, иначе - false.</returns>
    [Public]
    public virtual bool HasEmptyRequiredProperties()
    {
      // Виртуальная функция. Переопределено в потомках.
      return false;
    }
    
    #endregion
  }
}