private void Populate()
        {
            inspRep = new InspectionRepository();
            //IEnumerable<Inspection> inspections = Context.Inspections;
            //IEnumerable<InspectionViewModel> inspectionsVM = inspections
            //   .Select(o => new InspectionViewModel(o));

            //Inspections = new ObservableCollection<InspectionViewModel>(inspectionsVM);
            //RaisePropertyChanged("Inspections");

            //INSPECTIES PER MAAND
            InspectionsPerMonth = new ObservableCollection<InspectionPerMonth>();

            IEnumerable<KeyValuePair<Int32, Int32>> query = inspRep.GetInspectionsPerMonth();

            string[] months = new string[12] { "Januari", "februari" , "Maart", "April" , "Mei" , "Juni" , "Juli" , "Augustus" , "September" , "Oktober" , "November", "December" };
            foreach (var t in query)
            {
                InspectionsPerMonth.Add(new InspectionPerMonth() { Maand = months[t.Key - 1], Count = t.Value});
            }
            //END INSPECTIES PER MAAND

            //AANTAL INSPECTIES PER INSPECTEUR

            //END AANTAL INSPECTIES PER INSPECTEUR
        }
 public AboutUsController()
 {
     imageRepository      = new ImageRepository();
     inspectionRepository = new InspectionRepository();
     visitorRepository    = new VisitorRepository();
     db = new ITIDataEntities();
 }
        private void Populate()
        {
            inspRep = new InspectionRepository();
            //IEnumerable<Inspection> inspections = Context.Inspections;
            //IEnumerable<InspectionViewModel> inspectionsVM = inspections
            //   .Select(o => new InspectionViewModel(o));

            //Inspections = new ObservableCollection<InspectionViewModel>(inspectionsVM);
            //RaisePropertyChanged("Inspections");


            //INSPECTIES PER MAAND
            InspectionsPerMonth = new ObservableCollection <InspectionPerMonth>();

            IEnumerable <KeyValuePair <Int32, Int32> > query = inspRep.GetInspectionsPerMonth();

            string[] months = new string[12] {
                "Januari", "februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"
            };
            foreach (var t in query)
            {
                InspectionsPerMonth.Add(new InspectionPerMonth()
                {
                    Maand = months[t.Key - 1], Count = t.Value
                });
            }
            //END INSPECTIES PER MAAND

            //AANTAL INSPECTIES PER INSPECTEUR

            //END AANTAL INSPECTIES PER INSPECTEUR
        }
Beispiel #4
0
 public UnitOfWork()
 {
     DesignationRepository                = new DesignationRepository(context);
     UserRepository                       = new UserRepository(context);
     RoleRepository                       = new RoleRepository(context);
     BuildingTypeRepository               = new BuildingTypeRepository(context);
     RoofTypeRepository                   = new RoofTypeRepository(context);
     DefactsRepository                    = new DefactsRepository(context);
     ConstructionPartsRepository          = new ConstructionPartsRepository(context);
     BuildingRepository                   = new BuildingRepository(context);
     RoofComponentsRepository             = new RoofComponentRepository(context);
     InspectionRepository                 = new InspectionRepository(context);
     RoofRepository                       = new RoofRepository(context);
     RoofElementRepository                = new RoofElementRepository(context);
     RoofDetailElementConditionRepository = new RoofDetailElementConditionRepository(context);
     ObservedDefectRepository             = new ObservedDefectRepository(context);
     RoofConstructionRepository           = new RoofConstructionRepository(context);
     ElementConstructionRepository        = new ElementConstructionRepository(context);
     RoofAdvicesMaintenanceRepository     = new RoofAdvicesMaintenanceRepository(context);
     BuildingAdviceMaintenanceRepository  = new BuildingAdviceMaintenanceRepository(context);
     BuildingPicturesRepository           = new BuildingPictureRepository(context);
     ContractDutiesRepository             = new ContractDutiesRepository(context);
     BuildingDocumentsRepository          = new BuildingDocumentsRepository(context);
     TaskMastersRepository                = new TaskMastersRepository(context);
 }
        public void TestDuplicateInspectionInspectorLogic()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                Inspector Inspector1 = new Inspector()
                {
                    Id = Guid.NewGuid(), Name = "Inspector 1", Created = DateTime.Today
                };
                Inspection Inspection1 = new Inspection()
                {
                    Id           = Guid.NewGuid(),
                    Customer     = "Customer 1",
                    Address      = "Address 1",
                    Observations = "Observation 1",
                    Status       = Status.Done,
                    Created      = DateTime.Today
                };
                InspectionInspector relation1 = new InspectionInspector()
                {
                    InspectionDate = DateTime.Today.AddDays(-1), InspectionId = Inspection1.Id, InspectorId = Inspector1.Id
                };
                Inspection1.InspectionInspector = new List <InspectionInspector>()
                {
                    relation1
                };

                repositori.Create(Inspection1);
                context.SaveChanges();

                InspectorDTO inspectorDTO = new InspectorDTO()
                {
                    Id = Inspector1.Id, Name = "Inspector 1"
                };
                InspectionDTO InspectionDTO = new InspectionDTO()
                {
                    Id             = Inspection1.Id,
                    Customer       = "Customer 1",
                    Address        = "Address 1",
                    Observations   = "Observation 1",
                    status         = Status.Done,
                    InspectionDate = relation1.InspectionDate,
                    Inspectors     = new List <InspectorDTO>()
                    {
                        inspectorDTO
                    }
                };


                //Act
                Inspection found = repositori.GetSingleEagerAsync(o => o.Id == InspectionDTO.Id &&
                                                                  o.InspectionInspector.Any(ii => ii.InspectionDate == InspectionDTO.InspectionDate) &&
                                                                  o.InspectionInspector.Any(ii => InspectionDTO.Inspectors.Any(i => i.Id == ii.InspectorId))).Result;

                //Assert
                Assert.NotNull(found);
            }
        }
