Search in sources :

Example 96 with Utkast

use of se.inera.intyg.webcert.persistence.utkast.model.Utkast in project webcert by sklintyg.

the class IntygServiceImpl method buildIntygItemListFromDrafts.

private List<ListIntygEntry> buildIntygItemListFromDrafts(List<String> enhetId, Personnummer personnummer) {
    List<UtkastStatus> statuses = new ArrayList<>();
    statuses.add(UtkastStatus.SIGNED);
    SekretessStatus sekretessmarkering = patientDetailsResolver.getSekretessStatus(personnummer);
    Set<String> base = authoritiesHelper.getIntygstyperForPrivilege(webCertUserService.getUser(), AuthoritiesConstants.PRIVILEGE_VISA_INTYG);
    // Remove intygstyper that cannot be issued for a sekretessmarkerad patient
    Set<String> intygsTyper = (sekretessmarkering == SekretessStatus.TRUE || sekretessmarkering == SekretessStatus.UNDEFINED) ? filterAllowedForSekretessMarkering(base) : base;
    List<Utkast> drafts = utkastRepository.findDraftsByPatientAndEnhetAndStatus(DaoUtil.formatPnrForPersistence(personnummer), enhetId, statuses, intygsTyper);
    return IntygDraftsConverter.convertUtkastsToListIntygEntries(drafts);
}
Also used : UtkastStatus(se.inera.intyg.webcert.common.model.UtkastStatus) SekretessStatus(se.inera.intyg.webcert.common.model.SekretessStatus) Utkast(se.inera.intyg.webcert.persistence.utkast.model.Utkast) ArrayList(java.util.ArrayList)

Example 97 with Utkast

use of se.inera.intyg.webcert.persistence.utkast.model.Utkast in project webcert by sklintyg.

the class IntygServiceImpl method getIntygData.

/**
 * Builds a IntygContentHolder by first trying to get the Intyg from intygstjansten. If
 * not found or the Intygstjanst couldn't be reached, the local Utkast - if available -
 * will be used instead.
 * <p>
 * Note that even when found, we check if we need to decorate the response with data from the utkast in order
 * to mitigate async send states. (E.g. a send may be in resend due to 3rd party issues, in that case decorate with
 * data about sent state from the Utkast)
 *
 * @param relations
 */
