def get(self, vedlegg_id):

        rapport_vedlegg = current_app.db_session.query(RapportVedlegg).filter(
            RapportVedlegg.vedlegg_id == vedlegg_id).first()
        soknad_vedlegg = current_app.db_session.query(SoknadVedlegg).filter(
            SoknadVedlegg.vedlegg_id == vedlegg_id).first()

        if rapport_vedlegg is not None:
            object = rapport_vedlegg.rapport
            vedlegg = rapport_vedlegg.vedlegg
            soknad_id = object.soknad_id
        elif soknad_vedlegg is not None:
            object = soknad_vedlegg.soknad
            vedlegg = soknad_vedlegg.vedlegg
            soknad_id = object.id
        else:
            abort(404, __error__=['Vedlegg med id %d finnes ikke' % vedlegg_id])

        ensure(GET, object)

        try:
            doc_path = "%s/%s" % (DOC_PATH, get_rel_vedlegg_path(soknad_id))
            return send_from_directory(doc_path,
                                       vedlegg.file_ref,
                                       as_attachment=True,
                                       attachment_filename=vedlegg.filnavn.encode("utf-8"))

        except NotFound:
            abort(500, __error__=['Filen for vedlegg med id %d finnes ikke' % vedlegg_id])
示例#2
0
文件: views.py 项目: carfriends/odin
def show_score(user_id,score_id):
    teams = [t for t in Team.select() if can(auth.get_logged_in_user(),READ,t)]
    user = get_object_or_404(User, User.id == user_id)
    score = get_object_or_404(Score, Score.id == score_id)
    ensure(READ,user)
    users = [u for u in User.select().where(User.team == user.team) if can(auth.get_logged_in_user(),READ,u)]
    return render_template("score_detail.html", active_user=user, teams=teams, users=users, active_team = user.team, score=score)
    def get(self, application_id=None):
        if application_id is not None:
            application = self.get_object_by_id(application_id)
            ensure(GET, application)

            application_dict = marshal(application, application_fields)

            # Include emails in response, if requested
            if "include_emails" in request.args:
                _, granted_message = render_email_template(application, "Granted")
                _, denied_message = render_email_template(application, "Denied")
                application_dict['emails'] = dict(
                    granted_message=granted_message,
                    denied_message=denied_message
                )

            return application_dict

        applications = current_app.db_session.query(Application).order_by(Application.id)

        applications = filter_applications(applications, request.cookies)

        if "resource_uri" in request.args:
            applications = applications.filter(
                Application.resource_id == Resource.id,
                Resource.uri == request.args["resource_uri"]
            )
        if "organisation_uri" in request.args:
            applications = applications.filter(
                Application.organisation_id == Organisation.id,
                Organisation.uri == request.args["organisation_uri"]
            )
        if "status" in request.args:
            applications = applications.filter(
                Application.status == request.args["status"]
            )
        if "person_uri" in request.args:
            applications = applications.filter(
                Application.person_id == Person.id,
                Person.uri == request.args["person_uri"]
            )

        if "type" in request.args:

            if request.args["type"] == 'repeating':
                applications = applications.filter(
                    Application.requested_repeating_slots.any()
                )
            if request.args["type"] == 'single':
                applications = applications.filter(
                    Application.requested_single_slots.any()
                )
            if request.args["type"] == 'strotime':
                applications = applications.filter(
                    Application.strotime_slots.any()
                )

        return marshal(applications.all(), application_fields)
    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 post(self, soknad_id):

        rapport = Rapport()
        rapport.soknad_id = soknad_id
        ensure(POST, rapport)

        rapport = self.repo.create(rapport)

        return marshal(rapport, rapport_fields), 201
    def put(self, soknad_id):
        data = request.get_json()
        self.validate_put_fields(data)
        soknad = self.get_by_id(soknad_id)

        ensure(PUT, soknad)

        self.repo.save(soknad, data)
        return marshal(soknad, soknad_fields())
