コード例 #1
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var document = DistributionSheetReport.OutgoingDocument;

            DistributionSheetReport.ReportSessionId = System.Guid.NewGuid().ToString();

            // Шапка.
            DistributionSheetReport.LetterSubject = Docflow.PublicFunctions.Module.FormatDocumentNameForReport(document, false);

            var dataTable = new List <Structures.DistributionSheetReport.TableLine>();

            foreach (var addressee in document.Addressees.OrderBy(a => a.Number))
            {
                var tableLine = Structures.DistributionSheetReport.TableLine.Create();
                tableLine.ReportSessionId  = DistributionSheetReport.ReportSessionId;
                tableLine.CompanyName      = addressee.Correspondent.Name;
                tableLine.NameWithJobTitle = addressee.Addressee != null && !string.IsNullOrEmpty(addressee.Addressee.JobTitle)
          ? string.Concat(addressee.Addressee.JobTitle, System.Environment.NewLine)
          : string.Empty;
                tableLine.NameWithJobTitle += addressee.Addressee != null ? addressee.Addressee.Name : string.Empty;
                tableLine.DeliveryMethod    = addressee.DeliveryMethod != null
          ? addressee.DeliveryMethod.Name
          : string.Empty;
                tableLine.ContactsInformation = Docflow.PublicFunctions.OutgoingDocumentBase.GetContactsInformation(addressee, document);

                dataTable.Add(tableLine);
            }

            Docflow.PublicFunctions.Module.WriteStructuresToTable(Constants.DistributionSheetReport.SourceTableName, dataTable);
        }
コード例 #2
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            // ИД отчета.
            var reportId = Guid.NewGuid().ToString();

            ActionItemPrintReport.ReportSessionId = reportId;

            var task       = ActionItemPrintReport.Task;
            var assignment = ActionItemPrintReport.Assignment;
            var author     = task.Assignee;

            ActionItemPrintReport.Author = Company.PublicFunctions.Employee.GetShortName(author, DeclensionCase.Nominative, false);
            var currentUser = Users.Current;

            ActionItemPrintReport.PrintedBy = Sungero.Company.Employees.Is(currentUser)
        ? Company.PublicFunctions.Employee.GetShortName(Sungero.Company.Employees.Current,
                                                        DeclensionCase.Nominative,
                                                        false)
        : currentUser.Name;

            // Номер и дата документа.
            var document = task.DocumentsGroup.OfficialDocuments.FirstOrDefault();

            ActionItemPrintReport.DocumentShortName = PublicFunctions.Module.GetActionItemPrintReportDocumentShortName(document, assignment);

            // Получить данные для отчета.
            var reportData = PublicFunctions.Module.GetActionItemPrintReportData(task, reportId);

            // Записать данные в таблицу.
            Docflow.PublicFunctions.Module.WriteStructuresToTable(Constants.ActionItemPrintReport.SourceTableName, reportData);
        }
コード例 #3
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            IncomingDocumentsReport.DocumentsDataTableName         = Docflow.PublicFunctions.Module.GetReportTableName(IncomingDocumentsReport, Users.Current.Id);
            IncomingDocumentsReport.JobsDataTableName              = Docflow.PublicFunctions.Module.GetReportTableName(IncomingDocumentsReport, Users.Current.Id, "JobsList");
            IncomingDocumentsReport.AvailableDocumentsIdsTableName = Docflow.PublicFunctions.Module.GetReportTableName(IncomingDocumentsReport, Users.Current.Id, "Access");

            var reportSessionId = System.Guid.NewGuid().ToString();

            IncomingDocumentsReport.ReportSessionId = reportSessionId;

            // Удалить временные таблицы.
            Docflow.PublicFunctions.Module.DropReportTempTables(new[] { IncomingDocumentsReport.DocumentsDataTableName, IncomingDocumentsReport.JobsDataTableName, IncomingDocumentsReport.AvailableDocumentsIdsTableName });

            // Создать таблицу писем для учета прав.
            var availableDocumentsIds = Sungero.Docflow.IncomingDocumentBases.GetAll()
                                        .Where(d =>  Equals(d.DocumentRegister, IncomingDocumentsReport.DocumentRegister))
                                        .Where(d =>  d.RegistrationDate >= IncomingDocumentsReport.BeginDate.Value)
                                        .Where(d =>  d.RegistrationDate <= IncomingDocumentsReport.EndDate.Value)
                                        .Select(d => d.Id);

            Docflow.PublicFunctions.Module.CreateTempTableForRights(IncomingDocumentsReport.AvailableDocumentsIdsTableName, availableDocumentsIds);

            // Заполнить таблицы данных.
            var commandText = Queries.IncomingDocumentsReport.FillTempTables;

            Functions.Module.ExecuteSQLCommandFormat(commandText, new string[] { IncomingDocumentsReport.DocumentsDataTableName, IncomingDocumentsReport.JobsDataTableName, IncomingDocumentsReport.AvailableDocumentsIdsTableName });

            // Заполнить сурс таблицу.
            commandText = Queries.IncomingDocumentsReport.FillSourceTable;
            Functions.Module.ExecuteSQLCommandFormat(commandText, new string[] { IncomingDocumentsReport.DocumentsDataTableName, IncomingDocumentsReport.JobsDataTableName, Constants.IncomingDocumentsReport.IncomingDocumentsReportTableName, reportSessionId });

            // Удалить таблицу с правами.
            Docflow.PublicFunctions.Module.DropReportTempTables(new[] { IncomingDocumentsReport.AvailableDocumentsIdsTableName });
        }
コード例 #4
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            ApprovalSheetReport.ReportSessionId = Guid.NewGuid().ToString();
            Functions.ApprovalTask.UpdateApprovalSheetReportTable(ApprovalSheetReport.Document, ApprovalSheetReport.ReportSessionId);
            ApprovalSheetReport.HasRespEmployee = false;

            var document = ApprovalSheetReport.Document;

            if (document == null)
            {
                return;
            }

            // Наименование отчета.
            ApprovalSheetReport.DocumentName = Docflow.PublicFunctions.Module.FormatDocumentNameForReport(document, false);

            // НОР.
            var ourOrg = document.BusinessUnit;

            if (ourOrg != null)
            {
                ApprovalSheetReport.OurOrgName = ourOrg.Name;
            }

            // Дата отчета.
            ApprovalSheetReport.CurrentDate = Calendar.Now;

            // Ответственный.
            var responsibleEmployee = Functions.OfficialDocument.GetDocumentResponsibleEmployee(document);

            if (responsibleEmployee != null &&
                responsibleEmployee.IsSystem != true)
            {
                var respEmployee = string.Format("{0}: {1}",
                                                 Reports.Resources.ApprovalSheetReport.ResponsibleEmployee,
                                                 responsibleEmployee.Person.ShortName);

                if (responsibleEmployee.JobTitle != null)
                {
                    respEmployee = string.Format("{0} ({1})", respEmployee, responsibleEmployee.JobTitle.DisplayValue.Trim());
                }

                ApprovalSheetReport.RespEmployee = respEmployee;

                ApprovalSheetReport.HasRespEmployee = true;
            }

            // Распечатал.
            if (Employees.Current == null)
            {
                ApprovalSheetReport.Clerk = Users.Current.Name;
            }
            else
            {
                var clerkPerson = Employees.Current.Person;
                ApprovalSheetReport.Clerk = clerkPerson.ShortName;
            }
        }
コード例 #5
0
 public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
 {
     EnvelopeC4Report.ReportSessionId = Guid.NewGuid().ToString();
     Docflow.PublicFunctions.Module.DeleteReportData(Constants.EnvelopeC4Report.EnvelopesTableName, EnvelopeC4Report.ReportSessionId);
     Functions.Module.FillEnvelopeTable(EnvelopeC4Report.ReportSessionId,
                                        EnvelopeC4Report.OutgoingDocuments.ToList(),
                                        EnvelopeC4Report.ContractualDocuments.ToList(),
                                        EnvelopeC4Report.AccountingDocuments.ToList());
 }
コード例 #6
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var task   = AcquaintanceFormReport.Task;
            var taskId = task.Id;
            var isElectronicAcquaintance = task.IsElectronicAcquaintance == true;
            var sourceDocument           = task.DocumentGroup.OfficialDocuments.First();
            var versionNumber            = Functions.AcquaintanceTask.GetDocumentVersion(task);
            var nonBreakingSpace         = Convert.ToChar(160);

            // Шапка.
            AcquaintanceFormReport.DocumentName = Docflow.PublicFunctions.Module.FormatDocumentNameForReport(sourceDocument, versionNumber, false);

            // Приложения.
            var documentAddenda = Functions.Module.GetAcquintanceTaskAddendas(task);

            if (documentAddenda.Any())
            {
                AcquaintanceFormReport.AddendaDescription = Reports.Resources.AcquaintanceReport.Addendas;
                foreach (var addendum in documentAddenda)
                {
                    var addendumInfo = string.Format("\n - {0} ({1}:{2}{3}).", addendum.DisplayValue.Trim(),
                                                     Docflow.Resources.Id, nonBreakingSpace, addendum.Id);
                    AcquaintanceFormReport.AddendaDescription += addendumInfo;
                }
            }

            // Данные.
            var reportSessionId = System.Guid.NewGuid().ToString();

            AcquaintanceFormReport.ReportSessionId = reportSessionId;
            var dataTable = new List <Structures.AcquaintanceFormReport.TableLine>();
            var employees = GetEmployeesFromParticipants(task);

            foreach (var employee in employees)
            {
                var newLine = Structures.AcquaintanceFormReport.TableLine.Create();
                newLine.ShortName = employee.Person.ShortName;
                newLine.LastName  = employee.Person.LastName;
                if (employee.JobTitle != null)
                {
                    newLine.JobTitle = employee.JobTitle.DisplayValue;
                }
                newLine.Department      = employee.Department.DisplayValue;
                newLine.RowNumber       = 0;
                newLine.ReportSessionId = reportSessionId;
                dataTable.Add(newLine);
            }
            Docflow.PublicFunctions.Module.WriteStructuresToTable(Constants.AcquaintanceFormReport.SourceTableName, dataTable);

            // Подвал.
            var currentUser   = Users.Current;
            var printedByName = Employees.Is(currentUser)
        ? Employees.As(currentUser).Person.ShortName
        : currentUser.Name;

            AcquaintanceFormReport.Printed = Reports.Resources.AcquaintanceReport.PrintedByFormat(printedByName, Calendar.UserNow);
        }
コード例 #7
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var reportSessionId = System.Guid.NewGuid().ToString();

            ResponsibilitiesReport.ReportSessionId = reportSessionId;
            ResponsibilitiesReport.CurrentDate     = Calendar.Now;
            var reportData = PublicFunctions.Module.GetAllResponsibilitiesReportData(this.ResponsibilitiesReport.Employee);

            foreach (var element in reportData)
            {
                element.ReportSessionId = reportSessionId;
            }

            Docflow.PublicFunctions.Module.WriteStructuresToTable(Constants.ResponsibilitiesReport.ResponsibilitiesReportTableName, reportData);
        }
コード例 #8
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            // ИД отчета.
            var reportSessionId = Guid.NewGuid().ToString();

            DraftResolutionReport.ReportSessionId = reportSessionId;

            // Автор.
            var author = DraftResolutionReport.Author;

            if (author != null)
            {
                if (author.JobTitle != null)
                {
                    DraftResolutionReport.AuthorJobTitle = author.JobTitle.Name;
                }

                DraftResolutionReport.AuthorShortName = Company.PublicFunctions.Employee.GetReverseShortName(author);
            }

            // Номер и дата документа.
            var document = DraftResolutionReport.Document;

            DraftResolutionReport.DocumentShortName = PublicFunctions.Module.GetDraftResolutionReportDocumentShortName(document);

            // НОР.
            DraftResolutionReport.BusinessUnit = string.Empty;
            if (document != null && document.BusinessUnit != null)
            {
                DraftResolutionReport.BusinessUnit = document.BusinessUnit.Name;
            }
            else if (author.Department != null && author.Department.BusinessUnit != null)
            {
                DraftResolutionReport.BusinessUnit = author.Department.BusinessUnit.Name;
            }

            // Получить данные для отчета.
            var actionItems = DraftResolutionReport.Resolution.ToList();
            var reportData  = PublicFunctions.Module.GetDraftResolutionReportData(actionItems, reportSessionId, DraftResolutionReport.TextResolution);

            // Записать данные в таблицу.
            Docflow.PublicFunctions.Module.WriteStructuresToTable(Constants.DraftResolutionReport.SourceTableName, reportData);
        }
