class FinanceChecksNotesAddNoteController {

    @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_NOTES_SECTION')")
    @PostMapping
    public String saveNote(@P("projectId")@PathVariable final Long projectId,
                           @PathVariable final Long organisationId,
                           @Valid @ModelAttribute(FORM_ATTR) FinanceChecksNotesAddNoteForm form,
                           @SuppressWarnings("unused") BindingResult bindingResult,
                           ValidationHandler validationHandler,
                           Model model,
                           UserResource loggedInUser,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        if (postParametersMatchOrigin(request, projectId, organisationId, loggedInUser.getId())) {
            Supplier<String> failureView = () -> {
                List<Long> attachments = loadAttachmentsFromCookie(request, projectId, organisationId);
                FinanceChecksNotesAddNoteViewModel viewModel = populateNoteViewModel(projectId, organisationId, attachments);
                model.addAttribute("model", viewModel);
                model.addAttribute(FORM_ATTR, form);
                return NEW_NOTE_VIEW;
            };

            return validationHandler.failNowOrSucceedWith(failureView, () -> {

                ValidationMessages validationMessages = new ValidationMessages(bindingResult);

                ProjectFinanceResource projectFinance = projectFinanceService.getProjectFinance(projectId, organisationId);

                List<AttachmentResource> attachmentResources = new ArrayList<>();
                List<Long> attachments = loadAttachmentsFromCookie(request, projectId, organisationId);
                attachments.forEach(attachment -> financeCheckService.getAttachment(attachment).ifSuccessful(fileEntry -> attachmentResources.add(fileEntry)));

                PostResource post = new PostResource(null, loggedInUser, form.getNote(), attachmentResources, ZonedDateTime.now());

                List<PostResource> posts = new ArrayList<>();
                posts.add(post);
                NoteResource note = new NoteResource(null, projectFinance.getId(), posts, form.getNoteTitle(), ZonedDateTime.now());
                ServiceResult<Long> result = financeCheckService.saveNote(note);
                validationHandler.addAnyErrors(result);
                return validationHandler.addAnyErrors(validationMessages, fieldErrorsToFieldErrors(), asGlobalErrors()).
                        failNowOrSucceedWith(failureView, () -> {
                            deleteCookies(response, projectId, organisationId);
                            return redirectToNotePage(projectId, organisationId);
                        });
            });
        } else {
            throw new ObjectNotFoundException();
        }
    }

}