示例#7
0
文件: views.py 项目: carfriends/odin
def user_detail(user_id):
    teams = [t for t in Team.select() if can(auth.get_logged_in_user(),READ,t)]
    user = get_object_or_404(User, User.id == user_id)
    ensure(READ,user)
    scores = Score.select().where(Score.user == user).order_by(Score.created_at.desc())
    users = [u for u in User.select().where(User.team == user.team) if can(auth.get_logged_in_user(),READ,u)]
    pq = PaginatedQuery(scores, 20)
    last_date = datetime.now() - timedelta(days=5)
    return render_template("index.html", active_user=user, teams=teams, users=users, pagination=pq, page=pq.get_page(), active_team = user.team, weeks = [w for w in Week.select().where(Week.end > last_date) if not has_score(w.score_set)])
    def get(self, soknad_id=None):

        if soknad_id:
            soknad = self.get_by_id(soknad_id)
            ensure(GET, soknad)

            return marshal(soknad, soknad_fields())
        else:
            soknader = self.query_resource.query_soknader([])
            return marshal(soknader, soknadliste_fields())
    def post(self, resource_id = None):
        data = request.get_json()
        verify_request_contains_mandatory_fields(data, self.mandatory_fields)

        # Resource id might also be part of the incoming json.
        resource_uri = None
        if not resource_id:
            resource_uri = data["resource_uri"]

        resource = self.get_resource_with_id_or_uri(resource_id, resource_uri)

        start_date, end_date = self.parse_date_range_from_dict(data)

        start_time = parse_time(data["start_time"])
        end_time = parse_time(data["end_time"])
        week_day = data["week_day"]
        if data["note"]:
            note = data["note"]
            if not (len(note) <= 50):
                abort(400, __error__=[u'Maks lengde for merknad er 50 tegn'])
        else:
            note= ""


        self.validate_start_and_end_times(start_date, end_date, start_time, end_time)

        # Check that the time has correct minute interval, only 30-minute intervals allowed
        invalid_minutes = filter(lambda my_time: my_time.minute not in [0, 30], [start_time, end_time])
        if invalid_minutes:
            abort(400,
                  __error__=[u'Tidene må angis i hele halvtimer']
            )

        weekly_blocked_time = WeeklyBlockedTime(resource, week_day,
            start_date, end_date, start_time, end_time, note)
        ensure(POST, weekly_blocked_time)

        if self.is_conflict_slot_time(resource, start_date, end_date, week_day, start_time, end_time) or \
                self.is_conflict_rammetid(resource, start_date, end_date, week_day, start_time, end_time):
            abort(
                400,
                __error__=[u'Tiden er ikke tilgjengelig for blokkering']
            )       
        if self.is_conflict_blocked_time(resource, start_date, end_date, week_day, start_time, end_time):
            abort(
                400,
                __error__=[u'Tiden er allerede blokkert']
            )                 

        current_app.db_session.add(weekly_blocked_time)
        current_app.db_session.commit()
        current_app.db_session.refresh(weekly_blocked_time)

        return marshal(weekly_blocked_time, self.fields), 201
示例#10
0
文件: views.py 项目: carfriends/odin
def homepage():
    teams = [t for t in Team.select() if g.user.can(READ,t)]
    if not teams:
        abort(404)
    current_team = get_object_or_404(Team, Team.id == int(
        request.args.get('t'))) if request.args.has_key('t') else teams[0]

    ensure(READ,current_team)

    users = [u for u in User.select().where(User.team == current_team, User.active == True) if g.user.can(READ,u)]
    return render_template("index.html", teams=teams, users=users, active_team=current_team)
    def put(self, soknad_id=None, rapport_id=None):
        data = request.get_json()

        rapport = self.get_by_id(rapport_id)
        if rapport.soknad_id != soknad_id:
            abort(403)

        ensure(PUT, rapport)

        self.validate_put_fields(data)
        rapport = self.repo.save(rapport, data)
        return marshal(rapport, rapport_fields)
    def execute(cls, soknad, action, data):
        try:
            ensure(MANAGE, SoknadAction(soknad, action))
            current_app.logger.debug(
                u"Håndterer action %s på soknad %s i status %s" % (action.name, soknad.id, soknad.status))
            strategy = default_action_strategy

            if action in cls.custom_strategies:
                strategy = cls.custom_strategies[action]

            return strategy(soknad, action, data)
        except InvalidArkivExtensionError as e:
            abort(400, __error__=[e.message])
 def get(self, tilskuddsordning_id=None):
     user = get_user_from_auth()
     if tilskuddsordning_id:
         tilskuddsordning = self.get_by_id(tilskuddsordning_id)
         ensure(GET, tilskuddsordning)
         marshalled = marshal(tilskuddsordning, tilskuddsordning_fields)
         if is_administrator(user) or is_saksbehandler(user) or is_godkjenner(user):
             marshalled["vedtatt_belop"] = self.get_vedtatt_belop(tilskuddsordning_id)
         return marshalled
     else:
         if is_soker(user):
             return marshal(self.repo.find_by_where("publisert", True), tilskuddsordning_fields)
         else:
             return marshal(self.repo.find_all(), tilskuddsordning_fields)