コード例 #9
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var reportSessionId = System.Guid.NewGuid().ToString();

            ExchangeOrderReport.SessionId = reportSessionId;

            var document = ExchangeOrderReport.Entity;

            ExchangeOrderReport.DocumentName = document.Name;

            var exchangeInfo = Functions.Module.GetExchangeOrderInfo(reportSessionId, document);

            var dataTable = exchangeInfo.ExchangeOrderInfo;

            ExchangeOrderReport.CompletationString = Reports.Resources.ExchangeOrderReport.Docflow + " ";
            var completationString = exchangeInfo.IsComplete ? Reports.Resources.ExchangeOrderReport.Completed : Reports.Resources.ExchangeOrderReport.NotCompleted;

            ExchangeOrderReport.CompletationString += completationString;

            Functions.Module.WriteStructuresToTable(Constants.ExchangeOrderReport.SourceTableName, dataTable);
        }
コード例 #10
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var reportSessionId = System.Guid.NewGuid().ToString();

            AssignmentCompletionReport.ReportSessionId         = reportSessionId;
            AssignmentCompletionReport.ReportDate              = Calendar.Now;
            AssignmentCompletionReport.DepartmentId            = AssignmentCompletionReport.Department != null ? AssignmentCompletionReport.Department.Id : 0;
            AssignmentCompletionReport.PerformerId             = AssignmentCompletionReport.Performer != null ? AssignmentCompletionReport.Performer.Id : 0;
            AssignmentCompletionReport.BusinessUnitId          = AssignmentCompletionReport.BusinessUnit != null ? AssignmentCompletionReport.BusinessUnit.Id : 0;
            AssignmentCompletionReport.AssignmentViewTableName = Constants.AssignmentCompletionReport.SourceTableName;

            #region Описание параметров

            if (AssignmentCompletionReport.BusinessUnit != null)
            {
                AssignmentCompletionReport.ParamsDescription += string.Format(Docflow.Resources.ReportBusinessUnit, AssignmentCompletionReport.BusinessUnit.Name, System.Environment.NewLine);
            }

            if (AssignmentCompletionReport.Department != null)
            {
                AssignmentCompletionReport.ParamsDescription += string.Format(Docflow.Resources.ReportDepartment, AssignmentCompletionReport.Department.Name, System.Environment.NewLine);
            }

            AssignmentCompletionReport.ParamsDescription += string.Format(Docflow.Resources.ReportOldAssignments,
                                                                          AssignmentCompletionReport.LoadOldAssignments == true ? Docflow.Resources.ReportYes : Docflow.Resources.ReportNo);

            AssignmentCompletionReport.DoneAndNotOverdue   = Resources.DoneAndNotOverdue;
            AssignmentCompletionReport.DoneAndOverdue      = Resources.DoneAndOverdue;
            AssignmentCompletionReport.UndoneAndNotOverdue = Resources.UndoneAndNotOverdue;
            AssignmentCompletionReport.UndoneAndOverdue    = Resources.UndoneAndOverdue;

            #endregion

            var tableData = Functions.Module.GetAssignmentCompletionReportData(reportSessionId, AssignmentCompletionReport.Department,
                                                                               AssignmentCompletionReport.Performer, AssignmentCompletionReport.PeriodBegin, AssignmentCompletionReport.PeriodEnd, AssignmentCompletionReport.LoadOldAssignments);

            Functions.Module.WriteStructuresToTable(AssignmentCompletionReport.AssignmentViewTableName, tableData);
        }
コード例 #11
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var documents = MailRegisterReport.OutgoingDocuments;

            MailRegisterReport.TotalMailCount  = documents.Sum(d => d.Addressees.Count).ToString();
            MailRegisterReport.FromName        = documents.First().BusinessUnit.Name;
            MailRegisterReport.ReportSessionId = System.Guid.NewGuid().ToString();

            var dataTable = new List <Structures.MailRegisterReport.TableLine>();

            foreach (var document in documents)
            {
                foreach (var addressee in document.Addressees.OrderBy(a => a.Number))
                {
                    var tableLine = Structures.MailRegisterReport.TableLine.Create();
                    tableLine.ReportSessionId = MailRegisterReport.ReportSessionId;
                    tableLine.PostAddress     = addressee.Correspondent.PostalAddress ?? addressee.Correspondent.LegalAddress ?? string.Empty;
                    tableLine.ToName          = addressee.Correspondent.Name;
                    dataTable.Add(tableLine);
                }
            }

            Functions.Module.WriteStructuresToTable(Constants.MailRegisterReport.SourceTableName, dataTable);
        }
コード例 #12
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            RegistrationSettingReport.ReportDate = Calendar.UserToday;

            // Заполнить значения по умолчанию, если отчет вызван в невизуальном режиме.
            if (RegistrationSettingReport.FilterDepartmentsForBusinessUnits == null)
            {
                RegistrationSettingReport.FilterDepartmentsForBusinessUnits = true;
            }

            var filterDepartment = RegistrationSettingReport.FilterDepartmentsForBusinessUnits == true;

            #region Описание параметров

            if (RegistrationSettingReport.BusinessUnit != null)
            {
                RegistrationSettingReport.ParamsDescriprion += string.Format("{0}: {1} \n", Reports.Resources.RegistrationSettingReport.BusinessUnit, RegistrationSettingReport.BusinessUnit.Name);
            }

            if (!string.IsNullOrWhiteSpace(RegistrationSettingReport.Direction))
            {
                RegistrationSettingReport.ParamsDescriprion += string.Format("{0}: {1} \n", Reports.Resources.RegistrationSettingReport.DocumentFlow, RegistrationSettingReport.DirectionLabel);
            }

            RegistrationSettingReport.ParamsDescriprion += string.Format("{0}: {1} \n", Reports.Resources.RegistrationSettingReport.FilterDepartmentsForBusinessUnits,
                                                                         RegistrationSettingReport.FilterDepartmentsForBusinessUnits == true ? Reports.Resources.RegistrationSettingReport.Yes : Reports.Resources.RegistrationSettingReport.No);

            #endregion

            var sourceDataTableName = Constants.RegistrationSettingReport.SourceTableName;
            RegistrationSettingReport.SourceDataTableName = sourceDataTableName;
            var reportSessionId = System.Guid.NewGuid().ToString();
            RegistrationSettingReport.ReportSessionId = reportSessionId;

            var units = RegistrationSettingReport.BusinessUnit != null ?
                        new List <Company.IBusinessUnit>()
            {
                RegistrationSettingReport.BusinessUnit
            } :
            Company.BusinessUnits.GetAll().Where(u => u.Status == CoreEntities.DatabookEntry.Status.Active).ToList();

            var flows = new List <Enumeration>()
            {
                DocumentFlow.Incoming, DocumentFlow.Outgoing, DocumentFlow.Inner, DocumentFlow.Contracts
            };
            if (!string.IsNullOrWhiteSpace(RegistrationSettingReport.Direction))
            {
                flows = flows.Where(i => i.Value == RegistrationSettingReport.Direction).ToList();
            }

            var kinds = DocumentKinds.GetAll().Where(k => k.Status == CoreEntities.DatabookEntry.Status.Active &&
                                                     !Equals(k.NumberingType, DocumentKind.NumberingType.NotNumerable)).ToList();
            var settings    = RegistrationSettings.GetAll().Where(s => s.Status == CoreEntities.DatabookEntry.Status.Active && s.DocumentRegister.Status == CoreEntities.DatabookEntry.Status.Active).ToList();
            var departments = Company.Departments.GetAll().Where(d => d.Status == CoreEntities.DatabookEntry.Status.Active).OrderBy(d => d.Name).ToList();

            var separator             = ";" + System.Environment.NewLine;
            var allDepartmentString   = Reports.Resources.RegistrationSettingReport.AllDepartmentString;
            var otherDepartmentString = Reports.Resources.RegistrationSettingReport.OtherDepartmentString;
            // Строчки также используются в условной разметке для подсветки красным\курсивом.
            var settingNotFound  = Reports.Resources.RegistrationSettingReport.SettingNotFound;
            var defaultSetting   = Reports.Resources.RegistrationSettingReport.DefaultSetting;
            var registerNotFound = Reports.Resources.RegistrationSettingReport.RegisterNotFound;

            var tableData = new List <Structures.RegistrationSettingReport.TableLine>();

            foreach (var unit in units)
            {
                foreach (var flow in flows)
                {
                    foreach (var kind in kinds.Where(k => Equals(k.DocumentFlow, flow)))
                    {
                        var error       = Equals(kind.NumberingType, DocumentKind.NumberingType.Numerable) ? settingNotFound : defaultSetting;
                        var subSettings = settings.Where(s => Equals(s.DocumentFlow, flow) &&
                                                         (!s.BusinessUnits.Any() || s.BusinessUnits.Any(u => Equals(u.BusinessUnit, unit))) &&
                                                         s.DocumentKinds.Any(k => Equals(k.DocumentKind, kind)))
                                          .ToList();

                        foreach (var setting in subSettings)
                        {
                            var subDepartments = setting.Departments.Where(d => !filterDepartment || Equals(d.Department.BusinessUnit, unit)).ToList();
                            if (setting.Departments.Any() && !subDepartments.Any())
                            {
                                continue;
                            }

                            var department = !setting.Departments.Any() ? allDepartmentString : string.Join(separator, subDepartments.Select(d => d.Department.Name));
                            var example    = Functions.DocumentRegister.GetValueExample(setting.DocumentRegister);

                            var line = Structures.RegistrationSettingReport.TableLine.Create();
                            line.BusinessUnit           = unit.Name;
                            line.DocumentFlow           = GetDocumentFlowName(flow);
                            line.DocumentFlowIndex      = flows.IndexOf(flow);
                            line.DocumentKind           = kind.Name;
                            line.RegistrationSetting    = setting.Name;
                            line.RegistrationSettingUri = Hyperlinks.Get(setting);
                            line.Priority            = setting.Priority ?? 0;
                            line.Departments         = department;
                            line.SettingType         = GetSettingType(kind, setting);
                            line.DocumentRegister    = setting.DocumentRegister.Name;
                            line.DocumentRegisterUri = Hyperlinks.Get(setting.DocumentRegister);
                            line.NumberExample       = example;
                            line.ReportSessionId     = reportSessionId;

                            tableData.Add(line);
                        }

                        // Если настроек для вида не найдено.
                        if (!subSettings.Any() && kind.NumberingType == DocumentKind.NumberingType.Numerable)
                        {
                            var line = Structures.RegistrationSettingReport.TableLine.Create();
                            line.BusinessUnit        = unit.Name;
                            line.DocumentFlow        = GetDocumentFlowName(flow);
                            line.DocumentFlowIndex   = flows.IndexOf(flow);
                            line.DocumentKind        = kind.Name;
                            line.RegistrationSetting = error;
                            line.Priority            = -1;
                            line.Departments         = allDepartmentString;
                            line.SettingType         = GetSettingType(kind, null);
                            line.ReportSessionId     = reportSessionId;

                            tableData.Add(line);
                            continue;
                        }

                        // Если есть хоть одна настройка для всех подразделений - идём дальше.
                        if (subSettings.Any(s => !s.Departments.Any()))
                        {
                            continue;
                        }
                        // Если нет подразделений без настроек - идем дальше
                        var allDeparmentInUnit = departments.Where(d => Equals(d.BusinessUnit, unit)).ToList();
                        var settingDepartments = subSettings.SelectMany(s => s.Departments).Select(s => s.Department).ToList();
                        if (!allDeparmentInUnit.Except(settingDepartments).Any())
                        {
                            continue;
                        }

                        var allDepartments = filterDepartment ?
                                             departments.Where(d => Equals(d.BusinessUnit, unit)).ToList() :
                                             departments;
                        var registers       = new List <IDocumentRegister>();
                        var firstDepartment = allDepartments.Except(settingDepartments).FirstOrDefault();
                        if (firstDepartment != null)
                        {
                            registers.AddRange(Functions.DocumentRegister.GetDocumentRegistersByParams(kind, unit, firstDepartment, SettingType.Registration, false));
                        }
                        registers = registers.Distinct().ToList();
                        var regDepartment = allDepartments.Any(d => settingDepartments.Contains(d)) ? otherDepartmentString : allDepartmentString;

                        if (!registers.Any())
                        {
                            var line = Structures.RegistrationSettingReport.TableLine.Create();
                            line.BusinessUnit        = unit.Name;
                            line.DocumentFlow        = GetDocumentFlowName(flow);
                            line.DocumentFlowIndex   = flows.IndexOf(flow);
                            line.DocumentKind        = kind.Name;
                            line.RegistrationSetting = registerNotFound;
                            line.Priority            = -1;
                            line.Departments         = regDepartment;
                            line.SettingType         = GetSettingType(kind, null);
                            line.ReportSessionId     = reportSessionId;

                            tableData.Add(line);
                        }

                        foreach (var register in registers)
                        {
                            var example = Functions.DocumentRegister.GetValueExample(register);

                            var line = Structures.RegistrationSettingReport.TableLine.Create();
                            line.BusinessUnit        = unit.Name;
                            line.DocumentFlow        = GetDocumentFlowName(flow);
                            line.DocumentFlowIndex   = flows.IndexOf(flow);
                            line.DocumentKind        = kind.Name;
                            line.RegistrationSetting = error;
                            line.Priority            = 0;
                            line.Departments         = regDepartment;
                            line.DocumentRegister    = register.Name;
                            line.DocumentRegisterUri = Hyperlinks.Get(register);
                            line.SettingType         = GetSettingType(kind, null);
                            line.NumberExample       = example;
                            line.ReportSessionId     = reportSessionId;

                            tableData.Add(line);
                        }
                    }
                }
            }

            // Полная сортировка данных.
            tableData = tableData
                        .OrderBy(t => t.BusinessUnit)
                        .ThenBy(t => t.DocumentFlowIndex)
                        .ThenBy(t => t.DocumentKind)
                        .ThenByDescending(t => t.Priority)
                        .ThenBy(t => t.Departments)
                        .ToList();

            for (var i = 0; i < tableData.Count; i++)
            {
                tableData[i].Id = i;
            }

            Functions.Module.WriteStructuresToTable(RegistrationSettingReport.SourceDataTableName, tableData);
        }
