summaryrefslogtreecommitdiff
path: root/src/main/kotlin/dev/dnpm/etl/processor/web/StatisticsRestController.kt
blob: 3ea9667051406ac27646323ecce69c1c69be2220 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/*
 * This file is part of ETL-Processor
 *
 * Copyright (c) 2023       Comprehensive Cancer Center Mainfranken
 * Copyright (c) 2023-2026  Paul-Christian Volkmer, Datenintegrationszentrum Philipps-Universität Marburg and Contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package dev.dnpm.etl.processor.web

import dev.dnpm.etl.processor.monitoring.RequestStatus
import dev.dnpm.etl.processor.monitoring.RequestType
import dev.dnpm.etl.processor.services.RequestService
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.http.MediaType
import org.springframework.http.codec.ServerSentEvent
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Flux
import reactor.core.publisher.Sinks
import tools.jackson.databind.PropertyNamingStrategies
import tools.jackson.databind.annotation.JsonNaming
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

@RestController
@RequestMapping(path = ["/statistics"])
class StatisticsRestController(
    @param:Qualifier("statisticsUpdateProducer")
    private val statisticsUpdateProducer: Sinks.Many<Any>,
    private val requestService: RequestService,
) {
    private fun statusColor(status: RequestStatus) =
        when (status) {
            RequestStatus.ERROR -> "#FF0000"
            RequestStatus.WARNING -> "#FF8C00"
            RequestStatus.SUCCESS -> "#008000"
            RequestStatus.NO_CONSENT,
            RequestStatus.BLOCKED_INITIAL,
            -> "#004A9D"
            else -> "#708090"
        }

    @GetMapping(path = ["requeststates"])
    fun requestStates(
        @RequestParam(required = false, defaultValue = "false") delete: Boolean,
    ): List<NameValue> {
        val states =
            if (delete) {
                requestService.countDeleteStates()
            } else {
                requestService.countStates()
            }

        return states
            .map {
                NameValue(it.status.toString(), it.count, statusColor(it.status))
            }.sortedByDescending { it.value }
    }

    @GetMapping(path = ["requestslastmonth"])
    fun requestsLastMonth(
        @RequestParam(required = false, defaultValue = "false") delete: Boolean,
    ): List<DateNameValues> {
        val requestType =
            if (delete) {
                RequestType.DELETE
            } else {
                RequestType.MTB_FILE
            }

        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.of("Europe/Berlin"))
        val data =
            requestService
                .findAll()
                .filter { it.type == requestType }
                .filter { it.processedAt.isAfter(Instant.now().minus(30, ChronoUnit.DAYS)) }
                .groupBy { formatter.format(it.processedAt) }
                .map {
                    val requestList =
                        it.value
                            .groupBy { request -> request.status }
                            .map { request -> Pair(request.key, request.value.size) }
                            .toMap()
                    Pair(
                        it.key.toString(),
                        DateNameValues(
                            it.key.toString(),
                            NameValues(
                                error = requestList[RequestStatus.ERROR] ?: 0,
                                warning = requestList[RequestStatus.WARNING] ?: 0,
                                success = requestList[RequestStatus.SUCCESS] ?: 0,
                                noConsent = requestList[RequestStatus.NO_CONSENT] ?: 0,
                                duplication = requestList[RequestStatus.DUPLICATION] ?: 0,
                                blockedInitial = requestList[RequestStatus.BLOCKED_INITIAL] ?: 0,
                                unknown = requestList[RequestStatus.UNKNOWN] ?: 0,
                            ),
                        ),
                    )
                }.toMap()

        return (0L..30L)
            .map { Instant.now().minus(it, ChronoUnit.DAYS) }
            .map { formatter.format(it) }
            .map { DateNameValues(it, data[it]?.nameValues ?: NameValues()) }
            .sortedBy { it.date }
    }

    @GetMapping(path = ["requestpatientstates"])
    fun requestPatientStates(
        @RequestParam(required = false, defaultValue = "false") delete: Boolean,
    ): List<NameValue> {
        val states =
            if (delete) {
                requestService.findPatientUniqueDeleteStates()
            } else {
                requestService.findPatientUniqueStates()
            }

        return states.map {
            NameValue(it.status.toString(), it.count, statusColor(it.status))
        }
    }

    @GetMapping(path = ["events"], produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
    fun updater(): Flux<ServerSentEvent<Any>> =
        statisticsUpdateProducer.asFlux().flatMap {
            Flux.fromIterable(
                listOf(
                    ServerSentEvent
                        .builder<Any>()
                        .event("requeststates")
                        .id("none")
                        .data(this.requestStates(false))
                        .build(),
                    ServerSentEvent
                        .builder<Any>()
                        .event("requestslastmonth")
                        .id("none")
                        .data(this.requestsLastMonth(false))
                        .build(),
                    ServerSentEvent
                        .builder<Any>()
                        .event("requestpatientstates")
                        .id("none")
                        .data(this.requestPatientStates(false))
                        .build(),
                    ServerSentEvent
                        .builder<Any>()
                        .event("deleterequeststates")
                        .id("none")
                        .data(this.requestStates(true))
                        .build(),
                    ServerSentEvent
                        .builder<Any>()
                        .event("deleterequestslastmonth")
                        .id("none")
                        .data(this.requestsLastMonth(true))
                        .build(),
                    ServerSentEvent
                        .builder<Any>()
                        .event("deleterequestpatientstates")
                        .id("none")
                        .data(this.requestPatientStates(true))
                        .build(),
                    ServerSentEvent
                        .builder<Any>()
                        .event("newrequest")
                        .id("none")
                        .data("newrequest")
                        .build(),
                ),
            )
        }
}

data class NameValue(
    val name: String,
    val value: Int,
    val color: String,
)

data class DateNameValues(
    val date: String,
    val nameValues: NameValues,
)

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
data class NameValues(
    val error: Int = 0,
    val warning: Int = 0,
    val success: Int = 0,
    val noConsent: Int = 0,
    val duplication: Int = 0,
    val blockedInitial: Int = 0,
    val unknown: Int = 0,
)