Beispiel #6
0
        /// <summary>
        ///  Депо – вкладка с информацией о плановом назначении поезда на места постановки
        /// </summary>
        private static async Task <ReportResponse> GetDepoEventsTable(ReportRequest input, int planedRouteTrainId, ILogger logger)
        {
            var sqlRTrains            = new TrainRepository(logger);
            var sqlRTask              = new TaskRepository(logger);
            var sqlRPlanedRouteTrains = new PlanedRouteTrainsRepository(logger);
            var sqlRRoute             = new RoutesRepository(logger);
            var sqlRInspections       = new InspectionRepository(logger);
            var sqlRTaskAttributes    = new TrainTaskAttributesRepository(logger);
            var sqlREquipmentModel    = new EquipmentModelsRepository(logger);
            var sqlREquipment         = new EquipmentRepository(logger);
            var sqlRCarriage          = new CarriageRepository(logger);
            var sqlR          = new PrimitiveRepository(logger, "Parkings");
            var sqlRDepoEvent = new DepoEventsRepository(logger);



            var result = new ReportResponse {
                Rows = new List <Row>()
            };

            result.Columns = new List <Column>
            {
                new Column("col0", "Место постановки", "string"),
                new Column("col1", "Время захода на место постановки", "date"),
                new Column("col2", "Время выхода с места постановки", "date"),
            };

            var planedRouteTrain = await sqlRPlanedRouteTrains.ById(planedRouteTrainId);

            var events = await sqlRDepoEvent.ByTrainId(planedRouteTrain.TrainId);

            foreach (var item in events)
            {
                var parking = await sqlR.ById <Parking>(item.ParkingId);

                string testStopTime = null;
                if (item.TestStopTime != null)
                {
                    testStopTime = ((DateTime)item.TestStopTime).ToStringDateTime();
                }

                var row = new Row
                {
                    Id       = new RowId(item.Id, 1),
                    HasItems = false.ToString(),
                    ParentId = null,
                    //Место постановки
                    Col0 = parking.Name,
                    //Время захода на место постановки
                    Col1 = item.InTime.ToStringDateTime(),
                    //Время выхода с места постановки
                    Col2 = testStopTime
                };

                result.Rows.Add(row);
            }

            return(result);
        }
 public ProjectDetailViewModel(Project project)
 {
     Project     = project;
     DisplayName = project.ProjectName;
     Reviews     = new ReviewRepository(reviewData).Reviews;
     Tags        = new TagRepository(tagData).Tags;
     Inspections = new InspectionRepository(inspectionData).Inspections;
 }
Beispiel #8
0
        public void ShouldNotFindEagerInpectionsAsync()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                //Act
                Inspection result = repositori.FindEagerAsync(Guid.NewGuid()).Result;

                //Assert
                Assert.Null(result);
            }
        }
Beispiel #9
0
        public void ShouldNotRetriveSingleEagerInpections()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                //Act
                Inspection result = repositori.GetSingleEager(o => o.Id == Guid.NewGuid());

                //Assert
                Assert.Null(result);
            }
        }
Beispiel #10
0
        public void ShouldRetriveFilteredEagerInpectionsAsync()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                //Act
                IEnumerable <Inspection> result = repositori.GetFilteredEagerAsync(o => o.Status == testStatus).Result;

                //Assert
                Assert.Single(result);
            }
        }
Beispiel #11
0
        public async Task ShouldSave()
        {
            var data = new ImageMetaData()
            {
                Date        = DateTime.Now,
                Description = "SomeData",
                InspectorId = 123,
                Length      = 111,
                ImageStream = new byte[] { 1, 2, 3 }
            };

            var target = new InspectionRepository();
            await target.AddOrUpdateInspection("123", data);
        }
Beispiel #12
0
        public void ShouldFindEagerInpections()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                //Act
                Inspection result = repositori.FindEager(testId);

                //Assert
                Assert.NotNull(result);
            }
        }
        public void ShouldRetriveAllEagerInpectionsAsync()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                //Act
                IEnumerable <Inspection> result = repositori.GetAllEagerAsync().Result;

                //Assert
                Assert.Equal(3, result.Count());
            }
        }
Beispiel #14
0
        public void ShouldRetriveSingleInpectionAsync()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                //Act
                Inspection result = repositori.GetSingleAsync(o => o.Id == testId).Result;

                //Assert
                Assert.NotNull(result);
            }
        }
Beispiel #15
0
        public void ShouldRemoveInpection()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                //Act
                repositori.Delete(testId);
                Inspection result = repositori.Find(testId);

                //Assert
                Assert.False(result.Active);
            }
        }
Beispiel #16
0
        public async Task <InspectionByIdDto> InspectionByIdForEventTable(int inspectionId)
        {
            var sqlRInspection = new InspectionRepository(_logger);
            var inspectionDto  = await sqlRInspection.ByIdForEventTable(inspectionId);

            var sqlRTrainTaskAttributes = new TrainTaskAttributesRepository(_logger);

            if (inspectionDto == null)
            {
                throw new NotFoundException();
            }
            inspectionDto.Id = "M" + inspectionDto.InspectionId;

            inspectionDto.Type        = GetStringInspectionType((CheckListType)inspectionDto.TypeInt);
            inspectionDto.Status      = GetStringInspectionStatus((InspectionStatus)inspectionDto.StatusInt);
            inspectionDto.BrigadeName = GetStringBrigadeType((BrigadeType)inspectionDto.BrigadeTypeInt);

            var endDateString = string.Empty;

            if (inspectionDto.DateEnd.HasValue)
            {
                endDateString = $" - {inspectionDto.DateEnd:g}";
            }
            inspectionDto.Date = $"{inspectionDto.DateStart:g}" + endDateString;


            //TaskCount
            var taskAttributesByInspectionCount = await sqlRTrainTaskAttributes.ByInspectionId(inspectionId);

            inspectionDto.TaskCount = taskAttributesByInspectionCount.Count;

            //Метки
            inspectionDto.Labels = await GetInspectionLabels(inspectionId);

            //Счетчики киловат и прочей хери
            inspectionDto.InspectionDataCarriages = await GetInspectionCounters(inspectionId);

            //Остальные данные по инспекции
            inspectionDto.InspectionDataUis = await GetInspectionOtherData(inspectionId);

            return(inspectionDto);
        }
