-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1594 lines (1468 loc) · 48.4 KB
/
main.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
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"encoding/csv"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const (
policyWorkers = 3
quoteWorkers = 3
portalWorkers = 3
maxQuoteSz = 5000000
errorLog = "error.log"
historyFile = "prevResults.csv"
checkFile = "prevOutput.csv"
resultFile = "result.csv"
inputFile = "ufcicQuotes.csv"
trnsDtFail = "trnsDtFail.csv"
polNumFail = "polNumFail.csv"
polNoTerms = "polNoTerms.csv"
polMissNewBiz = "polMissNewBiz.csv"
missEffDate = "missEffDate.csv"
badEffDate = "badEffDate.csv"
invTermDup = "invTermDup.csv"
invTerm1stTrns = "invTerm1stTrns.csv"
invTermNoStart = "invTermNoStart.csv"
invTermSubNB = "invTermSubNB.csv"
invTermUnBnd = "invTermUnBnd.csv"
invTermUnBnd2 = "invTermUnBnd2.csv"
invUnbound1 = "invUnbound1.csv"
invUnbound2 = "invUnbound2.csv"
invUnbound3 = "invUnbound3.csv"
invUnbound4 = "invUnbound4.csv"
invUnbound5 = "invUnbound5.csv"
cancelledTerm = "cancelledTerm.csv"
dupCancel = "dupCancel.csv"
tbdQuotes = "tbdQuotes.csv"
invStatus = "invStatus.csv"
)
var (
httpClient http.Client
s3Client *s3.Client
downLoader *manager.Downloader
upLoader *manager.Uploader
exclTrans = []*transType{}
skipExcl = map[string]bool{
"6466799354709": true,
"6467abc92bd49": true,
"64691aaab287a": true,
"655397bd05eb1": true,
}
fixEffDate = map[string]string{
"645bc34d7387d": "2023-06-13",
"6489c2233df36": "2023-07-14",
"64c18d157e02e": "2023-09-06",
"64c2c77b2b9b7": "2023-09-06",
}
fixStatus = map[string]string{
"630d00cc8b34f": "issued",
"6306691e10fa3": "issued",
}
)
type checkTrans struct {
termNumber string
transType string
transNum string
transStatus string
quoteNumber string
active string
inactReas string
allowActs string
convStatus string
failReason string
}
type transType struct {
portalId string
prevPortalId string
acctId string
acctName string
policyNum string
policyBase string
LOB string
effDate time.Time
origEffDate time.Time
expDate time.Time
transEffDate time.Time
createdEffDate time.Time
origCrEffDate time.Time
endorseEffDate time.Time
cancelEffDate time.Time
transStamp time.Time
transType string
transStatus string
origStatus string
lastPLS *PlsItemType
lastQtNum string
sortDate time.Time
notConvReas string
}
func (t *transType) isIssued() bool {
return (t.transStatus == "issued")
}
type transSorter []*transType
func (l transSorter) Len() int { return len(l) }
func (l transSorter) Less(i, j int) bool {
// Order 1st by transEffDate.
if l[i].sortDate.Year() != 1 && l[j].sortDate.Year() != 1 {
if !l[i].sortDate.Equal(l[j].sortDate) {
return l[i].sortDate.Before(l[j].sortDate)
}
}
// Then order by transStamp.
return l[i].transStamp.Before(l[j].transStamp)
}
func (l transSorter) Swap(i, j int) {
tmp := l[i]
l[i] = l[j]
l[j] = tmp
}
type termTrans struct {
isNewBiz bool
isConvPol bool
termEffDate time.Time
renewalTrans transSorter
trans transSorter
}
type termSorter []*termTrans
func (l termSorter) Len() int { return len(l) }
func (l termSorter) Less(i, j int) bool {
// A term starting with New Business will always come before renewal.
if l[i].isNewBiz || l[i].isConvPol || l[i].termEffDate.Before(l[j].termEffDate) {
return true
}
return false
}
func (l termSorter) Swap(i, j int) {
tmp := l[i]
l[i] = l[j]
l[j] = tmp
}
// Manages a policy or the lists of transactions that aren't policies.
type policy struct {
policyBase string
allTrans transSorter
quotes transSorter
firstTermEffDate time.Time
isConv bool
isParseErr bool
terms termSorter
}
func fmtDt(t time.Time) string {
if t.Year() == 1 {
return "N/A"
}
return fmt.Sprintf("%04d-%02d-%02d", t.Year(), t.Month(), t.Day())
}
func fmtTm(t time.Time) string {
if t.Year() == 1 {
return "N/A"
}
return fmt.Sprintf(" %02d:%02d:%02d", t.Hour(), t.Minute(), t.Second())
}
func logToFile(fl, msg string) {
fh, err := os.OpenFile(fl, os.O_APPEND|os.O_WRONLY, 0644)
if os.IsNotExist(err) {
fh, err = os.OpenFile(fl, os.O_CREATE|os.O_WRONLY, 0644)
_ = os.Chmod(fl, 0644)
}
if err != nil {
log.Fatal(fmt.Errorf("Open log file %s failed: %s", fl, err.Error()))
}
if _, err = fh.WriteString(msg); err == nil {
err = fh.Close()
}
if err != nil {
log.Fatal(fmt.Errorf("Write log file %s failed: %s", fl, err.Error()))
}
}
func logPrintf(fl, strFmt string, params ...interface{}) {
logToFile(fl, fmt.Sprintf(strFmt, params...))
}
func parseDate(dt, dtType string, rowNum int) time.Time {
ret := time.Time{}
if dt == "" || dt == "Invalid date" {
return ret
}
delim := "/"
if strings.Contains(dt, "-") {
delim = "-"
}
dtPieces := strings.Split(dt, delim)
if len(dtPieces) != 3 {
//log.Fatal(fmt.Errorf("Invalid %s date %s, line %d", dtType, dt, rowNum))
return ret
}
if len(dtPieces[0]) == 2 {
dtPieces[0] = "20" + dtPieces[0]
}
if len(dtPieces[0]) != 4 || (dtPieces[0])[:2] != "20" {
log.Fatal(fmt.Errorf("Invalid %s date (year) %s, line %d", dtType, dt, rowNum))
}
for pIdx := 1; pIdx <= 2; pIdx++ {
if len(dtPieces[pIdx]) == 1 {
dtPieces[pIdx] = "0" + dtPieces[pIdx]
}
if len(dtPieces[pIdx]) != 2 {
log.Fatal(fmt.Errorf("Invalid %s date (day or month), %s, line %d", dtType, dt, rowNum))
}
}
ret, err := time.Parse("20060102", fmt.Sprintf("%s%s%s", dtPieces[0], dtPieces[1], dtPieces[2]))
if err != nil {
log.Fatal(fmt.Errorf("Invalid %s date (year) %s, line %d, err: %s", dtType, dt, rowNum, err.Error()))
}
return ret
}
func parseTimestamp(ts string, rowNum int) time.Time {
tsInt, err := strconv.Atoi(ts)
if err != nil {
log.Fatal(fmt.Errorf("Invalid timestamp %s, line %d, err: %s", ts, rowNum, err.Error()))
}
ret := time.Unix(int64(tsInt), 0)
year := ret.Year()
if year < 2010 || year > 2030 {
log.Fatal(fmt.Errorf("Invalid timestamp %s, year %d, line %d", ts, year, rowNum))
}
return ret
}
func pullQuotes(transMap map[string]*policy) {
nonPols, haveNonPols := transMap[""]
if haveNonPols {
for _, trans := range nonPols.allTrans {
if trans.transType != "new business" {
continue
}
nonPols.quotes = append(nonPols.quotes, trans)
}
if len(nonPols.quotes) > 0 {
sort.Sort(nonPols.quotes)
}
}
}
func parseAllTerms(transMap map[string]*policy) transSorter {
transMissingPolicyNum := make(transSorter, 0)
numPols := 0
for polNum, pol := range transMap {
if polNum == "" {
continue
}
polBadLog := ""
polBadReas := ""
termEffDates := make(map[string]*termTrans)
// First, check errors, and pull in just the renewal transactions.
for _, trans := range pol.allTrans {
if trans.effDate.Year() == 1 && trans.notConvReas == "" {
polBadLog = missEffDate
polBadReas = "missing effective date"
break
}
if trans.transType != "renewal" {
continue
}
// Check if this is the 1st renewal for this term eff date.
term, haveTerm := termEffDates[fmtDt(trans.effDate)]
if haveTerm {
// Add this renewal transaction to the existing term
term.renewalTrans = append(term.renewalTrans, trans)
sort.Sort(term.renewalTrans)
continue
}
newTerm := &termTrans{
isNewBiz: false,
isConvPol: false,
termEffDate: trans.effDate,
renewalTrans: transSorter{trans},
trans: transSorter{},
}
termEffDates[fmtDt(trans.effDate)] = newTerm
pol.terms = append(pol.terms, newTerm)
}
// Next, pull in the new business transaction if it exists.
for _, trans := range pol.allTrans {
if trans.transType != "new business" {
continue
}
_, haveTerm := termEffDates[fmtDt(trans.effDate)]
if haveTerm || trans.effDate.After(pol.firstTermEffDate) {
/*
polBadLog = badEffDate
polBadReas = fmt.Sprintf("new business must have earliest effective date for policy %s", trans.policyNum)
break
*/
// Per UFCIC-1404, just make new business the earliest, lol
trans.effDate = pol.firstTermEffDate.AddDate(0, 0, -1)
}
newTerm := &termTrans{
isNewBiz: true,
isConvPol: false,
termEffDate: trans.effDate,
renewalTrans: transSorter{},
trans: transSorter{trans},
}
pol.terms = append(pol.terms, newTerm)
}
if polBadLog != "" {
for _, trans := range pol.allTrans {
trans.notConvReas = polBadReas
logPrintf(polBadLog, "%s,%s,%s,%s\n", trans.portalId, trans.acctId, trans.LOB, trans.transType)
}
pol.isParseErr = true
continue
}
// Order the terms for each policy.
sort.Sort(pol.terms)
// Find terms that have only a renewal in deleted/declined and a subsequent renewal terms.
// Per UFCIC-1404, add these to the subsequent term as renewal quotes.
//
fixedRenewalQuotes := false
numTerms := len(pol.terms)
for idx, term := range pol.terms {
if !term.isNewBiz && len(term.trans) == 0 && idx < (numTerms-1) {
isQuoteOnly := true
for _, renewTrans := range term.renewalTrans {
if renewTrans.transStatus != "deleted" && renewTrans.transStatus != "declined" {
isQuoteOnly = false
break
}
}
if isQuoteOnly {
nextTerm := pol.terms[idx+1]
nextTerm.renewalTrans = append(nextTerm.renewalTrans, term.renewalTrans...)
term.renewalTrans = transSorter{}
sort.Sort(nextTerm.renewalTrans)
fixedRenewalQuotes = true
}
}
}
if fixedRenewalQuotes {
newTerms := termSorter{}
for _, chkTerm := range pol.terms {
if len(chkTerm.trans) > 0 || len(chkTerm.renewalTrans) > 0 {
newTerms = append(newTerms, chkTerm)
}
}
pol.terms = newTerms
}
// On the 2nd pass, bring in all the remaining transactions, finding the appropriate term to put them in.
for _, trans := range pol.allTrans {
if trans.transType == "new business" || trans.transType == "renewal" {
continue
}
// Find the matching term, which are sorted by effective date.
matchingTerm := (*termTrans)(nil)
for _, term := range pol.terms {
if trans.effDate.Equal(term.termEffDate) || trans.effDate.After(term.termEffDate) {
matchingTerm = term
}
}
if matchingTerm == nil {
polBadLog = invTermNoStart
polBadReas = "sub trans no trans to start term"
break
}
matchingTerm.trans = append(matchingTerm.trans, trans)
}
if polBadLog != "" {
for _, trans := range pol.allTrans {
trans.notConvReas = polBadReas
logPrintf(polBadLog, "%s,%s,%s,%s\n", trans.portalId, trans.acctId, trans.LOB, trans.transType)
}
pol.isParseErr = true
} else {
// Order the transactions within each term.
for _, term := range pol.terms {
sort.Sort(term.trans)
}
numPols++
}
}
log.Printf("Successfully loaded and ordered all terms and transactions. Num accts: %d\n", numPols)
return transMissingPolicyNum
}
func markConvertibleTerms(transMap map[string]*policy) {
numConv := 0
for polNum, pol := range transMap {
if polNum == "" || pol.isParseErr {
continue
}
if len(pol.terms) == 0 {
logPrintf(polNoTerms, "%s\n", polNum)
failReas[polNum] = "no terms"
continue
}
if !pol.terms[0].isNewBiz || len(pol.terms[0].renewalTrans) > 0 {
pol.terms[0].isConvPol = true
}
//logPrintf("debugTrc.txt", "policy: %s\n", polNum)
isConv := true
for idx, term := range pol.terms {
firstTrans := (*transType)(nil)
// Check if this a renewal term, and verify only one completed renewal transaction.
if len(term.renewalTrans) > 0 {
firstTrans = term.renewalTrans[0]
haveBound := false
isComplete := false
for _, renewTrans := range term.renewalTrans {
if renewTrans.isIssued() {
if haveBound {
logPrintf(invTermDup, "%s,%s,%s\n", renewTrans.LOB, polNum, renewTrans.portalId)
failReas[polNum] = "mult bound renewals same term"
isConv = false
break
}
haveBound = true
if renewTrans.isIssued() {
isComplete = true
}
}
}
if !isConv {
break
}
if !isComplete {
// Make sure incomplete term doesn't have any non-quote transactions.
if len(term.trans) > 0 {
logPrintf(invTermUnBnd, "%s,%s,%s\n", firstTrans.LOB, polNum, firstTrans.portalId)
failReas[polNum] = "incomplete term with sub trans"
isConv = false
break
}
// If unbound term we cannot have future terms.
if idx < len(pol.terms)-1 {
logPrintf(invTermUnBnd2, "%s,%s,%s\n", firstTrans.LOB, polNum, firstTrans.portalId)
failReas[polNum] = "incomplete term preceeds new term"
isConv = false
break
}
}
} else {
firstTrans = term.trans[0]
if firstTrans.transType != "new business" {
logPrintf(invTermNoStart, "%s,%s,%s,%s\n", firstTrans.portalId, firstTrans.acctId, firstTrans.LOB, firstTrans.transType)
failReas[polNum] = "sub trans no trans to start term"
isConv = false
break
}
if !firstTrans.isIssued() && len(term.trans) > 1 {
logPrintf(invTermUnBnd, "%s,%s,%s\n", firstTrans.LOB, polNum, firstTrans.portalId)
failReas[polNum] = "incomplete term with sub trans"
isConv = false
break
}
}
if firstTrans.transType != "new business" && firstTrans.transType != "renewal" {
logPrintf(invTerm1stTrns, "%s,%s,%s\n", firstTrans.LOB, polNum, firstTrans.portalId)
failReas[polNum] = "term does not start with new biz/renew"
isConv = false
break
}
//logPrintf("debugTrc.txt", "Term idx: %d, num trans: %d, term: %v, effDate: %s\n", idx, len(term.trans), *term, fmtDt(term.termEffDate))
// Scan for non-quote transactions and handle cases that require an adjustment to satisfy PLS.
lastTransIdx := len(term.trans) - 1
//logPrintf("debugTrc.txt", "lastTransIdx: %d, term.trans: %v\n", lastTransIdx, term.trans)
for tIdx, trans := range term.trans {
//logPrintf("debugTrc.txt", "trans: %v\n", *trans)
if trans.transType == "cancellation" || trans.transType == "endorsement" {
nextIdx := tIdx + 1
//logPrintf("debugTrc.txt", "nextIdx: %d\n", nextIdx)
if nextIdx > lastTransIdx {
haveNextTerm := (idx < len(pol.terms)-1)
if trans.transType == "endorsement" {
// If the term ends in an endorsement, it must be completed if there is a subsequent term.
if !trans.isIssued() && haveNextTerm && !strings.Contains(trans.transStatus, "-delete") {
logPrintf(invUnbound1, "%s,%s,%s,%s\n", trans.LOB, polNum, trans.portalId, trans.transStatus)
trans.transStatus += "-delete"
}
} else if haveNextTerm {
if !trans.isIssued() {
if !strings.Contains(trans.transStatus, "-delete") {
logPrintf(invUnbound2, "%s,%s,%s,%s\n", trans.LOB, polNum, trans.portalId, trans.transStatus)
trans.transStatus += "-delete"
}
}
}
break
}
laterTrans := term.trans[nextIdx]
if laterTrans.transType == trans.transType {
//logPrintf("debugTrc.txt", "trans and laterTrans match, trans: %v, laterTrans: %v\n", *trans, *laterTrans)
if !trans.isIssued() {
if !strings.Contains(trans.transStatus, "-delete") {
if !laterTrans.isIssued() {
logPrintf(invUnbound3, "%s,%s,%s,%s\n", trans.LOB, polNum, trans.portalId, trans.transStatus)
} else {
logPrintf(invUnbound4, "%s,%s,%s,%s\n", trans.LOB, polNum, trans.portalId, trans.transStatus)
}
trans.transStatus += "-delete"
}
} else if trans.transType == "cancellation" {
logPrintf(dupCancel, "%s,%s,%s,%s\n", trans.LOB, polNum, trans.portalId, trans.transStatus)
failReas[polNum] = "duplicate cancel"
isConv = false
break
}
} else if !trans.isIssued() {
if !strings.Contains(trans.transStatus, "-delete") {
logPrintf(invUnbound5, "%s,%s,%s,%s\n", trans.LOB, polNum, trans.portalId, trans.transStatus)
trans.transStatus += "-delete"
}
} else if trans.transType == "cancellation" {
logPrintf(cancelledTerm, "%s,%s,%s,%s\n", trans.LOB, polNum, trans.portalId, trans.transStatus)
failReas[polNum] = "cancelled term"
isConv = false
break
}
}
}
allTermTrans := transSorter{}
allTermTrans = append(allTermTrans, term.renewalTrans...)
allTermTrans = append(allTermTrans, term.trans...)
for _, trans := range allTermTrans {
if strings.Contains(trans.transStatus, "cancel") || (trans.transType != "renewal" && strings.Contains(trans.transStatus, "declined")) {
if trans.transType == "new business" && trans.transStatus == "cancelled" {
log.Printf("Change cancelled to created for %s\n", trans.portalId)
trans.transStatus = "created"
continue
}
if !strings.Contains(trans.transStatus, "-delete") {
logPrintf(invStatus, "%s,%s,%s,%s,%s\n", trans.LOB, polNum, trans.portalId, trans.transType, trans.transStatus)
trans.transStatus += "-delete"
}
}
}
if !isConv {
//logPrintf("debugTrc.txt", "idx %d, not simp, break\n", idx)
break
}
}
//logPrintf("debugTrc.txt", "Set policy terms from %v, isConv: %v\n", newTerms, isConv)
if isConv {
numConv++
}
pol.isConv = isConv
}
log.Printf("Successfully marked %d policies for conversion.\n", numConv)
}
type PlsItemType struct {
PortalId string `json:"portalId"`
RiskId string `json:"riskId"`
QuoteNumber *string `json:"quoteNumber"`
TransactionType string `json:"transactionType"`
TermNumber string `json:"termNumber"`
TransactionNumber string `json:"transactionNumber"`
TransactionStatus string `json:"transactionStatus"`
Active bool `json:"active"`
InactiveReason *string `json:"inactiveReason"`
AllowableActions []string `json:"allowableActions"`
PolicyView bool `json:"policyView"`
}
type RespDataType struct {
Data []PlsItemType `json:"data"`
}
type RequestType struct {
PortalId *string `json:"id,omitempty"`
LOB *string `json:"lob,omitempty"`
InsuredName *string `json:"insuredName,omitempty"`
RiskId *string `json:"riskId,omitempty"`
QuoteNumber *string `json:"quoteNumber,omitempty"`
ConvPolicyInd *bool `json:"convertedPolicyInd,omitempty"`
MigratePolicyInd *bool `json:"migratePolicyInd,omitempty"`
TransactionStatus *string `json:"transactionStatus,omitempty"`
TermNumber *string `json:"termNumber,omitempty"`
EffDate *string `json:"transactionEffectiveDate,omitempty"`
QtCopyOption *string `json:"quoteCopyOption,omitempty"`
}
func plsCall(method, cmd string, plsReq *RequestType) *RespDataType {
reqJson, err := json.Marshal(plsReq)
if err != nil {
log.Fatal(fmt.Errorf("Failed to marshal PLS request data: %s", err.Error()))
}
//fmt.Printf("Req, cmd %s: %s\n", cmd, string(reqJson))
apiResp := &RespDataType{}
try := 0
for {
try++
if try > 8 {
break
}
if try > 1 {
log.Printf("Sleeping, try: %d\n", try)
time.Sleep(100 * time.Millisecond)
}
//req, err := http.NewRequest(method, "https://pls-dev.clariondoor.com/api/transact/"+cmd, bytes.NewBuffer(reqJson))
req, err := http.NewRequest(method, "https://pls.ldev/api/transact/"+cmd, bytes.NewBuffer(reqJson))
//req, err := http.NewRequest(method, "https://policy-lifecycle-service.clariondoor.com/api/transact/"+cmd, bytes.NewBuffer(reqJson))
if err != nil {
logPrintf(errorLog, "plsCall, NewRequest failed, try %d, req %s, err: %s\n", try, string(reqJson), err.Error())
continue
}
req.Header.Set("Connection", "Keep-Alive")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CLIENT-ID", "demoClient-guid")
//req.Header.Set("X-CLIENT-ID", "9f466ec9-adc2-4910-a3c2-89537a8d4a2a")
//fmt.Printf("Call http do\n")
resp, err := httpClient.Do(req)
if err != nil {
logPrintf(errorLog, "plsCall, Do failed, try %d, req %s, err: %s\n", try, string(reqJson), err.Error())
continue
}
//fmt.Printf("Response status: %s\n", resp.Status)
if !strings.Contains(resp.Status, "200") {
body2, _ := ioutil.ReadAll(resp.Body)
logPrintf(errorLog, "plsCall, Invalid status %s, try %d, req %s, body: %s\n", resp.Status, try, string(reqJson), string(body2))
continue
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logPrintf(errorLog, "plsCall, ReadAll failed, try %d, req %s, err: %s\n", try, string(reqJson), err.Error())
continue
}
defer resp.Body.Close()
//fmt.Printf("Resp: %s\n", string(body))
if err = json.Unmarshal(body, apiResp); err != nil {
logPrintf(errorLog, "plsCall, Unmarshal failed, try %d, req %s, err: %s ,body: %s\n", try, string(reqJson), err.Error(), string(body))
continue
}
time.Sleep(50 * time.Millisecond)
break
}
return apiResp
}
func getBaseReq(portalId, riskId, qtNum, termNum string) *RequestType {
baseReq := &RequestType{
PortalId: &portalId,
}
if termNum != "" {
baseReq.TermNumber = &termNum
baseReq.RiskId = &riskId
baseReq.QuoteNumber = &qtNum
} else {
isTrue := true
baseReq.ConvPolicyInd = &isTrue
baseReq.MigratePolicyInd = &isTrue
baseReq.LOB = &qtNum
}
return baseReq
}
func respFromPortalId(portalId string, allResp *RespDataType, lkp map[string]*transType) *PlsItemType {
currResp := (*PlsItemType)(nil)
for idx := 0; idx < len(allResp.Data); idx++ {
resp := &allResp.Data[idx]
trans, have := lkp[resp.PortalId]
if !have {
fmt.Printf("Failed to locate transaction for portalId: %s", portalId)
}
trans.lastPLS = resp
if resp.QuoteNumber != nil && *resp.QuoteNumber != "" {
trans.lastQtNum = *resp.QuoteNumber
}
if resp.PortalId == portalId {
currResp = resp
}
}
if currResp == nil {
fmt.Printf("Failed to match PLS result item for portalId: %s", portalId)
currResp = &PlsItemType{}
}
return currResp
}
func doNewBizTransaction(t *transType, lkp map[string]*transType) *PlsItemType {
migratePolicy := true
plsReq := &RequestType{
PortalId: &t.portalId,
LOB: &t.LOB,
InsuredName: &t.acctName,
MigratePolicyInd: &migratePolicy,
}
return respFromPortalId(t.portalId, plsCall("POST", "NEW", plsReq), lkp)
}
func doCopyQtTransaction(portalId, riskId, qtNum, termNum string, lkp map[string]*transType) *PlsItemType {
plsReq := getBaseReq(portalId, riskId, qtNum, termNum)
cpSame := "quoteCopyToSame"
plsReq.QtCopyOption = &cpSame
return respFromPortalId(portalId, plsCall("POST", "COPY", plsReq), lkp)
}
func doGenericTransaction(transType, portalId, riskId, qtNum, termNum string, lkp map[string]*transType) *PlsItemType {
plsReq := getBaseReq(portalId, riskId, qtNum, termNum)
return respFromPortalId(portalId, plsCall("POST", transType, plsReq), lkp)
}
func doMarkTransaction(transStatus, portalId, riskId, qtNum, termNum string, transEffDate time.Time, lkp map[string]*transType) *PlsItemType {
plsReq := getBaseReq(portalId, riskId, qtNum, termNum)
// Can we add this here since we can't do it on new biz: MigratePolicyInd: &migratePolicy,
plsReq.TransactionStatus = &transStatus
if transStatus == "Completed" {
transEffDateStr := fmt.Sprintf("%04d-%02d-%02d", transEffDate.Year(), transEffDate.Month(), transEffDate.Day())
plsReq.EffDate = &transEffDateStr
}
return respFromPortalId(portalId, plsCall("POST", "MARK", plsReq), lkp)
}
type finalOutputSorter []*transType
func (l finalOutputSorter) Len() int { return len(l) }
func (l finalOutputSorter) Less(i, j int) bool {
ii := l[i]
jj := l[j]
// Order 1st by policyNum.
if ii.policyNum == "" && jj.policyNum != "" {
return true
} else if ii.policyNum != "" && jj.policyNum == "" {
return false
} else if ii.policyNum < jj.policyNum {
return true
} else if ii.policyNum != jj.policyNum {
return false
}
// Then by effDate.
if ii.effDate.Before(jj.effDate) {
return true
} else if !ii.effDate.Equal(jj.effDate) {
return false
}
// Then by (computed) transEffDate (ie. sortDate).
if ii.sortDate.Year() != 1 && jj.sortDate.Year() != 1 {
if ii.sortDate.Before(jj.sortDate) {
return true
} else if !ii.sortDate.Equal(jj.sortDate) {
return false
}
}
// Finally by transStamp.
return ii.transStamp.Before(jj.transStamp)
}
func (l finalOutputSorter) Swap(i, j int) {
tmp := l[i]
l[i] = l[j]
l[j] = tmp
}
var allTransactions = finalOutputSorter{}
var allTransMap = map[string]*transType{}
var failReas = map[string]string{}
var checkMap = map[string]*checkTrans{}
func updatePortalPls(t *transType) {
// First pull the existing quote from S3. Then we will append/overwrite the _pls property.
quoteBuf := make([]byte, maxQuoteSz)
at := manager.NewWriteAtBuffer(quoteBuf)
actual, err := downLoader.Download(context.TODO(), at, &s3.GetObjectInput{
Bucket: aws.String("quoting-portal"),
Key: aws.String(fmt.Sprintf("xxx/quotes-migrate/%s.json", t.portalId)),
})
if err != nil {
logPrintf(errorLog, "updatePortalPls, Download failed, portalId %s, err: %s\n", t.portalId, err.Error())
return
}
if actual >= maxQuoteSz {
logPrintf(errorLog, "updatePortalPls, Quote would be truncated, portalId %s\n", t.portalId)
return
}
qtData := make(map[string]interface{})
if err = json.Unmarshal(quoteBuf[:actual], &qtData); err != nil {
logPrintf(errorLog, "updatePortalPls, Unmarshal failed, portalId %s, err: %s\n", t.portalId, err.Error())
return
}
if t.createdEffDate.Year() == 1 {
loc, _ := time.LoadLocation("UTC")
t.createdEffDate = time.Date(t.transStamp.Year(), t.transStamp.Month(), t.transStamp.Day(), 0, 0, 0, 0, loc)
qtData["createdDate"] = fmtDt(t.createdEffDate)
}
status, have := qtData["status"].(string)
if have && status == "bound" {
qtData["status"] = "issued"
}
brokerNumber := ""
bStr, have := qtData["brokerNumber"].(string)
if have {
brokerNumber = bStr
}
brokerNameAndNumber := ""
bStr, have = qtData["brokerNameAndNumber"].(string)
if have {
brokerNameAndNumber = bStr
}
if brokerNumber == "" {
_, after, haveCut := strings.Cut(brokerNameAndNumber, "(")
if haveCut {
before, _, haveCut2 := strings.Cut(after, ")")
if haveCut2 {
fmt.Printf("Change brokerNumber to %s\n", before)
qtData["brokerNumber"] = before
}
}
}
// Append the PLS data to the quote, and marshal the data for s3 write.
qtData["_pls"] = t.lastPLS
qtJson, err := json.Marshal(qtData)
if err != nil {
logPrintf(errorLog, "updatePortalPls, Unmarshal failed, portalId %s, err: %s\n", t.portalId, err.Error())
return
}
_, err = upLoader.Upload(context.TODO(), &s3.PutObjectInput{
Body: bytes.NewReader([]byte(qtJson)),
Bucket: aws.String("quoting-portal"),
Key: aws.String(fmt.Sprintf("xxx/quotes-migrate/%s.json", t.portalId)),
})
if err != nil {
logPrintf(errorLog, "updatePortalPls, Upload failed, portalId %s, err: %s\n", t.portalId, err.Error())
}
}
func quotePlsWorker(c *chan *transType, myId int, m *sync.Mutex, numPending *int) {
log.Printf("quotePlsWorker %d starting...\n", myId)
for {
t := <-*c
if t == nil {
break
}
lkpPortalIds := map[string]*transType{t.portalId: t}
log.Printf("Process quote: %s (%d)\n", t.portalId, myId)
resp := doNewBizTransaction(t, lkpPortalIds)
if t.transStatus != "created" {
resp = doMarkTransaction("Rated", t.portalId, resp.RiskId, t.lastQtNum, resp.TermNumber, t.transEffDate, lkpPortalIds)
}
if t.transStatus == "declined" {
_ = doGenericTransaction("DECLINE", t.portalId, resp.RiskId, t.lastQtNum, resp.TermNumber, lkpPortalIds)
}
log.Printf("Quote %s completed processing\n", t.portalId)
m.Lock()
*numPending -= 1
m.Unlock()
}
log.Printf("quotePlsWorker %d finished!\n", myId)
}
func policyPlsWorker(c *chan *policy, myId int, m *sync.Mutex, numPending *int) {
log.Printf("policyPlsWorker %d starting...\n", myId)
for {
pol := <-*c
if pol == nil {
break
}
polNum := pol.policyBase
log.Printf("Process policy: %s (%d)\n", polNum, myId)
riskId := ""
resp := (*PlsItemType)(nil)
lkpPortalIds := make(map[string]*transType)
subTrans := make(transSorter, 0)
for _, term := range pol.terms {
//fmt.Printf("term: %v, resp: %v, polNum: %v\n", term, resp, polNum)
// Handle all of the renewal quotes at once.
if len(term.renewalTrans) > 0 {
// In the 1st pass, just create the quotes.
lastQtNum := ""
for rIdx, renewTrans := range term.renewalTrans {
//fmt.Printf("lastQtNum: %v, renewTrans: %v\n", lastQtNum, renewTrans)
lkpPortalIds[renewTrans.portalId] = renewTrans
if rIdx == 0 {
fakeQtNum := ""
termNum := ""
if term.isConvPol {
fakeQtNum = renewTrans.LOB
} else {
termNum = resp.TermNumber
}
//fmt.Printf("portal: %s, riskId: %s\n", renewTrans.portalId, riskId)
//fmt.Printf("fakeQtNum: %s, termNum: %s\n", fakeQtNum, termNum)
resp = doGenericTransaction("RENEW", renewTrans.portalId, riskId, fakeQtNum, termNum, lkpPortalIds)
riskId = resp.RiskId
if resp.QuoteNumber != nil {
lastQtNum = *resp.QuoteNumber
}
} else {
resp = doCopyQtTransaction(renewTrans.portalId, riskId, lastQtNum, resp.TermNumber, lkpPortalIds)
}
}
// In the 2nd pass, handle declined and expired quotes, or else rate it.
for _, renewTrans := range term.renewalTrans {
if renewTrans.transStatus == "declined" {
resp = doGenericTransaction("DECLINE", renewTrans.portalId, riskId, renewTrans.lastQtNum, resp.TermNumber, lkpPortalIds)
} else if renewTrans.transStatus != "created" {
resp = doMarkTransaction("Rated", renewTrans.portalId, riskId, renewTrans.lastQtNum, resp.TermNumber, renewTrans.transEffDate, lkpPortalIds)
}
}
// In the final pass, bind a single renewal, if applicable.
for _, renewTrans := range term.renewalTrans {
if renewTrans.isIssued() {
resp = doMarkTransaction("Bound", renewTrans.portalId, riskId, renewTrans.lastQtNum, resp.TermNumber, renewTrans.transEffDate, lkpPortalIds)
resp = doMarkTransaction("Completed", renewTrans.portalId, riskId, renewTrans.lastQtNum, resp.TermNumber, renewTrans.transEffDate, lkpPortalIds)
break
}
}
}
for _, trans := range term.trans {
if strings.Contains(trans.transStatus, "-delete") {
trans.lastPLS = nil
continue