示例#14
0
文件: views.py 项目: carfriends/odin
def save_score(user_id):
    user = get_object_or_404(User, User.id == user_id)
    week = Week.get(Week.id==int(request.form.get("week")))
    ensure(EDIT,user)
    Score.create(
        user = user,
        self_score = request.form.get("score"),
        week_start = week.start,
        week_end = week.end,
        week = week,
        self_memo = request.form.get("self_memo")
        )

    return redirect(url_for('user_detail',user_id=user_id))
    def get(self, soknad_id=None, rapport_id=None):

        if rapport_id:
            rapport = self.get_by_id(rapport_id)
            if rapport.soknad_id != soknad_id:
                abort(403)

            ensure(GET, rapport)
            return marshal(rapport, rapport_fields)
        else:
            if soknad_id:
                rapporter = self.repo.find_by_where("soknad_id", soknad_id)
                return marshal(rapporter, rapport_fields)

        abort(404)
    def post(self):

        rapport_id = request.form.get('rapport_id')
        soknad_id = request.form.get('soknad_id')

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

        ensure(PUT, soknad_or_rapport)

        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_vedlegg_path(soknad_id));

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

        vedlegg = Vedlegg()

        user = get_user_from_auth()
        vedlegg.filnavn = file.filename
        vedlegg.file_ref = filnavn
        vedlegg.user_id = user['id']
        vedlegg.vedlagtdato = datetime.now()

        soknad_or_rapport.vedlegg.append(vedlegg)

        current_app.db_session.commit()

        return Response(response=json.dumps(marshal(vedlegg, vedlegg_fields)),
                        status=201,
                        content_type='text/html')
    def get(self, soknad_id, saksvedlegg_id):

        soknad = SoknadRepo.find_by_id(soknad_id)

        ensure(GET, soknad)

        try:
            saksvedlegg = VedleggRepo.find_by_id(saksvedlegg_id)
            doc_path = "%s/%s" %(DOC_PATH, get_rel_saksvedlegg_path(soknad))

            return send_from_directory(doc_path,
                                       saksvedlegg.file_ref,
                                       as_attachment=True,
                                       attachment_filename=saksvedlegg.filnavn.encode("utf-8"))
        except NotFound:
            abort(400, __error__=['Vedlegg med id %d finnes ikke' % saksvedlegg_id])
    def delete(self, application_id):
        application = self.get_object_by_id(application_id)

        if not application:
            abort(404)

        if application.type != "strotime":
            abort(405)

        ensure(DELETE, application)

        for slot in application.strotime_slots:
            current_app.db_session.delete(slot)

        current_app.db_session.delete(application)
        current_app.db_session.commit()
        return "", 204
    def post(self):
        data = request.get_json()

        user = get_user_from_auth()

        self.validate_post_fields(data)
        soknad = Soknad()
        soknad.status = SoknadStateMachine.s_kladd.id
        soknad.person_id = user["person_id"]

        tilskuddsordning = TilskuddsordningRepo.find_by_id(int(data.get("tilskuddsordning_id")))
        soknad.tilskuddsordning = tilskuddsordning

        ensure(POST, soknad)

        self.repo.save(soknad, data)
        return marshal(soknad, soknad_fields()), 201
    def get(self, soknad_id, action_id=None):
        # hent søknad
        soknad = SoknadRepo.find_by_id(soknad_id)

        ensure(GET, soknad)

        user = get_user_from_auth()
        # filter transitions
        actions = filter_actions(soknad, user)

        if action_id:
            if action_id in actions:
                return marshal(actions[action_id], action_fields)
            else:
                abort(404, __error__=[u"Fant ingen action med id=%s" % action_id])

        return marshal(actions.values(), action_fields)
    def put(self, resource_id=None, resource_uri=None):
        data = request.get_json()

        mandatory_fields = ["auto_approval_allowed", "single_booking_allowed",
                            "repeating_booking_allowed"]
        verify_request_contains_mandatory_fields(data, mandatory_fields)

        resource = self.get_resource(resource_id, resource_uri)
        ensure(PUT, resource)
        # Update the allowed booking types..
        resource.auto_approval_allowed = data["auto_approval_allowed"]
        resource.single_booking_allowed = data["single_booking_allowed"]
        resource.repeating_booking_allowed = data["repeating_booking_allowed"]

        current_app.db_session.add(resource)
        current_app.db_session.commit()
        current_app.db_session.refresh(resource)
        return resource
    def delete(self, application_id):
        application = self.get_object_by_id(application_id)
        ensure(DELETE, application)

        if is_idporten_user(get_user(request.cookies)):
            if application.status == 'Denied':
                abort(400, __error__=[u'Kan ikke slette avviste søknader'])

            if application.status == 'Granted':
                # check that no slot has started
                slots = application.slots
                for slot in slots:
                    start = slot.start_date if hasattr(slot, 'start_date') else slot.start_time.date()
                    if start <= datetime.date.today():
                        abort(400, __error__=[u'Kan ikke slette godkjente søknader når perioden er påbegynt'])

        current_app.db_session.delete(application)
        current_app.db_session.commit()
        return "", 204