private IntygContentHolder getIntygData(String intygId, String typ, boolean relations) {
    try {
        CertificateResponse certificate = modelFacade.getCertificate(intygId, typ);
        String internalIntygJsonModel = certificate.getInternalModel();
        final Personnummer personId = certificate.getUtlatande().getGrundData().getPatient().getPersonId();
        // INTYG-4086: Patient object populated according to ruleset for the intygstyp at hand.
        // Since an FK-intyg never will have anything other than personId, try to fetch all using ruleset
        Patient newPatientData = patientDetailsResolver.resolvePatient(personId, typ);
        Utlatande utlatande = null;
        boolean patientNameChanged = false;
        boolean patientAddressChanged = false;
        try {
            utlatande = moduleRegistry.getModuleApi(typ).getUtlatandeFromJson(internalIntygJsonModel);
            patientNameChanged = patientDetailsResolver.isPatientNamedChanged(utlatande.getGrundData().getPatient(), newPatientData);
            patientAddressChanged = patientDetailsResolver.isPatientAddressChanged(utlatande.getGrundData().getPatient(), newPatientData);
        } catch (IOException e) {
            LOG.error("Failed to getUtlatandeFromJson intygsId {} while checking for updated patient information", intygId);
        }
        // parameters were available.
        if (newPatientData != null) {
            // Get the module api and use the "updateBeforeSave" to update the outbound "model" with the
            // Patient object.
            ModuleApi moduleApi = moduleRegistry.getModuleApi(typ);
            // INTYG-5354, INTYG-5380: Don't use incomplete address from external data sources (PU/js).
            if (!completeAddressProvided(newPatientData)) {
                // Use the old address data.
                Patient oldPatientData = utlatande.getGrundData().getPatient();
                copyOldAddressToNewPatientData(oldPatientData, newPatientData);
            }
            internalIntygJsonModel = moduleApi.updateBeforeSave(internalIntygJsonModel, newPatientData);
        }
        utkastIntygDecorator.decorateWithUtkastStatus(certificate);
        Relations certificateRelations = intygRelationHelper.getRelationsForIntyg(intygId);
        final SekretessStatus sekretessStatus = patientDetailsResolver.getSekretessStatus(personId);
        if (SekretessStatus.UNDEFINED.equals(sekretessStatus)) {
            throw new WebCertServiceException(WebCertServiceErrorCodeEnum.PU_PROBLEM, "Sekretesstatus could not be fetched from the PU service");
        }
        final boolean sekretessmarkering = SekretessStatus.TRUE.equals(sekretessStatus);
        Utkast utkast = utkastRepository.findOneByIntygsIdAndIntygsTyp(intygId, typ);
        final LocalDateTime created = utkast != null ? utkast.getSkapad() : null;
        return IntygContentHolder.builder().setContents(internalIntygJsonModel).setUtlatande(certificate.getUtlatande()).setStatuses(certificate.getMetaData().getStatus()).setRevoked(certificate.isRevoked()).setRelations(certificateRelations).setCreated(created).setDeceased(isDeceased(personId)).setSekretessmarkering(sekretessmarkering).setPatientNameChangedInPU(patientNameChanged).setPatientAddressChangedInPU(patientAddressChanged).build();
    } catch (IntygModuleFacadeException me) {
        // It's possible the Intygstjanst hasn't received the Intyg yet, look for it locally before rethrowing
        // exception
        Utkast utkast = utkastRepository.findOneByIntygsIdAndIntygsTyp(intygId, typ);
        if (utkast == null) {
            throw new WebCertServiceException(WebCertServiceErrorCodeEnum.MODULE_PROBLEM, me);
        }
        return buildIntygContentHolderForUtkast(utkast, relations);
    } catch (WebServiceException wse) {
        // Something went wrong communication-wise, try to find a matching Utkast instead.
        Utkast utkast = utkastRepository.findOneByIntygsIdAndIntygsTyp(intygId, typ);
        if (utkast == null) {
            throw new WebCertServiceException(WebCertServiceErrorCodeEnum.DATA_NOT_FOUND, "Cannot get intyg. Intygstjansten was not reachable and the Utkast could " + "not be found, perhaps it was issued by a non-webcert system?");
        }
        return buildIntygContentHolderForUtkast(utkast, relations);
    } catch (ModuleNotFoundException | ModuleException e) {
        throw new WebCertServiceException(WebCertServiceErrorCodeEnum.MODULE_PROBLEM, e);
    }
}
Also used : ModuleApi(se.inera.intyg.common.support.modules.support.api.ModuleApi) ChronoLocalDateTime(java.time.chrono.ChronoLocalDateTime) LocalDateTime(java.time.LocalDateTime) ModuleNotFoundException(se.inera.intyg.common.support.modules.registry.ModuleNotFoundException) SekretessStatus(se.inera.intyg.webcert.common.model.SekretessStatus) WebServiceException(javax.xml.ws.WebServiceException) CertificateResponse(se.inera.intyg.common.support.modules.support.api.dto.CertificateResponse) Patient(se.inera.intyg.common.support.model.common.internal.Patient) Relations(se.inera.intyg.webcert.web.web.controller.api.dto.Relations) IOException(java.io.IOException) IntygModuleFacadeException(se.inera.intyg.webcert.web.service.intyg.converter.IntygModuleFacadeException) WebCertServiceException(se.inera.intyg.webcert.common.service.exception.WebCertServiceException) Personnummer(se.inera.intyg.schemas.contract.Personnummer) Utlatande(se.inera.intyg.common.support.model.common.internal.Utlatande) Utkast(se.inera.intyg.webcert.persistence.utkast.model.Utkast) ModuleException(se.inera.intyg.common.support.modules.support.api.exception.ModuleException)

