Tue, 03 Jan 2023 18:19:40 +0100
simplify project-details view
1 /*
2 * Copyright 2021 Mike Becker. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 *
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
26 package de.uapcore.lightpit.servlet
28 import de.uapcore.lightpit.AbstractServlet
29 import de.uapcore.lightpit.HttpRequest
30 import de.uapcore.lightpit.boolValidator
31 import de.uapcore.lightpit.dao.DataAccessObject
32 import de.uapcore.lightpit.dateOptValidator
33 import de.uapcore.lightpit.entities.*
34 import de.uapcore.lightpit.types.*
35 import de.uapcore.lightpit.viewmodel.*
36 import jakarta.servlet.annotation.WebServlet
37 import java.sql.Date
39 @WebServlet(urlPatterns = ["/projects/*"])
40 class ProjectServlet : AbstractServlet() {
42 init {
43 get("/", this::projects)
44 get("/%project", this::project)
45 get("/%project/issues/%version/%component/", this::project)
46 get("/%project/edit", this::projectForm)
47 get("/-/create", this::projectForm)
48 post("/-/commit", this::projectCommit)
50 get("/%project/versions/", this::versions)
51 get("/%project/versions/%version/edit", this::versionForm)
52 get("/%project/versions/-/create", this::versionForm)
53 post("/%project/versions/-/commit", this::versionCommit)
55 get("/%project/components/", this::components)
56 get("/%project/components/%component/edit", this::componentForm)
57 get("/%project/components/-/create", this::componentForm)
58 post("/%project/components/-/commit", this::componentCommit)
60 get("/%project/issues/%version/%component/%issue", this::issue)
61 get("/%project/issues/%version/%component/%issue/edit", this::issueForm)
62 post("/%project/issues/%version/%component/%issue/comment", this::issueComment)
63 post("/%project/issues/%version/%component/%issue/relation", this::issueRelation)
64 get("/%project/issues/%version/%component/%issue/removeRelation", this::issueRemoveRelation)
65 get("/%project/issues/%version/%component/-/create", this::issueForm)
66 post("/%project/issues/%version/%component/-/commit", this::issueCommit)
67 }
69 private fun projects(http: HttpRequest, dao: DataAccessObject) {
70 val projects = dao.listProjects()
71 val projectInfos = projects.map {
72 ProjectInfo(
73 project = it,
74 versions = dao.listVersions(it),
75 components = emptyList(), // not required in this view
76 issueSummary = dao.collectIssueSummary(it)
77 )
78 }
80 with(http) {
81 view = ProjectsView(projectInfos)
82 navigationMenu = projectNavMenu(projects)
83 styleSheets = listOf("projects")
84 render("projects")
85 }
86 }
88 private fun activeProjectNavMenu(
89 projects: List<Project>,
90 projectInfo: ProjectInfo,
91 selectedVersion: Version? = null,
92 selectedComponent: Component? = null
93 ) =
94 projectNavMenu(
95 projects,
96 projectInfo.versions,
97 projectInfo.components,
98 projectInfo.project,
99 selectedVersion,
100 selectedComponent
101 )
103 private sealed interface LookupResult<T>
104 private class NotFound<T> : LookupResult<T>
105 private data class Found<T>(val elem: T?) : LookupResult<T>
107 private fun <T : HasNode> HttpRequest.lookupPathParam(paramName: String, list: List<T>): LookupResult<T> {
108 val node = pathParams[paramName]
109 return if (node == null || node == "-") {
110 Found(null)
111 } else {
112 val result = list.find { it.node == node }
113 if (result == null) {
114 NotFound()
115 } else {
116 Found(result)
117 }
118 }
119 }
121 private fun obtainProjectInfo(http: HttpRequest, dao: DataAccessObject): ProjectInfo? {
122 val project = dao.findProjectByNode(http.pathParams["project"] ?: "") ?: return null
124 val versions: List<Version> = dao.listVersions(project)
125 val components: List<Component> = dao.listComponents(project)
127 return ProjectInfo(
128 project,
129 versions,
130 components,
131 dao.collectIssueSummary(project)
132 )
133 }
135 private fun sanitizeNode(name: String): String {
136 val san = name.replace(Regex("[/\\\\]"), "-")
137 return if (san.startsWith(".")) {
138 "v$san"
139 } else {
140 san
141 }
142 }
144 private fun feedPath(project: Project) = "feed/${project.node}/issues.rss"
146 private data class PathInfos(
147 val projectInfo: ProjectInfo,
148 val version: Version?,
149 val component: Component?
150 ) {
151 val project = projectInfo.project
152 val issuesHref by lazyOf("projects/${project.node}/issues/${version?.node ?: "-"}/${component?.node ?: "-"}/")
153 }
155 private fun withPathInfo(http: HttpRequest, dao: DataAccessObject): PathInfos? {
156 val projectInfo = obtainProjectInfo(http, dao)
157 if (projectInfo == null) {
158 http.response.sendError(404)
159 return null
160 }
162 val version = when (val result = http.lookupPathParam("version", projectInfo.versions)) {
163 is NotFound -> {
164 http.response.sendError(404)
165 return null
166 }
167 is Found -> {
168 result.elem
169 }
170 }
171 val component = when (val result = http.lookupPathParam("component", projectInfo.components)) {
172 is NotFound -> {
173 http.response.sendError(404)
174 return null
175 }
176 is Found -> {
177 result.elem
178 }
179 }
181 return PathInfos(projectInfo, version, component)
182 }
184 private fun project(http: HttpRequest, dao: DataAccessObject) {
185 withPathInfo(http, dao)?.run {
187 val issues = dao.listIssues(project, version, component)
188 .sortedWith(
189 IssueSorter(
190 IssueSorter.Criteria(IssueSorter.Field.STATUS),
191 IssueSorter.Criteria(IssueSorter.Field.ETA),
192 IssueSorter.Criteria(IssueSorter.Field.UPDATED, false)
193 )
194 )
196 with(http) {
197 pageTitle = project.name
198 view = ProjectDetails(projectInfo, issues, version, component)
199 feedPath = feedPath(project)
200 navigationMenu = activeProjectNavMenu(
201 dao.listProjects(),
202 projectInfo,
203 version,
204 component
205 )
206 styleSheets = listOf("projects")
207 javascript = "project-details"
208 render("project-details")
209 }
210 }
211 }
213 private fun projectForm(http: HttpRequest, dao: DataAccessObject) {
214 if (!http.pathParams.containsKey("project")) {
215 http.view = ProjectEditView(Project(-1), dao.listUsers())
216 http.navigationMenu = projectNavMenu(dao.listProjects())
217 } else {
218 val projectInfo = obtainProjectInfo(http, dao)
219 if (projectInfo == null) {
220 http.response.sendError(404)
221 return
222 }
223 http.view = ProjectEditView(projectInfo.project, dao.listUsers())
224 http.navigationMenu = activeProjectNavMenu(
225 dao.listProjects(),
226 projectInfo
227 )
228 }
229 http.styleSheets = listOf("projects")
230 http.render("project-form")
231 }
233 private fun projectCommit(http: HttpRequest, dao: DataAccessObject) {
234 val project = Project(http.param("id")?.toIntOrNull() ?: -1).apply {
235 name = http.param("name") ?: ""
236 node = http.param("node") ?: ""
237 description = http.param("description") ?: ""
238 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
239 repoUrl = http.param("repoUrl") ?: ""
240 owner = (http.param("owner")?.toIntOrNull() ?: -1).let {
241 if (it < 0) null else dao.findUser(it)
242 }
243 // intentional defaults
244 if (node.isBlank()) node = name
245 // sanitizing
246 node = sanitizeNode(node)
247 }
249 if (project.id < 0) {
250 dao.insertProject(project)
251 } else {
252 dao.updateProject(project)
253 }
255 http.renderCommit("projects/${project.node}")
256 }
258 private fun versions(http: HttpRequest, dao: DataAccessObject) {
259 val projectInfo = obtainProjectInfo(http, dao)
260 if (projectInfo == null) {
261 http.response.sendError(404)
262 return
263 }
265 with(http) {
266 pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.versions")}"
267 view = VersionsView(
268 projectInfo,
269 dao.listVersionSummaries(projectInfo.project)
270 )
271 feedPath = feedPath(projectInfo.project)
272 navigationMenu = activeProjectNavMenu(
273 dao.listProjects(),
274 projectInfo
275 )
276 styleSheets = listOf("projects")
277 javascript = "project-details"
278 render("versions")
279 }
280 }
282 private fun versionForm(http: HttpRequest, dao: DataAccessObject) {
283 val projectInfo = obtainProjectInfo(http, dao)
284 if (projectInfo == null) {
285 http.response.sendError(404)
286 return
287 }
289 val version: Version
290 when (val result = http.lookupPathParam("version", projectInfo.versions)) {
291 is NotFound -> {
292 http.response.sendError(404)
293 return
294 }
295 is Found -> {
296 version = result.elem ?: Version(-1, projectInfo.project.id)
297 }
298 }
300 with(http) {
301 view = VersionEditView(projectInfo, version)
302 feedPath = feedPath(projectInfo.project)
303 navigationMenu = activeProjectNavMenu(
304 dao.listProjects(),
305 projectInfo,
306 selectedVersion = version
307 )
308 styleSheets = listOf("projects")
309 render("version-form")
310 }
311 }
313 private fun obtainIdAndProject(http: HttpRequest, dao: DataAccessObject): Pair<Int, Project>? {
314 val id = http.param("id")?.toIntOrNull()
315 val projectid = http.param("projectid")?.toIntOrNull() ?: -1
316 val project = dao.findProject(projectid)
317 return if (id == null || project == null) {
318 http.response.sendError(400)
319 null
320 } else {
321 Pair(id, project)
322 }
323 }
325 private fun versionCommit(http: HttpRequest, dao: DataAccessObject) {
326 val idParams = obtainIdAndProject(http, dao) ?: return
327 val (id, project) = idParams
329 val version = Version(id, project.id).apply {
330 name = http.param("name") ?: ""
331 node = http.param("node") ?: ""
332 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
333 status = http.param("status")?.let(VersionStatus::valueOf) ?: VersionStatus.Future
334 // TODO: process error messages
335 eol = http.param("eol", ::dateOptValidator, null, mutableListOf())
336 release = http.param("release", ::dateOptValidator, null, mutableListOf())
337 // intentional defaults
338 if (node.isBlank()) node = name
339 // sanitizing
340 node = sanitizeNode(node)
341 }
343 // sanitize eol and release date
344 if (version.status.isEndOfLife) {
345 if (version.eol == null) version.eol = Date(System.currentTimeMillis())
346 } else if (version.status.isReleased) {
347 if (version.release == null) version.release = Date(System.currentTimeMillis())
348 }
350 if (id < 0) {
351 dao.insertVersion(version)
352 } else {
353 dao.updateVersion(version)
354 }
356 http.renderCommit("projects/${project.node}/versions/")
357 }
359 private fun components(http: HttpRequest, dao: DataAccessObject) {
360 val projectInfo = obtainProjectInfo(http, dao)
361 if (projectInfo == null) {
362 http.response.sendError(404)
363 return
364 }
366 with(http) {
367 pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.components")}"
368 view = ComponentsView(
369 projectInfo,
370 dao.listComponentSummaries(projectInfo.project)
371 )
372 feedPath = feedPath(projectInfo.project)
373 navigationMenu = activeProjectNavMenu(
374 dao.listProjects(),
375 projectInfo
376 )
377 styleSheets = listOf("projects")
378 javascript = "project-details"
379 render("components")
380 }
381 }
383 private fun componentForm(http: HttpRequest, dao: DataAccessObject) {
384 val projectInfo = obtainProjectInfo(http, dao)
385 if (projectInfo == null) {
386 http.response.sendError(404)
387 return
388 }
390 val component: Component
391 when (val result = http.lookupPathParam("component", projectInfo.components)) {
392 is NotFound -> {
393 http.response.sendError(404)
394 return
395 }
396 is Found -> {
397 component = result.elem ?: Component(-1, projectInfo.project.id)
398 }
399 }
401 with(http) {
402 view = ComponentEditView(projectInfo, component, dao.listUsers())
403 feedPath = feedPath(projectInfo.project)
404 navigationMenu = activeProjectNavMenu(
405 dao.listProjects(),
406 projectInfo,
407 selectedComponent = component
408 )
409 styleSheets = listOf("projects")
410 render("component-form")
411 }
412 }
414 private fun componentCommit(http: HttpRequest, dao: DataAccessObject) {
415 val idParams = obtainIdAndProject(http, dao) ?: return
416 val (id, project) = idParams
418 val component = Component(id, project.id).apply {
419 name = http.param("name") ?: ""
420 node = http.param("node") ?: ""
421 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
422 color = WebColor(http.param("color") ?: "#000000")
423 description = http.param("description")
424 // TODO: process error message
425 active = http.param("active", ::boolValidator, true, mutableListOf())
426 lead = (http.param("lead")?.toIntOrNull() ?: -1).let {
427 if (it < 0) null else dao.findUser(it)
428 }
429 // intentional defaults
430 if (node.isBlank()) node = name
431 // sanitizing
432 node = sanitizeNode(node)
433 }
435 if (id < 0) {
436 dao.insertComponent(component)
437 } else {
438 dao.updateComponent(component)
439 }
441 http.renderCommit("projects/${project.node}/components/")
442 }
444 private fun issue(http: HttpRequest, dao: DataAccessObject) {
445 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
446 if (issue == null) {
447 http.response.sendError(404)
448 return
449 }
450 renderIssueView(http, dao, issue)
451 }
453 private fun renderIssueView(
454 http: HttpRequest,
455 dao: DataAccessObject,
456 issue: Issue,
457 relationError: String? = null
458 ) {
459 withPathInfo(http, dao)?.run {
460 val comments = dao.listComments(issue)
462 with(http) {
463 pageTitle = "${projectInfo.project.name}: #${issue.id} ${issue.subject}"
464 view = IssueDetailView(
465 issue,
466 comments,
467 project,
468 version,
469 component,
470 dao.listIssues(project),
471 dao.listIssueRelations(issue),
472 relationError
473 )
474 feedPath = feedPath(projectInfo.project)
475 navigationMenu = activeProjectNavMenu(
476 dao.listProjects(),
477 projectInfo,
478 version,
479 component
480 )
481 styleSheets = listOf("projects")
482 javascript = "issue-editor"
483 render("issue-view")
484 }
485 }
486 }
488 private fun issueForm(http: HttpRequest, dao: DataAccessObject) {
489 withPathInfo(http, dao)?.run {
490 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue) ?: Issue(
491 -1,
492 project,
493 )
495 // for new issues set some defaults
496 if (issue.id < 0) {
497 // pre-select component, if available in the path info
498 issue.component = component
500 // pre-select version, if available in the path info
501 if (version != null) {
502 if (version.status.isReleased) {
503 issue.affected = version
504 } else {
505 issue.resolved = version
506 }
507 }
508 }
510 with(http) {
511 view = IssueEditView(
512 issue,
513 projectInfo.versions,
514 projectInfo.components,
515 dao.listUsers(),
516 project,
517 version,
518 component
519 )
520 feedPath = feedPath(projectInfo.project)
521 navigationMenu = activeProjectNavMenu(
522 dao.listProjects(),
523 projectInfo,
524 version,
525 component
526 )
527 styleSheets = listOf("projects")
528 javascript = "issue-editor"
529 render("issue-form")
530 }
531 }
532 }
534 private fun issueComment(http: HttpRequest, dao: DataAccessObject) {
535 withPathInfo(http, dao)?.run {
536 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
537 if (issue == null) {
538 http.response.sendError(404)
539 return
540 }
542 val commentId = http.param("commentid")?.toIntOrNull() ?: -1
543 if (commentId > 0) {
544 val comment = dao.findComment(commentId)
545 if (comment == null) {
546 http.response.sendError(404)
547 return
548 }
549 val originalAuthor = comment.author?.username
550 if (originalAuthor != null && originalAuthor == http.remoteUser) {
551 val newComment = http.param("comment")
552 if (!newComment.isNullOrBlank()) {
553 comment.comment = newComment
554 dao.updateComment(comment)
555 dao.insertHistoryEvent(issue, comment)
556 } else {
557 logger.debug("Not updating comment ${comment.id} because nothing changed.")
558 }
559 } else {
560 http.response.sendError(403)
561 return
562 }
563 } else {
564 val comment = IssueComment(-1, issue.id).apply {
565 author = http.remoteUser?.let { dao.findUserByName(it) }
566 comment = http.param("comment") ?: ""
567 }
568 val newId = dao.insertComment(comment)
569 dao.insertHistoryEvent(issue, comment, newId)
570 }
572 http.renderCommit("${issuesHref}${issue.id}")
573 }
574 }
576 private fun issueCommit(http: HttpRequest, dao: DataAccessObject) {
577 withPathInfo(http, dao)?.run {
578 val issue = Issue(
579 http.param("id")?.toIntOrNull() ?: -1,
580 project
581 ).apply {
582 component = dao.findComponent(http.param("component")?.toIntOrNull() ?: -1)
583 category = IssueCategory.valueOf(http.param("category") ?: "")
584 status = IssueStatus.valueOf(http.param("status") ?: "")
585 subject = http.param("subject") ?: ""
586 description = http.param("description") ?: ""
587 assignee = http.param("assignee")?.toIntOrNull()?.let {
588 when (it) {
589 -1 -> null
590 -2 -> component?.lead
591 else -> dao.findUser(it)
592 }
593 }
594 // TODO: process error messages
595 eta = http.param("eta", ::dateOptValidator, null, mutableListOf())
597 affected = http.param("affected")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
598 resolved = http.param("resolved")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
599 }
601 val openId = if (issue.id < 0) {
602 val id = dao.insertIssue(issue)
603 dao.insertHistoryEvent(issue, id)
604 id
605 } else {
606 val reference = dao.findIssue(issue.id)
607 if (reference == null) {
608 http.response.sendError(404)
609 return
610 }
612 if (issue.hasChanged(reference)) {
613 dao.updateIssue(issue)
614 dao.insertHistoryEvent(issue)
615 } else {
616 logger.debug("Not updating issue ${issue.id} because nothing changed.")
617 }
619 val newComment = http.param("comment")
620 if (!newComment.isNullOrBlank()) {
621 val comment = IssueComment(-1, issue.id).apply {
622 author = http.remoteUser?.let { dao.findUserByName(it) }
623 comment = newComment
624 }
625 val commentid = dao.insertComment(comment)
626 dao.insertHistoryEvent(issue, comment, commentid)
627 }
628 issue.id
629 }
631 if (http.param("more") != null) {
632 http.renderCommit("${issuesHref}-/create")
633 } else {
634 http.renderCommit("${issuesHref}${openId}")
635 }
636 }
637 }
639 private fun issueRelation(http: HttpRequest, dao: DataAccessObject) {
640 withPathInfo(http, dao)?.run {
641 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
642 if (issue == null) {
643 http.response.sendError(404)
644 return
645 }
647 // determine the relation type
648 val type: Pair<RelationType, Boolean>? = http.param("type")?.let {
649 try {
650 if (it.startsWith("!")) {
651 Pair(RelationType.valueOf(it.substring(1)), true)
652 } else {
653 Pair(RelationType.valueOf(it), false)
654 }
655 } catch (_: IllegalArgumentException) {
656 null
657 }
658 }
660 // if the relation type was invalid, send HTTP 500
661 if (type == null) {
662 http.response.sendError(500)
663 return
664 }
666 // determine the target issue
667 val targetIssue: Issue? = http.param("issue")?.let {
668 if (it.startsWith("#") && it.length > 1) {
669 it.substring(1).split(" ", limit = 2)[0].toIntOrNull()
670 ?.let(dao::findIssue)
671 ?.takeIf { target -> target.project.id == issue.project.id }
672 } else {
673 null
674 }
675 }
677 // check if the target issue is valid
678 if (targetIssue == null) {
679 renderIssueView(http, dao, issue, "issue.relations.target.invalid")
680 return
681 }
683 // commit the result
684 dao.insertIssueRelation(IssueRelation(issue, targetIssue, type.first, type.second))
685 http.renderCommit("${issuesHref}${issue.id}")
686 }
687 }
689 private fun issueRemoveRelation(http: HttpRequest, dao: DataAccessObject) {
690 withPathInfo(http, dao)?.run {
691 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
692 if (issue == null) {
693 http.response.sendError(404)
694 return
695 }
697 // determine relation
698 val type = http.param("type")?.let {
699 try {RelationType.valueOf(it)}
700 catch (_:IllegalArgumentException) {null}
701 }
702 if (type == null) {
703 http.response.sendError(500)
704 return
705 }
706 val rel = http.param("to")?.toIntOrNull()?.let(dao::findIssue)?.let {
707 IssueRelation(
708 issue,
709 it,
710 type,
711 http.param("reverse")?.toBoolean() ?: false
712 )
713 }
715 // execute removal, if there is something to remove
716 rel?.run(dao::deleteIssueRelation)
718 // always pretend that the operation was successful - if there was nothing to remove, it's okay
719 http.renderCommit("${issuesHref}${issue.id}")
720 }
721 }
722 }