-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculate.go
More file actions
1880 lines (1792 loc) · 49.3 KB
/
Copy pathcalculate.go
File metadata and controls
1880 lines (1792 loc) · 49.3 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
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 calculate
import (
"encoding/csv"
"errors"
"flag"
"fmt"
"log/slog"
"math"
"os"
"path/filepath"
"sort"
"strings"
"time"
"cto-stats/connectors/config"
lo "github.com/samber/lo"
)
// Row models for reading CSVs
type issueRow struct {
Org string
Repo string
Number string
Title string
Type string
IsBug bool
CreatedAt time.Time
}
type statusEventRow struct {
Org string
Repo string
Number string
Type string // opened|closed|reopened
At time.Time
}
type projectEventRow struct {
Org string
Repo string
Number string
ProjectID string
ProjectName string
ToColumn string
At time.Time
EventType string // added|moved|removed
}
// Output row
type calculatedIssue struct {
ID string
Name string
ProjectID string
ProjectName string
CreationDatetime time.Time
LeadTimeStartDatetime *time.Time
CycleTimeStartDatetime *time.Time
PutInReadyStartDatetime *time.Time
DevStartDatetime *time.Time
ReviewStartDatetime *time.Time
QAStartDatetime *time.Time
WaitingToPodStartDatetime *time.Time
EndDatetime *time.Time
Bug bool
Type string
CurrentColumn string
}
// Run executes the calculate command
func Run(args []string) error {
fs := flag.NewFlagSet("calculate", flag.ContinueOnError)
issuesScope := fs.Bool("issues", false, "Process issues scope: calculate issue-based KPIs (cycle time, throughput, stocks)")
prScope := fs.Bool("pr", false, "Process pull-requests scope: change-requests KPIs only")
cloudSpendingScope := fs.Bool("cloudspending", false, "Process cloud spending scope: aggregate cost data")
if err := fs.Parse(args); err != nil {
return err
}
// Cloud spending scope is independent
if *cloudSpendingScope {
return runCloudSpendingCalculate()
}
// Backward compatibility: if no scope specified, process both
if !*issuesScope && !*prScope {
*issuesScope = true
*prScope = true
}
// Read config path from environment variable CONFIG_PATH; default to ./config.yml
cfgPath := os.Getenv("CONFIG_PATH")
if cfgPath == "" {
cfgPath = "./config.yml"
}
var projCfgByID map[string]config.Project
projCfgByID = map[string]config.Project{}
if *issuesScope {
// For issues calculations, a config file is required for project mappings
if _, err := os.Stat(cfgPath); err != nil {
return fmt.Errorf("calculate: config file required for --issues (set CONFIG_PATH or provide ./config.yml): %w", err)
}
cfg, err := config.Load(cfgPath)
if err != nil {
return fmt.Errorf("calculate: failed to load config: %w", err)
}
// Build a project lookup by ID for quick access
for _, p := range cfg.GitHub.Projects {
projCfgByID[p.ID] = p
}
}
// Read inputs from data/
base := "data"
var (
issues map[string]issueRow
statusByID map[string][]statusEventRow
projByID map[string][]projectEventRow
)
var err error
if *issuesScope {
issues, err = readIssues(filepath.Join(base, "issue.csv"))
if err != nil {
return err
}
statusByID, err = readStatus(filepath.Join(base, "issue_status_event.csv"))
if err != nil {
return err
}
projByID, err = readProject(filepath.Join(base, "issue_project_event.csv"))
if err != nil {
return err
}
}
// Build output
var allIssues []calculatedIssue
if *issuesScope {
for id, is := range issues {
projEvents := projByID[id]
st := statusByID[id]
row := calculatedIssue{
ID: id,
Name: is.Title,
CreationDatetime: is.CreatedAt,
Bug: is.IsBug,
Type: is.Type,
}
// Determine project on first project event if any
var pid, pname string
if len(projEvents) > 0 {
pid = projEvents[0].ProjectID
pname = projEvents[0].ProjectName
row.ProjectID = pid
row.ProjectName = pname
}
// Apply config filters if project known and present in config
if pc, ok := projCfgByID[pid]; ok {
if pc.Exclude {
continue
}
if len(pc.Types) > 0 {
// case-insensitive compare
allowed := false
for _, t := range pc.Types {
if strings.EqualFold(strings.TrimSpace(t), strings.TrimSpace(is.Type)) {
allowed = true
break
}
}
if !allowed {
continue
}
}
// Use configured columns for stage timestamps
choose := func(cols []string) *time.Time {
if len(cols) > 0 {
return firstMoveToAny(projEvents, cols)
}
return nil
}
row.LeadTimeStartDatetime = choose(pc.LeadTimeColumns)
row.CycleTimeStartDatetime = choose(pc.CycleTimeColumns)
row.PutInReadyStartDatetime = choose(pc.PutInReadyColumns)
row.DevStartDatetime = choose(pc.DevStartColumns)
row.ReviewStartDatetime = choose(pc.ReviewStartColumns)
row.QAStartDatetime = choose(pc.QAStartColumns)
row.WaitingToPodStartDatetime = choose(pc.WaitingToProdStartCols)
// End datetime: by default earliest of status closed and configured inprod columns (e.g., Archive/Done)
var endCandidates []*time.Time
if e := choose(pc.InProdStartColumns); e != nil {
endCandidates = append(endCandidates, e)
}
// closed status
if ev, ok := lo.Find(st, func(s statusEventRow) bool { return s.Type == "closed" }); ok {
end := ev.At
endCandidates = append(endCandidates, &end)
}
row.EndDatetime = earliest(endCandidates)
if row.EndDatetime != nil {
if row.CycleTimeStartDatetime == nil {
row.CycleTimeStartDatetime = row.LeadTimeStartDatetime
}
if row.DevStartDatetime == nil {
row.DevStartDatetime = row.LeadTimeStartDatetime
}
}
} else {
slog.Info("calculate.project_unknown", "issue_id", id, "id", pid, "name", pname, "type", is.Type, "events", projEvents, "status", st)
// No matching project in config: fallback to legacy behavior
row.LeadTimeStartDatetime = firstMoveToAny(projEvents, []string{"Backlog", "Ready"})
row.CycleTimeStartDatetime = firstMoveToAny(projEvents, []string{"In Progress", "In progress"})
if row.CycleTimeStartDatetime == nil {
row.CycleTimeStartDatetime = firstMoveToAny(projEvents, []string{"Backlog", "Ready"})
}
row.DevStartDatetime = firstMoveToAny(projEvents, []string{"In Progress", "In progress"})
if row.DevStartDatetime == nil {
row.DevStartDatetime = firstMoveToAny(projEvents, []string{"Backlog", "Ready"})
}
row.ReviewStartDatetime = firstMoveToAny(projEvents, []string{"In review", "In Review"})
row.QAStartDatetime = nil
row.PutInReadyStartDatetime = firstMoveToAny(projEvents, []string{"Ready", "In Ready", "Ready for Dev"})
row.WaitingToPodStartDatetime = firstMoveTo(projEvents, "Done")
row.EndDatetime = computeEnd(st, projEvents)
}
allIssues = append(allIssues, row)
}
// Deterministic order
sort.Slice(allIssues, func(i, j int) bool { return allIssues[i].ID < allIssues[j].ID })
// Build convenience slices using lo
closedIssues := lo.Filter(allIssues, func(ci calculatedIssue, _ int) bool { return ci.EndDatetime != nil })
openIssues := lo.Filter(allIssues, func(ci calculatedIssue, _ int) bool { return ci.EndDatetime == nil })
if err := writeOutput(filepath.Join(base, "calculated_issue.csv"), allIssues); err != nil {
return err
}
// Step 2: calculate monthly lead time and cycle time in days, using all issues with an EndDatetime
if err := writeMonthlyCycleSummary(filepath.Join(base, "cycle_time.csv"), closedIssues); err != nil {
return err
}
// Step 3: weekly throughput with Shewhart control limits (c-chart)
if err := writeWeeklyThroughput(filepath.Join(base, "throughput_week.csv"), closedIssues); err != nil {
return err
}
// Step 4: current stocks for not-closed issues by stage
if err := writeStocks(filepath.Join(base, "stocks.csv"), openIssues); err != nil {
return err
}
// Step 5: weekly stocks per project by ISO year-week (cutoff at Sunday 23:59:59 UTC)
if err := writeWeeklyStocks(filepath.Join(base, "stocks_week.csv"), allIssues); err != nil {
return err
}
}
// PR scope calculations (do not require config)
if *prScope {
// weekly PR change-requests stats (avg, median, p90) by PR open week
if err := writePRChangeRequestsWeekly(filepath.Join(base, "pr_change_requests_week.csv"), base); err != nil {
return err
}
// per-repo PR change-requests stats (median per repo) and distribution
if err := writePRChangeRequestsPerRepo(filepath.Join(base, "pr_change_requests_repo.csv"), base); err != nil {
return err
}
if err := writePRChangeRequestsRepoDist(filepath.Join(base, "pr_change_requests_repo_dist.csv"), base); err != nil {
return err
}
}
if *issuesScope {
slog.Info(fmt.Sprintf("calculate.done (issues)"))
}
if *prScope {
slog.Info(fmt.Sprintf("calculate.done (pr)"))
}
return nil
}
func key(org, repo, number string) string { return org + "/" + repo + "#" + number }
func readIssues(path string) (map[string]issueRow, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := csv.NewReader(f)
rec, err := r.Read()
if err != nil {
return nil, err
}
// Expect headers: org,repo,number,title,url,state,type,is_bug,creator,assignees,created_at,closed_at,committer
idx := indexMap(rec)
required := []string{"org", "repo", "number", "title", "created_at"}
for _, col := range required {
if _, ok := idx[col]; !ok {
return nil, fmt.Errorf("issue.csv missing column %s", col)
}
}
// Optional columns for backward compatibility
_, hasType := idx["type"]
_, hasIsBug := idx["is_bug"]
res := map[string]issueRow{}
for {
rec, err = r.Read()
if errors.Is(err, os.ErrClosed) {
break
}
if err != nil {
if errors.Is(err, csv.ErrFieldCount) {
continue
}
if err.Error() == "EOF" {
break
}
return nil, err
}
org := rec[idx["org"]]
repo := rec[idx["repo"]]
num := rec[idx["number"]]
title := rec[idx["title"]]
typeVal := ""
if hasType {
typeVal = rec[idx["type"]]
}
isBug := false
if hasIsBug {
isBug = parseBool(rec[idx["is_bug"]])
}
created, _ := time.Parse(time.RFC3339, rec[idx["created_at"]])
res[key(org, repo, num)] = issueRow{Org: org, Repo: repo, Number: num, Title: title, Type: typeVal, IsBug: isBug, CreatedAt: created}
}
return res, nil
}
func readStatus(path string) (map[string][]statusEventRow, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := csv.NewReader(f)
head, err := r.Read()
if err != nil {
return nil, err
}
idx := indexMap(head)
required := []string{"org", "repo", "number", "type", "at"}
for _, col := range required {
if _, ok := idx[col]; !ok {
return nil, fmt.Errorf("issue_status_event.csv missing column %s", col)
}
}
res := map[string][]statusEventRow{}
for {
rec, err := r.Read()
if err != nil {
if err.Error() == "EOF" {
break
}
return nil, err
}
org := rec[idx["org"]]
repo := rec[idx["repo"]]
num := rec[idx["number"]]
typ := rec[idx["type"]]
at, _ := time.Parse(time.RFC3339, rec[idx["at"]])
id := key(org, repo, num)
res[id] = append(res[id], statusEventRow{Org: org, Repo: repo, Number: num, Type: typ, At: at})
}
// Sort by time
for _, v := range res {
sort.Slice(v, func(i, j int) bool { return v[i].At.Before(v[j].At) })
}
return res, nil
}
func readProject(path string) (map[string][]projectEventRow, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := csv.NewReader(f)
head, err := r.Read()
if err != nil {
return nil, err
}
idx := indexMap(head)
required := []string{"org", "repo", "number", "project_id", "project_name", "to_column", "at", "type"}
for _, col := range required {
if _, ok := idx[col]; !ok {
return nil, fmt.Errorf("issue_project_event.csv missing column %s", col)
}
}
res := map[string][]projectEventRow{}
for {
rec, err := r.Read()
if err != nil {
if err.Error() == "EOF" {
break
}
return nil, err
}
org := rec[idx["org"]]
repo := rec[idx["repo"]]
num := rec[idx["number"]]
projID := rec[idx["project_id"]]
projName := rec[idx["project_name"]]
toCol := rec[idx["to_column"]]
at, _ := time.Parse(time.RFC3339, rec[idx["at"]])
typ := rec[idx["type"]]
id := key(org, repo, num)
res[id] = append(res[id], projectEventRow{Org: org, Repo: repo, Number: num, ProjectID: projID, ProjectName: projName, ToColumn: toCol, At: at, EventType: typ})
}
for _, v := range res {
sort.Slice(v, func(i, j int) bool { return v[i].At.Before(v[j].At) })
}
return res, nil
}
func indexMap(headers []string) map[string]int {
m := map[string]int{}
for i, h := range headers {
m[strings.TrimSpace(strings.ToLower(h))] = i
}
return m
}
func parseBool(s string) bool {
s = strings.TrimSpace(strings.ToLower(s))
return s == "true" || s == "1" || s == "yes"
}
// Independent rules per field
func firstMoveTo(events []projectEventRow, column string) *time.Time {
if len(events) == 0 {
return nil
}
col := strings.ToLower(strings.TrimSpace(column))
// Only consider moved events
if ev, ok := lo.Find(events, func(e projectEventRow) bool {
return e.EventType == "moved" && strings.ToLower(strings.TrimSpace(e.ToColumn)) == col
}); ok {
return &ev.At
}
return nil
}
func firstMoveToAny(events []projectEventRow, columns []string) *time.Time {
if len(events) == 0 {
return nil
}
set := lo.SliceToMap(columns, func(s string) (string, struct{}) { return strings.ToLower(strings.TrimSpace(s)), struct{}{} })
if ev, ok := lo.Find(events, func(e projectEventRow) bool {
_, wanted := set[strings.ToLower(strings.TrimSpace(e.ToColumn))]
return e.EventType == "moved" && wanted
}); ok {
return &ev.At
}
return nil
}
func computeEnd(status []statusEventRow, proj []projectEventRow) *time.Time {
var closed *time.Time
if ev, ok := lo.Find(status, func(s statusEventRow) bool { return s.Type == "closed" }); ok {
closed = &ev.At
}
var archived *time.Time
if ev, ok := lo.Find(proj, func(p projectEventRow) bool { return p.EventType == "moved" && equalFoldTrim(p.ToColumn, "Archive") }); ok {
archived = &ev.At
}
if closed == nil && archived == nil {
return nil
}
if closed == nil {
return archived
}
if archived == nil {
return closed
}
if closed.Before(*archived) {
return closed
}
return archived
}
func equalFoldTrim(a, b string) bool {
return strings.EqualFold(strings.TrimSpace(a), strings.TrimSpace(b))
}
// earliest returns the earliest non-nil time among candidates, or nil if none.
func earliest(ts []*time.Time) *time.Time {
var res *time.Time
for _, t := range ts {
if t == nil {
continue
}
if res == nil || t.Before(*res) {
tt := *t
res = &tt
}
}
return res
}
func writeOutput(path string, rows []calculatedIssue) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
headers := []string{"id", "name", "project_id", "project_name", "creationdatetime", "leadtimestartdatetime", "cycletimestartdatetime", "putinreadystartdatetime", "devstartdatetime", "reviewstartdatetime", "qastartdatetime", "waitingtopodstartdateime", "enddatetime", "bug", "type"}
if err := w.Write(headers); err != nil {
return err
}
for _, r := range rows {
row := []string{
r.ID,
r.Name,
r.ProjectID,
r.ProjectName,
r.CreationDatetime.UTC().Format(time.RFC3339),
formatTime(r.LeadTimeStartDatetime),
formatTime(r.CycleTimeStartDatetime),
formatTime(r.PutInReadyStartDatetime),
formatTime(r.DevStartDatetime),
formatTime(r.ReviewStartDatetime),
formatTime(r.QAStartDatetime),
formatTime(r.WaitingToPodStartDatetime),
formatTime(r.EndDatetime),
fmt.Sprintf("%t", r.Bug),
r.Type,
}
if err := w.Write(row); err != nil {
return err
}
}
return w.Error()
}
func formatTime(t *time.Time) string {
if t == nil {
return ""
}
return t.UTC().Format(time.RFC3339)
}
// Step 2 helpers: monthly summary of lead/cycle times in days
func writeMonthlyCycleSummary(path string, rows []calculatedIssue) error {
byMonth := map[string][]calculatedIssue{}
for _, r := range rows {
if r.EndDatetime == nil {
continue
}
m := r.EndDatetime.UTC().Format("2006-01")
byMonth[m] = append(byMonth[m], r)
}
// prepare output rows sorted by month
type outRow struct {
Month string
IssueCount int
LeadDaysAvg float64
LeadCount int
CycleDaysAvg float64
CycleCount int
TimeToPRAvg float64
}
var months []string
for m := range byMonth {
months = append(months, m)
}
sort.Strings(months)
var outs []outRow
for _, m := range months {
issues := byMonth[m]
var leadSum float64
var leadCnt int
var cycleSum float64
var cycleCnt int
var tprSum float64
var tprCnt int
for _, r := range issues {
end := r.EndDatetime.UTC()
if r.LeadTimeStartDatetime != nil {
lead := end.Sub(r.LeadTimeStartDatetime.UTC()).Hours() / 24.0
leadSum += lead
leadCnt++
}
if r.CycleTimeStartDatetime != nil {
cycle := end.Sub(r.CycleTimeStartDatetime.UTC()).Hours() / 24.0
cycleSum += cycle
cycleCnt++
}
// Time to PR = review_start - dev_start (in days)
if r.DevStartDatetime != nil && r.ReviewStartDatetime != nil {
dev := r.DevStartDatetime.UTC()
rev := r.ReviewStartDatetime.UTC()
if !rev.Before(dev) {
tpr := rev.Sub(dev).Hours() / 24.0
tprSum += tpr
tprCnt++
}
}
}
var leadAvg, cycleAvg, tprAvg float64
if leadCnt > 0 {
leadAvg = leadSum / float64(leadCnt)
}
if cycleCnt > 0 {
cycleAvg = cycleSum / float64(cycleCnt)
}
if tprCnt > 0 {
tprAvg = tprSum / float64(tprCnt)
}
outs = append(outs, outRow{Month: m, IssueCount: len(issues), LeadDaysAvg: leadAvg, LeadCount: leadCnt, CycleDaysAvg: cycleAvg, CycleCount: cycleCnt, TimeToPRAvg: tprAvg})
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
headers := []string{"month", "issues_count", "leadtime_days_avg", "lead_count", "cycletime_days_avg", "cycle_count", "time_to_pr"}
if err := w.Write(headers); err != nil {
return err
}
for _, r := range outs {
row := []string{
r.Month,
fmt.Sprintf("%d", r.IssueCount),
fmt.Sprintf("%.6f", r.LeadDaysAvg),
fmt.Sprintf("%d", r.LeadCount),
fmt.Sprintf("%.6f", r.CycleDaysAvg),
fmt.Sprintf("%d", r.CycleCount),
fmt.Sprintf("%.6f", r.TimeToPRAvg),
}
if err := w.Write(row); err != nil {
return err
}
}
return w.Error()
}
// Step 3 helpers: weekly throughput with Shewhart control limits (c-chart)
func writeWeeklyThroughput(path string, rows []calculatedIssue) error {
// Aggregate counts by ISO year-week
type wk struct{ Year, Week int }
counts := map[wk]int{}
var minTime, maxTime *time.Time
for _, r := range rows {
if r.EndDatetime == nil {
continue
}
end := r.EndDatetime.UTC()
y, w := end.ISOWeek()
counts[wk{Year: y, Week: w}]++
if minTime == nil || end.Before(*minTime) {
t := end
minTime = &t
}
if maxTime == nil || end.After(*maxTime) {
t := end
maxTime = &t
}
}
// Build ordered continuous list of ISO weeks between min and max (include zero-throughput weeks)
var keys []wk
if minTime != nil && maxTime != nil {
// Align to Monday (start of ISO week)
alignToMonday := func(t time.Time) time.Time {
wd := int(t.Weekday()) // Sunday=0, Monday=1, ..., Saturday=6
offset := (wd + 6) % 7 // 0 for Monday, 6 for Sunday
tt := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
return tt.AddDate(0, 0, -offset)
}
start := alignToMonday(*minTime)
end := alignToMonday(*maxTime)
for cur := start; !cur.After(end); cur = cur.AddDate(0, 0, 7) {
y, w := cur.ISOWeek()
keys = append(keys, wk{Year: y, Week: w})
}
}
// Prepare arrays for per-week limits
centers := make([]float64, len(keys))
ucls := make([]float64, len(keys))
lcls := make([]float64, len(keys))
// Helper to clamp LCL at 0
clamp0 := func(v float64) float64 {
if v < 0 {
return 0
}
return v
}
// If no weeks, just write headers
if len(keys) == 0 {
// Write CSV headers only
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
headers := []string{"year", "week", "throughput", "center", "ucl", "lcl"}
if err := w.Write(headers); err != nil {
return err
}
return w.Error()
}
if len(keys) < 6 {
// Fewer than 6 total weeks: compute from available weeks and apply to all
var sum float64
for _, k := range keys {
sum += float64(counts[k])
}
mean := sum / float64(len(keys))
ucl := mean + 3.0*math.Sqrt(mean)
lcl := clamp0(mean - 3.0*math.Sqrt(mean))
for i := range keys {
centers[i] = mean
ucls[i] = ucl
lcls[i] = lcl
}
} else {
// 6-week cadence: compute at week 6,12,18,... and apply for each 6-week block
lastAssigned := -1
for blockEnd := 5; blockEnd < len(keys); blockEnd += 6 {
// Compute mean over the last 6 observed weeks ending at blockEnd
var sum float64
for j := blockEnd - 5; j <= blockEnd; j++ {
sum += float64(counts[keys[j]])
}
mean := sum / 6
ucl := mean + 3.0*math.Sqrt(mean)
lcl := clamp0(mean - 3.0*math.Sqrt(mean))
// Assign the same limits for this 6-week block
blockStart := blockEnd - 5
for i := blockStart; i <= blockEnd && i < len(keys); i++ {
ucls[i] = ucl
lcls[i] = lcl
lastAssigned = i
}
}
// Tail: if any weeks remain after the last full block, reuse the last block's limits
if lastAssigned < len(keys)-1 {
lastUCL := ucls[lastAssigned]
lastLCL := lcls[lastAssigned]
for i := lastAssigned + 1; i < len(keys); i++ {
ucls[i] = lastUCL
lcls[i] = lastLCL
}
}
}
// Before writing, set center to the number of issues ended for each week (weekly throughput)
for i, k := range keys {
centers[i] = float64(counts[k])
}
// Remove the last week (current week) from the output
if len(keys) > 0 {
keys = keys[:len(keys)-1]
centers = centers[:len(centers)-1]
ucls = ucls[:len(ucls)-1]
lcls = lcls[:len(lcls)-1]
}
// Write CSV
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
headers := []string{"year", "week", "throughput", "center", "ucl", "lcl"}
if err := w.Write(headers); err != nil {
return err
}
for i, k := range keys {
row := []string{
fmt.Sprintf("%d", k.Year),
fmt.Sprintf("%02d", k.Week),
fmt.Sprintf("%d", counts[k]),
fmt.Sprintf("%.6f", centers[i]),
fmt.Sprintf("%.6f", ucls[i]),
fmt.Sprintf("%.6f", lcls[i]),
}
if err := w.Write(row); err != nil {
return err
}
}
return w.Error()
}
// Step 4: stocks for not-closed issues by stage
func writeStocks(path string, rows []calculatedIssue) error {
// aggregate by project
type agg struct {
OpenedBugs int
InBacklogs int
InReady int
InDev int
InReview int
InQA int
WaitingToProd int
}
byProj := map[string]struct {
ProjectID string
ProjectName string
Agg agg
}{}
// helper to get bucket/stage booleans for a not-closed issue
stageFlags := func(r calculatedIssue) (openedBug bool, inBacklog bool, inReady bool, inDev bool, inReview bool, inQA bool, waiting bool) {
if r.EndDatetime != nil {
return false, false, false, false, false, false, false
}
openedBug = r.Bug
// Stage logic: furthest known stage wins (exclusive buckets)
if r.WaitingToPodStartDatetime != nil {
return openedBug, false, false, false, false, false, true
}
if r.QAStartDatetime != nil {
return openedBug, false, false, false, true, false, false
}
if r.ReviewStartDatetime != nil {
return openedBug, false, false, true, false, false, false
}
if r.DevStartDatetime != nil {
return openedBug, false, false, true, false, false, false
}
if r.PutInReadyStartDatetime != nil {
return openedBug, false, true, false, false, false, false
}
// Backlog (only early dates present: creation/lead/cycle)
return openedBug, true, false, false, false, false, false
}
for _, r := range rows {
if r.EndDatetime != nil {
continue // only not-closed
}
key := r.ProjectID + "\u0000" + r.ProjectName
rec := byProj[key]
rec.ProjectID = r.ProjectID
rec.ProjectName = r.ProjectName
ob, ib, iready, id, ir, iq, iw := stageFlags(r)
if ob {
rec.Agg.OpenedBugs++
}
if ib {
rec.Agg.InBacklogs++
}
if iready {
rec.Agg.InReady++
}
if id {
rec.Agg.InDev++
}
if ir {
rec.Agg.InReview++
}
if iq {
rec.Agg.InQA++
}
if iw {
rec.Agg.WaitingToProd++
}
byProj[key] = rec
}
// Write CSV
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
headers := []string{"project_id", "project_name", "opened_bugs", "in_backlogs", "in_ready", "in_dev", "in_review", "in_qa", "waiting_to_prod"}
if err := w.Write(headers); err != nil {
return err
}
// stable order by project_id then name
var keys []string
for k := range byProj {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
rec := byProj[k]
row := []string{
rec.ProjectID,
rec.ProjectName,
fmt.Sprintf("%d", rec.Agg.OpenedBugs),
fmt.Sprintf("%d", rec.Agg.InBacklogs),
fmt.Sprintf("%d", rec.Agg.InReady),
fmt.Sprintf("%d", rec.Agg.InDev),
fmt.Sprintf("%d", rec.Agg.InReview),
fmt.Sprintf("%d", rec.Agg.InQA),
fmt.Sprintf("%d", rec.Agg.WaitingToProd),
}
if err := w.Write(row); err != nil {
return err
}
}
return w.Error()
}
// Step 5: weekly stocks per project and ISO week with Sunday cutoff (UTC)
func writeWeeklyStocks(path string, rows []calculatedIssue) error {
// Determine range of weeks
timeUTC := func(t time.Time) time.Time { return t.UTC() }
var minT, maxT *time.Time
for _, r := range rows {
c := timeUTC(r.CreationDatetime)
if minT == nil || c.Before(*minT) {
t := c
minT = &t
}
cands := []*time.Time{r.LeadTimeStartDatetime, r.CycleTimeStartDatetime, r.PutInReadyStartDatetime, r.DevStartDatetime, r.ReviewStartDatetime, r.QAStartDatetime, r.WaitingToPodStartDatetime, r.EndDatetime}
for _, p := range cands {
if p == nil {
continue
}
t := p.UTC()
if maxT == nil || t.After(*maxT) {
u := t
maxT = &u
}
}
}
if minT == nil {
// nothing to write, create headers only
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
headers := []string{"year", "week", "project_id", "project_name", "opened_bugs", "in_backlogs", "in_ready", "in_dev", "in_review", "in_qa", "waiting_to_prod"}
if err := w.Write(headers); err != nil {
return err
}
return w.Error()
}
if maxT == nil {
m := time.Now().UTC()
maxT = &m
}
// Align to Monday 00:00 UTC of ISO week
alignToMonday := func(t time.Time) time.Time {
wd := int(t.Weekday())
offset := (wd + 6) % 7
tt := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
return tt.AddDate(0, 0, -offset)
}
start := alignToMonday(*minT)
end := alignToMonday(*maxT)
type wk struct{ Year, Week int }
// Iterate weeks
type agg struct{ OpenedBugs, InBacklogs, InReady, InDev, InReview, InQA, WaitingToProd int }
type rec struct {
ProjectID, ProjectName string
Agg agg
}