/
web.go
1155 lines (1020 loc) · 26.6 KB
/
web.go
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
//TODO: -figure out testing of update pages
import (
"context"
"errors"
"fmt"
"html/template"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
"time"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
"google.golang.org/appengine/user"
)
type ContextHandler struct {
Real func(context.Context, http.ResponseWriter, *http.Request)
}
type client struct {
Firstname string
Lastname string
Address string
Apt string
CrossStreet string
DOB string
Phonenum string
Altphonenum string
Altphonedesc string
Ethnicity string
ReferredBy string
Notes string
Adultmales string
Adultfemales string
Fammbrs []fammbr
Financials financials
}
type fammbr struct {
Name string
DOB string
Female bool
}
type financials struct {
FatherIncome string
MotherIncome string
AFDCIncome string
GAIncome string
SSIIncome string
UnemploymentInsIncome string
SocialSecurityIncome string
AlimonyIncome string
ChildSupportIncome string
Other1Income string
Other1IncomeType string
Other2Income string
Other2IncomeType string
Other3Income string
Other3IncomeType string
RentExpense string
Section8Voucher bool
UtilitiesExpense string
WaterExpense string
PhoneExpense string
FoodExpense string
GasExpense string
CarPaymentExpense string
TVInternetExpense string
GarbageExpense string
Other1Expense string
Other1ExpenseType string
Other2Expense string
Other2ExpenseType string
Other3Expense string
Other3ExpenseType string
TotalExpense string
TotalIncome string
}
type update struct {
User string
When string
}
type visit struct {
Deleted bool
Vincentians string
Visitdate string
Assistancerequested string
Giftcardamt string
Numfoodboxes string
Rentassistance string
Utilitiesassistance string
Waterbillassistance string
Otherassistancetype string
Otherassistanceamt string
Vouchersclothing string
Vouchersfurniture string
Vouchersother string
Comment string
}
type clientrec struct {
Id int64
Clt client
}
type visitrec struct {
Id int64
ClientId int64
Visit visit
}
func (f ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
f.Real(c, w, r)
}
func main() {
http.Handle("/", ContextHandler{homepage})
http.Handle("/clients", ContextHandler{listclientspage})
http.Handle("/client/", ContextHandler{getclientpage})
http.Handle("/editclient/", ContextHandler{editclientpage})
http.Handle("/addclient", ContextHandler{newclientpage})
http.Handle("/recordvisit/", ContextHandler{recordvisitpage})
http.Handle("/editvisit/", ContextHandler{editvisitpage})
http.Handle("/visits", ContextHandler{listvisitsinrangepage})
http.Handle("/visitsbyclient", ContextHandler{listvisitsinrangebyclientpage})
http.Handle("/dedupedvisits", ContextHandler{listdedupedvisitsinrangebyclientpage})
http.Handle("/users", ContextHandler{edituserspage})
http.Handle("/tasks", ContextHandler{listtasks})
http.Handle("/startconversion", ContextHandler{startconversion})
http.Handle("/worker", ContextHandler{processTask})
http.Handle("/api/client", ContextHandler{addclient})
http.Handle("/api/client/", ContextHandler{editclient})
http.Handle("/api/visit/", ContextHandler{visitrouter})
http.Handle("/api/getallclients", ContextHandler{getallclients})
http.Handle("/api/getallvisits/", ContextHandler{getallvisits})
http.Handle("/api/getvisitsinrange/", ContextHandler{getvisitsinrange})
http.Handle("/api/users", ContextHandler{getallusers})
http.Handle("/api/users/edit", ContextHandler{editusers})
appengine.Main()
}
var funcMap = template.FuncMap{"ages": ages,
"girls": numGirls,
"boys": numBoys,
"add": add,
"famSize": famSize,
}
var templates = template.Must(template.New("client").Funcs(funcMap).ParseGlob("*.html"))
func age(dobs string) float64 {
if len(dobs) == 0 {
return 0
}
dob, err := time.Parse("2006-01-02", dobs)
if err != nil {
return -1
}
return time.Since(dob).Hours() / (24.0 * 365.25)
}
func ages(dobs string) string {
return strconv.FormatFloat(age(dobs), 'f', 0, 64)
}
func numBoys(children []fammbr) int {
return len(children) - numGirls(children)
}
func numGirls(children []fammbr) int {
n := 0
for _, child := range children {
if child.Female {
n++
}
}
return n
}
func numMinors(children []fammbr) int {
n := 0
for _, child := range children {
if age(child.DOB) < 18.0 {
n++
}
}
return n
}
func numSeniors(clt client) (num int, err error) {
n := 0
if a := age(clt.DOB); a >= 60.0 {
n++
} else if a == -1.0 {
return 0, errors.New(fmt.Sprintf("unable to compute age from %v", clt.DOB))
}
for _, child := range clt.Fammbrs {
if a := age(child.DOB); a >= 60.0 {
n++
} else if a == -1.0 {
return 0, errors.New(fmt.Sprintf("unable to compute age from %v", child.DOB))
}
}
return n, err
}
func numAdults(clt client) (num int, err error) {
var men, women, seniors int = 0, 0, 0
if clt.Adultmales != "" {
men, err = strconv.Atoi(clt.Adultmales)
if err != nil {
return -1, errors.New(fmt.Sprintf("unable to parse %v",
clt.Adultmales))
}
}
if clt.Adultfemales != "" {
women, err = strconv.Atoi(clt.Adultfemales)
if err != nil {
return -1, errors.New(fmt.Sprintf("unable to parse %v",
clt.Adultfemales))
}
}
if age(clt.DOB) >= 60.0 {
seniors++
}
for _, child := range clt.Fammbrs {
switch childage := age(child.DOB); {
case childage >= 60.0:
seniors++
case childage >= 18.0:
if child.Female {
women++
} else {
men++
}
case childage < 0.0:
return 0, errors.New(fmt.Sprintf("unable to parse %v, got %.1f", child.DOB, childage))
}
}
n := men + women - seniors
if n < 0 {
n = 0
}
return n, nil
}
func famSize(clt client) (num int, err error) {
adults, err := numAdults(clt)
if err != nil {
return 0, err
}
seniors, err := numSeniors(clt)
if err != nil {
return 0, err
}
minors := numMinors(clt.Fammbrs)
return adults + seniors + minors, nil
}
func add(a, b int) int {
return a + b
}
func webuserOK(c context.Context, w http.ResponseWriter, r *http.Request) bool {
if !userauthenticated(c) {
url, err := user.LoginURL(c, r.URL.String())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
}
w.Header().Set("Location", url)
w.WriteHeader(http.StatusFound)
return false
}
u := user.Current(c)
authzed, err := userauthorized(c, u.Email)
if err != nil {
log.Errorf(c, "authorization error: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
}
if !authzed {
log.Warningf(c, "authorization failure: %v", u.Email)
type UnauthInfo struct {
Email string
}
unauthInfo := UnauthInfo{u.Email}
w.WriteHeader(http.StatusForbidden)
err = templates.ExecuteTemplate(w, "unauthorized.html",
unauthInfo)
if err != nil {
log.Errorf(c, "unauthorized user and got err on template: %v", err)
}
return false
}
return true
}
func homepage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
u := user.Current(c)
l, err := user.LogoutURL(c, "http://www.svdpsm.org/")
data := struct {
U, LogoutUrl string
}{
u.Email,
l,
}
err = templates.ExecuteTemplate(w, "home.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
type clientreclist []clientrec
func (c clientreclist) Len() int {
return len(c)
}
func (c clientreclist) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
func (c clientreclist) Less(i, j int) bool {
if strings.ToLower(c[i].Clt.Lastname) != strings.ToLower(c[j].Clt.Lastname) {
return strings.ToLower(c[i].Clt.Lastname) < strings.ToLower(c[j].Clt.Lastname)
} else {
return strings.ToLower(c[i].Clt.Firstname) < strings.ToLower(c[j].Clt.Firstname)
}
}
func listclientspage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
u := user.Current(c)
q := datastore.NewQuery("SVDPClient")
var clients []client
keys, err := q.GetAll(c, &clients)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
clientrecs := make(clientreclist, len(keys))
for i := 0; i < len(clients); i++ {
clientrecs[i].Clt = clients[i]
clientrecs[i].Id = keys[i].IntID()
}
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
sort.Sort(clientrecs)
data := struct {
U, LogoutUrl string
Clients []clientrec
}{
u.Email,
l,
clientrecs,
}
err = templates.ExecuteTemplate(w, "clients.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func getclientpage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
u := user.Current(c)
re, err := regexp.Compile("[0-9]+")
if err != nil {
http.Error(w, "unable to parse regex: "+err.Error(),
http.StatusInternalServerError)
return
}
idstr := re.FindString(r.URL.Path)
if len(idstr) == 0 {
log.Warningf(c, "id missing in path")
http.Error(w, "client id missing in path", http.StatusNotFound)
return
}
clientid, err := strconv.ParseInt(idstr, 10, 64)
if err != nil {
log.Warningf(c, "got error %v trying to parse id %v\n", err, clientid)
http.Error(w, "error parsing client id "+idstr+
" ("+err.Error()+")", http.StatusInternalServerError)
return
}
key := datastore.NewKey(c, "SVDPClient", "", clientid, nil)
var clt client
err = datastore.Get(c, key, &clt)
if err != nil {
log.Warningf(c, "got error %v on datastore get for key %v\n", err,
key)
http.Error(w, "unable to find client",
http.StatusNotFound)
return
}
q := datastore.NewQuery("SVDPClientVisit").
Ancestor(key).
Filter("Deleted =", false).
Order("-Visitdate")
var visits []visit
visitkeys, err := q.GetAll(c, &visits)
if err != nil {
log.Warningf(c, "got error %v on datastore get for visits with key %v\n", err,
key)
http.Error(w, fmt.Sprintf("unable to find visits for key %v, got %v", key, err),
http.StatusInternalServerError)
return
}
vstrecs := make([]visitrec, len(visitkeys))
for i, v := range visits {
vstrecs[i].Id = visitkeys[i].IntID()
//not populating ClientId because they're all the same and we know it from client
vstrecs[i].Visit = v
}
q = datastore.NewQuery("SVDPUpdate").Ancestor(key).Order("-When")
var updates []update
_, err = q.GetAll(c, &updates)
if err != nil {
log.Warningf(c, "got error %v on datastore get for updates with key %v\n", err,
key)
http.Error(w, "unable to find updates",
http.StatusInternalServerError)
return
}
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
data := struct {
U, LogoutUrl string
Clientrec clientrec
Visitrecs []visitrec
Updates []update
}{
u.Email,
l,
clientrec{clientid, clt},
vstrecs,
updates,
}
err = templates.ExecuteTemplate(w, "client.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func newclientpage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
u := user.Current(c)
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
clt := client{}
data := struct {
U, LogoutUrl string
Clientrec clientrec
}{
u.Email,
l,
clientrec{0, clt},
}
err := templates.ExecuteTemplate(w, "newclient.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func editclientpage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
u := user.Current(c)
re, err := regexp.Compile("[0-9]+")
if err != nil {
http.Error(w, "unable to parse regex: "+err.Error(),
http.StatusNotFound)
return
}
idstr := re.FindString(r.URL.Path)
id, err := strconv.ParseInt(idstr, 10, 64)
if err != nil {
log.Warningf(c, "got error %v trying to parse id %v\n", err, id)
http.Error(w, "unable to find client", http.StatusNotFound)
return
}
key := datastore.NewKey(c, "SVDPClient", "", id, nil)
var clt client
err = datastore.Get(c, key, &clt)
if err != nil {
log.Warningf(c, "got error %v on datastore get for key %v\n", err,
key)
http.Error(w, "unable to find client",
http.StatusNotFound)
return
}
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
data := struct {
U, LogoutUrl string
Clientrec clientrec
}{
u.Email,
l,
clientrec{id, clt},
}
err = templates.ExecuteTemplate(w, "editclient.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func recordvisitpage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
u := user.Current(c)
re, err := regexp.Compile("[0-9]+")
idstr := re.FindString(r.URL.Path)
clientid, err := strconv.ParseInt(idstr, 10, 64)
if err != nil {
http.Error(w, "Invalid/missing client id ", http.StatusBadRequest)
return
}
clientkey := datastore.NewKey(c, "SVDPClient", "", clientid, nil)
clt := client{}
err = datastore.Get(c, clientkey, &clt)
if err == datastore.ErrNoSuchEntity {
http.Error(w, "Unable to find client with id "+idstr,
http.StatusNotFound)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
vst := visit{}
data := struct {
U, LogoutUrl string
Client client
Visit visit
Updates []update
}{
u.Email,
l,
clt,
vst,
nil,
}
err = templates.ExecuteTemplate(w, "recordvisit.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func editvisitpage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
u := user.Current(c)
re, err := regexp.Compile(`^/editvisit/([0-9]+)/([0-9]+)/edit$`)
matches := re.FindSubmatch([]byte(r.URL.Path))
if matches == nil {
http.Error(w,
fmt.Sprintf("id is missing in path for update request %v", r.URL.Path),
http.StatusBadRequest)
return
}
cltidstr := string(matches[1])
vstidstr := string(matches[2])
log.Debugf(c, "parsed id clt %v, vst %v from %v", cltidstr, vstidstr, r.URL.Path)
if cltidstr == "" {
log.Errorf(c, "cltid is missing for update request: path %v",
r.URL.Path)
http.Error(w,
fmt.Sprintf("id is missing in path for update request %v", r.URL.Path),
http.StatusBadRequest)
return
}
if vstidstr == "" {
log.Errorf(c, "vstid is missing for update request: path %v",
r.URL.Path)
http.Error(w,
fmt.Sprintf("id is missing in path for update request %v", r.URL.Path),
http.StatusBadRequest)
return
}
cltid, err := strconv.ParseInt(cltidstr, 10, 64)
if err != nil {
log.Errorf(c, "unable to parse id %v as int64: %v", cltid, err.Error())
http.Error(w,
fmt.Sprintf("unable to parse id %v as int64: %v", cltid,
err.Error()),
http.StatusBadRequest)
return
}
vstid, err := strconv.ParseInt(vstidstr, 10, 64)
if err != nil {
log.Errorf(c, "unable to parse vst id %v as int64: %v", vstid, err.Error())
http.Error(w,
fmt.Sprintf("unable to parse id %v as int64: %v", vstid,
err.Error()),
http.StatusBadRequest)
return
}
clientkey := datastore.NewKey(c, "SVDPClient", "", cltid, nil)
clt := client{}
err = datastore.Get(c, clientkey, &clt)
if err == datastore.ErrNoSuchEntity {
http.Error(w, "Unable to find client with id "+cltidstr,
http.StatusNotFound)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
visitkey := datastore.NewKey(c, "SVDPClientVisit", "", vstid, clientkey)
vst := visit{}
err = datastore.Get(c, visitkey, &vst)
if err == datastore.ErrNoSuchEntity {
http.Error(w, "Unable to find visit with id "+vstidstr,
http.StatusNotFound)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var updates []update
q := datastore.NewQuery("SVDPUpdate").Ancestor(visitkey).Order("-When")
_, err = q.GetAll(c, &updates)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := struct {
U, LogoutUrl string
Client client
Visit visit
Updates []update
}{
u.Email,
l,
clt,
vst,
updates,
}
err = templates.ExecuteTemplate(w, "editvisit.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func edituserspage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
u := user.Current(c)
admin, err := useradmin(c, u.Email)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !admin {
http.Error(w, "must be admin to access users page",
http.StatusForbidden)
return
}
q := datastore.NewQuery("SVDPUser").Order("Email")
var users []appuser
keys, err := q.GetAll(c, &users)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var resp useredit
resp.Aus = make([]appuser, len(keys))
resp.Ids = make([]int64, len(keys))
for i := range keys {
resp.Aus[i] = users[i]
resp.Ids[i] = keys[i].IntID()
}
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
var updates []update
q = datastore.NewQuery("SVDPUserUpdate").Order("-When")
keys, err = q.GetAll(c, &updates)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Infof(c, "UserUpdates %v", updates)
data := struct {
U, LogoutUrl string
Users useredit
Updates []update
}{
u.Email,
l,
resp,
updates,
}
err = templates.ExecuteTemplate(w, "users.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func listvisitsinrangepage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
start := r.FormValue("startdate")
end := r.FormValue("enddate")
csv := r.FormValue("csv")
log.Infof(c, "looking for visits between %v and %v; csv=%v", start, end, csv)
u := user.Current(c)
q := datastore.NewQuery("SVDPClientVisit").
Filter("Visitdate <=", end).
Filter("Visitdate >=", start).
Filter("Deleted =", false).
Order("-Visitdate")
var visits []visit
keys, err := q.GetAll(c, &visits)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
cltmap := map[int64]string{}
log.Infof(c, "got ids %v", keys)
visitrecs := make([]visitrec, len(keys))
for i, vst := range visits {
visitrecs[i].Visit = vst
visitrecs[i].Id = keys[i].IntID()
cltkey := keys[i].Parent()
if cltkey == nil { //this should never happen but...
log.Errorf(c, "cltkey nil for visit %v", keys[i])
break
}
visitrecs[i].ClientId = cltkey.IntID()
var clt client
err = datastore.Get(c, cltkey, &clt)
if err != nil {
log.Warningf(c, "unable to retrieve client with key %v for visit with key %v",
cltkey.String(), keys[i].String())
}
cltmap[visitrecs[i].ClientId] = clt.Lastname + ", " + clt.Firstname
}
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
data := struct {
U, LogoutUrl string
Visits []visitrec
Cltmap map[int64]string
Start string
End string
}{
u.Email,
l,
visitrecs,
cltmap,
start,
end,
}
if csv == "true" {
w.Header().Set("Content-Type", "text/csv")
err = txttemplates.ExecuteTemplate(w, "visits.csv", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
err = templates.ExecuteTemplate(w, "visits.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
type visitlist []visit
func (v visitlist) Len() int {
return len(v)
}
func (v visitlist) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
}
func (v visitlist) Less(i, j int) bool {
return v[i].Visitdate < v[j].Visitdate
}
type vstsbyclt struct {
ClientId int64
Name string
Visits visitlist
}
type cltvsts []vstsbyclt
func (c cltvsts) Len() int {
return len(c)
}
func (c cltvsts) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
func (c cltvsts) Less(i, j int) bool {
return strings.ToLower(c[i].Name) < strings.ToLower(c[j].Name)
}
func listvisitsinrangebyclientpage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return
}
start := r.FormValue("startdate")
end := r.FormValue("enddate")
csv := r.FormValue("csv")
log.Infof(c, "looking for visits between %v and %v; csv=%v", start, end, csv)
u := user.Current(c)
q := datastore.NewQuery("SVDPClientVisit").
Filter("Visitdate <=", end).
Filter("Visitdate >=", start).
Filter("Deleted =", false)
var visits []visit
keys, err := q.GetAll(c, &visits)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
cltmap := map[int64]*vstsbyclt{}
log.Infof(c, "got ids %v", keys)
visitrecs := make([]visitrec, len(keys))
for i, vst := range visits {
visitrecs[i].Visit = vst
visitrecs[i].Id = keys[i].IntID()
cltkey := keys[i].Parent()
if cltkey == nil { //this should never happen but...
log.Errorf(c, "cltkey nil for visit %v", keys[i])
break
}
visitrecs[i].ClientId = cltkey.IntID()
var clt client
err = datastore.Get(c, cltkey, &clt)
if err != nil {
log.Warningf(c, "unable to retrieve client with key %v for visit with key %v",
cltkey.String(), keys[i].String())
}
var rec *vstsbyclt
rec, ok := cltmap[visitrecs[i].ClientId]
log.Debugf(c, "rec=%p/%v, ok=%v, cltmap=%v", rec, rec, ok, cltmap)
if !ok {
rec = new(vstsbyclt)
rec.ClientId = visitrecs[i].ClientId
rec.Name = clt.Lastname + ", " + clt.Firstname
cltmap[visitrecs[i].ClientId] = rec
}
rec.Visits = append(rec.Visits, vst)
log.Debugf(c, "rec=%v, cltmap=%v", rec, cltmap)
}
log.Debugf(c, "cltmao=%v", cltmap)
var cv cltvsts
for _, clt := range cltmap {
sort.Sort(clt.Visits)
cv = append(cv, *clt)
log.Debugf(c, "appended to cltmap")
}
log.Debugf(c, "unsorted: cv=%v", cv)
sort.Sort(cv)
log.Debugf(c, "sorted: cv=%v", cv)
l, _ := user.LogoutURL(c, "http://www.svdpsm.org/")
data := struct {
U, LogoutUrl string
CV cltvsts
Start string
End string
}{
u.Email,
l,
cv,
start,
end,
}
if csv == "true" {
w.Header().Set("Content-Type", "text/csv")
err = txttemplates.ExecuteTemplate(w, "visitsbyclient.csv", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
err = templates.ExecuteTemplate(w, "visitsbyclient.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
type family struct {
Id int64
Name string
Address string
Adults int
Seniors int
Minors int
FamilySize int
}
type families []family
func (f families) Len() int {
return len(f)
}
func (f families) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}
func (f families) Less(i, j int) bool {
return strings.ToLower(f[i].Name) < strings.ToLower(f[j].Name)
}
func listdedupedvisitsinrangebyclientpage(c context.Context, w http.ResponseWriter, r *http.Request) {
if !webuserOK(c, w, r) {
return