Beispiel #17
0
        public UnitOfWork()
        {
            if (_context == null)
            {
                _context = new FestiSpecEntities();
            }

            Inspectors          = new InspectorRepository(_context);
            NawEmployee         = new NAWEmployeeRepository(_context);
            Employee            = new EmployeeRepository(_context);
            RoleEmployee        = new RoleEmployeeRepository(_context);
            NAWInspectors       = new NAWInspector_Repository(_context);
            Questionnaires      = new QuestionnaireRepository(_context);
            Inspections         = new InspectionRepository(_context);
            InspectionLocations = new LocationRepository(_context);
            Customers           = new CustomerRepository(_context);
            ContactPersons      = new ContactPersonRepository(_context);
            Certificates        = new CertificatesRepository(_context);
            NAWCustomers        = new NAWCustomerRepository(_context);
        }
        public void ShouldCreateInpection()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                Inspection Inspection1 = new Inspection()
                {
                    Customer     = "Customer 1",
                    Address      = "Address 1",
                    Observations = "Observation 1",
                    Status       = Status.Done,
                    Created      = DateTime.Today
                };

                //Act
                repositori.Create(Inspection1);
                Inspection result = repositori.Find(Inspection1.Id);

                //Assert
                Assert.NotNull(result);
            }
        }
        public void ShouldCreateWithInspectorInpection()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                Inspector Inspector1 = new Inspector()
                {
                    Name = "Inspector 1", Created = DateTime.Today
                };
                Inspection Inspection1 = new Inspection()
                {
                    Customer     = "Customer 1",
                    Address      = "Address 1",
                    Observations = "Observation 1",
                    Status       = Status.Done,
                    Created      = DateTime.Today
                };
                InspectionInspector relation1 = new InspectionInspector()
                {
                    InspectionDate = DateTime.Today.AddDays(-1), InspectionId = Inspection1.Id, InspectorId = Inspector1.Id
                };
                Inspection1.InspectionInspector = new List <InspectionInspector>()
                {
                    relation1
                };

                //Act
                repositori.Create(Inspection1);
                Inspection result = repositori.Find(Inspection1.Id);

                //Assert
                Assert.NotNull(result);
            }
        }
Beispiel #20
0
        /// <summary>
        ///  Приемка/Сдача ЛБ таблица
        /// </summary>
        private static async Task <ReportResponse> GetLocomotvInspectionsTable(ReportRequest input, int planedRouteTrainId, ILogger logger)
        {
            var sqlRTrains            = new TrainRepository(logger);
            var sqlRPlanedRouteTrains = new PlanedRouteTrainsRepository(logger);
            var sqlRRoute             = new RoutesRepository(logger);
            var sqlRInspections       = new InspectionRepository(logger);
            var sqlRTaskAttributes    = new TrainTaskAttributesRepository(logger);
            var sqlRUser    = new UserRepository(logger);
            var sqlRBrigade = new BrigadeRepository(logger);

            var result = new ReportResponse {
                Rows = new List <Row>()
            };

            result.Columns = new List <Column>
            {
                new Column("col0", "Состав", "string"),
                new Column("col1", "Тип", "string"),
                new Column("col2", "Время начала", "date"),
                new Column("col3", "Время окончания", "date"),
                new Column("col4", "Меток считано", "number"),
                new Column("col5", "Новых инцидентов заведено (из них критических)", "number"),
                new Column("col6", "Инцидентов на составе всего", "string"),
                new Column("col7", "Километров всего", "number"),
                new Column("col8", "Километров за смену", "number"),
                new Column("col9", "КВт*ч (по каждому вагону)", "string"),
            };

            var planedRouteTrain = await sqlRPlanedRouteTrains.ById(planedRouteTrainId);

            //var route = await sqlRRoute.ById(planedRouteTrain.RouteId);

            var currentTrainInspections = await sqlRInspections.GetByTrainId(planedRouteTrain.TrainId);

            var currentDayInspections =
                currentTrainInspections.Where(x => x.DateStart.Date.Equals(planedRouteTrain.CreateDate));



            foreach (var currentDayInspection in currentDayInspections)
            {
                var user = await sqlRUser.ById(currentDayInspection.UserId);

                if (user.BrigadeId == null)
                {
                    continue;
                }

                var brigade = await sqlRBrigade.ById((int)user.BrigadeId);

                if (brigade.BrigadeType != BrigadeType.Locomotiv)
                {
                    continue;
                }

                var row = new Row
                {
                    Id       = new RowId(currentDayInspection.Id, 1),
                    HasItems = false.ToString(),
                    ParentId = null,
                    //Состав
                    Col0 = (await sqlRTrains.ById(planedRouteTrain.TrainId)).Name,
                    //Тип
                    Col1 = GetStringInspectionType(currentDayInspection.CheckListType),
                    //Время начала
                    Col2 = currentDayInspection.DateStart.ToStringDateTime(),
                    //Время окончания
                    Col3 = currentDayInspection.DateEnd?.ToStringDateTime(),
                    //Меток считано
                    Col4 = "666",
                    //Новых инцидентов заведено (из них критических)
                    Col5 = "666",
                    //Инцидентов на составе всего
                    Col6 = "666",
                    //Километров всего
                    Col7 = "666",
                    //Километров за смену
                    Col8 = "666",
                    //КВт*ч (по каждому вагону)
                    Col9 = "In Development",
                };

                result.Rows.Add(row);
            }

            return(result);
        }
