-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpinkertons.go
More file actions
492 lines (435 loc) · 14.1 KB
/
pinkertons.go
File metadata and controls
492 lines (435 loc) · 14.1 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package apiary
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
// Activity represents a detective activity from the database
type Activity struct {
ID int `json:"id"`
Source NullString `json:"source"`
Operative NullString `json:"operative"`
Date NullString `json:"date"`
Time NullString `json:"time"`
Duration NullString `json:"duration"`
Activity NullString `json:"activity"`
Mode NullString `json:"mode"`
ActivityNotes NullString `json:"activity_notes"`
Subject NullString `json:"subject"`
Information NullString `json:"information"`
InformationType NullString `json:"information_type"`
Edited NullString `json:"edited"`
EditType NullString `json:"edit_type"`
Locations []Location `json:"locations,omitempty"`
}
// Location represents a location in the database
type Location struct {
ID int `json:"id"`
Locality NullString `json:"locality"`
StreetAddress NullString `json:"street_address"`
LocationName NullString `json:"location_name"`
LocationType NullString `json:"location_type"`
SpecificLocationType NullString `json:"specific_location_type"`
LocationNotes NullString `json:"location_notes"`
Visits NullInt64 `json:"visits"`
Latitude NullFloat64 `json:"latitude"`
Longitude NullFloat64 `json:"longitude"`
}
// NullFloat64 handles nullable float64 values for JSON marshaling
type NullFloat64 struct {
Float64 float64
Valid bool
}
// MarshalJSON marshals a null float64 as null instead of 0
func (v NullFloat64) MarshalJSON() ([]byte, error) {
if v.Valid {
return json.Marshal(v.Float64)
}
return json.Marshal(nil)
}
// UnmarshalJSON unmarshals a null float64 from JSON
func (v *NullFloat64) UnmarshalJSON(data []byte) error {
var x *float64
if err := json.Unmarshal(data, &x); err != nil {
return err
}
if x != nil {
v.Valid = true
v.Float64 = *x
} else {
v.Valid = false
}
return nil
}
// Scan implements the sql.Scanner interface for database scanning
func (v *NullFloat64) Scan(value interface{}) error {
if value == nil {
v.Float64, v.Valid = 0, false
return nil
}
v.Valid = true
switch val := value.(type) {
case float64:
v.Float64 = val
case float32:
v.Float64 = float64(val)
case int64:
v.Float64 = float64(val)
case int:
v.Float64 = float64(val)
case string:
// PostgreSQL numeric type may be returned as string
parsed, err := strconv.ParseFloat(val, 64)
if err != nil {
return fmt.Errorf("cannot parse string %q into NullFloat64: %w", val, err)
}
v.Float64 = parsed
case []byte:
// Handle byte slice (some drivers return numeric as bytes)
parsed, err := strconv.ParseFloat(string(val), 64)
if err != nil {
return fmt.Errorf("cannot parse bytes %q into NullFloat64: %w", val, err)
}
v.Float64 = parsed
default:
return fmt.Errorf("cannot scan %T into NullFloat64", value)
}
return nil
}
// ActivitiesHandler returns a list of all detective activities with location data and optional filtering
// Query parameters:
// - operative: filter by operative name
// - subject: filter by subject name
// - start_date: filter by start date (YYYY-MM-DD)
// - end_date: filter by end date (YYYY-MM-DD)
// - location_id: filter by location ID
// - limit: maximum number of results to return (default: no limit)
func (s *Server) ActivitiesHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
operative := r.URL.Query().Get("operative")
subject := r.URL.Query().Get("subject")
startDate := r.URL.Query().Get("start_date")
endDate := r.URL.Query().Get("end_date")
locationIDStr := r.URL.Query().Get("location_id")
limitStr := r.URL.Query().Get("limit")
// Build query dynamically based on parameters
baseQuery := `
SELECT
a.id, a.source, a.operative, a.date, a.time, a.duration,
a.activity, a.mode, a.activity_notes, a.subject, a.information,
a.information_type, a.edited, a.edit_type
FROM detectives.activities a
WHERE 1=1
`
// Add filters
args := make([]interface{}, 0)
argCount := 1
if operative != "" {
baseQuery += fmt.Sprintf(" AND a.operative = $%d", argCount)
args = append(args, operative)
argCount++
}
if subject != "" {
baseQuery += fmt.Sprintf(" AND a.subject = $%d", argCount)
args = append(args, subject)
argCount++
}
if startDate != "" {
baseQuery += fmt.Sprintf(" AND a.date >= $%d", argCount)
args = append(args, startDate)
argCount++
}
if endDate != "" {
baseQuery += fmt.Sprintf(" AND a.date <= $%d", argCount)
args = append(args, endDate)
argCount++
}
if locationIDStr != "" {
locationID, err := strconv.Atoi(locationIDStr)
if err != nil || locationID <= 0 {
http.Error(w, "Invalid location_id parameter", http.StatusBadRequest)
return
}
baseQuery += fmt.Sprintf(" AND a.id IN (SELECT activity_id FROM detectives.activity_locations WHERE location_id = $%d)", argCount)
args = append(args, locationID)
argCount++
}
baseQuery += " ORDER BY a.date, a.time"
// Add limit if specified
if limitStr != "" {
limit, err := strconv.Atoi(limitStr)
if err != nil || limit <= 0 {
http.Error(w, "Invalid limit parameter", http.StatusBadRequest)
return
}
baseQuery += fmt.Sprintf(" LIMIT $%d", argCount)
args = append(args, limit)
}
baseQuery += ";"
results := make([]Activity, 0)
rows, err := s.DB.Query(context.TODO(), baseQuery, args...)
if err != nil {
log.Println("Error querying activities:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer rows.Close()
for rows.Next() {
var row Activity
err := rows.Scan(
&row.ID, &row.Source, &row.Operative, &row.Date, &row.Time,
&row.Duration, &row.Activity, &row.Mode, &row.ActivityNotes,
&row.Subject, &row.Information, &row.InformationType,
&row.Edited, &row.EditType,
)
if err != nil {
log.Println("Error scanning activity row:", err)
continue
}
results = append(results, row)
}
if err = rows.Err(); err != nil {
log.Println("Error iterating activities:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// Fetch locations for each activity
locationsQuery := `
SELECT
l.id, l.locality, l.street_address, l.location_name,
l.location_type, l.specific_location_type, l.location_notes, l.visits, l.latitude, l.longitude
FROM detectives.locations l
INNER JOIN detectives.activity_locations al ON l.id = al.location_id
WHERE al.activity_id = $1;
`
for i := range results {
results[i].Locations = make([]Location, 0)
locRows, err := s.DB.Query(context.TODO(), locationsQuery, results[i].ID)
if err != nil {
log.Println("Error querying locations for activity", results[i].ID, ":", err)
continue
}
for locRows.Next() {
var loc Location
err := locRows.Scan(
&loc.ID, &loc.Locality, &loc.StreetAddress, &loc.LocationName,
&loc.LocationType, &loc.SpecificLocationType, &loc.LocationNotes, &loc.Visits, &loc.Latitude, &loc.Longitude,
)
if err != nil {
log.Println("Error scanning location row:", err)
continue
}
results[i].Locations = append(results[i].Locations, loc)
}
locRows.Close()
}
response, err := json.Marshal(results)
if err != nil {
log.Println("Error marshaling JSON:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(response))
}
}
// ActivityByIDHandler returns a single activity with its locations
func (s *Server) ActivityByIDHandler() http.HandlerFunc {
activityQuery := `
SELECT
a.id, a.source, a.operative, a.date, a.time, a.duration,
a.activity, a.mode, a.activity_notes, a.subject, a.information,
a.information_type, a.edited, a.edit_type
FROM detectives.activities a
WHERE a.id = $1;
`
locationsQuery := `
SELECT
l.id, l.locality, l.street_address, l.location_name,
l.location_type, l.specific_location_type, l.location_notes, l.visits, l.latitude, l.longitude
FROM detectives.locations l
INNER JOIN detectives.activity_locations al ON l.id = al.location_id
WHERE al.activity_id = $1;
`
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idStr := vars["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid activity ID", http.StatusBadRequest)
return
}
var activity Activity
// Get activity
err = s.DB.QueryRow(context.TODO(), activityQuery, id).Scan(
&activity.ID, &activity.Source, &activity.Operative, &activity.Date,
&activity.Time, &activity.Duration, &activity.Activity, &activity.Mode,
&activity.ActivityNotes, &activity.Subject, &activity.Information,
&activity.InformationType, &activity.Edited, &activity.EditType,
)
if err != nil {
log.Println("Error querying activity:", err)
http.Error(w, "Activity not found", http.StatusNotFound)
return
}
// Get locations for this activity
activity.Locations = make([]Location, 0)
rows, err := s.DB.Query(context.TODO(), locationsQuery, id)
if err != nil {
log.Println("Error querying locations:", err)
} else {
defer rows.Close()
for rows.Next() {
var loc Location
err := rows.Scan(
&loc.ID, &loc.Locality, &loc.StreetAddress, &loc.LocationName,
&loc.LocationType, &loc.SpecificLocationType, &loc.LocationNotes, &loc.Visits, &loc.Latitude, &loc.Longitude,
)
if err != nil {
log.Println("Error scanning location row:", err)
continue
}
activity.Locations = append(activity.Locations, loc)
}
}
response, err := json.Marshal(activity)
if err != nil {
log.Println("Error marshaling JSON:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(response))
}
}
// LocationsHandler returns all locations with coordinates
func (s *Server) LocationsHandler() http.HandlerFunc {
query := `
SELECT
l.id, l.locality, l.street_address, l.location_name,
l.location_type, l.specific_location_type, l.location_notes, l.visits, l.latitude, l.longitude
FROM detectives.locations l
ORDER BY l.locality, l.location_name;
`
return func(w http.ResponseWriter, r *http.Request) {
results := make([]Location, 0)
rows, err := s.DB.Query(context.TODO(), query)
if err != nil {
log.Println("Error querying locations:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer rows.Close()
for rows.Next() {
var row Location
err := rows.Scan(
&row.ID, &row.Locality, &row.StreetAddress, &row.LocationName,
&row.LocationType, &row.SpecificLocationType, &row.LocationNotes, &row.Visits, &row.Latitude, &row.Longitude,
)
if err != nil {
log.Println("Error scanning location row:", err)
continue
}
results = append(results, row)
}
if err = rows.Err(); err != nil {
log.Println("Error iterating locations:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
response, err := json.Marshal(results)
if err != nil {
log.Println("Error marshaling JSON:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(response))
}
}
// OperativesHandler returns a list of unique operatives
func (s *Server) OperativesHandler() http.HandlerFunc {
query := `
SELECT DISTINCT operative
FROM detectives.activities
WHERE operative IS NOT NULL
ORDER BY operative;
`
return func(w http.ResponseWriter, r *http.Request) {
results := make([]string, 0)
rows, err := s.DB.Query(context.TODO(), query)
if err != nil {
log.Println("Error querying operatives:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer rows.Close()
for rows.Next() {
var operative string
err := rows.Scan(&operative)
if err != nil {
log.Println("Error scanning operative:", err)
continue
}
results = append(results, operative)
}
if err = rows.Err(); err != nil {
log.Println("Error iterating operatives:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
response, err := json.Marshal(results)
if err != nil {
log.Println("Error marshaling JSON:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(response))
}
}
// SubjectsHandler returns a list of unique subjects
func (s *Server) SubjectsHandler() http.HandlerFunc {
query := `
SELECT DISTINCT subject
FROM detectives.activities
WHERE subject IS NOT NULL
ORDER BY subject;
`
return func(w http.ResponseWriter, r *http.Request) {
results := make([]string, 0)
rows, err := s.DB.Query(context.TODO(), query)
if err != nil {
log.Println("Error querying subjects:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer rows.Close()
for rows.Next() {
var subject string
err := rows.Scan(&subject)
if err != nil {
log.Println("Error scanning subject:", err)
continue
}
results = append(results, subject)
}
if err = rows.Err(); err != nil {
log.Println("Error iterating subjects:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
response, err := json.Marshal(results)
if err != nil {
log.Println("Error marshaling JSON:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(response))
}
}