示例#23
0
 def _verify_permissions(self, userid, permissions):
     user = Users.query.get(userid)
     with self.app.app_context():
         # can't figure out how to get into logged in app context, so just force a login here
         login_user(user, force=True)
         admin = user.usertypeforsystem.name == 'System Administrator'
         for model_name, operations in permissions.items():
             for operation, permission in operations.items():
                 expected = True
                 try:
                     ensure(operation, model_name)
                 except Unauthorized:
                     expected = False
                 expected = expected or admin
                 self.assertEqual(
                     permission['global'], expected,
                     "Expected permission " + operation + " on " +
                     model_name + " to be " + str(expected))
         # undo the forced login earlier
         logout_user()
示例#24
0
文件: views.py 项目: carfriends/odin
def update_score(user_id,score_id):
    with db.database.transaction():
        score = get_object_or_404(Score, Score.id == score_id)
        ensure(EDIT,score)
        score.rater = auth.get_logged_in_user()
        score.score = request.form.get("score")
        score.memo = request.form.get("memo")
        score.save()
        ScoreHistory.create(
            rater = auth.get_logged_in_user(),
            score = score,
            history = request.form.get("score")
            )
        Score.get_or_create(
            user = g.user,
            week = score.week,
            week_start = score.week_start,
            week_end = score.week_end
            )
    return redirect(url_for('user_detail',user_id=user_id))
 def delete(self, **kwargs):
     blocked_time = self.get_object_by_id(kwargs["id"])
     ensure(DELETE, blocked_time)
     current_app.db_session.delete(blocked_time)
     current_app.db_session.commit()
     return "", 204
    def put(self, slot_id):
        try:
            slot = current_app.db_session.query(RepeatingSlot).filter(RepeatingSlot.id == slot_id).one()
        except NoResultFound:
            abort(404, __error__=[u"No slot found with id %d." % slot_id])

        ensure(PUT, slot)
        args = request.get_json()

        if slot.application.status != 'Granted':
            abort(400, __error__=[u'Kan ikke frigi tid når søknaden ikke er godkjent'])

        if slot.end_date <= date.today():
            abort(400, __error__=[u'Kan ikke frigi allerede brukt tid'])

        repeating_slots = []

        if "release_from_date" in args or "release_to_date" in args:
            release_from_date = parse_date(args["release_from_date"])
            release_to_date = parse_date(args["release_to_date"])

            if release_from_date > release_to_date:
                abort(400, __error__=[u'Startdato er etter sluttdato'])

            if release_from_date <= date.today():
                abort(400, __error__=[u'Kan kun frigi tid frem i tid'])

            if release_from_date <= slot.start_date and release_to_date >= slot.end_date:
                abort(400, __error__=[u'Du kan ikke frigi hele perioden'])

            intervals = [{
                "start": release_from_date - timedelta(days=1),
                "end": release_to_date + timedelta(days=1)
            }]
            periods = self.split_range_by_intervals(slot.start_date, slot.end_date, intervals)
            for period in periods:
                repeating_slots.append(RepeatingSlot(slot.application, slot.week_day,
                                                     period['start'], period['end'],
                                                     slot.start_time, slot.end_time, ))

        if "release_from_time" in args or "release_to_time" in args:
            release_from_time = parse_time(args["release_from_time"])
            release_to_time = parse_time(args["release_to_time"])
            if release_from_time > release_to_time:
                abort(400, __error__=[u'Starttidspunkt er etter slutttidspunkt'])

            if release_from_time <= slot.start_time and release_to_time >= slot.end_time:
                abort(400, __error__=[u'Du kan ikke frigi hele tidsperioden'])

            split_slot = slot
            if slot.start_date <= date.today():
                intervals = [{
                    "start": date.today(),
                    "end": date.today()
                }]
                periods = self.split_range_by_intervals(slot.start_date, slot.end_date, intervals)
                # add period for past
                repeating_slots.append(RepeatingSlot(slot.application, slot.week_day,
                                                     periods[0]['start'], periods[0]['end'],
                                                     slot.start_time, slot.end_time))
                # continue splitting the future
                split_slot = RepeatingSlot(slot.application, slot.week_day,
                                           periods[1]['start'], periods[1]['end'],
                                           slot.start_time, slot.end_time)

            intervals = [{
                "start": release_from_time,
                "end": release_to_time
            }]
            periods = self.split_range_by_intervals(split_slot.start_time, split_slot.end_time, intervals)
            for period in periods:
                repeating_slots.append(RepeatingSlot(split_slot.application, split_slot.week_day,
                                                     split_slot.start_date + timedelta(days=1), split_slot.end_date,
                                                     period['start'], period['end']))

        # Remove old slot if new slots are generated
        if len(repeating_slots) > 0:
            current_app.db_session.delete(slot)

        # Add new slot(s)
        for repeating_slot in repeating_slots:
            current_app.db_session.add(repeating_slot)
        current_app.db_session.commit()

        return repeating_slots, 200
    def post(self):
        data = request.get_json()

        rammetid_to_application = RammetidToApplication(data.get('umbrella_organisation').get('uri'))
        ensure(POST, rammetid_to_application)

        resource = data.get("resource", None)
        if not resource:
            abort(403, __error__=[u'Ressurs er ikke angitt.'])

        resource = get_resource_for_uri(resource['uri'])
        if not resource:
            abort(404, __error__=[u'Ressursen finnes ikke.'])

        if not resource.repeating_booking_allowed:
            abort(403, __error__=[u'Gjentakende lån ikke tillatt'])

        user = get_user(request.cookies)
        person_uri = '/persons/{}'.format(user['person_id'])
        person = get_person_for_uri(person_uri)
        if not person:
            abort(404, __error__=[u'Personen finnes ikke.'])

        # get umbrella member orgs from organisations backend
        umbrella_member_organisations = get_umbrella_organisation_from_web(data.get('umbrella_organisation').get('uri')).get('organisations', [])

        # get local umbrella organisation object
        umbrella_organisation = get_umbrella_organisation_for_uri(data.get('umbrella_organisation').get('uri'))

        text = "Rammetid fordeling"

        applications = []
        organisations = data.get('organisations', None)
        for organisation in organisations:
            organisation_data = organisations[organisation]
            # have to be superuser if the organisation is not public and not copied to booking already
            organisation = get_organisation_for_uri(organisation_data['uri'], cookies=make_superuser_auth_cookie())

            if not organisation:
                abort(404, __error__=[u'Organisasjonen finnes ikke.'])

            if not any(org.get('uri') == organisation_data['uri'] for org in umbrella_member_organisations):
                abort(403, __error__=[u'Organisasjonen hører ikke til paraplyorganisasjonen'])

            application = Application(person, organisation, text, None, resource)
            application.status = 'Granted'

            slots = organisation_data["slots"]
            for slot_data in slots:

                slot = self.parse_slot(slot_data, application)
                slot_request = self.parse_slot_request(slot_data)

                start_date = slot.start_date
                end_date = slot.end_date
                week_day = slot.week_day
                start_time = slot.start_time
                end_time = slot.end_time

                self.validate_start_and_end_times(start_date, end_date, start_time, end_time)

                if not self.has_matching_rammetid(umbrella_organisation.id, start_date, end_date, week_day, start_time, end_time):
                    abort(400, __error__=[u'Ingen rammetid passer'])

                if self.is_conflict_slot_time(resource, start_date, end_date, week_day, start_time, end_time):
                    abort(400, __error__=[u'Tiden du har søkt på er ikke tilgjengelig'])

                if self.is_conflict_blocked_time(resource, start_date, end_date, week_day, start_time, end_time):
                    abort(400, __error__=[u'Tiden du har søkt på er blokkert'])

                application.request_repeating_slot(slot_request)
                application.add_repeating_slot(slot)
            applications.append(application)

        for application in applications:
            current_app.db_session.add(application)
            current_app.db_session.commit()
            current_app.db_session.refresh(application)

        return applications, 201