Beispiel #21
0
        /// <summary>
        ///  Инциденты – вкладка с перечнем открытых инцидентов на составе, с возможностью перехода в форму инцидента при клике по нему. Информация будет выводится в табличном виде, со следующим набором полей:
        /// </summary>
        private static async Task <ReportResponse> GetNotClosedTrainTaskTable(ReportRequest input, int planedRouteTrainId, ILogger logger)
        {
            var sqlRTrains            = new TrainRepository(logger);
            var sqlRTask              = new TaskRepository(logger);
            var sqlRPlanedRouteTrains = new PlanedRouteTrainsRepository(logger);
            var sqlRRoute             = new RoutesRepository(logger);
            var sqlRInspections       = new InspectionRepository(logger);
            var sqlRTaskAttributes    = new TrainTaskAttributesRepository(logger);
            var sqlREquipmentModel    = new EquipmentModelsRepository(logger);
            var sqlREquipment         = new EquipmentRepository(logger);
            var sqlRCarriage          = new CarriageRepository(logger);
            var sqlRTaskStatus        = new TaskStatusRepository(logger);

            var result = new ReportResponse {
                Rows = new List <Row>()
            };

            result.Columns = new List <Column>
            {
                new Column("col0", "Номер", "number"),
                new Column("col1", "Статус", "string"),
                new Column("col2", "Тип", "string"),
                new Column("col3", "Вагон", "string"),
                new Column("col4", "Оборудование", "string"),
                new Column("col5", "Дата", "date"),
            };

            var planedRouteTrain = await sqlRPlanedRouteTrains.ById(planedRouteTrainId);

            //var route = await sqlRRoute.ById(planedRouteTrain.RouteId);

            var trainTasks = await sqlRTask.ByTrainId(planedRouteTrain.TrainId);

            var notClosedTasks = new List <TrainTask>();

            foreach (var trainTask in trainTasks)
            {
                var status = await sqlRTaskStatus.ByTaskId(trainTask.Id);

                if (status.Length == 0)
                {
                    continue;
                }
                if (status.Last().Status != TaskStatus.Closed)
                {
                    notClosedTasks.Add(trainTask);
                }
            }

            foreach (var notClosedTask in notClosedTasks)
            {
                var taskAtributes = await sqlRTaskAttributes.ByTaskId(notClosedTask.Id);

                var lastStatus = await sqlRTaskStatus.ByTaskId(notClosedTask.Id);

                var carriage = await sqlRCarriage.GetById(notClosedTask.CarriageId);

                var equipmentModel = await sqlREquipmentModel.ById(notClosedTask.EquipmentModelId);

                var equpment = await sqlREquipment.ById(equipmentModel.EquipmentId);


                foreach (var taskAtribute in taskAtributes)
                {
                    var row = new Row
                    {
                        Id       = new RowId(notClosedTask.Id, 1),
                        HasItems = false.ToString(),
                        ParentId = null,
                        //Номер
                        Col0 = $"И{notClosedTask.Id}",
                        //Статус
                        Col1 = GetStringTaskStatus(lastStatus.Last().Status),
                        //Тип
                        Col2 = GetStringTaskType(notClosedTask.TaskType),
                        //Вагон
                        Col3 = $"{carriage.Number} - {carriage.Serial}",
                        //Оборудование
                        Col4 = equpment.Name,
                        //Дата
                        Col5 = notClosedTask.CreateDate.ToStringDateTime(),
                    };

                    result.Rows.Add(row);
                }
            }
            return(result);
        }
Beispiel #22
0
        //30 - Приёмка поезда ПР
        //31 - Выпуск поезда ПР
        //32 - Приёмка поезда ЛБ
        //33 - Сдача поезда ЛБ

        public async Task <JournalPaging> GetJournalInspectionAndTasks(int skip, int limit, string filter)
        {
            var sqlr = new InspectionRepository(_logger);

            var inspdatarep  = new InspectionDataRepository(_logger);
            var sqlTrainR    = new TrainRepository(_logger);
            var sqlUserR     = new UserRepository(_logger);
            var iR           = new InspectionRepository(_logger);
            var mR           = new MeterageRepository(_logger);
            var sqlStatusR   = new TaskStatusRepository(_logger);
            var sqlExecutorR = new ExecutorRepository(_logger);
            var sqlRTask     = new TaskRepository(_logger);
            var sqlRBrigade  = new BrigadeRepository(_logger);
            var sqlRJournal  = new JournalRepository(_logger);

            var listFull = new List <JournalDateItem>();

            var fromSqlsInspections = await sqlr.GetAll();

            foreach (var fromSqlsInspection in fromSqlsInspections)
            {
                var train = (await sqlTrainR.ByIdWithStations(fromSqlsInspection.TrainId));
                var user  = await sqlUserR.ById(fromSqlsInspection.UserId);

                var journalInspection = new JournalInspection
                {
                    Id           = fromSqlsInspection.Id,
                    Type         = "inspection",
                    InspectionId = fromSqlsInspection.Id,
                    StatusId     = (int)fromSqlsInspection.Status,
                    TypeId       = (int)fromSqlsInspection.CheckListType,
                    Date         = fromSqlsInspection.DateStart,
                    TrainName    = train.Name,
                    TrainId      = train.Id,
                    Tabs         = new JournalInspectionTabs(),
                    UserName     = user.Name,
                };

                if (user.BrigadeId != null)
                {
                    journalInspection.OwnerBrigadeType = (await sqlRBrigade.ById((int)user.BrigadeId)).BrigadeType;
                }


                //дескрипшен
                var counters = await iR.GetCounters(fromSqlsInspection.Id);

                journalInspection.Tabs.Description = new JournalInspectionDescription
                {
                    TasksCount = counters.Tasks,
                    DataEnd    = fromSqlsInspection.DateEnd,
                    //Выдает количество уникальных меток
                    AllLabelCount = counters.Labels,
                    TempCount     = counters.Measurements
                };


                //лейблы
                await getInspectionLabels(mR, fromSqlsInspection, journalInspection);

                //измерения
                await getInspectionMeterage(mR, fromSqlsInspection, journalInspection);

                //счетчики
                await GetInspectionCouters(inspdatarep, fromSqlsInspection, journalInspection);

                //говнохак под ебанутые фильтры и вывод. TypeId == 2 - Приемка, 3 - сдача
                changeInspetionTypeForUi(journalInspection);


                //Фильтруем
                var isFiltered = await InspectionFilter(filter, sqlRTask, fromSqlsInspection, journalInspection);

                if (!isFiltered)
                {
                    listFull.Add(new JournalDateItem
                    {
                        Date       = journalInspection.Date,
                        Inspection = journalInspection
                    }
                                 );
                }
            }


            //Таски

            var fromSqlsT = await sqlRJournal.GetAllTaskForJournal();

            foreach (var fromSql in fromSqlsT)
            {
                var journalTask = new JournalTask
                {
                    Type                  = "Task",
                    TaskId                = fromSql.TaskId,
                    TaskType              = fromSql.TaskType,
                    TrainName             = fromSql.TrainName,
                    TrainId               = fromSql.TrainId,
                    UserName              = fromSql.UserName,
                    Date                  = fromSql.CreateDate,
                    CarriageName          = CreateCarriageName(fromSql.TrainName, fromSql.CarriageNumber),
                    CarriageNum           = fromSql.CarriageNumber,
                    CarriageId            = fromSql.CarriageId,
                    EquipmentName         = fromSql.EquipmentName,
                    FaultName             = fromSql.FaultName,
                    InspectionInfo        = _GetInspectionInfo(fromSql.InspectionId, fromSql.InspectionType),
                    CarriagesSerialNumber = fromSql.CarriagesSerialNumber,
                    TaskAttributeId       = fromSql.TaskAttributeId
                };

                var executor = (await sqlExecutorR.GetByTaskId(fromSql.TaskId)).LastOrDefault();
                if (executor != null)
                {
                    journalTask.ExecutorBrigadeType = (int)executor.BrigadeType;
                }


                var taskStatus = sqlStatusR.GetByTrainTaskId(fromSql.TaskId);
                if (taskStatus != null)
                {
                    journalTask.StatusId = (int)sqlStatusR.GetByTrainTaskId(fromSql.TaskId).Status;
                }
                //journalTask.StatusId = fromSql.TaskId;

                var isFiltered = TaskFilter(filter, fromSql, journalTask);
                if (!isFiltered)
                {
                    //response.Add(journalTask.ToJson());
                    listFull.Add(new JournalDateItem
                    {
                        Date = journalTask.Date,
                        Task = journalTask
                    }
                                 );
                }
            }



            //sort by date
            listFull.Sort((x, y) => y.Date.CompareTo(x.Date));

            //пагинация
            List <JournalDateItem> listSkiplimit = paging(skip, ref limit, listFull);

            //Делаем жсон стрингу для вывода
            var pagingList = new List <string>();

            converToJsonString(listSkiplimit, pagingList);

            var result = new JournalPaging
            {
                Data  = pagingList.ToArray(),
                Total = listFull.Count
            };

            return(result);
        }