コード例 #13
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            // Задать минимальную и максимальную даты. Формат yyyy-MM-dd нужен для правильного парсинга на ru и en локализациях.
            DocumentReturnReport.MinDeliveryDate = DateTime.Parse("1753-01-01");
            DocumentReturnReport.MaxDeliveryDate = DateTime.Parse("9999-12-31");

            // Отфильтровать доступные документы.
            var documents = Docflow.OfficialDocuments.GetAll()
                            .Where(d => d.IsReturnRequired.HasValue)
                            .Where(d =>  d.Tracking.Any(l =>  (!l.ReturnDate.HasValue || l.ReturnResult == Docflow.OfficialDocumentTracking.ReturnResult.AtControl) && l.ExternalLinkId == null));

            // Фильтр по дате выдачи.
            if (DocumentReturnReport.DeliveryDateFrom.HasValue)
            {
                documents = documents.Where(d => d.Tracking.Any(l => l.DeliveryDate >= DocumentReturnReport.DeliveryDateFrom && !l.ReturnDate.HasValue));
            }
            if (DocumentReturnReport.DeliveryDateTo.HasValue)
            {
                documents = documents.Where(d => d.Tracking.Any(l => l.DeliveryDate <= DocumentReturnReport.DeliveryDateTo && !l.ReturnDate.HasValue));
            }

            // Фильтр по НОР.
            if (DocumentReturnReport.BusinessUnit != null)
            {
                documents = documents.Where(d => Equals(d.BusinessUnit, DocumentReturnReport.BusinessUnit));
            }

            // Фильтр по подразделению сотрудника.
            if (DocumentReturnReport.Department != null)
            {
                documents = documents.Where(d => d.Tracking.Any(l => Equals(l.DeliveredTo.Department, DocumentReturnReport.Department) && !l.ReturnDate.HasValue));
            }

            // Фильтр по сотруднику.
            if (DocumentReturnReport.Employee != null)
            {
                documents = documents.Where(d => d.Tracking.Any(l => Equals(l.DeliveredTo, DocumentReturnReport.Employee) && !l.ReturnDate.HasValue));
            }

            var reportSessionId = System.Guid.NewGuid().ToString();

            DocumentReturnReport.ReportSessionId = reportSessionId;

            // Заполнить данные.
            var dataTable = new List <Structures.DocumentReturnReport.DocumentReturnTableLine>();

            foreach (var document in documents)
            {
                // Заполнить информацию о выдачах документа.
                var tracking     = document.Tracking.Where(l => (!l.ReturnDate.HasValue || l.ReturnResult == Docflow.OfficialDocumentTracking.ReturnResult.AtControl) && l.ExternalLinkId == null);
                var docHyperlink = Hyperlinks.Get(document);

                foreach (var location in tracking)
                {
                    var tableLine = Structures.DocumentReturnReport.DocumentReturnTableLine.Create();
                    tableLine.ReportSessionId = reportSessionId;
                    tableLine.DocId           = document.Id;
                    tableLine.DocName         = document.Name;
                    tableLine.OriginalOrCopy  = location.IsOriginal.Value ? Reports.Resources.DocumentReturnReport.Original : Reports.Resources.DocumentReturnReport.Copy;
                    tableLine.Hyperlink       = docHyperlink;

                    // Заполнить информацию по дате выдаче и просрочке.
                    var today = Calendar.UserToday;
                    tableLine.DeliveryDate = location.DeliveryDate.Value.ToString("d");
                    var returnDeadline = location.ReturnDeadline;
                    tableLine.ScheduledReturnDate = returnDeadline.HasValue ? returnDeadline.Value.ToString("d") : "-";
                    var scheduledReturnDate = returnDeadline ?? today.AddDays(1);
                    tableLine.OverdueDelay = Docflow.PublicFunctions.Module.CalculateDelay(scheduledReturnDate, today, location.DeliveredTo);

                    // Заполнить информацию о сотруднике.
                    var employee = location.DeliveredTo;
                    tableLine.FullName = employee.Person.ShortName ?? employee.Name;
                    tableLine.DepId    = employee.Department.Id;
                    tableLine.DepName  = employee.Department.Name;
                    dataTable.Add(tableLine);
                }
            }

            Docflow.PublicFunctions.Module.WriteStructuresToTable(Constants.DocumentReturnReport.SourceTableName, dataTable);
        }