Example 98 with Utkast

use of se.inera.intyg.webcert.persistence.utkast.model.Utkast in project webcert by sklintyg.

the class SignaturServiceImpl method clientNiasSignature.

@Override
public SignaturTicket clientNiasSignature(String ticketId, SignatureType signatureType, String niasCertificate, WebCertUser user) {
    // Lookup signature ticket
    SignaturTicket ticket = ticketTracker.getTicket(ticketId);
    if (ticket == null) {
        LOG.warn("Ticket '{}' hittades ej", ticketId);
        throw new WebCertServiceException(WebCertServiceErrorCodeEnum.INVALID_STATE, "Biljett " + ticketId + " hittades ej");
    }
    LOG.debug("Klientsignering ticket '{}' intyg '{}'", ticket.getId(), ticket.getIntygsId());
    // Fetch the draft
    Utkast utkast = getUtkastForSignering(ticket.getIntygsId(), ticket.getVersion(), user);
    // Create and persist the new signature
    StringWriter sw = new StringWriter();
    JAXB.marshal(signatureType, sw);
    String rawSignaturXml = sw.toString();
    ticket = createAndPersistSignature(utkast, ticket, rawSignaturXml, user);
    monitoringService.logIntygSigned(utkast.getIntygsId(), utkast.getIntygsTyp(), user.getHsaId(), user.getAuthenticationScheme(), utkast.getRelationKod());
    // Notify stakeholders when certificate has been signed
    notificationService.sendNotificationForDraftSigned(utkast);
    LogRequest logRequest = LogRequestFactory.createLogRequestFromUtkast(utkast);
    // Note that we explictly supplies the WebCertUser here. The NIAS finalization is not executed in a HTTP
    // request context and thus we need to supply the user instance manually.
    logService.logSignIntyg(logRequest, logService.getLogUser(user));
    intygService.handleAfterSigned(utkast);
    return ticketTracker.updateStatus(ticket.getId(), SignaturTicket.Status.SIGNERAD);
}
Also used : LogRequest(se.inera.intyg.webcert.web.service.log.dto.LogRequest) StringWriter(java.io.StringWriter) Utkast(se.inera.intyg.webcert.persistence.utkast.model.Utkast) SignaturTicket(se.inera.intyg.webcert.web.service.signatur.dto.SignaturTicket) WebCertServiceException(se.inera.intyg.webcert.common.service.exception.WebCertServiceException)

Example 99 with Utkast

use of se.inera.intyg.webcert.persistence.utkast.model.Utkast in project webcert by sklintyg.

the class SignaturServiceImpl method createDraftHash.

/**
 * Called from the Controller when initiating a client (e.g. NetID) signature. Rewritten in INTYG-5048 so
 * <i>starting</i> a signature process does NOT mutate the Utkast in any way. Instead, a temporary intyg JSON model
 * including the signatureDate and signing identity is stored in a {@link PagaendeSignering} entity.
 * <p>
 * Once the signing has been completed
 * (see {@link SignaturServiceImpl#createAndPersistSignature(Utkast, SignaturTicket, String, WebCertUser)}) the
 * hash, intygsId and version from the JSON model in the PagaendeSignatur is validated and if everything works out,
 * the final state is written to the Utkast table.
 * <p>
 * If the user for some reason failed to finish the signing (cancelled in NetID etc.), the Utkast table won't be
 * affected or contain a signingDate even though it wasn't signed. A stale entry may remain in PAGAENDE_SIGNERING
 * but since those cannot be reused such entries can remain there indefinitely or until cleaned up by a janitor
 * task.
 *
 * @param intygId The id of the draft to generate signing ticket for
 * @param version version
 * @return
 */
