Пример #1
0
        public override void BeforeExecute(Sungero.Reporting.Client.BeforeExecuteEventArgs e)
        {
            if (DocumentUsageReport.PeriodBegin.HasValue && DocumentUsageReport.PeriodEnd.HasValue)
            {
                return;
            }

            var dialog = Dialogs.CreateInputDialog(Resources.DocumentUsageReportDialog);

            dialog.HelpCode = Constants.DocumentUsageReport.HelpCode;
            dialog.Buttons.AddOkCancel();

            CommonLibrary.IDateDialogValue periodBegin = null;
            CommonLibrary.IDateDialogValue periodEnd   = null;
            INavigationDialogValue <Company.IDepartment> department = null;

            // Период.
            var today = Calendar.UserToday;

            if (!DocumentUsageReport.PeriodBegin.HasValue)
            {
                periodBegin = dialog.AddDate(Resources.DocumentUsagePeriodBegin, true, today.AddDays(-30));
            }
            if (!DocumentUsageReport.PeriodEnd.HasValue)
            {
                periodEnd = dialog.AddDate(Resources.DocumentUsagePeriodEnd, true, today);
            }
            if (DocumentUsageReport.Department == null)
            {
                department = dialog.AddSelect(Resources.Department, false, Company.Departments.Null)
                             .Where(x => x.Status == CoreEntities.DatabookEntry.Status.Active);
            }

            dialog.SetOnButtonClick((args) =>
            {
                Functions.Module.CheckReportDialogPeriod(args, periodBegin, periodEnd);
            });

            if (dialog.Show() != DialogButtons.Ok)
            {
                e.Cancel = true;
                return;
            }
            if (!DocumentUsageReport.PeriodBegin.HasValue)
            {
                DocumentUsageReport.PeriodBegin       = Docflow.PublicFunctions.Module.Remote.GetTenantDateTimeFromUserDay(periodBegin.Value.Value);
                DocumentUsageReport.ClientPeriodBegin = periodBegin.Value.Value;
            }
            if (!DocumentUsageReport.PeriodEnd.HasValue)
            {
                DocumentUsageReport.PeriodEnd       = periodEnd.Value.Value.EndOfDay().FromUserTime();
                DocumentUsageReport.ClientPeriodEnd = periodEnd.Value.Value;
            }
            if (DocumentUsageReport.Department == null)
            {
                DocumentUsageReport.Department = department.Value;
            }
        }
