diff --git a/README.md b/README.md index 7bb9ba7..187d531 100644 --- a/README.md +++ b/README.md @@ -226,8 +226,10 @@ for a preview or `npm run seed:category-prompts:i18n` to apply. This uses pretranslated local resources for all 25 content languages, **no OPENAI_API_KEY and no external translation service**. New default categories reuse translations from the shared DB cache; custom company prompts are preserved. The same seed -rewrites repeated benefit instructions in existing A1 Slovenija prompts -and structured descriptions without dropping sections. Optional standalone A1 command: +upgrades recognizable obsolete A1 benefit boilerplate to the semantic SEO +body, including previously half-cleaned templates and empty JSON columns. +Unrelated custom descriptions, titles and meta rules remain untouched. Optional +standalone A1 command: `npm run cleanup:a1:prompts -- -apply`. Future A1 seed/WordPress imports now normalize duplicates on ingest. See `docs/category-prompt-translations.md`. @@ -270,3 +272,30 @@ those products to regenerate descriptions, where the company has AI processing configured. A1 and the Platform Demo currently have a separate deliberate backend rule that omits SEO meta from their processed product fields: updating prompt instructions alone does not change that store-level policy. + + +## A1 empty-JSON / partially cleaned category fix (Oct 14, 2026) + +Earlier versions of the offline seed reported `unexpected end of JSON input` +for A1 categories whose `description_template` column was empty. It also missed +A1's two- or three-pair historical prompts and left mixed 100-word and third- +benefit instructions visible in the editor. Both defects are fixed. + +After deployment, preview and repair **only A1**, without touching any other +tenants' prompts (no migration or OpenAI key needed for this code-only fix): + +```bash +npm run cleanup:a1:prompts +npm run cleanup:a1:prompts -- -apply +``` + +Alternatively, `npm run seed:category-prompts:i18n` incorporates the same +A1 cleanup when the global offline defaults should also be seeded. Re-running +either command is safe. No existing processed product descriptions are changed +until they are processed again. Only recognizable A1-imported boilerplate is +replaced; category-specific title/meta rules are preserved. + +Regression coverage includes the exact reported partially cleaned Slovenian +prompt, missing description-template JSON, redundant HTML H1, old 3–10 technical +specification lists, structured-formula metadata, and idempotence. The bundled +`scripts/seed/a1-category-prompts.json` was normalized as well. diff --git a/apps/api/cmd/cleanup-a1-category-prompts/main.go b/apps/api/cmd/cleanup-a1-category-prompts/main.go index c452fcd..f79910a 100644 --- a/apps/api/cmd/cleanup-a1-category-prompts/main.go +++ b/apps/api/cmd/cleanup-a1-category-prompts/main.go @@ -97,7 +97,7 @@ func main() { } updated++ rewrittenPairs += count - log.Printf("category=%s repeated_pairs_rewritten=%d", c.id, count) + log.Printf("category=%s legacy_sections_normalized=%d", c.id, count) if !*apply { continue } @@ -117,5 +117,5 @@ func main() { log.Fatal(fmt.Errorf("category %s changed concurrently; rerun dry-run", c.id)) } } - log.Printf("A1 cleanup: categories_scanned=%d categories_requiring_cleanup=%d rewritten_pairs=%d applied=%v", len(candidates), updated, rewrittenPairs, *apply) + log.Printf("A1 cleanup: categories_scanned=%d categories_requiring_cleanup=%d normalized_sections=%d applied=%v", len(candidates), updated, rewrittenPairs, *apply) } diff --git a/apps/api/cmd/seed-category-prompt-translations/main.go b/apps/api/cmd/seed-category-prompt-translations/main.go index 4fcb42d..75e9f36 100644 --- a/apps/api/cmd/seed-category-prompt-translations/main.go +++ b/apps/api/cmd/seed-category-prompt-translations/main.go @@ -440,7 +440,7 @@ func main() { } } - log.Printf("offline shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d A1_duplicate_pairs_rewritten=%d A1_categories_updated=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Updated, failures, *dryRun) + log.Printf("offline shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d A1_legacy_sections_normalized=%d A1_categories_updated=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Updated, failures, *dryRun) if *dryRun && missing > 0 { log.Printf("dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM") } diff --git a/apps/api/internal/aiprompts/a1_dedupe.go b/apps/api/internal/aiprompts/a1_dedupe.go index b238222..dba8f2e 100644 --- a/apps/api/internal/aiprompts/a1_dedupe.go +++ b/apps/api/internal/aiprompts/a1_dedupe.go @@ -145,17 +145,24 @@ func a1ReplaceTagContent(source string, expression *regexp.Regexp, newInstructio return source[:matches[4]] + newInstruction + source[matches[5]:] } -// isKnownA1Boilerplate only targets the old generated five-benefit formula. -// User-authored copy (even if it contains multiple H2s) is never replaced. +// isKnownA1Boilerplate recognizes the exact historical A1-generated +// instructions, even when a previous cleanup left only one to three pairs. +// Generic custom HTML with H2/P sections must never be replaced. func isKnownA1Boilerplate(body string, blocks int) bool { - if blocks < 4 { + if blocks < 1 { return false } - lower := strings.ToLower(body) - return (strings.Contains(lower, "napiši odstavek, ki je dolg 100 besed") || - strings.Contains(lower, "drugačno in preverjeno prednost") || - strings.Contains(lower, "napiši približno 100 besed o")) && - (strings.Contains(lower, "novo ime izdelka") || strings.Contains(lower, "prednost izdelka")) + lower := strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(body), " ")) + legacy := strings.Contains(lower, "napiši odstavek, ki je dolg 100 besed") + cableLegacy := strings.Contains(lower, "nadaljuj iz naslova in napiši 100 besed") && + strings.Contains(lower, "novo_ime_izdelka") + if !legacy && !cableLegacy { + return false + } + return (strings.Contains(lower, "novo ime izdelka") || strings.Contains(lower, "novo_ime_izdelka")) && + (strings.Contains(lower, "izpostavi en benefit") || + strings.Contains(lower, "prednost izdelka") || + strings.Contains(lower, "preverjeno prednost")) } func localizedA1SEODescription() string { @@ -167,6 +174,7 @@ func localizedA1SEODescription() string { } var a1SpecTrailing = regexp.MustCompile(`(?is)^\s*<\s*b\s*>.*?<\s*/\s*b\s*>\s*<\s*ul\s*>.*?<\s*/\s*ul\s*>`) +var a1RedundantH1 = regexp.MustCompile(`(?is)<\s*h1\s*>\s*\{\s*zapiši\s+novo_ime_izdelka\s*\}\s*<\s*/\s*h1\s*>\s*`) // upgradeKnownA1Boilerplate replaces only the recognizable generated legacy // five-benefit scaffold with short, factual HTML. The title/meta roles and @@ -182,18 +190,37 @@ func upgradeKnownA1Boilerplate(source string) (string, int) { } start, end := blocks[0][0], blocks[len(blocks)-1][1] if match := a1SpecTrailing.FindStringIndex(source[end:]); len(match) == 2 && match[0] == 0 { - end += match[1] + // Discard only the old generic spec instruction. A category-specific + // technical specification rule must remain intact. + trailing := strings.ToLower(source[end : end+match[1]]) + if strings.Contains(trailing, "napiši 3-10 tehničnih specifikacij") || + strings.Contains(trailing, "napiši 3–10 tehničnih specifikacij") { + end += match[1] + } } - return source[:start] + html + source[end:], len(blocks) + updated := source[:start] + html + source[end:] + // Only the known imported A1 scaffold generates a redundant page H1. + // The storefront already renders its own H1 from the product title. + updated = a1RedundantH1.ReplaceAllString(updated, "") + return updated, len(blocks) } // upgradeKnownA1Sections is equally narrow for JSON description_template. // It retains the existing metaTitle/metaDescription and unknown JSON fields. func upgradeKnownA1Sections(raw string) (string, int, error) { + // A1 categories frequently have no structured description_template. + // The HTML prompt alone is valid; an empty JSON column isn't an error. + trimmed := strings.TrimSpace(raw) + if trimmed == "" || trimmed == "null" || trimmed == "{}" { + return raw, 0, nil + } var obj map[string]json.RawMessage if err := json.Unmarshal([]byte(raw), &obj); err != nil { return raw, 0, err } + if len(obj) == 0 || len(obj["sections"]) == 0 || string(obj["sections"]) == "null" { + return raw, 0, nil + } var sections []DescriptionFormulaSection if err := json.Unmarshal(obj["sections"], §ions); err != nil { return raw, 0, nil @@ -263,8 +290,9 @@ func NormalizeA1RepeatedBenefits(source string) (string, int) { return out.String(), rewritten } -// NormalizeA1DescriptionTemplate applies the same non-repeating benefit rules -// to the structured A1 description editor sections. No sections are deleted. +// NormalizeA1DescriptionTemplate upgrades recognizable imported A1 description +// boilerplate to the semantic SEO sections. For unrelated custom descriptions, +// only repeated instructions are rewritten and sections remain intact. func NormalizeA1DescriptionTemplate(raw string) (string, int, error) { if cleaned, n, err := upgradeKnownA1Sections(raw); err != nil || n > 0 { return cleaned, n, err diff --git a/apps/api/internal/aiprompts/a1_dedupe_test.go b/apps/api/internal/aiprompts/a1_dedupe_test.go index 9f8d522..45790e1 100644 --- a/apps/api/internal/aiprompts/a1_dedupe_test.go +++ b/apps/api/internal/aiprompts/a1_dedupe_test.go @@ -143,3 +143,118 @@ func TestNormalizeA1LegacyStructuredSEO(t *testing.T) { t.Fatal("not repeatable") } } + +func TestNormalizeA1MissingDescriptionJSON(t *testing.T) { + for _, source := range []string{"", " ", "null", "{}", `{"metaDescription":"140 znakov"}`, `{"sections":null,"metaTitle":"Custom"}`} { + result, changed, err := NormalizeA1DescriptionTemplate(source) + if err != nil || changed != 0 || result != source { + t.Fatalf("source=%q changed=%d err=%v result=%q", source, changed, err, result) + } + } +} + +func TestNormalizeA1MixedOldAndNewInstructions(t *testing.T) { + source := `
{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}
+{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}
+ + +{Napiši približno 100 besed o 3. samostojni, z dejanskimi podatki podprti prednosti. Ne ponavljaj informacij iz prejšnjih odstavkov. Ne uporabi celotnega novega imena izdelka. Če prednosti ni mogoče potrditi z vhodnimi podatki, je ne izmišljaj.}
{Tehnične specifikacije}{") { + t.Fatalf("expected modern SEO description with 1 intro, 2 sections and one specs list: %s", cleaned) + } + again, changed := NormalizeA1RepeatedBenefits(cleaned) + if changed != 0 || again != cleaned { + t.Fatal("mixed A1 cleanup not idempotent") + } +} + +func TestNormalizeA1ShortLegacyAndPreservesOtherRoles(t *testing.T) { + source := `--- Title --- +{Ohranite naslov in pravila iz kategorije} +--- End Title --- +--- Description --- +
{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}
+{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}
+{Tehnične specifikacije}{Napiši opis glede na navedena dejstva, brez ugibanja.}
` + actual, changed := NormalizeA1RepeatedBenefits(source) + if actual != source || changed != 0 { + t.Fatalf("unexpected change of custom text: %s", actual) + } +} + +func TestNormalizeA1LegacyEnDashSpecs(t *testing.T) { + source := `{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}
+Tehnične specifikacije +{Nadaljuj iz naslova in napiši 100 besed o temu benefitu, ne vključuj Novo_ime_izdelka}
` + got, count := NormalizeA1RepeatedBenefits(source) + if count != 1 || strings.Contains(strings.ToLower(got), "`, optional `
` and optional `