def fatt_vedtak_action_strategy(soknad, action, data):
    vedtak = VedtakUtils.fatt_vedtak(soknad, data)
    if not data.get('saveOnly'):
        vedtak.vedtaksdato = datetime.now()
        soknad.status = action.get_end_state().id

        current_app.logger.debug("Generating vedtaksbrev...")
        rendered_file, file_size, mimetype, filename = VedtaksbrevGeneratorResource.generate_vedtaksbrev(soknad, vedtak)
        current_app.logger.debug("Saving vedtaksbrev to backend...")
        saved_filename, saved_in_dir = save_file_to_disk(rendered_file, filename,
                                                         relative_path=get_rel_vedtaksmappe_path(soknad, vedtak))
        current_app.logger.debug("Updating vedtaket med vedtaksbrev_file_ref=%s..." % saved_filename)
        vedtak.vedtaksbrev_file_ref = saved_filename

        # Arkivering
        # ###########
        organisation = get_organisation(soknad.organisation_id, request.cookies)
        person = get_person(soknad.person_id, request.cookies)
        save_journalpost_for_vedtaksbrev(soknad, organisation, person, vedtak, is_utgaaende_dokument=True)

        SoknadRepo.save(soknad)

        # Sending mail after save to avoid that mail integration errors make it impossible to perform action.
        # It also makes sense to send mail only when we know that the action is successful
        if action == SoknadStateMachine.t_fatt_vedtak:
            send_email_to_soker_on_action_fatt_vedtak(soknad)
        elif action == SoknadStateMachine.t_fatt_klagevedtak:
            send_email_to_soker_on_action_fatt_klagevedtak(soknad)

    else:
        SoknadRepo.save(soknad)
def vedtak_klaget_action_strategy(soknad, action, data):
    if data is None:
        abort(400, __error__=['Data mangler'])

    validator = BaseValidator(data)
    validator.validate_le_max_length("begrunnelse", 300, "begrunnelse")

    if validator.has_errors():
        abort(400, __error__=validator.errors)

    klage = Klage()
    klage.soknad_id = soknad.id
    klage.vedtak_id = data.get('vedtak_id')
    klage.levertdato = datetime.now()
    klage.begrunnelse = data.get('begrunnelse')

    soknad.klage.append(klage)

    soknad.status = action.get_end_state().id
    SoknadRepo.save(soknad, autocommit=False)

    # Arkivering
    # ###########
    organisation = get_organisation(soknad.organisation_id, request.cookies)
    person = get_person(soknad.person_id, request.cookies)
    save_journalpost_for_klage(soknad, organisation, person, klage.begrunnelse.encode("UTF-8"), u"soknad-%s-klage-%s.txt" % (soknad.id, datetime.now().isoformat()))

    current_app.db_session.commit()
def lever_rapport_action_strategy(soknad, action, data):
    rapport = RapportRepo.find_by_where("soknad_id", soknad.id)
    if len(rapport) != 1:
        abort(400, __error__=['Kan ikke finne rapport'])

    errors = rapport[0].validate_rapport_for_levering()
    if errors:
        abort(400, __error__=errors)

    soknad.status = action.get_end_state().id
    SoknadRepo.save(soknad, autocommit=False)

    # Arkivering
    # ###########
    organisation = get_organisation(soknad.organisation_id, request.cookies)
    person = get_person(soknad.person_id, request.cookies)

    csv_file_content = ExportRapporterResource().get(soknad_id=soknad.id, rapport_id=rapport[0].id).data

    save_journalpost_for_rapport(soknad, rapport[0], organisation, person, csv_file_content,
                                 u"soknad-%s-rapport-%s-%s.pdf" % (soknad.id, rapport[0].id, datetime.now().isoformat()))

    current_app.db_session.commit()

    # Sending mail after save to avoid that mail integration errors make it impossible to perform action.
    # It also makes sense to send mail only when we know that the action is successful
    send_email_to_soker_on_action_lever_rapport(soknad)
    send_email_to_saksbehandler_on_action_lever_rapport(soknad)