Пример #2
0
        /// <summary>
        /// Заполнение значений доверенности и документа с основанием "Другой документ".
        /// </summary>
        /// <param name="newValue">Основание.</param>
        /// <param name="powerOfAttorney">Доверенность.</param>
        /// <param name="basisDocument">Документ основания.</param>
        /// <param name="powerOfAttorneyValues">Список доверенностей.</param>
        /// <param name="basisDocumentValues">Список документов основания.</param>
        private static void FillBasisDocuments(string newValue,
                                               INavigationDialogValue <IPowerOfAttorney> powerOfAttorney,
                                               CommonLibrary.IDropDownDialogValue basisDocument,
                                               IPowerOfAttorney[] powerOfAttorneyValues,
                                               string[] basisDocumentValues)
        {
            var basisIsAttorney = newValue == SignatureSettings.Info.Properties.Reason.GetLocalizedValue(SignatureSetting.Reason.PowerOfAttorney);
            var basisIsOther    = newValue == SignatureSettings.Info.Properties.Reason.GetLocalizedValue(SignatureSetting.Reason.Other);

            if (powerOfAttorney != null)
            {
                powerOfAttorney.IsVisible  = !basisIsOther;
                powerOfAttorney.IsRequired = basisIsAttorney;
                powerOfAttorney.IsEnabled  = basisIsAttorney;
                if (!powerOfAttorney.IsEnabled)
                {
                    powerOfAttorney.Value = null;
                }
                else
                {
                    powerOfAttorney.Value = powerOfAttorneyValues.Length == 1 ? powerOfAttorneyValues.Single() : null;
                }
            }
            if (basisDocument != null)
            {
                basisDocument.IsVisible  = basisIsOther;
                basisDocument.IsRequired = basisIsOther;
                if (!basisDocument.IsVisible)
                {
                    basisDocument.Value = null;
                }
                else
                {
                    basisDocument.Value = basisDocumentValues.Length == 1 ? basisDocumentValues.Single() : null;
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Диалог с запросом параметров для отчетов по журналам регистрации.
        /// </summary>
        /// <param name="reportName">Наименование отчета.</param>
        /// <param name="direction">Направление документопотока журнала.</param>
        /// <param name="documentRegisterValue">Журнал.</param>
        /// <param name="helpCode">Код справки.</param>
        /// <returns>Возвращает структуру формата - запустить отчет, дата начала, дата окончания, журнал.</returns>
        public static Structures.Module.DocumentRegisterReportParametrs ShowDocumentRegisterReportDialog(string reportName, Enumeration direction,
                                                                                                         IDocumentRegister documentRegisterValue,
                                                                                                         string helpCode)
        {
            var personalSettings = Docflow.PublicFunctions.PersonalSetting.GetPersonalSettings(Employees.Current);
            var dialog           = Dialogs.CreateInputDialog(reportName);

            dialog.HelpCode = helpCode;

            var settingsBeginDate = Docflow.PublicFunctions.PersonalSetting.GetStartDate(personalSettings);
            var beginDate         = dialog.AddDate(Resources.StartDate, true, settingsBeginDate ?? Calendar.UserToday);
            var settingsEndDate   = Docflow.PublicFunctions.PersonalSetting.GetEndDate(personalSettings);
            var endDate           = dialog.AddDate(Resources.EndDate, true, settingsEndDate ?? Calendar.UserToday);

            INavigationDialogValue <IDocumentRegister> documentRegister = null;

            if (documentRegisterValue == null)
            {
                var documentRegisters = Functions.Module.Remote.GetFilteredDocumentRegistersForReport(direction);
                IDocumentRegister defaultDocumentRegister = null;
                if (personalSettings != null)
                {
                    if (direction == Docflow.DocumentRegister.DocumentFlow.Incoming)
                    {
                        defaultDocumentRegister = personalSettings.IncomingDocRegister;
                    }
                    else if (direction == Docflow.DocumentRegister.DocumentFlow.Outgoing)
                    {
                        defaultDocumentRegister = personalSettings.OutgoingDocRegister;
                    }
                    else
                    {
                        defaultDocumentRegister = personalSettings.InnerDocRegister;
                    }
                }

                if (documentRegisters.Count == 1)
                {
                    documentRegister = dialog.AddSelect(Docflow.Resources.DocumentRegister, true, documentRegisters.FirstOrDefault()).From(documentRegisters);
                }
                else
                {
                    documentRegister = dialog.AddSelect(Docflow.Resources.DocumentRegister, true, defaultDocumentRegister).From(documentRegisters);
                }
            }

            dialog.SetOnButtonClick((args) =>
            {
                Docflow.PublicFunctions.Module.CheckReportDialogPeriod(args, beginDate, endDate);
            });

            dialog.Buttons.AddOkCancel();
            dialog.Buttons.Default = DialogButtons.Ok;
            if (dialog.Show() == DialogButtons.Ok)
            {
                if (documentRegisterValue == null)
                {
                    documentRegisterValue = documentRegister.Value;
                }
                return(Structures.Module.DocumentRegisterReportParametrs.Create(true, beginDate.Value, endDate.Value, documentRegisterValue));
            }
            else
            {
                documentRegisterValue = null;
                return(Structures.Module.DocumentRegisterReportParametrs.Create(false, null, null, null));
            }
        }
Пример #4
0
        public virtual void ReturnDocument(Sungero.Domain.Client.ExecuteActionArgs e)
        {
            if (Functions.Module.IsLockedByOther(_obj, e))
            {
                return;
            }

            var tracking = _obj.Tracking.Where(l => (!l.ReturnDate.HasValue || Equals(l.ReturnResult, Docflow.OfficialDocumentTracking.ReturnResult.AtControl)) &&
                                               l.ReturnDeadline.HasValue &&
                                               (l.Action == Docflow.OfficialDocumentTracking.Action.Delivery ||
                                                l.Action == Docflow.OfficialDocumentTracking.Action.Sending)).ToList();

            if (!tracking.Any())
            {
                Dialogs.NotifyMessage(Docflow.Resources.ReturnDocumentActiveTrackingNotFound);
                return;
            }

            var employees = new List <Company.IEmployee>();

            foreach (var emp in tracking.Select(l => l.DeliveredTo))
            {
                if (!employees.Contains(emp))
                {
                    employees.Add(emp);
                }
            }
            var employee = employees.FirstOrDefault();

            var dialog = Dialogs.CreateInputDialog(Docflow.Resources.ReturnDocumentDialog, _obj.Name);

            dialog.HelpCode = Constants.OfficialDocument.HelpCode.Return;
            INavigationDialogValue <Company.IEmployee> employeeDialog = null;

            if (employees.Count > 1)
            {
                employeeDialog = dialog.AddSelect(Docflow.Resources.ReturnDocumentEmployee, true, employee).From(employees);
            }
            var returnDate = dialog.AddDate(Docflow.Resources.ReturnDocumentDate, true, Calendar.UserToday);

            var returnDocument = dialog.Buttons.AddCustom(Docflow.Resources.ReturnDocument);

            dialog.Buttons.Default = returnDocument;

            var hasAvailableTasks = false;

            foreach (var row in tracking)
            {
                if (row.ReturnTask.AccessRights.CanRead())
                {
                    hasAvailableTasks = hasAvailableTasks || Functions.OfficialDocument.Remote.GetReturnAssignments(row.ReturnTask).Any();
                }
            }
            CommonLibrary.DialogButton openAssignments = null;
            if (hasAvailableTasks)
            {
                openAssignments = dialog.Buttons.AddCustom(Docflow.Resources.ReturnDocumentOpenAssignment);
            }

            dialog.Buttons.AddCancel();

            dialog.SetOnRefresh(d =>
            {
                if (employeeDialog != null)
                {
                    employee = employeeDialog.Value;
                }
                if (employee == null)
                {
                    return;
                }

                var employeeTracking = tracking.Where(l => Equals(l.DeliveredTo, employee));
                foreach (var row in employeeTracking)
                {
                    if (returnDate.Value.HasValue && returnDate.Value.Value < row.DeliveryDate.Value)
                    {
                        d.AddError(Docflow.Resources.ReturnDocumentDeliveryAndReturnDate, returnDate);
                        return;
                    }
                }
            });

            var result = dialog.Show();

            if (result != DialogButtons.Cancel)
            {
                if (employeeDialog != null)
                {
                    employee = employeeDialog.Value;
                }
                var employeeTracking = tracking.Where(l => Equals(l.DeliveredTo, employee));

                if (result == returnDocument)
                {
                    var returnResult = Docflow.OfficialDocumentTracking.ReturnResult.Returned;
                    foreach (var row in employeeTracking)
                    {
                        row.ReturnDate   = returnDate.Value;
                        row.ReturnResult = returnResult;
                    }

                    _obj.Save();
                    Dialogs.NotifyMessage(Docflow.Resources.ReturnDocumentNotify);
                }

                if (result == openAssignments)
                {
                    try
                    {
                        var returnTasks = employeeTracking.Select(i => i.ReturnTask).ToList();
                        var assignments = Functions.OfficialDocument.Remote.GetReturnAssignments(returnTasks);

                        if (assignments.Count == 1)
                        {
                            assignments.Single().Show();
                        }
                        else if (assignments.Count > 1)
                        {
                            assignments.Show();
                        }
                        else if (!assignments.Any())
                        {
                            Dialogs.NotifyMessage(Docflow.Resources.JobToReturnNotFound);
                        }
                    }
                    catch (Exception)
                    {
                        // TODO: продумать ситуацию когда на часть задач все-таки есть права.
                        Dialogs.NotifyMessage(Docflow.Resources.JobToReturnNotFound);
                    }
                }
            }
        }
Пример #5
0
        public virtual void ReturnFromCounterparty(Sungero.Domain.Client.ExecuteActionArgs e)
        {
            // TODO: продумать ситуацию когда на часть задач все-таки есть права.
            if (Functions.Module.IsLockedByOther(_obj, e))
            {
                return;
            }

            var tracking = _obj.Tracking.Where(l => (!l.ReturnDate.HasValue || Equals(l.ReturnResult, Docflow.OfficialDocumentTracking.ReturnResult.AtControl)) &&
                                               l.ReturnDeadline.HasValue &&
                                               l.Action == Docflow.OfficialDocumentTracking.Action.Endorsement).ToList();

            if (tracking.Any() && tracking.All(t => t.ExternalLinkId != null))
            {
                Dialogs.NotifyMessage(OfficialDocuments.Resources.TrackingNoneReturnFromCounterparty);
                return;
            }

            tracking = tracking.Where(t => t.ReturnTask != null).ToList();

            if (!tracking.Any())
            {
                Dialogs.NotifyMessage(Docflow.Resources.ReturnDocumentActiveTrackingNotFound);
                return;
            }

            var employees = new List <Company.IEmployee>();

            foreach (var emp in tracking.Select(l => l.DeliveredTo))
            {
                if (!employees.Contains(emp))
                {
                    employees.Add(emp);
                }
            }
            var employee = employees.FirstOrDefault();

            var dialog = Dialogs.CreateInputDialog(Docflow.Resources.ReturnDocumentDialog, _obj.Name);

            dialog.HelpCode = Constants.OfficialDocument.HelpCode.ReturnFromCounterparty;
            INavigationDialogValue <Company.IEmployee> employeeDialog = null;

            if (employees.Count > 1)
            {
                employeeDialog = dialog.AddSelect(Docflow.Resources.ReturnDocumentEmployee, true, employee).From(employees);
            }
            var returnDate = dialog.AddDate(Docflow.Resources.ReturnDocumentDate, true, Calendar.UserToday);

            // Принудительно увеличиваем ширину диалога в Web для корректного отображения кнопок.
            if (ClientApplication.ApplicationType == ApplicationType.Web)
            {
                var fakeControl = dialog.AddString("12345678901234", false);
                fakeControl.IsVisible = false;
            }

            var signed = dialog.Buttons.AddCustom(Docflow.Resources.ReturnDocumentSigned);

            dialog.Buttons.Default = signed;
            var notSigned = dialog.Buttons.AddCustom(Docflow.Resources.ReturnDocumentNotSigned);

            var hasAvailableTasks = false;

            foreach (var row in tracking)
            {
                if (row.ReturnTask.AccessRights.CanRead())
                {
                    hasAvailableTasks = hasAvailableTasks || Functions.OfficialDocument.Remote.GetReturnAssignments(row.ReturnTask).Any();
                }
            }
            CommonLibrary.DialogButton openAssignments = null;
            if (hasAvailableTasks)
            {
                openAssignments = dialog.Buttons.AddCustom(Docflow.Resources.ReturnDocumentOpenAssignment);
            }

            dialog.Buttons.AddCancel();

            var result = dialog.Show();

            if (result != DialogButtons.Cancel)
            {
                if (employeeDialog != null)
                {
                    employee = employeeDialog.Value;
                }
                var employeeTracking = tracking.Where(l => Equals(l.DeliveredTo, employee));

                if (result == signed || result == notSigned)
                {
                    var returnResult = result == signed ?
                                       Docflow.OfficialDocumentTracking.ReturnResult.Signed :
                                       Docflow.OfficialDocumentTracking.ReturnResult.NotSigned;
                    foreach (var row in employeeTracking)
                    {
                        row.ReturnDate   = returnDate.Value;
                        row.ReturnResult = returnResult;
                    }

                    _obj.Save();
                    Dialogs.NotifyMessage(Docflow.Resources.ReturnDocumentNotify);
                }

                if (result == openAssignments)
                {
                    try
                    {
                        var returnTasks = employeeTracking.Select(i => i.ReturnTask).ToList();
                        var assignments = Functions.OfficialDocument.Remote.GetReturnAssignments(returnTasks);

                        if (assignments.Count == 1)
                        {
                            assignments.Single().Show();
                        }
                        else if (assignments.Count > 1)
                        {
                            assignments.Show();
                        }
                        else if (!assignments.Any())
                        {
                            Dialogs.NotifyMessage(Docflow.Resources.JobToReturnNotFound);
                        }
                    }
                    catch (Exception)
                    {
                        Dialogs.NotifyMessage(Docflow.Resources.JobToReturnNotFound);
                    }
                }
            }
        }
        public override void BeforeExecute(Sungero.Reporting.Client.BeforeExecuteEventArgs e)
        {
            if (AssignmentCompletionReport.PeriodBegin.HasValue && AssignmentCompletionReport.PeriodEnd.HasValue)
            {
                return;
            }

            // Запросить параметры.
            var dialog = Dialogs.CreateInputDialog(Resources.AssignmentCompletionReportDialog);

            dialog.HelpCode = Constants.AssignmentCompletionReport.HelpCode;
            dialog.Buttons.AddOkCancel();

            CommonLibrary.IDateDialogValue periodBegin = null;
            CommonLibrary.IDateDialogValue periodEnd   = null;
            INavigationDialogValue <Company.IDepartment>   department   = null;
            INavigationDialogValue <Company.IEmployee>     performer    = null;
            INavigationDialogValue <Company.IBusinessUnit> businessUnit = null;

            CommonLibrary.IBooleanDialogValue loadOldAssignments = null;

            // Период.
            var today = Calendar.UserToday;

            if (!AssignmentCompletionReport.PeriodBegin.HasValue)
            {
                periodBegin = dialog.AddDate(Resources.DocumentUsagePeriodBegin, true, today.AddDays(-30));
            }
            if (!AssignmentCompletionReport.PeriodEnd.HasValue)
            {
                periodEnd = dialog.AddDate(Resources.DocumentUsagePeriodEnd, true, today);
            }

            // НОР.
            if (AssignmentCompletionReport.BusinessUnit == null)
            {
                businessUnit = dialog.AddSelect(Resources.BusinessUnit, false, Company.BusinessUnits.Null);
            }

            // Подразделение.
            if (AssignmentCompletionReport.Department == null)
            {
                department = dialog.AddSelect(Resources.Department, false, Company.Departments.Null);
            }

            // Сотрудник.
            if (AssignmentCompletionReport.Performer == null)
            {
                performer = dialog.AddSelect(Resources.Employee, false, Company.Employees.Null);
            }

            if (AssignmentCompletionReport.LoadOldAssignments == null)
            {
                loadOldAssignments = dialog.AddBoolean(Resources.AddAssignmentsWithDeadlineBeforePeriodBegins, true);
            }

            dialog.SetOnButtonClick((args) =>
            {
                Functions.Module.CheckReportDialogPeriod(args, periodBegin, periodEnd);
            });

            if (dialog.Show() != DialogButtons.Ok)
            {
                e.Cancel = true;
                return;
            }

            if (!AssignmentCompletionReport.PeriodBegin.HasValue)
            {
                AssignmentCompletionReport.PeriodBegin = periodBegin.Value;
            }
            if (!AssignmentCompletionReport.PeriodEnd.HasValue)
            {
                AssignmentCompletionReport.ClientPeriodEnd = periodEnd.Value.Value;
                AssignmentCompletionReport.PeriodEnd       = periodEnd.Value.Value.EndOfDay();
            }

            if (AssignmentCompletionReport.BusinessUnit == null)
            {
                AssignmentCompletionReport.BusinessUnit = businessUnit.Value;
            }

            if (AssignmentCompletionReport.Department == null)
            {
                AssignmentCompletionReport.Department = department.Value;
            }

            if (AssignmentCompletionReport.Performer == null)
            {
                AssignmentCompletionReport.Performer = Users.As(performer.Value);
            }

            if (AssignmentCompletionReport.LoadOldAssignments == null)
            {
                AssignmentCompletionReport.LoadOldAssignments = loadOldAssignments.Value;
            }
        }
        public override void BeforeExecute(Sungero.Reporting.Client.BeforeExecuteEventArgs e)
        {
            if (RegistrationSettingReport.BusinessUnit != null && !string.IsNullOrWhiteSpace(RegistrationSettingReport.Direction))
            {
                return;
            }

            RegistrationSettingReport.ParamsDescriprion = string.Empty;

            INavigationDialogValue <IBusinessUnit> businessUnit = null;

            CommonLibrary.IDropDownDialogValue documentFlow = null;

            var dialog = Dialogs.CreateInputDialog(Docflow.Resources.RegistrationSettingReport);

            dialog.HelpCode = Constants.RegistrationSettingReport.HelpCode;
            dialog.Buttons.AddOkCancel();

            // НОР.
            if (RegistrationSettingReport.BusinessUnit == null)
            {
                businessUnit = dialog.AddSelect(Docflow.Resources.BusinessUnit, false, BusinessUnits.Null);
            }

            // Документопоток.
            var avalableDirections = new List <Enumeration>()
            {
                RegistrationSetting.DocumentFlow.Incoming, RegistrationSetting.DocumentFlow.Outgoing,
                RegistrationSetting.DocumentFlow.Inner, RegistrationSetting.DocumentFlow.Contracts
            };
            var documentFlows = avalableDirections.Select(a => RegistrationSettings.Info.Properties.DocumentFlow.GetLocalizedValue(a)).ToList();

            if (string.IsNullOrWhiteSpace(RegistrationSettingReport.Direction))
            {
                documentFlow = dialog.AddSelect(Docflow.Resources.Direction, false).From(documentFlows.ToArray());
            }
            var filterDepartmentsForBusinessUnits = dialog.AddBoolean(Reports.Resources.ApprovalRulesConsolidatedReport.FilterDepartmentsForBusinessUnitsDialogCheckBox, true);

            // Показ диалога.
            if (dialog.Show() == DialogButtons.Ok)
            {
                if (RegistrationSettingReport.BusinessUnit == null && businessUnit.Value != null)
                {
                    RegistrationSettingReport.BusinessUnit = businessUnit.Value;
                }

                if (string.IsNullOrWhiteSpace(RegistrationSettingReport.Direction))
                {
                    RegistrationSettingReport.DirectionLabel = documentFlow.Value;
                    RegistrationSettingReport.Direction      = documentFlow.Value == null ? string.Empty : avalableDirections[documentFlows.IndexOf(documentFlow.Value)].Value;
                }

                if (filterDepartmentsForBusinessUnits != null)
                {
                    RegistrationSettingReport.FilterDepartmentsForBusinessUnits = filterDepartmentsForBusinessUnits.Value;
                }
            }
            else
            {
                e.Cancel = true;
            }

            // Получить адресс сервиса гиперссылок.
            var userHyperlink = Sungero.Domain.Client.Hyperlinks.HyperlinkExtensions.CreateHyperlink(Users.Current);

            RegistrationSettingReport.HyperlinkServer = string.Format("{0}://{1}{2}", userHyperlink.Scheme, userHyperlink.Host, userHyperlink.LocalPath);
        }
Пример #8
0
        /// <summary>
        /// Диалог заполнения информации о покупателе.
        /// </summary>
        public virtual void BuyerTitlePropertiesFillingDialog()
        {
            var taxDocumentClassifier = Functions.AccountingDocumentBase.Remote.GetTaxDocumentClassifier(_obj);
            var isAct    = _obj.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Act;
            var isTorg12 = _obj.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.Waybill;
            var isDpt    = _obj.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer &&
                           taxDocumentClassifier == Exchange.PublicConstants.Module.TaxDocumentClassifier.GoodsTransferSeller;
            var isDprr = _obj.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer &&
                         taxDocumentClassifier == Exchange.PublicConstants.Module.TaxDocumentClassifier.WorksTransferSeller;
            var isUtdAny           = _obj.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer;
            var isUtdCorrection    = isUtdAny && _obj.IsAdjustment == true;
            var isUtdNotCorrection = isUtdAny && _obj.IsAdjustment != true;
            var isWaybill          = isTorg12 || isDpt;
            var isContractStatment = isAct || isDprr;

            if (!isUtdAny && !isWaybill && !isContractStatment)
            {
                return;
            }

            var dialog = Dialogs.CreateInputDialog(AccountingDocumentBases.Resources.PropertiesFillingDialog_Title);

            if (isTorg12)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.Waybill;
            }
            else if (isAct)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.ContractStatement;
            }
            else if (isDpt)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.GoodsTransfer;
            }
            else if (isDprr)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.WorksTransfer;
            }
            else if (isUtdNotCorrection)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.UniversalTransfer;
            }
            else if (isUtdCorrection)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.UniversalCorrectionTransfer;
            }

            Action <CommonLibrary.InputDialogRefreshEventArgs> refresh = null;
            var signatories = Functions.OfficialDocument.Remote.GetSignatories(_obj);

            var dialogText = string.Empty;

            if (isUtdNotCorrection)
            {
                dialogText = AccountingDocumentBases.Resources.PropertiesFillingDialog_Text_Universal;
            }

            if (isUtdCorrection)
            {
                dialogText = AccountingDocumentBases.Resources.PropertiesFillingDialog_Text_UniversalCorrection;
            }

            if (isWaybill)
            {
                dialogText = AccountingDocumentBases.Resources.PropertiesFillingDialog_Text_Waybill;
            }

            if (isContractStatment)
            {
                dialogText = AccountingDocumentBases.Resources.PropertiesFillingDialog_Text_Act;
            }

            dialog.Text = dialogText;

            var defaultSignatory = Company.Employees.Null;

            if (signatories.Any(s => _obj.OurSignatory != null && Equals(s.EmployeeId, _obj.OurSignatory.Id)))
            {
                defaultSignatory = _obj.OurSignatory;
            }
            else if (signatories.Any(s => Company.Employees.Current != null && Equals(s.EmployeeId, Company.Employees.Current.Id)))
            {
                defaultSignatory = Company.Employees.Current;
            }
            else if (signatories.Select(s => s.EmployeeId).Distinct().Count() == 1)
            {
                defaultSignatory = Functions.AccountingDocumentBase.Remote.GetEmployeesByIds(signatories.Select(s => s.EmployeeId).ToList()).FirstOrDefault();
            }

            // Поле Подписал.
            var defaultEmployees = Functions.AccountingDocumentBase.Remote.GetEmployeesByIds(signatories.Select(s => s.EmployeeId).ToList());
            var signatory        = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_SignedBy, true, Company.Employees.Null)
                                   .From(defaultEmployees.Distinct());

            // Поле Полномочия.
            CommonLibrary.IDropDownDialogValue hasAuthority = null;
            if (!isAct && !isTorg12)
            {
                hasAuthority = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority, true, 0)
                               .From(AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_Register,
                                     AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_Deal,
                                     AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_DealAndRegister);
                hasAuthority.IsEnabled = !isUtdCorrection;
            }

            // Поле Основание и связанные с ним Доверенность/Документ.
            CommonLibrary.IDropDownDialogValue        basis           = null;
            INavigationDialogValue <IPowerOfAttorney> powerOfAttorney = null;

            CommonLibrary.IDropDownDialogValue basisDocument = null;
            if (!isTorg12)
            {
                basis           = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_Basis, true, 0);
                powerOfAttorney = dialog.AddSelect(PowerOfAttorneys.Info.LocalizedName, false, PowerOfAttorneys.Null);

                if (!isAct)
                {
                    basisDocument = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_Document, false, null);
                }
            }

            // Дата подписания (Дата согласования, если УКД).
            var signingLable = isUtdCorrection ?
                               AccountingDocumentBases.Resources.PropertiesFillingDialog_DateApproving :
                               AccountingDocumentBases.Resources.PropertiesFillingDialog_SigningDate;
            var signingDate = dialog.AddDate(signingLable, true, Calendar.UserToday);

            // Результат и Разногласия.
            CommonLibrary.IDropDownDialogValue        result       = null;
            CommonLibrary.IMultilineStringDialogValue disagreement = null;
            if (!isUtdCorrection && !isContractStatment)
            {
                result = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_Result, true, 0)
                         .From(AccountingDocumentBases.Resources.PropertiesFillingDialog_Result_Accepted,
                               AccountingDocumentBases.Resources.PropertiesFillingDialog_Result_AcceptedWithDisagreement);
                disagreement = dialog.AddMultilineString(AccountingDocumentBases.Resources.PropertiesFillingDialog_Disagreement, false);
            }

            // Поле Результат для УКД.
            CommonLibrary.IDropDownDialogValue adjustmentResult = null;
            if (isUtdCorrection)
            {
                adjustmentResult = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_Result, true, 0)
                                   .From(AccountingDocumentBases.Resources.PropertiesFillingDialog_AdjustmentResult_AgreedChanges);
                adjustmentResult.IsEnabled = false;
            }

            // Груз принял получатель груза.
            CommonLibrary.IBooleanDialogValue          isSameConsignee = null;
            INavigationDialogValue <Company.IEmployee> consignee       = null;

            CommonLibrary.IDropDownDialogValue        consigneeBasis    = null;
            INavigationDialogValue <IPowerOfAttorney> consigneeAttorney = null;

            CommonLibrary.IStringDialogValue consigneeDocument = null;
            if (isWaybill || isUtdNotCorrection)
            {
                isSameConsignee = dialog.AddBoolean(AccountingDocumentBases.Resources.PropertiesFillingDialog_SameConsignee, true);
                consignee       = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_Consignee, false, Company.Employees.Null)
                                  .Where(x => Equals(x.Status, CoreEntities.DatabookEntry.Status.Active));
                consigneeBasis    = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_ConsigneeBasis, false, 0);
                consigneeAttorney = dialog.AddSelect(PowerOfAttorneys.Info.LocalizedName, false, PowerOfAttorneys.Null);
                consigneeDocument = dialog.AddString(AccountingDocumentBases.Resources.PropertiesFillingDialog_Document, false);
            }

            CommonLibrary.CustomDialogButton saveAndSignButton = null;
            if (signatories.Any(s => Users.Current != null && Equals(s.EmployeeId, Users.Current.Id)))
            {
                saveAndSignButton = dialog.Buttons.AddCustom(AccountingDocumentBases.Resources.PropertiesFillingDialog_SaveAndSign);
            }

            var saveButton = dialog.Buttons.AddCustom(AccountingDocumentBases.Resources.PropertiesFillingDialog_Save);

            dialog.Buttons.Default = saveAndSignButton ?? saveButton;
            var cancelButton = dialog.Buttons.AddCancel();

            string[]                 basisValues           = null;
            IPowerOfAttorney[]       powerOfAttorneyValues = null;
            string[]                 basisDocumentValues   = null;
            List <ISignatureSetting> settings = null;

            IPowerOfAttorney[] consigneePowerOfAttorneyValues = null;

            if (basis != null)
            {
                basis.SetOnValueChanged(bv => FillBasisDocuments(bv.NewValue, powerOfAttorney, basisDocument, powerOfAttorneyValues, basisDocumentValues));
            }

            signatory.SetOnValueChanged(
                (sc) =>
            {
                settings = Functions.OfficialDocument.Remote.GetSignatureSettings(_obj, sc.NewValue);
                if (basis != null)
                {
                    basisValues = settings.Select(s => s.Reason).Distinct()
                                  .Where(r => !isAct || r != SignatureSetting.Reason.Other)
                                  .OrderBy(r => r != SignatureSetting.Reason.Duties)
                                  .ThenBy(r => r != SignatureSetting.Reason.PowerOfAttorney)
                                  .Select(r => SignatureSettings.Info.Properties.Reason.GetLocalizedValue(r)).ToArray();
                    basis.From(basisValues);
                    basis.IsEnabled  = sc.NewValue != null;
                    basis.IsRequired = sc.NewValue != null;
                }
                if (powerOfAttorney != null)
                {
                    powerOfAttorneyValues = settings.Where(s => s.Reason == SignatureSetting.Reason.PowerOfAttorney)
                                            .Select(s => s.Document).OfType <IPowerOfAttorney>().Where(d => d.AccessRights.CanRead(Users.Current)).ToArray();
                    powerOfAttorney.From(powerOfAttorneyValues);
                }
                if (basisDocument != null)
                {
                    basisDocumentValues = settings.Where(s => s.Reason == SignatureSetting.Reason.Other).Select(s => s.DocumentInfo).ToArray();
                    basisDocument.From(basisDocumentValues);
                }
                if (basis != null)
                {
                    basis.Value = basisValues.FirstOrDefault();
                    FillBasisDocuments(basis.Value, powerOfAttorney, basisDocument, powerOfAttorneyValues, basisDocumentValues);
                }
            });
            signatory.Value = defaultSignatory;

            Action <CommonLibrary.InputDialogValueChangedEventArgs <string> > consigneeBasisChanged =
                cb =>
            {
                var basisIsDuties   = cb.NewValue == SignatureSettings.Info.Properties.Reason.GetLocalizedValue(SignatureSetting.Reason.Duties);
                var basisIsAttorney = cb.NewValue == SignatureSettings.Info.Properties.Reason.GetLocalizedValue(SignatureSetting.Reason.PowerOfAttorney);
                var basisIsOther    = cb.NewValue == SignatureSettings.Info.Properties.Reason.GetLocalizedValue(SignatureSetting.Reason.Other);

                if (consigneeAttorney != null)
                {
                    consigneeAttorney.IsVisible  = !basisIsOther;
                    consigneeAttorney.IsRequired = basisIsAttorney;
                    consigneeAttorney.IsEnabled  = basisIsAttorney;
                    if (!consigneeAttorney.IsEnabled)
                    {
                        consigneeAttorney.Value = null;
                    }
                    else
                    {
                        consigneeAttorney.Value = consigneePowerOfAttorneyValues.Length == 1 ? consigneePowerOfAttorneyValues.SingleOrDefault() : null;
                    }
                }

                if (consigneeDocument != null)
                {
                    consigneeDocument.IsVisible  = basisIsOther;
                    consigneeDocument.IsRequired = basisIsOther;
                    if (!consigneeDocument.IsVisible)
                    {
                        consigneeDocument.Value = null;
                    }
                }
            };

            if (consignee != null)
            {
                consignee.SetOnValueChanged(
                    ce =>
                {
                    var cbValues = new List <string>();
                    if (ce.NewValue != null)
                    {
                        cbValues.Add(SignatureSettings.Info.Properties.Reason.GetLocalizedValue(SignatureSetting.Reason.Duties));
                        cbValues.Add(SignatureSettings.Info.Properties.Reason.GetLocalizedValue(SignatureSetting.Reason.PowerOfAttorney));
                        if (!isTorg12)
                        {
                            cbValues.Add(SignatureSettings.Info.Properties.Reason.GetLocalizedValue(SignatureSetting.Reason.Other));
                        }

                        consigneePowerOfAttorneyValues = Functions.PowerOfAttorney.Remote.GetActivePowerOfAttorneys(ce.NewValue, signingDate.Value).ToArray();
                    }
                    else
                    {
                        consigneePowerOfAttorneyValues = new IPowerOfAttorney[0];
                    }

                    consigneeBasis.From(cbValues.ToArray());
                    consigneeAttorney.From(consigneePowerOfAttorneyValues);

                    consigneeBasis.Value = cbValues.OrderBy(v => v != consigneeBasis.Value).FirstOrDefault();
                    consigneeBasisChanged.Invoke(new CommonLibrary.InputDialogValueChangedEventArgs <string>(null, consigneeBasis.Value));
                });
            }

            if (consigneeBasis != null)
            {
                consigneeBasis.SetOnValueChanged(consigneeBasisChanged);
            }

            signingDate.SetOnValueChanged(
                sd =>
            {
                if (consigneeAttorney != null)
                {
                    if (sd.NewValue.HasValue && consignee.Value != null)
                    {
                        consigneePowerOfAttorneyValues = Functions.PowerOfAttorney.Remote.GetActivePowerOfAttorneys(consignee.Value, signingDate.Value).ToArray();
                    }
                    else
                    {
                        consigneePowerOfAttorneyValues = new IPowerOfAttorney[0];
                    }

                    consigneeAttorney.From(consigneePowerOfAttorneyValues);
                    consigneeBasisChanged.Invoke(new CommonLibrary.InputDialogValueChangedEventArgs <string>(null, consigneeBasis.Value));
                }
            });

            refresh = (r) =>
            {
                if (disagreement != null)
                {
                    disagreement.IsEnabled = result.Value == AccountingDocumentBases.Resources.PropertiesFillingDialog_Result_AcceptedWithDisagreement;
                }

                if (isSameConsignee != null)
                {
                    var needConsignee = !isSameConsignee.Value.Value;
                    consignee.IsEnabled       = needConsignee;
                    consignee.IsRequired      = needConsignee;
                    consigneeBasis.IsEnabled  = needConsignee && consignee.Value != null;
                    consigneeBasis.IsRequired = needConsignee && consignee.Value != null;

                    if (!needConsignee)
                    {
                        consignee.Value      = Company.Employees.Null;
                        consigneeBasis.Value = string.Empty;
                    }
                }
            };

            dialog.SetOnRefresh(refresh);
            dialog.SetOnButtonClick(
                (b) =>
            {
                if (b.Button == saveAndSignButton || b.Button == saveButton)
                {
                    if (!b.IsValid)
                    {
                        return;
                    }

                    var consigneeValue = isSameConsignee != null ? (isSameConsignee.Value == true ? signatory.Value : consignee.Value) : null;
                    var signatoryPowerOfAttorneyValue = powerOfAttorney != null ? powerOfAttorney.Value : null;
                    var signatoryOtherReasonValue     = basisDocument != null ? basisDocument.Value : null;
                    var consigneePowerOfAttorneyValue = consigneeAttorney != null ? consigneeAttorney.Value : null;
                    var consigneeOtherReasonValue     = consigneeDocument != null ? consigneeDocument.Value : null;
                    var errorlist = Functions.AccountingDocumentBase.Remote
                                    .TitleDialogValidationErrors(_obj, signatory.Value, consignee != null ? consignee.Value : null,
                                                                 signatoryPowerOfAttorneyValue, consigneePowerOfAttorneyValue,
                                                                 signatoryOtherReasonValue, consigneeOtherReasonValue);
                    foreach (var errors in errorlist.GroupBy(e => e.Text))
                    {
                        var controls = new List <CommonLibrary.IDialogControl>();
                        foreach (var error in errors)
                        {
                            if (error.Type == Constants.AccountingDocumentBase.GenerateTitleTypes.Signatory)
                            {
                                controls.Add(signatory);
                            }
                            if (error.Type == Constants.AccountingDocumentBase.GenerateTitleTypes.Consignee)
                            {
                                controls.Add(consignee);
                            }
                            if (error.Type == Constants.AccountingDocumentBase.GenerateTitleTypes.SignatoryPowerOfAttorney)
                            {
                                controls.Add(powerOfAttorney);
                            }
                            if (error.Type == Constants.AccountingDocumentBase.GenerateTitleTypes.ConsigneePowerOfAttorney)
                            {
                                controls.Add(consigneeAttorney);
                            }
                        }
                        b.AddError(errors.Key, controls.ToArray());
                    }

                    if (b.IsValid)
                    {
                        var signed = (result != null && result.IsVisible) ?
                                     result.Value != AccountingDocumentBases.Resources.PropertiesFillingDialog_Result_AcceptedWithDisagreement :
                                     true;
                        var consigneeBasisValue      = isSameConsignee != null && basis != null ? (isSameConsignee.Value == true ? basis.Value : consigneeBasis.Value) : string.Empty;
                        var disagreementValue        = disagreement != null ? disagreement.Value : string.Empty;
                        var basisValue               = basis != null ? basis.Value : string.Empty;
                        var hasAuthorityValue        = hasAuthority != null ? hasAuthority.Value : string.Empty;
                        var signatoryPowerOfAttorney = Structures.AccountingDocumentBase.Attorney.Create(signatoryPowerOfAttorneyValue, signatoryOtherReasonValue);
                        var consigneePowerOfAttorney = Structures.AccountingDocumentBase.Attorney.Create(consigneePowerOfAttorneyValue, consigneeOtherReasonValue);
                        var title = Structures.AccountingDocumentBase.BuyerTitle.Create();
                        title.ActOfDisagreement        = disagreementValue;
                        title.Signatory                = signatory.Value;
                        title.SignatoryPowersBase      = basisValue;
                        title.Consignee                = consigneeValue;
                        title.ConsigneePowersBase      = consigneeBasisValue;
                        title.SignResult               = signed;
                        title.SignatoryPowers          = hasAuthorityValue;
                        title.AcceptanceDate           = signingDate.Value;
                        title.SignatoryPowerOfAttorney = signatoryPowerOfAttorney.Document;
                        title.SignatoryOtherReason     = signatoryPowerOfAttorney.OtherReason;
                        title.ConsigneePowerOfAttorney = consigneePowerOfAttorney.Document;
                        title.ConsigneeOtherReason     = consigneePowerOfAttorney.OtherReason;

                        try
                        {
                            Functions.AccountingDocumentBase.Remote.GenerateAnswer(_obj, title, false);
                        }
                        catch (AppliedCodeException ex)
                        {
                            b.AddError(ex.Message);
                            return;
                        }
                        catch (ValidationException ex)
                        {
                            b.AddError(ex.Message);
                            return;
                        }
                        catch (Exception ex)
                        {
                            Logger.ErrorFormat("Error generation title: ", ex);
                            b.AddError(Sungero.Docflow.AccountingDocumentBases.Resources.ErrorBuyerTitlePropertiesFilling);
                            return;
                        }

                        if (b.Button == saveAndSignButton)
                        {
                            try
                            {
                                Functions.Module.ApproveWithAddenda(_obj, null, null, null, false, true, string.Empty);
                            }
                            catch (Exception ex)
                            {
                                b.AddError(ex.Message);
                            }
                        }
                    }
                }
            });
            dialog.Show();
        }