Beispiel #23
0
        private static async Task <FilteredTaskInspection> FilterPaginate(ReportRequest input, ILogger logger, bool isFillTask = true, bool isFillInspection = true)
        {
            var sqlRInspections       = new InspectionRepository(logger);
            var sqlRTask              = new TaskRepository(logger);
            var sqlRTaskStatus        = new TaskStatusRepository(logger);
            var sharedTaskInspections = new List <SharedTaskInspection>();

            if (!int.TryParse(input.Paging.Skip, out var skip))
            {
                throw new ValidationException(Error.ParserErrorInt);
            }

            if (!int.TryParse(input.Paging.Limit, out var limit))
            {
                throw new ValidationException(Error.ParserErrorInt);
            }



            List <Inspection> inspections;

            if (isFillInspection)
            {
                inspections = await sqlRInspections.GetAllSortByProperty("DateStart", "DESC");

                foreach (var inspection in inspections)
                {
                    sharedTaskInspections.Add(new SharedTaskInspection {
                        Inspection = inspection
                    });
                }
            }

            List <TrainTask> tasks;

            if (isFillTask)
            {
                tasks = await sqlRTask.GetAllSortByProperty("CreateDate", "DESC");

                foreach (var item in tasks)
                {
                    sharedTaskInspections.Add(new SharedTaskInspection {
                        TrainTask = item
                    });
                }
            }

            var sharedTaskInspectionFiltered = new List <SharedTaskInspection>();

            if (input.Filters.Any())
            {
                foreach (var filter in input.Filters)
                {
                    foreach (var sharedTaskInspection in sharedTaskInspections)
                    {
                        switch (filter.ColumnName)
                        {
                        //Статус
                        case "col1":
                            string filterField = null;
                            if (sharedTaskInspection.Inspection != null)
                            {
                                filterField = GetStringInspectionStatus(sharedTaskInspection.Inspection.Status);
                            }
                            if (sharedTaskInspection.TrainTask != null)
                            {
                                var currentTaskStatus = (await sqlRTaskStatus.ByTaskId(sharedTaskInspection.TrainTask.Id)).Last();
                                filterField = GetStringTaskStatus(currentTaskStatus.Status);
                            }

                            if (StringFilter(filterField, filter))
                            {
                                sharedTaskInspectionFiltered.Add(sharedTaskInspection);
                            }
                            break;

                        default:
                            throw new NotImplementedException(Error.InDevelopment);
                        }
                    }
                }

                sharedTaskInspections = sharedTaskInspectionFiltered;
            }

            if (skip > sharedTaskInspections.Count)
            {
                sharedTaskInspections = new List <SharedTaskInspection>();
            }
            if (skip == sharedTaskInspections.Count)
            {
                limit = 1;
            }
            if (skip + limit > sharedTaskInspections.Count)
            {
                limit = sharedTaskInspections.Count - skip;
            }
            var total = sharedTaskInspections.Count;

            sharedTaskInspections = sharedTaskInspections.GetRange(skip, limit);

            inspections = sharedTaskInspections.Where(x => x.Inspection != null).Select(q => q.Inspection).ToList();
            tasks       = sharedTaskInspections.Where(x => x.TrainTask != null).Select(q => q.TrainTask).ToList();


            return(new FilteredTaskInspection {
                Inspections = inspections, TrainTask = tasks, Total = total
            });
        }