def send_tilbake_til_saksbehandling_strategy(soknad, action, data):
    errors = soknad.validate_soknad_for_innsending()
    if errors:
        abort(400, __error__=errors)

    soknad.status = action.get_end_state().id

    SoknadRepo.save(soknad, autocommit=False)

    # Arkivering
    ############
    organisation = get_organisation(soknad.organisation_id, request.cookies)
    person = get_person(soknad.person_id, request.cookies)

    csv_file_content = ExportSoknaderResource().get(soknad_id=soknad.id).data

    save_journalpost_for_soknad(soknad, organisation, person, csv_file_content,
                                u"soknad-%s-%s.pdf" % (soknad.id, datetime.now().isoformat()))

    current_app.db_session.commit()

    # Sending mail after save to avoid that mail integration errors make it impossible to perform action.
    # It also makes sense to send mail only when we know that the action is successful
    send_email_to_soker_on_action_send_inn(soknad)
    if not soknad.tilskuddsordning.soknadsfrist:
        send_email_to_saksbehandlere_on_action_send_inn(soknad)
    def post(self, soknad_id):

        if soknad_id is not None:
            soknad = SoknadRepo.find_by_id(soknad_id)
        else:
            return SakApi.create_error_response_for_iframe(body_status=400, body_error='Missing object id')

        ensure(MANAGE, SoknadAction(soknad, SoknadStateMachine.t_last_opp_saksvedlegg))

        validator = VedleggValidator(request.form).validate_post_fields()
        if validator.has_errors():
            return SakApi.create_error_response_for_iframe(body_status=400, body_error=validator.errors)

        file = request.files.get('upload_file')
        if file is None:
            current_app.logger.warn('Missing required file: document')
            return SakApi.create_error_response_for_iframe(body_status=400, body_error=u'Dokument er påkrevd.')

        extension = os.path.splitext(file.filename)[1]

        if file.mimetype not in VALID_MIME_TYPES or extension not in VALID_EXTENSIONS:
            current_app.logger.warn('Invalid mimetype: %s', file.mimetype)
            return SakApi.create_error_response_for_iframe(body_status=400, body_error=u'Ugyldig filtype.')

        filnavn = uuid_with_ext(file.filename)

        target_path = generate_dir_path(DOC_PATH, get_rel_saksvedlegg_path(soknad))

        backend = get_backend(file, filename=filnavn, path=target_path)
        backend.save()

        saksvedlegg = Vedlegg()
        user = get_user_from_auth()

        saksvedlegg.filnavn = file.filename
        saksvedlegg.file_ref = filnavn
        saksvedlegg.beskrivelse = request.form.get('tittel')
        saksvedlegg.user_id = user['id']
        saksvedlegg.vedlagtdato = datetime.now()

        soknad.saksvedlegg.append(saksvedlegg)


        if soknad.saksbehandler_id:
            # Arkivering
            # ###########

            organisation = get_organisation(soknad.organisation_id, request.cookies)
            person = get_person(soknad.person_id, request.cookies)
            try:
                save_journalpost_for_saksvedlegg(soknad, organisation, person, saksvedlegg)
            except InvalidArkivExtensionError as e:
                return SakApi.create_error_response_for_iframe(body_status=400, body_error=e.message)

        current_app.db_session.commit()

        return Response(response=json.dumps(marshal(saksvedlegg, saksvedlegg_fields)), status=201,
                        content_type='text/html')
    def generate_vedtaksbrev(cls, soknad, vedtak):
        organisation = get_organisation(soknad.organisation_id, request.cookies)

        if vedtak is None:
            abort(404, __error__=[u'Ingen vedtak funnet på søknad!'])

        mimetype = "application/pdf"
        filename = VedtaksbrevGeneratorResource.generate_file_name(soknad, organisation, "pdf")
        rendered_file_content, file_size = create_vedtaksbrev_from_template(soknad, organisation, vedtak)

        return rendered_file_content, file_size, mimetype, filename
    def get(self, soknad_id):
        soknad = current_app.db_session.query(Soknad).filter(Soknad.id == soknad_id).one()
        utbetaling = soknad.nyeste_utbetaling()
        organisation = get_organisation(soknad.organisation_id, request.cookies)

        rendered_file_contents, size, mimetype, filename = self.create_docx(soknad, organisation, utbetaling)

        rendered_file = StringIO(rendered_file_contents)
        response = send_file(
            rendered_file, mimetype=mimetype, as_attachment=True, attachment_filename=filename.encode("utf-8")
        )

        response.headers["Content-Length"] = size
        return response
def behandle_action_strategy(soknad, action, data):
    if not data or not data.get("saksbehandler"):
        abort(400, __error__={'saksbehandler': u'Saksbehandler må være satt'})
    soknad.saksbehandler_id = data.get("saksbehandler")
    soknad.status = action.get_end_state().id

    SoknadRepo.save(soknad, autocommit=False)

    # Arkivering
    # ###########
    organisation = get_organisation(soknad.organisation_id, request.cookies)
    person = get_person(soknad.person_id, request.cookies)

    csv_file_content = ExportSoknaderResource().get(soknad_id=soknad.id).data

    save_sak(soknad)
    save_journalpost_for_soknad(soknad, organisation, person, csv_file_content, u"soknad-%s-%s.pdf" % (soknad.id, datetime.now().isoformat()))

    current_app.db_session.commit()
def send_email_to_organisasjon_on_action_send_inn(soknad):
    organisation = get_organisation(soknad.organisation_id, request.cookies)

    if (organisation.get('email_address') is None or organisation.get('email_address') == '') and \
        (organisation.get('local_email_address') is None or organisation.get('local_email_address') == ''):
        current_app.logger.warn(u"Kunne ikke sende epost til organisasjon %s ved innsendelse av søknad %s, "
                                u"ingen epost adresse registrert på søknaden!"
                                % (organisation.get("id"), soknad.id))
    else:
        person = get_person(soknad.person_id, request.cookies)
        name = person.get('first_name', '')+' '+ person.get('last_name', '')

        message = render_template(ORG_SOKNAD_SENDT_INN_TEMPLATE, aktor=organisation.get('name'), soker=name,
                                  prosjektnavn=soknad.prosjektnavn,levert_dato=soknad.levert_dato, soknad_id=soknad.id)

        celery_app.send_task('celery_tasks.email_tasks.send_email_task',
                             queue='email',
                             kwargs={'subject': u'Bekreftelse på mottatt søknad',
                                     'sender': u'*****@*****.**',
                                     'recipients': [organisation.get('email_address'), organisation.get('local_email_address')],
                                     'body': message})