def slett_action_strategy(soknad, action, data):
    ensure(DELETE, soknad)
    SoknadRepo.delete(soknad)
    def put(self, application_id):
        data = request.get_json()

        application = self.get_object_by_id(application_id)
        ensure(PUT, application)

        status = data.get("status", None)
        resource_uri = data["resource"]["uri"]
        application_message = data.get("message", "")
        to_be_invoiced = data.get("to_be_invoiced", None)
        invoice_amount = data.get("invoice_amount") or None
        if invoice_amount is not None and type(invoice_amount) is not int \
                and not invoice_amount.isdigit():
            abort(400, __error__=[u'Fakturabeløp må være heltall'])
        resource = get_resource_for_uri(resource_uri)
        if not resource:
            abort(404)
        resource_details = get_resource_from_web(application.resource.uri)
        if not resource_details:
            abort(404)

        settings = SettingsResource().get()

        user = get_user(request.cookies)

        # Check that the resource allows the type of application
        if application.get_type() == "single" and not resource.single_booking_allowed:
            abort(403, __error__=[u'Det er ikke mulig å behandle en søknad om engangslån fordi type utlån er deaktivert for lokalet'])

        if application.get_type() == "repeating" and (not resource.repeating_booking_allowed or \
                                                              (resource.repeating_booking_allowed and not settings["repeating_booking_allowed"] and not has_role(user,
                                                                                                                                                                 'flod_saksbehandlere'))):
            abort(403, __error__=[u'Det er ikke mulig å behandle en søknad om fast lån fordi type utlån er deaktivert for lokalet'])

        # The application might have been moved to a different resource.
        application.resource = resource
        if status == "Pending":
            application.amenities = application.requested_amenities
            application.accessibility = application.requested_accessibility
            application.equipment = application.requested_equipment
            application.suitability = application.requested_suitability
            application.facilitators = application.requested_facilitators
        else:
            application.amenities = data.get('amenities')
            application.accessibility = data.get('accessibility')
            application.equipment = data.get('equipment')
            application.suitability = data.get('suitability')
            application.facilitators = data.get('facilitators')

        slot_data = data.get("slots", None)
        if status == "Granted" and not slot_data:
            abort(403, __error__=[u'Tildelt tid mangler'])

        if application.get_type() == "single":
            slots = [parse_single_slot(slot, application) for slot in slot_data]
            application.single_slots = slots
        elif application.get_type() == "repeating":
            slots = [parse_repeating_slot(slot, application) for slot in slot_data]
            application.repeating_slots = slots

        # Check if there are any conflicts
        for slot in slots:
            if application.get_type() == "single":
                start_date = slot.start_time.date()
                end_date = slot.end_time.date()
                week_day = slot.start_time.isoweekday()
                start_time = slot.start_time.time()
                end_time = slot.end_time.time()
            elif application.get_type() == "repeating":
                start_date = slot.start_date
                end_date = slot.end_date
                week_day = slot.week_day
                start_time = slot.start_time
                end_time = slot.end_time

            if application.get_type() == "single":
                self.validate_end_date_of_slot(settings["single_booking_enddate"], end_date.isoformat(), u'engangslån')
            elif application.get_type() == "repeating":
                self.validate_end_date_of_slot(settings["repeating_booking_enddate"], end_date.isoformat(), u'fast lån')

            self.validate_start_and_end_times(start_date, end_date, start_time, end_time)
            if application.is_arrangement or status == "Denied":
                # NOTE: Arrangements trumph all other applications. If we reject an application, we dont nede to
                # check if the time is available...
                pass
            else:
                if self.is_conflict_slot_time(resource, start_date, end_date, week_day, start_time, end_time) or \
                        self.is_conflict_rammetid(resource, start_date, end_date, week_day, start_time, end_time):
                    abort(
                        400,
                        __error__=[u'Tiden du har søkt på er ikke tilgjengelig']
                    )

            if status != "Denied":
                if self.is_conflict_blocked_time(resource, start_date, end_date, week_day, start_time, end_time):
                    abort(
                        400,
                        __error__=[u'Tiden du har søkt på er blokkert']
                    )

        if status == "Granted" or status == "Denied" or (status == "Pending" and len(slots) == 0):
            application.status = status
        else:
            application.status = "Processing"

        application.message = application_message
        application.invoice_amount = invoice_amount
        application.to_be_invoiced = to_be_invoiced
        application.comment = data.get('comment')

        current_app.db_session.add(application)
        current_app.db_session.commit()
        current_app.db_session.refresh(application)

        document = ''
        if status == "Granted" or status == "Denied":
            document = send_email_application_processed(application)

        # Create erv code
        if invoice_amount is not None and status == "Granted":
            invoice_amount = int(invoice_amount)
            org_number = None
            if application.organisation is not None:
                organisation = get_organisation_from_web(
                    application.organisation.uri)
                org_number = organisation.get('org_number', None)

            if org_number is None:
                person = get_person_from_web(application.person.uri)
                erv_code = erv_person(application, invoice_amount,
                                      person['national_identity_number'])
            else:
                erv_code = erv_organisation(application, invoice_amount,
                                            org_number)

            print 'erv: "{}"'.format(erv_code)
            # Skip sending mail for now
            # send_erv_code_mail("{},".format(erv_code))

        application_dict = {}
        if application.get_type() == "single":
            application_dict = marshal(application, single_application_fields)
        elif application.get_type() == "repeating":
            # Authentication is not implemented for all resources yet, so we
            # skip creating sak/journalpost if no auth_token exists
            if status == 'Granted' and 'auth_token' in request.cookies:
                arkiver(application, document)

            application_dict = marshal(application, repeating_application_fields)

        # Include emails in response, if requested
        if data.get("include_emails", False):
            _, granted_message = render_email_template(application, "Granted")
            _, denied_message = render_email_template(application, "Denied")
            application_dict['emails'] = dict(
                granted_message=granted_message,
                denied_message=denied_message
            )

        return application_dict
    def post(self, resource_id = None):
        data = request.get_json()

        # Resource id might also be part of the incoming json.
        resource_uri = None
        if not resource_id:
            resource_uri = data["resource_uri"]

        resource = self.get_resource_with_id_or_uri(resource_id, resource_uri)

        start_time = parse_datetime(data["start_time"])
        end_time = parse_datetime(data["end_time"])
        if data["note"]:
            note = data["note"]
            if not (len(note) <= 50):
                abort(400, __error__=[u'Maks lengde for merknad er 50 tegn'])
        else:
            note= ""

        # Check that the time has correct minute interval, only 30-minute intervals allowed
        invalid_minutes = filter(lambda my_time: my_time.minute not in [0, 30], [start_time, end_time])
        if invalid_minutes:
            abort(400,
                  __error__=[u'Tidene må angis i hele halvtimer']
            )

        blocked_time_interval = BlockedTimeInterval(resource, start_time, end_time, note)
        ensure(POST, blocked_time_interval)

        start_date = start_time.date()
        end_date = end_time.date()
        start_time = start_time.time()
        end_time = end_time.time()

        self.validate_start_and_end_times(start_date, end_date, start_time, end_time)

        # Find out which ISO week days this blocking covers
        week_days = []
        d = start_date
        delta = datetime.timedelta(days=1)
        while d <= end_date:
            week_days.append(d.isoweekday())
            d += delta

        for week_day in week_days:
                #if self.is_conflict_slot_time(resource, start_date, end_date, week_day, start_time, end_time) or \
                #        self.is_conflict_rammetid(resource, start_date, end_date, week_day, start_time, end_time):
                #    abort(
                #        400,
                #        __error__=[u'Tiden er ikke tilgjengelig for blokkering']
                #    )
                if self.is_conflict_blocked_time(resource, start_date, end_date, week_day, start_time, end_time):
                    abort(
                        400,
                        __error__=[u'Tiden er allerede blokkert']
                    )

        current_app.db_session.add(blocked_time_interval)
        current_app.db_session.commit()
        current_app.db_session.refresh(blocked_time_interval)

        return marshal(blocked_time_interval, self.fields), 201