package service import ( "context" "strings" "testing" "github.com/glebarez/sqlite" repositories "gitlab.com/mbugroup/lti-api.git/internal/modules/master/production-standards/repositories" "gitlab.com/mbugroup/lti-api.git/internal/utils" "gorm.io/gorm" ) func TestEnsureWeekAvailableAllowsLayingBeforeFirstCommonStandardWeek(t *testing.T) { svc := setupProductionStandardServiceTest(t) if err := svc.EnsureWeekAvailable(context.Background(), 1, string(utils.ProjectFlockCategoryLaying), 85); err != nil { t.Fatalf("expected pre-standard laying week to be allowed, got %v", err) } } func TestEnsureWeekAvailableRejectsLayingMissingWeekAfterStandardStarts(t *testing.T) { svc := setupProductionStandardServiceTest(t) err := svc.EnsureWeekAvailable(context.Background(), 1, string(utils.ProjectFlockCategoryLaying), 127) if err == nil { t.Fatal("expected missing laying standard week to be rejected") } if !strings.Contains(err.Error(), "week 19") { t.Fatalf("expected error to mention requested week 19, got %v", err) } } func TestEnsureWeekAvailableKeepsGrowingWeekStrict(t *testing.T) { svc := setupProductionStandardServiceTest(t) err := svc.EnsureWeekAvailable(context.Background(), 2, string(utils.ProjectFlockCategoryGrowing), 8) if err == nil { t.Fatal("expected missing growing standard week to be rejected") } if !strings.Contains(err.Error(), "week 2") { t.Fatalf("expected error to mention requested week 2, got %v", err) } } func setupProductionStandardServiceTest(t *testing.T) productionStandardService { t.Helper() db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=private"), &gorm.Config{}) if err != nil { t.Fatalf("failed opening sqlite db: %v", err) } statements := []string{ `CREATE TABLE production_standard_details ( id INTEGER PRIMARY KEY, production_standard_id INTEGER NOT NULL, week INTEGER NOT NULL, target_hen_day_production NUMERIC NULL, target_hen_house_production NUMERIC NULL, target_egg_weight NUMERIC NULL, target_egg_mass NUMERIC NULL, standard_fcr NUMERIC NULL, created_at TIMESTAMP NULL, updated_at TIMESTAMP NULL )`, `CREATE TABLE standard_growth_details ( id INTEGER PRIMARY KEY, production_standard_id INTEGER NOT NULL, target_mean_bw NUMERIC NULL, max_depletion NUMERIC NULL, min_uniformity NUMERIC NOT NULL, week INTEGER NOT NULL, feed_intake NUMERIC NULL, created_at TIMESTAMP NULL, created_by INTEGER NOT NULL )`, `INSERT INTO production_standard_details (id, production_standard_id, week, standard_fcr) VALUES (1, 1, 18, 2.1)`, `INSERT INTO standard_growth_details (id, production_standard_id, week, min_uniformity, created_by) VALUES (1, 1, 18, 80, 1), (2, 2, 1, 80, 1)`, } for _, stmt := range statements { if err := db.Exec(stmt).Error; err != nil { t.Fatalf("failed preparing schema: %v", err) } } return productionStandardService{ ProductionStandardDetailRepo: repositories.NewProductionStandardDetailRepository(db), StandardGrowthDetailRepo: repositories.NewStandardGrowthDetailRepository(db), } }