Beispiel #24
0
        /// <summary>
        ///  То1 таблица
        /// </summary>
        private static async Task <ReportResponse> GetTo1Table(int planedRouteTrainId, ILogger logger)
        {
            var sqlRTrains            = new TrainRepository(logger);
            var sqlRPlanedRouteTrains = new PlanedRouteTrainsRepository(logger);
            var sqlRRoute             = new RoutesRepository(logger);
            var sqlRInspections       = new InspectionRepository(logger);
            var sqlRTaskAttributes    = new TrainTaskAttributesRepository(logger);
            var sqlRUser = new UserRepository(logger);

            var result = new ReportResponse {
                Rows = new List <Row>()
            };

            result.Columns = new List <Column>
            {
                new Column("col0", "Номер", "number"),
                new Column("col1", "Состав", "string"),
                new Column("col2", "Рейс", "string"),
                new Column("col3", "Время начала", "date"),
                new Column("col4", "Время окончания", "date"),
                new Column("col5", "Количество созданных инцидентов", "number"),
                new Column("col6", "Исполнитель", "string"),
                new Column("col7", "Меток считано всего (в том числе при обходе и закрытии задач)", "number"),
            };

            var planedRouteTrain = await sqlRPlanedRouteTrains.ById(planedRouteTrainId);

            var route = await sqlRRoute.ById(planedRouteTrain.RouteId);

            //Надо получить ТО 1 на этот день или блядь для этого поезда. хуй его знает
            var currentTrainInspections = await sqlRInspections.GetByTrainId(planedRouteTrain.TrainId);

            //Выбираем за текущий денек
            var currentDayInspections =
                currentTrainInspections.Where(x => x.DateStart.Date.Equals(planedRouteTrain.CreateDate) && x.CheckListType == CheckListType.TO1);

            foreach (var currentDayInspection in currentDayInspections)
            {
                var row = new Row
                {
                    Id       = new RowId(currentDayInspection.Id, 1),
                    HasItems = false.ToString(),
                    ParentId = null,
                    //Номер
                    Col0 = currentDayInspection.Id.ToString(),
                    //Состав
                    Col1 = (await sqlRTrains.ById(planedRouteTrain.TrainId)).Name,
                    //Рейс
                    Col2 = route.Name,
                    //Время начала
                    Col3 = currentDayInspection.DateStart.ToStringDateTime(),
                    //Время окончания
                    Col4 = currentDayInspection.DateEnd?.ToStringDateTime(),
                    //Количество созданных инцидентов
                    Col5 = (await sqlRTaskAttributes.ByInspectionId(currentDayInspection.Id))?.Count.ToString(),
                    //Исполнитель
                    Col6 = (await sqlRUser.ById(currentDayInspection.UserId))?.Name,
                    //Меток считано всего (в том числе при обходе и закрытии задач)
                    Col7 = "In Development",
                };

                result.Rows.Add(row);
            }

            return(result);
        }