コード例 #14
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            #region Параметры и дата выполнения отчета

            ActionItemsExecutionReport.ReportSessionId = Guid.NewGuid().ToString();
            ActionItemsExecutionReport.ReportDate      = Calendar.Now;

            if (string.IsNullOrEmpty(ActionItemsExecutionReport.Header))
            {
                if (ActionItemsExecutionReport.Meeting == null && ActionItemsExecutionReport.IsMeetingsCoverContext == true)
                {
                    ActionItemsExecutionReport.Header = Sungero.RecordManagement.Resources.ActionItemsExecutionReportForMeetings;
                }
                else
                {
                    ActionItemsExecutionReport.Header = Sungero.RecordManagement.Resources.ActionItemsExecutionReport;
                }
            }

            if (ActionItemsExecutionReport.Meeting != null)
            {
                ActionItemsExecutionReport.Subheader = Reports.Resources.ActionItemsExecutionReport.HeaderMeetingFormat(ActionItemsExecutionReport.Meeting.Name);

                if (ActionItemsExecutionReport.IsMeetingsCoverContext == true)
                {
                    var deadlineHeaderString = Reports.Resources.ActionItemsExecutionReport.HeaderDeadlineFormat(ActionItemsExecutionReport.BeginDate.Value.ToShortDateString(),
                                                                                                                 ActionItemsExecutionReport.ClientEndDate.Value.ToShortDateString());
                    ActionItemsExecutionReport.Subheader += string.Format("\n{0}", deadlineHeaderString);
                }
            }
            else if (ActionItemsExecutionReport.Document == null)
            {
                ActionItemsExecutionReport.Subheader = Reports.Resources.ActionItemsExecutionReport.HeaderDeadlineFormat(ActionItemsExecutionReport.BeginDate.Value.ToShortDateString(),
                                                                                                                         ActionItemsExecutionReport.ClientEndDate.Value.ToShortDateString());
            }
            else
            {
                ActionItemsExecutionReport.Subheader = Reports.Resources.ActionItemsExecutionReport.HeaderDocumentFormat(ActionItemsExecutionReport.Document.Name);
            }

            if (ActionItemsExecutionReport.Author != null)
            {
                ActionItemsExecutionReport.ParamsDescriprion += Reports.Resources.ActionItemsExecutionReport.FilterAuthorFormat(ActionItemsExecutionReport.Author.Person.ShortName,
                                                                                                                                System.Environment.NewLine);
            }

            if (ActionItemsExecutionReport.BusinessUnit != null)
            {
                ActionItemsExecutionReport.ParamsDescriprion += Reports.Resources.ActionItemsExecutionReport.FilterBusinessUnitFormat(ActionItemsExecutionReport.BusinessUnit.Name,
                                                                                                                                      System.Environment.NewLine);
            }

            if (ActionItemsExecutionReport.Department != null)
            {
                ActionItemsExecutionReport.ParamsDescriprion += Reports.Resources.ActionItemsExecutionReport.FilterDepartmentFormat(ActionItemsExecutionReport.Department.Name,
                                                                                                                                    System.Environment.NewLine);
            }

            if (ActionItemsExecutionReport.Performer != null)
            {
                var performerName = Employees.Is(ActionItemsExecutionReport.Performer) ?
                                    Employees.As(ActionItemsExecutionReport.Performer).Person.ShortName :
                                    ActionItemsExecutionReport.Performer.Name;
                ActionItemsExecutionReport.ParamsDescriprion += Reports.Resources.ActionItemsExecutionReport.FilterResponsibleFormat(performerName,
                                                                                                                                     System.Environment.NewLine);
            }

            #endregion

            #region  асчет итогов
            var actionItems = Functions.Module.GetActionItemCompletionData(ActionItemsExecutionReport.Meeting,
                                                                           ActionItemsExecutionReport.Document,
                                                                           ActionItemsExecutionReport.BeginDate,
                                                                           ActionItemsExecutionReport.EndDate,
                                                                           ActionItemsExecutionReport.Author,
                                                                           ActionItemsExecutionReport.BusinessUnit,
                                                                           ActionItemsExecutionReport.Department,
                                                                           ActionItemsExecutionReport.Performer,
                                                                           ActionItemsExecutionReport.DocumentType,
                                                                           ActionItemsExecutionReport.IsMeetingsCoverContext,
                                                                           true);
            ActionItemsExecutionReport.TotalCount      = actionItems.Count();
            ActionItemsExecutionReport.Completed       = actionItems.Where(j => j.Status == Workflow.Task.Status.Completed).Count();
            ActionItemsExecutionReport.CompletedInTime = actionItems
                                                         .Where(j => j.Status == Workflow.Task.Status.Completed)
                                                         .Where(j => Docflow.PublicFunctions.Module.CalculateDelay(j.Deadline, j.ActualDate.Value, j.Assignee) == 0).Count();
            ActionItemsExecutionReport.CompletedOverdue = actionItems
                                                          .Where(j => j.Status == Workflow.Task.Status.Completed)
                                                          .Where(j => Docflow.PublicFunctions.Module.CalculateDelay(j.Deadline, j.ActualDate.Value, j.Assignee) > 0).Count();
            ActionItemsExecutionReport.InProcess = actionItems.Where(j => j.Status == Workflow.Task.Status.InProcess).Count();

            ActionItemsExecutionReport.InProcessOverdue = actionItems
                                                          .Where(j => j.Status == Workflow.Task.Status.InProcess)
                                                          .Where(j => Docflow.PublicFunctions.Module.CalculateDelay(j.Deadline, Calendar.Now, j.Assignee) > 0).Count();

            if (ActionItemsExecutionReport.TotalCount != 0)
            {
                var inTimeActionItems = ActionItemsExecutionReport.CompletedInTime + ActionItemsExecutionReport.InProcess - ActionItemsExecutionReport.InProcessOverdue;
                ActionItemsExecutionReport.ExecutiveDisciplineLevel =
                    string.Format("{0:P2}", inTimeActionItems / (double)ActionItemsExecutionReport.TotalCount);
            }
            else
            {
                ActionItemsExecutionReport.ExecutiveDisciplineLevel = Reports.Resources.ActionItemsExecutionReport.NoAnyActionItems;
            }

            #endregion

            var dataTable = new List <Structures.ActionItemsExecutionReport.TableLine>();
            foreach (var actionItem in actionItems.OrderBy(a => a.Deadline))
            {
                var tableLine = Structures.ActionItemsExecutionReport.TableLine.Create();

                // ИД и ссылка.
                tableLine.Id        = actionItem.Id;
                tableLine.Hyperlink = Core.Hyperlinks.Get(ActionItemExecutionTasks.Info, actionItem.Id);

                // Поручение.
                tableLine.ActionItemText = actionItem.ActionItem;

                // Автор.
                var author = Employees.As(actionItem.Author);
                if (author != null && author.Person != null)
                {
                    tableLine.Author = author.Person.ShortName;
                }
                else
                {
                    tableLine.Author = actionItem.Author.Name;
                }

                // TODO Lomagin: Убрать замену на пробел после исправления 33360. Сделано в рамках бага 33343.
                // Сделано для корректного переноса инициалов, если фамилия длинная.
                tableLine.Author = tableLine.Author.Replace("\u00A0", " ");

                // Статус.
                tableLine.State = string.Empty;
                if (actionItem.ExecutionState != null)
                {
                    tableLine.State = ActionItemExecutionTasks.Info.Properties.ExecutionState.GetLocalizedValue(actionItem.ExecutionState.Value);
                }

                // Даты и просрочка.
                tableLine.PlanDate = string.Empty;
                if (actionItem.Deadline.HasValue)
                {
                    var deadline = Calendar.ToUserTime(actionItem.Deadline.Value);
                    tableLine.PlanDate     = Docflow.PublicFunctions.Module.ToShortDateShortTime(deadline);
                    tableLine.PlanDateSort = actionItem.Deadline.Value;
                }
                tableLine.ActualDate = string.Empty;
                var isCompleted = actionItem.Status == Sungero.Workflow.Task.Status.Completed;
                if (isCompleted)
                {
                    var endDate = actionItem.ActualDate.HasValue ? actionItem.ActualDate.Value : Calendar.Now;
                    tableLine.ActualDate = Docflow.PublicFunctions.Module.ToShortDateShortTime(Calendar.ToUserTime(endDate));
                    tableLine.Overdue    = Docflow.PublicFunctions.Module.CalculateDelay(actionItem.Deadline, endDate, actionItem.Assignee);
                }
                else
                {
                    tableLine.Overdue = Docflow.PublicFunctions.Module.CalculateDelay(actionItem.Deadline, Calendar.Now, actionItem.Assignee);
                }

                // Исполнители.
                tableLine.Assignee = actionItem.Assignee.Person.ShortName;

                tableLine.CoAssignees = string.Join(", ", actionItem.CoAssigneesShortNames);

                tableLine.ReportSessionId = ActionItemsExecutionReport.ReportSessionId;

                dataTable.Add(tableLine);
            }

            Docflow.PublicFunctions.Module.WriteStructuresToTable(Constants.ActionItemsExecutionReport.SourceTableName, dataTable);

            using (var command = SQL.GetCurrentConnection().CreateCommand())
            {
                // Заполнить таблицу именами документов.
                command.CommandText = string.Format(Queries.ActionItemsExecutionReport.PasteDocumentNames, Constants.ActionItemsExecutionReport.SourceTableName, ActionItemsExecutionReport.ReportSessionId);
                command.ExecuteNonQuery();
            }
        }
コード例 #15
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var documentsTableName = Constants.ExchangeServiceDocumentReport.SourceTableName;

            ExchangeServiceDocumentReport.DocumentsTableName = documentsTableName;
            var reportSessionId = System.Guid.NewGuid().ToString();

            ExchangeServiceDocumentReport.ReportSessionId = reportSessionId;

            #region Параметры отчета

            var resources     = Sungero.Docflow.Reports.Resources.ExchangeServiceDocumentReport;
            var parameterInfo = string.Empty;
            if (ExchangeServiceDocumentReport.BusinessUnit != null)
            {
                parameterInfo += string.Format("{0}: {1}\n", Resources.BusinessUnit, ExchangeServiceDocumentReport.BusinessUnit.Name);
            }

            if (ExchangeServiceDocumentReport.Department != null)
            {
                parameterInfo += string.Format("{0}: {1}\n", Resources.Department, ExchangeServiceDocumentReport.Department.Name);
            }

            if (ExchangeServiceDocumentReport.Employee != null)
            {
                parameterInfo += string.Format("{0}: {1}\n", Resources.Employee,
                                               ExchangeServiceDocumentReport.Employee.Person.ShortName ?? ExchangeServiceDocumentReport.Employee.Name);
            }

            if (ExchangeServiceDocumentReport.Counterparty != null)
            {
                parameterInfo += string.Format("{0}: {1}\n", resources.Counterparty, ExchangeServiceDocumentReport.Counterparty.Name);
            }

            parameterInfo += string.Format("{0}: {1}", resources.ExchangeService,
                                           string.Join(", ", ExchangeServiceDocumentReport.ExchangeService.Select(x => x.Name)));

            ExchangeServiceDocumentReport.ParametersInfo = parameterInfo;

            #endregion

            var sendFrom = ExchangeServiceDocumentReport.SendDateFrom;
            if (sendFrom.HasValue)
            {
                ExchangeServiceDocumentReport.SendPeriod += string.Format("{0} {1}",
                                                                          Sungero.Docflow.Reports.Resources.AssignmentCompletionReport.PeriodFrom,
                                                                          sendFrom.Value.ToString("d"));
            }
            var sendTo = ExchangeServiceDocumentReport.SendDateTo;
            if (sendTo.HasValue)
            {
                ExchangeServiceDocumentReport.SendPeriod += string.Format(" {0} {1}",
                                                                          Sungero.Docflow.Reports.Resources.AssignmentCompletionReport.PeriodTo,
                                                                          sendTo.Value.ToString("d"));
            }

            // Отфильтровать доступные документы.
            var documents = Docflow.OfficialDocuments.GetAll()
                            .Where(d => d.ExchangeState == Docflow.OfficialDocument.ExchangeState.SignAwaited)
                            .Where(d => d.Tracking.Any(t => t.ExternalLinkId.HasValue && !t.ReturnDate.HasValue))
                            .Where(d => d.Versions.Any());

            // Фильтр по дате отправки.
            if (sendFrom.HasValue)
            {
                documents = documents.Where(d => d.Tracking.Any(t => t.ExternalLinkId.HasValue && t.DeliveryDate >= sendFrom && !t.ReturnDate.HasValue));
            }
            if (sendTo.HasValue)
            {
                documents = documents.Where(d => d.Tracking.Any(t => t.ExternalLinkId.HasValue && t.DeliveryDate <= sendTo && !t.ReturnDate.HasValue));
            }

            // Фильтр по НОР.
            if (ExchangeServiceDocumentReport.BusinessUnit != null)
            {
                documents = documents.Where(d => d.BusinessUnit == null || Equals(d.BusinessUnit, ExchangeServiceDocumentReport.BusinessUnit));
            }

            // Фильтр по подразделению сотрудника.
            if (ExchangeServiceDocumentReport.Department != null)
            {
                documents = documents.Where(d => d.Tracking.Any(t => t.ExternalLinkId.HasValue && !t.ReturnDate.HasValue &&
                                                                Equals(t.DeliveredTo.Department, ExchangeServiceDocumentReport.Department)));
            }

            // Фильтр по сотруднику.
            if (ExchangeServiceDocumentReport.Employee != null)
            {
                documents = documents.Where(d => d.Tracking.Any(t => t.ExternalLinkId.HasValue && !t.ReturnDate.HasValue &&
                                                                Equals(t.DeliveredTo, ExchangeServiceDocumentReport.Employee)));
            }

            // Инфошки.
            var exchangeDocumentsInfos = Exchange.ExchangeDocumentInfos.GetAll()
                                         .Where(x => documents.Contains(x.Document))
                                         .Where(x => x.MessageType == Exchange.ExchangeDocumentInfo.MessageType.Outgoing);

            // Заполнить данные для временной таблицы.
            var dataTable = new List <Structures.ExchangeServiceDocumentReport.ExchangeServiceDocumentTableLine>();
            foreach (var document in documents)
            {
                var tableLine = Structures.ExchangeServiceDocumentReport.ExchangeServiceDocumentTableLine.Create();

                tableLine.ReportSessionId = reportSessionId;

                // Инфо об отправки документа.
                var documentExchangeInfo = exchangeDocumentsInfos.Where(x => Equals(x.Document, document)).OrderByDescending(x => x.MessageDate).FirstOrDefault();
                if (documentExchangeInfo == null)
                {
                    continue;
                }

                // НОР.
                var businessUnit = document.BusinessUnit;
                if (businessUnit == null)
                {
                    businessUnit = ExchangeCore.PublicFunctions.BoxBase.GetBusinessUnit(documentExchangeInfo.Box);
                }

                // Дофильтрация по НОР.
                if (ExchangeServiceDocumentReport.BusinessUnit != null && !Equals(businessUnit, ExchangeServiceDocumentReport.BusinessUnit))
                {
                    continue;
                }

                tableLine.BusinessUnitName = businessUnit != null ? businessUnit.Name : string.Empty;
                tableLine.BusinessUnitId   = businessUnit != null ? businessUnit.Id : 0;

                // Получатель.
                var counterparty = documentExchangeInfo.Counterparty;
                tableLine.Counterparty = counterparty != null ? counterparty.Name : string.Empty;

                // Фильтр по контрагенту.
                if (ExchangeServiceDocumentReport.Counterparty != null && counterparty != null &&
                    !Equals(counterparty, ExchangeServiceDocumentReport.Counterparty))
                {
                    continue;
                }

                // Сервис обмена.
                var exchangeService = ExchangeCore.PublicFunctions.BoxBase.GetExchangeService(documentExchangeInfo.Box);
                tableLine.ExchangeService = exchangeService.Name;

                // Фильтр по сервисам обмена.
                var exchangeServices = ExchangeServiceDocumentReport.ExchangeService.ToList();
                if (!exchangeServices.Contains(exchangeService))
                {
                    continue;
                }

                // Ответственный и его подразделение.
                var tracking = document.Tracking
                               .Where(t => t.ExternalLinkId.HasValue && !t.ReturnDate.HasValue)
                               .OrderByDescending(t => t.DeliveryDate)
                               .FirstOrDefault();
                if (tracking != null)
                {
                    var employee = tracking.DeliveredTo;
                    tableLine.Responsible = employee.Person.ShortName ?? employee.Name;
                    tableLine.Department  = employee.Department != null?string.Format("({0})", employee.Department.Name) : string.Empty;
                }
                else
                {
                    tableLine.Responsible = string.Empty;
                    tableLine.Department  = string.Empty;
                }

                // Дата отправки.
                tableLine.SendDate = documentExchangeInfo.MessageDate.HasValue ?
                                     documentExchangeInfo.MessageDate.Value.ToUserTime().ToString("d") :
                                     "-";

                // Время ожидания контрагента.
                tableLine.Delay = WorkingTime.GetDurationInWorkingDays(documentExchangeInfo.MessageDate.Value, Calendar.Now).ToString();

                // Документ.
                tableLine.DocName   = document.Name;
                tableLine.DocId     = document.Id;
                tableLine.Hyperlink = Hyperlinks.Get(document);

                dataTable.Add(tableLine);
            }

            Docflow.PublicFunctions.Module.WriteStructuresToTable(documentsTableName, dataTable);
        }
