-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshooting_environment_report.R
312 lines (240 loc) · 9.24 KB
/
shooting_environment_report.R
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/local/bin/Rscript
library(tidyverse)
library(lubridate)
library(emayili)
library(rmarkdown)
#library(notifier)
library(odbc)
library(DBI)
library(dplyr)
library(knitr)
# config for automation
config <- read_csv("C:/Users/april.welch/Downloads/config.csv")
recipients <- "april.welch@baltimorecity.gov"
#config$recipient_url
filename <- paste0("shooting_environment_report_", today(), ".nb.html")
analytics_filename <- paste0("performance_analytics_", today(), ".nb.html")
#csv_filename <- paste0("shooting_environment_report_data_", "2020-12-08", ".csv")
# not sure why this is needed to find pandoc
Sys.setenv(RSTUDIO_PANDOC="C:\\Program Files\\Pandoc")
tryCatch({
# connection to sql server
con <-dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = "BALT-SQL-FC",
Database = "CitiStat",
Trusted_Connection = "True",
host = "localhost",
port = 1433)
}, error = function(err) {
# if analytics report fails to render send me an email
print("Please connect to VPN and manually rerun.", title = "Shooting Environment Report")
render_email <- envelope() %>%
emayili::from(config$from_address) %>%
emayili::to(Sys.getenv("april.welch@baltimorecity.gov")) %>%
emayili::subject("Shooting Environment Report: Not Connected to VPN") %>%
emayili::html("Connect to VPN and manually run report script.")
smtp <- server(host = "smtp.gmail.com",
port = 587,
username = config$from_address,
password = config$password)
smtp(render_email)
}
)
message(paste0(Sys.time(), ": Getting crime data from SQL server"))
# part 1 crime query
violent_crime <- tbl(con, "Part1_Crime") %>%
filter(`Crime Date` >= "2020-01-01")
# sr query
#sr <- tbl(con, "CSR") %>%
# filter(`Created Date` >= "2021-02-10")
sr <- dbGetQuery(con, "SELECT [SR ID],
[Service Request Number],
[SR Type],
[Agency],
[Created Date],
[SR Status],
[Status Date],
[Priority],
[Due Date],
[Week Number],
[Street Address],
[Zip Code],
[Neighborhood],
[Latitude],
[Longitude],
[Police District],
[Council District],
[geo_east_west],
[Close Date],
[CHIP ID],
[SF Source],
[Contact Email],
[Borough],
[HashedRecord]
FROM CitiStat.dbo.CSR
Where [Created Date] >= \'2020-01-01\'")
# run queries
violent_crime <- collect(violent_crime)
message(paste0(Sys.time(), ": Crime data retrieved from SQL server"))
sr <- collect(sr)
message(paste0(Sys.time(), ": Service request data retrieved from SQL server"))
# clean up field names in violent crime
names(violent_crime)<-str_replace_all(names(violent_crime), c(" " = "" ))
names(sr)<-str_replace_all(names(sr), c(" " = "" ))
violent_crime <- violent_crime %>%
rename_all(funs(tolower)) %>%
rename(district = "policedistrict")
sr <- sr %>%
rename_all(funs(tolower)) %>%
rename("servicerequestnum" = "servicerequestnumber")
# get date of last crime in table
last_crime <- max(as.Date(violent_crime$crimedate), na.rm = T)
# filter crime down to shootings in last week
shootings <- violent_crime %>%
filter(description %in% c("HOMICIDE", "SHOOTING"),
crimedate <= last_crime - 2,
crimedate >= last_crime - 9)
# get latitude and longitude from geometry
# sr <- sr %>%
# mutate(
# latitude = unlist(map(sr$geometry,1)),
# longitude = unlist(map(sr$geometry,2)))
# Render analytics report ------------------
message(paste0(Sys.time(), ": Starting report render"))
tryCatch({
if (last_crime >= today() - 7){
# render analytics report
rmarkdown::render(
input = "analytics.Rmd",
output_file = analytics_filename,
#output_file = "example.nb.html",
#output_file = "garbage.nb.html",
output_dir = "reports",
clean = T
)
} else {
# send me an email if the data out of date (deprecate)
#notify("Open Baltimore is more than one week out of date. Report not rendered.",
# title = "Shooting Environment Report")
ob_ood_email <- envelope() %>%
emayili::from(config$from_address) %>%
emayili::to(Sys.getenv("CITY_EMAIL")) %>%
emayili::subject("Shooting Environment Report: Open Baltimore Out of Date") %>%
emayili::html("Open Baltimore is more than one week out of date. Contact BPD & BCIT to refresh.")
smtp <- server(host = "smtp.gmail.com",
port = 587,
username = config$from_address,
password = config$password)
smtp(ob_ood_email)
}
}, error = function(err) {
# if analytics report fails to render send me an email
# notify("Analytics report rendering failed. Check logs.", title = "Shooting Environment Report")
render_email <- envelope() %>%
emayili::from(getElement(config, "from_address")) %>%
emayili::to(Sys.getenv("CITY_EMAIL")) %>%
emayili::subject("Shooting Environment Report: Analytics Render Failure") %>%
emayili::html("Analytics report failed to render. Check logs.")
smtp <- server(host = "smtp.gmail.com",
port = 587,
username = config$from_address,
password = config$password)
smtp(render_email)
})
# Render new shooting environment report ---------------
tryCatch({
if (last_crime >= today() - 7){
# render report
rmarkdown::render(
input = "shooting_environment_report.Rmd",
output_file = filename,
#output_file = "example.nb.html",
#output_file = "garbage.nb.html",
output_dir = "reports",
clean = T
)
} else {
# if data out of date send me an email (deprecate)
# notify("Open Baltimore is more than one week out of date. Report not rendered.", title = "Shooting Environment Report")
ob_ood_email <- envelope() %>%
emayili::from(config$from_address) %>%
emayili::to(Sys.getenv("CITY_EMAIL")) %>%
emayili::subject("Shooting Environment Report: Open Baltimore Out of Date") %>%
emayili::html("Open Baltimore is more than one week out of date. Contact BPD & BCIT to refresh.")
smtp <- server(host = "smtp.gmail.com",
port = 587,
username = config$from_address,
password = config$password)
smtp(ob_ood_email)
}
}, error = function(err) {
# if report render fails send me an email
# notify("Report Rendering Failed. Check Logs.", title = "Shooting Environment Report")
render_email <- envelope() %>%
emayili::from(config$from_address) %>%
emayili::to(Sys.getenv("CITY_EMAIL")) %>%
emayili::subject("Shooting Environment Report: Render Failure") %>%
emayili::html("Shooting environment report failed to render. Check logs.")
smtp <- server(host = "smtp.gmail.com",
port = 587,
username = config$from_address,
password = config$password)
smtp(render_email)
})
# Send out new report and analytics report ---------
tryCatch({
if (last_crime >= today() - 7){
#attempt to send email
email_subject <- paste0(
"Shooting Environment Report, ", today()
)
email_message <- read_file("email_message.txt")
csv_filename <- paste0("shooting_environment_report_data_", today(), ".csv")
email <- envelope() %>%
emayili::from(config$from_address) %>%
#emayili::to(guests$email_address) %>%
emayili::to(Sys.getenv("CITY_EMAIL")) %>%
emayili::subject(email_subject) %>%
emayili::html(email_message) %>%
emayili::attachment(
path = paste0("reports/", filename),
type = "text/html") %>%
emayili::attachment(
path = paste0("reports/", analytics_filename),
type = "text/html") %>%
emayili::attachment(
path = paste0("reports/", csv_filename),
type = "text/comma-separated-values")
smtp <- server(host = "ssmtp.gmail.com",
port = 587,
username = config$from_address,
password = config$password)
message(paste0(Sys.time(), ": Attempting email send"))
smtp(email)
message(paste0(Sys.time(), ": Emails sent"))
# notify me on laptop that report is sent
# notify("Report sent.", title = "Shooting Environment Report")
# move files to sent folder for analytics
file.copy(paste0("reports/", csv_filename), "reports/sent/")
file.copy(paste0("reports/", filename), "reports/sent/")
file.copy(paste0("reports/", analytics_filename), "reports/sent/")
file.remove(paste0("reports/", csv_filename))
file.remove(paste0("reports/", filename))
file.remove(paste0("reports/", analytics_filename))
}
}, error = function(err) {
# notification on laptop if email fails
# notify("Report email failed to send.", title = "Shooting Environment Report")
# also try to email me that the email failed
render_email <- envelope() %>%
emayili::from(config$from_address) %>%
emayili::to(config$recipient_url) %>%
emayili::subject("Shooting Environment Report: Email Failure") %>%
emayili::html("Shooting environment email failed to send. Check logs.")
smtp <- server(host = "smtp.gmail.com",
port = 587,
username = config$from_address,
password = config$password)
smtp(render_email)
})