Beispiel #25
0
 public InspectionController()
 {
     inspectionRepository = new InspectionRepository();
 }
        //[Authorize]
        //[Route("api/[controller]/[action]")]
        private async Task <string> GetInspectionHtmlForPdf(int id)
        {
            //await CheckPermission();
            var ir  = new InspectionRepository(_logger);
            var tr  = new TaskRepository(_logger);
            var ur  = new UserRepository(_logger);
            var trr = new TrainRepository(_logger);

            var inspection = await ir.ById(id);

            if (inspection == null)
            {
                return("");
            }
            //throw new Exception("инспекция не найдена");

            inspection.User = await ur.ById(inspection.UserId);

            inspection.Train = await trr.ByIdWithStations(inspection.TrainId);

            var res = await tr.GetInspectionTasksForPdf(id);

            var tasks = res.FirstOrDefault();

            string checkListTypeRussian = null;

            if (inspection.CheckListType == CheckListType.TO1)
            {
                checkListTypeRussian = InspectionRussianName.To1;
            }
            if (inspection.CheckListType == CheckListType.TO2)
            {
                checkListTypeRussian = InspectionRussianName.To2;
            }
            if (inspection.CheckListType == CheckListType.Inspection)
            {
                checkListTypeRussian = InspectionRussianName.PriemkaPoezda;
            }
            if (inspection.CheckListType == CheckListType.Surrender)
            {
                checkListTypeRussian = InspectionRussianName.SdachaPoezda;
            }

            var html = "";/*"@"<html><head>
                           * <style type='text/css'>
                           * .task {
                           * border-collapse: collapse;
                           * border: 1px solid black;
                           * }
                           * .task td {
                           * padding: 5px;
                           * border: 1px solid black;
                           * }
                           * .task th {
                           * padding: 5px;
                           * background-color: #909090;
                           * border: 1px solid black;
                           * }
                           * </style></head><body>";*/

            html += "<table><tr><td>Мероприятие:</td><td>" + checkListTypeRussian + "</td></tr>";
            html += "<tr><td>Поезд:</td><td>" + inspection.Train.Name + "</td></tr>";
            html += "<tr><td>Начато:</td><td>" + inspection.DateStart + "</td></tr>";
            html += "<tr><td>Закончено:</td><td>" + inspection.DateEnd + "</td></tr>";
            html += "<tr><td>Выполнил:</td><td>" + inspection.User.Name + "</td></tr></table>";
            if (tasks != null && tasks.Tasks.Length > 0)
            {
                html +=
                    "<br /><h2>Задачи</h2><table class='task'><tr><th>Вагон</th><th>Местоположение</th><th>Оборудование</th><th>Типовая неисправность</th><th>Описание</th><th>Метка</th><th>№ задачи</th><th>Время</th></tr>";
                foreach (var task in tasks.Tasks)
                {
                    html += "<tr><td>" + task.CarriageSerialNum + "</td><td>" + task.Location + "</td><td>" + task.Equipment + "</td><td>" + task.Fault + "</td><td>" + task.Description + "</td><td>" + task.Label + "</td><td>" + task.Id + "</td><td>" + task.Created + "</td></tr>";
                }
                html += "</table><br /><br />";

                if (tasks.Labels.Any())
                {
                    html += "<h2>Метки</h2><table class='task'><tr><th>Вагон</th><th>Оборудование</th><th>Время</th><th>ИД метки</th></tr>";
                    foreach (var label in tasks.Labels)
                    {
                        html += "<tr><td>" + label.CarriageName + "</td><td>" + label.EquipmentName + "</td><td>" + label.TimeStamp + "</td><td>" + label.LabelSerial + "</td></tr>";
                    }
                    html += "</table><br /><br />";
                }

                if (tasks.Temperatures.Any())
                {
                    html += "<h2>Температура</h2><table class='task'><tr><th>Температура</th><th>Время</th><th>Температура</th><th>Время</th><th>Температура</th><th>Время</th><th>Температура</th><th>Время</th></tr>";
                    var cnt = 0;
                    foreach (var temp in tasks.Temperatures)
                    {
                        if (cnt % 4 == 0)
                        {
                            html += "<tr>";
                        }
                        html += "<td>" + temp.Value + "</td><td>" + temp.TimeStamp + "</td>";
                        if ((cnt + 1) % 4 == 0)
                        {
                            html += "</tr>";
                        }
                        cnt++;
                    }
                    var remain = 4 - (cnt % 4);
                    if (remain > 0)
                    {
                        for (var i = 0; i < remain; i++)
                        {
                            html += "<td></td><td></td>";
                        }
                        html += "</tr>";
                    }
                    html += "</table><br /><br />";
                }
            }
            else
            {
                html += "<h2>Не найдено задач</h2>";
            }

            //html += "</body></html>";
            //
            //var output = _pdfConverter.Convert(new HtmlToPdfDocument
            //{
            //    GlobalSettings = {
            //        ColorMode = ColorMode.Color,
            //        Orientation = Orientation.Portrait,
            //        PaperSize = PaperKind.A4,
            //    },
            //    Objects =
            //    {
            //        new ObjectSettings
            //        {
            //            HtmlContent = html,
            //            WebSettings = { DefaultEncoding = "utf-8" }
            //        }
            //    }
            //});
            ////
            //return File(output, "application/pdf", inspection.Id+"_"+inspection.DateStart+"_"+inspection.CheckListType+".pdf");
            return(html);
        }
        private async Task AddInspectionData(TaskByIdDto result, TaskDetailFromSql item)
        {
            var sqlRInspection = new InspectionRepository(_logger);
            var sqlRUsers      = new UserRepository(_logger);
            var sqlRBrigade    = new BrigadeRepository(_logger);

            var inspection = await sqlRInspection.ById(item.AttributeInspectionId);

            var inspectionUser = await sqlRUsers.ById(inspection.UserId);

            int?inspectionBrigadeType = null;

            if (inspectionUser.BrigadeId.HasValue)
            {
                var inspectionBrigade = await sqlRBrigade.ById(inspectionUser.BrigadeId.Value);

                inspectionBrigadeType = (int)inspectionBrigade.BrigadeType;
            }

            var inspectionToAdd = new InspectionTaskDto
            {
                Id          = inspection.Id,
                DateStart   = inspection.DateStart,
                DateEnd     = inspection.DateEnd,
                User        = inspectionUser.Name,
                Type        = (int)inspection.CheckListType,
                BrigadeType = inspectionBrigadeType,
                Texts       = new List <string>()
            };

            if (item.AttributeCheckListEquipmentId.HasValue)
            {
                var toAddText                = $"{item.EquipmentName} -> {item.CheckListEquipmentTaskName} -> ";
                var checkListStringValue     = string.Empty;
                var taskAttributeStringValue = string.Empty;
                if (item.CheckListEquipmentValueType == 1)
                {
                    if (item.CheckListEquipmentValue == 0)
                    {
                        checkListStringValue = "Нет";
                    }
                    if (item.CheckListEquipmentValue == 1)
                    {
                        checkListStringValue = "Да";
                    }

                    if (item.AttributeValue == 0)
                    {
                        taskAttributeStringValue = "Нет";
                    }
                    if (item.AttributeValue == 1)
                    {
                        taskAttributeStringValue = "да";
                    }
                }
                else
                {
                    checkListStringValue     = item.CheckListEquipmentValue.ToString();
                    taskAttributeStringValue = item.AttributeValue.ToString();
                }

                toAddText += $"{checkListStringValue} -> {taskAttributeStringValue}";

                inspectionToAdd.Texts.Add(toAddText);
            }


            // Для ТО-1 ТО-2 и тд
            if (inspection.CheckListType == CheckListType.TO1 || inspection.CheckListType == CheckListType.TO2)
            {
                //  Уровень критичности → Высокий
                if (item.TaskLevel.HasValue)
                {
                    var toAddText = $"Уровень критичности -> {GetStringTaskLevel(item.TaskLevel.Value)}";
                    inspectionToAdd.Texts.Add(toAddText);
                }

                //Смотрим что добавилось в рамках мероприятия TaskLevel или FaultId, пишим в текст
                if (item.AttributeFaultId.HasValue)
                {
                    var toAddText = $"{item.FaultName} -> {item.EquipmentName}";
                    inspectionToAdd.Texts.Add(toAddText);
                }
            }

            result.Inspections.Add(inspectionToAdd);
        }