コード例 #16
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            #region Параметры

            var reportSessionId = System.Guid.NewGuid().ToString();
            ApprovalRulesConsolidatedReport.ReportSessionId = reportSessionId;
            var includeSubsidiary  = ApprovalRulesConsolidatedReport.IncludeSubsidiary == true;
            var filterDepartment   = ApprovalRulesConsolidatedReport.Department;
            var filterBusinessUnit = ApprovalRulesConsolidatedReport.BusinessUnit;
            var filterDepartmentsForBusinessUnits = ApprovalRulesConsolidatedReport.FilterDepartmentsForBusinessUnits == true;
            var filterDocumentFlow = ApprovalRulesConsolidatedReport.DocumentFlow;
            var filterDocumentKind = ApprovalRulesConsolidatedReport.DocumentKind;
            var filterCategory     = ApprovalRulesConsolidatedReport.Category;

            #endregion

            #region Подготовка начальных данных

            var localizedValueCash = new Dictionary <Sungero.Core.Enumeration, string>();
            localizedValueCash[ApprovalRuleBase.Status.Active] = ApprovalRuleBases.Info.Properties.Status.GetLocalizedValue(ApprovalRuleBase.Status.Active);
            localizedValueCash[ApprovalRuleBase.Status.Draft]  = ApprovalRuleBases.Info.Properties.Status.GetLocalizedValue(ApprovalRuleBase.Status.Draft);

            var documentFlows = new List <Enumeration>()
            {
                ApprovalRuleBase.DocumentFlow.Incoming,
                ApprovalRuleBase.DocumentFlow.Outgoing,
                ApprovalRuleBase.DocumentFlow.Inner,
                ApprovalRuleBase.DocumentFlow.Contracts
            };
            foreach (var flow in documentFlows)
            {
                localizedValueCash[flow] = ApprovalRuleBases.Info.Properties.DocumentFlow.GetLocalizedValue(flow);
            }

            var tableData = new List <Structures.ApprovalRulesConsolidatedReport.TableLine>();
            // Сформировать список активных видов документов, которые можно утверждать.
            // Чтобы не было перезапросов к СП, весь список хранить в памяти.
            var approvalAction = Functions.Module.GetSendAction(OfficialDocuments.Info.Actions.SendForApproval);
            var rules          = ApprovalRuleBases.GetAll().Where(r => r.Status == ApprovalRuleBase.Status.Active ||
                                                                  r.Status == ApprovalRuleBase.Status.Draft).ToList();
            #endregion

            #region Фильтрация

            // НОР.
            List <Company.IBusinessUnit> businessUnits;
            if (filterBusinessUnit != null)
            {
                businessUnits = new List <Company.IBusinessUnit>()
                {
                    filterBusinessUnit
                };
                if (includeSubsidiary)
                {
                    businessUnits = this.GetSubBusinessUnits(businessUnits, Company.BusinessUnits.GetAll().Where(u => u.Status == Status.Active).ToList());
                }
            }
            else
            {
                businessUnits = Company.BusinessUnits.GetAll().Where(u => u.Status == Status.Active).ToList();

                // Для подразделений без НОР.
                if (filterDepartmentsForBusinessUnits)
                {
                    businessUnits.Add(null);
                }
            }

            // Подразделения.
            List <Company.IDepartment> departments;
            if (filterDepartment != null)
            {
                departments = new List <Company.IDepartment>()
                {
                    filterDepartment
                };
                if (includeSubsidiary)
                {
                    departments = this.GetSubDepartments(departments, Company.Departments.GetAll().Where(u => u.Status == Status.Active).ToList());
                }
            }
            else
            {
                departments = Company.Departments.GetAll().Where(u => u.Status == Status.Active).ToList();
            }

            // Виды документов.
            List <IDocumentKind> documentKinds;
            if (filterDocumentKind != null)
            {
                documentKinds = new List <IDocumentKind>()
                {
                    filterDocumentKind
                };
            }
            else
            {
                documentKinds = DocumentKinds.GetAll()
                                .Where(k => k.Status == DocumentKind.Status.Active && k.AvailableActions.Any(a => a.Action == approvalAction))
                                .ToList();
            }

            // Категории договоров.
            List <IDocumentGroupBase> categories;
            if (filterCategory != null)
            {
                categories = new List <IDocumentGroupBase>()
                {
                    filterCategory
                };
            }
            else
            {
                categories = DocumentGroupBases.GetAll().Where(d => d.Status == Status.Active).OrderBy(d => d.Name).ToList();
            }

            // Документопоток.
            if (!string.IsNullOrEmpty(filterDocumentFlow))
            {
                documentFlows = documentFlows.Where(x => localizedValueCash[x] == filterDocumentFlow).ToList();
            }

            #endregion

            var tableLines = new List <Structures.ApprovalRulesConsolidatedReport.TableLine>();

            foreach (var unit in businessUnits)
            {
                var subDepartments = departments.Where(d => (!filterDepartmentsForBusinessUnits && unit != null) || Equals(d.BusinessUnit, unit)).OrderBy(d => d.Name).ToList();

                if (!subDepartments.Any() &&
                    unit != null &&
                    filterDepartment == null)
                {
                    subDepartments.Add(null);
                }

                foreach (var department in subDepartments)
                {
                    foreach (var flow in documentFlows)
                    {
                        foreach (var kind in documentKinds.Where(k => Equals(k.DocumentFlow, flow)))
                        {
                            var subRules = rules
                                           .Where(r => r.DocumentFlow == flow &&
                                                  (!r.DocumentKinds.Any() || r.DocumentKinds.Any(k => Equals(k.DocumentKind, kind))) &&
                                                  (!r.BusinessUnits.Any() || r.BusinessUnits.Any(u => Equals(u.BusinessUnit, unit))) &&
                                                  (!r.Departments.Any() || r.Departments.Any(d => Equals(d.Department, department))));
                            var documentParentType = this.GetDocumentBaseTypeDisplayName(kind);

                            // Отдельно обрабатываем виды документов, для которых настроены категории.
                            var documentKindCategories = categories.Where(c => c.DocumentKinds.Any(d => Equals(d.DocumentKind, kind)));
                            if (documentKindCategories.Any())
                            {
                                foreach (var category in documentKindCategories)
                                {
                                    var categorySubRules = subRules.Where(sr => !sr.DocumentGroups.Any() || sr.DocumentGroups.Any(c => Equals(c.DocumentGroup, category)));
                                    tableLines = this.CreateTableDataLines(categorySubRules, reportSessionId, unit, department, category, flow, kind.Name, documentParentType, localizedValueCash);
                                    tableData.AddRange(tableLines);
                                }
                                continue;
                            }

                            // Если выбрана фильтрация по категории, то в отчет попадают только записи с заполненной категорией.
                            if (filterCategory == null)
                            {
                                // Если не найдено правила для доп. соглашений, тогда указываем, что используется правило договора.
                                var isSupAgreement = kind.DocumentType.DocumentTypeGuid == "265f2c57-6a8a-4a15-833b-ca00e8047fa5";
                                if (isSupAgreement)
                                {
                                    tableLines = this.CreateTableDataLines(subRules, reportSessionId, unit, department, null, flow, kind.Name, documentParentType, localizedValueCash);
                                    foreach (var tableLine in tableLines)
                                    {
                                        if (string.IsNullOrEmpty(tableLine.ApprovalRule))
                                        {
                                            tableLine.ApprovalRule = Reports.Resources.ApprovalRulesConsolidatedReport.ContractualDocumentRule;
                                        }
                                    }
                                    tableData.AddRange(tableLines);
                                    continue;
                                }

                                tableLines = this.CreateTableDataLines(subRules, reportSessionId, unit, department, null, flow, kind.Name, documentParentType, localizedValueCash);
                                tableData.AddRange(tableLines);
                            }
                        }
                    }
                }
            }

            Functions.Module.WriteStructuresToTable(Constants.ApprovalRulesConsolidatedReport.SourceTableName, tableData);
        }