Пример #9
0
        /// <summary>
        /// Диалог заполнения информации о продавце.
        /// </summary>
        public virtual void SellerTitlePropertiesFillingDialog()
        {
            var isDpt              = _obj.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer;
            var isDprr             = _obj.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer;
            var isUtdAny           = _obj.FormalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer;
            var isUtdCorrection    = isUtdAny && _obj.IsAdjustment == true;
            var isUtdNotCorrection = isUtdAny && _obj.IsAdjustment != true;

            if (!isDpt && !isDprr && !isUtdAny)
            {
                return;
            }

            var dialog = Dialogs.CreateInputDialog(AccountingDocumentBases.Resources.PropertiesFillingDialog_SellerTitle);

            if (isDpt)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.SellerGoodsTransfer;
            }
            else if (isDprr)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.SellerWorksTransfer;
            }
            else if (isUtdNotCorrection)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.SellerUniversalTransfer;
            }
            else if (isUtdCorrection)
            {
                dialog.HelpCode = Constants.AccountingDocumentBase.HelpCodes.SellerUniversalCorrectionTransfer;
            }

            Action <CommonLibrary.InputDialogRefreshEventArgs> refresh = null;
            var signatories = Functions.OfficialDocument.Remote.GetSignatories(_obj);

            dialog.Text = AccountingDocumentBases.Resources.PropertiesFillingDialog_Text_SellerTitle;

            var defaultSignatory = Company.Employees.Null;

            if (signatories.Any(s => _obj.OurSignatory != null && Equals(s.EmployeeId, _obj.OurSignatory.Id)))
            {
                defaultSignatory = _obj.OurSignatory;
            }
            else if (signatories.Any(s => Company.Employees.Current != null && Equals(s.EmployeeId, Company.Employees.Current.Id)))
            {
                defaultSignatory = Company.Employees.Current;
            }
            else if (signatories.Select(s => s.EmployeeId).Distinct().Count() == 1)
            {
                defaultSignatory = Functions.AccountingDocumentBase.Remote.GetEmployeesByIds(signatories.Select(s => s.EmployeeId).ToList()).FirstOrDefault();
            }

            // Поле Подписал.
            var defaultEmployees = Functions.AccountingDocumentBase.Remote.GetEmployeesByIds(signatories.Select(s => s.EmployeeId).ToList());
            var signedBy         = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_SignedBy, true, Company.Employees.Null)
                                   .From(defaultEmployees.Distinct());

            // Поле Полномочия.
            CommonLibrary.IDropDownDialogValue hasAuthority = null;
            if (isDpt || isDprr)
            {
                hasAuthority = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority, true, 0)
                               .From(AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_DealAndRegister,
                                     AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_Register);
            }
            else if (isUtdAny && _obj.IsAdjustment != true)
            {
                hasAuthority = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority, true, 0)
                               .From(AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_DealAndRegisterAndInvoiceSignatory,
                                     AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_RegisterAndInvoiceSignatory);
            }
            else if (isUtdAny && _obj.IsAdjustment == true)
            {
                hasAuthority = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority, true, 0)
                               .From(AccountingDocumentBases.Resources.PropertiesFillingDialog_HasAuthority_RegisterAndInvoiceSignatory);
                hasAuthority.IsEnabled = false;
            }

            // Поле Основание и связанные с ним Доверенность/Документ.
            CommonLibrary.IDropDownDialogValue        basis    = null;
            INavigationDialogValue <IPowerOfAttorney> attorney = null;

            CommonLibrary.IDropDownDialogValue basisDocument = null;
            basis         = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_Basis, true, 0);
            attorney      = dialog.AddSelect(PowerOfAttorneys.Info.LocalizedName, false, PowerOfAttorneys.Null);
            basisDocument = dialog.AddSelect(AccountingDocumentBases.Resources.PropertiesFillingDialog_Document, false, null);

            CommonLibrary.CustomDialogButton saveAndSignButton = null;
            if (signatories.Any(s => Users.Current != null && Equals(s.EmployeeId, Users.Current.Id)))
            {
                saveAndSignButton = dialog.Buttons.AddCustom(AccountingDocumentBases.Resources.PropertiesFillingDialog_SaveAndSign);
            }

            var saveButton = dialog.Buttons.AddCustom(AccountingDocumentBases.Resources.PropertiesFillingDialog_Save);

            dialog.Buttons.Default = saveAndSignButton ?? saveButton;
            var cancelButton = dialog.Buttons.AddCancel();

            string[]                 basisValues         = null;
            IPowerOfAttorney[]       attorneyValues      = null;
            string[]                 basisDocumentValues = null;
            List <ISignatureSetting> settings            = null;

            if (basis != null)
            {
                basis.SetOnValueChanged(bv => FillBasisDocuments(bv.NewValue, attorney, basisDocument, attorneyValues, basisDocumentValues));
            }

            signedBy.SetOnValueChanged(
                (sc) =>
            {
                settings = Functions.OfficialDocument.Remote.GetSignatureSettings(_obj, sc.NewValue);
                if (basis != null)
                {
                    basisValues = settings.Select(s => s.Reason).Distinct()
                                  .OrderBy(r => r != SignatureSetting.Reason.Duties)
                                  .ThenBy(r => r != SignatureSetting.Reason.PowerOfAttorney)
                                  .Select(r => SignatureSettings.Info.Properties.Reason.GetLocalizedValue(r)).ToArray();
                    basis.From(basisValues);
                    basis.IsEnabled  = sc.NewValue != null;
                    basis.IsRequired = sc.NewValue != null;
                }
                if (attorney != null)
                {
                    attorneyValues = settings.Where(s => s.Reason == SignatureSetting.Reason.PowerOfAttorney)
                                     .Select(s => s.Document).OfType <IPowerOfAttorney>().Where(d => d.AccessRights.CanRead(Users.Current)).ToArray();
                    attorney.From(attorneyValues);
                }
                if (basisDocument != null)
                {
                    basisDocumentValues = settings.Where(s => s.Reason == SignatureSetting.Reason.Other).Select(s => s.DocumentInfo).ToArray();
                    basisDocument.From(basisDocumentValues);
                }
                if (basis != null)
                {
                    basis.Value = basisValues.FirstOrDefault();
                    FillBasisDocuments(basis.Value, attorney, basisDocument, attorneyValues, basisDocumentValues);
                }
            });
            signedBy.Value = defaultSignatory;

            dialog.SetOnRefresh(refresh);
            dialog.SetOnButtonClick(
                (b) =>
            {
                if (b.Button == saveAndSignButton || b.Button == saveButton)
                {
                    if (!b.IsValid)
                    {
                        return;
                    }
                }
                var signatoryAttorneyValue    = attorney != null ? attorney.Value : null;
                var signatoryOtherReasonValue = basisDocument != null ? basisDocument.Value : null;

                var errorlist = Functions.AccountingDocumentBase.Remote
                                .TitleDialogValidationErrors(_obj, signedBy.Value, null,
                                                             signatoryAttorneyValue, null,
                                                             signatoryOtherReasonValue, null);
                foreach (var errors in errorlist.GroupBy(e => e.Text))
                {
                    var controls = new List <CommonLibrary.IDialogControl>();
                    foreach (var error in errors)
                    {
                        if (error.Type == Constants.AccountingDocumentBase.GenerateTitleTypes.Signatory)
                        {
                            controls.Add(signedBy);
                        }
                        if (error.Type == Constants.AccountingDocumentBase.GenerateTitleTypes.SignatoryPowerOfAttorney)
                        {
                            controls.Add(attorney);
                        }
                    }
                    b.AddError(errors.Key, controls.ToArray());
                }

                if (b.IsValid)
                {
                    var basisValue        = basis != null ? basis.Value : string.Empty;
                    var hasAuthorityValue = hasAuthority != null ? hasAuthority.Value : string.Empty;
                    var signatoryAttorney = Structures.AccountingDocumentBase.Attorney.Create(signatoryAttorneyValue, signatoryOtherReasonValue);
                    var title             = Structures.AccountingDocumentBase.SellerTitle.Create(signedBy.Value, basisValue, hasAuthorityValue,
                                                                                                 signatoryAttorney.Document, signatoryAttorney.OtherReason);

                    try
                    {
                        Functions.AccountingDocumentBase.Remote.GenerateSellerTitle(_obj, title);
                    }
                    catch (AppliedCodeException ex)
                    {
                        b.AddError(ex.Message);
                        return;
                    }
                    catch (ValidationException ex)
                    {
                        b.AddError(ex.Message);
                        return;
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("Error generation title: ", ex);
                        b.AddError(Sungero.Docflow.AccountingDocumentBases.Resources.ErrorSellerTitlePropertiesFilling);
                        return;
                    }

                    if (b.Button == saveAndSignButton)
                    {
                        try
                        {
                            Functions.Module.ApproveWithAddenda(_obj, null, null, null, false, true, string.Empty);
                        }
                        catch (Exception ex)
                        {
                            b.AddError(ex.Message);
                        }
                    }
                }
            });

            dialog.Show();
        }
        public override void BeforeExecute(Sungero.Reporting.Client.BeforeExecuteEventArgs e)
        {
            // При запуске из диалога регистрации передается дата регистрации. Запрашивать доп.параметры не требуется.
            if (SkippedNumbersReport.RegistrationDate.HasValue || !string.IsNullOrEmpty(SkippedNumbersReport.Period))
            {
                return;
            }

            // Проверить, передан ли журнал регистрации.
            var reportDocumentRgister = SkippedNumbersReport.DocumentRegister;

            var description = string.Empty;

            INavigationDialogValue <IDocumentRegister> documentRegister = null;

            var dialog = Dialogs.CreateInputDialog(Docflow.Resources.SkippedNumbersReport);

            dialog.HelpCode = Constants.SkippedNumbersReport.HelpCode;

            // Журнал регистрации.
            var documentRegisterSpecified = SkippedNumbersReport.DocumentRegister != null;

            if (!documentRegisterSpecified)
            {
                documentRegister = dialog.AddSelect(Docflow.Resources.DocumentRegister, true, DocumentRegisters.Null);
            }
            IQueryable <IOfficialDocument> availableLeadingDocuments = null;

            // Ведущий документ.
            if (documentRegisterSpecified && SkippedNumbersReport.DocumentRegister.NumberingSection == DocumentRegister.NumberingSection.LeadingDocument)
            {
                availableLeadingDocuments = Docflow.Functions.Module.Remote.GetAvaliableLeadingDocuments();
            }
            var leadingDocumentSelect = dialog.AddSelect(Docflow.Resources.LeadingDocument, false, OfficialDocuments.Null)
                                        .From(availableLeadingDocuments);

            // Подразделение.
            var departmentSelect = dialog.AddSelect(Docflow.Resources.Department, false, Company.Departments.Null);

            // НОР.
            var businessUnitSelect = dialog.AddSelect(Docflow.Resources.BusinessUnit, false, Company.BusinessUnits.Null);

            var period = dialog.AddSelect(Reports.Resources.SkippedNumbersReport.Period, true).From(this.GetPeriods(SkippedNumbersReport.DocumentRegister));

            period.Value = Reports.Resources.SkippedNumbersReport.CurrentMonth;

            if (!documentRegisterSpecified)
            {
                documentRegister.SetOnValueChanged((arg) =>
                {
                    var periodValues = this.GetPeriods(arg.NewValue);
                    period.From(periodValues);
                    if (!periodValues.Contains(period.Value))
                    {
                        period.Value = string.Empty;
                    }
                });
            }

            dialog.SetOnButtonClick((arg) =>
            {
                if (reportDocumentRgister == null && documentRegister.Value != null)
                {
                    SkippedNumbersReport.DocumentRegister = documentRegister.Value;
                }

                if (leadingDocumentSelect != null)
                {
                    SkippedNumbersReport.LeadingDocument = leadingDocumentSelect.Value;
                }

                if (departmentSelect != null)
                {
                    SkippedNumbersReport.Department = departmentSelect.Value;
                }

                if (businessUnitSelect != null)
                {
                    SkippedNumbersReport.BusinessUnit = businessUnitSelect.Value;
                }

                SkippedNumbersReport.PeriodOffset = 0;
                if (period.Value != null)
                {
                    // Определить период.
                    if (period.Value.Equals(Reports.Resources.SkippedNumbersReport.CurrentYear) ||
                        period.Value.Equals(Reports.Resources.SkippedNumbersReport.PreviousYear))
                    {
                        SkippedNumbersReport.Period = Constants.SkippedNumbersReport.Year;
                    }

                    if (period.Value.Equals(Reports.Resources.SkippedNumbersReport.CurrentQuarter) ||
                        period.Value.Equals(Reports.Resources.SkippedNumbersReport.PreviousQuarter))
                    {
                        SkippedNumbersReport.Period = Constants.SkippedNumbersReport.Quarter;
                    }

                    if (period.Value.Equals(Reports.Resources.SkippedNumbersReport.CurrentMonth) ||
                        period.Value.Equals(Reports.Resources.SkippedNumbersReport.PreviousMonth))
                    {
                        SkippedNumbersReport.Period = Constants.SkippedNumbersReport.Month;
                    }

                    if (period.Value.Equals(Reports.Resources.SkippedNumbersReport.CurrentWeek) ||
                        period.Value.Equals(Reports.Resources.SkippedNumbersReport.PreviousWeek))
                    {
                        SkippedNumbersReport.Period = Constants.SkippedNumbersReport.Week;
                    }

                    // Определить смещение.
                    if (period.Value.Equals(Reports.Resources.SkippedNumbersReport.PreviousYear) ||
                        period.Value.Equals(Reports.Resources.SkippedNumbersReport.PreviousQuarter) ||
                        period.Value.Equals(Reports.Resources.SkippedNumbersReport.PreviousMonth) ||
                        period.Value.Equals(Reports.Resources.SkippedNumbersReport.PreviousWeek))
                    {
                        SkippedNumbersReport.PeriodOffset = -1;
                    }
                }
            });

            dialog.SetOnRefresh((arg) =>
            {
                var docRegister = SkippedNumbersReport.DocumentRegister;
                if (docRegister == null && documentRegister != null)
                {
                    docRegister = documentRegister.Value;
                }

                documentRegisterSpecified  = docRegister != null;
                var hasLeadDocSection      = false;
                var hasDepartmentSection   = false;
                var hasBusinessUnitSection = false;

                if (documentRegisterSpecified)
                {
                    hasLeadDocSection      = docRegister.NumberingSection == DocumentRegister.NumberingSection.LeadingDocument;
                    hasDepartmentSection   = docRegister.NumberingSection == DocumentRegister.NumberingSection.Department;
                    hasBusinessUnitSection = docRegister.NumberingSection == DocumentRegister.NumberingSection.BusinessUnit;
                }

                if (hasLeadDocSection && availableLeadingDocuments == null)
                {
                    availableLeadingDocuments = Docflow.Functions.Module.Remote.GetAvaliableLeadingDocuments();
                    leadingDocumentSelect.From(availableLeadingDocuments);
                }
                leadingDocumentSelect.IsVisible  = documentRegisterSpecified && hasLeadDocSection;
                leadingDocumentSelect.IsRequired = documentRegisterSpecified && hasLeadDocSection;

                departmentSelect.IsVisible  = documentRegisterSpecified && hasDepartmentSection;
                departmentSelect.IsRequired = documentRegisterSpecified && hasDepartmentSection;

                businessUnitSelect.IsVisible  = documentRegisterSpecified && hasBusinessUnitSection;
                businessUnitSelect.IsRequired = documentRegisterSpecified && hasBusinessUnitSection;
            });
            if (documentRegister != null)
            {
                documentRegister.SetOnValueChanged((ex) =>
                {
                    if (ex.NewValue != ex.OldValue)
                    {
                        leadingDocumentSelect.Value = null;
                        departmentSelect.Value      = null;
                        businessUnitSelect.Value    = null;
                    }
                });
            }

            if (dialog.Show() != DialogButtons.Ok)
            {
                e.Cancel = true;
            }
        }