Beispiel #28
0
        /// <summary>
        /// Save job into database
        /// </summary>
        /// <returns></returns>
        public int SaveJob()
        {
            var book = _bookStateHolder.Load();
            //if(book.AppointmentDate!="")

            var cust       = new CustomerService(_dataContext);
            var prod       = new ProductService(_dataContext);
            var user       = new UserService(_dataContext);
            var store      = new StoreService(_dataContext);
            var job        = new BookRepair_JobModel();
            var quest      = new QuestionService(_dataContext);
            var jobService = new JobService(_dataContext);

            var prodInfo    = prod.GetGeneralInfoFromSession();
            var repairAgent = GetAgentRepairInfo();

            job.DateOfPurchase  = book.DateOfPurchase;
            job.SerialNumber    = prodInfo.SerialNumber;
            job.ItemCondition   = prodInfo.OriginalCondition;
            job.DateOfPurchase  = prodInfo.DateOfPurchase;
            job.StoreNumber     = book.StoreNumber;
            job.TillNumber      = book.TillNumber;
            job.TransNumber     = prodInfo.TransactionInfo;
            job.SelectedType    = book.Type;
            job.FaultDescr      = book.FaultDescr + " \n" + quest.GetAnswersFromSession();
            job.UserID          = user.GetUserId();
            job.EngineerId      = book.EngineerId;
            job.AppointmentDate = book.AppointmentDate;
            job.StoreCollection = book.StoreCollection;
            SetAcceptJobFlag(false);
            int custId   = cust.GetCustomerIdFromSession();
            var customer = cust.GetCustomerInfo();
            int Jobid    = _reporsitory.UpdateJob(job, custId, prod.GetModelId(), (DateTime)prod.GetTimeBookRepairClick(), book.ServiceId, store.GetStoreId());

            if (!string.IsNullOrEmpty(repairAgent.BookingUrl))
            {
                OnlineBookingService     onlineBookingService = new OnlineBookingService();
                OnlineBookRequestDetails model = new OnlineBookRequestDetails();
                // model.InjectFrom(ProductService.SessionInfo);
                model.ServiceID            = Jobid;
                model.CustomerTitle        = customer.TitleName;
                model.CustomerForename     = customer.Forename;
                model.CustomerSurname      = customer.Surname;
                model.CustomerStreet       = customer.Addr1;
                model.CustomerPostcode     = customer.Postcode;
                model.CustomerAddressTown  = customer.Town;
                model.CustomerWorkTelNo    = customer.LandlineTel;
                model.CustomerMobileNo     = customer.MobileTel;
                model.CustomerEmailAddress = customer.Email;
                model.SupplyDat            = prodInfo.DateOfPurchase.ToString("yyyy-MM-dd");
                //model.CustAplID = prodInfo.CustaplId;
                model.ApplianceCD = "";
                //model.Model = prodInfo.ItemNumber;
                //model.AltCode = prodInfo.ItemCode;
                // cast online booking - skyline  Argos Cat No (MODEL) should go into Skyline ProductCode field
//Argos Brand Model (ALTCODE)  should go into Skyline ModelNo field

                model.Model   = prodInfo.ItemCode;
                model.AltCode = prodInfo.ItemNumber;
                model.SNO     = job.SerialNumber;
                model.MFR     = prodInfo.ModelBrand;

                //model.PolicyNumber =prodInfo.p
                model.ReportFault = job.FaultDescr;
                model.ClientID    = store.GetStoreId();
                model.StatusID    = 4;

                //  model.VisitDate = DateTime.Parse(job.AppointmentDate);
                //  model.EngineerID = job.EngineerId.Value;
                model.SlotID = book.Slotid;
                //   model.CallType = job.StoreCollection ? "1 Store Collection" : "2 In Home Repair";//repairAgent.InHomeAvailable?"1 Store Collection":( job.StoreCollection ? "1 Store Collection" : "2 In Home Repair");
                model.CallType = !repairAgent.InHomeAvailable ? "1 Store Collection":(job.StoreCollection ? "1 Store Collection" : "2 In Home Repair");
                var response = onlineBookingService.BookJob(model);
                Log.File.ErrorFormat("Error {0}: {1}. ", response.ErrorMsg, response.BookSuccessfully);



                if (response.BookSuccessfully)
                {
                    _reporsitory.UpdateJobClientRef(Jobid, response.ServiceID);

                    HttpContext.Current.Session["ClientRef"] = response.ServiceID;
                }
                else
                {
                    book.OnlineBookingFailed = true;
                }
            }
            if (book.FieldsForInspection != null && book.FieldsForInspection.Count > 0)
            {
                InspectionRepository ins = new InspectionRepository(_dataContext);
                book.FieldsForInspection.ForEach(s => s.ServiceId = Jobid);
                ins.SaveSpecificInspection(book.FieldsForInspection);
            }
            return(Jobid);
        }
        public async Task <IActionResult> GetJournalTablePdf([FromBody] JournalTableRequest req)
        {
            await CheckPermission();

            var html = @"<html><head>
                <style type='text/css'>
                .task {
                    width: 100%;
                    border-collapse: collapse;
                    border: 1px solid black;
                }
                .task td {
                    padding: 5px;
                    border: 1px solid black;
                }
                .task th {
                    padding: 5px;
                    background-color: #909090;
                    border: 1px solid black;
                }
                </style></head><body>";

            var tr          = new TaskRepository(_logger);
            var ir          = new InspectionRepository(_logger);
            var serviceTask = new TaskService(_logger);

            html += "<br /><h2>Задачи</h2>";

            var filter = new JournalGridFilter();

            filter.Init(req.Options.Filter);

            var grid       = new ActionGrid <JournalGrid, JournalGridModel, JournalFilter>(_db.Connection, req.Options, filter);
            var gridResult = await grid.GetResultRows();

            if (gridResult.Count() == 0)
            {
                html += "<br /><h4>Список задач отсутствует</h4>";
            }
            else
            {
                html += "<table class='task'><tr><th>№ задачи</th><th>Вагон</th><th>Местоположение</th><th>Оборудование</th><th>Типовая неисправность</th><th>Описание</th><th>Метка</th><th>Время</th><th>Автор</th><th>Комментарий</th></tr>";

                foreach (var task in gridResult)
                {
                    var history = await serviceTask.AddHistoryData(task.Id);

                    var trainTask = await tr.GetTrainTaskForPdf(task.Id);

                    if (trainTask != null)
                    {
                        string comments     = null;
                        var    taskComments = history.OrderBy(h => h.Date).Where(h => h.Type == "Comment" && h.Text != null && h.Text != trainTask.Description);

                        foreach (var comment in taskComments)
                        {
                            comments += $"<i>{comment.Date.ToString("MM.dd.yy")}</i>: {comment.Text}<br />";
                        }

                        html += "<tr><td>" + trainTask.Id + "</td><td>" + trainTask.CarriageSerial + "</td><td>" + trainTask.Location +
                                "</td><td>" + trainTask.Equipment + "</td><td>" + trainTask.Fault + "</td><td>" + trainTask.Description +
                                "</td><td>" + trainTask.Label + "</td><td>" + trainTask.Created +
                                "</td><td>" + trainTask.UserName + "</td></td><td>" + comments + "</td></tr>";
                    }
                }

                html += "</table>";
            }

            var output = _pdfConverter.Convert(new HtmlToPdfDocument
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Landscape,
                    PaperSize   = PaperKind.A4,
                },
                Objects =
                {
                    new ObjectSettings
                    {
                        PagesCount     = true,
                        HtmlContent    = html,
                        WebSettings    = { DefaultEncoding = "utf-8" },
                        FooterSettings ={ FontName                             = "Arial", FontSize = 9, Right = "[page]", Line = false},
                    }
                }
            });

            return(File(output, "application/pdf", "journal_" + new Random().Next(0, 10000) + ".pdf"));
        }
Beispiel #30
0
 public InspectionService(InspectionRepository inspectionRepository)
 {
     _inspectionRepository = inspectionRepository;
 }