コード例 #17
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            // Удалить временные таблицы.
            IncomingDocumentsProcessingReport.DocumentsTableName = Constants.IncomingDocumentsProcessingReport.IncomingDocumentsProcessingReportTableName;
            var incomingDocumentsProcessingReportShortName = "IncDocPro";

            IncomingDocumentsProcessingReport.AvailableIdsTableName = Docflow.PublicFunctions.Module.GetReportTableName(incomingDocumentsProcessingReportShortName, Users.Current.Id);
            IncomingDocumentsProcessingReport.TasksTableName        = Docflow.PublicFunctions.Module.GetReportTableName(incomingDocumentsProcessingReportShortName, Users.Current.Id, "tasks");
            IncomingDocumentsProcessingReport.HyperlinksTableName   = Docflow.PublicFunctions.Module.GetReportTableName(incomingDocumentsProcessingReportShortName, Users.Current.Id, "hyperlinks");
            IncomingDocumentsProcessingReport.ViewDataTableName     = Docflow.PublicFunctions.Module.GetReportTableName(incomingDocumentsProcessingReportShortName, Users.Current.Id, "viewDates");
            Docflow.PublicFunctions.Module.DropReportTempTables(new[] { IncomingDocumentsProcessingReport.AvailableIdsTableName,
                                                                        IncomingDocumentsProcessingReport.TasksTableName,
                                                                        IncomingDocumentsProcessingReport.HyperlinksTableName,
                                                                        IncomingDocumentsProcessingReport.ViewDataTableName });

            // Создать временную таблицу с ИД доступных задач.
            var availableDocumentsIds = Sungero.Docflow.IncomingDocumentBases.GetAll()
                                        .Where(d =>  d.RegistrationState == Docflow.OfficialDocument.RegistrationState.Registered)
                                        .Where(d =>  d.RegistrationDate >= IncomingDocumentsProcessingReport.BeginDate.Value)
                                        .Where(d =>  d.RegistrationDate <= IncomingDocumentsProcessingReport.EndDate.Value)
                                        .OrderByDescending(d => d.RegistrationDate)
                                        .Select(d => d.Id);

            Docflow.PublicFunctions.Module.CreateTempTableForRights(IncomingDocumentsProcessingReport.AvailableIdsTableName, availableDocumentsIds);

            // Костыль для передачи кода культуры в CONVERT, потому что FORMAT в SQL 2008 не работает.
            var culture       = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
            var cultureCode   = 104;
            var cultureCodePG = "DD.MM.YYYY";

            if (culture == "en-US")
            {
                cultureCode   = 101;
                cultureCodePG = "MM/DD/YYYY";
            }
            if (culture == "en-GB")
            {
                cultureCode   = 103;
                cultureCodePG = "DD/MM/YYYY";
            }
            IncomingDocumentsProcessingReport.ReportSessionId = System.Guid.NewGuid().ToString();

            var commandParams = new string[] {
                IncomingDocumentsProcessingReport.AvailableIdsTableName,
                IncomingDocumentsProcessingReport.TasksTableName
            };

            var commandText = Queries.IncomingDocumentsProcessingReport.TasksQuery;

            Functions.Module.ExecuteSQLCommandFormat(commandText, commandParams);

            // Указать исполнителя и дату ознакомления во времени клиента.
            var viewDates = new List <Structures.IncomingDocumentsProcessingReport.ViewDates>();
            var viewDateCreateTableQuery = string.Format(Queries.IncomingDocumentsProcessingReport.CreateViewDateQuery,
                                                         IncomingDocumentsProcessingReport.ViewDataTableName);
            var viewDateSelectQuery = string.Format(Queries.IncomingDocumentsProcessingReport.ViewDataQuery,
                                                    IncomingDocumentsProcessingReport.TasksTableName);

            using (var command = SQL.GetCurrentConnection().CreateCommand())
            {
                command.CommandText = viewDateCreateTableQuery;
                command.ExecuteNonQuery();

                command.CommandText = viewDateSelectQuery;
                var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    var assignmentId = reader.GetInt32(0);
                    var viewDate     = reader.GetDateTime(1).ToUserTime();
                    viewDates.Add(Structures.IncomingDocumentsProcessingReport.ViewDates.Create(assignmentId, viewDate));
                }
            }

            Docflow.PublicFunctions.Module.WriteStructuresToTable(IncomingDocumentsProcessingReport.ViewDataTableName, viewDates);

            var updateCommand = string.Format(Queries.IncomingDocumentsProcessingReport.UpdateViewDateQuery,
                                              IncomingDocumentsProcessingReport.TasksTableName,
                                              IncomingDocumentsProcessingReport.ViewDataTableName);

            Docflow.PublicFunctions.Module.ExecuteSQLCommand(updateCommand);

            commandParams = new string[] {
                IncomingDocumentsProcessingReport.AvailableIdsTableName,
                IncomingDocumentsProcessingReport.DocumentsTableName,
                IncomingDocumentsProcessingReport.TasksTableName,
                Sungero.RecordManagement.Reports.Resources.IncomingDocumentsProcessingReport.OnReview,
                Sungero.RecordManagement.Reports.Resources.IncomingDocumentsProcessingReport.Sending,
                Sungero.RecordManagement.Reports.Resources.IncomingDocumentsProcessingReport.WithoutExecut,
                Sungero.RecordManagement.Reports.Resources.IncomingDocumentsProcessingReport.OnExecution,
                Sungero.RecordManagement.Reports.Resources.IncomingDocumentsProcessingReport.Executed,
                Sungero.RecordManagement.Reports.Resources.IncomingDocumentsProcessingReport.Aborted,
                IncomingDocumentsProcessingReport.ReportSessionId,
                cultureCode.ToString(),
                cultureCodePG
            };

            commandText = Queries.IncomingDocumentsProcessingReport.DataQuery;
            Functions.Module.ExecuteSQLCommandFormat(commandText, commandParams);

            var hyperlinks = new List <Structures.IncomingDocumentsProcessingReport.Hyperlinks>();
            var hyperlinksCreateTableQuery = string.Format(Queries.IncomingDocumentsProcessingReport.CreateHyperlinksTableQuery,
                                                           IncomingDocumentsProcessingReport.HyperlinksTableName);
            var docIdSelectQuery = string.Format(Queries.IncomingDocumentsProcessingReport.DocIdSelectQuery,
                                                 IncomingDocumentsProcessingReport.DocumentsTableName,
                                                 IncomingDocumentsProcessingReport.ReportSessionId);

            using (var command = SQL.GetCurrentConnection().CreateCommand())
            {
                command.CommandText = hyperlinksCreateTableQuery;
                command.ExecuteNonQuery();

                // Для всех строк вычислить и записать в таблицу гиперссылку.
                command.CommandText = docIdSelectQuery;
                var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    var docId             = reader.GetInt32(0);
                    var documentHyperlink = Hyperlinks.Get(Sungero.Docflow.IncomingDocumentBases.Info, docId);
                    hyperlinks.Add(Structures.IncomingDocumentsProcessingReport.Hyperlinks.Create(docId, documentHyperlink));
                }
            }

            Docflow.PublicFunctions.Module.WriteStructuresToTable(IncomingDocumentsProcessingReport.HyperlinksTableName, hyperlinks);

            updateCommand = string.Format(Queries.IncomingDocumentsProcessingReport.UpdateHyperlinksQuery,
                                          IncomingDocumentsProcessingReport.DocumentsTableName,
                                          IncomingDocumentsProcessingReport.HyperlinksTableName,
                                          IncomingDocumentsProcessingReport.ReportSessionId);
            Docflow.PublicFunctions.Module.ExecuteSQLCommand(updateCommand);
        }
コード例 #18
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var sourceDocument        = AcquaintanceReport.Document;
            var sourceTask            = AcquaintanceReport.Task;
            var calledFromDocument    = sourceDocument != null;
            var selectedVersionNumber = this.AcquaintanceReport.DocumentVersion;

            // Если у документа нет тела, но есть задачи ознакомления, номер версии берем 0, иначе выбранный.
            var versionNumber = 0;

            if (selectedVersionNumber != null)
            {
                versionNumber = Convert.ToInt32(selectedVersionNumber);
            }

            var tasks = new List <IAcquaintanceTask>();

            if (calledFromDocument)
            {
                // Получить задачи на ознакомление по документу.
                tasks = Docflow.PublicFunctions.OfficialDocument.Remote.GetAcquaintanceTasks(sourceDocument);

                // Фильтр по номеру версии.
                tasks = tasks
                        .Where(t => t.AcquaintanceVersions.First(v => v.IsMainDocument == true).Number == versionNumber)
                        .ToList();
            }
            else
            {
                tasks.Add(sourceTask);
                versionNumber  = Functions.AcquaintanceTask.GetDocumentVersion(sourceTask);
                sourceDocument = sourceTask.DocumentGroup.OfficialDocuments.First();
            }

            // Провалидировать подписи версии.
            Sungero.Domain.Shared.IEntity version = null;
            if (versionNumber > 0 && sourceDocument.Versions.Any(v => v.Number == versionNumber))
            {
                version = sourceDocument.Versions.First(v => v.Number == versionNumber).ElectronicDocument;
            }
            var validationMessages = Functions.Module.GetDocumentSignatureValidationErrors(version, true);

            if (validationMessages.Any())
            {
                validationMessages.Insert(0, RecordManagement.Resources.SignatureValidationErrorMessage);
                AcquaintanceReport.SignValidationErrors = string.Join(System.Environment.NewLine, validationMessages);
            }

            // Шапка.
            var nonBreakingSpace = Convert.ToChar(160);

            AcquaintanceReport.DocumentHyperlink = Hyperlinks.Get(sourceDocument);
            AcquaintanceReport.DocumentName      = Docflow.PublicFunctions.Module.FormatDocumentNameForReport(sourceDocument, versionNumber, true);

            // Приложения.
            var documentAddenda = Functions.Module.GetAcquintanceTaskAddendas(tasks);

            if (documentAddenda.Any())
            {
                AcquaintanceReport.AddendaDescription = Reports.Resources.AcquaintanceReport.Addendas;
                foreach (var addendum in documentAddenda)
                {
                    var addendumInfo = string.Format("\n - {0} ({1}:{2}{3}).", addendum.DisplayValue.Trim(),
                                                     Docflow.Resources.Id, nonBreakingSpace, addendum.Id);
                    AcquaintanceReport.AddendaDescription += addendumInfo;
                }
            }

            // Данные.
            var reportSessionId = System.Guid.NewGuid().ToString();

            AcquaintanceReport.ReportSessionId = reportSessionId;
            var dataTable  = new List <Structures.AcquaintanceReport.TableLine>();
            var department = this.AcquaintanceReport.Department;

            foreach (var task in tasks)
            {
                var createdDate              = Docflow.PublicFunctions.Module.ToShortDateShortTime(task.Created.Value.ToUserTime());
                var taskId                   = task.Id;
                var taskHyperlink            = Hyperlinks.Get(task);
                var isElectronicAcquaintance = task.IsElectronicAcquaintance == true;
                var taskDisplayName          = isElectronicAcquaintance
          ? Reports.Resources.AcquaintanceReport.ElectronicAcquaintanceTaskDisplayNameFormat(createdDate)
          : Reports.Resources.AcquaintanceReport.SelfSignAcquaintanceTaskDisplayNameFormat(createdDate);

                // Фильтрация сотрудников по подразделениям.
                var acquainters = AcquaintanceFormReportServerHandlers.GetEmployeesFromParticipants(task);
                if (AcquaintanceReport.Department != null)
                {
                    acquainters = AcquaintanceReport.IncludeSubDepartments == true
            ? acquainters.Where(x => x.IncludedIn(AcquaintanceReport.Department))
            : acquainters.Where(x => Equals(x.Department, AcquaintanceReport.Department));
                }

                foreach (var employee in acquainters)
                {
                    var newLine = Structures.AcquaintanceReport.TableLine.Create();
                    newLine.RowNumber       = 0;
                    newLine.ReportSessionId = reportSessionId;

                    // Задача.
                    newLine.TaskDisplayName = taskDisplayName;
                    newLine.TaskId          = taskId;
                    newLine.TaskHyperlink   = taskHyperlink;

                    // Сотрудник.
                    newLine.ShortName = employee.Person.ShortName;
                    newLine.LastName  = employee.Person.LastName;
                    if (employee.JobTitle != null)
                    {
                        newLine.JobTitle = employee.JobTitle.DisplayValue;
                    }
                    newLine.Department = employee.Department.DisplayValue;

                    if (task.Status != Status.InProcess &&
                        task.Status != Status.Suspended &&
                        task.Status != Status.Completed)
                    {
                        if (employee.Status != Company.Employee.Status.Closed)
                        {
                            dataTable.Add(newLine);
                        }
                        continue;
                    }

                    // Задание.
                    var assignment = AcquaintanceAssignments.GetAll()
                                     .Where(a => Equals(a.Task, task) &&
                                            Equals(a.Performer, employee) &&
                                            a.Created >= task.Started)
                                     .FirstOrDefault();

                    if (assignment == null)
                    {
                        if (employee.Status != Company.Employee.Status.Closed)
                        {
                            dataTable.Add(newLine);
                        }
                        continue;
                    }

                    newLine.AssignmentId        = assignment.Id.ToString();
                    newLine.AssignmentHyperlink = Hyperlinks.Get(assignment);

                    var isCompleted = assignment.Status == Sungero.Workflow.Task.Status.Completed;
                    if (isCompleted)
                    {
                        // Дата ознакомления.
                        var completed = Calendar.ToUserTime(assignment.Completed.Value);
                        newLine.AcquaintanceDate = Docflow.PublicFunctions.Module.ToShortDateShortTime(completed);

                        // Примечание.
                        if (!Equals(assignment.CompletedBy, assignment.Performer))
                        {
                            var completedByShortName = Employees.Is(assignment.CompletedBy)
                ? Employees.As(assignment.CompletedBy).Person.ShortName
                : assignment.CompletedBy.Name;
                            newLine.Note += string.Format("{0}\n", completedByShortName);
                            newLine.Note += string.Format("\"{0}\"", assignment.ActiveText);
                        }
                        else if (!Equals(assignment.ActiveText, Reports.Resources.AcquaintanceReport.AcquaintedDefaultResult.ToString()))
                        {
                            newLine.Note += string.Format("\"{0}\"", assignment.ActiveText);
                        }
                    }

                    // Статус.
                    newLine.State = Functions.Module.GetAcquaintanceAssignmentState(assignment, isElectronicAcquaintance, isCompleted);

                    dataTable.Add(newLine);
                }
            }

            // Фильтр по статусу выполнения.
            if (AcquaintanceReport.EmployeesAcquaintanceStatus.Equals(Reports.Resources.AcquaintanceReport.ForAcquaintedPerformers))
            {
                dataTable = dataTable.Where(d => d.State == Reports.Resources.AcquaintanceReport.AcquaintedState).ToList();
            }
            else if (AcquaintanceReport.EmployeesAcquaintanceStatus.Equals(Reports.Resources.AcquaintanceReport.ForNotAcquaintedPerformers))
            {
                dataTable = dataTable.Where(d => d.State != Reports.Resources.AcquaintanceReport.AcquaintedState).ToList();
            }

            Docflow.PublicFunctions.Module.WriteStructuresToTable(Constants.AcquaintanceReport.SourceTableName, dataTable);

            // Подвал.
            var currentUser   = Users.Current;
            var printedByName = Employees.Is(currentUser)
        ? Employees.As(currentUser).Person.ShortName
        : currentUser.Name;

            AcquaintanceReport.Printed = Reports.Resources.AcquaintanceReport.PrintedByFormat(printedByName, Calendar.UserNow);
        }