@Override
@Transactional("jpaTransactionManager")
public SignaturTicket createDraftHash(String intygId, long version) {
    LOG.debug("Hash for clientsignature of draft '{}'", intygId);
    // Fetch Webcert user
    WebCertUser user = getWebcertUserForSignering();
    // Fetch the certificate draft
    Utkast utkast = getUtkastForSignering(intygId, version, user);
    LocalDateTime signeringstid = LocalDateTime.now();
    try {
        VardpersonReferens vardpersonReferens = UpdateUserUtil.createVardpersonFromWebCertUser(user);
        ModuleApi moduleApi = moduleRegistry.getModuleApi(utkast.getIntygsTyp());
        Vardenhet vardenhetFromJson = moduleApi.getUtlatandeFromJson(utkast.getModel()).getGrundData().getSkapadAv().getVardenhet();
        String updatedInternal = moduleApi.updateBeforeSigning(utkast.getModel(), IntygConverterUtil.buildHosPersonalFromWebCertUser(user, vardenhetFromJson), signeringstid);
        // Skapa ny PagaendeSignering
        PagaendeSignering pagaendeSignering = new PagaendeSignering();
        pagaendeSignering.setIntygData(updatedInternal);
        pagaendeSignering.setIntygsId(utkast.getIntygsId());
        pagaendeSignering.setSigneradAvHsaId(vardpersonReferens.getHsaId());
        pagaendeSignering.setSigneradAvNamn(vardpersonReferens.getNamn());
        pagaendeSignering.setSigneringsDatum(signeringstid);
        pagaendeSignering = pagaendeSigneringRepository.save(pagaendeSignering);
        return createSignaturTicket(utkast.getIntygsId(), pagaendeSignering.getInternReferens(), utkast.getVersion(), updatedInternal, signeringstid);
    } catch (ModuleNotFoundException | IOException | ModuleException e) {
        throw new WebCertServiceException(WebCertServiceErrorCodeEnum.INTERNAL_PROBLEM, "Unable to sign certificate: " + e.getMessage());
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) ModuleApi(se.inera.intyg.common.support.modules.support.api.ModuleApi) ModuleNotFoundException(se.inera.intyg.common.support.modules.registry.ModuleNotFoundException) PagaendeSignering(se.inera.intyg.webcert.persistence.utkast.model.PagaendeSignering) IOException(java.io.IOException) Vardenhet(se.inera.intyg.common.support.model.common.internal.Vardenhet) WebCertServiceException(se.inera.intyg.webcert.common.service.exception.WebCertServiceException) Utkast(se.inera.intyg.webcert.persistence.utkast.model.Utkast) ModuleException(se.inera.intyg.common.support.modules.support.api.exception.ModuleException) WebCertUser(se.inera.intyg.webcert.web.service.user.dto.WebCertUser) VardpersonReferens(se.inera.intyg.webcert.persistence.utkast.model.VardpersonReferens) Transactional(org.springframework.transaction.annotation.Transactional)

Example 100 with Utkast

use of se.inera.intyg.webcert.persistence.utkast.model.Utkast in project webcert by sklintyg.

the class SignaturServiceImpl method createAndPersistSignature.

private SignaturTicket createAndPersistSignature(Utkast utkast, SignaturTicket ticket, String rawSignature, WebCertUser user) {
    validateUniqueIntyg(user, utkast.getIntygsTyp(), utkast.getPatientPersonnummer());
    PagaendeSignering pagaendeSignering = pagaendeSigneringRepository.findOne(ticket.getPagaendeSigneringId());
    if (pagaendeSignering == null) {
        throw new WebCertServiceException(WebCertServiceErrorCodeEnum.INVALID_STATE, "Can't complete signing of certificate, no PagaendeSignering found for interreferens " + ticket.getPagaendeSigneringId());
    }
    String payload = pagaendeSignering.getIntygData();
    if (!pagaendeSignering.getIntygsId().equals(utkast.getIntygsId())) {
        LOG.error("Signing of utkast '{}' failed since the intygsId ({}) on the Utkast is different from the one " + "on the signing operation ({})", utkast.getIntygsId(), pagaendeSignering.getIntygsId());
        throw new WebCertServiceException(WebCertServiceErrorCodeEnum.INVALID_STATE, "Internal error signing utkast, the payload of utkast " + utkast.getIntygsId() + " has been modified since signing was initialized");
    }
    if (!ticket.getHash().equals(createHash(payload))) {
        LOG.error("Signing of utkast '{}' failed since the payload has been modified since signing was initialized", utkast.getIntygsId());
        throw new WebCertServiceException(WebCertServiceErrorCodeEnum.INVALID_STATE, "Internal error signing utkast, the payload of utkast " + utkast.getIntygsId() + " has been modified since signing was initialized");
    }
    if (utkast.getVersion() != ticket.getVersion()) {
        LOG.error("Signing of utkast '{}' failed since the version on the utkast ({}) differs from when the signing was initialized ({})", utkast.getIntygsId(), utkast.getVersion(), ticket.getVersion());
        throw new WebCertServiceException(WebCertServiceErrorCodeEnum.CONCURRENT_MODIFICATION, "Cannot complete signing, Utkast version differs from signature ticket version.");
    }
    Signatur signatur = new Signatur(ticket.getSigneringstid(), user.getHsaId(), ticket.getIntygsId(), payload, ticket.getHash(), rawSignature);
    // Update user information ("senast sparat av")
    // Add signature to the utkast and set status as signed
    utkast.setSenastSparadAv(new VardpersonReferens(pagaendeSignering.getSigneradAvHsaId(), pagaendeSignering.getSigneradAvNamn()));
    utkast.setModel(payload);
    utkast.setSignatur(signatur);
    utkast.setStatus(UtkastStatus.SIGNED);
    // Persist utkast with added signature
    Utkast savedUtkast = utkastRepository.save(utkast);
    // Send to Intygstjanst
    intygService.storeIntyg(savedUtkast);
    // Remove PagaendeSignering
    pagaendeSigneringRepository.delete(ticket.getPagaendeSigneringId());
    return ticket;
}
Also used : Signatur(se.inera.intyg.webcert.persistence.utkast.model.Signatur) Utkast(se.inera.intyg.webcert.persistence.utkast.model.Utkast) PagaendeSignering(se.inera.intyg.webcert.persistence.utkast.model.PagaendeSignering) WebCertServiceException(se.inera.intyg.webcert.common.service.exception.WebCertServiceException) VardpersonReferens(se.inera.intyg.webcert.persistence.utkast.model.VardpersonReferens)

Aggregations

Utkast (se.inera.intyg.webcert.persistence.utkast.model.Utkast)171 Test (org.junit.Test)88 WebCertServiceException (se.inera.intyg.webcert.common.service.exception.WebCertServiceException)34 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)24 Personnummer (se.inera.intyg.schemas.contract.Personnummer)21 Signatur (se.inera.intyg.webcert.persistence.utkast.model.Signatur)21 VardpersonReferens (se.inera.intyg.webcert.persistence.utkast.model.VardpersonReferens)21 LogRequest (se.inera.intyg.webcert.web.service.log.dto.LogRequest)18 WebCertUser (se.inera.intyg.webcert.web.service.user.dto.WebCertUser)17 Arende (se.inera.intyg.webcert.persistence.arende.model.Arende)16 Utlatande (se.inera.intyg.common.support.model.common.internal.Utlatande)14 CreateNewDraftRequest (se.inera.intyg.webcert.web.service.utkast.dto.CreateNewDraftRequest)13 Patient (se.inera.intyg.common.support.model.common.internal.Patient)12 ModuleException (se.inera.intyg.common.support.modules.support.api.exception.ModuleException)12 ListIntygEntry (se.inera.intyg.webcert.web.web.controller.api.dto.ListIntygEntry)12 Transactional (org.springframework.transaction.annotation.Transactional)11 ModuleNotFoundException (se.inera.intyg.common.support.modules.registry.ModuleNotFoundException)11 MedicinsktArende (se.inera.intyg.webcert.persistence.arende.model.MedicinsktArende)11 CopyUtkastBuilderResponse (se.inera.intyg.webcert.web.service.utkast.dto.CopyUtkastBuilderResponse)10 ArrayList (java.util.ArrayList)9