public void DeleteCaseById(Guid caseId)
        {
            CaseDto caseDto = new CaseDto();

            try
            {
                Case caseToDelete = new Case();
                var  caseList     = this.CaseRepository.Find(c => c.Id == caseId);
                if (caseList.Count != 0)
                {
                    caseToDelete = caseList.First();
                }
                else
                {
                    return;
                }

                this.ClientBusinessLogic.DeleteClientByCaseId(caseId);
                this.CaseInformationBusinessLogic.DeleteCaseInformationByCaseId(caseId);
                this.CaseStatusBusinessLogic.DeleteCaseStatusByCaseId(caseId);
                this.NotesBusinessLogic.DeleteNotesByCaseId(caseId);
                this.CaseReferenceBusinessLogic.DeleteCaseReferenceByCaseId(caseId);
                this.CaseRepository.Delete(caseToDelete);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Beispiel #2
0
        public OperationResponse <CaseDto> Get(GetCaseById request)
        {
            OperationResponse <CaseDto> operationResponse = new OperationResponse <CaseDto>();

            try
            {
                CaseDto caseDto = CaseBusinessLogic.GetCaseById(request.CaseId);
                if (caseDto != null)
                {
                    operationResponse.OnSuccess(caseDto, "Fetched successfully");
                    return(operationResponse);
                }
                else
                {
                    operationResponse.OnError("No case found!!!", null);
                    return(operationResponse);
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                operationResponse.OnException(e.Message);
                return(operationResponse);
            }
        }
        public CaseDto EditCase(Guid caseId, ClientDto clientDto, CaseInformationDto caseInformationDto, NotesDto notesDto, CaseStatusDto caseStatusDto, List <CaseReferenceDto> caseReferenceDtos)
        {
            CaseDto caseDto = new CaseDto();

            try
            {
                var caseList = this.CaseRepository.Find(c => c.Id == caseId);
                if (caseList.Count == 0)
                {
                    return(null);
                }

                Case @case = caseList.First();
                @case              = this.CaseRepository.Update(@case);
                caseDto.Id         = @case.Id;
                caseDto.CaseId     = @case.CaseId;
                caseDto.ModifiedOn = @case.ModifiedOn;
                caseDto.CreatedOn  = @case.CreatedOn;

                caseDto.Client          = this.ClientBusinessLogic.EditClient(clientDto);
                caseDto.CaseInformation = this.CaseInformationBusinessLogic.EditCaseInformation(caseInformationDto);
                caseDto.CaseStatus      = this.CaseStatusBusinessLogic.EditCaseStatus(caseStatusDto);
                caseDto.Notes           = this.NotesBusinessLogic.EditNotes(notesDto);
                caseDto.References      = this.CaseReferenceBusinessLogic.EditCaseReferences(caseReferenceDtos, caseId);
                return(caseDto);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Beispiel #4
0
        public IActionResult GetCase(int caseId)
        {
            if (!_caseRepository.CaseExists(caseId))
            {
                return(NotFound());
            }

            var data = _caseRepository.GetCase(caseId);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var caseDto = new CaseDto()
            {
                Id          = data.Id,
                FirstName   = data.FirstName,
                LastName    = data.LastName,
                Type        = data.Type,
                Description = data.Description
            };

            return(Ok(caseDto));
        }
        public CaseDto GetCaseById(Guid caseId)
        {
            CaseDto caseDto = new CaseDto();

            try
            {
                var caseList = this.CaseRepository.Find(c => c.Id == caseId);
                if (caseList.Count == 0)
                {
                    return(null);
                }
                caseDto.CaseId          = caseList.First().CaseId;
                caseDto.Id              = caseList.First().Id;
                caseDto.ModifiedOn      = caseList.First().ModifiedOn;
                caseDto.CreatedOn       = caseList.First().CreatedOn;
                caseDto.Client          = ClientBusinessLogic.GetClientByCaseId(caseId);
                caseDto.CaseInformation = CaseInformationBusinessLogic.GetCaseInformationByCaseId(caseId);
                caseDto.CaseStatus      = CaseStatusBusinessLogic.GetCaseStatusByCaseId(caseId);
                caseDto.Notes           = NotesBusinessLogic.GetNotesByCaseId(caseId);
                caseDto.References      = CaseReferenceBusinessLogic.GetCaseReferencesByCaseId(caseId);
                return(caseDto);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Получение карточки по Id инцидента
        /// </summary>
        public async Task <Result <CaseDto> > GetCaseByCaseFolderIdAsync(Guid caseFolderId, Guid userId)
        {
            using (_unitOfWork.Begin())
            {
                var caseFolder = await _caseFolderRepository.GetById(caseFolderId);

                if (caseFolder == null)
                {
                    _logger.Warning($"CaseFolder with Id {caseFolderId} not found");
                    return(Result.Failure <CaseDto>(ErrorCodes.CaseFolderNotFound));
                }

                Result <UserClientDto> result = await _userManagementServiceClient.GetUserById(userId);

                if (result.IsFailure)
                {
                    _logger.Warning($"User with Id {userId} not found");
                    return(Result.Failure <CaseDto>(ErrorCodes.UserNotFound));
                }

                var user = _mapper.Map <UserDto>(result.Value);

                Result <Case> userCaseCard = caseFolder.GetCaseForUser(user.Id);
                if (userCaseCard.IsFailure)
                {
                    _logger.Warning(userCaseCard.ErrorMessage);
                    return(Result.Failure <CaseDto>(userCaseCard.ErrorCode));
                }

                await NotifyGisFacadeAboutNewApplicantLocation(caseFolder, userId);

                return(Result.Success(CaseDto.MapFromCaseEntity(userCaseCard.Value)));
            }
        }
Beispiel #7
0
        public IActionResult GetCase(int caseId)
        {
            if (!_caseRepository.CaseExists(caseId))
            {
                return(NotFound());
            }
            var Case = _caseRepository.GetCase(caseId);

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var CaseDto = new CaseDto()
            {
                id                  = Case.id,
                FirstName           = Case.FirstName,
                LastName            = Case.LastName,
                DateOfBirth         = Case.DateOfBirth,
                WithChronicDiseases = Case.WithChronicDiseases,
                Status              = Case.Status,
                DateOfConfirmation  = Case.DateOfConfirmation
            };

            return(Ok(CaseDto));
        }
        public async Task <OperationResult> Delete(int id)
        {
            Core _core = await _coreHelper.GetCore();

            ContractInspection dbContractInspection =
                await _dbContext.ContractInspection.SingleOrDefaultAsync(x => x.Id == id);

            try
            {
                if (dbContractInspection != null)
                {
                    await dbContractInspection.Delete(_dbContext);

                    ContractInspectionItem contractInspectionItem =
                        await _dbContext.ContractInspectionItem.SingleOrDefaultAsync(x =>
                                                                                     x.ContractInspectionId == dbContractInspection.Id);

                    CaseDto caseDto = await _core.CaseLookupMUId(contractInspectionItem.SDKCaseId);

                    if (caseDto.MicrotingUId != null)
                    {
                        await _core.CaseDelete((int)caseDto.MicrotingUId);
                    }
                }
                return(new OperationResult(true));
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                _logger.LogError(e.Message);
                return(new OperationResult(false, _rentableItemsLocalizationService.GetString("ErrorWhileDeletingContractInspection")));
            }
        }
        public List <CaseDto> GetAllCases(int index, string orderBy)
        {
            List <CaseDto> caseDtos = new List <CaseDto>();

            try
            {
                int         maxRows = 3;
                List <Case> cases   = CaseRepository.GetAllFilteredCases(index, orderBy);
                if (cases.Count == 0)
                {
                    return(null);
                }
                foreach (var @case in cases)
                {
                    CaseDto caseDto = new CaseDto();
                    caseDto.CaseId          = @case.CaseId;
                    caseDto.Id              = @case.Id;
                    caseDto.ModifiedOn      = @case.ModifiedOn;
                    caseDto.CreatedOn       = @case.CreatedOn;
                    caseDto.Client          = ClientBusinessLogic.GetClientByCaseId(@case.Id);
                    caseDto.CaseInformation = CaseInformationBusinessLogic.GetCaseInformationByCaseId(@case.Id);
                    caseDto.CaseStatus      = CaseStatusBusinessLogic.GetCaseStatusByCaseId(@case.Id);
                    caseDto.Notes           = NotesBusinessLogic.GetNotesByCaseId(@case.Id);
                    caseDto.References      = CaseReferenceBusinessLogic.GetCaseReferencesByCaseId(@case.Id);
                    caseDtos.Add(caseDto);
                }

                return(caseDtos);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Beispiel #10
0
        public async Task Handle(eFormCompleted message)
        {
            #region get case information

            WriteLogEntry($"eFormCompletedHandler.Handle: we got called for message.caseId {message.caseId} and message.checkId {message.checkId}");
            CaseDto caseDto = await _sdkCore.CaseLookup(message.caseId, message.checkId).ConfigureAwait(false);

            ReplyElement replyElement = await _sdkCore.CaseRead(message.caseId, message.checkId).ConfigureAwait(false);

            OuterInnerResourceSite machineAreaSite =
                _dbContext.OuterInnerResourceSites.SingleOrDefault(x =>
                                                                   x.MicrotingSdkCaseId == message.caseId);

            ResourceTimeRegistration machineAreaTimeRegistration =
                await _dbContext.ResourceTimeRegistrations.SingleOrDefaultAsync(x =>
                                                                                x.DoneAt == replyElement.DoneAt &&
                                                                                x.SDKCaseId == (int)caseDto.CaseId &&
                                                                                x.SDKSiteId == machineAreaSite.MicrotingSdkSiteId).ConfigureAwait(false);

            if (machineAreaTimeRegistration == null)
            {
                machineAreaTimeRegistration = new ResourceTimeRegistration();
                if (machineAreaSite != null)
                {
                    machineAreaTimeRegistration.OuterResourceId = machineAreaSite.OuterInnerResource.OuterResourceId;
                    machineAreaTimeRegistration.InnerResourceId = machineAreaSite.OuterInnerResource.InnerResourceId;
                    machineAreaTimeRegistration.DoneAt          = replyElement.DoneAt;
                    if (caseDto.CaseId != null)
                    {
                        machineAreaTimeRegistration.SDKCaseId = (int)caseDto.CaseId;
                    }
                    machineAreaTimeRegistration.SDKSiteId = machineAreaSite.MicrotingSdkSiteId;
                }

                CheckListValue dataElement = (CheckListValue)replyElement.ElementList[0];
                foreach (var field in dataElement.DataItemList)
                {
                    Field f = (Field)field;
                    if (f.Label.ToLower().Contains("start/stop tid"))
                    {
                        Console.WriteLine($"The field is {f.Label}");
                        FieldValue fv         = f.FieldValues[0];
                        String     fieldValue = fv.Value;
                        Console.WriteLine($"Current field_value is {fieldValue}");
                        int registeredTime = int.Parse(fieldValue.Split("|")[3]);
                        Console.WriteLine($"We are setting the registered time to {registeredTime.ToString()}");

                        machineAreaTimeRegistration.SDKFieldValueId = fv.Id;
                        machineAreaTimeRegistration.TimeInSeconds   = (registeredTime / 1000);
                        machineAreaTimeRegistration.TimeInMinutes   = ((registeredTime / 1000) / 60);
                        machineAreaTimeRegistration.TimeInHours     = ((registeredTime / 1000) / 3600);
                    }
                }
                #endregion

                await machineAreaTimeRegistration.Create(_dbContext).ConfigureAwait(false);
            }
        }
Beispiel #11
0
        public void CaseCompleted(object sender, EventArgs args)
        {
            CaseDto trigger = (CaseDto)sender;

            if (trigger.MicrotingUId != null)
            {
                _bus.SendLocal(new eFormCompleted(trigger.CaseId, trigger.MicrotingUId, trigger.CheckUId));
            }
        }
Beispiel #12
0
        public void CaseCompleted(object sender, EventArgs args)
        {
            CaseDto trigger = (CaseDto)sender;

            if (trigger.CheckUId != null && trigger.MicrotingUId != null)
            {
                _bus.SendLocal(new EformCompleted(trigger.CheckListId, trigger.CheckUId.Value, trigger.MicrotingUId.Value));
            }
        }
Beispiel #13
0
        public void CaseCompleted(object sender, EventArgs args)
        {
            CaseDto trigger = (CaseDto)sender;

            if (trigger.CaseId != null)
            {
                int caseId = (int)trigger.CaseId;
                _bus.SendLocal(new eFormCompleted(caseId));
            }
        }
Beispiel #14
0
#pragma warning disable 1998
        public async Task Handle(EformParsingError message)
        {
            await sqlController.NotificationCreate(message.NotificationId, message.MicrotringUUID, Constants.Notifications.EformParsingError);

            CaseDto cDto = await sqlController.CaseReadByMUId(message.MicrotringUUID);

            await core.FireHandleCaseProcessingError(cDto);

            // Potentially send new message onto local queue
        }
        public void CaseCompleted(object sender, EventArgs args)
        {
            CaseDto trigger = (CaseDto)sender;

            int?caseId = trigger.MicrotingUId;

            if (caseId != null)
            {
                _bus.SendLocal(new eFormCompleted((int)caseId));
            }
        }
Beispiel #16
0
        public async Task <IActionResult> Update([FromBody] CaseDto caseDto)
        {
            var(validation, result) = await _caseService.UpdateCase(caseDto);

            if (!validation.IsValid)
            {
                return(this.BadRequest(validation.Errors));
            }

            return(this.Ok(result));
        }
        public void eFormProcessingError(object sender, EventArgs args)
        {
            CaseDto trigger = (CaseDto)sender;

            int?caseId = trigger.MicrotingUId;

            if (caseId != null)
            {
                _bus.SendLocal(new EformParsingError((int)caseId));
            }
        }
        public void CaseCompleted(object sender, EventArgs args)
        {
            CaseDto trigger = (CaseDto)sender;

            if (trigger.MicrotingUId != null && trigger.CheckUId != null)
            {
                int caseId      = (int)trigger.MicrotingUId;
                int checkListId = (int)trigger.CheckListId;
                int checkUId    = (int)trigger.CheckUId;
                int siteId      = (int)trigger.SiteUId;
                _bus.SendLocal(new eFormCompleted(caseId, checkListId, checkUId, siteId));
            }
        }
        /// <summary>
        /// Получить карточку по Id
        /// </summary>
        public async Task <Result <CaseDto> > GetCaseById(Guid caseId)
        {
            using (_unitOfWork.Begin())
            {
                var caseCard = await _caseRepository.GetById(caseId);

                if (caseCard == null)
                {
                    _logger.Warning($"Case with Id {caseId} not found");
                    return(Result.Failure <CaseDto>(ErrorCodes.CaseNotFound));
                }

                return(Result.Success(CaseDto.MapFromCaseEntity(caseCard)));
            }
        }
        private async Task RetractFromMicroting(int itemCaseId)
        {
            List <ItemCaseSite> itemCaseSites =
                _dbContext.ItemCaseSites.Where(x => x.ItemCaseId == itemCaseId).ToList();

            foreach (ItemCaseSite caseSite in itemCaseSites)
            {
                CaseDto caseDto = await _sdkCore.CaseReadByCaseId(caseSite.MicrotingSdkCaseId);

                if (caseDto.MicrotingUId != null)
                {
                    await _sdkCore.CaseDelete((int)caseDto.MicrotingUId);
                }
            }
        }
        public async Task Handle(eFormCompleted message)
        {
            var planningCaseSite = await _dbContext.PlanningCaseSites.SingleOrDefaultAsync(x => x.MicrotingSdkCaseId == message.caseId);

            using MicrotingDbContext sdkDbContext = _sdkCore.dbContextHelper.GetDbContext();
            if (planningCaseSite != null)
            {
                planningCaseSite.Status = 100;
                CaseDto caseDto = await _sdkCore.CaseReadByCaseId(message.caseId);

                var microtingUId      = caseDto.MicrotingUId;
                var microtingCheckUId = caseDto.CheckUId;
                if (microtingUId != null && microtingCheckUId != null)
                {
                    ReplyElement theCase = await _sdkCore.CaseRead((int)microtingUId, (int)microtingCheckUId);

                    planningCaseSite = await SetFieldValue(planningCaseSite, theCase.Id);

                    planningCaseSite.MicrotingSdkCaseDoneAt = theCase.DoneAt;
                    planningCaseSite.DoneByUserId           = theCase.DoneById;
                    var worker = await sdkDbContext.workers.SingleAsync(x => x.Id == planningCaseSite.DoneByUserId);

                    planningCaseSite.DoneByUserName = $"{worker.FirstName} {worker.LastName}";
                    await planningCaseSite.Update(_dbContext);

                    var planningCase = await _dbContext.PlanningCases.SingleOrDefaultAsync(x => x.Id == planningCaseSite.PlanningCaseId);

                    if (planningCase.Status != 100)
                    {
                        planningCase.Status = 100;
                        planningCase.MicrotingSdkCaseDoneAt = theCase.DoneAt;
                        planningCase.MicrotingSdkCaseId     = planningCaseSite.MicrotingSdkCaseId;
                        planningCase.DoneByUserId           = theCase.DoneById;
                        planningCase.DoneByUserName         = planningCaseSite.DoneByUserName;
                        planningCase.WorkflowState          = Constants.WorkflowStates.Processed;
                        // planningCase.DoneByUserName = $"{site.Result.FirstName} {site.Result.LastName}";

                        planningCase = await SetFieldValue(planningCase, theCase.Id);

                        await planningCase.Update(_dbContext);
                    }

                    await RetractFromMicroting(planningCase.Id);
                }
            }
        }
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="caseDto">
        /// The case DTO.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task <(ValidationResultDto, bool)> UpdateCase(CaseDto caseDto)
        {
            var validator     = new CaseValidator();
            var validateAsync = await validator.ValidateAsync(caseDto);

            if (!validateAsync.IsValid)
            {
                var validationDto = _mapper.Map <ValidationResultDto>(validateAsync);
                return(validationDto, false);
            }

            var caseDomain = _mapper.Map <Case>(caseDto);

            var result = _caseRepository.Update(caseDomain);

            return(new ValidationResultDto(), result);
        }
Beispiel #23
0
        public async Task <IActionResult> DownloadEFormXml(int templateId)
        {
            if (!await _permissionsService.CheckEform(templateId,
                                                      AuthConsts.EformClaims.EformsClaims.DownloadXml))
            {
                return(Forbid());
            }

            try
            {
                var core = await _coreHelper.GetCore();

                var caseId = await core.CaseReadFirstId(templateId, "not_revmoed");

                CaseDto caseDto = await core.CaseLookupCaseId((int)caseId);

                var language = await _userService.GetCurrentUserLanguage();

                ReplyElement replyElement = await core.CaseRead((int)caseDto.MicrotingUId, (int)caseDto.CheckUId, language).ConfigureAwait(false);

                if (caseId != null)
                {
                    var filePath = await core.CaseToJasperXml(caseDto, replyElement, (int)caseId,
                                                              DateTime.Now.ToString("yyyyMMddHHmmssffff"),
                                                              $"{core.GetSdkSetting(Settings.httpServerAddress)}/" + "api/template-files/get-image/",
                                                              "", language);

                    if (!System.IO.File.Exists(filePath))
                    {
                        return(NotFound());
                    }

                    var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    return(File(fileStream, "application/xml", Path.GetFileName(filePath)));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #24
0
        public async Task RetractFromMicroting(int contractId)
        {
            List <ContractInspection> contractInspections =
                _dbContext.ContractInspection.Where(x => x.ContractId == contractId).ToList();

            foreach (ContractInspection contractInspection in contractInspections)
            {
                ContractInspectionItem contractInspectionItem =
                    await _dbContext.ContractInspectionItem.SingleOrDefaultAsync(x =>
                                                                                 x.ContractInspectionId == contractInspection.Id);

                CaseDto caseDto = await _sdkCore.CaseLookupMUId(contractInspectionItem.SDKCaseId);

                if (caseDto.MicrotingUId != null)
                {
                    await _sdkCore.CaseDelete((int)caseDto.MicrotingUId);
                }
            }
        }
Beispiel #25
0
        public void CaseCompleted(object sender, EventArgs args)
        {
            try
            {
                CaseDto trigger = (CaseDto)sender;

                if (trigger.MicrotingUId != null && trigger.CheckUId != null)
                {
                    int caseId      = (int)trigger.MicrotingUId;
                    int checkListId = (int)trigger.CheckListId;
                    int checkUId    = (int)trigger.CheckUId;
                    int siteId      = (int)trigger.SiteUId;
                    _bus.SendLocal(new eFormCompleted(caseId, checkListId, checkUId, siteId));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ERR] ServiceWorkOrdersPlugin.CaseCompleted: Got the following error: {ex.Message}");
            }
        }
Beispiel #26
0
        public void CaseCompleted(object sender, EventArgs args)
        {
            //if (sender is CaseDto trigger && trigger.MicrotingUId != null && trigger.CheckUId != null)
            //{
            //    _bus.SendLocal(new eFormCompleted((int)trigger.MicrotingUId, (int)trigger.CheckUId));
            //}
            Console.WriteLine("[INF] ServiceInstallationCheckingPlugin.CaseCompleted: called");

            CaseDto trigger = (CaseDto)sender;

            int?caseId = trigger.MicrotingUId;

            if (caseId != null)
            {
                Console.WriteLine("[INF] ServiceInstallationCheckingPlugin.CaseCompleted: caseId != null");
                Console.WriteLine($"[INF] ServiceInstallationCheckingPlugin.CaseCompleted: trigger.MicrotingUId is {trigger.MicrotingUId}");
                Console.WriteLine($"[INF] ServiceInstallationCheckingPlugin.CaseCompleted: trigger.CheckUId is {trigger.CheckUId}");
                _bus.SendLocal(new eFormCompleted((int)trigger.MicrotingUId, (int)trigger.CheckUId));
            }
        }
#pragma warning disable 1998
        public async Task Handle(EformRetrieved message)
        {
            try
            {
                await sqlController.CaseUpdateRetrieved(message.MicrotringUUID);

                await sqlController.NotificationUpdate(message.notificationUId, message.MicrotringUUID, Constants.WorkflowStates.Processed, "", "");

                CaseDto cDto = await sqlController.CaseReadByMUId(message.MicrotringUUID);

                log.LogStandard(t.GetMethodName("EformRetrievedHandler"), cDto.ToString() + " has been retrieved");
                await core.FireHandleCaseRetrived(cDto);
            }
            catch (Exception ex)
            {
                await sqlController.NotificationUpdate(message.notificationUId, message.MicrotringUUID, Constants.WorkflowStates.NotFound, ex.Message, ex.StackTrace.ToString());

                NoteDto noteDto = new NoteDto(message.notificationUId, message.MicrotringUUID, Constants.WorkflowStates.NotFound);
                await core.FireHandleNotificationNotFound(noteDto);
            }
        }
Beispiel #28
0
 public CaseDto AddNewCase(ClientDto clientDto, CaseInformationDto caseInformationDto, NotesDto notesDto, CaseStatusDto caseStatusDto, List <CaseReferenceDto> caseReferenceDtos)
 {
     try
     {
         CaseDto addedCaseDto = new CaseDto();
         Case    newCase      = new Case();
         Case    addedCase    = CaseRepository.Add(newCase);
         addedCaseDto.CaseId          = addedCase.CaseId;
         addedCaseDto.Id              = addedCase.Id;
         addedCaseDto.ModifiedOn      = addedCase.ModifiedOn;
         addedCaseDto.CreatedOn       = addedCase.CreatedOn;
         addedCaseDto.Client          = ClientBusinessLogic.AddNewClient(clientDto, addedCase.Id);
         addedCaseDto.CaseInformation = CaseInformationBusinessLogic.AddNewCaseInformation(caseInformationDto, addedCase.Id);
         addedCaseDto.CaseStatus      = CaseStatusBusinessLogic.AddNewCaseStatus(caseStatusDto, addedCase.Id);
         addedCaseDto.Notes           = NotesBusinessLogic.AddNewNotes(notesDto, addedCase.Id);
         addedCaseDto.References      = CaseReferenceBusinessLogic.AddNewCaseReferences(caseReferenceDtos, addedCase.Id);
         return(addedCaseDto);
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
        public async Task <string> DownloadEFormPdf(int id, string token, string fileType)
        {
            Core core = await _coreHelper.GetCore();

            var locale = await _userService.GetCurrentUserLocale();

            var    language = core.DbContextHelper.GetDbContext().Languages.Single(x => x.LanguageCode.ToLower() == locale.ToLower());
            string microtingUId;
            string microtingCheckUId;
            int    caseId  = 0;
            int    eFormId = 0;

            ContractInspection contractInspection =
                await _dbContext.ContractInspection.SingleOrDefaultAsync(x => x.Id == id);

            Contract contract = _dbContext.Contract.Single(x => x.Id == contractInspection.ContractId);

            int      i          = 0;
            XElement xmlContent = new XElement("ContractInspection");

            foreach (ContractRentableItem contractRentableItem in _dbContext.ContractRentableItem
                     .Where(x => x.ContractId == contract.Id &&
                            x.WorkflowState == Constants.WorkflowStates.Created)
                     .ToList())
            {
                RentableItem rentableItem = _dbContext.RentableItem.Single(x => x.Id == contractRentableItem.RentableItemId);
                xmlContent.Add(new XElement($"Brand_{i}", rentableItem.Brand));
                xmlContent.Add(new XElement($"ModelName_{i}", rentableItem.ModelName));
                xmlContent.Add(new XElement($"Serial_{i}", rentableItem.SerialNumber));
                xmlContent.Add(new XElement($"RegistrationDate_{i}", rentableItem.RegistrationDate));
                xmlContent.Add(new XElement($"vinNumber_{i}", rentableItem.VinNumber));
                xmlContent.Add(new XElement($"PlateNumber_{i}", rentableItem.PlateNumber));
                i += 1;
            }

            Customer customer =
                _customerDbContext.Customers.Single(x => x.Id == contract.CustomerId);

            xmlContent.Add(new XElement("CustomerCustomerNo", customer.CustomerNo));
            xmlContent.Add(new XElement("CustomerCompanyName", customer.CompanyName));
            xmlContent.Add(new XElement("CustomerContactPerson", customer.ContactPerson));
            xmlContent.Add(new XElement("CustomerCompanyAddress", customer.CompanyAddress));
            xmlContent.Add(new XElement("CustomerCompanyAddress2", customer.CompanyAddress2));
            xmlContent.Add(new XElement("CustomerCityName", customer.CityName));
            xmlContent.Add(new XElement("CustomerZipCode", customer.ZipCode));
            xmlContent.Add(new XElement("CustomerCountryCode", customer.CountryCode));
            xmlContent.Add(new XElement("CustomerEanCode", customer.EanCode));
            xmlContent.Add(new XElement("CustomerVatNumber", customer.VatNumber));
            xmlContent.Add(new XElement("CustomerEmail", customer.Email));
            xmlContent.Add(new XElement("CustomerPhone", customer.Phone));
            xmlContent.Add(new XElement("CustomerDescription", customer.Description));

            _coreHelper.LogEvent($"DownloadEFormPdf: xmlContent is {xmlContent}");
            ContractInspectionItem contractInspectionItem =
                _dbContext.ContractInspectionItem.FirstOrDefault(x =>
                                                                 x.ContractInspectionId == contractInspection.Id);

            CaseDto caseDto = await core.CaseLookupMUId(contractInspectionItem.SDKCaseId);

            caseId  = (int)caseDto.CaseId;
            eFormId = caseDto.CheckListId;

            if (caseId != 0 && eFormId != 0)
            {
                _coreHelper.LogEvent($"DownloadEFormPdf: caseId is {caseId}, eFormId is {eFormId}");
                var filePath = await core.CaseToPdf(caseId, eFormId.ToString(),
                                                    DateTime.Now.ToString("yyyyMMddHHmmssffff"),
                                                    $"{await core.GetSdkSetting(Settings.httpServerAddress)}/" + "api/template-files/get-image/", xmlContent.ToString(), language);

                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException();
                }

                return(filePath);
            }

            throw new Exception("could not find case of eform!");
        }
        public async Task Handle(eFormCompleted message)
        {
            WriteLogEntry($"eFormCompletedHandler.Handle: we got called for message.caseId {message.caseId} and message.checkId {message.checkId}");
            await using MicrotingDbContext microtingDbContext = _sdkCore.DbContextHelper.GetDbContext();
            Language language = await microtingDbContext.Languages.SingleAsync(x => x.LanguageCode == "da");

            CaseDto caseDto = await _sdkCore.CaseLookup(message.caseId, message.checkId).ConfigureAwait(false);

            ReplyElement replyElement = await _sdkCore.CaseRead(message.caseId, message.checkId, language).ConfigureAwait(false);

            OuterInnerResourceSite machineAreaSite =
                _dbContext.OuterInnerResourceSites.SingleOrDefault(x =>
                                                                   x.MicrotingSdkCaseId == message.caseId);

            var machineAreaTimeRegistrations =
                await _dbContext.ResourceTimeRegistrations.Where(x =>
                                                                 // x.DoneAt == replyElement.DoneAt &&
                                                                 x.SDKCaseId == (int)caseDto.CaseId &&
                                                                 x.SDKSiteId == machineAreaSite.MicrotingSdkSiteId).ToListAsync().ConfigureAwait(false);

            if (machineAreaTimeRegistrations.Count == 0)
            {
                ResourceTimeRegistration machineAreaTimeRegistration = new ResourceTimeRegistration();
                if (machineAreaSite != null)
                {
                    var outerInnerResource =
                        await _dbContext.OuterInnerResources.SingleOrDefaultAsync(x =>
                                                                                  x.Id == machineAreaSite.OuterInnerResourceId);

                    machineAreaTimeRegistration.OuterResourceId = outerInnerResource.OuterResourceId;
                    machineAreaTimeRegistration.InnerResourceId = outerInnerResource.InnerResourceId;
                    machineAreaTimeRegistration.DoneAt          = replyElement.DoneAt;
                    if (caseDto.CaseId != null)
                    {
                        machineAreaTimeRegistration.SDKCaseId = (int)caseDto.CaseId;
                    }
                    machineAreaTimeRegistration.SDKSiteId = machineAreaSite.MicrotingSdkSiteId;
                }

                CheckListValue dataElement = (CheckListValue)replyElement.ElementList[0];
                foreach (var field in dataElement.DataItemList)
                {
                    Field f = (Field)field;
                    if (f.Label.ToLower().Contains("start/stop tid"))
                    {
                        try
                        {
                            Console.WriteLine($"The field is {f.Label}");
                            FieldValue fv         = f.FieldValues[0];
                            String     fieldValue = fv.Value;
                            if (!string.IsNullOrEmpty(fieldValue))
                            {
                                Console.WriteLine($"Current field_value is {fieldValue}");
                                int registeredTime = int.Parse(fieldValue.Split("|")[3]);
                                Console.WriteLine($"We are setting the registered time to {registeredTime.ToString()}");

                                machineAreaTimeRegistration.SDKFieldValueId = fv.Id;
                                machineAreaTimeRegistration.TimeInSeconds   = (registeredTime / 1000);
                                machineAreaTimeRegistration.TimeInMinutes   = ((registeredTime / 1000) / 60);
                                machineAreaTimeRegistration.TimeInHours     = ((registeredTime / 1000) / 3600);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }

                await machineAreaTimeRegistration.Create(_dbContext).ConfigureAwait(false);
            }
            else
            {
                if (machineAreaTimeRegistrations.Count > 1)
                {
                    int i = 0;
                    foreach (ResourceTimeRegistration machineAreaTimeRegistration in machineAreaTimeRegistrations)
                    {
                        if (i > 0)
                        {
                            await machineAreaTimeRegistration.Delete(_dbContext);
                        }

                        i++;
                        Console.WriteLine("More than one time registration found");
                    }
                }
                else
                {
                    Console.WriteLine("One time registration found");
                }
            }
        }