コード例 #19
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            if (SkippedNumbersReport.DocumentRegisterId.HasValue)
            {
                SkippedNumbersReport.DocumentRegister = DocumentRegisters.Get(SkippedNumbersReport.DocumentRegisterId.Value);
            }

            SkippedNumbersReport.CurrentDate = Calendar.Now;

            var documentRegister = SkippedNumbersReport.DocumentRegister;

            var documents = Enumerable.Empty <IOfficialDocument>().AsQueryable();

            AccessRights.AllowRead(() =>
                                   { documents = Docflow.OfficialDocuments.GetAll()
                                                 .Where(d => d.DocumentRegister == SkippedNumbersReport.DocumentRegister)
                                                 .Where(d => d.RegistrationState == RegistrationState.Registered || d.RegistrationState == RegistrationState.Reserved); });

            #region Период формирования отчета и разрезы

            var baseDate     = Calendar.UserNow;
            var periodOffset = SkippedNumbersReport.PeriodOffset.HasValue
        ? SkippedNumbersReport.PeriodOffset.Value
        : 0;

            // Признак того, что отчет запущен из диалога регистрации.
            var launchedFromDialog = SkippedNumbersReport.RegistrationDate.HasValue;

            if (launchedFromDialog)
            {
                baseDate = SkippedNumbersReport.RegistrationDate.Value;
                // По умолчанию для отчета из диалога регистрации берем данные за последний месяц.
                SkippedNumbersReport.Period       = Constants.SkippedNumbersReport.Month;
                SkippedNumbersReport.PeriodOffset = 0;
            }

            if (SkippedNumbersReport.Period.Equals(Constants.SkippedNumbersReport.Year))
            {
                SkippedNumbersReport.PeriodBegin = Calendar.BeginningOfYear(baseDate.AddYears(periodOffset));
                SkippedNumbersReport.PeriodEnd   = periodOffset == 0 ? Calendar.EndOfYear(baseDate) :
                                                   Calendar.EndOfYear(baseDate.AddYears(periodOffset));
            }
            if (SkippedNumbersReport.Period.Equals(Constants.SkippedNumbersReport.Quarter))
            {
                SkippedNumbersReport.PeriodBegin = Docflow.PublicFunctions.AccountingDocumentBase.BeginningOfQuarter(baseDate.AddMonths(3 * periodOffset));
                SkippedNumbersReport.PeriodEnd   = periodOffset == 0 ? Docflow.PublicFunctions.AccountingDocumentBase.EndOfQuarter(baseDate) :
                                                   Docflow.PublicFunctions.AccountingDocumentBase.EndOfQuarter(baseDate.AddMonths(3 * periodOffset));
            }
            if (SkippedNumbersReport.Period.Equals(Constants.SkippedNumbersReport.Month))
            {
                SkippedNumbersReport.PeriodBegin = Calendar.BeginningOfMonth(baseDate.AddMonths(periodOffset));
                SkippedNumbersReport.PeriodEnd   = periodOffset == 0 ? Calendar.EndOfMonth(baseDate) :
                                                   Calendar.EndOfMonth(baseDate.AddMonths(periodOffset));
            }
            if (SkippedNumbersReport.Period.Equals(Constants.SkippedNumbersReport.Week))
            {
                SkippedNumbersReport.PeriodBegin = Calendar.BeginningOfWeek(baseDate.AddDays(7 * periodOffset));
                SkippedNumbersReport.PeriodEnd   = periodOffset == 0 ? Calendar.EndOfWeek(baseDate) :
                                                   Calendar.EndOfWeek(baseDate.AddDays(7 * periodOffset));
            }

            // Получить границы периода журнала регистрации.
            var      registrationDate            = launchedFromDialog ? SkippedNumbersReport.RegistrationDate.Value : SkippedNumbersReport.PeriodEnd.Value;
            DateTime?documentRegisterPeriodBegin = Functions.DocumentRegister.GetBeginPeriod(documentRegister, registrationDate);
            DateTime?documentRegisterPeriodEnd   = Functions.DocumentRegister.GetEndPeriod(documentRegister, registrationDate) ?? SkippedNumbersReport.PeriodEnd.Value;

            // Начало расчетного периода.
            var periodBegin = SkippedNumbersReport.PeriodBegin;

            // Если отчет вызван из диалога регистрации взять "месяц назад" от даты регистрации.
            if (launchedFromDialog)
            {
                periodBegin = registrationDate.AddMonths(-1);
            }

            // Если начало указанного периода раньше начала периода журнала, то считать от последнего.
            if (documentRegisterPeriodBegin.HasValue && documentRegisterPeriodBegin > periodBegin)
            {
                periodBegin = documentRegisterPeriodBegin;
            }
            else if (!documentRegisterPeriodBegin.HasValue)
            {
                documentRegisterPeriodBegin = Calendar.SqlMinValue;
            }

            SkippedNumbersReport.PeriodBegin = periodBegin;

            // Конец расчетного периода.
            var periodEnd = launchedFromDialog ? SkippedNumbersReport.RegistrationDate.Value.EndOfDay() : SkippedNumbersReport.PeriodEnd;
            SkippedNumbersReport.PeriodEnd = periodEnd;

            var hasLeadingDocument = SkippedNumbersReport.LeadingDocument != null;
            var hasDepartment      = SkippedNumbersReport.Department != null;
            var hasBusinessUnit    = SkippedNumbersReport.BusinessUnit != null;

            // Отфильтровать документы по разрезам.
            if (hasLeadingDocument)
            {
                documents = documents.Where(d => Equals(d.LeadingDocument, SkippedNumbersReport.LeadingDocument));
            }

            if (hasDepartment)
            {
                documents = documents.Where(d => Equals(d.Department, SkippedNumbersReport.Department));
            }

            if (hasBusinessUnit)
            {
                documents = documents.Where(d => Equals(d.BusinessUnit, SkippedNumbersReport.BusinessUnit));
            }

            #endregion

            #region Генерация формата номера

            var numberFormat = string.Empty;
            foreach (var item in documentRegister.NumberFormatItems.OrderBy(x => x.Number))
            {
                var elementName = string.Empty;
                if (item.Element == DocumentRegisterNumberFormatItems.Element.Number)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatNumber;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.Year2Place || item.Element == DocumentRegisterNumberFormatItems.Element.Year4Place)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatYear;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.Quarter)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatQuarter;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.Month)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatMonth;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.LeadingNumber)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatLeadingNumber;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.Log)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatLog;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.RegistrPlace)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatRegistrPlace;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.CaseFile)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatCaseFile;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.DepartmentCode)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatDepartmentCode;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.BUCode)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatBUCode;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.DocKindCode)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatDocKindCode;
                }
                else if (item.Element == DocumentRegisterNumberFormatItems.Element.CPartyCode)
                {
                    elementName = DocumentRegisters.Resources.NumberFormatCounterpartyCode;
                }

                numberFormat += elementName + item.Separator;
            }
            SkippedNumbersReport.NumberFormat = numberFormat;

            #endregion

            #region Границы индексов в выбранном периоде

            // Получить минимальный индекс по документам в периоде (при ручной регистрации мб нарушение следования индексов).
            var firstDocumentIndex = Functions.DocumentRegister.GetIndex(documents, periodBegin, periodEnd, false);

            // Получить индекс документа из предыдущего периода.
            var previousIndex = 0;
            if (periodBegin != documentRegisterPeriodBegin)
            {
                previousIndex = Functions.DocumentRegister.FilterDocumentsByPeriod(documents, documentRegisterPeriodBegin,
                                                                                   periodBegin.Value.AddDays(-1).EndOfDay())
                                .Where(d => !firstDocumentIndex.HasValue || d.Index < firstDocumentIndex).Select(d => d.Index).OrderByDescending(a => a).FirstOrDefault() ?? 0;
            }

            if (firstDocumentIndex == null)
            {
                firstDocumentIndex = previousIndex + 1;
            }

            var firstIndex = firstDocumentIndex < previousIndex ? firstDocumentIndex : previousIndex + 1;

            // Получить первый индекс документа следующего периода.
            var nextIndex = periodEnd != documentRegisterPeriodEnd?
                            Functions.DocumentRegister.GetIndex(documents, periodEnd.Value.AddDays(1).BeginningOfDay(), documentRegisterPeriodEnd, false) : null;

            // Если в следующем периоде ещё нет документов, то взять текущий индекс журнала.
            var leadingDocumentId = hasLeadingDocument
        ? SkippedNumbersReport.LeadingDocument.Id
        : 0;
            var departmentId = hasDepartment
        ? SkippedNumbersReport.Department.Id
        : 0;
            var businessUnitId = hasBusinessUnit
        ? SkippedNumbersReport.BusinessUnit.Id
        : 0;
            if (nextIndex == null)
            {
                nextIndex = Functions.DocumentRegister.GetCurrentNumber(documentRegister, registrationDate, leadingDocumentId, departmentId, businessUnitId) + 1;
            }

            // Получить индекс по зарегистрированным документам (при ручной регистрации мб нарушение следования индексов).
            var lastDocumentIndex = Functions.DocumentRegister.GetIndex(documents, periodBegin, periodEnd, true) ?? nextIndex - 1;
            var lastIndex         = lastDocumentIndex >= nextIndex ? lastDocumentIndex : nextIndex - 1;

            // Для случая когда нет документов в периоде.
            if (lastIndex < firstIndex)
            {
                lastIndex = firstIndex - 1;
            }

            #endregion

            // Отфильтровать документы по найденным границам индексов и по периоду журнала регистрации.
            // Допускать документы с номером не соответствующим формату (Index = 0).
            documents = documents
                        .Where(d => !documentRegisterPeriodBegin.HasValue || d.RegistrationDate >= documentRegisterPeriodBegin)
                        .Where(d => !documentRegisterPeriodEnd.HasValue || d.RegistrationDate <= documentRegisterPeriodEnd)
                        .Where(l => l.Index >= firstIndex && l.Index <= lastIndex ||
                               (l.Index == 0 && l.RegistrationDate <= SkippedNumbersReport.PeriodEnd && l.RegistrationDate >= SkippedNumbersReport.PeriodBegin));

            // Заполнить маску для гиперссылки.
            if (documents.Count() > 0)
            {
                var link  = Hyperlinks.Get(documents.First());
                var index = link.IndexOf("?type=");
                SkippedNumbersReport.hyperlinkMask = link.Substring(0, index) + "?type=DocGUID&id=DocId";
            }
            else
            {
                SkippedNumbersReport.hyperlinkMask = string.Empty;
            }

            #region Вычислить пропущенные индексы

            // Создать временную таблицу для списка номеров "подряд".
            var skipsTableName = Constants.SkippedNumbersReport.SkipsTableName;
            SkippedNumbersReport.SkipsTableName = skipsTableName;
            var skipedNumberList = new List <string>();
            var skipedNumbers    = new List <Structures.SkippedNumbersReport.SkippedNumber>();
            var reportSessionId  = Guid.NewGuid().ToString();
            SkippedNumbersReport.ReportSessionId = reportSessionId;

            // Заполнить таблицу номеров.
            var month     = documentRegisterPeriodBegin.Value.Month < 10 ? string.Format("0{0}", documentRegisterPeriodBegin.Value.Month) : documentRegisterPeriodBegin.Value.Month.ToString();
            var day       = documentRegisterPeriodBegin.Value.Day < 10 ? string.Format("0{0}", documentRegisterPeriodBegin.Value.Day) : documentRegisterPeriodBegin.Value.Day.ToString();
            var startDate = string.Format("{0}{1}{2}", documentRegisterPeriodBegin.Value.Year, month, day);

            month = documentRegisterPeriodEnd.Value.Month < 10 ? string.Format("0{0}", documentRegisterPeriodEnd.Value.Month) : documentRegisterPeriodEnd.Value.Month.ToString();
            day   = documentRegisterPeriodEnd.Value.Day < 10 ? string.Format("0{0}", documentRegisterPeriodEnd.Value.Day) : documentRegisterPeriodEnd.Value.Day.ToString();
            var endDate = string.Format("{0}{1}{2}", documentRegisterPeriodEnd.Value.Year, month, day);

            var queryText = string.Format(Queries.SkippedNumbersReport.GetSkippedIndexes,
                                          SkippedNumbersReport.DocumentRegister.Id.ToString(),
                                          (firstIndex - 1).ToString(),
                                          (lastIndex + 1).ToString(),
                                          hasBusinessUnit.ToString(),
                                          businessUnitId.ToString(),
                                          hasDepartment.ToString(),
                                          departmentId.ToString(),
                                          hasLeadingDocument.ToString(),
                                          leadingDocumentId.ToString(),
                                          documentRegisterPeriodBegin.HasValue.ToString(),
                                          startDate,
                                          endDate);

            // Получить интервалы пропущеных индексов журнала в периоде.
            // Key - начало интервала, Value - окончиние интервала.
            var skippedIndexIntervals = new Dictionary <int, int>();
            using (var command = SQL.GetCurrentConnection().CreateCommand())
            {
                command.CommandText = queryText;
                var result = command.ExecuteReader();
                while (result.Read())
                {
                    skippedIndexIntervals.Add((int)result[1], (int)result[0]);
                }
                result.Close();
            }

            // Заполнить отчет данными для пропущенных индексов.
            foreach (var interval in skippedIndexIntervals)
            {
                var intervalStart = interval.Key;
                var intervalEnd   = interval.Value;

                // Три и более подряд идущих пропущеных индексов должны быть собраны в одну строку.
                var intervalLength = intervalEnd - intervalStart + 1;
                if (intervalLength >= 3)
                {
                    skipedNumbers.Add(Structures.SkippedNumbersReport.SkippedNumber.Create(Docflow.Reports.Resources.SkippedNumbersReport.NumbersAreSkipped,
                                                                                           string.Format("{0}-{1}", intervalStart.ToString(), intervalEnd.ToString()),
                                                                                           intervalStart,
                                                                                           reportSessionId));
                    skipedNumberList.Add(string.Format("{0}-{1}",
                                                       intervalStart.ToString(),
                                                       intervalEnd.ToString()));

                    continue;
                }

                for (var i = intervalStart; i <= intervalEnd; i++)
                {
                    skipedNumbers.Add(Structures.SkippedNumbersReport.SkippedNumber.Create(Docflow.Reports.Resources.SkippedNumbersReport.NumberIsSkipped,
                                                                                           i.ToString(),
                                                                                           i,
                                                                                           reportSessionId));
                    skipedNumberList.Add(i.ToString());
                }
            }

            #endregion

            Functions.Module.WriteStructuresToTable(skipsTableName, skipedNumbers);

            // Получить 8-10 первых пропущенных номеров строкой. Для остальных указать общее количество.
            var skipedNumberCount       = skipedNumberList.Count;
            var maxDisplayedNumberCount = 10;
            var minHiddenNumberCount    = 3;
            var displayedValuesCount    = skipedNumberCount;
            if (skipedNumberCount >= (maxDisplayedNumberCount + minHiddenNumberCount))
            {
                displayedValuesCount = maxDisplayedNumberCount;
            }
            else if (skipedNumberCount > maxDisplayedNumberCount)
            {
                displayedValuesCount = skipedNumberCount - minHiddenNumberCount;
            }

            SkippedNumbersReport.SkipedNumberList = string.Join(", ", skipedNumberList.ToArray(), 0, displayedValuesCount);
            var hiddenSkipedNumberCount = skipedNumberCount - displayedValuesCount;
            if (hiddenSkipedNumberCount > 0)
            {
                var numberLabel = Functions.Module.GetNumberDeclination(hiddenSkipedNumberCount,
                                                                        Resources.SkippedNumbersReportNumber,
                                                                        Resources.SkippedNumbersReportNumberGenetive,
                                                                        Resources.SkippedNumbersReportNumberPlural);

                SkippedNumbersReport.SkipedNumberList += string.Format(Sungero.Docflow.Reports.Resources.SkippedNumbersReport.And, hiddenSkipedNumberCount, numberLabel);
            }

            // Создать таблицу для доступных пользователю документов.
            var availableDocuments = new List <Structures.SkippedNumbersReport.AvailableDocument>();
            var previousDocDate    = Calendar.SqlMinValue;
            foreach (var document in documents.ToList().OrderBy(x => x.Index))
            {
                var numberOnFormat = document.Index != null && document.Index != 0;
                var canRead        = document.AccessRights.CanRead();
                var inCorrectOrder = (previousDocDate <= document.RegistrationDate || !numberOnFormat) &&
                                     (document.RegistrationDate >= SkippedNumbersReport.PeriodBegin && document.RegistrationDate <= SkippedNumbersReport.PeriodEnd);
                availableDocuments.Add(Structures.SkippedNumbersReport.AvailableDocument.Create(document.Id, numberOnFormat, canRead, inCorrectOrder, reportSessionId));

                if (numberOnFormat && inCorrectOrder)
                {
                    previousDocDate = document.RegistrationDate.Value;
                }
            }

            SkippedNumbersReport.AvailableDocumentsTableName = Constants.SkippedNumbersReport.AvailableDocumentsTableName;
            Functions.Module.WriteStructuresToTable(SkippedNumbersReport.AvailableDocumentsTableName, availableDocuments);
        }
