Files
phishingclub/backend/service/programReplan_db_test.go
2026-12-01 21:25:01 +01:00

952 lines
40 KiB
Go

package service
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"github.com/oapi-codegen/nullable"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/model"
"github.com/phishingclub/phishingclub/repository"
"github.com/phishingclub/phishingclub/utils"
"gorm.io/gorm"
)
// sendAt adds a campaign recipient row planned for the given time, sent or not
func (p *programTest) sendAt(campaignID, recipientID uuid.UUID, at time.Time, sent bool) uuid.UUID {
p.t.Helper()
id := p.send(campaignID, recipientID, sent)
if err := p.db.Model(&database.CampaignRecipient{}).Where("id = ?", id).
// stored as RFC3339 text, the same as the campaign send path
Update("send_at", utils.RFC3339UTC(at)).Error; err != nil {
p.t.Fatalf("set send_at: %v", err)
}
return id
}
func (p *programTest) setProgram(id uuid.UUID, fields map[string]any) {
p.t.Helper()
if err := p.db.Model(&database.Program{}).Where("id = ?", id).Updates(fields).Error; err != nil {
p.t.Fatalf("update program: %v", err)
}
}
func (p *programTest) setEnrollment(id *uuid.UUID, fields map[string]any) {
p.t.Helper()
if err := p.svc.ProgramRepository.UpdateEnrollmentFields(p.ctx, id, fields); err != nil {
p.t.Fatalf("update enrollment: %v", err)
}
}
func (p *programTest) campaignRecipient(id uuid.UUID) database.CampaignRecipient {
p.t.Helper()
var row database.CampaignRecipient
if err := p.db.Where("id = ?", id).First(&row).Error; err != nil {
p.t.Fatalf("load campaign recipient: %v", err)
}
return row
}
// TestReplanReactivatesCompletedOnNewStep checks a completed person comes back
// when a step they have not had is added, and one who had every step does not
func TestReplanReactivatesCompletedOnNewStep(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
step1 := p.step(programID, 0, true)
campaign1 := p.stepCampaign(programID, step1, 0)
alice := p.recipient("alice@example.com")
bob := p.recipient("bob@example.com")
ea := p.enroll(programID, alice, 0)
eb := p.enroll(programID, bob, 0)
p.send(campaign1, alice, true)
p.send(campaign1, bob, true)
for _, e := range []*database.ProgramEnrollment{ea, eb} {
p.setEnrollment(e.ID, map[string]any{
"status": model.ProgramEnrollmentCompleted, "completed_at": time.Now(), "next_due_at": nil,
"last_send_at": time.Now().Add(-time.Hour),
})
}
before := p.loadProgram(programID)
// a step edit with no new step changes nobody
if err := p.svc.replanAfterEdit(p.ctx, before, &programID, true); err != nil {
t.Fatalf("replan: %v", err)
}
if row := p.enrollment(ea.ID); row.Status != model.ProgramEnrollmentCompleted {
t.Fatalf("expected still completed, got %s", row.Status)
}
// a new step: alice and bob both have it left
step2 := p.step(programID, 1, true)
// bob already had the new step, for example from an earlier edit
campaign2 := p.stepCampaign(programID, step2, 0)
p.send(campaign2, bob, true)
now := time.Now()
if err := p.svc.replanAfterEdit(p.ctx, before, &programID, true); err != nil {
t.Fatalf("replan: %v", err)
}
row := p.enrollment(ea.ID)
if row.Status != model.ProgramEnrollmentActive || row.CompletedAt != nil || row.NextDueAt == nil {
t.Fatalf("expected alice active with a send planned, got %s %v %v", row.Status, row.CompletedAt, row.NextDueAt)
}
minNext := row.LastSendAt.Add(before.IntervalOrDefault() / 2)
if row.NextDueAt.Before(minNext) || row.NextDueAt.Before(now.Add(-time.Second)) {
t.Fatalf("expected the next send after the minimum gap, got %v", row.NextDueAt)
}
if row := p.enrollment(eb.ID); row.Status != model.ProgramEnrollmentCompleted {
t.Fatalf("expected bob still completed, got %s", row.Status)
}
}
// TestReplanReactivatesCompletedOnLoopMode checks switching to loop mode brings
// every completed person back, and a closed program changes nobody
func TestReplanReactivatesCompletedOnLoopMode(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
step1 := p.step(programID, 0, true)
campaign1 := p.stepCampaign(programID, step1, 0)
alice := p.recipient("alice@example.com")
e := p.enroll(programID, alice, 0)
p.send(campaign1, alice, true)
p.setEnrollment(e.ID, map[string]any{
"status": model.ProgramEnrollmentCompleted, "completed_at": time.Now(), "next_due_at": nil,
})
before := p.loadProgram(programID)
p.setProgram(programID, map[string]any{"loop_mode": model.ProgramLoopLoop, "closed_at": time.Now().UTC()})
if err := p.svc.replanAfterEdit(p.ctx, before, &programID, false); err != nil {
t.Fatalf("replan: %v", err)
}
if row := p.enrollment(e.ID); row.Status != model.ProgramEnrollmentCompleted {
t.Fatalf("a closed program must change nobody, got %s", row.Status)
}
p.setProgram(programID, map[string]any{"closed_at": nil})
if err := p.svc.replanAfterEdit(p.ctx, before, &programID, false); err != nil {
t.Fatalf("replan: %v", err)
}
row := p.enrollment(e.ID)
if row.Status != model.ProgramEnrollmentActive || row.NextDueAt == nil {
t.Fatalf("expected active again in loop mode, got %s %v", row.Status, row.NextDueAt)
}
}
// TestReplanRedrawsOnIntervalChange checks a shorter interval moves the stored
// next send of an active person closer, never under half the new interval
// after the last send, and leaves a person who is due now alone
func TestReplanRedrawsOnIntervalChange(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
p.step(programID, 0, true)
p.step(programID, 1, true)
alice := p.recipient("alice@example.com")
bob := p.recipient("bob@example.com")
ea := p.enroll(programID, alice, 0)
eb := p.enroll(programID, bob, 0)
before := p.loadProgram(programID)
now := time.Now()
lastSend := now.Add(-time.Hour)
round := lastSend.Add(before.IntervalOrDefault())
p.setEnrollment(ea.ID, map[string]any{
"last_send_at": lastSend, "round_start_at": round, "next_due_at": round, "position": 1,
})
bobDue := now.Add(-time.Minute).UTC().Truncate(time.Second)
p.setEnrollment(eb.ID, map[string]any{"next_due_at": bobDue})
p.setProgram(programID, map[string]any{"step_interval_minutes": 2 * 24 * 60})
if err := p.svc.replanAfterEdit(p.ctx, before, &programID, false); err != nil {
t.Fatalf("replan: %v", err)
}
row := p.enrollment(ea.ID)
want := lastSend.Add(2 * 24 * time.Hour)
if row.NextDueAt == nil || row.NextDueAt.Sub(want).Abs() > time.Second {
t.Fatalf("expected the next send two days after the last, got %v want %v", row.NextDueAt, want)
}
if row := p.enrollment(eb.ID); row.NextDueAt == nil || !row.NextDueAt.Equal(bobDue) {
t.Fatalf("a person due now must be left to the tick, got %v", row.NextDueAt)
}
}
// respreadHeld moves the held sends of a program the way a resume does
func (p *programTest) respreadHeld(programID uuid.UUID, now time.Time) {
p.t.Helper()
moves, err := p.svc.heldSendMoves(p.ctx, p.loadProgram(programID), now)
if err == nil {
err = p.svc.ProgramRepository.MoveSends(p.ctx, moves)
}
if err != nil {
p.t.Fatalf("respread: %v", err)
}
}
// TestRespreadHeldSends checks a held send whose time passed is moved to now or
// later, a training send too, and a send still ahead stays
func TestRespreadHeldSends(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
step1 := p.step(programID, 0, true)
campaign1 := p.stepCampaign(programID, step1, 0)
alice := p.recipient("alice@example.com")
bob := p.recipient("bob@example.com")
now := time.Now()
past := p.sendAt(campaign1, alice, now.Add(-48*time.Hour), false)
ahead := now.Add(48 * time.Hour).UTC().Truncate(time.Second)
future := p.sendAt(campaign1, bob, ahead, false)
p.respreadHeld(programID, now)
if row := p.campaignRecipient(past); row.SendAt == nil || row.SendAt.Before(now.Add(-time.Second)) {
t.Fatalf("expected the held send moved to now or later, got %v", row.SendAt)
}
if row := p.campaignRecipient(future); row.SendAt == nil || !row.SendAt.Equal(ahead) {
t.Fatalf("expected the send ahead unchanged, got %v want %v", row.SendAt, ahead)
}
}
// TestRespreadHeldSendsKeepsBlackout checks a held send is not let out on a
// blackout day
func TestRespreadHeldSendsKeepsBlackout(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
now := time.Now().UTC()
today := now.Format(model.ProgramDateLayout)
tomorrow := now.Add(24 * time.Hour).Format(model.ProgramDateLayout)
blackout := `[{"from":"` + today + `","to":"` + tomorrow + `"}]`
p.setProgram(programID, map[string]any{"blackout_dates": blackout, "time_zone": "UTC"})
step1 := p.step(programID, 0, true)
campaign1 := p.stepCampaign(programID, step1, 0)
alice := p.recipient("alice@example.com")
held := p.sendAt(campaign1, alice, now.Add(-time.Hour), false)
p.respreadHeld(programID, now)
open := time.Date(now.Year(), now.Month(), now.Day()+2, 0, 0, 0, 0, time.UTC)
if row := p.campaignRecipient(held); row.SendAt == nil || row.SendAt.Before(open) {
t.Fatalf("expected the held send after the blackout, got %v", row.SendAt)
}
}
// TestResumeMembershipCancelsHeldSendsOfLeavers checks that people gone from
// the groups when a program resumes get none of the held sends, while members
// keep theirs
func TestResumeMembershipCancelsHeldSendsOfLeavers(t *testing.T) {
p := newProgramServiceTest(t)
if err := p.db.AutoMigrate(&database.RecipientGroup{}, &database.RecipientGroupRecipient{}); err != nil {
t.Fatalf("migrate: %v", err)
}
p.svc.RecipientGroupRepository = &repository.RecipientGroup{DB: p.db}
programID := p.program(model.ProgramLoopComplete)
step1 := p.step(programID, 0, true)
campaign1 := p.stepCampaign(programID, step1, 0)
alice := p.recipient("alice@example.com")
bob := p.recipient("bob@example.com")
now := time.Now().UTC()
groupID := uuid.New()
p.create(&database.RecipientGroup{ID: &groupID, CreatedAt: &now, UpdatedAt: &now, Name: "group"})
p.create(&database.RecipientGroupRecipient{RecipientID: &alice, RecipientGroupID: &groupID})
p.create(&database.ProgramRecipientGroup{ProgramID: &programID, RecipientGroupID: &groupID})
ea := p.enroll(programID, alice, 0)
eb := p.enroll(programID, bob, 0)
aliceSend := p.sendAt(campaign1, alice, now.Add(-time.Hour), false)
bobSend := p.sendAt(campaign1, bob, now.Add(-time.Hour), false)
plan, err := p.svc.resumeMembers(p.ctx, &programID, now)
if err != nil || plan == nil {
t.Fatalf("expected the members of a started program: %v", err)
}
found, changed, err := p.svc.resolveMembershipOnResume(p.ctx, &programID, plan, now)
if err != nil || changed {
t.Fatalf("resolve membership: changed %v err %v", changed, err)
}
always := func(*model.Program) bool { return true }
if _, err := p.svc.finishResumeMembership(p.ctx, &programID, found, now, always); err != nil {
t.Fatalf("cancel held sends: %v", err)
}
if row := p.campaignRecipient(bobSend); row.CancelledAt == nil {
t.Fatalf("expected the held send of the leaver cancelled")
}
if row := p.campaignRecipient(aliceSend); row.CancelledAt != nil {
t.Fatalf("expected the held send of the member kept")
}
if row := p.enrollment(eb.ID); row.MissingSince == nil {
t.Fatalf("expected the leaver marked missing")
}
if row := p.enrollment(ea.ID); row.MissingSince != nil || row.Status != model.ProgramEnrollmentActive {
t.Fatalf("expected the member unchanged")
}
}
// TestHeldSendMovesSpreadAfterHours checks held sends whose time passed during
// a pause are not all moved to the same second when the resume is after hours
func TestHeldSendMovesSpreadAfterHours(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
friday18 := time.Date(2024, 1, 5, 18, 0, 0, 0, time.UTC)
for i := 0; i < 50; i++ {
p.sendAt(campaignID, p.recipient(uuid.NewString()+"@example.com"), friday18.Add(-24*time.Hour), false)
}
program := workWeekProgram()
program.ID = nullable.NewNullableWithValue(programID)
moves, err := p.svc.heldSendMoves(p.ctx, program, friday18)
if err != nil || len(moves) != 50 {
t.Fatalf("expected 50 moves, got %d %v", len(moves), err)
}
distinct := map[time.Time]bool{}
for _, m := range moves {
distinct[m.SendAt] = true
}
if len(distinct) < 40 {
t.Fatalf("held sends were moved to %d distinct times only", len(distinct))
}
}
// TestProgramRecipientDeleteRacesResume checks a resume that read the
// enrollments before a person was deleted does not make the unlinked
// enrollment active again from its stale copy
func TestProgramRecipientDeleteRacesResume(t *testing.T) {
p := newProgramLifecycleTest(t)
programID, alice, e := p.exitedMember()
now := time.Now()
plan, err := p.svc.resumeMembers(p.ctx, &programID, now)
if err != nil || plan == nil {
t.Fatalf("plan: %v %v", plan, err)
}
p.deleteRecipient(alice)
m, changed, err := p.svc.resolveMembershipOnResume(p.ctx, &programID, plan, now)
if err != nil || changed {
t.Fatalf("resolve: changed %v err %v", changed, err)
}
if len(m.returners.returning) != 1 {
t.Fatalf("the stale copy must plan alice as returning, got %d", len(m.returners.returning))
}
always := func(*model.Program) bool { return true }
if done, err := p.svc.finishResumeMembership(p.ctx, &programID, m, now, always); err != nil || !done {
t.Fatalf("finish: done %v err %v", done, err)
}
p.checkUnlinkedStaysOut(programID, e.ID)
}
// TestRemovedStepBacklogSkipsLinksWithNothingLeft checks the read of the
// sends of removed steps finds a new send after more open links of removed
// steps than one read looks at, all with nothing left to cancel, and skips a
// program being closed
func TestRemovedStepBacklogSkipsLinksWithNothingLeft(t *testing.T) {
p := newProgramLifecycleTest(t)
programID := p.program(model.ProgramLoopComplete)
removedStep := p.step(programID, 0, true)
now := time.Now().UTC()
n := 1001
campaigns := make([]*database.Campaign, 0, n)
links := make([]*database.ProgramCampaign, 0, n)
for i := 0; i < n; i++ {
cid, lid := uuid.New(), uuid.New()
campaigns = append(campaigns, &database.Campaign{ID: &cid, CreatedAt: &now, UpdatedAt: &now, Name: "campaign " + cid.String(), ProgramID: &programID})
links = append(links, &database.ProgramCampaign{ID: &lid, CreatedAt: &now, ProgramID: &programID, ProgramStepID: &removedStep, LoopIndex: i + 1, CampaignID: &cid})
}
for _, rows := range []any{campaigns, links} {
if err := p.db.CreateInBatches(rows, 200).Error; err != nil {
t.Fatalf("create: %v", err)
}
}
// the new work sorts after every link with nothing left
newCampaign := uuid.New()
p.create(&database.Campaign{ID: &newCampaign, CreatedAt: &now, UpdatedAt: &now, Name: "new", ProgramID: &programID})
last := uuid.MustParse("ffffffff-ffff-4fff-bfff-ffffffffffff")
p.create(&database.ProgramCampaign{ID: &last, CreatedAt: &now, ProgramID: &programID, ProgramStepID: &removedStep, LoopIndex: 0, CampaignID: &newCampaign})
alice := p.recipient("alice@example.com")
send := p.sendAt(newCampaign, alice, now.Add(time.Hour), false)
if err := p.db.Where("id = ?", removedStep).Delete(&database.ProgramStep{}).Error; err != nil {
t.Fatalf("remove step: %v", err)
}
found, err := p.svc.ProgramRepository.GetUnsentSendsOfRemovedSteps(p.ctx, 10)
if err != nil || len(found) != 1 || found[0].ID != send {
t.Fatalf("expected the new send found, got %v %v", found, err)
}
p.setProgram(programID, map[string]any{"closing_at": now})
found, err = p.svc.ProgramRepository.GetUnsentSendsOfRemovedSteps(p.ctx, 10)
if err != nil || len(found) != 0 {
t.Fatalf("a program being closed cancels its own sends, got %v %v", found, err)
}
}
// The tests in this file change a running program through the service update
// and check what happens to the people in it.
// template stores a usable template that is not training
func (p *programTest) template() uuid.UUID {
p.t.Helper()
now := time.Now().UTC()
id, urlID := uuid.New(), uuid.New()
p.create(&database.CampaignTemplate{
ID: &id, CreatedAt: &now, UpdatedAt: &now, Name: "template " + id.String(),
URLIdentifierID: &urlID, IsUsable: true,
})
return id
}
// trainingTemplate stores a usable awareness training template
func (p *programTest) trainingTemplate() uuid.UUID {
p.t.Helper()
now := time.Now().UTC()
id, urlID := uuid.New(), uuid.New()
p.create(&database.CampaignTemplate{
ID: &id, CreatedAt: &now, UpdatedAt: &now, Name: "training " + id.String(),
URLIdentifierID: &urlID, IsUsable: true, IsTraining: true,
})
return id
}
// keepStep is a step of an update request that keeps a stored step at a
// position
func (p *programTest) keepStep(stepID uuid.UUID, position int) *model.ProgramStep {
st := &model.ProgramStep{}
st.ID.Set(stepID)
st.CampaignTemplateID.Set(p.stepTemplate(stepID))
st.Position.Set(position)
return st
}
// newStep is a step of an update request with a template at a position
func newStep(templateID uuid.UUID, position int) *model.ProgramStep {
st := &model.ProgramStep{}
st.CampaignTemplateID.Set(templateID)
st.Position.Set(position)
return st
}
// update stores a change through the service update, with the stored name as
// the update asks for one
func (p *programTest) update(programID uuid.UUID, update *model.Program) error {
p.t.Helper()
update.Name = p.loadProgram(programID).Name
return p.svc.UpdateByID(p.ctx, authorizedSession(p.t), &programID, update)
}
// updateSteps stores a new step list through the service update
func (p *programTest) updateSteps(programID uuid.UUID, steps ...*model.ProgramStep) {
p.t.Helper()
if err := p.update(programID, &model.Program{Steps: steps}); err != nil {
p.t.Fatalf("update steps: %v", err)
}
}
// updateGroups stores a new group list through the service update
func (p *programTest) updateGroups(programID uuid.UUID, groupIDs ...uuid.UUID) {
p.t.Helper()
ids := make([]*uuid.UUID, 0, len(groupIDs))
for i := range groupIDs {
ids = append(ids, &groupIDs[i])
}
update := &model.Program{RecipientGroupIDs: nullable.NewNullableWithValue(ids)}
if err := p.update(programID, update); err != nil {
p.t.Fatalf("update groups: %v", err)
}
}
// addToGroup puts a recipient in a group
func (p *programTest) addToGroup(groupID, recipientID uuid.UUID) {
p.t.Helper()
p.create(&database.RecipientGroupRecipient{RecipientID: &recipientID, RecipientGroupID: &groupID})
}
// assignGroup assigns a group to a program
func (p *programTest) assignGroup(programID, groupID uuid.UUID) {
p.t.Helper()
p.create(&database.ProgramRecipientGroup{ProgramID: &programID, RecipientGroupID: &groupID})
}
// stepCampaignOfStep returns the hidden campaign of a step in a loop, made
// when there is none yet
func (p *programTest) stepCampaignOfStep(programID, stepID uuid.UUID, loop int) uuid.UUID {
p.t.Helper()
var link database.ProgramCampaign
res := p.db.Where("program_step_id = ? AND loop_index = ?", stepID, loop).Limit(1).Find(&link)
if res.Error != nil {
p.t.Fatalf("load link: %v", res.Error)
}
if res.RowsAffected > 0 {
return *link.CampaignID
}
return p.stepCampaign(programID, stepID, loop)
}
// enrollmentOf returns the enrollment of a recipient in a program
func (p *programTest) enrollmentOf(programID, recipientID uuid.UUID) *database.ProgramEnrollment {
p.t.Helper()
var rows []database.ProgramEnrollment
if err := p.db.Where("program_id = ? AND recipient_id = ?", programID, recipientID).Find(&rows).Error; err != nil {
p.t.Fatalf("load enrollment: %v", err)
}
if len(rows) != 1 {
p.t.Fatalf("expected one enrollment, got %d", len(rows))
}
return &rows[0]
}
// sendsOf returns every send of a recipient in a campaign
func (p *programTest) sendsOf(campaignID, recipientID uuid.UUID) []database.CampaignRecipient {
p.t.Helper()
var rows []database.CampaignRecipient
if err := p.db.Where("campaign_id = ? AND recipient_id = ?", campaignID, recipientID).Find(&rows).Error; err != nil {
p.t.Fatalf("load sends: %v", err)
}
return rows
}
// queuedAfterSend sets an enrollment the way the advance leaves it right
// after it planned a send of step at sendAt in the round that started at
// round: the next round is one interval later
func (p *programTest) queuedAfterSend(e *database.ProgramEnrollment, step uuid.UUID, sendAt, round time.Time, position int) time.Time {
p.t.Helper()
next := round.Add(model.ProgramDefaultIntervalMinutes * time.Minute)
p.setEnrollment(e.ID, map[string]any{
"last_send_at": sendAt, "last_step_id": step, "round_start_at": next,
"next_due_at": next, "position": position,
})
return next
}
// TestEditRemoveTemplateCancelsQueuedSend checks a removed template is never
// sent again, in a running and in a paused program: the queued send of it is
// cancelled, also one moved to a later window opening, the person is due again
// about when that send would have gone out and the next tick gives them a
// template they have left, in the same round. Their history keeps the sent
// sends, a person who had every other template stays completed with one send
// fewer.
func TestEditRemoveTemplateCancelsQueuedSend(t *testing.T) {
for _, paused := range []bool{false, true} {
p := newProgramWriteTest(t)
programID := p.program(model.ProgramLoopComplete)
stepA := p.step(programID, 0, true)
stepB := p.step(programID, 1, true)
stepC := p.step(programID, 2, true)
campaignA := p.stepCampaign(programID, stepA, 0)
campaignB := p.stepCampaign(programID, stepB, 0)
campaignC := p.stepCampaign(programID, stepC, 0)
now := time.Now().UTC().Truncate(time.Second)
round := now.Add(-time.Hour)
interval := model.ProgramDefaultIntervalMinutes * time.Minute
// alice had A a round ago, B is queued now
alice := p.recipient("alice@example.com")
ea := p.enroll(programID, alice, 0)
sentA := p.sendAt(campaignA, alice, round.Add(-interval), true)
queuedB := p.sendAt(campaignB, alice, now.Add(-time.Minute), false)
p.queuedAfterSend(ea, stepB, now.Add(-time.Minute), round, 2)
// dave's send of B waits for the window to open in ten hours
dave := p.recipient("dave@example.com")
ed := p.enroll(programID, dave, 0)
p.sendAt(campaignA, dave, round.Add(-interval), true)
laterB := p.sendAt(campaignB, dave, now.Add(10*time.Hour), false)
p.queuedAfterSend(ed, stepB, now.Add(10*time.Hour), round, 2)
// bob had A and C, B was his last and is queued, so he is completed
bob := p.recipient("bob@example.com")
eb := p.enroll(programID, bob, 0)
p.sendAt(campaignA, bob, round.Add(-2*interval), true)
p.sendAt(campaignC, bob, round.Add(-interval), true)
bobB := p.sendAt(campaignB, bob, now.Add(-time.Minute), false)
p.setEnrollment(eb.ID, map[string]any{
"status": model.ProgramEnrollmentCompleted, "completed_at": now, "next_due_at": nil,
"position": 3, "last_step_id": stepB, "round_start_at": round,
})
if paused {
p.setProgram(programID, map[string]any{"paused_at": now})
}
p.updateSteps(programID, p.keepStep(stepA, 0), p.keepStep(stepC, 1))
for name, id := range map[string]uuid.UUID{"alice": queuedB, "dave": laterB, "bob": bobB} {
if p.campaignRecipient(id).CancelledAt == nil {
t.Fatalf("paused=%v: the queued send of the removed template to %s must be cancelled", paused, name)
}
}
if row := p.campaignRecipient(sentA); row.CancelledAt != nil || row.SentAt == nil {
t.Fatalf("paused=%v: a sent send stays in the history", paused)
}
row := p.enrollment(ea.ID)
if row.Status != model.ProgramEnrollmentActive || row.NextDueAt == nil || row.NextDueAt.After(time.Now().Add(time.Second)) {
t.Fatalf("paused=%v: alice must be due now, got %s %v", paused, row.Status, row.NextDueAt)
}
if row.RoundStartAt == nil || !row.RoundStartAt.Equal(round) {
t.Fatalf("paused=%v: alice keeps the round of the cancelled send, got %v want %v", paused, row.RoundStartAt, round)
}
if row := p.enrollment(ed.ID); row.NextDueAt == nil || !row.NextDueAt.Equal(now.Add(10*time.Hour)) {
t.Fatalf("paused=%v: dave must be due when his cancelled send would have gone out, got %v", paused, row.NextDueAt)
}
if row := p.enrollment(eb.ID); row.Status != model.ProgramEnrollmentCompleted {
t.Fatalf("paused=%v: bob had every template left and stays completed, got %s", paused, row.Status)
}
if paused {
continue
}
// the next tick gives alice C and completes her round with one fewer
row = p.enrollment(ea.ID)
p.advance(programID, &row)
if rows := p.sendsOf(campaignC, alice); len(rows) != 1 || rows[0].CancelledAt != nil {
t.Fatalf("expected alice to get the remaining template, got %d", len(rows))
}
if rows := p.sendsOf(campaignB, alice); len(rows) != 1 || rows[0].CancelledAt == nil {
t.Fatalf("the removed template must not be sent again")
}
if row := p.enrollment(ea.ID); row.Status != model.ProgramEnrollmentCompleted || row.Position != 2 {
t.Fatalf("expected alice completed after two templates, got %s %d", row.Status, row.Position)
}
// later picks never choose the removed template
program := p.loadProgram(programID)
for _, st := range program.Steps {
if st.ID.MustGet() == stepB {
t.Fatalf("the removed step must be gone")
}
}
}
}
// TestEditChangeTemplateIsRemoveAndAdd checks a step whose template changes
// in the same position becomes a new step with its own hidden campaign: the
// queued send of the old template is cancelled, the person gets the new one at
// the next tick, and a completed person who had the old one is active again
// for the new one
func TestEditChangeTemplateIsRemoveAndAdd(t *testing.T) {
p := newProgramWriteTest(t)
programID := p.program(model.ProgramLoopComplete)
stepA := p.step(programID, 0, true)
stepB := p.step(programID, 1, true)
campaignA := p.stepCampaign(programID, stepA, 0)
campaignB := p.stepCampaign(programID, stepB, 0)
now := time.Now().UTC().Truncate(time.Second)
round := now.Add(-time.Hour)
interval := model.ProgramDefaultIntervalMinutes * time.Minute
alice := p.recipient("alice@example.com")
ea := p.enroll(programID, alice, 0)
p.sendAt(campaignA, alice, round.Add(-interval), true)
queuedB := p.sendAt(campaignB, alice, now.Add(-time.Minute), false)
p.queuedAfterSend(ea, stepB, now.Add(-time.Minute), round, 2)
bob := p.recipient("bob@example.com")
eb := p.enroll(programID, bob, 0)
p.sendAt(campaignA, bob, round.Add(-2*interval), true)
sentB := p.sendAt(campaignB, bob, round.Add(-interval), true)
p.setEnrollment(eb.ID, map[string]any{
"status": model.ProgramEnrollmentCompleted, "completed_at": now, "next_due_at": nil,
"position": 2, "last_step_id": stepB, "round_start_at": round.Add(-interval),
})
other := p.template()
changed := newStep(other, 1)
changed.ID.Set(stepB)
p.updateSteps(programID, p.keepStep(stepA, 0), changed)
program := p.loadProgram(programID)
if len(program.Steps) != 2 || program.Steps[1].ID.MustGet() == stepB || program.Steps[1].CampaignTemplateID.MustGet() != other {
t.Fatalf("a new template in the same position must be a new step")
}
newStepID := program.Steps[1].ID.MustGet()
if p.campaignRecipient(queuedB).CancelledAt == nil {
t.Fatalf("the queued send of the old template must be cancelled")
}
if row := p.campaignRecipient(sentB); row.CancelledAt != nil {
t.Fatalf("a sent send of the old template stays in the history")
}
row := p.enrollment(ea.ID)
if row.NextDueAt == nil || row.NextDueAt.After(time.Now().Add(time.Second)) {
t.Fatalf("alice must be due now, got %v", row.NextDueAt)
}
if row := p.enrollment(eb.ID); row.Status != model.ProgramEnrollmentActive || row.NextDueAt == nil {
t.Fatalf("bob has the new template left and must be active, got %s", row.Status)
}
newCampaign := p.stepCampaignOfStep(programID, newStepID, 0)
if newCampaign == campaignB {
t.Fatalf("the new step must have its own hidden campaign")
}
p.advance(programID, &row)
if rows := p.sendsOf(newCampaign, alice); len(rows) != 1 {
t.Fatalf("expected alice to get the new template, got %d", len(rows))
}
}
// TestEditAddTemplate checks a template added to a running program: active
// people keep their next send time and get it later in the round, in its
// position in same order. A completed person with the new template left is
// active again in stop mode, every completed person in start over mode.
func TestEditAddTemplate(t *testing.T) {
p := newProgramWriteTest(t)
programID := p.program(model.ProgramLoopComplete)
stepA := p.step(programID, 0, true)
stepB := p.step(programID, 1, true)
campaignA := p.stepCampaign(programID, stepA, 0)
campaignB := p.stepCampaign(programID, stepB, 0)
now := time.Now().UTC().Truncate(time.Second)
interval := model.ProgramDefaultIntervalMinutes * time.Minute
alice := p.recipient("alice@example.com")
ea := p.enroll(programID, alice, 0)
p.sendAt(campaignA, alice, now.Add(-interval), true)
aliceDue := now.Add(time.Hour)
p.setEnrollment(ea.ID, map[string]any{
"last_send_at": now.Add(-interval), "last_step_id": stepA, "round_start_at": aliceDue,
"next_due_at": aliceDue, "position": 1,
})
bob := p.recipient("bob@example.com")
eb := p.enroll(programID, bob, 0)
p.sendAt(campaignA, bob, now.Add(-2*interval), true)
p.sendAt(campaignB, bob, now.Add(-interval), true)
p.setEnrollment(eb.ID, map[string]any{
"status": model.ProgramEnrollmentCompleted, "completed_at": now, "next_due_at": nil, "position": 2,
})
added := p.template()
p.updateSteps(programID, p.keepStep(stepA, 0), newStep(added, 1), p.keepStep(stepB, 2))
row := p.enrollment(ea.ID)
if row.NextDueAt == nil || !row.NextDueAt.Equal(aliceDue) {
t.Fatalf("an active person keeps their next send time, got %v want %v", row.NextDueAt, aliceDue)
}
if row := p.enrollment(eb.ID); row.Status != model.ProgramEnrollmentActive || row.NextDueAt == nil {
t.Fatalf("a completed person with the new template left must be active, got %s", row.Status)
}
program := p.loadProgram(programID)
addedStep := program.Steps[1].ID.MustGet()
addedCampaign := p.stepCampaignOfStep(programID, addedStep, 0)
// same order: alice gets the new template next, it sits before B
if err := p.svc.advanceEnrollment(p.ctx, nil, program, &row, aliceDue, nil, nil); err != nil {
t.Fatalf("advance: %v", err)
}
if rows := p.sendsOf(addedCampaign, alice); len(rows) != 1 {
t.Fatalf("expected the added template next in its position, got %d", len(rows))
}
if rows := p.sendsOf(campaignB, alice); len(rows) != 0 {
t.Fatalf("B comes after the added template in same order")
}
// start over: every completed person comes back, also one who had all
q := newProgramWriteTest(t)
loopID := q.program(model.ProgramLoopLoop)
only := q.step(loopID, 0, true)
carol := q.recipient("carol@example.com")
ec := q.enroll(loopID, carol, 0)
q.sendAt(q.stepCampaign(loopID, only, 0), carol, now.Add(-interval), true)
q.setEnrollment(ec.ID, map[string]any{
"status": model.ProgramEnrollmentCompleted, "completed_at": now, "next_due_at": nil, "position": 1,
})
q.updateSteps(loopID, q.keepStep(only, 0), newStep(q.template(), 1))
if row := q.enrollment(ec.ID); row.Status != model.ProgramEnrollmentActive {
t.Fatalf("start over brings every completed person back, got %s", row.Status)
}
}
// TestEditTimingKeepsQueuedSends checks a timing change draws the next send of
// an active person again but leaves a send already queued at its time
func TestEditTimingKeepsQueuedSends(t *testing.T) {
p := newProgramWriteTest(t)
programID := p.program(model.ProgramLoopComplete)
stepA := p.step(programID, 0, true)
p.step(programID, 1, true)
campaignA := p.stepCampaign(programID, stepA, 0)
alice := p.recipient("alice@example.com")
ea := p.enroll(programID, alice, 0)
now := time.Now().UTC().Truncate(time.Second)
queuedAt := now.Add(30 * time.Minute)
queued := p.sendAt(campaignA, alice, queuedAt, false)
oldDue := p.queuedAfterSend(ea, stepA, queuedAt, now, 1)
update := &model.Program{}
update.StepIntervalMinutes.Set(2 * 24 * 60)
if err := p.update(programID, update); err != nil {
t.Fatalf("update: %v", err)
}
row := p.enrollment(ea.ID)
if row.NextDueAt == nil || row.NextDueAt.Equal(oldDue) {
t.Fatalf("the next send must be drawn again, got %v", row.NextDueAt)
}
if minNext := queuedAt.Add(24 * time.Hour); row.NextDueAt.Before(minNext) {
t.Fatalf("the next send keeps half the new interval after the queued one, got %v", row.NextDueAt)
}
if got := p.campaignRecipient(queued); got.CancelledAt != nil || got.SendAt == nil || !got.SendAt.Equal(queuedAt) {
t.Fatalf("a queued send keeps its time, got %v", got.SendAt)
}
}
// TestEditEndEarlierCancelsLaterSends checks an earlier end set through the
// update cancels the sends planned at or after it and keeps those before it
func TestEditEndEarlierCancelsLaterSends(t *testing.T) {
p := newProgramWriteTest(t)
programID := p.program(model.ProgramLoopComplete)
stepA := p.step(programID, 0, true)
campaignA := p.stepCampaign(programID, stepA, 0)
end := time.Now().UTC().Add(48 * time.Hour).Truncate(time.Second)
kept := p.sendAt(campaignA, p.recipient("a@example.com"), end.Add(-time.Hour), false)
dropped := p.sendAt(campaignA, p.recipient("b@example.com"), end.Add(time.Hour), false)
update := &model.Program{}
update.EndAt.Set(end)
if err := p.update(programID, update); err != nil {
t.Fatalf("update: %v", err)
}
if p.campaignRecipient(kept).CancelledAt != nil {
t.Fatalf("a send before the new end must be kept")
}
if p.campaignRecipient(dropped).CancelledAt == nil {
t.Fatalf("a send after the new end must be cancelled")
}
}
// TestEditRemoveTemplateCancelsAfterRequestEnds checks the queued sends of a
// removed template are cancelled also when the request ends right after the
// new step list is stored
func TestEditRemoveTemplateCancelsAfterRequestEnds(t *testing.T) {
p := newProgramWriteTest(t)
programID := p.program(model.ProgramLoopComplete)
stepA := p.step(programID, 0, true)
stepB := p.step(programID, 1, true)
campaignB := p.stepCampaign(programID, stepB, 0)
alice := p.recipient("alice@example.com")
p.enroll(programID, alice, 0)
queued := p.sendAt(campaignB, alice, time.Now().Add(time.Hour), false)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// the first read of the sends comes after the new step list is stored
endRequest := func(db *gorm.DB) {
if db.Statement.Table == database.CAMPAIGN_RECIPIENT_TABLE_NAME {
cancel()
}
}
if err := p.db.Callback().Query().After("gorm:query").Register("test:end_request", endRequest); err != nil {
t.Fatalf("register hook: %v", err)
}
if err := p.db.Callback().Row().After("gorm:row").Register("test:end_request", endRequest); err != nil {
t.Fatalf("register hook: %v", err)
}
t.Cleanup(func() {
_ = p.db.Callback().Query().Remove("test:end_request")
_ = p.db.Callback().Row().Remove("test:end_request")
})
update := &model.Program{Name: p.loadProgram(programID).Name, Steps: []*model.ProgramStep{p.keepStep(stepA, 0)}}
if err := p.svc.UpdateByID(ctx, authorizedSession(t), &programID, update); err != nil {
t.Fatalf("update: %v", err)
}
if ctx.Err() == nil {
t.Fatalf("the request must have ended during the edit")
}
if p.campaignRecipient(queued).CancelledAt == nil {
t.Fatalf("the queued send of the removed template must be cancelled")
}
}
// TestResumeMembershipCancelsOnlyWhileAllowed checks the cancels of a resume
// for the people missing now and the people who left before check the
// program under the lock first, so an edit in between keeps their sends
func TestResumeMembershipCancelsOnlyWhileAllowed(t *testing.T) {
p := newProgramLifecycleTest(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
missing := p.recipient("missing@example.com")
left := p.recipient("left@example.com")
p.enroll(programID, missing, 0)
el := p.enroll(programID, left, 0)
p.setEnrollment(el.ID, map[string]any{"status": model.ProgramEnrollmentExited})
missingSend := p.sendAt(campaignID, missing, time.Now().Add(time.Hour), false)
leftSend := p.sendAt(campaignID, left, time.Now().Add(time.Hour), false)
refused := func(*model.Program) bool { return false }
m := programResumeMembership{gone: []*uuid.UUID{&missing}}
done, err := p.svc.finishResumeMembership(p.ctx, &programID, m, time.Now(), refused)
if err != nil || done {
t.Fatalf("expected the resume stopped: done %v err %v", done, err)
}
if p.campaignRecipient(missingSend).CancelledAt != nil {
t.Fatal("a person missing now keeps the send when the program changed")
}
if done, err := p.svc.cancelGoneSends(p.ctx, &programID, refused); err != nil || done {
t.Fatalf("expected the gone cancel stopped: done %v err %v", done, err)
}
if p.campaignRecipient(leftSend).CancelledAt != nil {
t.Fatal("a person who left keeps the send when the program changed")
}
allowed := func(*model.Program) bool { return true }
done, err = p.svc.finishResumeMembership(p.ctx, &programID, m, time.Now(), allowed)
if err != nil || !done {
t.Fatalf("expected the resume membership written: done %v err %v", done, err)
}
if p.campaignRecipient(missingSend).CancelledAt == nil || p.campaignRecipient(leftSend).CancelledAt == nil {
t.Fatal("expected both sends cancelled")
}
}
// TestEndMovedLaterPlansCancelledLastSend checks a completed person whose last
// send an earlier end cancelled is planned again when the end moves later, so
// they still get that template
func TestEndMovedLaterPlansCancelledLastSend(t *testing.T) {
p := newProgramWriteTest(t)
programID := p.program(model.ProgramLoopComplete)
stepA := p.step(programID, 0, true)
stepB := p.step(programID, 1, true)
campaignA := p.stepCampaign(programID, stepA, 0)
campaignB := p.stepCampaign(programID, stepB, 0)
now := time.Now().UTC().Truncate(time.Second)
rid := p.recipient("pat@example.com")
e := p.enroll(programID, rid, 0)
p.sendAt(campaignA, rid, now.Add(-20*24*time.Hour), true)
last := p.sendAt(campaignB, rid, now.Add(5*24*time.Hour), false)
// the earlier end cancelled the last send of the completed person
p.db.Model(&database.CampaignRecipient{}).Where("id = ?", last).Update("cancelled_at", utils.NowRFC3339UTC())
p.setEnrollment(e.ID, map[string]any{
"status": model.ProgramEnrollmentCompleted, "completed_at": now, "next_due_at": nil,
"position": 2, "last_step_id": stepB, "round_start_at": now.Add(-20 * 24 * time.Hour),
})
before := p.loadProgram(programID)
before.EndAt = nullable.NewNullableWithValue(now.Add(2 * 24 * time.Hour))
after := *before
after.EndAt = nullable.NewNullableWithValue(now.Add(60 * 24 * time.Hour))
if err := p.svc.replanPeople(p.ctx, before, &after, false, nil); err != nil {
t.Fatalf("replan: %v", err)
}
if row := p.enrollment(e.ID); row.Status != model.ProgramEnrollmentActive || row.NextDueAt == nil {
t.Fatalf("an end moved later must plan the cancelled template again, got %s", row.Status)
}
}
// TestReplanEndMovedLaterRedrawsParked checks people waiting at the old end
// are drawn again over the spread when the end moves later or is cleared, and
// people with a normal next send keep it
func TestReplanEndMovedLaterRedrawsParked(t *testing.T) {
for _, clear := range []bool{false, true} {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
oldEnd := time.Now().UTC().Add(2 * time.Hour).Truncate(time.Second)
p.setProgram(programID, map[string]any{"end_at": oldEnd, "spread_minutes": 7 * 24 * 60})
p.step(programID, 0, true)
p.step(programID, 1, true)
alice := p.recipient("alice@example.com")
bob := p.recipient("bob@example.com")
parked := p.enroll(programID, alice, 0)
p.setEnrollment(parked.ID, map[string]any{"next_due_at": oldEnd, "round_start_at": time.Now().UTC()})
normal := p.enroll(programID, bob, 0)
bobDue := time.Now().UTC().Add(time.Hour).Truncate(time.Second)
p.setEnrollment(normal.ID, map[string]any{"next_due_at": bobDue})
before := p.loadProgram(programID)
if clear {
p.setProgram(programID, map[string]any{"end_at": nil})
} else {
p.setProgram(programID, map[string]any{"end_at": oldEnd.AddDate(0, 1, 0)})
}
if err := p.svc.replanAfterEdit(p.ctx, before, &programID, false); err != nil {
t.Fatalf("replan: %v", err)
}
row := p.enrollment(parked.ID)
if row.NextDueAt == nil || row.NextDueAt.Equal(oldEnd) {
t.Fatalf("clear=%v: the parked person must be drawn again, got %v", clear, row.NextDueAt)
}
if row := p.enrollment(normal.ID); row.NextDueAt == nil || !row.NextDueAt.Equal(bobDue) {
t.Fatalf("clear=%v: a normal next send is kept, got %v", clear, row.NextDueAt)
}
}
}