//go:build integration package integration import ( "context" "encoding/json" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgtype" "github.com/shopspring/decimal" "github.com/missionworkforce/missionmatch/internal/modules/ai" "github.com/missionworkforce/missionmatch/internal/platform/database/dbgen" ) // seedTeamingOpportunity inserts one expiring opportunity_records row carrying an incumbent UEI and a // pop_end_date inside the forward window, the recompete teaming surface, as the migrator (the global public // catalog the app role may only read). It is the recompete clock side the G2 teaming field reads; the // incumbent neighborhood is resolved over the public awards in the same NAICS. func seedTeamingOpportunity(t *testing.T, srcID, agency, naics, incumbentUEI, incumbentName string, popEnd time.Time) { t.Helper() if err := dbgen.New(migrator).UpsertOpportunityRecord(context.Background(), dbgen.UpsertOpportunityRecordParams{ SourceName: "SAM.gov", SourceRecordID: srcID, RecordKind: "active_solicitation", Title: "Recompete " + srcID, Agency: agency, Naics: naics, IncumbentUei: incumbentUEI, IncumbentName: incumbentName, PopEndDate: pgtype.Date{Time: popEnd, Valid: true}, FetchedAt: time.Now().UTC(), }); err != nil { t.Fatalf("seed teaming opportunity %s: %v", srcID, err) } } // TestG2VendorCooccurrenceField is the live proof of the co occurrence field against real Postgres. It seeds a // (agency, naics) segment with two co occurring recipient UEIs plus the tenant's own is_galapagos award, then // proves the field returns the co occurring set ordered by the dollar concentration with a UEI tiebreaker, // each edge labeled prime-of-record and carrying its source, the tenant's own row flagged is_galapagos, the // segment dollars exact decimals, and byte stable on a re run. The awards arm keys ONLY on (agency, naics). func TestG2VendorCooccurrenceField(t *testing.T) { org := seedOrg(t) run := uuid.NewString()[:8] agency := "DEPT OF THE AIR FORCE " + run // unique per run so the segment is isolated naics := "541512" recent := time.Now().UTC().AddDate(0, -3, 0) // Two co occurring recipients (a dominant and a challenger) plus the tenant's own past performance, all in // the same (agency, naics) segment. seedMarketAward(t, "G2-CO-"+run+"-1", "PIID-1", agency, naics, "UEIDOMINANT01", "Dominant Defense LLC", "8000000.00", recent, false) seedMarketAward(t, "G2-CO-"+run+"-2", "PIID-2", agency, naics, "UEICHALLENG02", "Challenger Two LLC", "2000000.00", recent, false) seedMarketAward(t, "G2-CO-"+run+"-3", "PIID-3", agency, naics, "UEIGALAPAGOS3", "Galapagos Federal", "1000000.00", recent, true) rows, err := ai.VendorCooccurrenceField(ctxOrg(org), appDB, agency, naics) if err != nil { t.Fatalf("vendor co occurrence field: %v", err) } if len(rows) < 3 { t.Fatalf("the field must return the three co occurring recipients, got %d", len(rows)) } // The awards arm leads ordered by the dollar concentration descending; the dominant recipient is first. if rows[0].VendorUEI != "UEIDOMINANT01" { t.Errorf("the dominant recipient must lead the co occurrence field, got %q", rows[0].VendorUEI) } var sawGalapagos bool for _, r := range rows { if r.VendorUEI == "" { t.Error("a co occurring vendor must carry an honest UEI, never the empty string") } if r.VendorRole != "prime-of-record" { t.Errorf("every vendor edge must be labeled prime-of-record, got %q for %s", r.VendorRole, r.VendorUEI) } if r.SourceTable == "" { t.Errorf("every edge must carry its source table, got empty for %s", r.VendorUEI) } if r.SourceTable == "usaspending_awards" && (r.SegmentDollars == nil || r.SegmentDollars.LessThanOrEqual(decimal.Zero)) { t.Errorf("an award sourced edge must carry positive segment dollars as a decimal, got %v for %s", r.SegmentDollars, r.VendorUEI) } if r.VendorUEI == "UEIGALAPAGOS3" && r.SourceTable == "usaspending_awards" { sawGalapagos = true if !r.IsGalapagos { t.Error("the tenant's own past performance row must be labeled is_galapagos") } } } if !sawGalapagos { t.Error("the co occurrence field must include the tenant's own past performance award row") } again, err := ai.VendorCooccurrenceField(ctxOrg(org), appDB, agency, naics) if err != nil { t.Fatalf("vendor co occurrence field re run: %v", err) } first, _ := json.Marshal(rows) second, _ := json.Marshal(again) if string(first) != string(second) { t.Errorf("the co occurrence field must be byte stable on a re run.\nfirst: %s\nsecond: %s", first, second) } } // TestG2PartnerOrCompetitorRatio proves the team versus compete ratio is computed from PUBLIC co occurrence // alone (the is_galapagos self tag), never a tenant table. It seeds a partner that co occurs with the tenant's // own past performance in one market (a team market) and holds the prime alone in a second market in the same // core NAICS (a compete market), and proves the ratio is a meaningful decimal. It also seeds a second partner // with ONLY a team market (no compete market) and proves the ratio divides safely to a null pointer (the // divide by zero guard), never an error. func TestG2PartnerOrCompetitorRatio(t *testing.T) { org := seedOrg(t) run := uuid.NewString()[:8] naics := "541330" recent := time.Now().UTC().AddDate(0, -3, 0) agencyTeam := "DEPT OF DEFENSE " + run // a market where the partner co occurs with the tenant agencyCompete := "DEPT OF THE ARMY " + run // a market where the partner holds the prime alone // The partner UEI must be unique per run: usaspending_awards is a global table on the shared staging DB // and rows persist across runs, so a fixed UEI accumulates extra markets from prior runs (the agencies are // already run suffixed). A unique partner isolates its segments so the exact market counts hold. partner := "UEIP" + run // Team market: the partner and the tenant's own is_galapagos award both in (agencyTeam, naics). seedMarketAward(t, "G2-PR-T1-"+run, "PIID-T1", agencyTeam, naics, partner, "Partner AA LLC", "5000000.00", recent, false) seedMarketAward(t, "G2-PR-T2-"+run, "PIID-T2", agencyTeam, naics, "UEIGALAPAGOS3", "Galapagos Federal", "1000000.00", recent, true) // Compete market: the partner holds the prime alone in (agencyCompete, naics), no tenant award present. seedMarketAward(t, "G2-PR-C1-"+run, "PIID-C1", agencyCompete, naics, partner, "Partner AA LLC", "4000000.00", recent, false) rows, err := ai.PartnerOrCompetitorRatio(ctxOrg(org), appDB, partner, naics) if err != nil { t.Fatalf("partner or competitor ratio: %v", err) } if len(rows) != 1 { t.Fatalf("the ratio must return a single summary row, got %d", len(rows)) } r := rows[0] if r.PartnerUEI != partner { t.Errorf("the summary must name the partner UEI, got %q", r.PartnerUEI) } if r.PartnerRole != "prime-of-record" { t.Errorf("the partner must be labeled prime-of-record, got %q", r.PartnerRole) } if r.TeamMarkets != 1 { t.Errorf("the partner must have exactly 1 team market (co occurring with the tenant), got %d", r.TeamMarkets) } if r.CompeteMarkets != 1 { t.Errorf("the partner must have exactly 1 compete market (prime alone), got %d", r.CompeteMarkets) } // The ratio is team over compete, 1 over 1 equals 1, an exact decimal, never a float. if r.TeamVsCompeteRatio == nil || !r.TeamVsCompeteRatio.Equal(decimal.NewFromInt(1)) { t.Errorf("the team versus compete ratio must be the decimal 1, got %v", r.TeamVsCompeteRatio) } // The divide by zero safe case: a partner with ONLY a team market and no compete market. The ratio divides // to a null decimal pointer (the NULLIF guard), never a divide by zero error. partnerTeamOnly := "UEIB" + run seedMarketAward(t, "G2-PR-TO1-"+run, "PIID-TO1", agencyTeam, naics, partnerTeamOnly, "Partner BB LLC", "3000000.00", recent, false) // (the tenant's own is_galapagos award is already present in agencyTeam from above, so this is a team market) zeroRows, err := ai.PartnerOrCompetitorRatio(ctxOrg(org), appDB, partnerTeamOnly, naics) if err != nil { t.Fatalf("partner or competitor ratio (team only): %v", err) } if len(zeroRows) != 1 { t.Fatalf("the team only ratio must return a single summary row, got %d", len(zeroRows)) } z := zeroRows[0] if z.TeamMarkets != 1 { t.Errorf("the team only partner must have 1 team market, got %d", z.TeamMarkets) } if z.CompeteMarkets != 0 { t.Errorf("the team only partner must have 0 compete markets, got %d", z.CompeteMarkets) } if z.TeamVsCompeteRatio != nil { t.Errorf("a partner with no compete market must divide to a null ratio (the divide by zero guard), got %v", z.TeamVsCompeteRatio) } } // TestG2RecompeteTeamingField proves the recompete teaming field returns the expiring opportunities in the // forward window, each carrying its incumbent UEI labeled prime-of-record joined to that incumbent's co // occurring vendor neighborhood in the same NAICS over the public awards, the likely teaming field before the // RFP drops, ordered by the period of performance end with a unique tiebreaker, and byte stable on a re run. // It includes a NULL slice case: an expiring opportunity whose incumbent has NO co occurring neighborhood, so // the LEFT JOIN yields a null neighbor that must scan cleanly (the empty string neighbor UEI and a nil // neighbor dollars), never a failed scan. func TestG2RecompeteTeamingField(t *testing.T) { org := seedOrg(t) run := uuid.NewString()[:8] agency := "DEPT OF THE NAVY " + run naics := "541512" recent := time.Now().UTC().AddDate(0, -3, 0) soon := time.Now().UTC().AddDate(0, 6, 0) // pop end six months out, inside the default window incumbent := "UEIINCUMBENT01" neighbor := "UEINEIGHBOR002" galapagosNbr := "UEIGALAPAGOS3" // The incumbent and two neighbors all hold awards in the SAME (agency, naics), so the neighbors co occur // with the incumbent. One neighbor is the tenant's own past performance (is_galapagos). seedMarketAward(t, "G2-RT-INC-"+run, "PIID-INC", agency, naics, incumbent, "Incumbent Prime LLC", "9000000.00", recent, false) seedMarketAward(t, "G2-RT-NBR-"+run, "PIID-NBR", agency, naics, neighbor, "Neighbor LLC", "2000000.00", recent, false) seedMarketAward(t, "G2-RT-GAL-"+run, "PIID-GAL", agency, naics, galapagosNbr, "Galapagos Federal", "1000000.00", recent, true) // The expiring opportunity whose incumbent has a real co occurring neighborhood. seedTeamingOpportunity(t, "G2-RT-OPP-"+run, agency, naics, incumbent, "Incumbent Prime LLC", soon) // The NULL slice case: an expiring opportunity in a DIFFERENT NAICS whose incumbent holds no award in that // NAICS, so it has no co occurring neighborhood. The LEFT JOIN must yield a null neighbor that scans cleanly. lonelyNaics := "999999" seedTeamingOpportunity(t, "G2-RT-LONELY-"+run, agency, lonelyNaics, "UEILONELYINC9", "Lonely Inc LLC", soon) rows, err := ai.RecompeteTeamingField(ctxOrg(org), appDB, agency, 0) if err != nil { t.Fatalf("recompete teaming field: %v", err) } if len(rows) == 0 { t.Fatal("the teaming field must return the expiring opportunities and their incumbent neighborhoods") } var sawNeighbor, sawGalapagosNbr, sawLonely bool prevDate := "" for _, r := range rows { // Ordered by the period of performance end ascending (the byte stable order); the dates are non // decreasing. if prevDate != "" && r.PopEndDate < prevDate { t.Errorf("the teaming field must be ordered by the period of performance end ascending, got %s after %s", r.PopEndDate, prevDate) } prevDate = r.PopEndDate if r.IncumbentRole != "prime-of-record" { t.Errorf("the incumbent must be labeled prime-of-record, got %q for %s", r.IncumbentRole, r.OpportunityID) } if r.IncumbentUEI == "" { t.Errorf("every expiring opportunity in the field must carry its incumbent UEI, got empty for %s", r.OpportunityID) } switch r.IncumbentUEI { case incumbent: // The real neighborhood: the neighbor and the galapagos neighbor co occur with the incumbent, the // incumbent's own UEI is excluded from its neighborhood. if r.NeighborUEI == incumbent { t.Error("the incumbent must be excluded from its own neighborhood") } if r.NeighborUEI == neighbor { sawNeighbor = true if r.NeighborDollars == nil || r.NeighborDollars.LessThanOrEqual(decimal.Zero) { t.Errorf("a co occurring neighbor must carry positive segment dollars as a decimal, got %v", r.NeighborDollars) } } if r.NeighborUEI == galapagosNbr { sawGalapagosNbr = true if !r.NeighborIsGalapagos { t.Error("the tenant's own past performance neighbor must be flagged is_galapagos") } } case "UEILONELYINC9": // The NULL slice case: the lonely incumbent has no neighborhood, so the LEFT JOIN yields a null // neighbor that scans cleanly (the empty string neighbor UEI, a nil neighbor dollars, a zero edge // count), never a failed scan. sawLonely = true if r.NeighborUEI != "" { t.Errorf("the lonely incumbent must have an empty neighbor UEI, got %q", r.NeighborUEI) } if r.NeighborDollars != nil { t.Errorf("the lonely incumbent must have a nil neighbor dollars, got %v", r.NeighborDollars) } if r.NeighborEdgeCount != 0 { t.Errorf("the lonely incumbent must have a zero neighbor edge count, got %d", r.NeighborEdgeCount) } } } if !sawNeighbor { t.Error("the teaming field must include the co occurring neighbor of the incumbent") } if !sawGalapagosNbr { t.Error("the teaming field must include the tenant's own past performance neighbor flagged is_galapagos") } if !sawLonely { t.Error("the teaming field must include the lonely incumbent and scan its null neighborhood cleanly (the NULL slice case)") } again, err := ai.RecompeteTeamingField(ctxOrg(org), appDB, agency, 0) if err != nil { t.Fatalf("recompete teaming field re run: %v", err) } first, _ := json.Marshal(rows) second, _ := json.Marshal(again) if string(first) != string(second) { t.Errorf("the recompete teaming field must be byte stable on a re run.\nfirst: %s\nsecond: %s", first, second) } }