コード例 #20
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            var entity = ApprovalRuleCardReport.ApprovalRule;

            ApprovalRuleCardReport.ReportSessionId = System.Guid.NewGuid().ToString();
            ApprovalRuleCardReport.CurrentDate     = Calendar.Now;
            var tableData = new List <Structures.ApprovalRuleCardReport.CriteriaTableLine>();

            // Основные свойства.
            ApprovalRuleCardReport.RuleFlowLocalized   = entity.Info.Properties.DocumentFlow.GetLocalizedValue(entity.DocumentFlow.Value);
            ApprovalRuleCardReport.RuleStatusLocalized = entity.Info.Properties.Status.GetLocalizedValue(entity.Status.Value);

            // Доработка.
            if (entity.ReworkPerformerType == ApprovalRule.ReworkPerformerType.EmployeeRole)
            {
                ApprovalRuleCardReport.ReworkPerformer = Functions.ApprovalStage.GetRecipientDescription(entity.ReworkPerformer);
            }
            if (entity.ReworkPerformerType == ApprovalRule.ReworkPerformerType.Author)
            {
                ApprovalRuleCardReport.ReworkPerformer = Sungero.Docflow.ApprovalStages.Resources.ReportAuthor;
            }
            if (entity.ReworkPerformerType == ApprovalRule.ReworkPerformerType.ApprovalRole)
            {
                ApprovalRuleCardReport.ReworkPerformer = string.Format("\"{0}\"", entity.ReworkApprovalRole.Name);
            }
            ApprovalRuleCardReport.ReworkDeadline = string.Format("{0} {1}",
                                                                  entity.ReworkDeadline,
                                                                  Functions.Module.GetNumberDeclination(entity.ReworkDeadline.Value, Resources.StateViewDay, Resources.StateViewDayGenetive, Resources.StateViewDayPlural));

            // Критерии.
            // НОР.
            var propertyLocalizedName = ApprovalRuleBases.Info.Properties.BusinessUnits.LocalizedName;
            var businessUnits         = ApprovalRuleCardReport.ApprovalRule.BusinessUnits;

            foreach (var businessUnit in businessUnits)
            {
                tableData.Add(this.CreateCriteriaTableLine(propertyLocalizedName, businessUnit.BusinessUnit));
            }
            if (!businessUnits.Any())
            {
                tableData.Add(this.CreateCriteriaTableLine(propertyLocalizedName, Reports.Resources.ApprovalRuleCardReport.All));
            }

            // Подразделения.
            propertyLocalizedName = ApprovalRuleBases.Info.Properties.Departments.LocalizedName;
            var departments = ApprovalRuleCardReport.ApprovalRule.Departments;

            foreach (var department in departments)
            {
                tableData.Add(this.CreateCriteriaTableLine(propertyLocalizedName, department.Department));
            }
            if (!departments.Any())
            {
                tableData.Add(this.CreateCriteriaTableLine(propertyLocalizedName, Reports.Resources.ApprovalRuleCardReport.All));
            }

            // Виды документов.
            propertyLocalizedName = ApprovalRuleBases.Info.Properties.DocumentKinds.LocalizedName;
            var documentKinds = ApprovalRuleCardReport.ApprovalRule.DocumentKinds;

            foreach (var documentKind in documentKinds)
            {
                tableData.Add(this.CreateCriteriaTableLine(propertyLocalizedName, documentKind.DocumentKind));
            }
            if (!documentKinds.Any())
            {
                tableData.Add(this.CreateCriteriaTableLine(propertyLocalizedName,
                                                           Reports.Resources.ApprovalRuleCardReport.AllKindsFormat(ApprovalRuleCardReport.RuleFlowLocalized)));
            }

            // Категории договоров, если правило для договорных.
            if (Sungero.Contracts.ContractsApprovalRules.Is(entity))
            {
                propertyLocalizedName = Sungero.Contracts.ContractsApprovalRules.Info.Properties.DocumentGroups.LocalizedName;
                var documentGroups = ApprovalRuleCardReport.ApprovalRule.DocumentGroups;
                foreach (var documentGroup in documentGroups)
                {
                    tableData.Add(this.CreateCriteriaTableLine(propertyLocalizedName, documentGroup.DocumentGroup));
                }
                if (!documentGroups.Any())
                {
                    tableData.Add(this.CreateCriteriaTableLine(propertyLocalizedName, Reports.Resources.ApprovalRuleCardReport.All));
                }
            }

            Functions.Module.WriteStructuresToTable(Constants.ApprovalRuleCardReport.CriteriaTableName, tableData);

            var conditionTableData = this.GetConditionTableData(entity, ApprovalRuleCardReport.ReportSessionId);

            Functions.Module.WriteStructuresToTable(Constants.ApprovalRuleCardReport.ConditionTableName, conditionTableData);

            // Добавить права подписи.
            if (entity.Stages.Any(x => x.StageType == Docflow.ApprovalRuleStages.StageType.Sign ||
                                  x.StageType == Docflow.ApprovalRuleStages.StageType.Review))
            {
                ApprovalRuleCardReport.SignSettHeader = Reports.Resources.ApprovalRuleCardReport.SignatureSettingsHeader;
                var signatureSettingsData = this.GetSignatureSettingsTableData(entity, ApprovalRuleCardReport.ReportSessionId);
                if (!signatureSettingsData.Any())
                {
                    ApprovalRuleCardReport.SignSettEmpty = Reports.Resources.ApprovalRuleCardReport.SignatureSettingsEmpty;
                }
                Functions.Module.WriteStructuresToTable(Constants.ApprovalRuleCardReport.SignatureSettingsTableName, signatureSettingsData);
            }
        }
コード例 #21
0
 public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
 {
     DocumentUsageReport.ReportDate   = Calendar.Now;
     DocumentUsageReport.DepartmentId = DocumentUsageReport.Department != null ? DocumentUsageReport.Department.Id : 0;
 }