Compare commits
26
Commits
176b1fe47f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ec433815b | ||
|
|
e7964c58c8 | ||
|
|
41f1a7dbe4 | ||
|
|
eefb7e2b75 | ||
|
|
1ad180a052 | ||
|
|
c347d2418f | ||
|
|
edbbf127ba | ||
|
|
fd83a7c523 | ||
|
|
c83347b9a5 | ||
|
|
1c003e30a4 | ||
|
|
0e48ea427b | ||
|
|
486502852e | ||
|
|
feebf7d3c1 | ||
|
|
1e7c7bbfbb | ||
|
|
6586722652 | ||
|
|
26e7453ad9 | ||
|
|
cfd31f398c | ||
|
|
04794aea54 | ||
|
|
af670e79f0 | ||
|
|
c92ee93482 | ||
|
|
8b540d22bc | ||
|
|
3b0d692839 | ||
|
|
43cfaa0411 | ||
|
|
ff6c2df618 | ||
|
|
7537a41955 | ||
|
|
3bfeb6b61e |
No files matched your search
+1
-1
@@ -19,7 +19,7 @@ coverage/
|
|||||||
*.log
|
*.log
|
||||||
*cookies.txt
|
*cookies.txt
|
||||||
*.cookies.txt
|
*.cookies.txt
|
||||||
|
examples/
|
||||||
# Runtime uploads (keep data/sample-*.csv)
|
# Runtime uploads (keep data/sample-*.csv)
|
||||||
data/uploads/
|
data/uploads/
|
||||||
apps/api/data/uploads/
|
apps/api/data/uploads/
|
||||||
|
|||||||
@@ -1,3 +1,40 @@
|
|||||||
|
# Admin billing create/edit plan hotfix (October 14, 2026)
|
||||||
|
|
||||||
|
The Create plan form previously called `.trim()` on `max_products` and `yearly_credits`. Svelte's number inputs bind numeric values as numbers (or `undefined` when empty), causing `max_products.trim is not a function` and preventing custom Demo plans from being created.
|
||||||
|
|
||||||
|
**Fix:** Both optional limits now normalize to positive/zero safe integers or `null` (unlimited/unset), monthly credits allow `0`, and invalid numeric values show a field-specific error without sending a request. The same correction applies to **Edit plan**.
|
||||||
|
|
||||||
|
No migration, API update, or seed is needed. **Deploy the updated web frontend** and reload `/admin/billing`.
|
||||||
|
|
||||||
|
Regression tests:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd apps/web
|
||||||
|
node --experimental-strip-types --test src/lib/admin-plan-form.test.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
This package includes all earlier v8 changes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# v8 fix — existing non-A1 language prompts
|
||||||
|
|
||||||
|
This update addresses the remaining English/Croatian/Bulgarian mismatch in existing non-A1 categories. It includes the exact historical v3 locale snapshots, so the seed can identify the old five-section translations and upgrade them **without overriding custom company instructions**. It also updates any exact old structured description formula that would otherwise force the AI to output five H2 sections.
|
||||||
|
|
||||||
|
**Run after deploying API + worker + frontend**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run migrate
|
||||||
|
npm run seed:category-prompts:i18n -- -dry-run
|
||||||
|
npm run seed:category-prompts:i18n
|
||||||
|
```
|
||||||
|
|
||||||
|
Check `legacy_upgraded` and `non_a1_legacy_locales_repaired` in the seed output, then reload the category editor. No OpenAI key is needed for the seed. See `docs/seo-prompts-v8.md` and `docs/seo-prompts-all-25-languages.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> **Prompt hotfix v7 (October 2026):** Fixed the API/worker Go compile error, normalized all 25 languages to brace-delimited SEO title/HTML description/meta instructions, and corrected the offline seed's stale shared cache and v6 legacy migration. A1's obsolete meta rule is upgraded, and A1 SEO meta is no longer silently discarded. Run `npm run migrate` then `npm run seed:category-prompts:i18n`. See [docs/seo-prompts-v7.md](docs/seo-prompts-v7.md).
|
||||||
|
|
||||||
# Descrybe v2
|
# Descrybe v2
|
||||||
|
|
||||||
Go API + SvelteKit frontend + PostgreSQL rewrite of Descrybe (no Clerk).
|
Go API + SvelteKit frontend + PostgreSQL rewrite of Descrybe (no Clerk).
|
||||||
@@ -217,3 +254,85 @@ go run ./cmd/migrator -mysql "$MIGRATE_MYSQL_DSN" -postgres "$DATABASE_URL" -dry
|
|||||||
- [docs/schema-map.md](docs/schema-map.md) — MySQL → Postgres ID maps
|
- [docs/schema-map.md](docs/schema-map.md) — MySQL → Postgres ID maps
|
||||||
- [docs/cutover.md](docs/cutover.md) — production cutover runbook
|
- [docs/cutover.md](docs/cutover.md) — production cutover runbook
|
||||||
- [docs/ops-runtime.md](docs/ops-runtime.md) — SMTP, sessions, Woo encryption
|
- [docs/ops-runtime.md](docs/ops-runtime.md) — SMTP, sessions, Woo encryption
|
||||||
|
|
||||||
|
|
||||||
|
## Offline category prompt translations and A1 cleanup
|
||||||
|
|
||||||
|
Run `npm run migrate`, then `npm run seed:category-prompts:i18n -- -dry-run`
|
||||||
|
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
|
||||||
|
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`.
|
||||||
|
|
||||||
|
## SEO product formulas v4 (25 content languages)
|
||||||
|
|
||||||
|
All supported languages now use the same **semantic product-page HTML skeleton** with
|
||||||
|
localized instructions in `{...}`: one verified introductory `<p>`, an optional
|
||||||
|
feature `<h2>` and `<p>` when product facts justify them, then an optional technical
|
||||||
|
specification `<h2>` and `<ul><li>` list. Never generate an `<h1>` inside the
|
||||||
|
body, an empty list, fabricated product claims, or repeat a fixed number of
|
||||||
|
100-word sales sections. Product `name`, `meta_title`, and `meta_description` are
|
||||||
|
separate **plain-text JSON fields**, not HTML in the body. Keep structured data,
|
||||||
|
product-page H1, and the real page heading in the storefront template.
|
||||||
|
|
||||||
|
`apps/api/internal/aiprompts/defaults/prompt-rules-25.json` is the canonical
|
||||||
|
**offline** set of 25 language versions; the category editor examples carry the
|
||||||
|
same instructions. The API now parses the `<ul><li>` formula as one list section,
|
||||||
|
keeps optional sections optional during validation, and prefers the category
|
||||||
|
formula over generic short-copy system instructions. Translations do not require
|
||||||
|
an OpenAI key (product *generation* still uses the configured AI integration).
|
||||||
|
|
||||||
|
After deploying the API, worker, web frontend, and running migration scripts:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run migrate
|
||||||
|
npm run seed:category-prompts:i18n -- -dry-run
|
||||||
|
npm run seed:category-prompts:i18n
|
||||||
|
```
|
||||||
|
|
||||||
|
Only prompts identifiable as unchanged built-in defaults are upgraded; custom
|
||||||
|
company formulas are preserved. A1's recognizable historical repeated boilerplate
|
||||||
|
is repaired by the seed, and can also be repaired independently with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run cleanup:a1:prompts -- -apply
|
||||||
|
```
|
||||||
|
|
||||||
|
**Existing processed products are not rewritten by a prompt seed**. Reprocess
|
||||||
|
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.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Descrybe: processing credit settings and Unicode exports (2026-10-20)
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
- Fixed `PUT /api/admin/credit-value-eur` failing with `unknown settings key`. The platform-settings allowlist now permits the `billing.reference_eur_per_credit` value (not a secret).
|
||||||
|
- Fixed `GET /api/admin/processing-costs` reporting `could not scan processing costs` by reading PostgreSQL numeric/integer costs as text, then explicitly parsing into the JSON response. This avoids driver conversion problems across schema revisions.
|
||||||
|
- Product Management can still start a valid full-enrichment request when the *credit estimate* endpoint is temporarily unavailable, without displaying an invented credit estimate. A retry action is provided. Permission and billing checks still happen on the API/worker side.
|
||||||
|
- Price, stock and availability remain optional supplier/product inputs; missing values are not fabricated or used to block enrichment.
|
||||||
|
- All server-generated CSV downloads (product exports, public feed CSV, usage, Stripe invoices, AI costs) now use UTF-8 plus a single BOM (`EF BB BF`) for direct Microsoft Excel compatibility.
|
||||||
|
- Browser-generated CSV/TSV downloads (categories, attribute templates, sample feed) use UTF-8 with BOM. XML and JSON exports remain standard UTF-8 **without** a BOM.
|
||||||
|
- Added tests for credit reference-setting permission, price/stock-optional enrichment, CSV/TSV Unicode and XML/JSON preservation.
|
||||||
|
|
||||||
|
## Deploy
|
||||||
|
|
||||||
|
1. Backup your database and deploy **both** the updated Go API/worker and SvelteKit web client. Don't just upload the web files.
|
||||||
|
2. Apply existing database migrations through `054_catalog_import_languages.sql`, especially `049_processing_cost_overrides.sql` and `053_content_credit_rates.sql`. From the project root, `npm run migrate` after setting up the database environment.
|
||||||
|
3. Rebuild/restart API and web; refresh the UI.
|
||||||
|
4. In Admin > Billing, save the EUR-per-credit **reference value**. Set the actual product/output credit costs on the plan separately; **EUR reference value does not set processing charges**.
|
||||||
|
5. Check `GET /api/admin/processing-costs` and `GET /api/billing/processing-costs` with appropriate authenticated roles.
|
||||||
|
6. Try an imported product with no price/stock information, and export `Črpalka, šoba, Žarnica` to CSV. A CSV file should begin `EF BB BF` and decode as UTF-8.
|
||||||
|
|
||||||
|
## Validation in this environment
|
||||||
|
|
||||||
|
- Focused JS tests (pricing fallback, plan mode, UTF-8 exports): **6 passed, 0 failed**.
|
||||||
|
- Full web test suite: **299 passed, 6 failed**, due to unrelated existing translation key discrepancies, an absent source file and missing dependencies in the supplied archive.
|
||||||
|
- Go source was formatted/parsed by `gofmt`. Full Go tests/build could not be run here: project requires Go 1.25, host has Go 1.23.2, and external downloads are unavailable. Run `go test ./internal/platformsettings ./internal/feeds ./internal/httpapi ./internal/billing ./internal/processing` from `apps/api` in your Go 1.25 environment.
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# JAGER × Descrybe – 30-minutni sestanek
|
||||||
|
|
||||||
|
**Cilj:** na dejanskih izdelkih pokazati pot od dobaviteljevega vira do slovenskega naziva, opisa, SEO podatkov in izvoza. Na koncu potrdimo, ali je Descrybe za JAGER primeren, kaj potrebujejo in kakšna je ponudba. **Brez tehničnega razvoja po meri.**
|
||||||
|
|
||||||
|
## Potek (30 minut)
|
||||||
|
|
||||||
|
| Čas | Tema | Kaj naredimo |
|
||||||
|
|---|---|---|
|
||||||
|
| **0–5 min** | Potrebe | Vprašamo, koliko **različnih EAN-ov** imajo v katalogu in koliko **obdelav mesečno** (omenjenih ~1.000); koliko jezikov in kam bodo izvažali. |
|
||||||
|
| **5–15 min** | Živ prikaz | Odpremo **GROHE CSV** in **EMOS XML**, pokažemo preslikavo, kategorije/atribute ter izbor 5–10 njihovih EAN-ov. Če je pripravljen, pogledamo še **Sanotechnik JSON**. |
|
||||||
|
| **15–20 min** | AI | Obdelamo 1–2 izdelka: naslov, slovenski HTML opis in SEO meta. Pokažemo pregled, popravek in porabo kreditov. Prikaz izvedemo le s testnimi krediti. |
|
||||||
|
| **20–25 min** | Rezultat | Izvoz razpoložljivih polj v CSV/XML/JSON; pokažemo, kako lahko sami urejajo vir. |
|
||||||
|
| **25–30 min** | Dogovor | Povzamemo primeren paket, ceno začetne nastavitve in podatke, ki jih še potrebujemo; dogovorimo se za naslednji korak. |
|
||||||
|
|
||||||
|
## Šest vprašanj, ki jih moramo dobiti odgovorjenih
|
||||||
|
|
||||||
|
1. **Koliko aktivnih, unikatnih EAN-ov imate skupaj?** Je 1.000 število novih/ponovno AI-obdelanih izdelkov *na mesec* ali velikost celotnega kataloga?
|
||||||
|
2. **Kateri dobavitelji so prva prioriteta?** Predlagamo GROHE, EMOS in Sanotechnik. Ali imajo za KOOPMAN, TRBOVC in Groupe SEB dejanski CSV/XML/JSON?
|
||||||
|
3. **Katere podatke želite izboljšati?** Naslov, opis, SEO meta ali vse; kateri jezik oziroma jeziki?
|
||||||
|
4. **Kam se bo vsebina izvažala?** Potrebujemo vzorec formata in zahtevana polja (EAN, SKU, kategorija, atributi, slike, opisi …).
|
||||||
|
5. **Kdo bo upravljal vire in potrjeval vsebino?** Sami ali želite plačljivo začetno pomoč?
|
||||||
|
6. **Kdaj želite začeti?** Kdo odobri naročnino in enkratno nastavitev?
|
||||||
|
|
||||||
|
## Kaj potrebujemo pred začetkom
|
||||||
|
|
||||||
|
- Njihov **seznam EAN-ov v TXT/CSV** in 5–10 EAN-ov za demo.
|
||||||
|
- Povezave ali datoteke **CSV/XML/JSON** in dostopne podatke, če so potrebni.
|
||||||
|
- Želeni **jezik, izvozni format in primer pričakovanega rezultata**.
|
||||||
|
- Odgovorno kontaktno osebo za preverjanje rezultatov.
|
||||||
|
|
||||||
|
## Kaj ponujamo in česa ne
|
||||||
|
|
||||||
|
**Vključeno v aplikacijo:** uvoz in sinhronizacija podprtih strukturiranih virov; preslikava polj; kategorije in atributi iz razpoložljivih podatkov; AI nazivi/opisi/SEO; pregled rezultatov; izvoz CSV/XML/JSON in uporaba ustreznih energetskih podatkov, ko so preverljivo na voljo.
|
||||||
|
|
||||||
|
**Ni del standardne storitve:** branje PDF katalogov; scraping spletnih strani; ročno prepisovanje produktov; razvoj prilagojenih ERP konektorjev; ustvarjanje manjkajočih slik, energetskih nalepk ali slovenskih dokumentov; jamstvo, da bodo podatki dobavitelja popolni. Pri KOOPMAN energijske podatke in slovenske listine preverimo pri dobavitelju/EPREL.
|
||||||
|
|
||||||
|
## Ponudba (predlog, brez DDV)
|
||||||
|
|
||||||
|
| Možnost | Enkratna cena | Kaj je vključeno |
|
||||||
|
|---|---:|---|
|
||||||
|
| **Samostojno** | **0 €** | Naročnik sam nastavi vire po navodilih; brez vključenih ur uvajanja. |
|
||||||
|
| **Prvi vir** | **199 €** | Do 1 strukturiranega vira, osnovna preslikava, test; do 30 min uvoda, približno 1–2 delovna dneva. |
|
||||||
|
| **3 dobavitelji – priporočeno za začetek** | **649 €** | Do 3 standardni viri, preslikave, osnovne kategorije/atributi, test in izvoz; do 1 h usposabljanja, približno 3–5 delovnih dni. |
|
||||||
|
| **Poslovni zagon** | **1.490 €** | Do 5 standardnih virov, uskladitev izvoznega profila; do 2 h usposabljanja, približno 5–10 delovnih dni. |
|
||||||
|
| **Večji standardni katalog** | **2.490 €** | Do 8 podprtih virov, več preslikav, QA; do 3 h usposabljanja, približno 2–3 tedne. |
|
||||||
|
|
||||||
|
**Naročnina ločeno:** Growth **299 €/mes.** (do 1.200 SKU, 5 virov, 1.200 kreditov); Business **499 €/mes.** (do 4.000 SKU, 8 virov, 4.000 kreditov). Za ~1.000 izdelkov na mesec ne izberemo avtomatsko Business: potrebo določajo **aktivni SKU + število virov + konfigurirana poraba kreditov**. Pri standardnih treh operacijah je primer **0,10 + 0,25 + 0,10 = 0,45 kredita/izdelek**; pri posebnem paketu *Per product* velja njegova ročno nastavljena cena. Za 1.000 izdelkov je to pri 0,45 približno **450 kreditov**, če ni dodatnih obdelav ali jezikov. Pred ponudbo preverimo realno porabo in omogočene funkcije. Cene v EUR veljajo po potrditvi ustreznih cen v Stripe.
|
||||||
|
|
||||||
|
**Podpora:** paketi vključujejo tehnično podporo skladno s cenikom, **ne** pa neomejenih ur nastavitev ali svetovanja. Ure v tabeli so enkratne. Ni dodatnih storitev brez dogovora.
|
||||||
|
|
||||||
|
## Kratki odgovori in zaključek
|
||||||
|
|
||||||
|
- **»Ali se lahko povežemo sami?«** Da, če dobavitelj zagotavlja ustrezen CSV, XML ali JSON in deluje z obstoječimi preslikavami.
|
||||||
|
- **»Zakaj GROHE še nima prevoda?«** Uvoz ni AI obdelava. Preverimo jezik, pravila in kreditno stanje ter na srečanju izvedemo test.
|
||||||
|
- **»Kaj pa PDF TRBOVC?«** PDF katalogov ne obdelujemo; dobavitelj mora dati strukturirane podatke.
|
||||||
|
- **»Ali lahko preizkusimo pred nakupom?«** Da, ponudimo kratek prikaz na 5–10 njihovih EAN-ih s posebej odobrenimi testnimi krediti.
|
||||||
|
- **»Kaj pa energijski listi?«** Uporabimo preverjene dobaviteljske/EPREL podatke; manjkajočih dokumentov ne izdelujemo.
|
||||||
|
|
||||||
|
**Zaključni stavek:** »Predlagam, da najprej brezplačno preizkusimo nekaj vaših EAN-ov, skupaj pogledamo kakovost slovenskih opisov in izvoz. Če ste zadovoljni, vam nastavimo prve tri dobavitelje za 649 € in izberemo naročnino glede na dejansko velikost kataloga ter mesečno porabo.«
|
||||||
|
|
||||||
|
**Po sestanku zapišemo:** potrjeni dobavitelji · EAN število · število obdelav · jeziki · zahtevana izvozna polja · odgovor odgovorne osebe · dogovorjeni naslednji korak.
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Descrybe v19 — Per-product plan pricing + JAGER meeting
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
- Admin > Billing > Create/Edit plan: **Processing mode** dropdown (`Choose outputs` or `Per product`).
|
||||||
|
- `Per product` sets a flat, decimal credit charge for one product process; it replaces the 3 output checkboxes in Product Management **only for companies assigned to such plans**.
|
||||||
|
- Per-output pricing remains the default for all existing plans. Legacy plans can opt in by editing them.
|
||||||
|
- The effective customer/company price is used for display, preflight balance checks, and actual debits, including public API processing.
|
||||||
|
- Updated concise 30-minute Slovenian JAGER meeting in `README_JAGER_SESTANEK_SL.md`, `README_SESTANEK_SL.md`, and `docs/client/`.
|
||||||
|
- Detailed acceptance checks: `docs/V19_PER_PRODUCT_PLAN_MODE.md`.
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
Commit this source to Git and run the existing deployment. Requires the previously applied migrations 049 and 053. No new migration is needed. Deploy frontend/API/worker together.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Passed: isolated Go 1.23 test of the exact flat-rate debit function; 4 focused Node frontend tests; changed Go source formatting, Svelte script parsing, and Svelte control-flow balance checks. Full Go 1.25, Svelte production build, and live PostgreSQL/Stripe tests were not available in this environment.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Descrybe v20
|
||||||
|
|
||||||
|
- Admin-editable EUR-per-credit **reference** value (kept separate from checkout/invoices).
|
||||||
|
- Per-language CSV/JSON catalog imports and XML/CSV/JSON feed-sync language selection.
|
||||||
|
- Catalog translation storage isolated by tenant, entity key and language.
|
||||||
|
- Database migration 054 required.
|
||||||
|
|
||||||
|
See `docs/V20_CREDIT_VALUE_AND_IMPORT_LANGUAGES.md` for API request examples and safe deployment notes.
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
// Rewrite repeated heading/paragraph instructions in A1 Slovenija prompts,
|
||||||
|
// keeping the section count and intended product-name inclusion rules.
|
||||||
|
// Runs only for the A1 tenant and never rewrites title or meta instructions.
|
||||||
|
// Dry run by default; pass -apply to write changes atomically.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/config"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
const a1ID = "604f23a8-b66e-4b21-8b45-0d72b68f4790"
|
||||||
|
|
||||||
|
func normalizeSections(raw string) (string, int, error) {
|
||||||
|
return aiprompts.NormalizeA1DescriptionTemplate(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
config.LoadDotEnv()
|
||||||
|
databaseURL := flag.String("postgres", os.Getenv("DATABASE_URL"), "Postgres connection URL")
|
||||||
|
apply := flag.Bool("apply", false, "commit changes (default: dry run)")
|
||||||
|
flag.Parse()
|
||||||
|
if strings.TrimSpace(*databaseURL) == "" {
|
||||||
|
log.Fatal("DATABASE_URL is required")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
db, err := pgxpool.New(ctx, *databaseURL)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
rows, err := db.Query(ctx, `SELECT c.id, COALESCE(c.prompt, '{}'::jsonb)::text,
|
||||||
|
COALESCE(c.description_template::text, '')
|
||||||
|
FROM categories c JOIN companies co ON co.id = c.company_id
|
||||||
|
WHERE (co.id = $1 OR LOWER(BTRIM(co.name)) = 'a1 slovenija')
|
||||||
|
ORDER BY c.name`, uuid.MustParse(a1ID))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
type candidate struct {
|
||||||
|
id uuid.UUID
|
||||||
|
prompt, desc string
|
||||||
|
}
|
||||||
|
candidates := make([]candidate, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var c candidate
|
||||||
|
if err := rows.Scan(&c.id, &c.prompt, &c.desc); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
candidates = append(candidates, c)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
if len(candidates) == 0 {
|
||||||
|
log.Fatal("no A1 Slovenija categories found; no changes made")
|
||||||
|
}
|
||||||
|
updated, rewrittenPairs := 0, 0
|
||||||
|
for _, c := range candidates {
|
||||||
|
var prompts map[string]string
|
||||||
|
if err := json.Unmarshal([]byte(c.prompt), &prompts); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
if prompts == nil {
|
||||||
|
prompts = map[string]string{}
|
||||||
|
}
|
||||||
|
changed, count := false, 0
|
||||||
|
for language, text := range prompts {
|
||||||
|
cleaned, n := aiprompts.NormalizeA1RepeatedBenefits(text)
|
||||||
|
locale := language
|
||||||
|
if locale == "*" {
|
||||||
|
locale = "sl"
|
||||||
|
}
|
||||||
|
if meta, repaired := aiprompts.NormalizeA1MetaRole(cleaned, locale); repaired {
|
||||||
|
cleaned = meta
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if n != 0 {
|
||||||
|
changed = true
|
||||||
|
count += n
|
||||||
|
}
|
||||||
|
prompts[language] = cleaned
|
||||||
|
}
|
||||||
|
desc, n, err := normalizeSections(c.desc)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
if n != 0 {
|
||||||
|
count += n
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if meta, repaired, metaErr := aiprompts.NormalizeA1MetaTemplate(desc, "sl"); metaErr != nil {
|
||||||
|
log.Fatal(metaErr)
|
||||||
|
} else if repaired {
|
||||||
|
desc = meta
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
updated++
|
||||||
|
rewrittenPairs += count
|
||||||
|
log.Printf("category=%s legacy_sections_normalized=%d", c.id, count)
|
||||||
|
if !*apply {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(prompts)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
tag, err := db.Exec(ctx, `UPDATE categories SET prompt=$2::jsonb,
|
||||||
|
description_template=NULLIF($3, '')::jsonb, updated_at=now()
|
||||||
|
WHERE id=$1 AND COALESCE(prompt, '{}'::jsonb)::text=$4
|
||||||
|
AND COALESCE(description_template::text, '')=$5`,
|
||||||
|
c.id, string(encoded), desc, c.prompt, c.desc)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
if tag.RowsAffected() != 1 {
|
||||||
|
log.Fatal(fmt.Errorf("category %s changed concurrently; rerun dry-run", c.id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.Printf("A1 cleanup: categories_scanned=%d categories_requiring_cleanup=%d normalized_sections=%d applied=%v", len(candidates), updated, rewrittenPairs, *apply)
|
||||||
|
}
|
||||||
@@ -102,7 +102,7 @@ func loadCategoryPromptsFromWPSQL(path string) (categoryPromptsFile, error) {
|
|||||||
entries = append(entries, categoryPromptEntry{
|
entries = append(entries, categoryPromptEntry{
|
||||||
Name: e.Name,
|
Name: e.Name,
|
||||||
UniqueID: e.UniqueID,
|
UniqueID: e.UniqueID,
|
||||||
Prompt: e.Prompt,
|
Prompt: func() string { value, _ := aiprompts.NormalizeA1RepeatedBenefits(e.Prompt); return value }(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if len(entries) == 0 {
|
if len(entries) == 0 {
|
||||||
@@ -201,6 +201,7 @@ func applyCategoryPrompts(ctx context.Context, pg *pgxpool.Pool, companyID uuid.
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
raw := strings.TrimSpace(e.Prompt)
|
raw := strings.TrimSpace(e.Prompt)
|
||||||
|
raw, _ = aiprompts.NormalizeA1RepeatedBenefits(raw)
|
||||||
var canonical string
|
var canonical string
|
||||||
if raw == "" {
|
if raw == "" {
|
||||||
out.Skipped++
|
out.Skipped++
|
||||||
@@ -216,6 +217,9 @@ func applyCategoryPrompts(ctx context.Context, pg *pgxpool.Pool, companyID uuid.
|
|||||||
out.Skipped++
|
out.Skipped++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if metaNormalized, changed := aiprompts.NormalizeA1MetaRole(canonical, "sl"); changed {
|
||||||
|
canonical = metaNormalized
|
||||||
|
}
|
||||||
if canonical == "" {
|
if canonical == "" {
|
||||||
out.Skipped++
|
out.Skipped++
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -0,0 +1,883 @@
|
|||||||
|
// Command seed-category-prompt-translations permanently caches translations of
|
||||||
|
// PLATFORM DEFAULT category prompts for every tenant and all new categories.
|
||||||
|
// Categories with any custom prompt are never modified. Safe to rerun.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
//
|
||||||
|
// go run ./cmd/seed-category-prompt-translations -dry-run
|
||||||
|
// go run ./cmd/seed-category-prompt-translations
|
||||||
|
// go run ./cmd/seed-category-prompt-translations -langs sl,hr,de
|
||||||
|
//
|
||||||
|
// Requires migration 048 and DATABASE_URL only. No API key or LLM is used.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/config"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type categoryRow struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
Company uuid.UUID
|
||||||
|
Name string
|
||||||
|
UID string
|
||||||
|
Prompts company.LangPromptMap
|
||||||
|
Raw []byte
|
||||||
|
Title string
|
||||||
|
Desc string
|
||||||
|
CompanyName string
|
||||||
|
}
|
||||||
|
|
||||||
|
func langsToSeed(raw string) ([]string, error) {
|
||||||
|
if strings.TrimSpace(raw) == "" {
|
||||||
|
return append([]string(nil), company.ContentLanguages...), nil
|
||||||
|
}
|
||||||
|
unique := map[string]bool{}
|
||||||
|
out := make([]string, 0)
|
||||||
|
for _, input := range strings.Split(raw, ",") {
|
||||||
|
lang, err := company.ParseLanguage(input, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !unique[lang] {
|
||||||
|
out = append(out, lang)
|
||||||
|
unique[lang] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetchCategories includes NULL/empty prompts: those also receive defaults.
|
||||||
|
func fetchCategories(ctx context.Context, pool *pgxpool.Pool, id uuid.UUID, all bool) ([]categoryRow, error) {
|
||||||
|
query := `SELECT c.id, c.company_id, c.name, c.unique_id,
|
||||||
|
COALESCE(c.prompt, '{}'::jsonb), COALESCE(c.title_template::text, ''), COALESCE(c.description_template::text, ''), COALESCE(co.name, '') FROM categories c JOIN companies co ON co.id = c.company_id`
|
||||||
|
args := []any{}
|
||||||
|
if !all {
|
||||||
|
query += ` WHERE c.company_id = $1`
|
||||||
|
args = append(args, id)
|
||||||
|
}
|
||||||
|
query += ` ORDER BY c.company_id, c.unique_id`
|
||||||
|
rows, err := pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make([]categoryRow, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var row categoryRow
|
||||||
|
if err := rows.Scan(&row.ID, &row.Company, &row.Name, &row.UID, &row.Raw, &row.Title, &row.Desc, &row.CompanyName); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(row.Raw, &row.Prompts); err != nil {
|
||||||
|
return nil, fmt.Errorf("category %s: decode prompt: %w", row.UID, err)
|
||||||
|
}
|
||||||
|
if row.Prompts == nil {
|
||||||
|
row.Prompts = company.LangPromptMap{}
|
||||||
|
}
|
||||||
|
out = append(out, row)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
type defaultTranslation struct {
|
||||||
|
Source string
|
||||||
|
Values company.LangPromptMap
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadTranslationCache(ctx context.Context, pool *pgxpool.Pool) (map[string]*defaultTranslation, error) {
|
||||||
|
rows, err := pool.Query(ctx, `SELECT source_hash, source_prompt, translations FROM default_category_prompt_translations`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("load shared defaults (run migration 048): %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make(map[string]*defaultTranslation)
|
||||||
|
for rows.Next() {
|
||||||
|
var hash, source string
|
||||||
|
var raw []byte
|
||||||
|
if err := rows.Scan(&hash, &source, &raw); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if catalog.DefaultPromptHash(source) != hash {
|
||||||
|
return nil, fmt.Errorf("corrupt shared default hash %s", hash)
|
||||||
|
}
|
||||||
|
var values company.LangPromptMap
|
||||||
|
if err := json.Unmarshal(raw, &values); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if values == nil {
|
||||||
|
values = company.LangPromptMap{}
|
||||||
|
}
|
||||||
|
out[hash] = &defaultTranslation{Source: source, Values: values}
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveDefaultLanguage owns ONLY the shared platform-default cache. Unlike tenant
|
||||||
|
// prompts, this is generated application data: outdated translations must be
|
||||||
|
// refreshed on a release. Earlier versions used DO NOTHING and permanently
|
||||||
|
// retained the English five-benefit scaffold in this cache.
|
||||||
|
func saveDefaultLanguage(ctx context.Context, pool *pgxpool.Pool, hash, source, lang, value string) (bool, error) {
|
||||||
|
result, err := pool.Exec(ctx, `INSERT INTO default_category_prompt_translations
|
||||||
|
(source_hash, source_prompt, translations, updated_at)
|
||||||
|
VALUES ($1, $2, jsonb_build_object($3::text, $4::text), now())
|
||||||
|
ON CONFLICT (source_hash) DO UPDATE SET
|
||||||
|
translations = jsonb_set(default_category_prompt_translations.translations,
|
||||||
|
ARRAY[$3::text], to_jsonb($4::text), true), updated_at = now()
|
||||||
|
WHERE default_category_prompt_translations.source_prompt = EXCLUDED.source_prompt
|
||||||
|
AND default_category_prompt_translations.translations->>$3 IS DISTINCT FROM $4`,
|
||||||
|
hash, source, lang, value)
|
||||||
|
return result.RowsAffected() > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Historical cache snapshots are read-only proof of previously shipped platform
|
||||||
|
// translations. They may be used for exact-match migration, NEVER as replacement
|
||||||
|
// text. This keeps custom company wording protected.
|
||||||
|
func knownCacheValues(source string, current, historical map[string]*defaultTranslation, lang string) []string {
|
||||||
|
values := make([]string, 0, 2)
|
||||||
|
hash := catalog.DefaultPromptHash(source)
|
||||||
|
for _, cache := range []map[string]*defaultTranslation{current, historical} {
|
||||||
|
if entry := cache[hash]; entry != nil {
|
||||||
|
if value := strings.TrimSpace(entry.Values[lang]); value != "" {
|
||||||
|
values = append(values, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
// extendDefaultPrompt inserts only missing language variants. The SQL compares
|
||||||
|
// the full source snapshot: edits made during a long translation run are safe.
|
||||||
|
func extendDefaultPrompt(ctx context.Context, pool *pgxpool.Pool, row categoryRow, expectedSource string, cached company.LangPromptMap, langs []string) (bool, error) {
|
||||||
|
if !catalog.IsUntouchedDefaultPrompt(row.Prompts, expectedSource, cached) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
next := make(company.LangPromptMap, len(row.Prompts)+len(langs)+1)
|
||||||
|
for k, v := range row.Prompts {
|
||||||
|
next[k] = v
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(next["*"]) == "" {
|
||||||
|
next["*"] = expectedSource
|
||||||
|
}
|
||||||
|
changed := len(row.Prompts) == 0 || next["*"] != row.Prompts["*"]
|
||||||
|
for _, lang := range langs {
|
||||||
|
if strings.TrimSpace(next[lang]) != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if text := strings.TrimSpace(cached[lang]); text != "" {
|
||||||
|
next[lang] = text
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
encoded, err := company.EncodeLangPromptMap(next)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb, updated_at = now()
|
||||||
|
WHERE id = $1 AND company_id = $2 AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb`,
|
||||||
|
row.ID, row.Company, string(row.Raw), string(encoded))
|
||||||
|
return result.RowsAffected() > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchesDefaultFormula compares semantically identical JSON values, allowing
|
||||||
|
// column whitespace/key order differences but never matching a custom formula.
|
||||||
|
func matchesDefaultFormula(current, previous string) bool {
|
||||||
|
current = strings.TrimSpace(current)
|
||||||
|
if current == "" || current == "null" || current == "{}" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if previous == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var a, b any
|
||||||
|
if json.Unmarshal([]byte(current), &a) != nil || json.Unmarshal([]byte(previous), &b) != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
left, _ := json.Marshal(a)
|
||||||
|
right, _ := json.Marshal(b)
|
||||||
|
return string(left) == string(right)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isMixedBuiltInEnglishPrompt recognizes a historical default whose three
|
||||||
|
// roles came from different RELEASED defaults. A full role scaffold is required;
|
||||||
|
// each role must be an EXACT prior built-in fragment. Never match arbitrary
|
||||||
|
// user-written instructions by keywords or number of paragraphs.
|
||||||
|
func isMixedBuiltInEnglishPrompt(value string, versions []aiprompts.CategoryFormulaDefaults) bool {
|
||||||
|
markers := [][2]string{
|
||||||
|
{aiprompts.SectionTitleStart, aiprompts.SectionTitleEnd},
|
||||||
|
{aiprompts.SectionDescriptionStart, aiprompts.SectionDescriptionEnd},
|
||||||
|
{aiprompts.SectionMetaStart, aiprompts.SectionMetaEnd},
|
||||||
|
}
|
||||||
|
if !aiprompts.CategoryEnhanceHasRoleSections(value) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// No unrecognized preamble, trailing content, or hidden custom section.
|
||||||
|
if strings.TrimSpace(strings.ReplaceAll(value, "\r\n", "\n")) != aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
|
||||||
|
TitleRules: aiprompts.ExtractEnhanceSectionBody(value, markers[0][0], markers[0][1]),
|
||||||
|
DescriptionRules: aiprompts.ExtractEnhanceSectionBody(value, markers[1][0], markers[1][1]),
|
||||||
|
MetaRules: aiprompts.ExtractEnhanceSectionBody(value, markers[2][0], markers[2][1]),
|
||||||
|
WasLegacy: true,
|
||||||
|
}) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, pair := range markers {
|
||||||
|
text := aiprompts.ExtractEnhanceSectionBody(value, pair[0], pair[1])
|
||||||
|
if text == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
known := false
|
||||||
|
for _, ver := range versions {
|
||||||
|
if text == aiprompts.ExtractEnhanceSectionBody(ver.Overlay, pair[0], pair[1]) {
|
||||||
|
known = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !known {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// isKnownBuiltInVariantSet permits migrations from *mixed* released platform
|
||||||
|
// versions (for example, English from the old five-H2 default and German from
|
||||||
|
// the SEO-v4 release). Every non-empty language must match a known, exact
|
||||||
|
// built-in value. One company-authored field disqualifies the entire category.
|
||||||
|
// Cache lookups are read-only; no fuzzy matches on real tenant instructions.
|
||||||
|
func isKnownBuiltInVariantSet(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache, historical map[string]*defaultTranslation) bool {
|
||||||
|
allowedEN := map[string]bool{}
|
||||||
|
allowedLocalized := map[string]map[string]bool{}
|
||||||
|
for _, version := range versions {
|
||||||
|
if version.Overlay == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
allowedEN[strings.TrimSpace(version.Overlay)] = true
|
||||||
|
for _, previous := range []map[string]*defaultTranslation{cache, historical} {
|
||||||
|
if entry := previous[catalog.DefaultPromptHash(version.Overlay)]; entry != nil {
|
||||||
|
for lang, val := range entry.Values {
|
||||||
|
if !company.IsAllowedLanguage(lang) || strings.TrimSpace(val) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if lang == "en" {
|
||||||
|
allowedEN[strings.TrimSpace(val)] = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if allowedLocalized[lang] == nil {
|
||||||
|
allowedLocalized[lang] = map[string]bool{}
|
||||||
|
}
|
||||||
|
allowedLocalized[lang][strings.TrimSpace(val)] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for lang, val := range prompts {
|
||||||
|
// The v3 localized plain-text template was not in the v6 migration
|
||||||
|
// allowlist, which left non-A1 companies using five 100-word sections.
|
||||||
|
if isExactOldDefaultLanguage(val, lang, versions, cache, historical) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val = strings.TrimSpace(val)
|
||||||
|
if val == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if lang == "*" || lang == "en" {
|
||||||
|
if !allowedEN[val] && !isMixedBuiltInEnglishPrompt(val, versions) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
} else if !company.IsAllowedLanguage(lang) || !allowedLocalized[lang][val] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only exact former built-in JSON is eligible for an upgrade, even when the
|
||||||
|
// prompt and formula columns happen to be from different older deployments.
|
||||||
|
func isKnownBuiltInFormula(current string, versions []aiprompts.CategoryFormulaDefaults, title bool) bool {
|
||||||
|
if matchesDefaultFormula(current, "") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, version := range versions {
|
||||||
|
compare := version.DescriptionTemplateJSON
|
||||||
|
if title {
|
||||||
|
compare = version.TitleTemplateJSON
|
||||||
|
}
|
||||||
|
if matchesDefaultFormula(current, compare) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// upgradeOldDefault is scoped to a single category and guarded by an exact
|
||||||
|
// snapshot of its three current columns, so concurrent edits are not overwritten.
|
||||||
|
func upgradeOldDefault(ctx context.Context, pool *pgxpool.Pool, row categoryRow, def aiprompts.CategoryFormulaDefaults, translations company.LangPromptMap) (bool, error) {
|
||||||
|
next := company.LangPromptMap{"*": def.Overlay}
|
||||||
|
for lang, value := range translations {
|
||||||
|
if company.IsAllowedLanguage(lang) && strings.TrimSpace(value) != "" {
|
||||||
|
next[lang] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next["en"] = def.Overlay
|
||||||
|
encoded, err := company.EncodeLangPromptMap(next)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
// Preserve existing complete title formulas if equal to the legacy default,
|
||||||
|
// but repair missing ones. Replace standard description layout with the
|
||||||
|
// non-repeating platform structure after confirming it was not customized.
|
||||||
|
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb,
|
||||||
|
title_template = $5::jsonb, description_template = $6::jsonb,
|
||||||
|
updated_at = now() WHERE id = $1 AND company_id = $2
|
||||||
|
AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb
|
||||||
|
AND COALESCE(title_template::text, '') = $7
|
||||||
|
AND COALESCE(description_template::text, '') = $8`,
|
||||||
|
row.ID, row.Company, string(row.Raw), string(encoded),
|
||||||
|
def.TitleTemplateJSON, def.DescriptionTemplateJSON, row.Title, row.Desc)
|
||||||
|
return result.RowsAffected() > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// isExactOldDefaultLanguage recognizes prior SHIPPED locale values, including
|
||||||
|
// the v3 plain-text Croatian/Bulgarian instructions that the old migrations
|
||||||
|
// missed. It never matches arbitrary text by language, length or keywords.
|
||||||
|
func isExactOldDefaultLanguage(value, lang string, versions []aiprompts.CategoryFormulaDefaults, cache, historical map[string]*defaultTranslation) bool {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if old, err := aiprompts.PreviousOfflineDefaultPromptV3(lang); err == nil && value == old {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if old, err := aiprompts.PreviousOfflineDefaultPromptV6(lang); err == nil && value == old {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if lang != "*" && lang != "en" {
|
||||||
|
for _, oldFn := range []func(string) (string, error){aiprompts.PreviousOfflineDefaultPromptV3, aiprompts.PreviousOfflineDefaultPromptV6} {
|
||||||
|
old, err := oldFn(lang)
|
||||||
|
if err == nil && value == aiprompts.ExtractEnhanceSectionBody(old, aiprompts.SectionDescriptionStart, aiprompts.SectionDescriptionEnd) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, prior := range versions {
|
||||||
|
if prior.Overlay == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (lang == "*" || lang == "en") && value == strings.TrimSpace(prior.Overlay) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, old := range knownCacheValues(prior.Overlay, cache, historical, lang) {
|
||||||
|
if value == strings.TrimSpace(old) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// patchKnownRoleSections upgrades a matching old default ROLE, even when the
|
||||||
|
// company customized an unrelated role (e.g. title). The custom role remains
|
||||||
|
// unchanged. Only exact bundled historical strings qualify for replacement.
|
||||||
|
func patchKnownRoleSections(value, lang, replacement string, versions []aiprompts.CategoryFormulaDefaults) (string, bool) {
|
||||||
|
if !aiprompts.CategoryEnhanceHasRoleSections(value) || !aiprompts.CategoryEnhanceHasRoleSections(replacement) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
extract := func(prompt, start, end string) string {
|
||||||
|
return aiprompts.ExtractEnhanceSectionBody(prompt, start, end)
|
||||||
|
}
|
||||||
|
starts := [3]string{aiprompts.SectionTitleStart, aiprompts.SectionDescriptionStart, aiprompts.SectionMetaStart}
|
||||||
|
ends := [3]string{aiprompts.SectionTitleEnd, aiprompts.SectionDescriptionEnd, aiprompts.SectionMetaEnd}
|
||||||
|
oldParts := [3]string{}
|
||||||
|
for i := range starts {
|
||||||
|
oldParts[i] = extract(value, starts[i], ends[i])
|
||||||
|
}
|
||||||
|
// Do not normalize a prompt containing preambles, extra text, or custom markup.
|
||||||
|
if strings.TrimSpace(value) != aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
|
||||||
|
TitleRules: oldParts[0], DescriptionRules: oldParts[1], MetaRules: oldParts[2], WasLegacy: true,
|
||||||
|
}) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
parts := oldParts
|
||||||
|
changed := false
|
||||||
|
for _, oldFn := range []func(string) (string, error){aiprompts.PreviousOfflineDefaultPromptV3, aiprompts.PreviousOfflineDefaultPromptV6} {
|
||||||
|
old, err := oldFn(lang)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for i := range starts {
|
||||||
|
prev := extract(old, starts[i], ends[i])
|
||||||
|
newText := extract(replacement, starts[i], ends[i])
|
||||||
|
if prev != "" && parts[i] == prev && newText != "" && parts[i] != newText {
|
||||||
|
parts[i] = newText
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Older English categories used category-specific built-in naming with
|
||||||
|
// the five-H2 boilerplate. Match only shipped role text; never guess by
|
||||||
|
// counting H2s or searching for marketing words.
|
||||||
|
if lang == "en" {
|
||||||
|
for _, prior := range versions[1:] {
|
||||||
|
if prior.Overlay == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for i := range starts {
|
||||||
|
prev := extract(prior.Overlay, starts[i], ends[i])
|
||||||
|
newText := extract(replacement, starts[i], ends[i])
|
||||||
|
if prev != "" && parts[i] == prev && newText != "" && parts[i] != newText {
|
||||||
|
parts[i] = newText
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
|
||||||
|
TitleRules: parts[0], DescriptionRules: parts[1], MetaRules: parts[2], WasLegacy: true,
|
||||||
|
}), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// repairOldLocaleDefaults upgrades specific released default values without
|
||||||
|
// relying on the other language entries or the title/description JSON columns.
|
||||||
|
// This is deliberately separate from the all-or-nothing category upgrade: an
|
||||||
|
// unrelated custom locale or formula must not prevent safe default repairs.
|
||||||
|
func repairOldLocaleDefaults(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache, historical map[string]*defaultTranslation, targetLangs []string) (company.LangPromptMap, int) {
|
||||||
|
allowed := map[string]bool{}
|
||||||
|
for _, lang := range targetLangs {
|
||||||
|
allowed[lang] = true
|
||||||
|
}
|
||||||
|
next := make(company.LangPromptMap, len(prompts))
|
||||||
|
updates := 0
|
||||||
|
for lang, value := range prompts {
|
||||||
|
next[lang] = value
|
||||||
|
if lang != "*" && !allowed[lang] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
locale := lang
|
||||||
|
if lang == "*" {
|
||||||
|
locale = "en"
|
||||||
|
if !allowed[locale] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
replacement, err := aiprompts.OfflineDefaultPrompt(locale)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if lang == "*" || lang == "en" {
|
||||||
|
replacement = versions[0].Overlay
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(replacement) == strings.TrimSpace(value) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if isExactOldDefaultLanguage(value, lang, versions, cache, historical) {
|
||||||
|
next[lang] = replacement
|
||||||
|
updates++
|
||||||
|
} else if patched, ok := patchKnownRoleSections(value, locale, replacement, versions); ok {
|
||||||
|
next[lang] = patched
|
||||||
|
updates++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next, updates
|
||||||
|
}
|
||||||
|
|
||||||
|
// repairOldFormulaField replaces an exact known platform JSON formula, leaving
|
||||||
|
// edited company formulas untouched. A language-agnostic old HTML constraint
|
||||||
|
// can otherwise override an already-migrated localized prompt in the API.
|
||||||
|
func repairOldFormulaField(value string, versions []aiprompts.CategoryFormulaDefaults, title bool) (string, bool) {
|
||||||
|
if len(versions) < 2 {
|
||||||
|
return value, false
|
||||||
|
}
|
||||||
|
current := versions[0].DescriptionTemplateJSON
|
||||||
|
if title {
|
||||||
|
current = versions[0].TitleTemplateJSON
|
||||||
|
}
|
||||||
|
if matchesDefaultFormula(value, current) {
|
||||||
|
return value, false
|
||||||
|
}
|
||||||
|
for _, old := range versions[1:] {
|
||||||
|
previous := old.DescriptionTemplateJSON
|
||||||
|
if title {
|
||||||
|
previous = old.TitleTemplateJSON
|
||||||
|
}
|
||||||
|
if previous != "" && matchesDefaultFormula(value, previous) {
|
||||||
|
return current, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return value, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// persistRepairedDefaults applies a compare-and-swap update to all three
|
||||||
|
// columns, even when only a single field changed. Racing admin edits are safe.
|
||||||
|
func persistRepairedDefaults(ctx context.Context, pool *pgxpool.Pool, row categoryRow, next company.LangPromptMap, title, description string) (bool, error) {
|
||||||
|
encoded, err := company.EncodeLangPromptMap(next)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb,
|
||||||
|
title_template = NULLIF($5, '')::jsonb,
|
||||||
|
description_template = NULLIF($6, '')::jsonb,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = $1 AND company_id = $2 AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb
|
||||||
|
AND COALESCE(title_template::text, '') = $7
|
||||||
|
AND COALESCE(description_template::text, '') = $8`,
|
||||||
|
row.ID, row.Company, string(row.Raw), string(encoded), title, description, row.Title, row.Desc)
|
||||||
|
return result.RowsAffected() == 1, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// replaceKnownBuiltInLocales upgrades only exact released DEFAULT locale values.
|
||||||
|
// A1 can contain its own custom Slovenian category prompt alongside an old
|
||||||
|
// platform-generated English translation. Preserve its custom languages, name
|
||||||
|
// and meta formulas while replacing the old built-in English/other languages.
|
||||||
|
func replaceKnownBuiltInLocales(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache, historical map[string]*defaultTranslation) int {
|
||||||
|
if len(versions) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
canonical := versions[0]
|
||||||
|
current := cache[catalog.DefaultPromptHash(canonical.Overlay)]
|
||||||
|
if current == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
updates := 0
|
||||||
|
for lang, text := range prompts {
|
||||||
|
val := strings.TrimSpace(text)
|
||||||
|
if val == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
replacement := strings.TrimSpace(current.Values[lang])
|
||||||
|
if lang == "*" || lang == "en" {
|
||||||
|
replacement = canonical.Overlay
|
||||||
|
}
|
||||||
|
if replacement == "" || replacement == val {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, prior := range versions {
|
||||||
|
if prior.Overlay == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
known := []string{}
|
||||||
|
if lang == "*" || lang == "en" {
|
||||||
|
known = append(known, prior.Overlay)
|
||||||
|
} else {
|
||||||
|
known = knownCacheValues(prior.Overlay, cache, historical, lang)
|
||||||
|
}
|
||||||
|
matched := (lang == "*" || lang == "en") && isMixedBuiltInEnglishPrompt(val, versions)
|
||||||
|
for _, old := range known {
|
||||||
|
if val == strings.TrimSpace(old) && old != "" {
|
||||||
|
matched = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !matched && isExactOldDefaultLanguage(val, lang, versions, cache, historical) {
|
||||||
|
matched = true
|
||||||
|
}
|
||||||
|
if matched {
|
||||||
|
prompts[lang] = replacement
|
||||||
|
updates++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return updates
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeA1Category differentiates repetitive legacy A1 benefit instructions.
|
||||||
|
// It neither translates nor changes A1 naming/meta instructions.
|
||||||
|
func normalizeA1Category(ctx context.Context, pool *pgxpool.Pool, row categoryRow, cache, historical map[string]*defaultTranslation, dryRun bool) (int, int, bool, error) {
|
||||||
|
next := make(company.LangPromptMap, len(row.Prompts))
|
||||||
|
removed := 0
|
||||||
|
metaUpdated := 0
|
||||||
|
for lang, value := range row.Prompts {
|
||||||
|
cleaned, n := aiprompts.NormalizeA1RepeatedBenefits(value)
|
||||||
|
removed += n
|
||||||
|
locale := lang
|
||||||
|
if locale == "*" || !company.IsAllowedLanguage(locale) {
|
||||||
|
locale = "sl"
|
||||||
|
}
|
||||||
|
if metaClean, changed := aiprompts.NormalizeA1MetaRole(cleaned, locale); changed {
|
||||||
|
cleaned = metaClean
|
||||||
|
metaUpdated++
|
||||||
|
}
|
||||||
|
next[lang] = cleaned
|
||||||
|
}
|
||||||
|
def := aiprompts.DefaultCategoryFormula(row.UID, row.Name)
|
||||||
|
versions := []aiprompts.CategoryFormulaDefaults{def,
|
||||||
|
aiprompts.PreviousCanonicalV6CategoryFormula(row.UID, row.Name),
|
||||||
|
aiprompts.PreviousSEODefaultCategoryFormula(row.UID, row.Name),
|
||||||
|
aiprompts.PriorDefaultCategoryFormula(row.UID, row.Name),
|
||||||
|
aiprompts.LegacyDefaultCategoryFormula(row.UID, row.Name)}
|
||||||
|
localesUpgraded := replaceKnownBuiltInLocales(next, versions, cache, historical)
|
||||||
|
desc, n, err := aiprompts.NormalizeA1DescriptionTemplate(row.Desc)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, false, err
|
||||||
|
}
|
||||||
|
removed += n
|
||||||
|
metaLocale := "sl"
|
||||||
|
if normalized, repaired, normalizeErr := aiprompts.NormalizeA1MetaTemplate(desc, metaLocale); normalizeErr != nil {
|
||||||
|
return 0, 0, false, normalizeErr
|
||||||
|
} else if repaired {
|
||||||
|
desc = normalized
|
||||||
|
metaUpdated++
|
||||||
|
}
|
||||||
|
if (removed == 0 && localesUpgraded == 0 && metaUpdated == 0) || dryRun {
|
||||||
|
return removed, localesUpgraded, false, nil
|
||||||
|
}
|
||||||
|
encoded, err := company.EncodeLangPromptMap(next)
|
||||||
|
if err != nil {
|
||||||
|
return removed, localesUpgraded, false, err
|
||||||
|
}
|
||||||
|
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb,
|
||||||
|
description_template = NULLIF($5,'')::jsonb, updated_at = now()
|
||||||
|
WHERE id = $1 AND company_id = $2
|
||||||
|
AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb
|
||||||
|
AND COALESCE(description_template::text,'') = $6`,
|
||||||
|
row.ID, row.Company, string(row.Raw), string(encoded), desc, row.Desc)
|
||||||
|
if err != nil {
|
||||||
|
return removed, localesUpgraded, false, err
|
||||||
|
}
|
||||||
|
return removed, localesUpgraded, result.RowsAffected() == 1, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
config.LoadDotEnv()
|
||||||
|
postgres := flag.String("postgres", os.Getenv("DATABASE_URL"), "Postgres URL")
|
||||||
|
companyID := flag.String("company", "", "optional company UUID for backfilling existing categories; shared defaults are global")
|
||||||
|
all := flag.Bool("all-companies", false, "legacy alias; all companies are now the default")
|
||||||
|
dryRun := flag.Bool("dry-run", false, "show needed localized defaults and eligible categories without database writes")
|
||||||
|
langs := flag.String("langs", "", "comma-separated subset; defaults to all supported content languages")
|
||||||
|
limit := flag.Int("limit", 0, "optional maximum number of built-in templates to seed (pilot only)")
|
||||||
|
flag.Parse()
|
||||||
|
if strings.TrimSpace(*postgres) == "" {
|
||||||
|
log.Fatal("DATABASE_URL/-postgres is required")
|
||||||
|
}
|
||||||
|
if *limit < 0 {
|
||||||
|
log.Fatal("-limit must be >= 0")
|
||||||
|
}
|
||||||
|
if *companyID != "" && *all {
|
||||||
|
log.Fatal("choose -company or -all-companies, not both")
|
||||||
|
}
|
||||||
|
allCompanies := *companyID == ""
|
||||||
|
var id uuid.UUID
|
||||||
|
if !allCompanies {
|
||||||
|
var err error
|
||||||
|
id, err = uuid.Parse(*companyID)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("invalid -company UUID: ", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
targetLangs, err := langsToSeed(*langs)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
pool, err := pgxpool.New(ctx, *postgres)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
cache, err := loadTranslationCache(ctx, pool)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
// Keep the old cache for exact-match detection when correcting stale records.
|
||||||
|
historical := make(map[string]*defaultTranslation, len(cache))
|
||||||
|
for key, entry := range cache {
|
||||||
|
values := make(company.LangPromptMap, len(entry.Values))
|
||||||
|
for lang, value := range entry.Values {
|
||||||
|
values[lang] = value
|
||||||
|
}
|
||||||
|
historical[key] = &defaultTranslation{Source: entry.Source, Values: values}
|
||||||
|
}
|
||||||
|
// An exact frozen v6 bundle supplies migration evidence even when a past
|
||||||
|
// deployment failed to populate its shared translation cache.
|
||||||
|
previous := aiprompts.PreviousCanonicalV6CategoryFormula("", "")
|
||||||
|
oldHash := catalog.DefaultPromptHash(previous.Overlay)
|
||||||
|
if historical[oldHash] == nil {
|
||||||
|
oldValues := make(company.LangPromptMap)
|
||||||
|
for _, lang := range company.ContentLanguages {
|
||||||
|
if old, loadErr := aiprompts.PreviousOfflineDefaultPromptV6(lang); loadErr == nil {
|
||||||
|
oldValues[lang] = old
|
||||||
|
}
|
||||||
|
}
|
||||||
|
historical[oldHash] = &defaultTranslation{Source: previous.Overlay, Values: oldValues}
|
||||||
|
}
|
||||||
|
// Always include the generic default and the complete bundled taxonomy.
|
||||||
|
// One translation cache is shared across EVERY company, including future ones.
|
||||||
|
sources := aiprompts.AllDefaultCategoryPrompts()
|
||||||
|
if *limit > 0 && *limit < len(sources) {
|
||||||
|
sources = sources[:*limit]
|
||||||
|
}
|
||||||
|
missing, inserted, failures := 0, 0, 0
|
||||||
|
for i, source := range sources {
|
||||||
|
hash := catalog.DefaultPromptHash(source)
|
||||||
|
entry, exists := cache[hash]
|
||||||
|
if !exists {
|
||||||
|
entry = &defaultTranslation{Source: source, Values: company.LangPromptMap{}}
|
||||||
|
cache[hash] = entry
|
||||||
|
}
|
||||||
|
if entry.Source != source {
|
||||||
|
log.Fatalf("shared default hash collision for %s", hash)
|
||||||
|
}
|
||||||
|
for _, lang := range targetLangs {
|
||||||
|
translated := source
|
||||||
|
if lang != "en" {
|
||||||
|
translated, err = aiprompts.OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
failures++
|
||||||
|
log.Printf("FAIL bundled default=%d lang=%s: %v", i+1, lang, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if entry.Values[lang] == translated {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
missing++
|
||||||
|
if *dryRun {
|
||||||
|
// A dry run must compare against the corrected bundle, not an
|
||||||
|
// old value from the database cache.
|
||||||
|
entry.Values[lang] = translated
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
saved, saveErr := saveDefaultLanguage(ctx, pool, hash, source, lang, translated)
|
||||||
|
if saveErr != nil {
|
||||||
|
failures++
|
||||||
|
log.Printf("FAIL storing default=%d lang=%s: %v", i+1, lang, saveErr)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if saved {
|
||||||
|
inserted++
|
||||||
|
}
|
||||||
|
entry.Values[lang] = translated
|
||||||
|
}
|
||||||
|
if !*dryRun {
|
||||||
|
log.Printf("default templates %d/%d cached languages=%d", i+1, len(sources), len(entry.Values))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Refresh from the database before comparing company prompts: another seed
|
||||||
|
// or administrator may have changed a cached language during this run.
|
||||||
|
if !*dryRun {
|
||||||
|
cache, err = loadTranslationCache(ctx, pool)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
categories, err := fetchCategories(ctx, pool, id, allCompanies)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
eligible, changed, custom, upgraded, protected, a1Removed, a1Updated, a1Locales, localeRepaired := 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||||
|
for _, row := range categories {
|
||||||
|
// A1 has its own Slovenian category instructions. Never apply the
|
||||||
|
// global platform-default backfill to this customer.
|
||||||
|
if row.Company.String() == "604f23a8-b66e-4b21-8b45-0d72b68f4790" ||
|
||||||
|
strings.EqualFold(strings.TrimSpace(row.CompanyName), "A1 Slovenija") {
|
||||||
|
protected++
|
||||||
|
removed, localized, updated, cleanErr := normalizeA1Category(ctx, pool, row, cache, historical, *dryRun)
|
||||||
|
if cleanErr != nil {
|
||||||
|
failures++
|
||||||
|
log.Printf("FAIL cleaning A1 category=%s: %v", row.UID, cleanErr)
|
||||||
|
} else {
|
||||||
|
a1Removed += removed
|
||||||
|
a1Locales += localized
|
||||||
|
if updated {
|
||||||
|
a1Updated++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
def := aiprompts.DefaultCategoryFormula(row.UID, row.Name)
|
||||||
|
entry := cache[catalog.DefaultPromptHash(def.Overlay)]
|
||||||
|
if entry == nil {
|
||||||
|
continue
|
||||||
|
} // -limit pilot excludes some templates
|
||||||
|
if catalog.IsUntouchedDefaultPrompt(row.Prompts, def.Overlay, entry.Values) &&
|
||||||
|
matchesDefaultFormula(row.Title, def.TitleTemplateJSON) &&
|
||||||
|
matchesDefaultFormula(row.Desc, def.DescriptionTemplateJSON) &&
|
||||||
|
strings.TrimSpace(row.Title) != "" && strings.TrimSpace(row.Desc) != "" {
|
||||||
|
eligible++
|
||||||
|
if *dryRun {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
updated, err := extendDefaultPrompt(ctx, pool, row, def.Overlay, entry.Values, targetLangs)
|
||||||
|
if err != nil {
|
||||||
|
failures++
|
||||||
|
log.Printf("FAIL extending company=%s category=%s: %v", row.Company, row.UID, err)
|
||||||
|
} else if updated {
|
||||||
|
changed++
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Upgrade *only* built-in snapshots, including mixed versions left by
|
||||||
|
// prior migrations. Never touch any tenant-authored language or formula.
|
||||||
|
versions := []aiprompts.CategoryFormulaDefaults{
|
||||||
|
def,
|
||||||
|
aiprompts.PreviousCanonicalV6CategoryFormula(row.UID, row.Name),
|
||||||
|
aiprompts.PreviousSEODefaultCategoryFormula(row.UID, row.Name),
|
||||||
|
aiprompts.PriorDefaultCategoryFormula(row.UID, row.Name),
|
||||||
|
aiprompts.LegacyDefaultCategoryFormula(row.UID, row.Name),
|
||||||
|
}
|
||||||
|
if !isKnownBuiltInVariantSet(row.Prompts, versions, cache, historical) ||
|
||||||
|
!isKnownBuiltInFormula(row.Title, versions, true) ||
|
||||||
|
!isKnownBuiltInFormula(row.Desc, versions, false) {
|
||||||
|
// Repair only exact-match *shipped* defaults when a different
|
||||||
|
// language or a structured formula was intentionally customized.
|
||||||
|
next, repaired := repairOldLocaleDefaults(row.Prompts, versions, cache, historical, targetLangs)
|
||||||
|
title, repairedTitle := repairOldFormulaField(row.Title, versions, true)
|
||||||
|
desc, repairedDesc := repairOldFormulaField(row.Desc, versions, false)
|
||||||
|
if repaired != 0 || repairedTitle || repairedDesc {
|
||||||
|
eligible++
|
||||||
|
if *dryRun {
|
||||||
|
localeRepaired += repaired
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
updated, updateErr := persistRepairedDefaults(ctx, pool, row, next, title, desc)
|
||||||
|
if updateErr != nil {
|
||||||
|
failures++
|
||||||
|
log.Printf("FAIL repairing default locales company=%s category=%s: %v", row.Company, row.UID, updateErr)
|
||||||
|
} else if updated {
|
||||||
|
changed++
|
||||||
|
localeRepaired += repaired
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
custom++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
eligible++
|
||||||
|
if *dryRun {
|
||||||
|
upgraded++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
updated, err := upgradeOldDefault(ctx, pool, row, def, entry.Values)
|
||||||
|
if err != nil {
|
||||||
|
failures++
|
||||||
|
log.Printf("FAIL upgrading company=%s category=%s: %v", row.Company, row.UID, err)
|
||||||
|
} else if updated {
|
||||||
|
changed++
|
||||||
|
upgraded++
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
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_default_locales_upgraded=%d A1_categories_updated=%d non_a1_legacy_locales_repaired=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Locales, a1Updated, localeRepaired, failures, *dryRun)
|
||||||
|
if *dryRun && missing > 0 {
|
||||||
|
log.Printf("dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM")
|
||||||
|
}
|
||||||
|
if failures > 0 {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDefaultMigrationRecognizesMixedLegacyEnglishWithoutTouchingCustom(t *testing.T) {
|
||||||
|
current := aiprompts.DefaultCategoryFormula("", "High chairs")
|
||||||
|
old := aiprompts.PriorDefaultCategoryFormula("", "High chairs")
|
||||||
|
seo := aiprompts.PreviousSEODefaultCategoryFormula("", "High chairs")
|
||||||
|
variants := []aiprompts.CategoryFormulaDefaults{current, seo, old, aiprompts.LegacyDefaultCategoryFormula("", "High chairs")}
|
||||||
|
mixed := strings.Replace(current.Overlay,
|
||||||
|
aiprompts.DescriptionSectionInstructions(current.Overlay),
|
||||||
|
aiprompts.DescriptionSectionInstructions(old.Overlay), 1)
|
||||||
|
if !isMixedBuiltInEnglishPrompt(mixed, variants) {
|
||||||
|
t.Fatal("old English five-section mixed default was not recognized")
|
||||||
|
}
|
||||||
|
cache := map[string]*defaultTranslation{
|
||||||
|
catalog.DefaultPromptHash(current.Overlay): {Source: current.Overlay, Values: company.LangPromptMap{"en": current.Overlay}},
|
||||||
|
catalog.DefaultPromptHash(old.Overlay): {Source: old.Overlay, Values: company.LangPromptMap{"en": old.Overlay}},
|
||||||
|
}
|
||||||
|
if !isKnownBuiltInVariantSet(company.LangPromptMap{"en": mixed}, variants, cache, nil) {
|
||||||
|
t.Fatal("mixed, unedited platform default was flagged custom")
|
||||||
|
}
|
||||||
|
bad := strings.Replace(mixed, "--- Meta ---", "--- Meta ---\nUse my shop's custom brand voice", 1)
|
||||||
|
if isKnownBuiltInVariantSet(company.LangPromptMap{"en": bad}, variants, cache, nil) {
|
||||||
|
t.Fatal("custom tenant meta text must remain protected")
|
||||||
|
}
|
||||||
|
a1 := company.LangPromptMap{"sl": "A1 custom Slovenian naming, meta, and description", "en": mixed}
|
||||||
|
changed := replaceKnownBuiltInLocales(a1, variants, cache, nil)
|
||||||
|
if changed != 1 || a1["sl"] != "A1 custom Slovenian naming, meta, and description" || a1["en"] != current.Overlay {
|
||||||
|
t.Fatalf("A1 locale migration touched custom data: changed=%d, en=%q, sl=%q", changed, a1["en"], a1["sl"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestV6SharedCacheMigrationUsesHistoricalExactStrings(t *testing.T) {
|
||||||
|
canonical := aiprompts.DefaultCategoryFormula("", "Cables")
|
||||||
|
previous := aiprompts.PreviousCanonicalV6CategoryFormula("", "Cables")
|
||||||
|
if previous.Overlay == canonical.Overlay {
|
||||||
|
t.Fatal("v6/v7 should be distinct snapshots")
|
||||||
|
}
|
||||||
|
oldCroatian, err := aiprompts.PreviousOfflineDefaultPromptV6("hr")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
newCroatian, err := aiprompts.OfflineDefaultPrompt("hr")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
current := map[string]*defaultTranslation{
|
||||||
|
catalog.DefaultPromptHash(canonical.Overlay): {Source: canonical.Overlay, Values: company.LangPromptMap{"en": canonical.Overlay, "hr": newCroatian}},
|
||||||
|
}
|
||||||
|
history := map[string]*defaultTranslation{
|
||||||
|
catalog.DefaultPromptHash(previous.Overlay): {Source: previous.Overlay, Values: company.LangPromptMap{"en": previous.Overlay, "hr": oldCroatian}},
|
||||||
|
}
|
||||||
|
versions := []aiprompts.CategoryFormulaDefaults{canonical, previous}
|
||||||
|
legacy := company.LangPromptMap{"*": previous.Overlay, "hr": oldCroatian}
|
||||||
|
if !isKnownBuiltInVariantSet(legacy, versions, current, history) {
|
||||||
|
t.Fatal("v6 stock translations not upgradeable")
|
||||||
|
}
|
||||||
|
legacy["hr"] = "This company wrote its own Croatian instructions"
|
||||||
|
if isKnownBuiltInVariantSet(legacy, versions, current, history) {
|
||||||
|
t.Fatal("custom company locale overwritten")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reproduces the non-A1 records from the production report: the v3 seed
|
||||||
|
// generated only a translated paragraph of five-H2 instructions in hr/bg,
|
||||||
|
// while the English company variant still used five literal HTML H2 blocks.
|
||||||
|
func TestV3NonA1DescriptionMigrationAcrossAll25Languages(t *testing.T) {
|
||||||
|
canonical := aiprompts.DefaultCategoryFormula("", "Bathroom mixers")
|
||||||
|
prior := aiprompts.PriorDefaultCategoryFormula("", "Bathroom mixers")
|
||||||
|
versions := []aiprompts.CategoryFormulaDefaults{canonical, prior}
|
||||||
|
oldPrompts := company.LangPromptMap{}
|
||||||
|
for _, lang := range company.ContentLanguages {
|
||||||
|
old, err := aiprompts.PreviousOfflineDefaultPromptV3(lang)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
oldPrompts[lang] = old
|
||||||
|
}
|
||||||
|
oldPrompts["*"] = prior.Overlay
|
||||||
|
// A manually customized German description must remain untouched.
|
||||||
|
oldPrompts["de"] = "--- Title ---\nMein Shop Titel\n--- End Title ---\n\n--- Description ---\nEigenes Unternehmen\n--- End Description ---\n\n--- Meta ---\nMeine Meta\n--- End Meta ---"
|
||||||
|
got, count := repairOldLocaleDefaults(oldPrompts, versions, nil, nil, company.ContentLanguages)
|
||||||
|
if count != len(company.ContentLanguages) { // 24 translated + wildcard; custom de untouched
|
||||||
|
t.Fatalf("repaired %d entries; want %d", count, len(company.ContentLanguages))
|
||||||
|
}
|
||||||
|
if got["de"] != oldPrompts["de"] {
|
||||||
|
t.Fatal("custom German company formula overwritten")
|
||||||
|
}
|
||||||
|
for _, lang := range company.ContentLanguages {
|
||||||
|
if lang == "de" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
expected, err := aiprompts.OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if lang == "en" {
|
||||||
|
expected = canonical.Overlay
|
||||||
|
}
|
||||||
|
if got[lang] != expected {
|
||||||
|
t.Fatalf("%s retained obsolete default", lang)
|
||||||
|
}
|
||||||
|
body := aiprompts.DescriptionSectionInstructions(got[lang])
|
||||||
|
if strings.Count(body, "<h2>{") != 2 || strings.Count(body, "<p>{") != 2 || strings.Count(body, "<ul><li>{") != 1 {
|
||||||
|
t.Fatalf("%s did not receive HTML scaffold: %s", lang, body)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(body, "<p>{") {
|
||||||
|
t.Fatalf("%s not starting with intro", lang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got["*"] != canonical.Overlay {
|
||||||
|
t.Fatal("shared English five-H2 default survived migration")
|
||||||
|
}
|
||||||
|
twice, further := repairOldLocaleDefaults(got, versions, nil, nil, company.ContentLanguages)
|
||||||
|
if further != 0 {
|
||||||
|
t.Fatalf("migration is not idempotent: %+v", twice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestV3ExactReportedCroatianAndBulgarianMigration(t *testing.T) {
|
||||||
|
snippets := map[string]string{
|
||||||
|
"hr": "Napiši pet različitih naslova H2, a ispod svakog odlomak od približno 100 riječi.",
|
||||||
|
"bg": "Напиши пет различни заглавия H2, всяко следвано от абзац с около 100 думи.",
|
||||||
|
}
|
||||||
|
current := aiprompts.DefaultCategoryFormula("", "Any")
|
||||||
|
for lang, expected := range snippets {
|
||||||
|
old, err := aiprompts.PreviousOfflineDefaultPromptV3(lang)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(old, expected) {
|
||||||
|
t.Fatalf("lost exact %s regression fixture", lang)
|
||||||
|
}
|
||||||
|
if !isExactOldDefaultLanguage(old, lang, []aiprompts.CategoryFormulaDefaults{current}, nil, nil) {
|
||||||
|
t.Fatalf("%s historical snapshot not recognized", lang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestV3CustomRolePreservedWhileDefaultDescriptionRepaired(t *testing.T) {
|
||||||
|
current := aiprompts.DefaultCategoryFormula("", "Other")
|
||||||
|
old, err := aiprompts.PreviousOfflineDefaultPromptV3("hr")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
originalTitle := "Korisnički prilagođene upute za naslov"
|
||||||
|
legacy := aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
|
||||||
|
TitleRules: originalTitle,
|
||||||
|
DescriptionRules: aiprompts.ExtractEnhanceSectionBody(old, aiprompts.SectionDescriptionStart, aiprompts.SectionDescriptionEnd),
|
||||||
|
MetaRules: "Korisnički SEO meta",
|
||||||
|
})
|
||||||
|
next, changed := repairOldLocaleDefaults(company.LangPromptMap{"hr": legacy}, []aiprompts.CategoryFormulaDefaults{current}, nil, nil, company.ContentLanguages)
|
||||||
|
if changed != 1 {
|
||||||
|
t.Fatalf("description partial migration changed=%d", changed)
|
||||||
|
}
|
||||||
|
updated := next["hr"]
|
||||||
|
if aiprompts.ExtractEnhanceSectionBody(updated, aiprompts.SectionTitleStart, aiprompts.SectionTitleEnd) != originalTitle ||
|
||||||
|
aiprompts.ExtractEnhanceSectionBody(updated, aiprompts.SectionMetaStart, aiprompts.SectionMetaEnd) != "Korisnički SEO meta" {
|
||||||
|
t.Fatal("company-authored title/meta were overwritten")
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(aiprompts.DescriptionSectionInstructions(updated), "<p>{") {
|
||||||
|
t.Fatal("old default Croatian description not repaired")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLegacyDescriptionConstraintMustNotOverrideLocalizedPrompt(t *testing.T) {
|
||||||
|
canonical := aiprompts.DefaultCategoryFormula("", "Bathroom mixers")
|
||||||
|
previous := aiprompts.PriorDefaultCategoryFormula("", "Bathroom mixers")
|
||||||
|
versions := []aiprompts.CategoryFormulaDefaults{canonical, previous}
|
||||||
|
patched, ok := repairOldFormulaField(previous.DescriptionTemplateJSON, versions, false)
|
||||||
|
if !ok || patched != canonical.DescriptionTemplateJSON {
|
||||||
|
t.Fatal("old language-neutral five-H2 description formula was not upgraded")
|
||||||
|
}
|
||||||
|
own := `{"sections":[{"type":"p","instructions":"Custom layout"}]}`
|
||||||
|
if updated, changed := repairOldFormulaField(own, versions, false); changed || updated != own {
|
||||||
|
t.Fatal("custom formula was overwritten")
|
||||||
|
}
|
||||||
|
if updated, changed := repairOldFormulaField(canonical.DescriptionTemplateJSON, versions, false); changed || updated != canonical.DescriptionTemplateJSON {
|
||||||
|
t.Fatal("canonical formula should be idempotent")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -67,7 +67,7 @@ func main() {
|
|||||||
flag = "created/updated"
|
flag = "created/updated"
|
||||||
}
|
}
|
||||||
fmt.Printf(" %-8s $%-5d credits=%-6d price=%s product=%s (%s)\n",
|
fmt.Printf(" %-8s $%-5d credits=%-6d price=%s product=%s (%s)\n",
|
||||||
r.PackID, r.PriceUSD, r.Credits, r.PriceID, r.ProductID, flag)
|
r.PackID, r.PriceEUR, r.Credits, r.PriceID, r.ProductID, flag)
|
||||||
if *writeSettings {
|
if *writeSettings {
|
||||||
if plat == nil {
|
if plat == nil {
|
||||||
fmt.Fprintln(os.Stderr, "-write-settings requires DATABASE_URL")
|
fmt.Fprintln(os.Stderr, "-write-settings requires DATABASE_URL")
|
||||||
|
|||||||
@@ -339,6 +339,13 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if feeds.AutoSyncEnabled() && !cfg.MaintenanceMode && !cfg.ReadOnlyMode {
|
||||||
|
if n, err := feedSvc.EnqueueDueFeeds(ctx, 100, uuid.Nil); err != nil {
|
||||||
|
log.Printf("feed schedule enqueue (startup): %v", err)
|
||||||
|
} else if n > 0 {
|
||||||
|
log.Printf("feed schedule enqueued=%d (startup)", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
@@ -355,6 +362,13 @@ func main() {
|
|||||||
} else if res.Processed > 0 {
|
} else if res.Processed > 0 {
|
||||||
log.Printf("billing cycles processed=%d", res.Processed)
|
log.Printf("billing cycles processed=%d", res.Processed)
|
||||||
}
|
}
|
||||||
|
if feeds.AutoSyncEnabled() {
|
||||||
|
if n, err := feedSvc.EnqueueDueFeeds(ctx, 100, uuid.Nil); err != nil {
|
||||||
|
log.Printf("feed schedule enqueue: %v", err)
|
||||||
|
} else if n > 0 {
|
||||||
|
log.Printf("feed schedule enqueued=%d", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
if n, err := woo.EnqueueDueScheduled(ctx, 6*time.Hour); err != nil {
|
if n, err := woo.EnqueueDueScheduled(ctx, 6*time.Hour); err != nil {
|
||||||
log.Printf("woo schedule enqueue: %v", err)
|
log.Printf("woo schedule enqueue: %v", err)
|
||||||
} else if n > 0 {
|
} else if n > 0 {
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ require (
|
|||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/jackc/pgx/v5 v5.10.0
|
github.com/jackc/pgx/v5 v5.10.0
|
||||||
github.com/microcosm-cc/bluemonday v1.0.27
|
github.com/microcosm-cc/bluemonday v1.0.27
|
||||||
|
github.com/pbnjay/grate v0.0.0-20231006022435-3f8e65d74a14
|
||||||
|
github.com/xuri/excelize/v2 v2.11.0
|
||||||
golang.org/x/crypto v0.54.0
|
golang.org/x/crypto v0.54.0
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
)
|
)
|
||||||
@@ -22,8 +24,15 @@ require (
|
|||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
github.com/richardlehane/mscfb v1.0.7 // indirect
|
||||||
|
github.com/richardlehane/msoleps v1.0.6 // indirect
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.2 // indirect
|
||||||
|
github.com/xuri/efp v0.0.1 // indirect
|
||||||
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
|
||||||
golang.org/x/net v0.57.0 // indirect
|
golang.org/x/net v0.57.0 // indirect
|
||||||
golang.org/x/sync v0.22.0 // indirect
|
golang.org/x/sync v0.22.0 // indirect
|
||||||
golang.org/x/sys v0.47.0 // indirect
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
golang.org/x/text v0.40.0 // indirect
|
golang.org/x/text v0.40.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
|
replace github.com/pbnjay/grate => ./third_party/grate
|
||||||
@@ -43,6 +43,10 @@ github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwX
|
|||||||
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
|
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/richardlehane/mscfb v1.0.7 h1:oeoiM0WE79vHwE8RpIYYvIAc8ajTH2mb6UZm55/+EB0=
|
||||||
|
github.com/richardlehane/mscfb v1.0.7/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo=
|
||||||
|
github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg=
|
||||||
|
github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||||
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
|
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
|
||||||
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
@@ -55,12 +59,22 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
|
|||||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44=
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
|
||||||
|
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
|
||||||
|
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||||
|
github.com/xuri/excelize/v2 v2.11.0 h1:HxaEFl6sRN2+8J5a8HaKq+0M4FsjBGMnWWtjOCPSG88=
|
||||||
|
github.com/xuri/excelize/v2 v2.11.0/go.mod h1:jxFLbzaIwGQ5ufFNvYfUOHqXhfPaNmP14KWfmNz2Uak=
|
||||||
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
|
||||||
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||||
|
golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
|
||||||
|
golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
|
||||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
|||||||
@@ -130,11 +130,12 @@ const insertCallSQL = `
|
|||||||
INSERT INTO ai_call_logs (
|
INSERT INTO ai_call_logs (
|
||||||
company_id, user_id, job_id, raw_product_id, role, provider_mode, model,
|
company_id, user_id, job_id, raw_product_id, role, provider_mode, model,
|
||||||
system_prompt, user_prompt, response_text, error, finish_reason,
|
system_prompt, user_prompt, response_text, error, finish_reason,
|
||||||
prompt_tokens, completion_tokens, total_tokens, duration_ms)
|
prompt_tokens, completion_tokens, total_tokens, duration_ms,
|
||||||
|
cached_prompt_tokens, cost_micros)
|
||||||
VALUES (
|
VALUES (
|
||||||
$1, $2, $3, $4, $5, $6, $7,
|
$1, $2, $3, $4, $5, $6, $7,
|
||||||
$8, $9, $10, $11, $12,
|
$8, $9, $10, $11, $12,
|
||||||
$13, $14, $15, $16)`
|
$13, $14, $15, $16, $17, $18)`
|
||||||
|
|
||||||
// Record persists one call, merging any CallContext on ctx. Capture must never
|
// Record persists one call, merging any CallContext on ctx. Capture must never
|
||||||
// break the request it is observing: every failure is swallowed after one log line.
|
// break the request it is observing: every failure is swallowed after one log line.
|
||||||
@@ -167,11 +168,19 @@ func (r *Recorder) Record(ctx context.Context, c Call) {
|
|||||||
|
|
||||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
// Persist the exact model-rate cost at capture time. Historical call rows stay
|
||||||
|
// NULL rather than displaying a fabricated per-call amount.
|
||||||
|
price := r.priceFor(ctx, c.Model)
|
||||||
|
var recordedCost any
|
||||||
|
if price.InputPerMTok > 0 || price.CachedInputPerMTok > 0 || price.OutputPerMTok > 0 {
|
||||||
|
recordedCost = CostMicros(price, c.PromptTokens, c.CachedPromptTokens, c.OutputTokens)
|
||||||
|
}
|
||||||
_, err := r.pool.Exec(writeCtx, insertCallSQL,
|
_, err := r.pool.Exec(writeCtx, insertCallSQL,
|
||||||
nullUUID(c.CompanyID), nullUUID(c.UserID), nullUUID(c.JobID), nullUUID(c.RawProductID),
|
nullUUID(c.CompanyID), nullUUID(c.UserID), nullUUID(c.JobID), nullUUID(c.RawProductID),
|
||||||
c.Role, c.ProviderMode, c.Model,
|
c.Role, c.ProviderMode, c.Model,
|
||||||
clamp(c.System), clamp(c.User), clamp(c.Response), clamp(c.Error), c.FinishReason,
|
clamp(c.System), clamp(c.User), clamp(c.Response), clamp(c.Error), c.FinishReason,
|
||||||
c.PromptTokens, c.OutputTokens, c.TotalTokens, int(c.Duration.Milliseconds()),
|
c.PromptTokens, c.OutputTokens, c.TotalTokens, int(c.Duration.Milliseconds()),
|
||||||
|
c.CachedPromptTokens, recordedCost,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
r.noteFailure(err)
|
r.noteFailure(err)
|
||||||
|
|||||||
@@ -74,3 +74,11 @@ func TestClamp_boundsBody(t *testing.T) {
|
|||||||
t.Fatal("clamped body must say it was truncated")
|
t.Fatal("clamped body must say it was truncated")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCallCapturePersistsCostAndCachedTokens(t *testing.T) {
|
||||||
|
for _, name := range []string{"cached_prompt_tokens", "cost_micros"} {
|
||||||
|
if !strings.Contains(insertCallSQL, name) {
|
||||||
|
t.Fatalf("missing AI call capture field %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,10 @@ type ModelPrice struct {
|
|||||||
// GPT-5.6 rates here means a fresh database still costs correctly before the
|
// GPT-5.6 rates here means a fresh database still costs correctly before the
|
||||||
// migration seed is edited. Rates: OpenAI list price, 2026-07-30.
|
// migration seed is edited. Rates: OpenAI list price, 2026-07-30.
|
||||||
var defaultModelPrices = map[string]ModelPrice{
|
var defaultModelPrices = map[string]ModelPrice{
|
||||||
|
// OpenAI public standard-rate text models, verified 2026-10-16.
|
||||||
|
"gpt-5.4-mini": {InputPerMTok: 750_000, CachedInputPerMTok: 75_000, OutputPerMTok: 4_500_000},
|
||||||
|
"gpt-5-mini": {InputPerMTok: 250_000, CachedInputPerMTok: 25_000, OutputPerMTok: 2_000_000},
|
||||||
|
"gpt-6-luna": {InputPerMTok: 100_000, CachedInputPerMTok: 10_000, OutputPerMTok: 500_000},
|
||||||
"gpt-5.6-luna": {InputPerMTok: 200_000, CachedInputPerMTok: 20_000, OutputPerMTok: 1_200_000},
|
"gpt-5.6-luna": {InputPerMTok: 200_000, CachedInputPerMTok: 20_000, OutputPerMTok: 1_200_000},
|
||||||
"gpt-5.6-terra": {InputPerMTok: 2_000_000, CachedInputPerMTok: 200_000, OutputPerMTok: 12_000_000},
|
"gpt-5.6-terra": {InputPerMTok: 2_000_000, CachedInputPerMTok: 200_000, OutputPerMTok: 12_000_000},
|
||||||
"gpt-5.6-sol": {InputPerMTok: 5_000_000, CachedInputPerMTok: 500_000, OutputPerMTok: 30_000_000},
|
"gpt-5.6-sol": {InputPerMTok: 5_000_000, CachedInputPerMTok: 500_000, OutputPerMTok: 30_000_000},
|
||||||
|
|||||||
@@ -0,0 +1,359 @@
|
|||||||
|
package aiprompts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A1's historical content sometimes repeats the exact same H2/paragraph pair.
|
||||||
|
// Remove only identical pairs; different benefits, paragraph inclusion rules,
|
||||||
|
// technical specifications and all non-description instructions stay intact.
|
||||||
|
var a1HeadingParagraph = regexp.MustCompile(`(?is)<\s*h[1-4]\s*>.*?<\s*/\s*h[1-4]\s*>\s*<\s*p\s*>.*?<\s*/\s*p\s*>`)
|
||||||
|
var a1Whitespace = regexp.MustCompile(`\s+`)
|
||||||
|
|
||||||
|
func DedupeA1DescriptionBlocks(source string) (string, int) {
|
||||||
|
blocks := a1HeadingParagraph.FindAllStringIndex(source, -1)
|
||||||
|
if len(blocks) < 2 {
|
||||||
|
return source, 0
|
||||||
|
}
|
||||||
|
seen := make(map[string]bool, len(blocks))
|
||||||
|
var out strings.Builder
|
||||||
|
out.Grow(len(source))
|
||||||
|
cursor, removed := 0, 0
|
||||||
|
for _, b := range blocks {
|
||||||
|
part := source[b[0]:b[1]]
|
||||||
|
key := strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(part), " "))
|
||||||
|
// Keep non-description content exactly as it was. Removing an exact
|
||||||
|
// repeated pair must not also delete the next section or specs.
|
||||||
|
out.WriteString(source[cursor:b[0]])
|
||||||
|
if seen[key] {
|
||||||
|
removed++
|
||||||
|
} else {
|
||||||
|
seen[key] = true
|
||||||
|
out.WriteString(part)
|
||||||
|
}
|
||||||
|
cursor = b[1]
|
||||||
|
}
|
||||||
|
out.WriteString(source[cursor:])
|
||||||
|
if removed == 0 {
|
||||||
|
return source, 0
|
||||||
|
}
|
||||||
|
// Do not rewrite punctuation/case/brand-specific rules.
|
||||||
|
return out.String(), removed
|
||||||
|
}
|
||||||
|
|
||||||
|
// DedupeA1DescriptionTemplate removes repeated adjacent H2/P instruction pairs
|
||||||
|
// from the structured formula as well as from legacy HTML prompts. Other JSON
|
||||||
|
// fields, including metaTitle and metaDescription, are preserved unchanged.
|
||||||
|
func DedupeA1DescriptionTemplate(raw string) (string, int, error) {
|
||||||
|
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "null" {
|
||||||
|
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 {
|
||||||
|
return raw, 0, nil
|
||||||
|
}
|
||||||
|
var sections []map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(obj["sections"], §ions); err != nil {
|
||||||
|
return raw, 0, nil
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
result := make([]map[string]json.RawMessage, 0, len(sections))
|
||||||
|
removed := 0
|
||||||
|
for i := 0; i < len(sections); i++ {
|
||||||
|
var typ, instruction string
|
||||||
|
_ = json.Unmarshal(sections[i]["type"], &typ)
|
||||||
|
_ = json.Unmarshal(sections[i]["instructions"], &instruction)
|
||||||
|
if strings.EqualFold(typ, "h2") && i+1 < len(sections) {
|
||||||
|
var nextType, nextText string
|
||||||
|
_ = json.Unmarshal(sections[i+1]["type"], &nextType)
|
||||||
|
_ = json.Unmarshal(sections[i+1]["instructions"], &nextText)
|
||||||
|
if strings.EqualFold(nextType, "p") {
|
||||||
|
key := strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(instruction+"\x00"+nextText), " "))
|
||||||
|
if seen[key] {
|
||||||
|
removed++
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[key] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result = append(result, sections[i])
|
||||||
|
}
|
||||||
|
if removed == 0 {
|
||||||
|
return raw, 0, nil
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(result)
|
||||||
|
if err != nil {
|
||||||
|
return raw, 0, err
|
||||||
|
}
|
||||||
|
obj["sections"] = encoded
|
||||||
|
bytes, err := json.Marshal(obj)
|
||||||
|
if err != nil {
|
||||||
|
return raw, 0, err
|
||||||
|
}
|
||||||
|
return string(bytes), removed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeA1RepeatedBenefits retains the number/order of A1 HTML sections,
|
||||||
|
// but makes duplicate benefit instructions distinct instead of deleting copy.
|
||||||
|
// It preserves title/meta instructions, original product-name inclusion intent,
|
||||||
|
// and the technical-specifications block.
|
||||||
|
var a1HeadingText = regexp.MustCompile(`(?is)(<\s*h[1-4]\s*>\s*\{?)(.*?)(\}?\s*<\s*/\s*h[1-4]\s*>)`)
|
||||||
|
var a1ParagraphText = regexp.MustCompile(`(?is)(<\s*p\s*>\s*\{?)(.*?)(\}?\s*<\s*/\s*p\s*>)`)
|
||||||
|
|
||||||
|
func a1NormalizeInstruction(value string) string {
|
||||||
|
return strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(strings.Trim(value, "{} \t\n")), " "))
|
||||||
|
}
|
||||||
|
|
||||||
|
func a1UniqBenefit(heading, paragraph string, position int, seenHeadings, seenParagraphs map[string]bool) (string, string, bool) {
|
||||||
|
headKey := a1NormalizeInstruction(heading)
|
||||||
|
paragraphKey := a1NormalizeInstruction(paragraph)
|
||||||
|
duplicate := (headKey != "" && seenHeadings[headKey]) || (paragraphKey != "" && seenParagraphs[paragraphKey])
|
||||||
|
if headKey != "" {
|
||||||
|
seenHeadings[headKey] = true
|
||||||
|
}
|
||||||
|
if paragraphKey != "" {
|
||||||
|
seenParagraphs[paragraphKey] = true
|
||||||
|
}
|
||||||
|
if !duplicate {
|
||||||
|
return heading, paragraph, false
|
||||||
|
}
|
||||||
|
newHeading := fmt.Sprintf("Izpostavi %d. drugačno in preverjeno prednost izdelka. Ne ponavljaj prejšnjih prednosti ali celotnega imena izdelka.", position)
|
||||||
|
lower := strings.ToLower(paragraph)
|
||||||
|
includeName := strings.Contains(lower, "vključi") || strings.Contains(lower, "vkljuci") || strings.Contains(lower, "vsebuje novo ime") && !strings.Contains(lower, "ne vsebuje")
|
||||||
|
newParagraph := fmt.Sprintf("Napiši približno 100 besed o %d. samostojni, z dejanskimi podatki podprti prednosti. Ne ponavljaj informacij iz prejšnjih odstavkov.", position)
|
||||||
|
if includeName {
|
||||||
|
newParagraph += " Novo ime izdelka vključi naravno natanko enkrat."
|
||||||
|
} else {
|
||||||
|
newParagraph += " Ne uporabi celotnega novega imena izdelka."
|
||||||
|
}
|
||||||
|
newParagraph += " Če prednosti ni mogoče potrditi z vhodnimi podatki, je ne izmišljaj."
|
||||||
|
return newHeading, newParagraph, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func a1ReplaceTagContent(source string, expression *regexp.Regexp, newInstruction string) string {
|
||||||
|
matches := expression.FindStringSubmatchIndex(source)
|
||||||
|
if len(matches) < 8 {
|
||||||
|
return source
|
||||||
|
}
|
||||||
|
return source[:matches[4]] + newInstruction + source[matches[5]:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 < 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
prompt, err := OfflineDefaultPrompt("sl")
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return DescriptionSectionInstructions(prompt)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
// surrounding category-specific instructions are kept untouched.
|
||||||
|
func upgradeKnownA1Boilerplate(source string) (string, int) {
|
||||||
|
blocks := a1HeadingParagraph.FindAllStringIndex(source, -1)
|
||||||
|
if !isKnownA1Boilerplate(source, len(blocks)) {
|
||||||
|
return source, 0
|
||||||
|
}
|
||||||
|
html := localizedA1SEODescription()
|
||||||
|
if html == "" {
|
||||||
|
return source, 0
|
||||||
|
}
|
||||||
|
start, end := blocks[0][0], blocks[len(blocks)-1][1]
|
||||||
|
if match := a1SpecTrailing.FindStringIndex(source[end:]); len(match) == 2 && match[0] == 0 {
|
||||||
|
// 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]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
var joined strings.Builder
|
||||||
|
pairs := 0
|
||||||
|
for i := 0; i+1 < len(sections); i++ {
|
||||||
|
if sections[i].Type == "h2" && sections[i+1].Type == "p" {
|
||||||
|
joined.WriteString(sections[i].Instructions + " " + sections[i+1].Instructions + " ")
|
||||||
|
pairs++
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isKnownA1Boilerplate(joined.String(), pairs) {
|
||||||
|
return raw, 0, nil
|
||||||
|
}
|
||||||
|
seo := localizedA1SEODescription()
|
||||||
|
parsed := DeriveDescriptionFormulaFromLegacyParts(LegacyEnhanceParts{DescriptionRules: seo, WasLegacy: true})
|
||||||
|
if len(parsed.Sections) != 5 {
|
||||||
|
return raw, 0, fmt.Errorf("invalid bundled Slovenian description")
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(parsed.Sections)
|
||||||
|
if err != nil {
|
||||||
|
return raw, 0, err
|
||||||
|
}
|
||||||
|
obj["sections"] = encoded
|
||||||
|
out, err := json.Marshal(obj)
|
||||||
|
if err != nil {
|
||||||
|
return raw, 0, err
|
||||||
|
}
|
||||||
|
return string(out), pairs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NormalizeA1RepeatedBenefits(source string) (string, int) {
|
||||||
|
if cleaned, n := upgradeKnownA1Boilerplate(source); n > 0 {
|
||||||
|
return cleaned, n
|
||||||
|
}
|
||||||
|
blocks := a1HeadingParagraph.FindAllStringIndex(source, -1)
|
||||||
|
if len(blocks) < 2 {
|
||||||
|
return source, 0
|
||||||
|
}
|
||||||
|
heads := map[string]bool{}
|
||||||
|
paragraphs := map[string]bool{}
|
||||||
|
var out strings.Builder
|
||||||
|
out.Grow(len(source))
|
||||||
|
cursor, rewritten := 0, 0
|
||||||
|
for i, idx := range blocks {
|
||||||
|
part := source[idx[0]:idx[1]]
|
||||||
|
headingMatch := a1HeadingText.FindStringSubmatch(part)
|
||||||
|
paragraphMatch := a1ParagraphText.FindStringSubmatch(part)
|
||||||
|
out.WriteString(source[cursor:idx[0]])
|
||||||
|
if len(headingMatch) == 4 && len(paragraphMatch) == 4 {
|
||||||
|
heading, paragraph, changed := a1UniqBenefit(headingMatch[2], paragraphMatch[2], i+1, heads, paragraphs)
|
||||||
|
if changed {
|
||||||
|
part = a1ReplaceTagContent(part, a1ParagraphText, paragraph)
|
||||||
|
part = a1ReplaceTagContent(part, a1HeadingText, heading)
|
||||||
|
rewritten++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.WriteString(part)
|
||||||
|
cursor = idx[1]
|
||||||
|
}
|
||||||
|
out.WriteString(source[cursor:])
|
||||||
|
if rewritten == 0 {
|
||||||
|
return source, 0
|
||||||
|
}
|
||||||
|
return out.String(), rewritten
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "null" {
|
||||||
|
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 {
|
||||||
|
return raw, 0, nil
|
||||||
|
}
|
||||||
|
var sections []map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(obj["sections"], §ions); err != nil {
|
||||||
|
return raw, 0, nil
|
||||||
|
}
|
||||||
|
heads := map[string]bool{}
|
||||||
|
paragraphs := map[string]bool{}
|
||||||
|
normalized := 0
|
||||||
|
pairNumber := 0
|
||||||
|
for i := 0; i+1 < len(sections); i++ {
|
||||||
|
var headingType, paragraphType, heading, paragraph string
|
||||||
|
_ = json.Unmarshal(sections[i]["type"], &headingType)
|
||||||
|
_ = json.Unmarshal(sections[i+1]["type"], ¶graphType)
|
||||||
|
if !strings.EqualFold(headingType, "h2") || !strings.EqualFold(paragraphType, "p") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(sections[i]["instructions"], &heading)
|
||||||
|
_ = json.Unmarshal(sections[i+1]["instructions"], ¶graph)
|
||||||
|
pairNumber++
|
||||||
|
newHeading, newParagraph, changed := a1UniqBenefit(heading, paragraph, pairNumber, heads, paragraphs)
|
||||||
|
if !changed {
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
hb, err := json.Marshal(newHeading)
|
||||||
|
if err != nil {
|
||||||
|
return raw, 0, err
|
||||||
|
}
|
||||||
|
pb, err := json.Marshal(newParagraph)
|
||||||
|
if err != nil {
|
||||||
|
return raw, 0, err
|
||||||
|
}
|
||||||
|
sections[i]["instructions"] = hb
|
||||||
|
sections[i+1]["instructions"] = pb
|
||||||
|
normalized++
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
if normalized == 0 {
|
||||||
|
return raw, 0, nil
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(sections)
|
||||||
|
if err != nil {
|
||||||
|
return raw, 0, err
|
||||||
|
}
|
||||||
|
obj["sections"] = encoded
|
||||||
|
result, err := json.Marshal(obj)
|
||||||
|
if err != nil {
|
||||||
|
return raw, 0, err
|
||||||
|
}
|
||||||
|
return string(result), normalized, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
package aiprompts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDedupeA1DescriptionBlocks(t *testing.T) {
|
||||||
|
input := `--- Title ---
|
||||||
|
Napiši ime v slovenščini
|
||||||
|
--- End Title ---
|
||||||
|
--- Description ---
|
||||||
|
<H2>{Benefit one}</H2><p>{No title}</p>
|
||||||
|
<H2>{Benefit two}</H2><p>{Include title}</p>
|
||||||
|
<H2>{Benefit one}</H2><p>{No title}</p>
|
||||||
|
<H2>{Benefit two}</H2><p>{Exclude title}</p>
|
||||||
|
<H2>{Benefit two}</H2><p>{Include title}</p>
|
||||||
|
<b>{Tehnične specifikacije}</b><ul><li>{3-10}</li></ul>
|
||||||
|
--- End Description ---
|
||||||
|
--- Meta ---
|
||||||
|
140 znakov
|
||||||
|
--- End Meta ---`
|
||||||
|
got, n := DedupeA1DescriptionBlocks(input)
|
||||||
|
if n != 2 {
|
||||||
|
t.Fatalf("removed=%d want 2", n)
|
||||||
|
}
|
||||||
|
if strings.Count(got, "<H2>") != 3 {
|
||||||
|
t.Fatalf("H2 count changed incorrectly: %s", got)
|
||||||
|
}
|
||||||
|
for _, want := range []string{"Napiši ime", "140 znakov", "Tehnične specifikacije", "Exclude title"} {
|
||||||
|
if !strings.Contains(got, want) {
|
||||||
|
t.Fatalf("lost %q", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
again, n := DedupeA1DescriptionBlocks(got)
|
||||||
|
if n != 0 || again != got {
|
||||||
|
t.Fatal("cleanup not idempotent")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDedupeA1RealRepeatingTemplate(t *testing.T) {
|
||||||
|
headingA := `<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2>`
|
||||||
|
headingB := `<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>`
|
||||||
|
paragraphA := `<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>`
|
||||||
|
paragraphB := `<p>{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}</p>`
|
||||||
|
original := headingA + "\n" + paragraphA + "\n" + headingB + "\n" + paragraphB + "\n" +
|
||||||
|
headingA + "\n" + paragraphA + "\n" + headingB + "\n" + paragraphB + "\n" +
|
||||||
|
headingB + "\n" + paragraphA + `<b>{Tehnične specifikacije}</b><ul><li>{Napiši 3-10 tehničnih specifikacij v alinejah}</li></ul>`
|
||||||
|
cleaned, removed := DedupeA1DescriptionBlocks(original)
|
||||||
|
if removed != 2 {
|
||||||
|
t.Fatalf("expected 2 duplicate pairs, got %d", removed)
|
||||||
|
}
|
||||||
|
if strings.Count(cleaned, "<H2>") != 3 {
|
||||||
|
t.Fatalf("expected 3 distinct pairs: %s", cleaned)
|
||||||
|
}
|
||||||
|
if !strings.Contains(cleaned, "Tehnične specifikacije") {
|
||||||
|
t.Fatal("lost specs")
|
||||||
|
}
|
||||||
|
twice, removedAgain := DedupeA1DescriptionBlocks(cleaned)
|
||||||
|
if removedAgain != 0 || twice != cleaned {
|
||||||
|
t.Fatal("A1 cleanup must be idempotent")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDedupeStructuredA1Descriptions(t *testing.T) {
|
||||||
|
raw := `{"sections":[{"type":"h2","instructions":"A"},{"type":"p","instructions":"X"},{"type":"h2","instructions":"B"},{"type":"p","instructions":"Y"},{"type":"h2","instructions":"A"},{"type":"p","instructions":"X"},{"type":"ul","instructions":"Specifications"}],"metaDescription":"140 znakov"}`
|
||||||
|
cleaned, removed, err := DedupeA1DescriptionTemplate(raw)
|
||||||
|
if err != nil || removed != 1 {
|
||||||
|
t.Fatalf("removed=%d err=%v", removed, err)
|
||||||
|
}
|
||||||
|
if strings.Count(cleaned, `"type":"h2"`) != 2 || !strings.Contains(cleaned, `140 znakov`) || !strings.Contains(cleaned, `Specifications`) {
|
||||||
|
t.Fatalf("invalid result: %s", cleaned)
|
||||||
|
}
|
||||||
|
again, n, err := DedupeA1DescriptionTemplate(cleaned)
|
||||||
|
if n != 0 || err != nil || again != cleaned {
|
||||||
|
t.Fatal("structured cleanup not idempotent")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeA1LegacySEOHTML(t *testing.T) {
|
||||||
|
source := `--- Title ---
|
||||||
|
Napiši Novo ime izdelka
|
||||||
|
--- End Title ---
|
||||||
|
--- Description ---
|
||||||
|
<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>
|
||||||
|
<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}</p>
|
||||||
|
<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>
|
||||||
|
<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}</p>
|
||||||
|
<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p><b>{Tehnične specifikacije}</b><ul><li>{Napiši 3-10 tehničnih specifikacij v alinejah}</li></ul>
|
||||||
|
--- End Description ---
|
||||||
|
--- Meta ---
|
||||||
|
Najprej Novo ime izdelka
|
||||||
|
--- End Meta ---`
|
||||||
|
result, changed := NormalizeA1RepeatedBenefits(source)
|
||||||
|
if changed != 5 {
|
||||||
|
t.Fatalf("expected five legacy boilerplate pairs, got %d", changed)
|
||||||
|
}
|
||||||
|
for _, want := range []string{"--- Title ---", "Napiši Novo ime izdelka", "--- Meta ---", "Najprej Novo ime izdelka", "<p>{", "<h2>{", "<ul><li>{"} {
|
||||||
|
if !strings.Contains(result, want) {
|
||||||
|
t.Fatalf("missing %q: %s", want, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Count(result, "<h2>") != 2 || strings.Contains(result, "100 besed") {
|
||||||
|
t.Fatalf("still repetitive: %s", result)
|
||||||
|
}
|
||||||
|
again, n := NormalizeA1RepeatedBenefits(result)
|
||||||
|
if n != 0 || again != result {
|
||||||
|
t.Fatal("SEO upgrade must be idempotent")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeA1StructuredKeepsSections(t *testing.T) {
|
||||||
|
source := `{"sections":[{"type":"h2","instructions":"Benefit A"},{"type":"p","instructions":"NE vsebuje Novo ime izdelka"},{"type":"h2","instructions":"Benefit B"},{"type":"p","instructions":"VKLJUČI Novo ime izdelka"},{"type":"h2","instructions":"Benefit A"},{"type":"p","instructions":"NE vsebuje Novo ime izdelka"}],"metaDescription":"140 znakov"}`
|
||||||
|
result, changed, err := NormalizeA1DescriptionTemplate(source)
|
||||||
|
if err != nil || changed != 1 {
|
||||||
|
t.Fatalf("changed=%d err=%v", changed, err)
|
||||||
|
}
|
||||||
|
if strings.Count(result, `"type":"h2"`) != 3 || !strings.Contains(result, "3. drugačno") || !strings.Contains(result, "140 znakov") {
|
||||||
|
t.Fatalf("invalid: %s", result)
|
||||||
|
}
|
||||||
|
again, n, err := NormalizeA1DescriptionTemplate(result)
|
||||||
|
if n != 0 || err != nil || again != result {
|
||||||
|
t.Fatal("not idempotent")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeA1LegacyStructuredSEO(t *testing.T) {
|
||||||
|
raw := `{"sections":[{"type":"h2","instructions":"Napiši Novo ime izdelka brez barve in izpostavi en benefit"},{"type":"p","instructions":"Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka"},{"type":"h2","instructions":"Izpostavi en benefit"},{"type":"p","instructions":"Napiši odstavek, ki je dolg 100 besed in VKLJUČI Novo ime izdelka"},{"type":"h2","instructions":"Napiši Novo ime izdelka"},{"type":"p","instructions":"Napiši odstavek, ki je dolg 100 besed"},{"type":"h2","instructions":"Benefit"},{"type":"p","instructions":"Napiši odstavek, ki je dolg 100 besed"},{"type":"ul","instructions":"Tehnične specifikacije"}],"metaDescription":"140 znakov"}`
|
||||||
|
clean, n, err := NormalizeA1DescriptionTemplate(raw)
|
||||||
|
if err != nil || n != 4 {
|
||||||
|
t.Fatalf("changed=%d err=%v", n, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(clean, `"type":"ul"`) || !strings.Contains(clean, `140 znakov`) || strings.Contains(clean, "100 besed") {
|
||||||
|
t.Fatal(clean)
|
||||||
|
}
|
||||||
|
twice, n, err := NormalizeA1DescriptionTemplate(clean)
|
||||||
|
if err != nil || n != 0 || twice != clean {
|
||||||
|
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 := `<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>
|
||||||
|
<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}</p>
|
||||||
|
|
||||||
|
|
||||||
|
<H2>{Izpostavi 3. drugačno in preverjeno prednost izdelka. Ne ponavljaj prejšnjih prednosti ali celotnega imena izdelka.}</H2>
|
||||||
|
<p>{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.}</p><b>{Tehnične specifikacije}</b><ul><li>{Napiši 3-10 tehničnih specifikacij v alinejah}</li></ul>`
|
||||||
|
cleaned, replaced := NormalizeA1RepeatedBenefits(source)
|
||||||
|
if replaced != 3 {
|
||||||
|
t.Fatalf("expected three old/mixed pairs replaced, got %d: %s", replaced, cleaned)
|
||||||
|
}
|
||||||
|
if strings.Contains(cleaned, "100 besed") || strings.Contains(cleaned, "Izpostavi en benefit") || strings.Contains(cleaned, "3. drugačno") {
|
||||||
|
t.Fatalf("mixed legacy boilerplate survived: %s", cleaned)
|
||||||
|
}
|
||||||
|
if strings.Count(cleaned, "<h2>") != 2 || strings.Count(cleaned, "<ul><li>") != 1 || !strings.HasPrefix(cleaned, "<p>{") {
|
||||||
|
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 ---
|
||||||
|
<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>
|
||||||
|
<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>
|
||||||
|
<p>{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}</p>
|
||||||
|
<b>{Tehnične specifikacije}</b><ul><li>{Napiši 3-10 tehničnih specifikacij v alinejah}</li></ul>
|
||||||
|
--- End Description ---
|
||||||
|
--- Meta ---
|
||||||
|
{Ohranite lasten meta prompt}
|
||||||
|
--- End Meta ---`
|
||||||
|
cleaned, n := NormalizeA1RepeatedBenefits(source)
|
||||||
|
if n != 2 || strings.Count(cleaned, "<h2>") != 2 {
|
||||||
|
t.Fatalf("expected short template upgraded, changed=%d: %s", n, cleaned)
|
||||||
|
}
|
||||||
|
for _, retained := range []string{"{Ohranite naslov in pravila iz kategorije}", "{Ohranite lasten meta prompt}", "--- End Description ---"} {
|
||||||
|
if !strings.Contains(cleaned, retained) {
|
||||||
|
t.Fatalf("custom content lost: %s", cleaned)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(cleaned, "100 besed") || strings.Count(cleaned, "<ul><li>") != 1 {
|
||||||
|
t.Fatalf("duplicated spec or old paragraph remains: %s", cleaned)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeA1MixedStructuredTemplatePreservesMeta(t *testing.T) {
|
||||||
|
source := `{"sections":[{"type":"h2","instructions":"Napiši Novo ime izdelka brez barve in izpostavi en benefit"},{"type":"p","instructions":"Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka"},{"type":"h2","instructions":"Izpostavi en benefit, in NE napiši Novo ime izdelka"},{"type":"p","instructions":"Napiši odstavek, ki je dolg 100 besed in VKLJUČI Novo ime izdelka"},{"type":"h2","instructions":"Izpostavi 3. drugačno in preverjeno prednost izdelka. Ne ponavljaj prejšnjih prednosti ali celotnega imena izdelka"},{"type":"p","instructions":"Napiši približno 100 besed o 3. samostojni prednosti"},{"type":"ul","instructions":"Napiši 3-10 tehničnih specifikacij v alinejah"}],"metaTitle":"A1 custom title","metaDescription":"A1 custom meta","otherField":true}`
|
||||||
|
cleaned, count, err := NormalizeA1DescriptionTemplate(source)
|
||||||
|
if err != nil || count != 3 {
|
||||||
|
t.Fatalf("mixed structured template count=%d err=%v result=%s", count, err, cleaned)
|
||||||
|
}
|
||||||
|
for _, retained := range []string{`"metaTitle":"A1 custom title"`, `"metaDescription":"A1 custom meta"`, `"otherField":true`} {
|
||||||
|
if !strings.Contains(cleaned, retained) {
|
||||||
|
t.Fatalf("lost metadata %s in %s", retained, cleaned)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(cleaned, "100 besed") || strings.Count(cleaned, `"type":"h2"`) != 2 || strings.Count(cleaned, `"type":"ul"`) != 1 {
|
||||||
|
t.Fatalf("did not upgrade description to SEO structure: %s", cleaned)
|
||||||
|
}
|
||||||
|
twice, n, err := NormalizeA1DescriptionTemplate(cleaned)
|
||||||
|
if err != nil || n != 0 || twice != cleaned {
|
||||||
|
t.Fatalf("structured upgrade not idempotent: n=%d err=%v", n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeA1UnrelatedCustomPromptsUntouched(t *testing.T) {
|
||||||
|
source := `<H2>{Izbira pravega izdelka}</H2><p>{Napiši opis glede na navedena dejstva, brez ugibanja.}</p>`
|
||||||
|
actual, changed := NormalizeA1RepeatedBenefits(source)
|
||||||
|
if actual != source || changed != 0 {
|
||||||
|
t.Fatalf("unexpected change of custom text: %s", actual)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeA1LegacyEnDashSpecs(t *testing.T) {
|
||||||
|
source := `<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2><p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>
|
||||||
|
<b>Tehnične specifikacije</b>
|
||||||
|
<ul><li>{Napiši 3–10 tehničnih specifikacij v alinejah}</li></ul>`
|
||||||
|
got, count := NormalizeA1RepeatedBenefits(source)
|
||||||
|
if count != 1 || strings.Count(got, "<ul><li>") != 1 || strings.Contains(got, "3–10 tehničnih") {
|
||||||
|
t.Fatalf("duplicated technical specifications: %d %s", count, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeA1OldCableH1(t *testing.T) {
|
||||||
|
source := `<name>{Ohrani specifičen naslov kabla}</name>
|
||||||
|
<metaDescription>{Ohrani meta}</metaDescription>
|
||||||
|
<H1>{Zapiši Novo_ime_izdelka}</H1>
|
||||||
|
<H2>{Naj vključuje Novo_ime_izdelka in izpostavi en benefit}</H2>
|
||||||
|
<p>{Nadaljuj iz naslova in napiši 100 besed o temu benefitu, ne vključuj Novo_ime_izdelka}</p>`
|
||||||
|
got, count := NormalizeA1RepeatedBenefits(source)
|
||||||
|
if count != 1 || strings.Contains(strings.ToLower(got), "<h1>") || strings.Contains(got, "napiši 100 besed") {
|
||||||
|
t.Fatalf("legacy H1 not removed: %d %s", count, got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(got, "Ohrani meta") || !strings.Contains(got, "Ohrani specifičen naslov kabla") {
|
||||||
|
t.Fatal("overwrote category specific metadata")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
package aiprompts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// isObsoleteA1Meta recognizes only known, previously shipped generic meta
|
||||||
|
// instructions. A category's genuinely custom SEO copy must not be overwritten.
|
||||||
|
func isObsoleteA1Meta(value string) bool {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" || value == "{}" || value == "null" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(value)
|
||||||
|
// Platform-generated English SEO instructions in an A1 Slovenian category
|
||||||
|
// are also defaults, not custom authoring. Upgrade those to Slovenian.
|
||||||
|
if enTitle, enDesc, err := DefaultSEOMetaInstructions("en"); err == nil && (value == enTitle || value == enDesc) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return (strings.Contains(lower, "novo_ime_izdelka") && strings.Contains(lower, "140 znakov")) ||
|
||||||
|
(strings.Contains(lower, "novo ime izdelka") && strings.Contains(lower, "50-60 znakov")) ||
|
||||||
|
(strings.Contains(lower, "new product name") && strings.Contains(lower, "140 characters")) ||
|
||||||
|
value == DefaultLegacyMetaTitleRule || value == DefaultMetaTitleRuleEN
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeA1MetaRole updates ONLY a missing or recognized obsolete Meta role.
|
||||||
|
// Title and Description roles, and user-authored meta rules, remain byte-identical.
|
||||||
|
// The selected language determines which bundled translated rule is inserted.
|
||||||
|
func NormalizeA1MetaRole(source, lang string) (string, bool) {
|
||||||
|
if !CategoryEnhanceHasRoleSections(source) {
|
||||||
|
return source, false
|
||||||
|
}
|
||||||
|
old := ExtractEnhanceSectionBody(source, SectionMetaStart, SectionMetaEnd)
|
||||||
|
// Imported A1 combined formulas may already have good meta rules but lack
|
||||||
|
// the {} instruction wrappers. Preserve those words and normalize markup.
|
||||||
|
if title, description, ok := splitLocalizedMetaRules(old); ok {
|
||||||
|
canonical := "{meta_title: " + title + "}\n{meta_description: " + description + "}"
|
||||||
|
if strings.TrimSpace(old) == canonical {
|
||||||
|
return source, false
|
||||||
|
}
|
||||||
|
return replaceA1MetaBody(source, canonical)
|
||||||
|
}
|
||||||
|
if !isObsoleteA1Meta(old) {
|
||||||
|
return source, false
|
||||||
|
}
|
||||||
|
localized, err := OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
return source, false
|
||||||
|
}
|
||||||
|
replacement := ExtractEnhanceSectionBody(localized, SectionMetaStart, SectionMetaEnd)
|
||||||
|
if replacement == "" || strings.TrimSpace(old) == replacement {
|
||||||
|
return source, false
|
||||||
|
}
|
||||||
|
return replaceA1MetaBody(source, replacement)
|
||||||
|
}
|
||||||
|
|
||||||
|
func replaceA1MetaBody(source, replacement string) (string, bool) {
|
||||||
|
// Locate the exact Meta role without touching the other two roles.
|
||||||
|
normal := strings.ToLower(source)
|
||||||
|
start := strings.Index(normal, strings.ToLower(SectionMetaStart))
|
||||||
|
if start < 0 {
|
||||||
|
return source, false
|
||||||
|
}
|
||||||
|
offset := start + len(SectionMetaStart)
|
||||||
|
end := strings.Index(normal[offset:], strings.ToLower(SectionMetaEnd))
|
||||||
|
if end < 0 {
|
||||||
|
return source, false
|
||||||
|
}
|
||||||
|
return source[:offset] + "\n" + replacement + "\n" + source[offset+end:], true
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeA1MetaTemplate adds/repairs metaTitle and metaDescription on the
|
||||||
|
// A1 JSON description_template. Existing HTML sections and custom metadata are
|
||||||
|
// preserved. An empty template is valid and is initialized with metadata only.
|
||||||
|
func NormalizeA1MetaTemplate(raw, lang string) (string, bool, error) {
|
||||||
|
trimmed := strings.TrimSpace(raw)
|
||||||
|
if trimmed == "null" {
|
||||||
|
trimmed = ""
|
||||||
|
}
|
||||||
|
obj := make(map[string]json.RawMessage)
|
||||||
|
if trimmed != "" {
|
||||||
|
if err := json.Unmarshal([]byte(trimmed), &obj); err != nil {
|
||||||
|
return raw, false, fmt.Errorf("decode A1 description_template: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if obj == nil {
|
||||||
|
obj = make(map[string]json.RawMessage)
|
||||||
|
}
|
||||||
|
title, desc, err := DefaultSEOMetaInstructions(lang)
|
||||||
|
if err != nil {
|
||||||
|
return raw, false, err
|
||||||
|
}
|
||||||
|
changed := false
|
||||||
|
for key, replacement := range map[string]string{"metaTitle": title, "metaDescription": desc} {
|
||||||
|
var existing string
|
||||||
|
if value := obj[key]; len(value) > 0 && string(value) != "null" {
|
||||||
|
if err := json.Unmarshal(value, &existing); err != nil {
|
||||||
|
return raw, false, fmt.Errorf("decode A1 %s: %w", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isObsoleteA1Meta(existing) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if existing == replacement {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(replacement)
|
||||||
|
if err != nil {
|
||||||
|
return raw, false, err
|
||||||
|
}
|
||||||
|
obj[key] = encoded
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
return raw, false, nil
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(obj)
|
||||||
|
if err != nil {
|
||||||
|
return raw, false, err
|
||||||
|
}
|
||||||
|
return string(encoded), true, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package aiprompts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLocalizedDefaultTemplatesConsistentAndBraced(t *testing.T) {
|
||||||
|
languages := OfflinePromptLanguages()
|
||||||
|
if len(languages) != 25 {
|
||||||
|
t.Fatalf("languages=%d", len(languages))
|
||||||
|
}
|
||||||
|
for _, lang := range languages {
|
||||||
|
prompt, err := OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
desc := DescriptionSectionInstructions(prompt)
|
||||||
|
if strings.Count(desc, "<h2>") != 2 || strings.Count(desc, "<p>") != 2 || strings.Count(desc, "<ul><li>{") != 1 || strings.Contains(desc, "<h1>") {
|
||||||
|
t.Errorf("%s invalid semantic HTML: %s", lang, desc)
|
||||||
|
}
|
||||||
|
if strings.Count(desc, "<h2>{") != 2 || strings.Count(desc, "<p>{") != 2 {
|
||||||
|
t.Errorf("%s missing localized instruction braces", lang)
|
||||||
|
}
|
||||||
|
if strings.Contains(desc, "100 words") || strings.Contains(desc, "100 besed") {
|
||||||
|
t.Errorf("%s obsolete quota", lang)
|
||||||
|
}
|
||||||
|
title, meta, err := DefaultSEOMetaInstructions(lang)
|
||||||
|
if err != nil || title == "" || meta == "" || strings.Contains(title, "meta_description:") || strings.Contains(meta, "meta_title:") {
|
||||||
|
t.Errorf("%s meta incorrectly parsed: %q %q %v", lang, title, meta, err)
|
||||||
|
}
|
||||||
|
body := ExtractEnhanceSectionBody(prompt, SectionMetaStart, SectionMetaEnd)
|
||||||
|
if strings.Count(body, "{meta_title:") != 1 || strings.Count(body, "{meta_description:") != 1 {
|
||||||
|
t.Errorf("%s meta must have independently braced instructions: %s", lang, body)
|
||||||
|
}
|
||||||
|
f := EffectiveDescriptionFormula(nil, prompt)
|
||||||
|
if len(f.Sections) != 5 || f.MetaTitle != title || f.MetaDescription != meta {
|
||||||
|
t.Errorf("%s formula parsing mismatch sections=%d title=%q meta=%q", lang, len(f.Sections), f.MetaTitle, f.MetaDescription)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestA1MetaCleanupPreservesOtherSectionsAndCustomRules(t *testing.T) {
|
||||||
|
source := BuildCategoryEnhanceOverlay(LegacyEnhanceParts{
|
||||||
|
TitleRules: "{Custom A1 product title}", DescriptionRules: "<p>{Custom A1 description}</p>",
|
||||||
|
MetaRules: "Najprej napiši Novo_ime_izdelka in potem nadaljuj dokler nisi zapisal 140 znakov vključno s presledki",
|
||||||
|
})
|
||||||
|
corrected, changed := NormalizeA1MetaRole(source, "sl")
|
||||||
|
if !changed {
|
||||||
|
t.Fatal("expected obsolete A1 meta update")
|
||||||
|
}
|
||||||
|
if !strings.Contains(corrected, "<p>{Custom A1 description}</p>") || !strings.Contains(corrected, "{Custom A1 product title}") {
|
||||||
|
t.Fatal("rewrote custom A1 rules")
|
||||||
|
}
|
||||||
|
if !strings.Contains(corrected, "{meta_title:") || !strings.Contains(corrected, "{meta_description:") {
|
||||||
|
t.Fatalf("incorrect normalized markup: %s", corrected)
|
||||||
|
}
|
||||||
|
again, changed := NormalizeA1MetaRole(corrected, "sl")
|
||||||
|
if changed || again != corrected {
|
||||||
|
t.Fatal("cleanup not idempotent")
|
||||||
|
}
|
||||||
|
custom := strings.Replace(source, "Najprej napiši Novo_ime_izdelka in potem nadaljuj dokler nisi zapisal 140 znakov vključno s presledki", "Always mention our extended warranty", 1)
|
||||||
|
unchanged, changed := NormalizeA1MetaRole(custom, "sl")
|
||||||
|
if changed || unchanged != custom {
|
||||||
|
t.Fatal("custom A1 meta overwritten")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestA1MetaTemplateRepairsOnlyLegacy(t *testing.T) {
|
||||||
|
raw := `{"metaTitle":"Najprej napiši Novo ime izdelka in dodaj glavno prednost. Dolžina 50-60 znakov vključno s presledki.","metaDescription":"Najprej napiši Novo_ime_izdelka in potem nadaljuj dokler nisi zapisal 140 znakov vključno s presledki","sections":[{"type":"p","instructions":"Existing custom"}]}`
|
||||||
|
updated, changed, err := NormalizeA1MetaTemplate(raw, "sl")
|
||||||
|
if err != nil || !changed {
|
||||||
|
t.Fatalf("failed to upgrade %v", err)
|
||||||
|
}
|
||||||
|
var obj map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(updated), &obj); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if obj["sections"].([]any)[0].(map[string]any)["instructions"] != "Existing custom" {
|
||||||
|
t.Fatal("lost original A1 section")
|
||||||
|
}
|
||||||
|
if strings.Contains(updated, "140 znakov") {
|
||||||
|
t.Fatal("old meta still present")
|
||||||
|
}
|
||||||
|
second, changed, err := NormalizeA1MetaTemplate(updated, "sl")
|
||||||
|
if err != nil || changed || second != updated {
|
||||||
|
t.Fatalf("A1 meta repeat changed: %v", err)
|
||||||
|
}
|
||||||
|
custom, changed, err := NormalizeA1MetaTemplate(`{"metaTitle":"Our own rule","metaDescription":"Our own description"}`, "sl")
|
||||||
|
if err != nil || changed || !strings.Contains(custom, "Our own description") {
|
||||||
|
t.Fatal("custom meta overwritten")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLegacyAndNewMetaWrapperCompatibility(t *testing.T) {
|
||||||
|
for _, raw := range []string{
|
||||||
|
"{meta_title: Short SEO title\nmeta_description: Concise summary}",
|
||||||
|
"{meta_title: Short SEO title}\n{meta_description: Concise summary}",
|
||||||
|
"meta_title: Short SEO title\nmeta_description: Concise summary",
|
||||||
|
} {
|
||||||
|
title, desc, ok := splitLocalizedMetaRules(raw)
|
||||||
|
if !ok || title != "Short SEO title" || desc != "Concise summary" {
|
||||||
|
t.Errorf("unparsed %q: %q %q", raw, title, desc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package aiprompts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCanonicalDefaultsSameForEveryCategory(t *testing.T) {
|
||||||
|
canonical, err := OfflineDefaultPrompt("en")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
names := []string{"", "High chairs", "Televisions", "Cables", "Mixers", "Unlisted category", "Stolčki"}
|
||||||
|
for _, name := range names {
|
||||||
|
got := DefaultCategoryFormula("", name)
|
||||||
|
if got.Overlay != canonical {
|
||||||
|
t.Fatalf("%s differs from canonical English\n%s", name, got.Overlay)
|
||||||
|
}
|
||||||
|
if !strings.Contains(got.Overlay, "<p>{") || strings.Contains(got.Overlay, "first verified benefit") {
|
||||||
|
t.Fatalf("legacy HTML slipped through for %s", name)
|
||||||
|
}
|
||||||
|
if got.DescriptionTemplateJSON != DefaultCategoryFormula("", "unknown").DescriptionTemplateJSON {
|
||||||
|
t.Fatalf("%s has category-specific HTML validation shape", name)
|
||||||
|
}
|
||||||
|
if got.TitleTemplateJSON != DefaultCategoryFormula("", "unknown").TitleTemplateJSON {
|
||||||
|
t.Fatalf("%s has category-specific structured title", name)
|
||||||
|
}
|
||||||
|
old := PriorDefaultCategoryFormula("", name)
|
||||||
|
if old.Overlay == got.Overlay {
|
||||||
|
t.Fatalf("%s lost old default for migration", name)
|
||||||
|
}
|
||||||
|
previous := PreviousSEODefaultCategoryFormula("", name)
|
||||||
|
if previous.Overlay == got.Overlay {
|
||||||
|
t.Fatalf("%s lost SEO-v4 default for migration", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sources := AllDefaultCategoryPrompts(); len(sources) != 1 || sources[0] != canonical {
|
||||||
|
t.Fatalf("expected one shared template, got %d", len(sources))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLocalizedMetaOverridesGlobalEnglishTemplate(t *testing.T) {
|
||||||
|
en := DefaultCategoryFormula("", "Any")
|
||||||
|
hr, err := OfflineDefaultPrompt("hr")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resolved := EffectiveDescriptionFormula(en.DescriptionTemplateJSON, hr)
|
||||||
|
if !strings.Contains(resolved.MetaDescription, "sažmi") {
|
||||||
|
t.Fatalf("Croatian meta instructions not honored: %s", resolved.MetaDescription)
|
||||||
|
}
|
||||||
|
if strings.Contains(resolved.MetaDescription, "Summarize what") {
|
||||||
|
t.Fatalf("English leaked into Croatian meta")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCanonicalLocalesHaveExactlySameHTMLStructure(t *testing.T) {
|
||||||
|
want := []string{"p", "h2", "p", "h2", "ul"}
|
||||||
|
for _, lang := range OfflinePromptLanguages() {
|
||||||
|
source, err := OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
section := DescriptionSectionInstructions(source)
|
||||||
|
f := DeriveDescriptionFormulaFromLegacyParts(LegacyEnhanceParts{DescriptionRules: section, WasLegacy: true})
|
||||||
|
if len(f.Sections) != len(want) {
|
||||||
|
t.Fatalf("%s has %d sections", lang, len(f.Sections))
|
||||||
|
}
|
||||||
|
for i, typ := range want {
|
||||||
|
if f.Sections[i].Type != typ {
|
||||||
|
t.Fatalf("%s section %d is %s not %s", lang, i, f.Sections[i].Type, typ)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !f.Sections[1].Optional || !f.Sections[2].Optional || !f.Sections[3].Optional || !f.Sections[4].Optional {
|
||||||
|
t.Fatalf("%s optional feature/spec sections missing flags", lang)
|
||||||
|
}
|
||||||
|
if strings.Contains(section, "<h1>") || strings.Contains(section, "100 words") {
|
||||||
|
t.Fatalf("%s obsolete structure", lang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package aiprompts
|
|||||||
import (
|
import (
|
||||||
_ "embed"
|
_ "embed"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"unicode"
|
"unicode"
|
||||||
@@ -18,6 +19,18 @@ import (
|
|||||||
// defaults/default-category-prompts.json is generated from the A1 seed by
|
// defaults/default-category-prompts.json is generated from the A1 seed by
|
||||||
// scripts/seed/build-default-category-prompts.mjs and embedded so the defaults ship
|
// scripts/seed/build-default-category-prompts.mjs and embedded so the defaults ship
|
||||||
// with the binary. Categories outside that taxonomy fall back to
|
// with the binary. Categories outside that taxonomy fall back to
|
||||||
|
// PriorDefaultCategoryFormula identifies the immediately preceding built-in
|
||||||
|
// template, so rerunning the seed safely upgrades default-only categories.
|
||||||
|
func PriorDefaultCategoryFormula(uniqueID, name string) CategoryFormulaDefaults {
|
||||||
|
defaultFormulaOnce.Do(loadDefaultCategoryFormulas)
|
||||||
|
for _, key := range []string{uniqueID, name} {
|
||||||
|
if def, ok := priorFormulaByKey[NormalizeCategoryKey(key)]; ok {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return priorFormulaGeneric
|
||||||
|
}
|
||||||
|
|
||||||
// GenericCategoryFormula, which carries the same structure without category-specific
|
// GenericCategoryFormula, which carries the same structure without category-specific
|
||||||
// naming slots.
|
// naming slots.
|
||||||
|
|
||||||
@@ -27,7 +40,43 @@ var defaultCategoryPromptsJSON []byte
|
|||||||
// GenericDefaultCategoryPrompt is the English formula applied to any category the
|
// GenericDefaultCategoryPrompt is the English formula applied to any category the
|
||||||
// seed does not name. Same shape as the A1 template: naming formula, meta rule, two
|
// seed does not name. Same shape as the A1 template: naming formula, meta rule, two
|
||||||
// heading/paragraph pairs, technical specifications list.
|
// heading/paragraph pairs, technical specifications list.
|
||||||
const GenericDefaultCategoryPrompt = `Create a new product description in {{language}} using the following variables:
|
// GenericDefaultCategoryPrompt is the A1-inspired standard platform template.
|
||||||
|
// Each paragraph focuses on a distinct benefit; no duplicated headings/pairs.
|
||||||
|
// GenericDefaultCategoryPrompt is the canonical English reference used for the
|
||||||
|
// shared default hash and for generic fallback categories. Prompt sections for
|
||||||
|
// other languages come from the same offline 25-language JSON as the UI.
|
||||||
|
const GenericDefaultCategoryPrompt = `Create an accurate product listing in {{language}} from {{name}}, {{description}}, {{attrs}} and {{category}}. Use only supported facts.
|
||||||
|
Product template:
|
||||||
|
<name>{Brand with correct capitalization, product type in lowercase, complete model and uppercase model ID, then color as one word if known. No commas. Use only facts from {{name}}, {{description}} and {{attrs}}; keep official model codes, omit missing details and never invent features. Product name must be plain text, not HTML.}</name>
|
||||||
|
<metaDescription>{meta_title: Create a distinct, concise SEO page title based on the product name and one useful differentiator if known. Avoid repetition and clickbait; aim for about 50–60 characters only when natural. Plain text, no HTML.
|
||||||
|
meta_description: Summarize what the product is and one or two verified characteristics in natural language. Include the exact model when relevant. Aim for 120–155 characters when facts allow, otherwise shorter; max 155 characters including spaces. No HTML, claims, keyword stuffing or cut-off words.}</metaDescription>
|
||||||
|
<p>{Introduce {{name}} in one useful paragraph. Explain its product type and purpose using {{description}} and {{attrs}}. Keep it concise (roughly 30–60 words if facts permit); do not repeat the title word for word or invent claims.}</p>
|
||||||
|
<h2>{Write a short, specific H2 about the most useful documented feature or application, not a generic sales slogan. Do not repeat the product title. If no feature or use is supported beyond the product identity, omit this heading and the following feature paragraph.}</h2>
|
||||||
|
<p>{Explain that feature using actual source details and how it matters in practice. Use a natural, non-repetitive paragraph of around 50–90 words only if the evidence supports it; be shorter when information is sparse. Do not add unverifiable benefits.}</p>
|
||||||
|
<h2>{Write the localized heading “Technical specifications” only when at least one factual specification is available.}</h2>
|
||||||
|
<ul><li>{List only confirmed specifications as separate list items, ideally “Property: value”. Keep original model codes, measurements and units. If there are no specifications, omit this H2 and the whole list; never output empty list item elements.}</li></ul>`
|
||||||
|
|
||||||
|
// PriorGenericDefaultCategoryPrompt is the exact shipped pre-SEO-v4 platform
|
||||||
|
// formula. It is used ONLY to migrate proven untouched platform copies.
|
||||||
|
const PriorGenericDefaultCategoryPrompt = `Create an accurate product listing in {{language}} from {{name}}, {{description}}, {{attrs}} and {{category}}. Use only supported facts.
|
||||||
|
Product template:
|
||||||
|
<name>{Write the new product name in this order: brand correctly capitalized, product type in lowercase, complete model with official capitalization and uppercase model ID, and color as one word if known. Do not use commas. Omit unavailable parts.}</name>
|
||||||
|
<metaDescription>{Start with the new product name and continue to a maximum of 140 characters including spaces. Be natural, factual and do not cut words in half.}</metaDescription>
|
||||||
|
<H2>{Write the new product name without the color and highlight the first verified benefit.}</H2>
|
||||||
|
<p>{Write approximately 100 words about the first benefit WITHOUT repeating the complete new product name. Avoid unsupported claims.}</p>
|
||||||
|
<H2>{Highlight a different second verified benefit WITHOUT using the new product name.}</H2>
|
||||||
|
<p>{Write approximately 100 words about the second benefit and INCLUDE the new product name naturally once.}</p>
|
||||||
|
<H2>{Highlight a different third verified benefit, without the new product name.}</H2>
|
||||||
|
<p>{Write approximately 100 words about the third benefit WITHOUT repeating the complete new product name.}</p>
|
||||||
|
<H2>{Highlight a different fourth verified benefit, without the new product name.}</H2>
|
||||||
|
<p>{Write approximately 100 words about the fourth benefit and INCLUDE the new product name naturally once.}</p>
|
||||||
|
<H2>{Highlight a different fifth verified benefit, without the new product name.}</H2>
|
||||||
|
<p>{Write approximately 100 words about the fifth benefit WITHOUT repeating the complete new product name.}</p>
|
||||||
|
<b>{Technical specifications}</b><ul><li>{List 3–10 sourced technical specifications as bullet points. If fewer than 3 are verified, list only those available. Never invent specifications.}</li></ul>`
|
||||||
|
|
||||||
|
// Previous generic default, kept only to safely identify untouched old values
|
||||||
|
// when migrating existing companies to the new platform default.
|
||||||
|
const LegacyGenericDefaultCategoryPrompt = `Create a new product description in {{language}} using the following variables:
|
||||||
|
|
||||||
Old_product_description: {"PRODUCT DESCRIPTION"};
|
Old_product_description: {"PRODUCT DESCRIPTION"};
|
||||||
Old_product_name: {"OLD PRODUCT NAME"};
|
Old_product_name: {"OLD PRODUCT NAME"};
|
||||||
@@ -85,13 +134,31 @@ type defaultCategoryPromptsFile struct {
|
|||||||
var (
|
var (
|
||||||
defaultFormulaOnce sync.Once
|
defaultFormulaOnce sync.Once
|
||||||
defaultFormulaByKey map[string]CategoryFormulaDefaults
|
defaultFormulaByKey map[string]CategoryFormulaDefaults
|
||||||
|
legacyFormulaByKey map[string]CategoryFormulaDefaults
|
||||||
|
priorFormulaByKey map[string]CategoryFormulaDefaults
|
||||||
|
seoV4FormulaByKey map[string]CategoryFormulaDefaults
|
||||||
|
legacyFormulaGeneric CategoryFormulaDefaults
|
||||||
|
priorFormulaGeneric CategoryFormulaDefaults
|
||||||
|
seoV4FormulaGeneric CategoryFormulaDefaults
|
||||||
defaultFormulaGeneric CategoryFormulaDefaults
|
defaultFormulaGeneric CategoryFormulaDefaults
|
||||||
defaultFormulaCount int
|
defaultFormulaCount int
|
||||||
)
|
)
|
||||||
|
|
||||||
func loadDefaultCategoryFormulas() {
|
func loadDefaultCategoryFormulas() {
|
||||||
defaultFormulaGeneric = buildCategoryFormulaDefaults("", GenericDefaultCategoryPrompt)
|
// Every platform category now shares EXACTLY the same structural formula.
|
||||||
|
// Localization changes language only, never the number or order of blocks.
|
||||||
|
canonical, err := OfflineDefaultPrompt("en")
|
||||||
|
if err != nil {
|
||||||
|
panic("invalid bundled English default: " + err.Error())
|
||||||
|
}
|
||||||
|
defaultFormulaGeneric = buildCanonicalCategoryFormulaDefaults("", canonical)
|
||||||
|
seoV4FormulaGeneric = withPreviouslyShippedMetaTitle(buildCategoryFormulaDefaults("", GenericDefaultCategoryPrompt))
|
||||||
|
legacyFormulaGeneric = buildCategoryFormulaDefaults("", LegacyGenericDefaultCategoryPrompt)
|
||||||
|
priorFormulaGeneric = buildCategoryFormulaDefaults("", PriorGenericDefaultCategoryPrompt)
|
||||||
defaultFormulaByKey = map[string]CategoryFormulaDefaults{}
|
defaultFormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||||
|
legacyFormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||||
|
priorFormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||||
|
seoV4FormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||||
|
|
||||||
var f defaultCategoryPromptsFile
|
var f defaultCategoryPromptsFile
|
||||||
if err := json.Unmarshal(defaultCategoryPromptsJSON, &f); err != nil {
|
if err := json.Unmarshal(defaultCategoryPromptsJSON, &f); err != nil {
|
||||||
@@ -104,7 +171,29 @@ func loadDefaultCategoryFormulas() {
|
|||||||
if prompt == "" {
|
if prompt == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
res := buildCategoryFormulaDefaults(strings.TrimSpace(e.Name), prompt)
|
legacy := buildCategoryFormulaDefaults(strings.TrimSpace(e.Name), prompt)
|
||||||
|
// Retain category-specific naming instructions but standardize the
|
||||||
|
// description and meta structure across the platform defaults.
|
||||||
|
parts := ParseLegacyCombinedEnhancePrompt(prompt)
|
||||||
|
base := ParseLegacyCombinedEnhancePrompt(GenericDefaultCategoryPrompt)
|
||||||
|
seoV4Parts := parts
|
||||||
|
seoV4Parts.DescriptionRules = base.DescriptionRules
|
||||||
|
seoV4Parts.MetaRules = base.MetaRules
|
||||||
|
if seoV4Parts.TitleRules == "" {
|
||||||
|
seoV4Parts.TitleRules = base.TitleRules
|
||||||
|
}
|
||||||
|
seoV4 := withPreviouslyShippedMetaTitle(buildCategoryFormulaDefaultsFromParts(strings.TrimSpace(e.Name), seoV4Parts))
|
||||||
|
priorBase := ParseLegacyCombinedEnhancePrompt(PriorGenericDefaultCategoryPrompt)
|
||||||
|
priorParts := parts
|
||||||
|
priorParts.DescriptionRules = priorBase.DescriptionRules
|
||||||
|
priorParts.MetaRules = priorBase.MetaRules
|
||||||
|
priorFormula := buildCategoryFormulaDefaultsFromParts(strings.TrimSpace(e.Name), priorParts)
|
||||||
|
parts.DescriptionRules = base.DescriptionRules
|
||||||
|
parts.MetaRules = base.MetaRules
|
||||||
|
if parts.TitleRules == "" {
|
||||||
|
parts.TitleRules = base.TitleRules
|
||||||
|
}
|
||||||
|
res := buildCanonicalCategoryFormulaDefaults(strings.TrimSpace(e.Name), canonical)
|
||||||
if res.Overlay == "" {
|
if res.Overlay == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -112,16 +201,98 @@ func loadDefaultCategoryFormulas() {
|
|||||||
for _, key := range append([]string{e.Name, e.UniqueID}, e.Aliases...) {
|
for _, key := range append([]string{e.Name, e.UniqueID}, e.Aliases...) {
|
||||||
if k := NormalizeCategoryKey(key); k != "" {
|
if k := NormalizeCategoryKey(key); k != "" {
|
||||||
defaultFormulaByKey[k] = res
|
defaultFormulaByKey[k] = res
|
||||||
|
legacyFormulaByKey[k] = legacy
|
||||||
|
priorFormulaByKey[k] = priorFormula
|
||||||
|
seoV4FormulaByKey[k] = seoV4
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// buildCanonicalCategoryFormulaDefaults derives the JSON validation and title
|
||||||
|
// elements from the SAME localized prompt used by the API/UI. Never derive the
|
||||||
|
// default English shape from legacy taxonomy-specific prompts.
|
||||||
|
func buildCanonicalCategoryFormulaDefaults(name, prompt string) CategoryFormulaDefaults {
|
||||||
|
title := ExtractEnhanceSectionBody(prompt, SectionTitleStart, SectionTitleEnd)
|
||||||
|
description := ExtractEnhanceSectionBody(prompt, SectionDescriptionStart, SectionDescriptionEnd)
|
||||||
|
meta := ExtractEnhanceSectionBody(prompt, SectionMetaStart, SectionMetaEnd)
|
||||||
|
if title == "" || description == "" || meta == "" {
|
||||||
|
panic("incomplete canonical SEO prompt")
|
||||||
|
}
|
||||||
|
parts := LegacyEnhanceParts{TitleRules: title, DescriptionRules: description, MetaRules: meta, WasLegacy: true}
|
||||||
|
result := buildCategoryFormulaDefaultsFromParts(name, parts)
|
||||||
|
// Generic legacy parsing falls back to type-before-brand and omits color.
|
||||||
|
// The canonical title must use the exact brand → type → model → optional
|
||||||
|
// color order stated in all 25 human-readable instructions.
|
||||||
|
titleFormula := TitleFormula{Separator: " ", Elements: []TitleFormulaElement{
|
||||||
|
{ID: "0-variable-brand", Type: "variable", Label: "Brand", Value: "brand", Description: "Official brand spelling", Example: "GROHE"},
|
||||||
|
{ID: "1-variable-product_type", Type: "variable", Label: "Product type", Value: "product_type", Description: "Specific product type in the target language", Example: "basin mixer"},
|
||||||
|
{ID: "2-variable-product_model", Type: "variable", Label: "Model", Value: "product_model", Description: "Official model and part number", Example: "Essence 24058GN1"},
|
||||||
|
{ID: "3-variable-barva", Type: "variable", Label: "Color (optional)", Value: "barva", Description: "Only when a verified color is supplied"},
|
||||||
|
}}
|
||||||
|
if encoded, err := json.Marshal(titleFormula); err == nil {
|
||||||
|
result.TitleTemplateJSON = string(encoded)
|
||||||
|
}
|
||||||
|
result.Overlay = prompt
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// PreviousCanonicalV6CategoryFormula recognizes the exact default shipped in
|
||||||
|
// v6, before the Meta field was split into two independently braced prompts.
|
||||||
|
// This is migration-only; it is never used for new categories.
|
||||||
|
func PreviousCanonicalV6CategoryFormula(uniqueID, name string) CategoryFormulaDefaults {
|
||||||
|
old, err := PreviousOfflineDefaultPromptV6("en")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
result := buildCanonicalCategoryFormulaDefaults(name, old)
|
||||||
|
current := DefaultCategoryFormula(uniqueID, name)
|
||||||
|
result.MatchedName = current.MatchedName
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// SEO-v4 historically overwrote explicit English meta-title instructions with
|
||||||
|
// a legacy title length rule. Match the stored bytes for exact migrations only;
|
||||||
|
// new canonical defaults retain their actual localized meta instructions.
|
||||||
|
func withPreviouslyShippedMetaTitle(def CategoryFormulaDefaults) CategoryFormulaDefaults {
|
||||||
|
if strings.TrimSpace(def.DescriptionTemplateJSON) == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
var f DescriptionFormula
|
||||||
|
if json.Unmarshal([]byte(def.DescriptionTemplateJSON), &f) != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(f.MetaTitle) != "" {
|
||||||
|
f.MetaTitle = DefaultMetaTitleRuleEN
|
||||||
|
if data, err := json.Marshal(f); err == nil {
|
||||||
|
def.DescriptionTemplateJSON = string(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
// PreviousSEODefaultCategoryFormula matches the built-in SEO-v4 formula, which
|
||||||
|
// differed by category in English and by language for non-English locales.
|
||||||
|
// It is only used for safe migrations of exact old platform defaults.
|
||||||
|
func PreviousSEODefaultCategoryFormula(uniqueID, name string) CategoryFormulaDefaults {
|
||||||
|
defaultFormulaOnce.Do(loadDefaultCategoryFormulas)
|
||||||
|
for _, key := range []string{uniqueID, name} {
|
||||||
|
if def, ok := seoV4FormulaByKey[NormalizeCategoryKey(key)]; ok {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return seoV4FormulaGeneric
|
||||||
|
}
|
||||||
|
|
||||||
func buildCategoryFormulaDefaults(name, legacyPrompt string) CategoryFormulaDefaults {
|
func buildCategoryFormulaDefaults(name, legacyPrompt string) CategoryFormulaDefaults {
|
||||||
parts := ParseLegacyCombinedEnhancePrompt(legacyPrompt)
|
parts := ParseLegacyCombinedEnhancePrompt(legacyPrompt)
|
||||||
if !parts.WasLegacy {
|
if !parts.WasLegacy {
|
||||||
return CategoryFormulaDefaults{}
|
return CategoryFormulaDefaults{}
|
||||||
}
|
}
|
||||||
|
return buildCategoryFormulaDefaultsFromParts(name, parts)
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildCategoryFormulaDefaultsFromParts(name string, parts LegacyEnhanceParts) CategoryFormulaDefaults {
|
||||||
out := CategoryFormulaDefaults{
|
out := CategoryFormulaDefaults{
|
||||||
MatchedName: name,
|
MatchedName: name,
|
||||||
Overlay: BuildCategoryEnhanceOverlay(parts),
|
Overlay: BuildCategoryEnhanceOverlay(parts),
|
||||||
@@ -129,7 +300,7 @@ func buildCategoryFormulaDefaults(name, legacyPrompt string) CategoryFormulaDefa
|
|||||||
desc := DeriveDescriptionFormulaFromLegacyParts(parts)
|
desc := DeriveDescriptionFormulaFromLegacyParts(parts)
|
||||||
// The derivation seeds a Slovenian meta-title rule for legacy A1 dumps; these
|
// The derivation seeds a Slovenian meta-title rule for legacy A1 dumps; these
|
||||||
// formulas are the English set, so the whole formula must read in English.
|
// formulas are the English set, so the whole formula must read in English.
|
||||||
if strings.TrimSpace(desc.MetaTitle) != "" {
|
if strings.TrimSpace(desc.MetaTitle) == DefaultLegacyMetaTitleRule {
|
||||||
desc.MetaTitle = DefaultMetaTitleRuleEN
|
desc.MetaTitle = DefaultMetaTitleRuleEN
|
||||||
}
|
}
|
||||||
if len(desc.Sections) > 0 || desc.MetaTitle != "" || desc.MetaDescription != "" {
|
if len(desc.Sections) > 0 || desc.MetaTitle != "" || desc.MetaDescription != "" {
|
||||||
@@ -161,6 +332,19 @@ func DefaultCategoryFormula(uniqueID, name string) CategoryFormulaDefaults {
|
|||||||
return defaultFormulaGeneric
|
return defaultFormulaGeneric
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LegacyDefaultCategoryFormula is used exclusively by the migration seed to
|
||||||
|
// recognize previously generated platform defaults. It MUST NOT be used for
|
||||||
|
// creating new category instructions.
|
||||||
|
func LegacyDefaultCategoryFormula(uniqueID, name string) CategoryFormulaDefaults {
|
||||||
|
defaultFormulaOnce.Do(loadDefaultCategoryFormulas)
|
||||||
|
for _, key := range []string{uniqueID, name} {
|
||||||
|
if def, ok := legacyFormulaByKey[NormalizeCategoryKey(key)]; ok {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return legacyFormulaGeneric
|
||||||
|
}
|
||||||
|
|
||||||
// GenericCategoryFormula is DefaultCategoryFormula's fallback on its own — used
|
// GenericCategoryFormula is DefaultCategoryFormula's fallback on its own — used
|
||||||
// when only the shape matters and the category is unknown.
|
// when only the shape matters and the category is unknown.
|
||||||
func GenericCategoryFormula() CategoryFormulaDefaults {
|
func GenericCategoryFormula() CategoryFormulaDefaults {
|
||||||
@@ -208,3 +392,24 @@ func NormalizeCategoryKey(s string) string {
|
|||||||
}
|
}
|
||||||
return strings.TrimSpace(b.String())
|
return strings.TrimSpace(b.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AllDefaultCategoryPrompts returns every bundled English default enhance overlay,
|
||||||
|
// including the generic fallback. Seed these once globally so future categories
|
||||||
|
// never require an AI request during creation.
|
||||||
|
func AllDefaultCategoryPrompts() []string {
|
||||||
|
defaultFormulaOnce.Do(loadDefaultCategoryFormulas)
|
||||||
|
unique := map[string]bool{defaultFormulaGeneric.Overlay: true}
|
||||||
|
for _, def := range defaultFormulaByKey {
|
||||||
|
if def.Overlay != "" {
|
||||||
|
unique[def.Overlay] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := make([]string, 0, len(unique))
|
||||||
|
for source := range unique {
|
||||||
|
if source != "" {
|
||||||
|
out = append(out, source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -36,7 +36,7 @@ func TestDefaultCategoryFormula_matchesA1Shape(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Mirrors the Slovenian Stolčki formula: znamka, tip izdelka, poln model.
|
// Mirrors the Slovenian Stolčki formula: znamka, tip izdelka, poln model.
|
||||||
want := []string{"brand", "product_type", "product_model"}
|
want := []string{"brand", "product_type", "product_model", "barva"}
|
||||||
if strings.Join(vars, ",") != strings.Join(want, ",") {
|
if strings.Join(vars, ",") != strings.Join(want, ",") {
|
||||||
t.Fatalf("title slots = %v want %v", vars, want)
|
t.Fatalf("title slots = %v want %v", vars, want)
|
||||||
}
|
}
|
||||||
@@ -49,8 +49,11 @@ func TestDefaultCategoryFormula_matchesA1Shape(t *testing.T) {
|
|||||||
for _, s := range f.Sections {
|
for _, s := range f.Sections {
|
||||||
types = append(types, s.Type)
|
types = append(types, s.Type)
|
||||||
}
|
}
|
||||||
if strings.Join(types, ",") != "h2,p,h2,p,ul" {
|
if strings.Join(types, ",") != "p,h2,p,h2,ul" {
|
||||||
t.Fatalf("description sections = %v want h2,p,h2,p,ul", types)
|
t.Fatalf("description sections = %v want p,h2,p,h2,ul", types)
|
||||||
|
}
|
||||||
|
if len(f.Sections) == 5 && (!f.Sections[3].Optional || !f.Sections[4].Optional) {
|
||||||
|
t.Fatal("technical-specification section should be optional when no verified data exists")
|
||||||
}
|
}
|
||||||
if f.MetaTitle == "" || f.MetaDescription == "" {
|
if f.MetaTitle == "" || f.MetaDescription == "" {
|
||||||
t.Fatalf("meta rules missing: %+v", f)
|
t.Fatalf("meta rules missing: %+v", f)
|
||||||
@@ -129,7 +132,7 @@ func TestSplitLegacyCombinedEnhancePrompt_handlesBothScaffoldings(t *testing.T)
|
|||||||
t.Fatal("English default must parse as a combined formula prompt")
|
t.Fatal("English default must parse as a combined formula prompt")
|
||||||
}
|
}
|
||||||
overlay := SplitLegacyCombinedEnhancePrompt(en)
|
overlay := SplitLegacyCombinedEnhancePrompt(en)
|
||||||
if !strings.Contains(overlay, SectionTitleStart) || !strings.Contains(overlay, "<H2>") {
|
if !strings.Contains(overlay, SectionTitleStart) || !strings.Contains(overlay, "<h2>") {
|
||||||
t.Fatalf("English split lost its sections:\n%s", overlay)
|
t.Fatalf("English split lost its sections:\n%s", overlay)
|
||||||
}
|
}
|
||||||
// Scaffolding lines must not leak into the Description role.
|
// Scaffolding lines must not leak into the Description role.
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
{
|
||||||
|
"en": {
|
||||||
|
"title": "{Brand with correct capitalization, product type in lowercase, complete model and uppercase model ID, then color as one word if known. No commas. Use only facts from {{name}}, {{description}} and {{attrs}}; keep official model codes, omit missing details and never invent features. Product name must be plain text, not HTML.}",
|
||||||
|
"description": "<p>{Introduce {{name}} in one useful paragraph. Explain its product type and purpose using {{description}} and {{attrs}}. Keep it concise (roughly 30–60 words if facts permit); do not repeat the title word for word or invent claims.}</p>\n<h2>{Write a short, specific H2 about the most useful documented feature or application, not a generic sales slogan. Do not repeat the product title. If no feature or use is supported beyond the product identity, omit this heading and the following feature paragraph.}</h2>\n<p>{Explain that feature using actual source details and how it matters in practice. Use a natural, non-repetitive paragraph of around 50–90 words only if the evidence supports it; be shorter when information is sparse. Do not add unverifiable benefits.}</p>\n<h2>{Write the localized heading “Technical specifications” only when at least one factual specification is available.}</h2>\n<ul><li>{List only confirmed specifications as separate list items, ideally “Property: value”. Keep original model codes, measurements and units. If there are no specifications, omit this H2 and the whole list; never output empty list item elements.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Create a distinct, concise SEO page title based on the product name and one useful differentiator if known. Avoid repetition and clickbait; aim for about 50–60 characters only when natural. Plain text, no HTML.}\n{meta_description: Summarize what the product is and one or two verified characteristics in natural language. Include the exact model when relevant. Aim for 120–155 characters when facts allow, otherwise shorter; max 155 characters including spaces. No HTML, claims, keyword stuffing or cut-off words.}"
|
||||||
|
},
|
||||||
|
"fr": {
|
||||||
|
"title": "{Rédigez un titre de produit clair pour {{name}} à partir des {{attrs}} vérifiés. Marque avec la casse correcte, type de produit en minuscules, modèle complet et référence en majuscules, puis couleur en un seul mot si elle est connue. Sans virgules.}",
|
||||||
|
"description": "<p>{Présentez {{name}} en un court paragraphe : type de produit et usage, d’après {{description}} et {{attrs}}. Environ 30 à 60 mots si les données le permettent, sans recopier le titre ni inventer de faits.}</p>\n<h2>{Rédigez un H2 précis sur la caractéristique ou l’usage le mieux documenté, sans slogan vague ni répétition du nom complet. Si aucune caractéristique ou utilisation n’est démontrée, omettez ce H2 et le paragraphe suivant.}</h2>\n<p>{Expliquez cette caractéristique et son intérêt concret en 50 à 90 mots seulement si les données sont suffisantes. Sinon, soyez plus bref ; évitez les répétitions et les avantages non prouvés.}</p>\n<h2>{Rédigez le titre « Caractéristiques techniques » seulement si des données techniques sont disponibles.}</h2>\n<ul><li>{Listez uniquement les caractéristiques vérifiées, une par élément de liste, sous la forme « Propriété : valeur » si possible. Conservez les unités et références. Si aucune n’est disponible, omettez le H2 et toute la liste.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Rédigez un titre SEO distinct et concis avec le nom du produit et une caractéristique utile si elle est établie. Visez 50 à 60 caractères sans forcer. Texte brut, sans HTML.}\n{meta_description: Résumez le produit et une ou deux caractéristiques confirmées. Visez 120 à 155 caractères si les faits le permettent, sinon soyez plus bref ; 155 caractères maximum, espaces compris. Sans HTML ni mots-clés répétés.}"
|
||||||
|
},
|
||||||
|
"de": {
|
||||||
|
"title": "{Verfasse einen klaren Produkttitel für {{name}} anhand geprüfter {{attrs}}. Marke korrekt schreiben, Produkttyp nach deutscher Rechtschreibung, vollständiges Modell mit Modellkennung in Großbuchstaben, danach die Farbe als ein Wort, falls bekannt. Keine Kommas.}",
|
||||||
|
"description": "<p>{Stelle {{name}} in einem kurzen Absatz mit Produkttyp und Verwendungszweck anhand von {{description}} und {{attrs}} vor. Etwa 30–60 Wörter nur bei ausreichenden Fakten; keine erfundenen Behauptungen und keine Titelwiederholung.}</p>\n<h2>{Formuliere eine konkrete H2 über die wichtigste belegte Eigenschaft oder Anwendung, ohne Werbefloskel oder vollständigen Produktnamen. Wenn kein Merkmal oder Einsatz belegt ist, diese H2 und den folgenden Absatz weglassen.}</h2>\n<p>{Erkläre diese Eigenschaft und ihren praktischen Nutzen anhand belegter Angaben. Etwa 50–90 Wörter nur wenn genug Informationen vorliegen; sonst kürzer und ohne Wiederholungen.}</p>\n<h2>{Schreibe die Überschrift „Technische Daten“ nur wenn technische Angaben vorhanden sind.}</h2>\n<ul><li>{Führe ausschließlich bestätigte Daten einzeln als Listeneintrag auf, möglichst „Merkmal: Wert“. Einheiten und Modellcodes unverändert lassen. Ohne Daten die Überschrift und Liste vollständig weglassen.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Erstelle einen eindeutigen, knappen SEO-Titel mit Produktname und belegtem Unterscheidungsmerkmal. Etwa 50–60 Zeichen, sofern sinnvoll; ohne HTML.}\n{meta_description: Fasse Produkttyp und ein bis zwei bestätigte Eigenschaften natürlich zusammen. Wenn möglich 120–155 Zeichen, sonst kürzer; maximal 155 einschließlich Leerzeichen. Kein HTML, keine Wiederholungen oder unbelegten Aussagen.}"
|
||||||
|
},
|
||||||
|
"es": {
|
||||||
|
"title": "{Redacta un título de producto claro para {{name}} utilizando {{attrs}} verificados. Marca con mayúsculas correctas, tipo de producto en minúsculas, modelo completo e identificador del modelo en mayúsculas y color en una sola palabra si se conoce. Sin comas.}",
|
||||||
|
"description": "<p>{Presenta {{name}} en un párrafo breve indicando el tipo de producto y su uso, basándote en {{description}} y {{attrs}}. Unas 30–60 palabras solo si hay datos suficientes; sin repetir el título ni inventar información.}</p>\n<h2>{Escribe un H2 concreto sobre la característica o aplicación mejor documentada, sin eslóganes genéricos ni repetir el nombre completo. Si no hay una característica o uso confirmado, omite este H2 y el párrafo siguiente.}</h2>\n<p>{Explica esa característica y su utilidad práctica con hechos verificados. Usa unas 50–90 palabras si hay suficiente información, o menos si faltan datos; evita repeticiones.}</p>\n<h2>{Escribe el encabezado « Especificaciones técnicas » solo si existen especificaciones verificadas.}</h2>\n<ul><li>{Incluye solo datos confirmados, cada uno en un elemento de lista, preferiblemente « Característica: valor ». Conserva unidades y referencias; si no hay datos, omite el H2 y la lista completos.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Crea un título SEO conciso y específico con el nombre del producto y una característica demostrable. Unas 50–60 letras si resulta natural; sin HTML.}\n{meta_description: Resume qué es el producto y una o dos características verificadas. Apunta a 120–155 caracteres si hay datos; máximo 155 con espacios. Sin HTML, repeticiones ni afirmaciones inventadas.}"
|
||||||
|
},
|
||||||
|
"it": {
|
||||||
|
"title": "{Scrivi un titolo di prodotto chiaro per {{name}} usando {{attrs}} verificati. Marchio con maiuscole corrette, tipo di prodotto in minuscolo, modello completo e codice modello in maiuscolo, poi colore in una parola se noto. Senza virgole.}",
|
||||||
|
"description": "<p>{Introduci {{name}} con un paragrafo breve sul tipo di prodotto e il suo utilizzo, usando {{description}} e {{attrs}}. Circa 30–60 parole solo se supportate dai dati, senza ripetere il titolo né inventare informazioni.}</p>\n<h2>{Scrivi un H2 specifico sulla caratteristica o sull’impiego meglio documentato, evitando slogan generici e il nome completo. Se nessuna caratteristica o uso è documentato, ometti questo H2 e il paragrafo seguente.}</h2>\n<p>{Spiega la caratteristica e il suo vantaggio pratico con fatti verificati. Circa 50–90 parole solo se ci sono informazioni sufficienti; altrimenti resta conciso e non ripeterti.}</p>\n<h2>{Scrivi « Specifiche tecniche » soltanto se sono presenti caratteristiche tecniche verificate.}</h2>\n<ul><li>{Elenca soltanto dati accertati, uno per elemento della lista, preferibilmente « Caratteristica: valore ». Mantieni unità e codici; in assenza di dati ometti sia H2 sia elenco.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Crea un titolo SEO chiaro e specifico con nome del prodotto e una caratteristica comprovata. Circa 50–60 caratteri se naturale; niente HTML.}\n{meta_description: Riassumi prodotto e una o due caratteristiche verificate. Circa 120–155 caratteri se i dati lo consentono, massimo 155 spazi inclusi. Niente HTML o parole chiave ripetute.}"
|
||||||
|
},
|
||||||
|
"nl": {
|
||||||
|
"title": "{Schrijf een duidelijke producttitel voor {{name}} op basis van gecontroleerde {{attrs}}. Merk met juiste hoofdletters, producttype in kleine letters, volledig model met modelcode in hoofdletters, daarna kleur als één woord indien bekend. Geen komma’s.}",
|
||||||
|
"description": "<p>{Introduceer {{name}} in een korte alinea met producttype en toepassing op basis van {{description}} en {{attrs}}. Ongeveer 30–60 woorden als de feiten dat toelaten; herhaal de titel niet en verzin niets.}</p>\n<h2>{Schrijf een specifieke H2 over de best onderbouwde eigenschap of toepassing; geen algemene reclametaal of herhaling van de hele productnaam. Als er geen bevestigde eigenschap of toepassing is, laat deze H2 en de volgende alinea weg.}</h2>\n<p>{Leg de eigenschap en het praktische nut uit met geverifieerde gegevens. Gebruik circa 50–90 woorden alleen bij voldoende informatie; anders korter en zonder herhaling.}</p>\n<h2>{Gebruik de kop ‘Technische specificaties’ alleen wanneer er bevestigde specificaties zijn.}</h2>\n<ul><li>{Zet alleen geverifieerde gegevens elk in een afzonderlijke lijstitem, liefst ‘Kenmerk: waarde’. Behoud eenheden en modelcodes. Zonder gegevens de kop én lijst weglaten.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Maak een unieke, beknopte SEO-titel met de productnaam en een bewezen onderscheidend kenmerk. Streef waar passend naar 50–60 tekens; geen HTML.}\n{meta_description: Vat het product en een of twee bewezen kenmerken samen. Streef naar 120–155 tekens als er genoeg gegevens zijn; maximaal 155 inclusief spaties. Geen HTML of zoekwoordherhaling.}"
|
||||||
|
},
|
||||||
|
"pt": {
|
||||||
|
"title": "{Escreve um título de produto claro para {{name}} com base em {{attrs}} verificados. Marca com capitalização correta, tipo de produto em minúsculas, modelo completo e código do modelo em maiúsculas e cor numa única palavra, se conhecida. Sem vírgulas.}",
|
||||||
|
"description": "<p>{Apresenta {{name}} num parágrafo breve com o tipo de produto e a finalidade, com base em {{description}} e {{attrs}}. Cerca de 30–60 palavras se houver dados suficientes; não repitas o título nem inventes factos.}</p>\n<h2>{Escreve um H2 específico sobre a característica ou aplicação mais bem documentada, sem slogans vagos nem repetir o nome completo. Se não houver característica ou uso comprovado, omite este H2 e o parágrafo seguinte.}</h2>\n<p>{Explica a característica e a utilidade prática com dados confirmados. Usa 50–90 palavras apenas se houver informação suficiente; caso contrário, escreve menos e evita repetições.}</p>\n<h2>{Usa o título « Especificações técnicas » apenas se houver especificações confirmadas.}</h2>\n<ul><li>{Apresenta apenas características verificadas, uma por item da lista, idealmente « Atributo: valor ». Mantém unidades e códigos; sem dados, omite o H2 e a lista.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Cria um título SEO claro e distinto com o nome do produto e uma característica comprovada. Aponta a 50–60 caracteres se fizer sentido; sem HTML.}\n{meta_description: Resume o produto e uma ou duas características confirmadas. Idealmente 120–155 caracteres quando houver dados, no máximo 155 com espaços. Sem HTML ou repetição de palavras-chave.}"
|
||||||
|
},
|
||||||
|
"pl": {
|
||||||
|
"title": "{Napisz jasny tytuł produktu {{name}}, korzystając ze zweryfikowanych {{attrs}}. Marka z poprawną pisownią, typ produktu małymi literami, pełny model i jego kod wielkimi literami, a następnie kolor jednym słowem, jeśli jest znany. Bez przecinków.}",
|
||||||
|
"description": "<p>{Przedstaw {{name}} w krótkim akapicie: typ produktu i zastosowanie na podstawie {{description}} oraz {{attrs}}. Około 30–60 słów tylko przy wystarczających danych; nie powtarzaj tytułu i niczego nie wymyślaj.}</p>\n<h2>{Zapisz konkretny nagłówek H2 o najlepiej potwierdzonej cesze lub zastosowaniu, bez pustych sloganów i powtarzania pełnej nazwy. Jeśli żadna cecha ani zastosowanie nie są potwierdzone, pomiń ten H2 i następny akapit.}</h2>\n<p>{Wyjaśnij cechę i jej praktyczne znaczenie na podstawie potwierdzonych faktów. Około 50–90 słów, gdy dane na to pozwalają; w przeciwnym razie krócej i bez powtórzeń.}</p>\n<h2>{Użyj nagłówka „Dane techniczne” wyłącznie wtedy, gdy są potwierdzone parametry.}</h2>\n<ul><li>{Wymień tylko sprawdzone dane, po jednej pozycji listy, najlepiej „Parametr: wartość”. Zachowaj jednostki i symbole modeli. Bez danych pomiń nagłówek i listę.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Utwórz unikalny, krótki tytuł SEO z nazwą produktu i potwierdzoną cechą wyróżniającą. Około 50–60 znaków, jeśli naturalne; bez HTML.}\n{meta_description: Podsumuj produkt i jedną lub dwie sprawdzone cechy. Celuj w 120–155 znaków, gdy są dane; maksymalnie 155 ze spacjami. Bez HTML i upychania słów kluczowych.}"
|
||||||
|
},
|
||||||
|
"cs": {
|
||||||
|
"title": "{Napište výstižný název produktu {{name}} podle ověřených {{attrs}}. Značku napiš se správnými velkými písmeny, typ výrobku malými písmeny, celý model a jeho kód velkými písmeny a barvu jedním slovem, je-li známá. Bez čárek.}",
|
||||||
|
"description": "<p>{Představ {{name}} krátkým odstavcem s typem výrobku a použitím podle {{description}} a {{attrs}}. Asi 30–60 slov pouze při dostatku údajů; neopakuj celý název ani si nic nevymýšlej.}</p>\n<h2>{Napiš konkrétní nadpis H2 o nejlépe doložené vlastnosti či využití, bez obecného reklamního hesla a opakování názvu. Pokud není doložena žádná vlastnost ani použití, vynech tento H2 i následující odstavec.}</h2>\n<p>{Vysvětli vlastnost a její praktický význam jen na základě ověřených údajů. Přibližně 50–90 slov, pokud je dost informací; jinak kratší text bez opakování.}</p>\n<h2>{Nadpis „Technické parametry“ použij jen tehdy, pokud jsou potvrzené údaje.}</h2>\n<ul><li>{Vypiš pouze ověřené údaje samostatně do položky seznamu, nejlépe „Parametr: hodnota“. Zachovej jednotky a označení modelů. Pokud nejsou, vynech nadpis i seznam.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Vytvoř jedinečný stručný SEO titulek s názvem výrobku a doloženou vlastností. Přibližně 50–60 znaků, pokud to dává smysl; bez HTML.}\n{meta_description: Shrň výrobek a jednu či dvě ověřené vlastnosti. Ideálně 120–155 znaků, pokud jsou podklady; maximálně 155 včetně mezer. Bez HTML a opakování klíčových slov.}"
|
||||||
|
},
|
||||||
|
"sk": {
|
||||||
|
"title": "{Napíšte výstižný názov produktu {{name}} podľa overených {{attrs}}. Značku uveď so správnymi veľkými písmenami, typ výrobku malými písmenami, úplný model a jeho kód veľkými písmenami a farbu jedným slovom, ak je známa. Bez čiarok.}",
|
||||||
|
"description": "<p>{Predstav {{name}} krátkym odsekom s typom výrobku a použitím podľa {{description}} a {{attrs}}. Asi 30–60 slov len pri dostatku údajov; neopakuj celý názov a nič si nevymýšľaj.}</p>\n<h2>{Napíš konkrétny nadpis H2 o najlepšie doloženej vlastnosti alebo použití, bez všeobecných sloganov a opakovania názvu. Ak nie je potvrdená vlastnosť ani použitie, vynechaj tento H2 aj nasledujúci odsek.}</h2>\n<p>{Vysvetli vlastnosť a jej praktický význam na základe overených údajov. Približne 50–90 slov, ak je dosť informácií; inak kratšie, bez opakovania.}</p>\n<h2>{Nadpis „Technické parametre“ použi len vtedy, keď sú potvrdené údaje.}</h2>\n<ul><li>{Uveď iba overené údaje, každý v samostatnej položke zoznamu, najlepšie „Parameter: hodnota“. Zachovaj jednotky a kódy modelov. Bez údajov vynechaj nadpis aj zoznam.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Vytvor jedinečný stručný SEO titulok s názvom výrobku a potvrdenou vlastnosťou. Približne 50–60 znakov, ak je to prirodzené; bez HTML.}\n{meta_description: Zhrň výrobok a jednu či dve potvrdené vlastnosti. Ideálne 120–155 znakov, ak je dosť údajov; najviac 155 vrátane medzier. Bez HTML a opakovania kľúčových slov.}"
|
||||||
|
},
|
||||||
|
"hu": {
|
||||||
|
"title": "{Írj egyértelmű termékcímet a(z) {{name}} számára az ellenőrzött {{attrs}} alapján. A márkanevet helyes nagybetűzéssel, a terméktípust kisbetűkkel, a teljes modellt és modellszámot nagybetűs azonosítóval, a színt pedig egy szóban add meg, ha ismert. Vessző nélkül.}",
|
||||||
|
"description": "<p>{Mutasd be a(z) {{name}} terméket egy rövid bekezdésben: típusa és felhasználása a {{description}} és {{attrs}} alapján. Kb. 30–60 szó csak elegendő adat esetén; ne ismételd a címet, és ne találj ki tényeket.}</p>\n<h2>{Adj konkrét H2 címet a legjobban igazolt tulajdonságról vagy felhasználásról, általános reklámszöveg és teljes névismétlés nélkül. Ha nincs igazolt tulajdonság vagy alkalmazás, hagyd el ezt a H2 címet és a következő bekezdést.}</h2>\n<p>{Magyarázd el a tulajdonság gyakorlati jelentőségét igazolt adatokkal. Csak megfelelő információ esetén írj 50–90 szót; egyébként légy rövidebb, ismétlések nélkül.}</p>\n<h2>{A „Műszaki adatok” címet csak akkor írd ki, ha vannak igazolt adatok.}</h2>\n<ul><li>{Csak ellenőrzött adatokat sorolj fel külön listaelem elemekben, lehetőleg „Jellemző: érték” formában. Mértékegységeket és típuskódokat őrizd meg; adatok hiányában hagyd el a címet és a listát.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Készíts egyedi, rövid SEO-címet a terméknévvel és egy igazolt megkülönböztető jellemzővel. Kb. 50–60 karakter, ha természetes; HTML nélkül.}\n{meta_description: Foglald össze a terméket és egy-két ellenőrzött jellemzőjét. Ha lehet, 120–155 karakter; legfeljebb 155 szóközökkel együtt. HTML és kulcsszóhalmozás nélkül.}"
|
||||||
|
},
|
||||||
|
"ro": {
|
||||||
|
"title": "{Scrie un titlu clar pentru produsul {{name}}, folosind {{attrs}} verificate. Marca scrisă corect, tipul produsului cu litere mici, modelul complet și codul modelului cu majuscule, apoi culoarea într-un singur cuvânt, dacă este cunoscută. Fără virgule.}",
|
||||||
|
"description": "<p>{Prezintă {{name}} într-un paragraf scurt: tipul produsului și utilizarea sa, pe baza {{description}} și {{attrs}}. Aproximativ 30–60 de cuvinte dacă există date, fără a repeta titlul sau a inventa detalii.}</p>\n<h2>{Scrie un H2 concret despre caracteristica ori utilizarea cea mai bine documentată, fără sloganuri vagi sau repetarea numelui complet. Dacă nu există caracteristică sau utilizare confirmată, omite acest H2 și paragraful următor.}</h2>\n<p>{Explică acea caracteristică și utilitatea ei practică pe baza datelor confirmate. Circa 50–90 de cuvinte numai dacă există suficiente informații; altfel mai scurt, fără repetiții.}</p>\n<h2>{Folosește subtitlul „Specificații tehnice” numai când există date confirmate.}</h2>\n<ul><li>{Enumeră doar specificații verificate, fiecare într-un element de listă, ideal „Caracteristică: valoare”. Păstrează unitățile și codurile; în lipsa lor, omite subtitlul și lista.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Creează un titlu SEO unic și concis cu numele produsului și o caracteristică demonstrată. Circa 50–60 de caractere, dacă sună natural; fără HTML.}\n{meta_description: Rezumă produsul și una sau două caracteristici confirmate. 120–155 de caractere dacă datele permit, cel mult 155 cu spații. Fără HTML sau repetiții de cuvinte-cheie.}"
|
||||||
|
},
|
||||||
|
"bg": {
|
||||||
|
"title": "{Напиши ясно заглавие на продукта {{name}}, като използваш проверените {{attrs}}. Марката с правилни главни букви, видът на продукта с малки букви, пълният модел и кодът му с главни букви, а след това цветът с една дума, ако е известен. Без запетаи.}",
|
||||||
|
"description": "<p>{Представи {{name}} с кратък абзац за вида и предназначението въз основа на {{description}} и {{attrs}}. Около 30–60 думи само при достатъчно данни; без повторение на заглавието и измислени твърдения.}</p>\n<h2>{Напиши конкретно H2 заглавие за най-добре потвърдената характеристика или употреба, без общи рекламни фрази и пълното име. Ако няма потвърдена характеристика или употреба, пропусни това H2 и следващия абзац.}</h2>\n<p>{Обясни характеристиката и практическата ѝ полза с доказани данни. Около 50–90 думи само ако има информация; иначе по-кратко и без повтаряне.}</p>\n<h2>{Използвай заглавие „Технически характеристики“ само при потвърдени данни.}</h2>\n<ul><li>{Изброй само проверени данни поотделно в елемент от списъка, за предпочитане „Показател: стойност“. Запази мерните единици и кодовете; при липса на данни пропусни заглавието и списъка.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Създай кратко уникално SEO заглавие с името и проверена отличителна характеристика. Около 50–60 знака, ако е естествено; без HTML.}\n{meta_description: Обобщи продукта и една-две потвърдени характеристики. Около 120–155 знака при налични данни, максимум 155 с интервалите. Без HTML и повтаряне на ключови думи.}"
|
||||||
|
},
|
||||||
|
"hr": {
|
||||||
|
"title": "{Napiši jasan naziv proizvoda {{name}} koristeći provjerene {{attrs}}. Marku napiši s pravilnim velikim slovima, vrstu proizvoda malim slovima, puni model i oznaku modela velikim slovima, a zatim boju jednom riječju ako je poznata. Bez zareza.}",
|
||||||
|
"description": "<p>{Predstavi {{name}} u kratkom odlomku: vrstu proizvoda i namjenu prema {{description}} i {{attrs}}. Otprilike 30–60 riječi samo ako ima dovoljno podataka. Ne prepisuj puni naslov niti izmišljaj tvrdnje.}</p>\n<h2>{Napiši konkretan H2 naslov o najvažnijoj potvrđenoj značajci ili primjeni, bez općih marketinških fraza i ponavljanja cijelog naziva. Ako nema potvrđene značajke ili primjene, izostavi ovaj H2 naslov i sljedeći odlomak.}</h2>\n<p>{Objasni tu značajku i njezinu praktičnu korist na temelju potvrđenih podataka. Oko 50–90 riječi samo kad ima dovoljno činjenica, inače kraće; ne ponavljaj uvod.}</p>\n<h2>{Napiši naslov „Tehničke specifikacije” samo ako postoje potvrđeni tehnički podaci.}</h2>\n<ul><li>{Navedi isključivo provjerene podatke, svaki u zasebnoj stavci popisa, po mogućnosti „Svojstvo: vrijednost”. Sačuvaj mjerne jedinice i oznake modela. Ako podataka nema, izostavi i naslov i popis.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Napiši jedinstven, jasan SEO naslov s nazivom proizvoda i jednom potvrđenom razlikovnom značajkom. Ciljaj na 50–60 znakova samo ako zvuči prirodno; bez HTML-a.}\n{meta_description: Prirodno sažmi proizvod i jednu ili dvije potvrđene značajke. Ciljaj na 120–155 znakova ako je moguće, najviše 155 uključujući razmake. Bez HTML-a, izmišljanja ili gomilanja ključnih riječi.}"
|
||||||
|
},
|
||||||
|
"sl": {
|
||||||
|
"title": "{Napiši jasen naslov izdelka {{name}} na podlagi preverjenih {{attrs}}. Znamko zapiši s pravilnimi velikimi črkami, tip izdelka z malimi črkami, celoten model in oznako modela z velikimi črkami, nato barvo z eno besedo, če je znana. Brez vejic.}",
|
||||||
|
"description": "<p>{V kratkem uvodnem odstavku predstavi {{name}}: vrsto izdelka in namen uporabe na podlagi {{description}} ter {{attrs}}. Približno 30–60 besed, če podatki to omogočajo. Ne prepisuj celotnega naslova in ne dodajaj nepotrjenih trditev.}</p>\n<h2>{Napiši konkreten naslov H2 o najpomembnejši preverjeni lastnosti ali uporabi. Ne ponavljaj celotnega imena izdelka in ne uporabljaj splošnih oglaševalskih fraz. Če ni nobene potrjene lastnosti ali uporabe, izpusti ta naslov H2 in naslednji odstavek.}</h2>\n<p>{Razloži to lastnost in njen praktični pomen na podlagi preverjenih podatkov. Približno 50–90 besed samo, če je dovolj dejstev, sicer napiši krajši odstavek. Ne ponavljaj uvoda.}</p>\n<h2>{Naslov »Tehnične specifikacije« napiši le, če so na voljo preverjeni tehnični podatki.}</h2>\n<ul><li>{Navedi samo potrjene tehnične podatke, vsakega v svoji alineji, po možnosti »Lastnost: vrednost«. Ohrani enote in modelne oznake. Če podatkov ni, izpusti naslov in celoten seznam.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Napiši edinstven in jedrnat SEO naslov z imenom izdelka in eno dokazano razlikovalno lastnostjo. Približno 50–60 znakov, če zveni naravno; brez HTML-ja.}\n{meta_description: V eni naravni povedi povzemi izdelek in eno ali dve potrjeni lastnosti. Približno 120–155 znakov, če je dovolj podatkov; največ 155 s presledki. Brez HTML-ja, izmišljanja in kopičenja ključnih besed.}"
|
||||||
|
},
|
||||||
|
"sv": {
|
||||||
|
"title": "{Skriv en tydlig produkttitel för {{name}} med hjälp av verifierade {{attrs}}. Skriv varumärket med rätt stora bokstäver, produkttypen med gemener, fullständig modell och modellkod med versaler samt färgen som ett ord om den är känd. Inga kommatecken.}",
|
||||||
|
"description": "<p>{Presentera {{name}} i ett kort stycke med produkttyp och användning utifrån {{description}} och {{attrs}}. Cirka 30–60 ord om fakta räcker; upprepa inte rubriken och hitta inte på uppgifter.}</p>\n<h2>{Skriv en tydlig H2 om den bäst belagda egenskapen eller användningen, utan generiska säljklyschor eller upprepning av hela produktnamnet. Om ingen egenskap eller användning är bekräftad, utelämna denna H2 och följande stycke.}</h2>\n<p>{Förklara egenskapen och dess praktiska betydelse med verifierade uppgifter. Cirka 50–90 ord bara om materialet räcker; annars kortare och utan upprepningar.}</p>\n<h2>{Använd rubriken ”Tekniska specifikationer” endast om det finns verifierade uppgifter.}</h2>\n<ul><li>{Lista bara bekräftade specifikationer, en per listpunkt, helst ”Egenskap: värde”. Behåll enheter och modellkoder. Finns inga uppgifter ska både rubrik och lista utelämnas.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Skriv en unik och kort SEO-titel med produktnamnet och en dokumenterad särskiljande egenskap. Cirka 50–60 tecken där det passar, utan HTML.}\n{meta_description: Sammanfatta produkten och en eller två bekräftade egenskaper. Sikta på 120–155 tecken om fakta räcker, max 155 inklusive blanksteg. Utan HTML eller upprepade nyckelord.}"
|
||||||
|
},
|
||||||
|
"da": {
|
||||||
|
"title": "{Skriv en tydelig produkttitel til {{name}} med udgangspunkt i verificerede {{attrs}}. Skriv mærket med korrekt brug af store bogstaver, produkttypen med små bogstaver, den fulde model og modelkode med store bogstaver samt farven som ét ord, hvis den kendes. Ingen kommaer.}",
|
||||||
|
"description": "<p>{Præsenter {{name}} i et kort afsnit med produkttype og anvendelse ud fra {{description}} og {{attrs}}. Omkring 30–60 ord, hvis fakta rækker; gentag ikke hele titlen og opfind ikke oplysninger.}</p>\n<h2>{Skriv en konkret H2 om den bedst dokumenterede egenskab eller brug, uden generiske salgsfraser eller gentagelse af hele navnet. Hvis ingen egenskab eller brug er dokumenteret, udelad denne H2 og det følgende afsnit.}</h2>\n<p>{Forklar egenskaben og dens praktiske værdi med verificerede oplysninger. Omkring 50–90 ord kun ved tilstrækkelige fakta, ellers kortere og uden gentagelser.}</p>\n<h2>{Brug overskriften »Tekniske specifikationer« kun hvis der findes bekræftede data.}</h2>\n<ul><li>{Angiv kun kontrollerede specifikationer, en pr. listepunkt, gerne »Egenskab: værdi«. Bevar enheder og modelkoder. Uden data udelades både overskrift og liste.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Lav en unik, kort SEO-titel med produktnavn og et dokumenteret kendetegn. Omkring 50–60 tegn hvis naturligt; ingen HTML.}\n{meta_description: Opsummér produktet og en eller to verificerede egenskaber. Omkring 120–155 tegn hvis muligt, højst 155 inklusive mellemrum. Ingen HTML eller gentagne søgeord.}"
|
||||||
|
},
|
||||||
|
"fi": {
|
||||||
|
"title": "{Kirjoita selkeä tuotteen {{name}} nimi vahvistettujen {{attrs}}-tietojen perusteella. Kirjoita tuotemerkki oikealla kirjainkoolla, tuotetyyppi pienillä kirjaimilla, koko malli ja mallikoodi isoilla kirjaimilla sekä väri yhtenä sanana, jos se tiedetään. Ei pilkkuja.}",
|
||||||
|
"description": "<p>{Esittele {{name}} lyhyessä kappaleessa: tuotetyyppi ja käyttötarkoitus {{description}}- ja {{attrs}}-tietojen pohjalta. Noin 30–60 sanaa vain tietojen riittäessä; älä toista nimeä tai keksi väitteitä.}</p>\n<h2>{Kirjoita täsmällinen H2-otsikko parhaiten varmennetusta ominaisuudesta tai käyttötavasta, ei yleistä mainoslausetta tai koko tuotenimen toistoa. Jos ominaisuudesta tai käyttötavasta ei ole vahvistettua tietoa, jätä tämä H2 ja seuraava kappale pois.}</h2>\n<p>{Kerro ominaisuuden käytännön merkityksestä vahvistetuilla tiedoilla. Noin 50–90 sanaa vain, jos tietoja riittää; muussa tapauksessa lyhyemmin ilman toistoa.}</p>\n<h2>{Käytä otsikkoa ”Tekniset tiedot” vain, jos vahvistettuja teknisiä tietoja on saatavilla.}</h2>\n<ul><li>{Luettele vain tarkistetut tiedot erillisiin luettelokohtiin, mieluiten ”Ominaisuus: arvo”. Säilytä yksiköt ja mallikoodit. Ilman tietoja jätä otsikko ja luettelo pois.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Laadi yksilöllinen, ytimekäs SEO-otsikko tuotteen nimellä ja varmennetulla erottavalla ominaisuudella. Noin 50–60 merkkiä jos luontevaa; ei HTML:ää.}\n{meta_description: Kuvaa tuote ja yksi tai kaksi vahvistettua ominaisuutta. Pyri 120–155 merkkiin, jos tietoja on; enintään 155 välilyönteineen. Ei HTML:ää eikä avainsanojen toistoa.}"
|
||||||
|
},
|
||||||
|
"el": {
|
||||||
|
"title": "{Γράψε έναν σαφή τίτλο προϊόντος για το {{name}} με βάση τα επαληθευμένα {{attrs}}. Γράψε τη μάρκα με σωστά κεφαλαία, τον τύπο προϊόντος με πεζά, το πλήρες μοντέλο και τον κωδικό μοντέλου με κεφαλαία και έπειτα το χρώμα με μία λέξη, εφόσον είναι γνωστό. Χωρίς κόμματα.}",
|
||||||
|
"description": "<p>{Παρουσίασε το {{name}} με σύντομη παράγραφο για τον τύπο και τη χρήση του, βάσει των {{description}} και {{attrs}}. Περίπου 30–60 λέξεις μόνο με επαρκή στοιχεία, χωρίς επανάληψη του τίτλου ή επινοήσεις.}</p>\n<h2>{Γράψε συγκεκριμένο τίτλο H2 για το καλύτερα τεκμηριωμένο χαρακτηριστικό ή τη χρήση, χωρίς γενικά διαφημιστικά συνθήματα. Αν δεν υπάρχει τεκμηριωμένο χαρακτηριστικό ή χρήση, παράλειψε αυτό το H2 και την επόμενη παράγραφο.}</h2>\n<p>{Εξήγησε το χαρακτηριστικό και την πρακτική αξία του με επιβεβαιωμένα στοιχεία. Περίπου 50–90 λέξεις μόνο αν επαρκούν οι πληροφορίες· διαφορετικά συντομότερα, χωρίς επαναλήψεις.}</p>\n<h2>{Χρησιμοποίησε τον τίτλο «Τεχνικά χαρακτηριστικά» μόνο εφόσον υπάρχουν επιβεβαιωμένα δεδομένα.}</h2>\n<ul><li>{Παράθεσε μόνο επαληθευμένα στοιχεία, ένα ανά στοιχείο λίστας, ιδανικά «Χαρακτηριστικό: τιμή». Διατήρησε μονάδες και κωδικούς. Χωρίς στοιχεία παράλειψε και τον τίτλο και τη λίστα.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Δημιούργησε μοναδικό, σύντομο τίτλο SEO με το όνομα του προϊόντος και τεκμηριωμένη διαφορά. Περίπου 50–60 χαρακτήρες εφόσον φυσικό· χωρίς HTML.}\n{meta_description: Συνόψισε το προϊόν και ένα ή δύο επιβεβαιωμένα χαρακτηριστικά. 120–155 χαρακτήρες όπου είναι δυνατό, μέγιστο 155 μαζί με κενά. Χωρίς HTML ή επανάληψη λέξεων-κλειδιών.}"
|
||||||
|
},
|
||||||
|
"et": {
|
||||||
|
"title": "{Kirjuta tootele {{name}} selge pealkiri, kasutades kontrollitud {{attrs}} andmeid. Kirjuta kaubamärk õige suur- ja väiketähekasutusega, tootetüüp väiketähtedega, täielik mudel ja mudelikood suurtähtedega ning värv ühe sõnana, kui see on teada. Ilma komadeta.}",
|
||||||
|
"description": "<p>{Tutvusta {{name}} lühikeses lõigus, kirjeldades tooteliiki ja kasutust {{description}} ning {{attrs}} põhjal. Umbes 30–60 sõna vaid piisavate faktide korral; ära korda pealkirja ega mõtle omadusi välja.}</p>\n<h2>{Kirjuta täpne H2 kõige paremini tõendatud omaduse või kasutusviisi kohta, ilma üldise reklaamlause ja täieliku tootenime korduseta. Kui ühtki omadust või kasutust pole kinnitatud, jäta see H2 ja järgmine lõik ära.}</h2>\n<p>{Selgita omadust ja praktilist väärtust kontrollitud faktidega. Umbes 50–90 sõna ainult piisava teabe korral; muidu lühemalt ja kordusteta.}</p>\n<h2>{Kasuta pealkirja „Tehnilised andmed” ainult siis, kui kinnitatud andmed on olemas.}</h2>\n<ul><li>{Loetle ainult kontrollitud andmed eraldi loendikirje-elementides, näiteks „Omadus: väärtus”. Säilita ühikud ja mudelikoodid. Kui andmeid pole, jäta pealkiri ja loend ära.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Koosta ainulaadne lühike SEO-pealkiri tootenime ja tõendatud eristava omadusega. Umbes 50–60 märki, kui sobib; ilma HTML-ita.}\n{meta_description: Võta toode ja üks-kaks tõendatud omadust kokku. Võimalusel 120–155 märki, maksimaalselt 155 koos tühikutega. Ilma HTML-i ja märksõnade kordamiseta.}"
|
||||||
|
},
|
||||||
|
"lv": {
|
||||||
|
"title": "{Uzraksti skaidru produkta {{name}} nosaukumu, izmantojot pārbaudītos {{attrs}}. Zīmolu raksti ar pareiziem lielajiem burtiem, produkta veidu ar mazajiem burtiem, pilnu modeli un modeļa kodu ar lielajiem burtiem, bet krāsu vienā vārdā, ja tā zināma. Bez komatiem.}",
|
||||||
|
"description": "<p>{Īsā rindkopā iepazīstini ar {{name}}, norādot produkta veidu un lietojumu, izmantojot {{description}} un {{attrs}}. Apmēram 30–60 vārdu, ja pietiek faktu; neatkārto visu virsrakstu un neko neizdomā.}</p>\n<h2>{Izveido konkrētu H2 par vislabāk apstiprināto īpašību vai lietojumu, bez vispārīgiem reklāmas saukļiem un pilnā nosaukuma atkārtošanas. Ja nav apstiprinātas īpašības vai lietojuma, izlaid šo H2 un nākamo rindkopu.}</h2>\n<p>{Izskaidro īpašību un tās praktisko nozīmi ar pārbaudītiem faktiem. Apmēram 50–90 vārdu, ja informācijas pietiek; citādi īsāk, bez atkārtošanās.}</p>\n<h2>{Virsrakstu „Tehniskā specifikācija” lieto tikai tad, ja ir apstiprināti dati.}</h2>\n<ul><li>{Uzskaiti tikai pārbaudītus parametrus atsevišķos saraksta punktos, vēlams „Parametrs: vērtība”. Saglabā mērvienības un modeļu kodus. Bez datiem izlaid virsrakstu un sarakstu.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Izveido unikālu, īsu SEO virsrakstu ar produkta nosaukumu un apstiprinātu īpašību. Apmēram 50–60 rakstzīmes, ja dabiski; bez HTML.}\n{meta_description: Apkopojiet produktu un vienu vai divas apstiprinātas īpašības. Ja var, 120–155 rakstzīmes, ne vairāk kā 155 ar atstarpēm. Bez HTML vai atslēgvārdu atkārtošanas.}"
|
||||||
|
},
|
||||||
|
"lt": {
|
||||||
|
"title": "{Parašyk aiškų produkto {{name}} pavadinimą pagal patikrintus {{attrs}}. Prekės ženklą rašyk taisyklingomis didžiosiomis raidėmis, gaminio tipą mažosiomis, pilną modelį ir modelio kodą didžiosiomis, o spalvą vienu žodžiu, jei žinoma. Be kablelių.}",
|
||||||
|
"description": "<p>{Trumpa pastraipa pristatyk {{name}}: produkto tipą ir paskirtį remdamasis {{description}} ir {{attrs}}. Apie 30–60 žodžių tik jei duomenų pakanka; nekartok pavadinimo ir neišgalvok faktų.}</p>\n<h2>{Parašyk konkretų H2 apie geriausiai patvirtintą savybę ar naudojimą, be bendrų reklaminių frazių ir viso pavadinimo kartojimo. Jei nėra patvirtintos savybės ar naudojimo, praleisk šį H2 ir kitą pastraipą.}</h2>\n<p>{Paaiškink savybę ir praktinę naudą tik patikrintais faktais. Apie 50–90 žodžių, jei duomenų pakanka; kitaip trumpiau ir be pasikartojimų.}</p>\n<h2>{Antraštę „Techninės specifikacijos” rašyk tik jei yra patvirtintų techninių duomenų.}</h2>\n<ul><li>{Išvardyk tik patikrintus parametrus atskiruose sąrašo elementuose, geriausia „Savybė: vertė”. Išsaugok vienetus ir modelių kodus. Jei duomenų nėra, praleisk ir antraštę, ir sąrašą.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Sukurk unikalų, glaustą SEO pavadinimą su produkto vardu ir pagrįsta išskirtine savybe. Apie 50–60 simbolių, jei natūralu; be HTML.}\n{meta_description: Apibendrink produktą ir vieną ar dvi patikrintas savybes. Jei įmanoma, 120–155 simboliai, daugiausia 155 su tarpais. Be HTML ar raktažodžių kartojimo.}"
|
||||||
|
},
|
||||||
|
"mt": {
|
||||||
|
"title": "{Ikteb titlu ċar għall-prodott {{name}} billi tuża {{attrs}} ivverifikati. Ikteb il-marka bil-kapitalizzazzjoni korretta, it-tip tal-prodott b’ittri żgħar, il-mudell sħiħ u l-kodiċi tiegħu b’ittri kbar, u l-kulur b’kelma waħda jekk magħruf. Bla virgoli.}",
|
||||||
|
"description": "<p>{Introduċi {{name}} f’paragrafu qasir bit-tip ta’ prodott u l-użu tiegħu, skont {{description}} u {{attrs}}. Madwar 30–60 kelma jekk hemm biżżejjed fatti; irrepetix it-titlu kollu u tivvintax dettalji.}</p>\n<h2>{Ikteb intestatura H2 speċifika dwar il-karatteristika jew l-użu l-aktar dokumentat, mhux slogan ġeneriku jew ripetizzjoni tal-isem kollu. Jekk m’hemmx karatteristika jew użu vverifikat, ħalli barra dan il-H2 u l-paragrafu ta’ warajh.}</h2>\n<p>{Spjega l-karatteristika u l-utilità prattika tagħha b’fatti kkonfermati. Madwar 50–90 kelma biss jekk hemm data biżżejjed; inkella iqsar u bla ripetizzjonijiet.}</p>\n<h2>{Uża t-titlu “Speċifikazzjonijiet tekniċi” biss meta jkun hemm data kkonfermata.}</h2>\n<ul><li>{Elenka biss speċifikazzjonijiet ivverifikati, waħda f’kull punt tal-lista, idealment “Proprjetà: valur”. Żomm l-unitajiet u l-kodiċijiet. Jekk m’hemmx data, ħalli barra kemm l-intestatura kif ukoll il-lista.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Oħloq titlu SEO uniku u qasir bl-isem tal-prodott u karatteristika dokumentata. Madwar 50–60 karattru jekk naturali; bla HTML.}\n{meta_description: Agħti sommarju tal-prodott u karatteristika waħda jew tnejn ivverifikati. Jekk possibbli 120–155 karattru, massimu 155 bl-ispazji. Bla HTML jew ripetizzjoni tal-kliem ewlieni.}"
|
||||||
|
},
|
||||||
|
"ga": {
|
||||||
|
"title": "{Scríobh teideal soiléir don táirge {{name}} bunaithe ar {{attrs}} fíoraithe. Scríobh an branda leis na ceannlitreacha cearta, cineál an táirge i litreacha beaga, an tsamhail iomlán agus a cód i gceannlitreacha, agus an dath in aon fhocal más eol é. Gan camóga.}",
|
||||||
|
"description": "<p>{Cuir {{name}} i láthair in alt gearr leis an gcineál táirge agus a úsáid bunaithe ar {{description}} agus {{attrs}}. Thart ar 30–60 focal nuair atá dóthain sonraí ann; ná déan an teideal a athrá ná sonraí a chumadh.}</p>\n<h2>{Scríobh ceannteideal H2 sonrach faoin tréith nó faoin úsáid is fearr atá deimhnithe, gan mana fógraíochta ná athrá ar ainm iomlán an táirge. Mura bhfuil gné ná úsáid deimhnithe ann, fág an H2 seo agus an chéad alt eile ar lár.}</h2>\n<p>{Mínigh an tréith agus a tairbhe phraiticiúil le fíricí deimhnithe. Thart ar 50–90 focal má tá dóthain sonraí ann; mura bhfuil, scríobh níos giorra agus seachain athrá.}</p>\n<h2>{Úsáid an ceannteideal “Sonraíochtaí teicniúla” ach amháin má tá sonraí fíoraithe ar fáil.}</h2>\n<ul><li>{Liostaigh sonraí deimhnithe amháin, ceann amháin i ngach mír liosta, mar “Airí: luach” más féidir. Coinnigh aonaid agus cóid mhúnla. Gan sonraí, fág an ceannteideal agus an liosta ar lár.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Cruthaigh teideal SEO uathúil gonta le hainm an táirge agus tréith dheimhnithe. Thart ar 50–60 carachtar más nádúrtha; gan HTML.}\n{meta_description: Déan achoimre ar an táirge agus tréith nó dhó atá fíoraithe. Más féidir 120–155 carachtar, uasmhéid 155 le spásanna. Gan HTML ná eochairfhocail athchleachtacha.}"
|
||||||
|
},
|
||||||
|
"ja": {
|
||||||
|
"title": "{確認済みの {{name}} と {{attrs}} を基に、正式なブランド名、商品種別、モデル名・型番、確認できた場合のみ色を含めた自然な商品名を作成してください。ブランドと型番の正式表記を維持し、不要な句読点や未確認の特長を加えないでください。HTML は使わないでください。}",
|
||||||
|
"description": "<p>{商品名 {{name}} の種類と用途を {{description}} と {{attrs}} の確認済み情報に基づいて短い導入段落で説明してください。情報が十分なら簡潔にまとめ、商品名全体の不自然な繰り返しや推測は避けてください。}</p>\n<h2>{最もよく裏付けられた特徴または用途を表す具体的な H2 見出しを書いてください。誇張した宣伝文句や商品名全体の繰り返しは避けてください。 特徴や用途を裏付ける情報がなければ、この H2 と続く段落を省略してください。}</h2>\n<p>{その特徴と実際の使い方を確認済みの情報だけで説明してください。情報が十分な場合は自然な長さにし、不足する場合は短くしてください。同じ内容を繰り返さないでください。}</p>\n<h2>{技術仕様が確認できる場合にのみ「製品仕様」に相当する見出しを書いてください。}</h2>\n<ul><li>{確認済みの仕様のみを 1 項目ずつ箇条書きに記載してください。可能なら「項目:値」とし、単位と型番は維持してください。仕様がなければ見出しとリスト全体を省略してください。}</li></ul>",
|
||||||
|
"meta": "{meta_title: 正式な商品名と確認済みの特徴を使って、固有で簡潔な SEO タイトルを作成してください。不自然な文字数調整は不要です。HTML は使用しないでください。}\n{meta_description: 商品が何か、確認できた特徴を 1〜2 点、自然な日本語で要約してください。空白を含め 155 文字以内を目安とし、情報が少ない場合は短くしてください。HTML やキーワードの羅列は避けてください。}"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
{
|
||||||
|
"en": {
|
||||||
|
"title": "Brand with correct capitalization, product type in lowercase, complete model and uppercase model ID, then color as one word if known. No commas.",
|
||||||
|
"description": "Write five distinct H2 headings, each followed by a paragraph of approximately 100 words. Omit the complete product name from paragraphs 1, 3 and 5; include it naturally once in paragraphs 2 and 4. Finish with a list of 3–10 verified technical specifications. Never invent benefits or specifications.",
|
||||||
|
"meta": "Start the meta description with the new product name; maximum 140 characters including spaces."
|
||||||
|
},
|
||||||
|
"fr": {
|
||||||
|
"title": "Marque avec la casse correcte, type de produit en minuscules, modèle complet et référence en majuscules, puis couleur en un seul mot si elle est connue. Sans virgules.",
|
||||||
|
"description": "Rédigez cinq titres H2 distincts, chacun suivi d’un paragraphe d’environ 100 mots. Omettez le nom complet dans les paragraphes 1, 3 et 5 ; insérez-le naturellement une fois dans les paragraphes 2 et 4. Terminez par 3 à 10 caractéristiques techniques vérifiées, sans rien inventer.",
|
||||||
|
"meta": "Commencez la méta-description par le nouveau nom du produit ; 140 caractères maximum, espaces compris."
|
||||||
|
},
|
||||||
|
"de": {
|
||||||
|
"title": "Marke korrekt schreiben, Produkttyp klein, vollständiges Modell mit Modellkennung in Großbuchstaben, danach die Farbe als ein Wort, falls bekannt. Keine Kommas.",
|
||||||
|
"description": "Schreibe fünf unterschiedliche H2-Überschriften mit jeweils einem Absatz von etwa 100 Wörtern. In Absatz 1, 3 und 5 den vollständigen Produktnamen nicht nennen; in Absatz 2 und 4 jeweils einmal natürlich einbauen. Danach 3–10 belegte technische Daten als Liste, ohne Angaben zu erfinden.",
|
||||||
|
"meta": "Beginne die Meta-Beschreibung mit dem neuen Produktnamen; höchstens 140 Zeichen einschließlich Leerzeichen."
|
||||||
|
},
|
||||||
|
"es": {
|
||||||
|
"title": "Marca con mayúsculas correctas, tipo de producto en minúsculas, modelo completo e identificador del modelo en mayúsculas y color en una sola palabra si se conoce. Sin comas.",
|
||||||
|
"description": "Escribe cinco encabezados H2 diferentes, cada uno con un párrafo de unas 100 palabras. Evita el nombre completo en los párrafos 1, 3 y 5; inclúyelo una vez de forma natural en los párrafos 2 y 4. Termina con 3–10 especificaciones técnicas verificadas, sin inventar datos.",
|
||||||
|
"meta": "Empieza la metadescripción con el nombre nuevo del producto; máximo 140 caracteres con espacios."
|
||||||
|
},
|
||||||
|
"it": {
|
||||||
|
"title": "Marchio con maiuscole corrette, tipo di prodotto in minuscolo, modello completo e codice modello in maiuscolo, poi colore in una parola se noto. Senza virgole.",
|
||||||
|
"description": "Scrivi cinque titoli H2 distinti, ciascuno seguito da un paragrafo di circa 100 parole. Non ripetere il nome completo nei paragrafi 1, 3 e 5; includilo naturalmente una volta nei paragrafi 2 e 4. Termina con 3–10 specifiche tecniche verificate, senza inventare dati.",
|
||||||
|
"meta": "Inizia la meta descrizione con il nuovo nome del prodotto; massimo 140 caratteri, spazi inclusi."
|
||||||
|
},
|
||||||
|
"nl": {
|
||||||
|
"title": "Merk met juiste hoofdletters, producttype in kleine letters, volledig model met modelcode in hoofdletters, daarna kleur als één woord indien bekend. Geen komma’s.",
|
||||||
|
"description": "Schrijf vijf verschillende H2-koppen met elk een alinea van circa 100 woorden. Laat de volledige productnaam weg in alinea 1, 3 en 5; gebruik die eenmaal natuurlijk in alinea 2 en 4. Sluit af met 3–10 gecontroleerde technische specificaties, zonder gegevens te verzinnen.",
|
||||||
|
"meta": "Begin de metabeschrijving met de nieuwe productnaam; maximaal 140 tekens inclusief spaties."
|
||||||
|
},
|
||||||
|
"pt": {
|
||||||
|
"title": "Marca com capitalização correta, tipo de produto em minúsculas, modelo completo e código do modelo em maiúsculas e cor numa única palavra, se conhecida. Sem vírgulas.",
|
||||||
|
"description": "Escreve cinco títulos H2 diferentes, cada um seguido de um parágrafo de cerca de 100 palavras. Não uses o nome completo nos parágrafos 1, 3 e 5; inclui-o naturalmente uma vez nos parágrafos 2 e 4. Termina com 3–10 especificações técnicas verificadas, sem inventar dados.",
|
||||||
|
"meta": "Começa a meta descrição pelo novo nome do produto; máximo de 140 caracteres, incluindo espaços."
|
||||||
|
},
|
||||||
|
"pl": {
|
||||||
|
"title": "Marka z poprawną pisownią, typ produktu małymi literami, pełny model i jego kod wielkimi literami, a następnie kolor jednym słowem, jeśli jest znany. Bez przecinków.",
|
||||||
|
"description": "Napisz pięć różnych nagłówków H2, a pod każdym akapit o długości około 100 słów. Nie używaj pełnej nazwy produktu w akapitach 1, 3 i 5; umieść ją naturalnie raz w akapitach 2 i 4. Zakończ listą 3–10 potwierdzonych parametrów technicznych. Niczego nie wymyślaj.",
|
||||||
|
"meta": "Zacznij metaopis od nowej nazwy produktu; maksymalnie 140 znaków wraz ze spacjami."
|
||||||
|
},
|
||||||
|
"cs": {
|
||||||
|
"title": "Značku napiš se správnými velkými písmeny, typ výrobku malými písmeny, celý model a jeho kód velkými písmeny a barvu jedním slovem, je-li známá. Bez čárek.",
|
||||||
|
"description": "Napiš pět odlišných nadpisů H2 a ke každému odstavec o přibližně 100 slovech. Úplný název výrobku vynech v odstavcích 1, 3 a 5; přirozeně ho jednou použij v odstavcích 2 a 4. Na závěr uveď 3–10 ověřených technických parametrů, bez vymýšlení údajů.",
|
||||||
|
"meta": "Meta popis začni novým názvem výrobku; maximálně 140 znaků včetně mezer."
|
||||||
|
},
|
||||||
|
"sk": {
|
||||||
|
"title": "Značku uveď so správnymi veľkými písmenami, typ výrobku malými písmenami, úplný model a jeho kód veľkými písmenami a farbu jedným slovom, ak je známa. Bez čiarok.",
|
||||||
|
"description": "Napíš päť odlišných nadpisov H2 a ku každému odsek s približne 100 slovami. Úplný názov výrobku vynechaj v odsekoch 1, 3 a 5; prirodzene ho raz zahrň do odsekov 2 a 4. Na konci uveď 3–10 overených technických parametrov, bez vymýšľania údajov.",
|
||||||
|
"meta": "Meta popis začni novým názvom výrobku; najviac 140 znakov vrátane medzier."
|
||||||
|
},
|
||||||
|
"hu": {
|
||||||
|
"title": "A márkanevet helyes nagybetűzéssel, a terméktípust kisbetűkkel, a teljes modellt és modellszámot nagybetűs azonosítóval, a színt pedig egy szóban add meg, ha ismert. Vessző nélkül.",
|
||||||
|
"description": "Írj öt különböző H2 címsort, mindegyik után körülbelül 100 szavas bekezdéssel. Az 1., 3. és 5. bekezdésben ne szerepeljen a teljes terméknév; a 2. és 4. bekezdésben egyszer, természetesen szerepeljen. Végül sorolj fel 3–10 igazolt műszaki adatot. Ne találj ki adatokat.",
|
||||||
|
"meta": "A metaleírás a termék új nevével kezdődjön; legfeljebb 140 karakter szóközökkel együtt."
|
||||||
|
},
|
||||||
|
"ro": {
|
||||||
|
"title": "Marca scrisă corect, tipul produsului cu litere mici, modelul complet și codul modelului cu majuscule, apoi culoarea într-un singur cuvânt, dacă este cunoscută. Fără virgule.",
|
||||||
|
"description": "Scrie cinci subtitluri H2 distincte, fiecare urmat de un paragraf de aproximativ 100 de cuvinte. Omite denumirea completă din paragrafele 1, 3 și 5; include-o natural o singură dată în paragrafele 2 și 4. Încheie cu 3–10 specificații tehnice verificate, fără date inventate.",
|
||||||
|
"meta": "Începe metadescrierea cu noua denumire a produsului; maximum 140 de caractere, inclusiv spațiile."
|
||||||
|
},
|
||||||
|
"bg": {
|
||||||
|
"title": "Марката с правилни главни букви, видът на продукта с малки букви, пълният модел и кодът му с главни букви, а след това цветът с една дума, ако е известен. Без запетаи.",
|
||||||
|
"description": "Напиши пет различни заглавия H2, всяко следвано от абзац с около 100 думи. Не използвай пълното име в абзаци 1, 3 и 5; включи го естествено по веднъж в абзаци 2 и 4. Завърши с 3–10 потвърдени технически характеристики, без измислени данни.",
|
||||||
|
"meta": "Започни метаописанието с новото име на продукта; максимум 140 знака, включително интервалите."
|
||||||
|
},
|
||||||
|
"hr": {
|
||||||
|
"title": "Marku napiši s pravilnim velikim slovima, vrstu proizvoda malim slovima, puni model i oznaku modela velikim slovima, a zatim boju jednom riječju ako je poznata. Bez zareza.",
|
||||||
|
"description": "Napiši pet različitih naslova H2, a ispod svakog odlomak od približno 100 riječi. Izostavi puni naziv proizvoda iz odlomaka 1, 3 i 5; prirodno ga uključi jednom u odlomke 2 i 4. Završi popisom 3–10 potvrđenih tehničkih specifikacija. Ne izmišljaj podatke.",
|
||||||
|
"meta": "Započni meta opis novim nazivom proizvoda; najviše 140 znakova, uključujući razmake."
|
||||||
|
},
|
||||||
|
"sl": {
|
||||||
|
"title": "Znamko zapiši s pravilnimi velikimi črkami, tip izdelka z malimi črkami, celoten model in oznako modela z velikimi črkami, nato barvo z eno besedo, če je znana. Brez vejic.",
|
||||||
|
"description": "Napiši pet različnih naslovov H2, vsakemu naj sledi odstavek s približno 100 besedami. V odstavkih 1, 3 in 5 ne uporabi celotnega novega imena izdelka; v odstavkih 2 in 4 ga naravno vključi enkrat. Zaključi s seznamom 3–10 preverjenih tehničnih specifikacij. Ne izmišljaj si podatkov.",
|
||||||
|
"meta": "Meta opis začni z novim imenom izdelka; največ 140 znakov skupaj s presledki."
|
||||||
|
},
|
||||||
|
"sv": {
|
||||||
|
"title": "Skriv varumärket med rätt stora bokstäver, produkttypen med gemener, fullständig modell och modellkod med versaler samt färgen som ett ord om den är känd. Inga kommatecken.",
|
||||||
|
"description": "Skriv fem olika H2-rubriker, var och en följd av ett stycke på cirka 100 ord. Utelämna det fullständiga produktnamnet i stycke 1, 3 och 5; ta med det naturligt en gång i stycke 2 och 4. Avsluta med 3–10 verifierade tekniska specifikationer, utan påhittade uppgifter.",
|
||||||
|
"meta": "Börja metabeskrivningen med det nya produktnamnet; högst 140 tecken inklusive mellanslag."
|
||||||
|
},
|
||||||
|
"da": {
|
||||||
|
"title": "Skriv mærket med korrekt brug af store bogstaver, produkttypen med små bogstaver, den fulde model og modelkode med store bogstaver samt farven som ét ord, hvis den kendes. Ingen kommaer.",
|
||||||
|
"description": "Skriv fem forskellige H2-overskrifter, hver efterfulgt af et afsnit på cirka 100 ord. Udelad det fulde produktnavn i afsnit 1, 3 og 5; medtag det naturligt én gang i afsnit 2 og 4. Afslut med 3–10 verificerede tekniske specifikationer, og opfind aldrig oplysninger.",
|
||||||
|
"meta": "Start metabeskrivelsen med det nye produktnavn; højst 140 tegn inklusive mellemrum."
|
||||||
|
},
|
||||||
|
"fi": {
|
||||||
|
"title": "Kirjoita tuotemerkki oikealla kirjainkoolla, tuotetyyppi pienillä kirjaimilla, koko malli ja mallikoodi isoilla kirjaimilla sekä väri yhtenä sanana, jos se tiedetään. Ei pilkkuja.",
|
||||||
|
"description": "Kirjoita viisi erilaista H2-otsikkoa ja jokaisen alle noin 100 sanan kappale. Jätä tuotteen koko nimi pois kappaleista 1, 3 ja 5; sisällytä se luontevasti kerran kappaleisiin 2 ja 4. Päätä teksti 3–10 varmennettuun tekniseen ominaisuuteen. Älä keksi tietoja.",
|
||||||
|
"meta": "Aloita metakuvaus tuotteen uudella nimellä; enintään 140 merkkiä välilyönnit mukaan lukien."
|
||||||
|
},
|
||||||
|
"el": {
|
||||||
|
"title": "Γράψε τη μάρκα με σωστά κεφαλαία, τον τύπο προϊόντος με πεζά, το πλήρες μοντέλο και τον κωδικό μοντέλου με κεφαλαία και έπειτα το χρώμα με μία λέξη, εφόσον είναι γνωστό. Χωρίς κόμματα.",
|
||||||
|
"description": "Γράψε πέντε διαφορετικές επικεφαλίδες H2, καθεμία με παράγραφο περίπου 100 λέξεων. Μην αναφέρεις ολόκληρο το όνομα στις παραγράφους 1, 3 και 5· συμπερίλαβέ το φυσικά μία φορά στις παραγράφους 2 και 4. Κλείσε με 3–10 επαληθευμένες τεχνικές προδιαγραφές, χωρίς επινοημένα στοιχεία.",
|
||||||
|
"meta": "Ξεκίνα τη μετα-περιγραφή με το νέο όνομα του προϊόντος· έως 140 χαρακτήρες μαζί με τα κενά."
|
||||||
|
},
|
||||||
|
"et": {
|
||||||
|
"title": "Kirjuta kaubamärk õige suur- ja väiketähekasutusega, tootetüüp väiketähtedega, täielik mudel ja mudelikood suurtähtedega ning värv ühe sõnana, kui see on teada. Ilma komadeta.",
|
||||||
|
"description": "Kirjuta viis erinevat H2-pealkirja, igaühe järele umbes 100-sõnaline lõik. Ära kasuta toote täielikku nime lõikudes 1, 3 ja 5; lisa see loomulikult üks kord lõikudesse 2 ja 4. Lõpeta 3–10 kontrollitud tehnilise näitaja loendiga, ilma andmeid välja mõtlemata.",
|
||||||
|
"meta": "Alusta metakirjeldust toote uue nimega; kuni 140 tähemärki koos tühikutega."
|
||||||
|
},
|
||||||
|
"lv": {
|
||||||
|
"title": "Zīmolu raksti ar pareiziem lielajiem burtiem, produkta veidu ar mazajiem burtiem, pilnu modeli un modeļa kodu ar lielajiem burtiem, bet krāsu vienā vārdā, ja tā zināma. Bez komatiem.",
|
||||||
|
"description": "Uzraksti piecus dažādus H2 virsrakstus, katram seko apmēram 100 vārdu rindkopa. Nelieto pilnu produkta nosaukumu 1., 3. un 5. rindkopā; dabiski iekļauj to vienreiz 2. un 4. rindkopā. Noslēdz ar 3–10 pārbaudītām tehniskajām specifikācijām, neizdomājot faktus.",
|
||||||
|
"meta": "Sāc metaaprakstu ar jauno produkta nosaukumu; ne vairāk kā 140 rakstzīmes, ieskaitot atstarpes."
|
||||||
|
},
|
||||||
|
"lt": {
|
||||||
|
"title": "Prekės ženklą rašyk taisyklingomis didžiosiomis raidėmis, gaminio tipą mažosiomis, pilną modelį ir modelio kodą didžiosiomis, o spalvą vienu žodžiu, jei žinoma. Be kablelių.",
|
||||||
|
"description": "Parašyk penkias skirtingas H2 antraštes, po kiekvienos pateik apie 100 žodžių pastraipą. 1, 3 ir 5 pastraipose neminėk viso gaminio pavadinimo; 2 ir 4 pastraipose natūraliai panaudok jį po vieną kartą. Pabaigoje pateik 3–10 patvirtintų techninių specifikacijų. Neišgalvok duomenų.",
|
||||||
|
"meta": "Metaaprašymą pradėk nauju gaminio pavadinimu; daugiausia 140 simbolių su tarpais."
|
||||||
|
},
|
||||||
|
"mt": {
|
||||||
|
"title": "Ikteb il-marka bil-kapitalizzazzjoni korretta, it-tip tal-prodott b’ittri żgħar, il-mudell sħiħ u l-kodiċi tiegħu b’ittri kbar, u l-kulur b’kelma waħda jekk magħruf. Bla virgoli.",
|
||||||
|
"description": "Ikteb ħames intestaturi H2 differenti, kull waħda b’paragrafu ta’ madwar 100 kelma. Tinkludix l-isem sħiħ fil-paragrafi 1, 3 u 5; inkludih darba b’mod naturali fil-paragrafi 2 u 4. Temm b’3–10 speċifikazzjonijiet tekniċi vverifikati, bla fatti ivvintati.",
|
||||||
|
"meta": "Ibda l-meta-deskrizzjoni bl-isem il-ġdid tal-prodott; mhux aktar minn 140 karattru inklużi l-ispazji."
|
||||||
|
},
|
||||||
|
"ga": {
|
||||||
|
"title": "Scríobh an branda leis na ceannlitreacha cearta, cineál an táirge i litreacha beaga, an tsamhail iomlán agus a cód i gceannlitreacha, agus an dath in aon fhocal más eol é. Gan camóga.",
|
||||||
|
"description": "Scríobh cúig cheannteideal H2 éagsúla, agus alt thart ar 100 focal i ndiaidh gach ceann. Ná húsáid ainm iomlán an táirge in ailt 1, 3 agus 5; cuir isteach go nádúrtha uair amháin é in ailt 2 agus 4. Críochnaigh le 3–10 sonraíocht theicniúil fhíoraithe, gan sonraí a chumadh.",
|
||||||
|
"meta": "Cuir tús leis an meiteathuairisc le hainm nua an táirge; uasmhéid 140 carachtar lena n-áirítear spásanna."
|
||||||
|
},
|
||||||
|
"ja": {
|
||||||
|
"title": "ブランド名は正式な表記、商品種別は適切な小文字表記、モデル名は正式表記、型番は大文字、色は判明している場合のみ一語で記載してください。カンマは使わないでください。",
|
||||||
|
"description": "異なる利点を示すH2見出しを5つ書き、各見出しの下に約100語相当の段落を置いてください。第1・3・5段落では商品名全体を繰り返さず、第2・4段落では自然に一度だけ含めてください。最後に確認済みの技術仕様を3~10項目列挙し、未確認の情報は作らないでください。",
|
||||||
|
"meta": "メタディスクリプションは新しい商品名から始め、空白を含めて最大140文字にしてください。"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
{
|
||||||
|
"en": {
|
||||||
|
"title": "{Brand with correct capitalization, product type in lowercase, complete model and uppercase model ID, then color as one word if known. No commas. Use only facts from {{name}}, {{description}} and {{attrs}}; keep official model codes, omit missing details and never invent features. Product name must be plain text, not HTML.}",
|
||||||
|
"description": "<p>{Introduce {{name}} in one useful paragraph. Explain its product type and purpose using {{description}} and {{attrs}}. Keep it concise (roughly 30–60 words if facts permit); do not repeat the title word for word or invent claims.}</p>\n<h2>{Write a short, specific H2 about the most useful documented feature or application, not a generic sales slogan. Do not repeat the product title. If no feature or use is supported beyond the product identity, omit this heading and the following feature paragraph.}</h2>\n<p>{Explain that feature using actual source details and how it matters in practice. Use a natural, non-repetitive paragraph of around 50–90 words only if the evidence supports it; be shorter when information is sparse. Do not add unverifiable benefits.}</p>\n<h2>{Write the localized heading “Technical specifications” only when at least one factual specification is available.}</h2>\n<ul><li>{List only confirmed specifications as separate list items, ideally “Property: value”. Keep original model codes, measurements and units. If there are no specifications, omit this H2 and the whole list; never output empty list item elements.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Create a distinct, concise SEO page title based on the product name and one useful differentiator if known. Avoid repetition and clickbait; aim for about 50–60 characters only when natural. Plain text, no HTML.\nmeta_description: Summarize what the product is and one or two verified characteristics in natural language. Include the exact model when relevant. Aim for 120–155 characters when facts allow, otherwise shorter; max 155 characters including spaces. No HTML, claims, keyword stuffing or cut-off words.}"
|
||||||
|
},
|
||||||
|
"fr": {
|
||||||
|
"title": "{Rédigez un titre de produit clair pour {{name}} à partir des {{attrs}} vérifiés. Marque avec la casse correcte, type de produit en minuscules, modèle complet et référence en majuscules, puis couleur en un seul mot si elle est connue. Sans virgules.}",
|
||||||
|
"description": "<p>{Présentez {{name}} en un court paragraphe : type de produit et usage, d’après {{description}} et {{attrs}}. Environ 30 à 60 mots si les données le permettent, sans recopier le titre ni inventer de faits.}</p>\n<h2>{Rédigez un H2 précis sur la caractéristique ou l’usage le mieux documenté, sans slogan vague ni répétition du nom complet. Si aucune caractéristique ou utilisation n’est démontrée, omettez ce H2 et le paragraphe suivant.}</h2>\n<p>{Expliquez cette caractéristique et son intérêt concret en 50 à 90 mots seulement si les données sont suffisantes. Sinon, soyez plus bref ; évitez les répétitions et les avantages non prouvés.}</p>\n<h2>{Rédigez le titre « Caractéristiques techniques » seulement si des données techniques sont disponibles.}</h2>\n<ul><li>{Listez uniquement les caractéristiques vérifiées, une par élément de liste, sous la forme « Propriété : valeur » si possible. Conservez les unités et références. Si aucune n’est disponible, omettez le H2 et toute la liste.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Rédigez un titre SEO distinct et concis avec le nom du produit et une caractéristique utile si elle est établie. Visez 50 à 60 caractères sans forcer. Texte brut, sans HTML.\nmeta_description: Résumez le produit et une ou deux caractéristiques confirmées. Visez 120 à 155 caractères si les faits le permettent, sinon soyez plus bref ; 155 caractères maximum, espaces compris. Sans HTML ni mots-clés répétés.}"
|
||||||
|
},
|
||||||
|
"de": {
|
||||||
|
"title": "{Verfasse einen klaren Produkttitel für {{name}} anhand geprüfter {{attrs}}. Marke korrekt schreiben, Produkttyp nach deutscher Rechtschreibung, vollständiges Modell mit Modellkennung in Großbuchstaben, danach die Farbe als ein Wort, falls bekannt. Keine Kommas.}",
|
||||||
|
"description": "<p>{Stelle {{name}} in einem kurzen Absatz mit Produkttyp und Verwendungszweck anhand von {{description}} und {{attrs}} vor. Etwa 30–60 Wörter nur bei ausreichenden Fakten; keine erfundenen Behauptungen und keine Titelwiederholung.}</p>\n<h2>{Formuliere eine konkrete H2 über die wichtigste belegte Eigenschaft oder Anwendung, ohne Werbefloskel oder vollständigen Produktnamen. Wenn kein Merkmal oder Einsatz belegt ist, diese H2 und den folgenden Absatz weglassen.}</h2>\n<p>{Erkläre diese Eigenschaft und ihren praktischen Nutzen anhand belegter Angaben. Etwa 50–90 Wörter nur wenn genug Informationen vorliegen; sonst kürzer und ohne Wiederholungen.}</p>\n<h2>{Schreibe die Überschrift „Technische Daten“ nur wenn technische Angaben vorhanden sind.}</h2>\n<ul><li>{Führe ausschließlich bestätigte Daten einzeln als Listeneintrag auf, möglichst „Merkmal: Wert“. Einheiten und Modellcodes unverändert lassen. Ohne Daten die Überschrift und Liste vollständig weglassen.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Erstelle einen eindeutigen, knappen SEO-Titel mit Produktname und belegtem Unterscheidungsmerkmal. Etwa 50–60 Zeichen, sofern sinnvoll; ohne HTML.\nmeta_description: Fasse Produkttyp und ein bis zwei bestätigte Eigenschaften natürlich zusammen. Wenn möglich 120–155 Zeichen, sonst kürzer; maximal 155 einschließlich Leerzeichen. Kein HTML, keine Wiederholungen oder unbelegten Aussagen.}"
|
||||||
|
},
|
||||||
|
"es": {
|
||||||
|
"title": "{Redacta un título de producto claro para {{name}} utilizando {{attrs}} verificados. Marca con mayúsculas correctas, tipo de producto en minúsculas, modelo completo e identificador del modelo en mayúsculas y color en una sola palabra si se conoce. Sin comas.}",
|
||||||
|
"description": "<p>{Presenta {{name}} en un párrafo breve indicando el tipo de producto y su uso, basándote en {{description}} y {{attrs}}. Unas 30–60 palabras solo si hay datos suficientes; sin repetir el título ni inventar información.}</p>\n<h2>{Escribe un H2 concreto sobre la característica o aplicación mejor documentada, sin eslóganes genéricos ni repetir el nombre completo. Si no hay una característica o uso confirmado, omite este H2 y el párrafo siguiente.}</h2>\n<p>{Explica esa característica y su utilidad práctica con hechos verificados. Usa unas 50–90 palabras si hay suficiente información, o menos si faltan datos; evita repeticiones.}</p>\n<h2>{Escribe el encabezado « Especificaciones técnicas » solo si existen especificaciones verificadas.}</h2>\n<ul><li>{Incluye solo datos confirmados, cada uno en un elemento de lista, preferiblemente « Característica: valor ». Conserva unidades y referencias; si no hay datos, omite el H2 y la lista completos.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Crea un título SEO conciso y específico con el nombre del producto y una característica demostrable. Unas 50–60 letras si resulta natural; sin HTML.\nmeta_description: Resume qué es el producto y una o dos características verificadas. Apunta a 120–155 caracteres si hay datos; máximo 155 con espacios. Sin HTML, repeticiones ni afirmaciones inventadas.}"
|
||||||
|
},
|
||||||
|
"it": {
|
||||||
|
"title": "{Scrivi un titolo di prodotto chiaro per {{name}} usando {{attrs}} verificati. Marchio con maiuscole corrette, tipo di prodotto in minuscolo, modello completo e codice modello in maiuscolo, poi colore in una parola se noto. Senza virgole.}",
|
||||||
|
"description": "<p>{Introduci {{name}} con un paragrafo breve sul tipo di prodotto e il suo utilizzo, usando {{description}} e {{attrs}}. Circa 30–60 parole solo se supportate dai dati, senza ripetere il titolo né inventare informazioni.}</p>\n<h2>{Scrivi un H2 specifico sulla caratteristica o sull’impiego meglio documentato, evitando slogan generici e il nome completo. Se nessuna caratteristica o uso è documentato, ometti questo H2 e il paragrafo seguente.}</h2>\n<p>{Spiega la caratteristica e il suo vantaggio pratico con fatti verificati. Circa 50–90 parole solo se ci sono informazioni sufficienti; altrimenti resta conciso e non ripeterti.}</p>\n<h2>{Scrivi « Specifiche tecniche » soltanto se sono presenti caratteristiche tecniche verificate.}</h2>\n<ul><li>{Elenca soltanto dati accertati, uno per elemento della lista, preferibilmente « Caratteristica: valore ». Mantieni unità e codici; in assenza di dati ometti sia H2 sia elenco.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Crea un titolo SEO chiaro e specifico con nome del prodotto e una caratteristica comprovata. Circa 50–60 caratteri se naturale; niente HTML.\nmeta_description: Riassumi prodotto e una o due caratteristiche verificate. Circa 120–155 caratteri se i dati lo consentono, massimo 155 spazi inclusi. Niente HTML o parole chiave ripetute.}"
|
||||||
|
},
|
||||||
|
"nl": {
|
||||||
|
"title": "{Schrijf een duidelijke producttitel voor {{name}} op basis van gecontroleerde {{attrs}}. Merk met juiste hoofdletters, producttype in kleine letters, volledig model met modelcode in hoofdletters, daarna kleur als één woord indien bekend. Geen komma’s.}",
|
||||||
|
"description": "<p>{Introduceer {{name}} in een korte alinea met producttype en toepassing op basis van {{description}} en {{attrs}}. Ongeveer 30–60 woorden als de feiten dat toelaten; herhaal de titel niet en verzin niets.}</p>\n<h2>{Schrijf een specifieke H2 over de best onderbouwde eigenschap of toepassing; geen algemene reclametaal of herhaling van de hele productnaam. Als er geen bevestigde eigenschap of toepassing is, laat deze H2 en de volgende alinea weg.}</h2>\n<p>{Leg de eigenschap en het praktische nut uit met geverifieerde gegevens. Gebruik circa 50–90 woorden alleen bij voldoende informatie; anders korter en zonder herhaling.}</p>\n<h2>{Gebruik de kop ‘Technische specificaties’ alleen wanneer er bevestigde specificaties zijn.}</h2>\n<ul><li>{Zet alleen geverifieerde gegevens elk in een afzonderlijke lijstitem, liefst ‘Kenmerk: waarde’. Behoud eenheden en modelcodes. Zonder gegevens de kop én lijst weglaten.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Maak een unieke, beknopte SEO-titel met de productnaam en een bewezen onderscheidend kenmerk. Streef waar passend naar 50–60 tekens; geen HTML.\nmeta_description: Vat het product en een of twee bewezen kenmerken samen. Streef naar 120–155 tekens als er genoeg gegevens zijn; maximaal 155 inclusief spaties. Geen HTML of zoekwoordherhaling.}"
|
||||||
|
},
|
||||||
|
"pt": {
|
||||||
|
"title": "{Escreve um título de produto claro para {{name}} com base em {{attrs}} verificados. Marca com capitalização correta, tipo de produto em minúsculas, modelo completo e código do modelo em maiúsculas e cor numa única palavra, se conhecida. Sem vírgulas.}",
|
||||||
|
"description": "<p>{Apresenta {{name}} num parágrafo breve com o tipo de produto e a finalidade, com base em {{description}} e {{attrs}}. Cerca de 30–60 palavras se houver dados suficientes; não repitas o título nem inventes factos.}</p>\n<h2>{Escreve um H2 específico sobre a característica ou aplicação mais bem documentada, sem slogans vagos nem repetir o nome completo. Se não houver característica ou uso comprovado, omite este H2 e o parágrafo seguinte.}</h2>\n<p>{Explica a característica e a utilidade prática com dados confirmados. Usa 50–90 palavras apenas se houver informação suficiente; caso contrário, escreve menos e evita repetições.}</p>\n<h2>{Usa o título « Especificações técnicas » apenas se houver especificações confirmadas.}</h2>\n<ul><li>{Apresenta apenas características verificadas, uma por item da lista, idealmente « Atributo: valor ». Mantém unidades e códigos; sem dados, omite o H2 e a lista.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Cria um título SEO claro e distinto com o nome do produto e uma característica comprovada. Aponta a 50–60 caracteres se fizer sentido; sem HTML.\nmeta_description: Resume o produto e uma ou duas características confirmadas. Idealmente 120–155 caracteres quando houver dados, no máximo 155 com espaços. Sem HTML ou repetição de palavras-chave.}"
|
||||||
|
},
|
||||||
|
"pl": {
|
||||||
|
"title": "{Napisz jasny tytuł produktu {{name}}, korzystając ze zweryfikowanych {{attrs}}. Marka z poprawną pisownią, typ produktu małymi literami, pełny model i jego kod wielkimi literami, a następnie kolor jednym słowem, jeśli jest znany. Bez przecinków.}",
|
||||||
|
"description": "<p>{Przedstaw {{name}} w krótkim akapicie: typ produktu i zastosowanie na podstawie {{description}} oraz {{attrs}}. Około 30–60 słów tylko przy wystarczających danych; nie powtarzaj tytułu i niczego nie wymyślaj.}</p>\n<h2>{Zapisz konkretny nagłówek H2 o najlepiej potwierdzonej cesze lub zastosowaniu, bez pustych sloganów i powtarzania pełnej nazwy. Jeśli żadna cecha ani zastosowanie nie są potwierdzone, pomiń ten H2 i następny akapit.}</h2>\n<p>{Wyjaśnij cechę i jej praktyczne znaczenie na podstawie potwierdzonych faktów. Około 50–90 słów, gdy dane na to pozwalają; w przeciwnym razie krócej i bez powtórzeń.}</p>\n<h2>{Użyj nagłówka „Dane techniczne” wyłącznie wtedy, gdy są potwierdzone parametry.}</h2>\n<ul><li>{Wymień tylko sprawdzone dane, po jednej pozycji listy, najlepiej „Parametr: wartość”. Zachowaj jednostki i symbole modeli. Bez danych pomiń nagłówek i listę.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Utwórz unikalny, krótki tytuł SEO z nazwą produktu i potwierdzoną cechą wyróżniającą. Około 50–60 znaków, jeśli naturalne; bez HTML.\nmeta_description: Podsumuj produkt i jedną lub dwie sprawdzone cechy. Celuj w 120–155 znaków, gdy są dane; maksymalnie 155 ze spacjami. Bez HTML i upychania słów kluczowych.}"
|
||||||
|
},
|
||||||
|
"cs": {
|
||||||
|
"title": "{Napište výstižný název produktu {{name}} podle ověřených {{attrs}}. Značku napiš se správnými velkými písmeny, typ výrobku malými písmeny, celý model a jeho kód velkými písmeny a barvu jedním slovem, je-li známá. Bez čárek.}",
|
||||||
|
"description": "<p>{Představ {{name}} krátkým odstavcem s typem výrobku a použitím podle {{description}} a {{attrs}}. Asi 30–60 slov pouze při dostatku údajů; neopakuj celý název ani si nic nevymýšlej.}</p>\n<h2>{Napiš konkrétní nadpis H2 o nejlépe doložené vlastnosti či využití, bez obecného reklamního hesla a opakování názvu. Pokud není doložena žádná vlastnost ani použití, vynech tento H2 i následující odstavec.}</h2>\n<p>{Vysvětli vlastnost a její praktický význam jen na základě ověřených údajů. Přibližně 50–90 slov, pokud je dost informací; jinak kratší text bez opakování.}</p>\n<h2>{Nadpis „Technické parametry“ použij jen tehdy, pokud jsou potvrzené údaje.}</h2>\n<ul><li>{Vypiš pouze ověřené údaje samostatně do položky seznamu, nejlépe „Parametr: hodnota“. Zachovej jednotky a označení modelů. Pokud nejsou, vynech nadpis i seznam.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Vytvoř jedinečný stručný SEO titulek s názvem výrobku a doloženou vlastností. Přibližně 50–60 znaků, pokud to dává smysl; bez HTML.\nmeta_description: Shrň výrobek a jednu či dvě ověřené vlastnosti. Ideálně 120–155 znaků, pokud jsou podklady; maximálně 155 včetně mezer. Bez HTML a opakování klíčových slov.}"
|
||||||
|
},
|
||||||
|
"sk": {
|
||||||
|
"title": "{Napíšte výstižný názov produktu {{name}} podľa overených {{attrs}}. Značku uveď so správnymi veľkými písmenami, typ výrobku malými písmenami, úplný model a jeho kód veľkými písmenami a farbu jedným slovom, ak je známa. Bez čiarok.}",
|
||||||
|
"description": "<p>{Predstav {{name}} krátkym odsekom s typom výrobku a použitím podľa {{description}} a {{attrs}}. Asi 30–60 slov len pri dostatku údajov; neopakuj celý názov a nič si nevymýšľaj.}</p>\n<h2>{Napíš konkrétny nadpis H2 o najlepšie doloženej vlastnosti alebo použití, bez všeobecných sloganov a opakovania názvu. Ak nie je potvrdená vlastnosť ani použitie, vynechaj tento H2 aj nasledujúci odsek.}</h2>\n<p>{Vysvetli vlastnosť a jej praktický význam na základe overených údajov. Približne 50–90 slov, ak je dosť informácií; inak kratšie, bez opakovania.}</p>\n<h2>{Nadpis „Technické parametre“ použi len vtedy, keď sú potvrdené údaje.}</h2>\n<ul><li>{Uveď iba overené údaje, každý v samostatnej položke zoznamu, najlepšie „Parameter: hodnota“. Zachovaj jednotky a kódy modelov. Bez údajov vynechaj nadpis aj zoznam.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Vytvor jedinečný stručný SEO titulok s názvom výrobku a potvrdenou vlastnosťou. Približne 50–60 znakov, ak je to prirodzené; bez HTML.\nmeta_description: Zhrň výrobok a jednu či dve potvrdené vlastnosti. Ideálne 120–155 znakov, ak je dosť údajov; najviac 155 vrátane medzier. Bez HTML a opakovania kľúčových slov.}"
|
||||||
|
},
|
||||||
|
"hu": {
|
||||||
|
"title": "{Írj egyértelmű termékcímet a(z) {{name}} számára az ellenőrzött {{attrs}} alapján. A márkanevet helyes nagybetűzéssel, a terméktípust kisbetűkkel, a teljes modellt és modellszámot nagybetűs azonosítóval, a színt pedig egy szóban add meg, ha ismert. Vessző nélkül.}",
|
||||||
|
"description": "<p>{Mutasd be a(z) {{name}} terméket egy rövid bekezdésben: típusa és felhasználása a {{description}} és {{attrs}} alapján. Kb. 30–60 szó csak elegendő adat esetén; ne ismételd a címet, és ne találj ki tényeket.}</p>\n<h2>{Adj konkrét H2 címet a legjobban igazolt tulajdonságról vagy felhasználásról, általános reklámszöveg és teljes névismétlés nélkül. Ha nincs igazolt tulajdonság vagy alkalmazás, hagyd el ezt a H2 címet és a következő bekezdést.}</h2>\n<p>{Magyarázd el a tulajdonság gyakorlati jelentőségét igazolt adatokkal. Csak megfelelő információ esetén írj 50–90 szót; egyébként légy rövidebb, ismétlések nélkül.}</p>\n<h2>{A „Műszaki adatok” címet csak akkor írd ki, ha vannak igazolt adatok.}</h2>\n<ul><li>{Csak ellenőrzött adatokat sorolj fel külön listaelem elemekben, lehetőleg „Jellemző: érték” formában. Mértékegységeket és típuskódokat őrizd meg; adatok hiányában hagyd el a címet és a listát.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Készíts egyedi, rövid SEO-címet a terméknévvel és egy igazolt megkülönböztető jellemzővel. Kb. 50–60 karakter, ha természetes; HTML nélkül.\nmeta_description: Foglald össze a terméket és egy-két ellenőrzött jellemzőjét. Ha lehet, 120–155 karakter; legfeljebb 155 szóközökkel együtt. HTML és kulcsszóhalmozás nélkül.}"
|
||||||
|
},
|
||||||
|
"ro": {
|
||||||
|
"title": "{Scrie un titlu clar pentru produsul {{name}}, folosind {{attrs}} verificate. Marca scrisă corect, tipul produsului cu litere mici, modelul complet și codul modelului cu majuscule, apoi culoarea într-un singur cuvânt, dacă este cunoscută. Fără virgule.}",
|
||||||
|
"description": "<p>{Prezintă {{name}} într-un paragraf scurt: tipul produsului și utilizarea sa, pe baza {{description}} și {{attrs}}. Aproximativ 30–60 de cuvinte dacă există date, fără a repeta titlul sau a inventa detalii.}</p>\n<h2>{Scrie un H2 concret despre caracteristica ori utilizarea cea mai bine documentată, fără sloganuri vagi sau repetarea numelui complet. Dacă nu există caracteristică sau utilizare confirmată, omite acest H2 și paragraful următor.}</h2>\n<p>{Explică acea caracteristică și utilitatea ei practică pe baza datelor confirmate. Circa 50–90 de cuvinte numai dacă există suficiente informații; altfel mai scurt, fără repetiții.}</p>\n<h2>{Folosește subtitlul „Specificații tehnice” numai când există date confirmate.}</h2>\n<ul><li>{Enumeră doar specificații verificate, fiecare într-un element de listă, ideal „Caracteristică: valoare”. Păstrează unitățile și codurile; în lipsa lor, omite subtitlul și lista.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Creează un titlu SEO unic și concis cu numele produsului și o caracteristică demonstrată. Circa 50–60 de caractere, dacă sună natural; fără HTML.\nmeta_description: Rezumă produsul și una sau două caracteristici confirmate. 120–155 de caractere dacă datele permit, cel mult 155 cu spații. Fără HTML sau repetiții de cuvinte-cheie.}"
|
||||||
|
},
|
||||||
|
"bg": {
|
||||||
|
"title": "{Напиши ясно заглавие на продукта {{name}}, като използваш проверените {{attrs}}. Марката с правилни главни букви, видът на продукта с малки букви, пълният модел и кодът му с главни букви, а след това цветът с една дума, ако е известен. Без запетаи.}",
|
||||||
|
"description": "<p>{Представи {{name}} с кратък абзац за вида и предназначението въз основа на {{description}} и {{attrs}}. Около 30–60 думи само при достатъчно данни; без повторение на заглавието и измислени твърдения.}</p>\n<h2>{Напиши конкретно H2 заглавие за най-добре потвърдената характеристика или употреба, без общи рекламни фрази и пълното име. Ако няма потвърдена характеристика или употреба, пропусни това H2 и следващия абзац.}</h2>\n<p>{Обясни характеристиката и практическата ѝ полза с доказани данни. Около 50–90 думи само ако има информация; иначе по-кратко и без повтаряне.}</p>\n<h2>{Използвай заглавие „Технически характеристики“ само при потвърдени данни.}</h2>\n<ul><li>{Изброй само проверени данни поотделно в елемент от списъка, за предпочитане „Показател: стойност“. Запази мерните единици и кодовете; при липса на данни пропусни заглавието и списъка.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Създай кратко уникално SEO заглавие с името и проверена отличителна характеристика. Около 50–60 знака, ако е естествено; без HTML.\nmeta_description: Обобщи продукта и една-две потвърдени характеристики. Около 120–155 знака при налични данни, максимум 155 с интервалите. Без HTML и повтаряне на ключови думи.}"
|
||||||
|
},
|
||||||
|
"hr": {
|
||||||
|
"title": "{Napiši jasan naziv proizvoda {{name}} koristeći provjerene {{attrs}}. Marku napiši s pravilnim velikim slovima, vrstu proizvoda malim slovima, puni model i oznaku modela velikim slovima, a zatim boju jednom riječju ako je poznata. Bez zareza.}",
|
||||||
|
"description": "<p>{Predstavi {{name}} u kratkom odlomku: vrstu proizvoda i namjenu prema {{description}} i {{attrs}}. Otprilike 30–60 riječi samo ako ima dovoljno podataka. Ne prepisuj puni naslov niti izmišljaj tvrdnje.}</p>\n<h2>{Napiši konkretan H2 naslov o najvažnijoj potvrđenoj značajci ili primjeni, bez općih marketinških fraza i ponavljanja cijelog naziva. Ako nema potvrđene značajke ili primjene, izostavi ovaj H2 naslov i sljedeći odlomak.}</h2>\n<p>{Objasni tu značajku i njezinu praktičnu korist na temelju potvrđenih podataka. Oko 50–90 riječi samo kad ima dovoljno činjenica, inače kraće; ne ponavljaj uvod.}</p>\n<h2>{Napiši naslov „Tehničke specifikacije” samo ako postoje potvrđeni tehnički podaci.}</h2>\n<ul><li>{Navedi isključivo provjerene podatke, svaki u zasebnom stavci popisa, po mogućnosti „Svojstvo: vrijednost”. Sačuvaj mjerne jedinice i oznake modela. Ako podataka nema, izostavi i naslov i popis.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Napiši jedinstven, jasan SEO naslov s nazivom proizvoda i jednom potvrđenom razlikovnom značajkom. Ciljaj na 50–60 znakova samo ako zvuči prirodno; bez HTML-a.\nmeta_description: Prirodno sažmi proizvod i jednu ili dvije potvrđene značajke. Ciljaj na 120–155 znakova ako je moguće, najviše 155 uključujući razmake. Bez HTML-a, izmišljanja ili gomilanja ključnih riječi.}"
|
||||||
|
},
|
||||||
|
"sl": {
|
||||||
|
"title": "{Napiši jasen naslov izdelka {{name}} na podlagi preverjenih {{attrs}}. Znamko zapiši s pravilnimi velikimi črkami, tip izdelka z malimi črkami, celoten model in oznako modela z velikimi črkami, nato barvo z eno besedo, če je znana. Brez vejic.}",
|
||||||
|
"description": "<p>{V kratkem uvodnem odstavku predstavi {{name}}: vrsto izdelka in namen uporabe na podlagi {{description}} ter {{attrs}}. Približno 30–60 besed, če podatki to omogočajo. Ne prepisuj celotnega naslova in ne dodajaj nepotrjenih trditev.}</p>\n<h2>{Napiši konkreten naslov H2 o najpomembnejši preverjeni lastnosti ali uporabi. Ne ponavljaj celotnega imena izdelka in ne uporabljaj splošnih oglaševalskih fraz. Če ni nobene potrjene lastnosti ali uporabe, izpusti ta naslov H2 in naslednji odstavek.}</h2>\n<p>{Razloži to lastnost in njen praktični pomen na podlagi preverjenih podatkov. Približno 50–90 besed samo, če je dovolj dejstev, sicer napiši krajši odstavek. Ne ponavljaj uvoda.}</p>\n<h2>{Naslov »Tehnične specifikacije« napiši le, če so na voljo preverjeni tehnični podatki.}</h2>\n<ul><li>{Navedi samo potrjene tehnične podatke, vsakega v svojem elementu alineji, po možnosti »Lastnost: vrednost«. Ohrani enote in modelne oznake. Če podatkov ni, izpusti naslov in celoten seznam.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Napiši edinstven in jedrnat SEO naslov z imenom izdelka in eno dokazano razlikovalno lastnostjo. Približno 50–60 znakov, če zveni naravno; brez HTML-ja.\nmeta_description: V eni naravni povedi povzemi izdelek in eno ali dve potrjeni lastnosti. Približno 120–155 znakov, če je dovolj podatkov; največ 155 s presledki. Brez HTML-ja, izmišljanja in kopičenja ključnih besed.}"
|
||||||
|
},
|
||||||
|
"sv": {
|
||||||
|
"title": "{Skriv en tydlig produkttitel för {{name}} med hjälp av verifierade {{attrs}}. Skriv varumärket med rätt stora bokstäver, produkttypen med gemener, fullständig modell och modellkod med versaler samt färgen som ett ord om den är känd. Inga kommatecken.}",
|
||||||
|
"description": "<p>{Presentera {{name}} i ett kort stycke med produkttyp och användning utifrån {{description}} och {{attrs}}. Cirka 30–60 ord om fakta räcker; upprepa inte rubriken och hitta inte på uppgifter.}</p>\n<h2>{Skriv en tydlig H2 om den bäst belagda egenskapen eller användningen, utan generiska säljklyschor eller upprepning av hela produktnamnet. Om ingen egenskap eller användning är bekräftad, utelämna denna H2 och följande stycke.}</h2>\n<p>{Förklara egenskapen och dess praktiska betydelse med verifierade uppgifter. Cirka 50–90 ord bara om materialet räcker; annars kortare och utan upprepningar.}</p>\n<h2>{Använd rubriken ”Tekniska specifikationer” endast om det finns verifierade uppgifter.}</h2>\n<ul><li>{Lista bara bekräftade specifikationer, en per listpunkt, helst ”Egenskap: värde”. Behåll enheter och modellkoder. Finns inga uppgifter ska både rubrik och lista utelämnas.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Skriv en unik och kort SEO-titel med produktnamnet och en dokumenterad särskiljande egenskap. Cirka 50–60 tecken där det passar, utan HTML.\nmeta_description: Sammanfatta produkten och en eller två bekräftade egenskaper. Sikta på 120–155 tecken om fakta räcker, max 155 inklusive blanksteg. Utan HTML eller upprepade nyckelord.}"
|
||||||
|
},
|
||||||
|
"da": {
|
||||||
|
"title": "{Skriv en tydelig produkttitel til {{name}} med udgangspunkt i verificerede {{attrs}}. Skriv mærket med korrekt brug af store bogstaver, produkttypen med små bogstaver, den fulde model og modelkode med store bogstaver samt farven som ét ord, hvis den kendes. Ingen kommaer.}",
|
||||||
|
"description": "<p>{Præsenter {{name}} i et kort afsnit med produkttype og anvendelse ud fra {{description}} og {{attrs}}. Omkring 30–60 ord, hvis fakta rækker; gentag ikke hele titlen og opfind ikke oplysninger.}</p>\n<h2>{Skriv en konkret H2 om den bedst dokumenterede egenskab eller brug, uden generiske salgsfraser eller gentagelse af hele navnet. Hvis ingen egenskab eller brug er dokumenteret, udelad denne H2 og det følgende afsnit.}</h2>\n<p>{Forklar egenskaben og dens praktiske værdi med verificerede oplysninger. Omkring 50–90 ord kun ved tilstrækkelige fakta, ellers kortere og uden gentagelser.}</p>\n<h2>{Brug overskriften »Tekniske specifikationer« kun hvis der findes bekræftede data.}</h2>\n<ul><li>{Angiv kun kontrollerede specifikationer, en pr. listepunkt, gerne »Egenskab: værdi«. Bevar enheder og modelkoder. Uden data udelades både overskrift og liste.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Lav en unik, kort SEO-titel med produktnavn og et dokumenteret kendetegn. Omkring 50–60 tegn hvis naturligt; ingen HTML.\nmeta_description: Opsummér produktet og en eller to verificerede egenskaber. Omkring 120–155 tegn hvis muligt, højst 155 inklusive mellemrum. Ingen HTML eller gentagne søgeord.}"
|
||||||
|
},
|
||||||
|
"fi": {
|
||||||
|
"title": "{Kirjoita selkeä tuotteen {{name}} nimi vahvistettujen {{attrs}}-tietojen perusteella. Kirjoita tuotemerkki oikealla kirjainkoolla, tuotetyyppi pienillä kirjaimilla, koko malli ja mallikoodi isoilla kirjaimilla sekä väri yhtenä sanana, jos se tiedetään. Ei pilkkuja.}",
|
||||||
|
"description": "<p>{Esittele {{name}} lyhyessä kappaleessa: tuotetyyppi ja käyttötarkoitus {{description}}- ja {{attrs}}-tietojen pohjalta. Noin 30–60 sanaa vain tietojen riittäessä; älä toista nimeä tai keksi väitteitä.}</p>\n<h2>{Kirjoita täsmällinen H2-otsikko parhaiten varmennetusta ominaisuudesta tai käyttötavasta, ei yleistä mainoslausetta tai koko tuotenimen toistoa. Jos ominaisuudesta tai käyttötavasta ei ole vahvistettua tietoa, jätä tämä H2 ja seuraava kappale pois.}</h2>\n<p>{Kerro ominaisuuden käytännön merkityksestä vahvistetuilla tiedoilla. Noin 50–90 sanaa vain, jos tietoja riittää; muussa tapauksessa lyhyemmin ilman toistoa.}</p>\n<h2>{Käytä otsikkoa ”Tekniset tiedot” vain, jos vahvistettuja teknisiä tietoja on saatavilla.}</h2>\n<ul><li>{Luettele vain tarkistetut tiedot erillisiin luettelokohtiin, mieluiten ”Ominaisuus: arvo”. Säilytä yksiköt ja mallikoodit. Ilman tietoja jätä otsikko ja luettelo pois.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Laadi yksilöllinen, ytimekäs SEO-otsikko tuotteen nimellä ja varmennetulla erottavalla ominaisuudella. Noin 50–60 merkkiä jos luontevaa; ei HTML:ää.\nmeta_description: Kuvaa tuote ja yksi tai kaksi vahvistettua ominaisuutta. Pyri 120–155 merkkiin, jos tietoja on; enintään 155 välilyönteineen. Ei HTML:ää eikä avainsanojen toistoa.}"
|
||||||
|
},
|
||||||
|
"el": {
|
||||||
|
"title": "{Γράψε έναν σαφή τίτλο προϊόντος για το {{name}} με βάση τα επαληθευμένα {{attrs}}. Γράψε τη μάρκα με σωστά κεφαλαία, τον τύπο προϊόντος με πεζά, το πλήρες μοντέλο και τον κωδικό μοντέλου με κεφαλαία και έπειτα το χρώμα με μία λέξη, εφόσον είναι γνωστό. Χωρίς κόμματα.}",
|
||||||
|
"description": "<p>{Παρουσίασε το {{name}} με σύντομη παράγραφο για τον τύπο και τη χρήση του, βάσει των {{description}} και {{attrs}}. Περίπου 30–60 λέξεις μόνο με επαρκή στοιχεία, χωρίς επανάληψη του τίτλου ή επινοήσεις.}</p>\n<h2>{Γράψε συγκεκριμένο τίτλο H2 για το καλύτερα τεκμηριωμένο χαρακτηριστικό ή τη χρήση, χωρίς γενικά διαφημιστικά συνθήματα. Αν δεν υπάρχει τεκμηριωμένο χαρακτηριστικό ή χρήση, παράλειψε αυτό το H2 και την επόμενη παράγραφο.}</h2>\n<p>{Εξήγησε το χαρακτηριστικό και την πρακτική αξία του με επιβεβαιωμένα στοιχεία. Περίπου 50–90 λέξεις μόνο αν επαρκούν οι πληροφορίες· διαφορετικά συντομότερα, χωρίς επαναλήψεις.}</p>\n<h2>{Χρησιμοποίησε τον τίτλο «Τεχνικά χαρακτηριστικά» μόνο εφόσον υπάρχουν επιβεβαιωμένα δεδομένα.}</h2>\n<ul><li>{Παράθεσε μόνο επαληθευμένα στοιχεία, ένα ανά στοιχείο λίστας, ιδανικά «Χαρακτηριστικό: τιμή». Διατήρησε μονάδες και κωδικούς. Χωρίς στοιχεία παράλειψε και τον τίτλο και τη λίστα.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Δημιούργησε μοναδικό, σύντομο τίτλο SEO με το όνομα του προϊόντος και τεκμηριωμένη διαφορά. Περίπου 50–60 χαρακτήρες εφόσον φυσικό· χωρίς HTML.\nmeta_description: Συνόψισε το προϊόν και ένα ή δύο επιβεβαιωμένα χαρακτηριστικά. 120–155 χαρακτήρες όπου είναι δυνατό, μέγιστο 155 μαζί με κενά. Χωρίς HTML ή επανάληψη λέξεων-κλειδιών.}"
|
||||||
|
},
|
||||||
|
"et": {
|
||||||
|
"title": "{Kirjuta tootele {{name}} selge pealkiri, kasutades kontrollitud {{attrs}} andmeid. Kirjuta kaubamärk õige suur- ja väiketähekasutusega, tootetüüp väiketähtedega, täielik mudel ja mudelikood suurtähtedega ning värv ühe sõnana, kui see on teada. Ilma komadeta.}",
|
||||||
|
"description": "<p>{Tutvusta {{name}} lühikeses lõigus, kirjeldades tooteliiki ja kasutust {{description}} ning {{attrs}} põhjal. Umbes 30–60 sõna vaid piisavate faktide korral; ära korda pealkirja ega mõtle omadusi välja.}</p>\n<h2>{Kirjuta täpne H2 kõige paremini tõendatud omaduse või kasutusviisi kohta, ilma üldise reklaamlause ja täieliku tootenime korduseta. Kui ühtki omadust või kasutust pole kinnitatud, jäta see H2 ja järgmine lõik ära.}</h2>\n<p>{Selgita omadust ja praktilist väärtust kontrollitud faktidega. Umbes 50–90 sõna ainult piisava teabe korral; muidu lühemalt ja kordusteta.}</p>\n<h2>{Kasuta pealkirja „Tehnilised andmed” ainult siis, kui kinnitatud andmed on olemas.}</h2>\n<ul><li>{Loetle ainult kontrollitud andmed eraldi loendikirje-elementides, näiteks „Omadus: väärtus”. Säilita ühikud ja mudelikoodid. Kui andmeid pole, jäta pealkiri ja loend ära.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Koosta ainulaadne lühike SEO-pealkiri tootenime ja tõendatud eristava omadusega. Umbes 50–60 märki, kui sobib; ilma HTML-ita.\nmeta_description: Võta toode ja üks-kaks tõendatud omadust kokku. Võimalusel 120–155 märki, maksimaalselt 155 koos tühikutega. Ilma HTML-i ja märksõnade kordamiseta.}"
|
||||||
|
},
|
||||||
|
"lv": {
|
||||||
|
"title": "{Uzraksti skaidru produkta {{name}} nosaukumu, izmantojot pārbaudītos {{attrs}}. Zīmolu raksti ar pareiziem lielajiem burtiem, produkta veidu ar mazajiem burtiem, pilnu modeli un modeļa kodu ar lielajiem burtiem, bet krāsu vienā vārdā, ja tā zināma. Bez komatiem.}",
|
||||||
|
"description": "<p>{Īsā rindkopā iepazīstini ar {{name}}, norādot produkta veidu un lietojumu, izmantojot {{description}} un {{attrs}}. Apmēram 30–60 vārdu, ja pietiek faktu; neatkārto visu virsrakstu un neko neizdomā.}</p>\n<h2>{Izveido konkrētu H2 par vislabāk apstiprināto īpašību vai lietojumu, bez vispārīgiem reklāmas saukļiem un pilnā nosaukuma atkārtošanas. Ja nav apstiprinātas īpašības vai lietojuma, izlaid šo H2 un nākamo rindkopu.}</h2>\n<p>{Izskaidro īpašību un tās praktisko nozīmi ar pārbaudītiem faktiem. Apmēram 50–90 vārdu, ja informācijas pietiek; citādi īsāk, bez atkārtošanās.}</p>\n<h2>{Virsrakstu „Tehniskā specifikācija” lieto tikai tad, ja ir apstiprināti dati.}</h2>\n<ul><li>{Uzskaiti tikai pārbaudītus parametrus atsevišķos saraksta vienībā, vēlams „Parametrs: vērtība”. Saglabā mērvienības un modeļu kodus. Bez datiem izlaid virsrakstu un sarakstu.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Izveido unikālu, īsu SEO virsrakstu ar produkta nosaukumu un apstiprinātu īpašību. Apmēram 50–60 rakstzīmes, ja dabiski; bez HTML.\nmeta_description: Apkopojiet produktu un vienu vai divas apstiprinātas īpašības. Ja var, 120–155 rakstzīmes, ne vairāk kā 155 ar atstarpēm. Bez HTML vai atslēgvārdu atkārtošanas.}"
|
||||||
|
},
|
||||||
|
"lt": {
|
||||||
|
"title": "{Parašyk aiškų produkto {{name}} pavadinimą pagal patikrintus {{attrs}}. Prekės ženklą rašyk taisyklingomis didžiosiomis raidėmis, gaminio tipą mažosiomis, pilną modelį ir modelio kodą didžiosiomis, o spalvą vienu žodžiu, jei žinoma. Be kablelių.}",
|
||||||
|
"description": "<p>{Trumpa pastraipa pristatyk {{name}}: produkto tipą ir paskirtį remdamasis {{description}} ir {{attrs}}. Apie 30–60 žodžių tik jei duomenų pakanka; nekartok pavadinimo ir neišgalvok faktų.}</p>\n<h2>{Parašyk konkretų H2 apie geriausiai patvirtintą savybę ar naudojimą, be bendrų reklaminių frazių ir viso pavadinimo kartojimo. Jei nėra patvirtintos savybės ar naudojimo, praleisk šį H2 ir kitą pastraipą.}</h2>\n<p>{Paaiškink savybę ir praktinę naudą tik patikrintais faktais. Apie 50–90 žodžių, jei duomenų pakanka; kitaip trumpiau ir be pasikartojimų.}</p>\n<h2>{Antraštę „Techninės specifikacijos” rašyk tik jei yra patvirtintų techninių duomenų.}</h2>\n<ul><li>{Išvardyk tik patikrintus parametrus atskiruose sąrašo elemente, geriausia „Savybė: vertė”. Išsaugok vienetus ir modelių kodus. Jei duomenų nėra, praleisk ir antraštę, ir sąrašą.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Sukurk unikalų, glaustą SEO pavadinimą su produkto vardu ir pagrįsta išskirtine savybe. Apie 50–60 simbolių, jei natūralu; be HTML.\nmeta_description: Apibendrink produktą ir vieną ar dvi patikrintas savybes. Jei įmanoma, 120–155 simboliai, daugiausia 155 su tarpais. Be HTML ar raktažodžių kartojimo.}"
|
||||||
|
},
|
||||||
|
"mt": {
|
||||||
|
"title": "{Ikteb titlu ċar għall-prodott {{name}} billi tuża {{attrs}} ivverifikati. Ikteb il-marka bil-kapitalizzazzjoni korretta, it-tip tal-prodott b’ittri żgħar, il-mudell sħiħ u l-kodiċi tiegħu b’ittri kbar, u l-kulur b’kelma waħda jekk magħruf. Bla virgoli.}",
|
||||||
|
"description": "<p>{Introduċi {{name}} f’paragrafu qasir bit-tip ta’ prodott u l-użu tiegħu, skont {{description}} u {{attrs}}. Madwar 30–60 kelma jekk hemm biżżejjed fatti; irrepetix it-titlu kollu u tivvintax dettalji.}</p>\n<h2>{Ikteb intestatura H2 speċifika dwar il-karatteristika jew l-użu l-aktar dokumentat, mhux slogan ġeneriku jew ripetizzjoni tal-isem kollu. Jekk m’hemmx karatteristika jew użu vverifikat, ħalli barra dan il-H2 u l-paragrafu ta’ warajh.}</h2>\n<p>{Spjega l-karatteristika u l-utilità prattika tagħha b’fatti kkonfermati. Madwar 50–90 kelma biss jekk hemm data biżżejjed; inkella iqsar u bla ripetizzjonijiet.}</p>\n<h2>{Uża t-titlu “Speċifikazzjonijiet tekniċi” biss meta jkun hemm data kkonfermata.}</h2>\n<ul><li>{Elenka biss speċifikazzjonijiet ivverifikati, waħda f’kull punt tal-lista, idealment “Proprjetà: valur”. Żomm l-unitajiet u l-kodiċijiet. Jekk m’hemmx data, ħalli barra kemm l-intestatura kif ukoll il-lista.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Oħloq titlu SEO uniku u qasir bl-isem tal-prodott u karatteristika dokumentata. Madwar 50–60 karattru jekk naturali; bla HTML.\nmeta_description: Agħti sommarju tal-prodott u karatteristika waħda jew tnejn ivverifikati. Jekk possibbli 120–155 karattru, massimu 155 bl-ispazji. Bla HTML jew ripetizzjoni tal-kliem ewlieni.}"
|
||||||
|
},
|
||||||
|
"ga": {
|
||||||
|
"title": "{Scríobh teideal soiléir don táirge {{name}} bunaithe ar {{attrs}} fíoraithe. Scríobh an branda leis na ceannlitreacha cearta, cineál an táirge i litreacha beaga, an tsamhail iomlán agus a cód i gceannlitreacha, agus an dath in aon fhocal más eol é. Gan camóga.}",
|
||||||
|
"description": "<p>{Cuir {{name}} i láthair in alt gearr leis an gcineál táirge agus a úsáid bunaithe ar {{description}} agus {{attrs}}. Thart ar 30–60 focal nuair atá dóthain sonraí ann; ná déan an teideal a athrá ná sonraí a chumadh.}</p>\n<h2>{Scríobh ceannteideal H2 sonrach faoin tréith nó faoin úsáid is fearr atá deimhnithe, gan mana fógraíochta ná athrá ar ainm iomlán an táirge. Mura bhfuil gné ná úsáid deimhnithe ann, fág an H2 seo agus an chéad alt eile ar lár.}</h2>\n<p>{Mínigh an tréith agus a tairbhe phraiticiúil le fíricí deimhnithe. Thart ar 50–90 focal má tá dóthain sonraí ann; mura bhfuil, scríobh níos giorra agus seachain athrá.}</p>\n<h2>{Úsáid an ceannteideal “Sonraíochtaí teicniúla” ach amháin má tá sonraí fíoraithe ar fáil.}</h2>\n<ul><li>{Liostaigh sonraí deimhnithe amháin, ceann amháin i ngach mír liosta, mar “Airí: luach” más féidir. Coinnigh aonaid agus cóid mhúnla. Gan sonraí, fág an ceannteideal agus an liosta ar lár.}</li></ul>",
|
||||||
|
"meta": "{meta_title: Cruthaigh teideal SEO uathúil gonta le hainm an táirge agus tréith dheimhnithe. Thart ar 50–60 carachtar más nádúrtha; gan HTML.\nmeta_description: Déan achoimre ar an táirge agus tréith nó dhó atá fíoraithe. Más féidir 120–155 carachtar, uasmhéid 155 le spásanna. Gan HTML ná eochairfhocail athchleachtacha.}"
|
||||||
|
},
|
||||||
|
"ja": {
|
||||||
|
"title": "{確認済みの {{name}} と {{attrs}} を基に、正式なブランド名、商品種別、モデル名・型番、確認できた場合のみ色を含めた自然な商品名を作成してください。ブランドと型番の正式表記を維持し、不要な句読点や未確認の特長を加えないでください。HTML は使わないでください。}",
|
||||||
|
"description": "<p>{商品名 {{name}} の種類と用途を {{description}} と {{attrs}} の確認済み情報に基づいて短い導入段落で説明してください。情報が十分なら簡潔にまとめ、商品名全体の不自然な繰り返しや推測は避けてください。}</p>\n<h2>{最もよく裏付けられた特徴または用途を表す具体的な H2 見出しを書いてください。誇張した宣伝文句や商品名全体の繰り返しは避けてください。 特徴や用途を裏付ける情報がなければ、この H2 と続く段落を省略してください。}</h2>\n<p>{その特徴と実際の使い方を確認済みの情報だけで説明してください。情報が十分な場合は自然な長さにし、不足する場合は短くしてください。同じ内容を繰り返さないでください。}</p>\n<h2>{技術仕様が確認できる場合にのみ「製品仕様」に相当する見出しを書いてください。}</h2>\n<ul><li>{確認済みの仕様のみを 1 項目ずつ 箇条書き項目 に記載してください。可能なら「項目:値」とし、単位と型番は維持してください。仕様がなければ見出しとリスト全体を省略してください。}</li></ul>",
|
||||||
|
"meta": "{meta_title: 正式な商品名と確認済みの特徴を使って、固有で簡潔な SEO タイトルを作成してください。不自然な文字数調整は不要です。HTML は使用しないでください。\nmeta_description: 商品が何か、確認できた特徴を 1〜2 点、自然な日本語で要約してください。空白を含め 155 文字以内を目安とし、情報が少ない場合は短くしてください。HTML やキーワードの羅列は避けてください。}"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,12 +2,14 @@ package aiprompts
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
reLegacyHTMLBlock = regexp.MustCompile(`(?is)<\s*(h[1-4]|p|ul|ol|li|b|strong)\s*>\s*\{?\s*(.*?)\s*\}?\s*<\s*/\s*(?:h[1-4]|p|ul|ol|li|b|strong)\s*>`)
|
reLegacyHTMLBlock = regexp.MustCompile(`(?is)<\s*(h[1-4]|p|ul|ol|li|b|strong)\s*>\s*\{?\s*(.*?)\s*\}?\s*<\s*/\s*(?:h[1-4]|p|ul|ol|li|b|strong)\s*>`)
|
||||||
|
reLegacyList = regexp.MustCompile(`(?is)<\s*ul\s*>\s*<\s*li\s*>\s*\{?\s*(.*?)\s*\}?\s*<\s*/\s*li\s*>\s*<\s*/\s*ul\s*>`)
|
||||||
reLegacyBoldUL = regexp.MustCompile(`(?is)<\s*b\s*>\s*\{?\s*(.*?)\s*\}?\s*<\s*/\s*b\s*>\s*<\s*ul\s*>\s*<\s*li\s*>\s*\{?\s*(.*?)\s*\}?\s*<\s*/\s*li\s*>\s*<\s*/\s*ul\s*>`)
|
reLegacyBoldUL = regexp.MustCompile(`(?is)<\s*b\s*>\s*\{?\s*(.*?)\s*\}?\s*<\s*/\s*b\s*>\s*<\s*ul\s*>\s*<\s*li\s*>\s*\{?\s*(.*?)\s*\}?\s*<\s*/\s*li\s*>\s*<\s*/\s*ul\s*>`)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -21,6 +23,7 @@ func LegacyHTMLFormulaPresent(s string) bool {
|
|||||||
type DescriptionFormulaSection struct {
|
type DescriptionFormulaSection struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Instructions string `json:"instructions"`
|
Instructions string `json:"instructions"`
|
||||||
|
Optional bool `json:"optional,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DescriptionFormula is the JSON shape stored in categories.description_template
|
// DescriptionFormula is the JSON shape stored in categories.description_template
|
||||||
@@ -59,12 +62,15 @@ const DefaultMetaTitleRuleEN = "Start with the New product name and add the main
|
|||||||
// title rule, so meta intent (MetaRules present) also seeds a default metaTitle
|
// title rule, so meta intent (MetaRules present) also seeds a default metaTitle
|
||||||
// instruction — the category UI then shows all four prompt areas filled.
|
// instruction — the category UI then shows all four prompt areas filled.
|
||||||
func DeriveDescriptionFormulaFromLegacyParts(parts LegacyEnhanceParts) DescriptionFormula {
|
func DeriveDescriptionFormulaFromLegacyParts(parts LegacyEnhanceParts) DescriptionFormula {
|
||||||
out := DescriptionFormula{
|
out := DescriptionFormula{MetaDescription: strings.TrimSpace(parts.MetaRules)}
|
||||||
MetaDescription: strings.TrimSpace(parts.MetaRules),
|
|
||||||
}
|
|
||||||
if out.MetaDescription != "" {
|
if out.MetaDescription != "" {
|
||||||
|
if mt, md, ok := splitLocalizedMetaRules(out.MetaDescription); ok {
|
||||||
|
out.MetaTitle, out.MetaDescription = mt, md
|
||||||
|
} else {
|
||||||
out.MetaTitle = DefaultLegacyMetaTitleRule
|
out.MetaTitle = DefaultLegacyMetaTitleRule
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
body := strings.TrimSpace(parts.DescriptionRules)
|
body := strings.TrimSpace(parts.DescriptionRules)
|
||||||
if body == "" {
|
if body == "" {
|
||||||
return out
|
return out
|
||||||
@@ -74,7 +80,18 @@ func DeriveDescriptionFormulaFromLegacyParts(parts LegacyEnhanceParts) Descripti
|
|||||||
remaining := body
|
remaining := body
|
||||||
for remaining != "" {
|
for remaining != "" {
|
||||||
boldUL := reLegacyBoldUL.FindStringSubmatchIndex(remaining)
|
boldUL := reLegacyBoldUL.FindStringSubmatchIndex(remaining)
|
||||||
|
list := reLegacyList.FindStringSubmatchIndex(remaining)
|
||||||
block := reLegacyHTMLBlock.FindStringSubmatchIndex(remaining)
|
block := reLegacyHTMLBlock.FindStringSubmatchIndex(remaining)
|
||||||
|
if list != nil && (block == nil || list[0] <= block[0]) && (boldUL == nil || list[0] < boldUL[0]) {
|
||||||
|
m := reLegacyList.FindStringSubmatch(remaining[list[0]:list[1]])
|
||||||
|
if len(m) > 1 {
|
||||||
|
if instr := cleanLegacyInstruction(m[1]); instr != "" {
|
||||||
|
out.Sections = append(out.Sections, DescriptionFormulaSection{Type: "ul", Instructions: instr, Optional: true})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
remaining = remaining[list[1]:]
|
||||||
|
continue
|
||||||
|
}
|
||||||
switch {
|
switch {
|
||||||
case boldUL != nil && (block == nil || boldUL[0] <= block[0]):
|
case boldUL != nil && (block == nil || boldUL[0] <= block[0]):
|
||||||
m := reLegacyBoldUL.FindStringSubmatch(remaining[boldUL[0]:boldUL[1]])
|
m := reLegacyBoldUL.FindStringSubmatch(remaining[boldUL[0]:boldUL[1]])
|
||||||
@@ -89,7 +106,7 @@ func DeriveDescriptionFormulaFromLegacyParts(parts LegacyEnhanceParts) Descripti
|
|||||||
instr = heading
|
instr = heading
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(instr) != "" {
|
if strings.TrimSpace(instr) != "" {
|
||||||
out.Sections = append(out.Sections, DescriptionFormulaSection{Type: "ul", Instructions: instr})
|
out.Sections = append(out.Sections, DescriptionFormulaSection{Type: "ul", Instructions: instr, Optional: true})
|
||||||
}
|
}
|
||||||
remaining = remaining[boldUL[1]:]
|
remaining = remaining[boldUL[1]:]
|
||||||
case block != nil:
|
case block != nil:
|
||||||
@@ -112,6 +129,20 @@ func DeriveDescriptionFormulaFromLegacyParts(parts LegacyEnhanceParts) Descripti
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// The modern product-page formula has an introduction and optional
|
||||||
|
// feature/specification blocks. If evidence is sparse, do not require the
|
||||||
|
// model to hallucinate headings or empty paragraphs.
|
||||||
|
if len(out.Sections) == 5 && out.Sections[0].Type == "p" &&
|
||||||
|
out.Sections[1].Type == "h2" && out.Sections[2].Type == "p" &&
|
||||||
|
out.Sections[3].Type == "h2" && out.Sections[4].Type == "ul" {
|
||||||
|
out.Sections[1].Optional = true
|
||||||
|
out.Sections[2].Optional = true
|
||||||
|
}
|
||||||
|
for i := 0; i+1 < len(out.Sections); i++ {
|
||||||
|
if out.Sections[i].Type == "h2" && out.Sections[i+1].Type == "ul" {
|
||||||
|
out.Sections[i].Optional = true
|
||||||
|
}
|
||||||
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,7 +249,12 @@ func EffectiveDescriptionFormula(stored any, categoryPrompt string) DescriptionF
|
|||||||
if isBuiltInMetaRoleBoilerplate(metaBody) {
|
if isBuiltInMetaRoleBoilerplate(metaBody) {
|
||||||
metaBody = ""
|
metaBody = ""
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(out.MetaTitle) == "" && strings.TrimSpace(out.MetaDescription) == "" && strings.TrimSpace(metaBody) != "" {
|
// Explicit language-scoped Meta instructions belong to the current language.
|
||||||
|
// A shared JSON description_template may hold English default meta rules,
|
||||||
|
// but must not override the translated --- Meta --- section in the API.
|
||||||
|
if mt, md, ok := splitLocalizedMetaRules(metaBody); ok {
|
||||||
|
out.MetaTitle, out.MetaDescription = mt, md
|
||||||
|
} else if strings.TrimSpace(out.MetaTitle) == "" && strings.TrimSpace(out.MetaDescription) == "" && strings.TrimSpace(metaBody) != "" {
|
||||||
out.MetaDescription = strings.TrimSpace(metaBody)
|
out.MetaDescription = strings.TrimSpace(metaBody)
|
||||||
out.MetaTitle = DefaultLegacyMetaTitleRule
|
out.MetaTitle = DefaultLegacyMetaTitleRule
|
||||||
} else {
|
} else {
|
||||||
@@ -232,6 +268,52 @@ func EffectiveDescriptionFormula(stored any, categoryPrompt string) DescriptionF
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// splitLocalizedMetaRules parses the two fixed schema keys while retaining the
|
||||||
|
// instructions verbatim in the category's selected content language. The braces
|
||||||
|
// are editor instruction delimiters, not text for SEO output.
|
||||||
|
func splitLocalizedMetaRules(body string) (title, description string, ok bool) {
|
||||||
|
body = strings.TrimSpace(body)
|
||||||
|
if strings.HasPrefix(body, "{") && strings.HasSuffix(body, "}") {
|
||||||
|
body = strings.TrimSpace(body[1 : len(body)-1])
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(body)
|
||||||
|
if !strings.HasPrefix(lower, "meta_title:") {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
idx := strings.Index(lower, "meta_description:")
|
||||||
|
if idx < 0 {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
// Both legacy {meta_title: ...\nmeta_description: ...} and the newer
|
||||||
|
// {meta_title: ...}\n{meta_description: ...} are valid. Store plain
|
||||||
|
// instructions in description_template, keeping {} only in the editor.
|
||||||
|
title = strings.TrimSpace(strings.TrimSpace(body[len("meta_title:"):idx]))
|
||||||
|
title = strings.TrimSpace(title)
|
||||||
|
// The two-brace form leaves the separator "}\n{" between the roles
|
||||||
|
// after the outer braces were removed. Strip ONLY those delimiters, never
|
||||||
|
// user variables such as {{name}} at the end of an instruction.
|
||||||
|
if strings.HasSuffix(title, "{") {
|
||||||
|
title = strings.TrimSpace(strings.TrimSuffix(title, "{"))
|
||||||
|
title = strings.TrimSpace(strings.TrimSuffix(title, "}"))
|
||||||
|
}
|
||||||
|
description = strings.TrimSpace(body[idx+len("meta_description:"):])
|
||||||
|
return title, description, title != "" && description != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultSEOMetaInstructions returns the two translated prompt rules for a
|
||||||
|
// language as plain text (without the editor's instruction braces).
|
||||||
|
func DefaultSEOMetaInstructions(lang string) (title, description string, err error) {
|
||||||
|
prompt, err := OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
title, description, ok := splitLocalizedMetaRules(ExtractEnhanceSectionBody(prompt, SectionMetaStart, SectionMetaEnd))
|
||||||
|
if !ok {
|
||||||
|
return "", "", fmt.Errorf("invalid meta rules for %q", lang)
|
||||||
|
}
|
||||||
|
return title, description, nil
|
||||||
|
}
|
||||||
|
|
||||||
func isBuiltInMetaRoleBoilerplate(body string) bool {
|
func isBuiltInMetaRoleBoilerplate(body string) bool {
|
||||||
lower := strings.ToLower(strings.TrimSpace(body))
|
lower := strings.ToLower(strings.TrimSpace(body))
|
||||||
return strings.HasPrefix(lower, "role: meta")
|
return strings.HasPrefix(lower, "role: meta")
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package aiprompts
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "embed"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This frozen v6 snapshot is used ONLY to identify exact old default templates
|
||||||
|
// during migrations. Never serve these obsolete instructions to new categories.
|
||||||
|
//
|
||||||
|
//go:embed defaults/prompt-rules-v6.json
|
||||||
|
var previousOfflinePromptRulesJSON []byte
|
||||||
|
|
||||||
|
func PreviousOfflineDefaultPromptV6(lang string) (string, error) {
|
||||||
|
var rules map[string]offlineRules
|
||||||
|
if err := json.Unmarshal(previousOfflinePromptRulesJSON, &rules); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
rule, ok := rules[lang]
|
||||||
|
if !ok || rule.Title == "" || rule.Description == "" || rule.Meta == "" {
|
||||||
|
return "", fmt.Errorf("missing historical v6 language %q", lang)
|
||||||
|
}
|
||||||
|
return "--- Title ---\n" + rule.Title + "\n--- End Title ---\n\n--- Description ---\n" + rule.Description +
|
||||||
|
"\n--- End Description ---\n\n--- Meta ---\n" + rule.Meta + "\n--- End Meta ---", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// The v3 bundle is kept ONLY as exact-match migration evidence. The v3
|
||||||
|
// descriptions were plain text with five 100-word sections and must NEVER be
|
||||||
|
// served as defaults or shown as the new editor examples.
|
||||||
|
//
|
||||||
|
//go:embed defaults/prompt-rules-v3.json
|
||||||
|
var previousOfflinePromptRulesV3JSON []byte
|
||||||
|
|
||||||
|
func PreviousOfflineDefaultPromptV3(lang string) (string, error) {
|
||||||
|
var rules map[string]offlineRules
|
||||||
|
if err := json.Unmarshal(previousOfflinePromptRulesV3JSON, &rules); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
rule, ok := rules[lang]
|
||||||
|
if !ok || rule.Title == "" || rule.Description == "" || rule.Meta == "" {
|
||||||
|
return "", fmt.Errorf("missing historical v3 language %q", lang)
|
||||||
|
}
|
||||||
|
return "--- Title ---\n" + rule.Title + "\n--- End Title ---\n\n--- Description ---\n" + rule.Description +
|
||||||
|
"\n--- End Description ---\n\n--- Meta ---\n" + rule.Meta + "\n--- End Meta ---", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shipped, human-readable platform instructions for every supported content
|
||||||
|
// language. This is offline reference data, not a request to an LLM.
|
||||||
|
//
|
||||||
|
//go:embed defaults/prompt-rules-25.json
|
||||||
|
var offlinePromptRulesJSON []byte
|
||||||
|
|
||||||
|
type offlineRules struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Meta string `json:"meta"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var offlinePromptOnce sync.Once
|
||||||
|
var offlinePrompts map[string]offlineRules
|
||||||
|
var offlinePromptErr error
|
||||||
|
|
||||||
|
// OfflineDefaultPrompt returns a fully localized, A1-style platform template.
|
||||||
|
// Original category-specific English title instructions continue to live in
|
||||||
|
// the English wildcard and the structured title_template; this shared default
|
||||||
|
// uses the standard brand/type/model/color formula for non-English languages.
|
||||||
|
// Returns an error, rather than silently falling back to English, if a locale
|
||||||
|
// has no bundled translation.
|
||||||
|
func OfflineDefaultPrompt(lang string) (string, error) {
|
||||||
|
offlinePromptOnce.Do(func() {
|
||||||
|
offlinePromptErr = json.Unmarshal(offlinePromptRulesJSON, &offlinePrompts)
|
||||||
|
})
|
||||||
|
if offlinePromptErr != nil {
|
||||||
|
return "", fmt.Errorf("load bundled prompts: %w", offlinePromptErr)
|
||||||
|
}
|
||||||
|
rule, ok := offlinePrompts[lang]
|
||||||
|
if !ok || strings.TrimSpace(rule.Title) == "" || strings.TrimSpace(rule.Description) == "" || strings.TrimSpace(rule.Meta) == "" {
|
||||||
|
return "", fmt.Errorf("no bundled category formula for language %q", lang)
|
||||||
|
}
|
||||||
|
// The editor and processing pipeline interpret each role section using
|
||||||
|
// the exact marker syntax below. Body structure is defined in the
|
||||||
|
// localized Description HTML instructions, not a repetitive fixed-length article.
|
||||||
|
return "--- Title ---\n" + rule.Title +
|
||||||
|
"\n--- End Title ---\n\n--- Description ---\n" + rule.Description +
|
||||||
|
"\n--- End Description ---\n\n--- Meta ---\n" + rule.Meta +
|
||||||
|
"\n--- End Meta ---", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func OfflinePromptLanguages() []string {
|
||||||
|
offlinePromptOnce.Do(func() { offlinePromptErr = json.Unmarshal(offlinePromptRulesJSON, &offlinePrompts) })
|
||||||
|
out := make([]string, 0, len(offlinePrompts))
|
||||||
|
for lang := range offlinePrompts {
|
||||||
|
out = append(out, lang)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package aiprompts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAllBundledLanguageRules(t *testing.T) {
|
||||||
|
want := []string{"en", "fr", "de", "es", "it", "nl", "pt", "pl", "cs", "sk", "hu", "ro", "bg", "hr", "sl", "sv", "da", "fi", "el", "et", "lv", "lt", "mt", "ga", "ja"}
|
||||||
|
if len(OfflinePromptLanguages()) != len(want) {
|
||||||
|
t.Fatalf("need 25 locales, have %d", len(OfflinePromptLanguages()))
|
||||||
|
}
|
||||||
|
for _, lang := range want {
|
||||||
|
prompt, err := OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, tag := range []string{"--- Title ---", "--- End Title ---", "--- Description ---", "--- End Description ---", "--- Meta ---", "--- End Meta ---"} {
|
||||||
|
if !strings.Contains(prompt, tag) {
|
||||||
|
t.Fatalf("missing %q in %s", tag, lang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(prompt) > 8000 {
|
||||||
|
t.Fatalf("too long %s", lang)
|
||||||
|
}
|
||||||
|
if !strings.Contains(prompt, "{{attrs}}") || !strings.Contains(prompt, "{{name}}") {
|
||||||
|
t.Fatalf("localized instruction %s missing product evidence placeholders", lang)
|
||||||
|
}
|
||||||
|
if !strings.Contains(prompt, "<p>{") || !strings.Contains(prompt, "<h2>{") || !strings.Contains(prompt, "<ul><li>{") {
|
||||||
|
t.Fatalf("localized instruction %s missing structured HTML", lang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := OfflineDefaultPrompt("invalid"); err == nil {
|
||||||
|
t.Fatal("unknown language silently fell back")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package aiprompts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSEOProductHTMLAllLocales(t *testing.T) {
|
||||||
|
for _, lang := range OfflinePromptLanguages() {
|
||||||
|
prompt, err := OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body := DescriptionSectionInstructions(prompt)
|
||||||
|
if strings.Count(body, "<p>{") != 2 || strings.Count(body, "<h2>{") != 2 || strings.Count(body, "<ul><li>{") != 1 {
|
||||||
|
t.Fatalf("%s invalid HTML: %s", lang, body)
|
||||||
|
}
|
||||||
|
formula := DeriveDescriptionFormulaFromLegacyParts(LegacyEnhanceParts{DescriptionRules: body, WasLegacy: true})
|
||||||
|
if len(formula.Sections) != 5 {
|
||||||
|
t.Fatalf("%s got %d sections; want 5: %+v", lang, len(formula.Sections), formula.Sections)
|
||||||
|
}
|
||||||
|
got := []string{}
|
||||||
|
for _, section := range formula.Sections {
|
||||||
|
got = append(got, section.Type)
|
||||||
|
}
|
||||||
|
if strings.Join(got, ",") != "p,h2,p,h2,ul" {
|
||||||
|
t.Fatalf("%s wrong sections %v", lang, got)
|
||||||
|
}
|
||||||
|
if !formula.Sections[3].Optional || !formula.Sections[4].Optional {
|
||||||
|
t.Fatalf("%s missing optional flags", lang)
|
||||||
|
}
|
||||||
|
if strings.Contains(body, "<h1>") || strings.Contains(body, "<b>") {
|
||||||
|
t.Fatalf("%s non-semantic HTML", lang)
|
||||||
|
}
|
||||||
|
if strings.Contains(body, "five distinct H2") || strings.Contains(body, "pet različitih naslova H2") {
|
||||||
|
t.Fatalf("%s repetitive formula", lang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSEOEnglishMetaSplit(t *testing.T) {
|
||||||
|
parts := ParseLegacyCombinedEnhancePrompt(GenericDefaultCategoryPrompt)
|
||||||
|
if !parts.WasLegacy {
|
||||||
|
t.Fatal("English default not parsed")
|
||||||
|
}
|
||||||
|
meta := DeriveDescriptionFormulaFromLegacyParts(parts)
|
||||||
|
if !strings.HasPrefix(meta.MetaTitle, "Create a distinct") {
|
||||||
|
t.Fatalf("metaTitle=%s", meta.MetaTitle)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(meta.MetaDescription, "Summarize what") {
|
||||||
|
t.Fatalf("metaDescription=%s", meta.MetaDescription)
|
||||||
|
}
|
||||||
|
if strings.Contains(meta.MetaDescription, "meta_title:") {
|
||||||
|
t.Fatal("title rule leaked into description")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSEOUpgradeHasPreviousVersionAndDifferentHashSource(t *testing.T) {
|
||||||
|
for _, name := range []string{"Televisions", "Grohe mixers", "High chairs"} {
|
||||||
|
old := PriorDefaultCategoryFormula("", name)
|
||||||
|
now := DefaultCategoryFormula("", name)
|
||||||
|
if old.Overlay == "" || now.Overlay == "" || old.Overlay == now.Overlay {
|
||||||
|
t.Fatalf("%s migration source missing", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEveryLocalizedDefaultUsesDistinctBracedMetaFields(t *testing.T) {
|
||||||
|
for _, lang := range OfflinePromptLanguages() {
|
||||||
|
prompt, err := OfflineDefaultPrompt(lang)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
meta := ExtractEnhanceSectionBody(prompt, SectionMetaStart, SectionMetaEnd)
|
||||||
|
if strings.Count(meta, "{meta_title:") != 1 || strings.Count(meta, "{meta_description:") != 1 || strings.Count(meta, "}") != 2 {
|
||||||
|
t.Fatalf("%s SEO meta has inconsistent brace structure: %s", lang, meta)
|
||||||
|
}
|
||||||
|
parts := LegacyEnhanceParts{MetaRules: meta, WasLegacy: true}
|
||||||
|
result := DeriveDescriptionFormulaFromLegacyParts(parts)
|
||||||
|
if result.MetaTitle == "" || result.MetaDescription == "" || strings.Contains(result.MetaTitle, "meta_description:") {
|
||||||
|
t.Fatalf("%s metadata parser lost a field: %+v", lang, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
package billing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Content credit rates use fixed four-decimal units (1 credit = 10,000 units).
|
||||||
|
// They are independent of provider token billing and cannot be rounded to an int.
|
||||||
|
const contentCreditScale int64 = 10000
|
||||||
|
|
||||||
|
var contentFeatures = map[string]string{
|
||||||
|
"title": "title_ai",
|
||||||
|
"description": "description_ai",
|
||||||
|
"seo_meta": "seo_meta_ai",
|
||||||
|
}
|
||||||
|
|
||||||
|
// ContentDebitUnits bills one credit for one processed product in one language,
|
||||||
|
// regardless of which supported outputs were selected. The EUR value of a
|
||||||
|
// credit is a separate reference value and is never a processing multiplier.
|
||||||
|
// rates is retained for existing callers, but output-level admin prices no
|
||||||
|
// longer affect the product enrichment charge.
|
||||||
|
func ContentDebitUnits(selected []string, processingType string, rates map[string]int64) (int64, error) {
|
||||||
|
_ = rates
|
||||||
|
if len(selected) == 0 {
|
||||||
|
switch processingType {
|
||||||
|
case "seo", "seo_meta", "seo_ai":
|
||||||
|
selected = []string{"seo_meta"}
|
||||||
|
case "title":
|
||||||
|
selected = []string{"title"}
|
||||||
|
case "description":
|
||||||
|
selected = []string{"description"}
|
||||||
|
default:
|
||||||
|
selected = []string{"title", "description"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, output := range selected {
|
||||||
|
if _, ok := contentFeatures[output]; !ok {
|
||||||
|
return 0, fmt.Errorf("unknown content processing type %q", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return contentCreditScale, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ContentRates resolves company overrides > active plan overrides > global default.
|
||||||
|
// Postgres computes fixed-point integers, avoiding floating-point money arithmetic.
|
||||||
|
type contentRateQuerier interface {
|
||||||
|
Query(context.Context, string, ...any) (pgx.Rows, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ContentRates(ctx context.Context, companyID uuid.UUID) (map[string]int64, error) {
|
||||||
|
return contentRatesFrom(ctx, s.Pool, companyID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func contentRatesFrom(ctx context.Context, source contentRateQuerier, companyID uuid.UUID) (map[string]int64, error) {
|
||||||
|
rows, err := source.Query(ctx, `
|
||||||
|
SELECT f.output, COALESCE(
|
||||||
|
(SELECT (cost_per_unit * 10000)::bigint FROM company_processing_costs
|
||||||
|
WHERE company_id=$1 AND feature_name=f.feature),
|
||||||
|
(SELECT (pc.cost_per_unit * 10000)::bigint FROM plan_processing_costs pc
|
||||||
|
JOIN company_plans cp ON cp.plan_id=pc.plan_id
|
||||||
|
WHERE cp.company_id=$1 AND cp.is_active=true AND pc.feature_name=f.feature
|
||||||
|
ORDER BY cp.created_at DESC LIMIT 1),
|
||||||
|
(SELECT (cost_per_unit * 10000)::bigint FROM processing_costs
|
||||||
|
WHERE feature_name=f.feature AND is_active=true),
|
||||||
|
f.fallback)
|
||||||
|
FROM (VALUES
|
||||||
|
('title'::text,'title_ai'::text,1000::bigint),
|
||||||
|
('description'::text,'description_ai'::text,2500::bigint),
|
||||||
|
('seo_meta'::text,'seo_meta_ai'::text,1000::bigint)
|
||||||
|
) AS f(output,feature,fallback)
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'product'::text, COALESCE(
|
||||||
|
(SELECT (cc.cost_per_unit * 10000)::bigint FROM company_processing_costs cc
|
||||||
|
WHERE cc.company_id=$1 AND cc.feature_name='product_ai'),
|
||||||
|
(SELECT (pc.cost_per_unit * 10000)::bigint FROM plan_processing_costs pc
|
||||||
|
WHERE pc.plan_id=(SELECT cp.plan_id FROM company_plans cp
|
||||||
|
WHERE cp.company_id=$1 AND cp.is_active=true
|
||||||
|
ORDER BY cp.created_at DESC LIMIT 1)
|
||||||
|
AND pc.feature_name='product_ai'))
|
||||||
|
WHERE EXISTS (
|
||||||
|
SELECT 1 FROM plan_processing_costs pc
|
||||||
|
WHERE pc.plan_id=(SELECT cp.plan_id FROM company_plans cp
|
||||||
|
WHERE cp.company_id=$1 AND cp.is_active=true
|
||||||
|
ORDER BY cp.created_at DESC LIMIT 1)
|
||||||
|
AND pc.feature_name='product_ai'
|
||||||
|
)`, companyID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
rates := make(map[string]int64, 3)
|
||||||
|
for rows.Next() {
|
||||||
|
var output string
|
||||||
|
var units int64
|
||||||
|
if err := rows.Scan(&output, &units); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rates[output] = units
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for name := range contentFeatures {
|
||||||
|
if _, ok := rates[name]; !ok {
|
||||||
|
return nil, errors.New("incomplete content pricing rules")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rates, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsumeContentCreditsTx atomically debits the fractional wallet and the current
|
||||||
|
// billing cycle in the caller's product transaction. It never overdraws credits.
|
||||||
|
func (s *Service) ConsumeContentCreditsTx(ctx context.Context, tx pgx.Tx, companyID uuid.UUID, selected []string, processingType string) (float64, error) {
|
||||||
|
if tx == nil {
|
||||||
|
return 0, errors.New("missing billing transaction")
|
||||||
|
}
|
||||||
|
units, err := ContentDebitUnits(selected, processingType, nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if units == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
// Lock credit_balances once. Both integer legacy debits and fractional debits
|
||||||
|
// account for this column when checking remaining capacity.
|
||||||
|
_, err = tx.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
var allowed bool
|
||||||
|
err = tx.QueryRow(ctx, `
|
||||||
|
UPDATE credit_balances SET fractional_credits_used=fractional_credits_used+($2::numeric/10000), updated_at=now()
|
||||||
|
WHERE company_id=$1 AND (total_credits-used_credits-fractional_credits_used)>=($2::numeric/10000)
|
||||||
|
RETURNING true`, companyID, units).Scan(&allowed)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return 0, ErrInsufficientCredits
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
tag, err := tx.Exec(ctx, `
|
||||||
|
UPDATE billing_cycles SET fractional_credits_used=fractional_credits_used+($2::numeric/10000),
|
||||||
|
products_processed=products_processed+1, updated_at=now()
|
||||||
|
WHERE id=(SELECT id FROM billing_cycles WHERE company_id=$1 AND end_date>now() ORDER BY start_date DESC LIMIT 1)`, companyID, units)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if tag.RowsAffected() == 0 {
|
||||||
|
var start, end time.Time
|
||||||
|
err = tx.QueryRow(ctx, `SELECT billing_cycle_start,next_billing_date FROM company_plans
|
||||||
|
WHERE company_id=$1 AND is_active=true ORDER BY created_at DESC LIMIT 1`, companyID).Scan(&start, &end)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
start = time.Now().UTC()
|
||||||
|
end = start.AddDate(0, 1, 0)
|
||||||
|
} else if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(ctx, `INSERT INTO billing_cycles (company_id,start_date,end_date,credits_used,fractional_credits_used,products_processed)
|
||||||
|
VALUES ($1,$2,$3,0,$4::numeric/10000,1)`, companyID, start, end, units)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return float64(units) / float64(contentCreditScale), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package billing
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestContentDebitUnits(t *testing.T) {
|
||||||
|
rates := map[string]int64{"title": 1000, "description": 2500, "seo_meta": 1000}
|
||||||
|
cases := []struct {
|
||||||
|
selected []string
|
||||||
|
processingType string
|
||||||
|
want int64
|
||||||
|
}{
|
||||||
|
{[]string{"title"}, "title", 10000},
|
||||||
|
{[]string{"title", "description"}, "enhance", 10000},
|
||||||
|
{[]string{"title", "description", "seo_meta"}, "enhance", 10000},
|
||||||
|
{[]string{"seo_meta"}, "seo_meta", 10000},
|
||||||
|
{[]string{"title", "title"}, "title", 10000},
|
||||||
|
{nil, "description", 10000},
|
||||||
|
}
|
||||||
|
for _, tt := range cases {
|
||||||
|
got, err := ContentDebitUnits(tt.selected, tt.processingType, rates)
|
||||||
|
if err != nil || got != tt.want {
|
||||||
|
t.Errorf("%v/%s => %d, %v; expected %d", tt.selected, tt.processingType, got, err, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := ContentDebitUnits([]string{"campaign_copy"}, "full", rates); err == nil {
|
||||||
|
t.Fatal("unknown type accepted")
|
||||||
|
}
|
||||||
|
for _, outputs := range [][]string{nil, {"title"}, {"title", "description", "seo_meta"}} {
|
||||||
|
got, err := ContentDebitUnits(outputs, "enhance", map[string]int64{"title": 1000, "description": 2500, "seo_meta": 1000, "product": 3750})
|
||||||
|
if err != nil || got != 10000 {
|
||||||
|
t.Errorf("per-product price outputs=%v got=%d err=%v", outputs, got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
zero, err := ContentDebitUnits([]string{"title"}, "title", map[string]int64{"title": 0})
|
||||||
|
if err != nil || zero != 10000 {
|
||||||
|
t.Fatalf("zero cost %v %v", zero, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -113,24 +113,24 @@ type CreditPack struct {
|
|||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
Credits int `json:"credits"`
|
Credits int `json:"credits"`
|
||||||
PriceUSD int `json:"price_usd"` // whole dollars for marketing UI
|
PriceEUR int `json:"price_eur"` // whole euros for marketing UI
|
||||||
// Approx product×language passes at CreditsPerAIProduct.
|
// Approx product×language passes at CreditsPerAIProduct.
|
||||||
AIProducts int `json:"ai_products"`
|
AIProducts int `json:"ai_products"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func packFromCredits(id, name, desc string, credits, priceUSD int) CreditPack {
|
func packFromCredits(id, name, desc string, credits, priceEUR int) CreditPack {
|
||||||
return CreditPack{
|
return CreditPack{
|
||||||
ID: id,
|
ID: id,
|
||||||
Name: name,
|
Name: name,
|
||||||
Description: desc,
|
Description: desc,
|
||||||
Credits: credits,
|
Credits: credits,
|
||||||
PriceUSD: priceUSD,
|
PriceEUR: priceEUR,
|
||||||
AIProducts: credits / CreditsPerAIProduct,
|
AIProducts: credits / CreditsPerAIProduct,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// DefaultCreditPacks is the public top-up ladder (credits-first sizing).
|
// DefaultCreditPacks is the public top-up ladder (credits-first sizing).
|
||||||
// Prices are balanced so small packs are not punitive $/credit vs larger ones,
|
// Prices are balanced so small packs are not punitive €/credit vs larger ones,
|
||||||
// while staying expensive enough that packs cannot undercut plan upgrades or A1 (~€300).
|
// while staying expensive enough that packs cannot undercut plan upgrades or A1 (~€300).
|
||||||
func DefaultCreditPacks() []CreditPack {
|
func DefaultCreditPacks() []CreditPack {
|
||||||
return []CreditPack{
|
return []CreditPack{
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ func ComputeEntitlements(planName string, monthlyCredits, remaining int, isTrial
|
|||||||
func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUID) (Entitlements, error) {
|
func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUID) (Entitlements, error) {
|
||||||
var total, used int
|
var total, used int
|
||||||
err := s.Pool.QueryRow(ctx, `
|
err := s.Pool.QueryRow(ctx, `
|
||||||
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
|
SELECT total_credits, (total_credits - CEIL(GREATEST(0,total_credits-used_credits-fractional_credits_used)))::integer FROM credit_balances WHERE company_id = $1`, companyID).
|
||||||
Scan(&total, &used)
|
Scan(&total, &used)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
total, used = 0, 0
|
total, used = 0, 0
|
||||||
@@ -162,7 +162,7 @@ func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUI
|
|||||||
// (cannot be silently downgraded to normalize/specs/fill).
|
// (cannot be silently downgraded to normalize/specs/fill).
|
||||||
func ProcessingTypeRequiresAI(processingType string) bool {
|
func ProcessingTypeRequiresAI(processingType string) bool {
|
||||||
switch strings.ToLower(strings.TrimSpace(processingType)) {
|
switch strings.ToLower(strings.TrimSpace(processingType)) {
|
||||||
case "enhance", "enhance_only", "enhance-only", "title", "description", "seo", "seo_ai":
|
case "enhance", "enhance_only", "enhance-only", "title", "description", "seo", "seo_ai", "seo_meta":
|
||||||
return true
|
return true
|
||||||
default:
|
default:
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -36,9 +36,9 @@ const featureGatesCacheTTL = 30 * time.Second
|
|||||||
|
|
||||||
type CreditsOverview struct {
|
type CreditsOverview struct {
|
||||||
TotalCredits int `json:"total_credits"`
|
TotalCredits int `json:"total_credits"`
|
||||||
UsedCredits int `json:"used_credits"`
|
UsedCredits float64 `json:"used_credits"`
|
||||||
Remaining int `json:"remaining"`
|
Remaining float64 `json:"remaining"`
|
||||||
RemainingCredits int `json:"remaining_credits"`
|
RemainingCredits float64 `json:"remaining_credits"`
|
||||||
LowCredits bool `json:"low_credits"`
|
LowCredits bool `json:"low_credits"`
|
||||||
LowCreditsThreshold int `json:"low_credits_threshold"`
|
LowCreditsThreshold int `json:"low_credits_threshold"`
|
||||||
ProductCount int `json:"product_count"`
|
ProductCount int `json:"product_count"`
|
||||||
@@ -69,9 +69,10 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
|
|||||||
lowThreshold = 100
|
lowThreshold = 100
|
||||||
}
|
}
|
||||||
var total, used int
|
var total, used int
|
||||||
|
var fractional float64
|
||||||
err := s.Pool.QueryRow(ctx, `
|
err := s.Pool.QueryRow(ctx, `
|
||||||
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
|
SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID).
|
||||||
Scan(&total, &used)
|
Scan(&total, &used, &fractional)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
_, _ = s.Pool.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID)
|
_, _ = s.Pool.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID)
|
||||||
total, used = 0, 0
|
total, used = 0, 0
|
||||||
@@ -79,10 +80,13 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
|
|||||||
return CreditsOverview{}, err
|
return CreditsOverview{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
remaining := RemainingCreditsClamped(total, used)
|
remaining := float64(total-used) - fractional
|
||||||
|
if remaining < 0 {
|
||||||
|
remaining = 0
|
||||||
|
}
|
||||||
out := CreditsOverview{
|
out := CreditsOverview{
|
||||||
TotalCredits: total,
|
TotalCredits: total,
|
||||||
UsedCredits: used,
|
UsedCredits: float64(used) + fractional,
|
||||||
Remaining: remaining,
|
Remaining: remaining,
|
||||||
RemainingCredits: remaining,
|
RemainingCredits: remaining,
|
||||||
LowCreditsThreshold: lowThreshold,
|
LowCreditsThreshold: lowThreshold,
|
||||||
@@ -157,13 +161,13 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
|
|||||||
planName = "Free"
|
planName = "Free"
|
||||||
featuresRaw = []byte("{}")
|
featuresRaw = []byte("{}")
|
||||||
}
|
}
|
||||||
ent := ComputeEntitlements(planName, monthlyVal, remaining, isTrial)
|
ent := ComputeEntitlements(planName, monthlyVal, int(remaining+0.9999), isTrial)
|
||||||
out.CanUseAI = ent.CanUseAI
|
out.CanUseAI = ent.CanUseAI
|
||||||
out.CanUseEPREL = ent.CanUseEPREL
|
out.CanUseEPREL = ent.CanUseEPREL
|
||||||
out.IsFreePlan = ent.IsFreePlan
|
out.IsFreePlan = ent.IsFreePlan
|
||||||
out.IsPaidPlan = ent.IsPaidPlan
|
out.IsPaidPlan = ent.IsPaidPlan
|
||||||
// Free (0 monthly credits) is not "low credits" — AI is simply unavailable.
|
// Free (0 monthly credits) is not "low credits" — AI is simply unavailable.
|
||||||
out.LowCredits = ent.CanUseAI && remaining <= lowThreshold && remaining > 0
|
out.LowCredits = ent.CanUseAI && remaining <= float64(lowThreshold) && remaining > 0
|
||||||
// Resolve features from the plan row already loaded (avoids a second CapabilitiesForCompany
|
// Resolve features from the plan row already loaded (avoids a second CapabilitiesForCompany
|
||||||
// round-trip that re-queries company_plans + credit_balances). Still uses GetFeatureGates cache
|
// round-trip that re-queries company_plans + credit_balances). Still uses GetFeatureGates cache
|
||||||
// and plans.features JSON overrides via decodeFeaturesJSON + ResolveEffectiveFeaturesEx.
|
// and plans.features JSON overrides via decodeFeaturesJSON + ResolveEffectiveFeaturesEx.
|
||||||
@@ -214,6 +218,9 @@ func (s *Service) AIBrandApplyAllowed(ctx context.Context, companyID uuid.UUID)
|
|||||||
type ProcessingGateOpts struct {
|
type ProcessingGateOpts struct {
|
||||||
// RequiresAI when true enforces can_use_ai + credit wallet (AI-only job types).
|
// RequiresAI when true enforces can_use_ai + credit wallet (AI-only job types).
|
||||||
RequiresAI bool
|
RequiresAI bool
|
||||||
|
// CreditsPerProduct is the effective per-output rate for this job.
|
||||||
|
// Zero retains legacy one-credit minimum for callers without content pricing.
|
||||||
|
CreditsPerProduct float64
|
||||||
// RequiresEPREL when true enforces can_use_eprel (EPREL-only job types).
|
// RequiresEPREL when true enforces can_use_eprel (EPREL-only job types).
|
||||||
RequiresEPREL bool
|
RequiresEPREL bool
|
||||||
}
|
}
|
||||||
@@ -239,9 +246,15 @@ func (s *Service) AssertCanStartProcessing(ctx context.Context, companyID uuid.U
|
|||||||
if ent.RemainingCredits < 1 {
|
if ent.RemainingCredits < 1 {
|
||||||
return fmt.Errorf("%w: no credits remaining — upgrade your plan to continue AI processing", ErrInsufficientCredits)
|
return fmt.Errorf("%w: no credits remaining — upgrade your plan to continue AI processing", ErrInsufficientCredits)
|
||||||
}
|
}
|
||||||
if ent.RemainingCredits < batchSize {
|
needed := float64(batchSize)
|
||||||
return fmt.Errorf("%w: need at least %d credits for this batch (have %d) — upgrade or select fewer products",
|
if opts.CreditsPerProduct > 0 {
|
||||||
ErrInsufficientCredits, batchSize, ent.RemainingCredits)
|
needed *= opts.CreditsPerProduct
|
||||||
|
}
|
||||||
|
// The wallet debit uses precise fractional values and remains authoritative.
|
||||||
|
// The coarse entitlement is rounded up, so avoid rejecting a valid sub-credit job.
|
||||||
|
if float64(ent.RemainingCredits)+0.000001 < needed {
|
||||||
|
return fmt.Errorf("%w: need about %.2f credits for this batch (up to %d whole-credit units available)",
|
||||||
|
ErrInsufficientCredits, needed, ent.RemainingCredits)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,10 +347,10 @@ func (s *Service) consumeCredits(ctx context.Context, tx pgx.Tx, companyID uuid.
|
|||||||
}
|
}
|
||||||
_ = s.EnsureDefaultCosts(ctx)
|
_ = s.EnsureDefaultCosts(ctx)
|
||||||
|
|
||||||
featureCost := s.lookupCost(ctx, featureName, 1)
|
featureCost := s.lookupCostForCompany(ctx, companyID, featureName, 1)
|
||||||
tokenKCost := 1
|
tokenKCost := 1
|
||||||
if tokenCount > 0 {
|
if tokenCount > 0 {
|
||||||
tokenKCost = s.lookupCost(ctx, "openai_token_k", 1)
|
tokenKCost = s.lookupCostForCompany(ctx, companyID, "openai_token_k", 1)
|
||||||
}
|
}
|
||||||
var debit int
|
var debit int
|
||||||
if productCount == 1 {
|
if productCount == 1 {
|
||||||
@@ -385,7 +398,7 @@ func (s *Service) applyCreditDebit(ctx context.Context, tx pgx.Tx, companyID uui
|
|||||||
WITH upd AS (
|
WITH upd AS (
|
||||||
UPDATE credit_balances
|
UPDATE credit_balances
|
||||||
SET used_credits = used_credits + $2, updated_at = now()
|
SET used_credits = used_credits + $2, updated_at = now()
|
||||||
WHERE company_id = $1 AND (total_credits - used_credits) >= $2
|
WHERE company_id = $1 AND (total_credits - used_credits - fractional_credits_used) >= $2
|
||||||
RETURNING company_id
|
RETURNING company_id
|
||||||
),
|
),
|
||||||
cyc AS (
|
cyc AS (
|
||||||
@@ -462,7 +475,7 @@ func (s *Service) lookupCost(ctx context.Context, feature string, fallback int)
|
|||||||
|
|
||||||
var cost int
|
var cost int
|
||||||
err := s.Pool.QueryRow(ctx, `
|
err := s.Pool.QueryRow(ctx, `
|
||||||
SELECT cost_per_unit FROM processing_costs
|
SELECT cost_per_unit::integer FROM processing_costs
|
||||||
WHERE feature_name = $1 AND is_active = true`, feature).Scan(&cost)
|
WHERE feature_name = $1 AND is_active = true`, feature).Scan(&cost)
|
||||||
if err != nil || cost <= 0 {
|
if err != nil || cost <= 0 {
|
||||||
return fallback
|
return fallback
|
||||||
@@ -477,6 +490,43 @@ func (s *Service) lookupCost(ctx context.Context, feature string, fallback int)
|
|||||||
return cost
|
return cost
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// lookupCostForCompany resolves credit pricing without caching tenant-specific rules.
|
||||||
|
// Overrides must be positive; the existing credit engine enforces a minimum of 1.
|
||||||
|
// An unconfigured/missing migration retains the global default behavior.
|
||||||
|
func (s *Service) lookupCostForCompany(ctx context.Context, companyID uuid.UUID, feature string, fallback int) int {
|
||||||
|
var cost int
|
||||||
|
err := s.Pool.QueryRow(ctx, `
|
||||||
|
SELECT COALESCE(
|
||||||
|
(SELECT cc.cost_per_unit FROM company_processing_costs cc
|
||||||
|
WHERE cc.company_id = $1 AND cc.feature_name = $2),
|
||||||
|
(SELECT pc.cost_per_unit FROM plan_processing_costs pc
|
||||||
|
JOIN company_plans cp ON cp.plan_id = pc.plan_id
|
||||||
|
WHERE cp.company_id = $1 AND cp.is_active = true AND pc.feature_name = $2
|
||||||
|
ORDER BY cp.created_at DESC LIMIT 1),
|
||||||
|
(SELECT gc.cost_per_unit FROM processing_costs gc
|
||||||
|
WHERE gc.feature_name = $2 AND gc.is_active = true),
|
||||||
|
$3
|
||||||
|
)::integer`, companyID, feature, fallback).Scan(&cost)
|
||||||
|
if err == nil && cost >= 0 {
|
||||||
|
return cost
|
||||||
|
}
|
||||||
|
return s.lookupCost(ctx, feature, fallback)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EstimateDebitForCompany uses the same company/plan pricing rules as the actual debit.
|
||||||
|
func (s *Service) EstimateDebitForCompany(ctx context.Context, companyID uuid.UUID, feature string, tokenCount int) int {
|
||||||
|
if feature == "" {
|
||||||
|
feature = "product_processing"
|
||||||
|
}
|
||||||
|
_ = s.EnsureDefaultCosts(ctx)
|
||||||
|
base := s.lookupCostForCompany(ctx, companyID, feature, 1)
|
||||||
|
perK := 1
|
||||||
|
if tokenCount > 0 {
|
||||||
|
perK = s.lookupCostForCompany(ctx, companyID, "openai_token_k", 1)
|
||||||
|
}
|
||||||
|
return DebitAmount(base, perK, tokenCount)
|
||||||
|
}
|
||||||
|
|
||||||
// EnsureDefaultCosts seeds plan-aligned processing cost rows (idempotent).
|
// EnsureDefaultCosts seeds plan-aligned processing cost rows (idempotent).
|
||||||
// After a successful seed in this process, subsequent calls no-op (worker seeds at boot).
|
// After a successful seed in this process, subsequent calls no-op (worker seeds at boot).
|
||||||
func (s *Service) EnsureDefaultCosts(ctx context.Context) error {
|
func (s *Service) EnsureDefaultCosts(ctx context.Context) error {
|
||||||
@@ -847,7 +897,7 @@ func (s *Service) AssignPlan(ctx context.Context, companyID uuid.UUID, planID in
|
|||||||
_, err = tx.Exec(ctx, `
|
_, err = tx.Exec(ctx, `
|
||||||
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
|
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
|
||||||
VALUES ($1, $2, 0, now())
|
VALUES ($1, $2, 0, now())
|
||||||
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, updated_at = now()`,
|
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, fractional_credits_used = 0, updated_at = now()`,
|
||||||
companyID, alloc)
|
companyID, alloc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -894,12 +944,16 @@ type UsageDayPoint struct {
|
|||||||
type UsageSummary struct {
|
type UsageSummary struct {
|
||||||
CompanyID uuid.UUID `json:"company_id"`
|
CompanyID uuid.UUID `json:"company_id"`
|
||||||
Range string `json:"range"`
|
Range string `json:"range"`
|
||||||
CreditsUsed int `json:"credits_used"`
|
CreditsUsed float64 `json:"credits_used"`
|
||||||
CreditsTotal int `json:"credits_total"`
|
CreditsTotal int `json:"credits_total"`
|
||||||
CreditsRemaining int `json:"credits_remaining"`
|
CreditsRemaining float64 `json:"credits_remaining"`
|
||||||
ProductsProcessed int `json:"products_processed"`
|
ProductsProcessed int `json:"products_processed"`
|
||||||
ProductsTotal int `json:"products_total"`
|
ProductsTotal int `json:"products_total"`
|
||||||
Tokens int64 `json:"tokens"`
|
Tokens int64 `json:"tokens"`
|
||||||
|
InputTokens int64 `json:"input_tokens"`
|
||||||
|
CachedInputTokens int64 `json:"cached_input_tokens"`
|
||||||
|
OutputTokens int64 `json:"output_tokens"`
|
||||||
|
AICalls int64 `json:"ai_calls"`
|
||||||
FeedsInput int `json:"feeds_input"`
|
FeedsInput int `json:"feeds_input"`
|
||||||
FeedsExport int `json:"feeds_export"`
|
FeedsExport int `json:"feeds_export"`
|
||||||
JobsTotal int `json:"jobs_total"`
|
JobsTotal int `json:"jobs_total"`
|
||||||
@@ -928,17 +982,21 @@ func (s *Service) UsageSummary(ctx context.Context, companyID uuid.UUID, rangeRa
|
|||||||
}
|
}
|
||||||
|
|
||||||
var total, used int
|
var total, used int
|
||||||
|
var fractional float64
|
||||||
err := s.Pool.QueryRow(ctx, `
|
err := s.Pool.QueryRow(ctx, `
|
||||||
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
|
SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID).
|
||||||
Scan(&total, &used)
|
Scan(&total, &used, &fractional)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
total, used = 0, 0
|
total, used = 0, 0
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
out.CreditsTotal = total
|
out.CreditsTotal = total
|
||||||
out.CreditsUsed = used
|
out.CreditsUsed = float64(used) + fractional
|
||||||
out.CreditsRemaining = RemainingCreditsClamped(total, used)
|
out.CreditsRemaining = float64(total-used) - fractional
|
||||||
|
if out.CreditsRemaining < 0 {
|
||||||
|
out.CreditsRemaining = 0
|
||||||
|
}
|
||||||
out.Notes = append(out.Notes,
|
out.Notes = append(out.Notes,
|
||||||
"Credits are the live wallet (credit_balances). Daily credit history is not ledgered yet — range filters apply to products and tokens only.")
|
"Credits are the live wallet (credit_balances). Daily credit history is not ledgered yet — range filters apply to products and tokens only.")
|
||||||
|
|
||||||
@@ -1010,6 +1068,21 @@ func (s *Service) UsageSummary(ctx context.Context, companyID uuid.UUID, rangeRa
|
|||||||
out.ProductsProcessed = out.ProductsTotal
|
out.ProductsProcessed = out.ProductsTotal
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Detailed token usage comes from the durable per-call ledger, not processed
|
||||||
|
// product rows (a single product can make several model calls).
|
||||||
|
// A missing old ledger should not prevent viewing the rest of billing.
|
||||||
|
if err := s.Pool.QueryRow(ctx, `
|
||||||
|
SELECT COALESCE(SUM(prompt_tokens),0)::bigint,
|
||||||
|
COALESCE(SUM(cached_prompt_tokens),0)::bigint,
|
||||||
|
COALESCE(SUM(completion_tokens),0)::bigint,
|
||||||
|
COALESCE(SUM(calls),0)::bigint
|
||||||
|
FROM ai_usage_daily
|
||||||
|
WHERE company_id = $1 AND ($2::timestamptz IS NULL OR day >= $2::date)
|
||||||
|
AND ($3::timestamptz IS NULL OR day < $3::date)`,
|
||||||
|
companyID, since, until).Scan(&out.InputTokens, &out.CachedInputTokens, &out.OutputTokens, &out.AICalls); err != nil {
|
||||||
|
out.Notes = append(out.Notes, "Detailed token usage unavailable; check the AI usage ledger migration.")
|
||||||
|
}
|
||||||
|
|
||||||
if rangeKey == "7d" || rangeKey == "30d" || (rangeKey == "cycle" && since != nil) {
|
if rangeKey == "7d" || rangeKey == "30d" || (rangeKey == "cycle" && since != nil) {
|
||||||
seriesSince := now.Truncate(24*time.Hour).AddDate(0, 0, -29)
|
seriesSince := now.Truncate(24*time.Hour).AddDate(0, 0, -29)
|
||||||
days := 30
|
days := 30
|
||||||
@@ -1194,7 +1267,7 @@ func (s *Service) claimAndRollDueCompanyPlan(ctx context.Context, rowID int64) (
|
|||||||
_, err = tx.Exec(ctx, `
|
_, err = tx.Exec(ctx, `
|
||||||
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
|
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
|
||||||
VALUES ($1, $2, 0, now())
|
VALUES ($1, $2, 0, now())
|
||||||
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, updated_at = now()`,
|
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, fractional_credits_used = 0, updated_at = now()`,
|
||||||
companyID, monthly)
|
companyID, monthly)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
|
|||||||
@@ -328,6 +328,10 @@ func (s *StripeService) CreateCheckoutSession(ctx context.Context, companyID uui
|
|||||||
return CheckoutResult{}, fmt.Errorf("%w: %s %s", ErrStripePriceMissing, plan, term)
|
return CheckoutResult{}, fmt.Errorf("%w: %s %s", ErrStripePriceMissing, plan, term)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := s.requireEuroStripePrice(ctx, priceID); err != nil {
|
||||||
|
return CheckoutResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
customerID, err := s.ensureCustomer(ctx, companyID, email, companyName)
|
customerID, err := s.ensureCustomer(ctx, companyID, email, companyName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return CheckoutResult{}, err
|
return CheckoutResult{}, err
|
||||||
@@ -406,6 +410,10 @@ func (s *StripeService) CreateCreditPackCheckout(ctx context.Context, companyID
|
|||||||
return CheckoutResult{}, fmt.Errorf("%w: credit pack %s", ErrStripePriceMissing, pack.ID)
|
return CheckoutResult{}, fmt.Errorf("%w: credit pack %s", ErrStripePriceMissing, pack.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := s.requireEuroStripePrice(ctx, priceID); err != nil {
|
||||||
|
return CheckoutResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
customerID, err := s.ensureCustomer(ctx, companyID, email, companyName)
|
customerID, err := s.ensureCustomer(ctx, companyID, email, companyName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return CheckoutResult{}, err
|
return CheckoutResult{}, err
|
||||||
@@ -1034,6 +1042,22 @@ func verifyStripeSignature(payload []byte, header, secret string, tolerance time
|
|||||||
return ErrStripeBadSignature
|
return ErrStripeBadSignature
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// requireEuroStripePrice blocks checkout against old USD Stripe Price IDs.
|
||||||
|
// Publishing euro list prices cannot alter an existing Stripe Price currency.
|
||||||
|
func (s *StripeService) requireEuroStripePrice(ctx context.Context, priceID string) error {
|
||||||
|
var price struct {
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
Active bool `json:"active"`
|
||||||
|
}
|
||||||
|
if err := s.stripeGET(ctx, "https://api.stripe.com/v1/prices/"+url.PathEscape(priceID), &price); err != nil {
|
||||||
|
return fmt.Errorf("verify Stripe EUR price: %w", err)
|
||||||
|
}
|
||||||
|
if !price.Active || !strings.EqualFold(strings.TrimSpace(price.Currency), "eur") {
|
||||||
|
return errors.New("Stripe Price must be active and denominated in EUR; configure a EUR Price ID before checkout")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// LoadStripePriceIDs reads STRIPE_PRICE_* env into the price map.
|
// LoadStripePriceIDs reads STRIPE_PRICE_* env into the price map.
|
||||||
func LoadStripePriceIDs(getenv func(string) string) map[string]string {
|
func LoadStripePriceIDs(getenv func(string) string) map[string]string {
|
||||||
out := map[string]string{}
|
out := map[string]string{}
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package billing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StripeInvoice contains only identifiers and URLs supplied by Stripe, never a
|
||||||
|
// locally invented financial document. Amounts are in the invoice currency's
|
||||||
|
// smallest unit, as returned by Stripe.
|
||||||
|
type StripeInvoice struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Number string `json:"number"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
Created int64 `json:"created"`
|
||||||
|
AmountDue int64 `json:"amount_due"`
|
||||||
|
AmountPaid int64 `json:"amount_paid"`
|
||||||
|
AmountRemaining int64 `json:"amount_remaining"`
|
||||||
|
HostedInvoiceURL string `json:"hosted_invoice_url,omitempty"`
|
||||||
|
InvoicePDF string `json:"invoice_pdf,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *StripeService) ListCompanyInvoices(ctx context.Context, companyID uuid.UUID) ([]StripeInvoice, error) {
|
||||||
|
ctx, cfg, err := s.bindCfg(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if cfg.MockMode() {
|
||||||
|
return []StripeInvoice{}, nil
|
||||||
|
}
|
||||||
|
var customerID *string
|
||||||
|
err = s.Pool.QueryRow(ctx, `SELECT stripe_customer_id FROM companies WHERE id=$1`, companyID).Scan(&customerID)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || customerID == nil || strings.TrimSpace(*customerID) == "" {
|
||||||
|
return []StripeInvoice{}, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var result struct {
|
||||||
|
Data []StripeInvoice `json:"data"`
|
||||||
|
}
|
||||||
|
endpoint := "https://api.stripe.com/v1/invoices?limit=100&customer=" + url.QueryEscape(*customerID)
|
||||||
|
if err := s.stripeGET(ctx, endpoint, &result); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if result.Data == nil {
|
||||||
|
result.Data = []StripeInvoice{}
|
||||||
|
}
|
||||||
|
return result.Data, nil
|
||||||
|
}
|
||||||
@@ -64,7 +64,10 @@ func (s *StripeService) CreateSalesQuoteCheckout(ctx context.Context, in SalesQu
|
|||||||
}
|
}
|
||||||
currency := strings.ToLower(strings.TrimSpace(in.Currency))
|
currency := strings.ToLower(strings.TrimSpace(in.Currency))
|
||||||
if currency == "" {
|
if currency == "" {
|
||||||
currency = "usd"
|
currency = "eur"
|
||||||
|
}
|
||||||
|
if currency != "eur" {
|
||||||
|
return SalesQuoteCheckoutResult{}, fmt.Errorf("%w: only EUR sales quotes are supported", ErrStripePlanUnsupported)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cfg, err := s.bindCfg(ctx)
|
ctx, cfg, err := s.bindCfg(ctx)
|
||||||
@@ -206,7 +209,7 @@ func (s *StripeService) createSalesQuotePrice(ctx context.Context, productID str
|
|||||||
form.Set("product", productID)
|
form.Set("product", productID)
|
||||||
form.Set("currency", strings.ToLower(strings.TrimSpace(in.Currency)))
|
form.Set("currency", strings.ToLower(strings.TrimSpace(in.Currency)))
|
||||||
if form.Get("currency") == "" {
|
if form.Get("currency") == "" {
|
||||||
form.Set("currency", "usd")
|
form.Set("currency", "eur")
|
||||||
}
|
}
|
||||||
form.Set("unit_amount", strconv.Itoa(in.InstallmentAmountCents))
|
form.Set("unit_amount", strconv.Itoa(in.InstallmentAmountCents))
|
||||||
form.Set("metadata[descrybe_sales_quote]", in.QuoteID.String())
|
form.Set("metadata[descrybe_sales_quote]", in.QuoteID.String())
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type SyncCreditPackResult struct {
|
|||||||
PriceID string `json:"price_id"`
|
PriceID string `json:"price_id"`
|
||||||
Created bool `json:"created"`
|
Created bool `json:"created"`
|
||||||
Credits int `json:"credits"`
|
Credits int `json:"credits"`
|
||||||
PriceUSD int `json:"price_usd"`
|
PriceEUR int `json:"price_eur"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SyncCreditPackProducts creates/updates Stripe Products + one-time Prices for
|
// SyncCreditPackProducts creates/updates Stripe Products + one-time Prices for
|
||||||
@@ -47,7 +47,7 @@ func (s *StripeService) SyncCreditPackProducts(ctx context.Context) ([]SyncCredi
|
|||||||
PriceID: priceID,
|
PriceID: priceID,
|
||||||
Created: createdProduct || createdPrice,
|
Created: createdProduct || createdPrice,
|
||||||
Credits: pack.Credits,
|
Credits: pack.Credits,
|
||||||
PriceUSD: pack.PriceUSD,
|
PriceEUR: pack.PriceEUR,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
@@ -73,7 +73,7 @@ func (s *StripeService) ensureCreditPackProduct(ctx context.Context, pack Credit
|
|||||||
form.Set("metadata[descrybe_pack]", pack.ID)
|
form.Set("metadata[descrybe_pack]", pack.ID)
|
||||||
form.Set("metadata[credits]", strconv.Itoa(pack.Credits))
|
form.Set("metadata[credits]", strconv.Itoa(pack.Credits))
|
||||||
form.Set("metadata[ai_products]", strconv.Itoa(pack.AIProducts))
|
form.Set("metadata[ai_products]", strconv.Itoa(pack.AIProducts))
|
||||||
form.Set("metadata[price_usd]", strconv.Itoa(pack.PriceUSD))
|
form.Set("metadata[price_eur]", strconv.Itoa(pack.PriceEUR))
|
||||||
var product struct {
|
var product struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,7 @@ func (s *StripeService) ensureCreditPackProduct(ctx context.Context, pack Credit
|
|||||||
|
|
||||||
func (s *StripeService) ensureCreditPackPrice(ctx context.Context, productID string, pack CreditPack) (priceID string, created bool, err error) {
|
func (s *StripeService) ensureCreditPackPrice(ctx context.Context, productID string, pack CreditPack) (priceID string, created bool, err error) {
|
||||||
// Reuse an active one-time price on this product that matches unit amount.
|
// Reuse an active one-time price on this product that matches unit amount.
|
||||||
wantCents := pack.PriceUSD * 100
|
wantCents := pack.PriceEUR * 100
|
||||||
var list struct {
|
var list struct {
|
||||||
Data []struct {
|
Data []struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
@@ -103,14 +103,14 @@ func (s *StripeService) ensureCreditPackPrice(ctx context.Context, productID str
|
|||||||
return "", false, err
|
return "", false, err
|
||||||
}
|
}
|
||||||
for _, p := range list.Data {
|
for _, p := range list.Data {
|
||||||
if p.Active && p.Type == "one_time" && strings.EqualFold(p.Currency, "usd") && int(p.UnitAmount) == wantCents {
|
if p.Active && p.Type == "one_time" && strings.EqualFold(p.Currency, "eur") && int(p.UnitAmount) == wantCents {
|
||||||
return p.ID, false, nil
|
return p.ID, false, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
form := url.Values{}
|
form := url.Values{}
|
||||||
form.Set("product", productID)
|
form.Set("product", productID)
|
||||||
form.Set("currency", "usd")
|
form.Set("currency", "eur")
|
||||||
form.Set("unit_amount", strconv.Itoa(wantCents))
|
form.Set("unit_amount", strconv.Itoa(wantCents))
|
||||||
form.Set("metadata[descrybe_pack]", pack.ID)
|
form.Set("metadata[descrybe_pack]", pack.ID)
|
||||||
form.Set("metadata[credits]", strconv.Itoa(pack.Credits))
|
form.Set("metadata[credits]", strconv.Itoa(pack.Credits))
|
||||||
|
|||||||
@@ -205,19 +205,19 @@ func TestCreditPackCatalog(t *testing.T) {
|
|||||||
t.Fatalf("want at least 7 packs, got %d", len(packs))
|
t.Fatalf("want at least 7 packs, got %d", len(packs))
|
||||||
}
|
}
|
||||||
tiny, ok := CreditPackByID("tiny")
|
tiny, ok := CreditPackByID("tiny")
|
||||||
if !ok || tiny.Credits != 25 || tiny.PriceUSD != 29 {
|
if !ok || tiny.Credits != 25 || tiny.PriceEUR != 29 {
|
||||||
t.Fatalf("tiny pack: %#v ok=%v", tiny, ok)
|
t.Fatalf("tiny pack: %#v ok=%v", tiny, ok)
|
||||||
}
|
}
|
||||||
small, ok := CreditPackByID("small")
|
small, ok := CreditPackByID("small")
|
||||||
if !ok || small.Credits != 65 || small.PriceUSD != 59 {
|
if !ok || small.Credits != 65 || small.PriceEUR != 59 {
|
||||||
t.Fatalf("small pack: %#v ok=%v", small, ok)
|
t.Fatalf("small pack: %#v ok=%v", small, ok)
|
||||||
}
|
}
|
||||||
med, ok := CreditPackByID("medium")
|
med, ok := CreditPackByID("medium")
|
||||||
if !ok || med.Credits != 200 || med.PriceUSD != 149 {
|
if !ok || med.Credits != 200 || med.PriceEUR != 149 {
|
||||||
t.Fatalf("medium pack: %#v ok=%v", med, ok)
|
t.Fatalf("medium pack: %#v ok=%v", med, ok)
|
||||||
}
|
}
|
||||||
mega, ok := CreditPackByID("mega")
|
mega, ok := CreditPackByID("mega")
|
||||||
if !ok || mega.Credits != 8000 || mega.PriceUSD != 2999 {
|
if !ok || mega.Credits != 8000 || mega.PriceEUR != 2999 {
|
||||||
t.Fatalf("mega pack: %#v ok=%v", mega, ok)
|
t.Fatalf("mega pack: %#v ok=%v", mega, ok)
|
||||||
}
|
}
|
||||||
if CreditPackSettingsKey("small") != "stripe.price.pack.small" {
|
if CreditPackSettingsKey("small") != "stripe.price.pack.small" {
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ const applyDefaultCategoryFormulasSQL = `
|
|||||||
UPDATE categories AS c SET
|
UPDATE categories AS c SET
|
||||||
prompt = CASE
|
prompt = CASE
|
||||||
WHEN c.prompt IS NULL OR c.prompt = '{}'::jsonb
|
WHEN c.prompt IS NULL OR c.prompt = '{}'::jsonb
|
||||||
THEN v.prompt::jsonb ELSE c.prompt END,
|
THEN v.prompt::jsonb || v.translations ELSE c.prompt END,
|
||||||
title_template = CASE
|
title_template = CASE
|
||||||
WHEN c.title_template IS NULL OR c.title_template::text IN ('null', '{}')
|
WHEN c.title_template IS NULL OR c.title_template::text IN ('null', '{}')
|
||||||
THEN NULLIF(v.title_template, '')::jsonb ELSE c.title_template END,
|
THEN NULLIF(v.title_template, '')::jsonb ELSE c.title_template END,
|
||||||
@@ -39,13 +39,16 @@ const applyDefaultCategoryFormulasSQL = `
|
|||||||
THEN NULLIF(v.description_template, '')::jsonb ELSE c.description_template END,
|
THEN NULLIF(v.description_template, '')::jsonb ELSE c.description_template END,
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
FROM (
|
FROM (
|
||||||
SELECT * FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[])
|
SELECT t.id, t.prompt, t.title_template, t.description_template,
|
||||||
AS t(id, prompt, title_template, description_template)
|
COALESCE(cache.translations, '{}'::jsonb) AS translations
|
||||||
|
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[])
|
||||||
|
AS t(id, prompt, title_template, description_template, source_hash)
|
||||||
|
LEFT JOIN default_category_prompt_translations cache ON cache.source_hash = t.source_hash
|
||||||
) AS v
|
) AS v
|
||||||
WHERE c.id = v.id AND c.company_id = $1`
|
WHERE c.id = v.id AND c.company_id = $1`
|
||||||
|
|
||||||
// ApplyDefaultCategoryFormulas gives newly created categories the platform-default
|
// ApplyDefaultCategoryFormulas gives newly created categories the platform-default
|
||||||
// formulas (English, same style as the A1 legacy templates) when they have none.
|
// formulas and any seeded translations when they have none.
|
||||||
//
|
//
|
||||||
// New categories get a working title/description/meta formula out of the box
|
// New categories get a working title/description/meta formula out of the box
|
||||||
// instead of falling through to generic "1-3 paragraphs" copy. Existing rows are
|
// instead of falling through to generic "1-3 paragraphs" copy. Existing rows are
|
||||||
@@ -56,6 +59,7 @@ func ApplyDefaultCategoryFormulas(ctx context.Context, db pgxExecer, companyID u
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
ids := make([]uuid.UUID, 0, len(targets))
|
ids := make([]uuid.UUID, 0, len(targets))
|
||||||
|
hashes := make([]string, 0, len(targets))
|
||||||
prompts := make([]string, 0, len(targets))
|
prompts := make([]string, 0, len(targets))
|
||||||
titles := make([]string, 0, len(targets))
|
titles := make([]string, 0, len(targets))
|
||||||
descs := make([]string, 0, len(targets))
|
descs := make([]string, 0, len(targets))
|
||||||
@@ -67,12 +71,13 @@ func ApplyDefaultCategoryFormulas(ctx context.Context, db pgxExecer, companyID u
|
|||||||
if def.Overlay == "" {
|
if def.Overlay == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// "*" applies to every content language: the formula text is English while
|
// Keep the English wildcard for an explicit fallback if a translation
|
||||||
// {{language}} still selects the output language at render time.
|
// is missing; the seed's language variants take precedence.
|
||||||
promptJSON, err := company.EncodeLangPromptMap(company.LangPromptMap{"*": def.Overlay})
|
promptJSON, err := company.EncodeLangPromptMap(company.LangPromptMap{"*": def.Overlay})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
hashes = append(hashes, DefaultPromptHash(def.Overlay))
|
||||||
ids = append(ids, t.ID)
|
ids = append(ids, t.ID)
|
||||||
prompts = append(prompts, string(promptJSON))
|
prompts = append(prompts, string(promptJSON))
|
||||||
titles = append(titles, def.TitleTemplateJSON)
|
titles = append(titles, def.TitleTemplateJSON)
|
||||||
@@ -81,6 +86,6 @@ func ApplyDefaultCategoryFormulas(ctx context.Context, db pgxExecer, companyID u
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
_, err := db.Exec(ctx, applyDefaultCategoryFormulasSQL, companyID, ids, prompts, titles, descs)
|
_, err := db.Exec(ctx, applyDefaultCategoryFormulasSQL, companyID, ids, prompts, titles, descs, hashes)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultPromptHash versions platform translations by the exact English formula.
|
||||||
|
// Editing a built-in formula therefore cannot accidentally apply stale translations.
|
||||||
|
func DefaultPromptHash(source string) string {
|
||||||
|
sum := sha256.Sum256([]byte(source))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsUntouchedDefaultPrompt ensures tenant-authored prompts are NEVER translated,
|
||||||
|
// modified, or mistaken for the platform's default. A language override is
|
||||||
|
// eligible only when it is an exact copy of a previously seeded default.
|
||||||
|
func IsUntouchedDefaultPrompt(prompts company.LangPromptMap, source string, seeded company.LangPromptMap) bool {
|
||||||
|
if strings.TrimSpace(source) == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for code, value := range prompts {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if code == "*" || code == "en" {
|
||||||
|
if value != source {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !company.IsAllowedLanguage(code) || strings.TrimSpace(seeded[code]) != value {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestIsUntouchedDefaultPrompt(t *testing.T) {
|
||||||
|
source := aiprompts.GenericCategoryFormula().Overlay
|
||||||
|
seeded := company.LangPromptMap{"de": "Vorgabe", "sl": "Predloga"}
|
||||||
|
for name, prompts := range map[string]company.LangPromptMap{
|
||||||
|
"no stored prompt": {},
|
||||||
|
"shared default": {"*": source},
|
||||||
|
"existing translated default": {"*": source, "de": "Vorgabe", "sl": "Predloga"},
|
||||||
|
"english default": {"en": source},
|
||||||
|
} {
|
||||||
|
if !IsUntouchedDefaultPrompt(prompts, source, seeded) {
|
||||||
|
t.Errorf("%s should be default", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, prompts := range map[string]company.LangPromptMap{
|
||||||
|
"custom shared": {"*": "My shop-specific instructions"},
|
||||||
|
"custom english": {"en": "Custom"},
|
||||||
|
"custom german override": {"*": source, "de": "Our custom German copy"},
|
||||||
|
"custom extra language": {"*": source, "fr": "custom"},
|
||||||
|
"unsupported override": {"*": source, "xx": "custom"},
|
||||||
|
} {
|
||||||
|
if IsUntouchedDefaultPrompt(prompts, source, seeded) {
|
||||||
|
t.Errorf("%s must stay custom", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if DefaultPromptHash(source) == DefaultPromptHash("changed "+source) {
|
||||||
|
t.Fatal("hash not versioned by source")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultPromptSourcesCoverGenericAndTaxonomy(t *testing.T) {
|
||||||
|
all := aiprompts.AllDefaultCategoryPrompts()
|
||||||
|
if len(all) != 1 {
|
||||||
|
t.Fatalf("expected one shared canonical source for all categories, got %d", len(all))
|
||||||
|
}
|
||||||
|
generic := aiprompts.GenericCategoryFormula().Overlay
|
||||||
|
found := false
|
||||||
|
for _, s := range all {
|
||||||
|
if s == generic {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
if s == "" {
|
||||||
|
t.Fatal("empty default")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("generic default not included")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The product detail payload must carry feed_field_sources so the product page can
|
||||||
|
// show which feed supplied each field.
|
||||||
|
func TestProductDetailsExposeFeedFieldSources(t *testing.T) {
|
||||||
|
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("DATABASE_URL not set")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
pg, err := pgxpool.New(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer pg.Close()
|
||||||
|
|
||||||
|
companyID := uuid.New()
|
||||||
|
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, companyID, "ffs-"+companyID.String()[:8]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _, _ = pg.Exec(context.Background(), `DELETE FROM companies WHERE id = $1`, companyID) })
|
||||||
|
|
||||||
|
var feedA, feedB uuid.UUID
|
||||||
|
for name, dst := range map[string]*uuid.UUID{"Vendor A": &feedA, "Vendor B": &feedB} {
|
||||||
|
if err := pg.QueryRow(ctx, `
|
||||||
|
INSERT INTO input_feeds (company_id, name, url, feed_type, status, sync_interval_minutes, options)
|
||||||
|
VALUES ($1, $2, 'https://example.com/f.csv', 'csv', 'active', 60, '{}'::jsonb) RETURNING id`,
|
||||||
|
companyID, name).Scan(dst); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sources := `{"primary":{"feed_id":"` + feedA.String() + `","feed_name":"Vendor A"},
|
||||||
|
"feeds":[{"feed_id":"` + feedA.String() + `","feed_name":"Vendor A"},{"feed_id":"` + feedB.String() + `","feed_name":"Vendor B"}],
|
||||||
|
"fields":{"description":{"feed_id":"` + feedB.String() + `","feed_name":"Vendor B","conflict":true,"also":[{"feed_id":"` + feedA.String() + `","feed_name":"Vendor A"}]},
|
||||||
|
"brand":{"feed_id":"` + feedA.String() + `","feed_name":"Vendor A"}}}`
|
||||||
|
var rawID, procID uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `
|
||||||
|
INSERT INTO raw_products (company_id, gtin, feed_id, mapped_data, feed_field_sources)
|
||||||
|
VALUES ($1, '4548736180307', $2, '{"name":"TV","brand":"Sony"}'::jsonb, $3::jsonb) RETURNING id`,
|
||||||
|
companyID, feedA, sources).Scan(&rawID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := pg.QueryRow(ctx, `
|
||||||
|
INSERT INTO processed_products (company_id, raw_product_id, product_id, name)
|
||||||
|
VALUES ($1, $2, '4548736180307', 'TV') RETURNING id`, companyID, rawID).Scan(&procID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := &Service{Pool: pg}
|
||||||
|
for name, load := range map[string]func() (map[string]any, error){
|
||||||
|
"processed": func() (map[string]any, error) { return svc.GetProcessedProduct(ctx, companyID, procID) },
|
||||||
|
"raw": func() (map[string]any, error) { return svc.GetRawProduct(ctx, companyID, rawID) },
|
||||||
|
} {
|
||||||
|
item, err := load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
ffs, ok := item["feed_field_sources"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%s: feed_field_sources missing or wrong type: %#v", name, item["feed_field_sources"])
|
||||||
|
}
|
||||||
|
fields, _ := ffs["fields"].(map[string]any)
|
||||||
|
desc, _ := fields["description"].(map[string]any)
|
||||||
|
if desc["feed_name"] != "Vendor B" || desc["conflict"] != true {
|
||||||
|
t.Errorf("%s: description source = %#v", name, desc)
|
||||||
|
}
|
||||||
|
if feeds, _ := ffs["feeds"].([]any); len(feeds) != 2 {
|
||||||
|
t.Errorf("%s: feeds = %#v", name, ffs["feeds"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A product synced before merging existed has no sources: the key is present but empty.
|
||||||
|
if _, err := pg.Exec(ctx, `UPDATE raw_products SET feed_field_sources = NULL WHERE id = $1`, rawID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
item, err := svc.GetRawProduct(ctx, companyID, rawID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if v := item["feed_field_sources"]; v != nil {
|
||||||
|
t.Errorf("NULL sources should surface as nil, got %#v", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,7 +16,10 @@ import (
|
|||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
const maxUploadBytes = 5 << 20 // 5 MiB
|
const (
|
||||||
|
maxUploadBytes = 5 << 20 // 5 MiB
|
||||||
|
maxFeedUploadBytes = 32 << 20 // 32 MiB; feeds.maxExcelBytes is the Excel parse-time cap
|
||||||
|
)
|
||||||
|
|
||||||
func sanitizeFileName(name string) string {
|
func sanitizeFileName(name string) string {
|
||||||
name = filepath.Base(strings.TrimSpace(name))
|
name = filepath.Base(strings.TrimSpace(name))
|
||||||
@@ -43,13 +46,35 @@ func (s *Service) SaveUpload(ctx context.Context, companyID, userID uuid.UUID, u
|
|||||||
if uploadDir == "" {
|
if uploadDir == "" {
|
||||||
return nil, ClientMsg("upload directory not configured")
|
return nil, ClientMsg("upload directory not configured")
|
||||||
}
|
}
|
||||||
|
kind = strings.ToLower(strings.TrimSpace(kind))
|
||||||
safe := sanitizeFileName(originalName)
|
safe := sanitizeFileName(originalName)
|
||||||
lower := strings.ToLower(safe)
|
lower := strings.ToLower(safe)
|
||||||
if !strings.HasSuffix(lower, ".csv") {
|
isCSV := strings.HasSuffix(lower, ".csv") || strings.HasSuffix(lower, ".tsv")
|
||||||
return nil, ClientMsg("only .csv uploads are allowed")
|
isXML := strings.HasSuffix(lower, ".xml") && kind == "feed"
|
||||||
|
isJSON := strings.HasSuffix(lower, ".json")
|
||||||
|
// .zip = several workbooks as one feed (e.g. one GroupeSeb product sheet per file).
|
||||||
|
isExcel := kind == "feed" && (strings.HasSuffix(lower, ".xls") || strings.HasSuffix(lower, ".xlsx") || strings.HasSuffix(lower, ".xlsm") || strings.HasSuffix(lower, ".zip"))
|
||||||
|
if !isCSV && !isXML && !isJSON && !isExcel {
|
||||||
|
return nil, ClientMsg("only CSV, JSON, XML, Excel or zipped Excel feed uploads are allowed")
|
||||||
}
|
}
|
||||||
if contentType != "" &&
|
limit := int64(maxUploadBytes)
|
||||||
|
if kind == "feed" {
|
||||||
|
// Supplier catalogs (full XML exports, workbooks with embedded photos) run well past 5 MiB.
|
||||||
|
limit = maxFeedUploadBytes
|
||||||
|
}
|
||||||
|
ctLower := strings.ToLower(contentType)
|
||||||
|
if isExcel && contentType != "" &&
|
||||||
|
!strings.Contains(ctLower, "excel") &&
|
||||||
|
!strings.Contains(ctLower, "spreadsheetml") &&
|
||||||
|
!strings.Contains(ctLower, "octet-stream") &&
|
||||||
|
!strings.Contains(ctLower, "zip") {
|
||||||
|
return nil, ClientMsg("invalid content type for Excel upload")
|
||||||
|
}
|
||||||
|
if !isExcel && contentType != "" &&
|
||||||
!strings.Contains(strings.ToLower(contentType), "csv") &&
|
!strings.Contains(strings.ToLower(contentType), "csv") &&
|
||||||
|
!strings.Contains(strings.ToLower(contentType), "json") &&
|
||||||
|
!strings.Contains(strings.ToLower(contentType), "xml") &&
|
||||||
|
!strings.Contains(strings.ToLower(contentType), "tab-separated") &&
|
||||||
!strings.Contains(strings.ToLower(contentType), "text/plain") &&
|
!strings.Contains(strings.ToLower(contentType), "text/plain") &&
|
||||||
!strings.Contains(strings.ToLower(contentType), "octet-stream") {
|
!strings.Contains(strings.ToLower(contentType), "octet-stream") {
|
||||||
return nil, ClientMsg("invalid content type for CSV upload")
|
return nil, ClientMsg("invalid content type for CSV upload")
|
||||||
@@ -75,14 +100,14 @@ func (s *Service) SaveUpload(ctx context.Context, companyID, userID uuid.UUID, u
|
|||||||
}
|
}
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
n, err := io.Copy(f, io.LimitReader(r, maxUploadBytes+1))
|
n, err := io.Copy(f, io.LimitReader(r, limit+1))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = os.Remove(abs)
|
_ = os.Remove(abs)
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if n > maxUploadBytes {
|
if n > limit {
|
||||||
_ = os.Remove(abs)
|
_ = os.Remove(abs)
|
||||||
return nil, ClientMsg(fmt.Sprintf("file exceeds %d byte limit", maxUploadBytes))
|
return nil, ClientMsg(fmt.Sprintf("file exceeds %d byte limit", limit))
|
||||||
}
|
}
|
||||||
|
|
||||||
var uid any
|
var uid any
|
||||||
|
|||||||
@@ -412,3 +412,15 @@ func TestSanitizeFileName(t *testing.T) {
|
|||||||
t.Fatalf("got %q", sanitizeFileName("a b*.csv"))
|
t.Fatalf("got %q", sanitizeFileName("a b*.csv"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Historical API processing predates origin tagging. Generated fields remain
|
||||||
|
// visible in Processed without silently transitioning review-state records.
|
||||||
|
func TestGeneratedProductFilterIncludesLegacyContent(t *testing.T) {
|
||||||
|
_, where := appendProcessedProductFilters(ProductFilter{Status: "generated"}, nil, nil)
|
||||||
|
joined := strings.Join(where, " ")
|
||||||
|
for _, value := range []string{"p.status = 'completed'", "p.processed_name", "p.processed_description", "p.meta_title", "p.meta_description", "needs_review"} {
|
||||||
|
if !strings.Contains(joined, value) {
|
||||||
|
t.Fatalf("missing %s in generated filter: %s", value, joined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,7 +37,7 @@ func headerIndex(headers []string, names ...string) int {
|
|||||||
want[strings.ToLower(strings.TrimSpace(n))] = struct{}{}
|
want[strings.ToLower(strings.TrimSpace(n))] = struct{}{}
|
||||||
}
|
}
|
||||||
for i, h := range headers {
|
for i, h := range headers {
|
||||||
if _, ok := want[strings.ToLower(strings.TrimSpace(h))]; ok {
|
if _, ok := want[strings.ToLower(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(h), "\uFEFF")))]; ok {
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,6 +124,7 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
|
|||||||
if len(batch) == 0 {
|
if len(batch) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
lang, primary := s.importLanguage(ctx, companyID)
|
||||||
|
|
||||||
byUID := make(map[string]categoryCSVRow, len(batch))
|
byUID := make(map[string]categoryCSVRow, len(batch))
|
||||||
order := make([]string, 0, len(batch))
|
order := make([]string, 0, len(batch))
|
||||||
@@ -184,12 +185,15 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
|
|||||||
if len(updIDs) > 0 {
|
if len(updIDs) > 0 {
|
||||||
_, err = tx.Exec(ctx, `
|
_, err = tx.Exec(ctx, `
|
||||||
UPDATE categories AS c SET
|
UPDATE categories AS c SET
|
||||||
name = v.name,
|
name = CASE WHEN $5 THEN v.name ELSE c.name END,
|
||||||
description = CASE WHEN v.description <> '' THEN v.description ELSE c.description END,
|
description = CASE WHEN $5 AND v.description <> '' THEN v.description ELSE c.description END,
|
||||||
|
localized_fields = jsonb_set(COALESCE(c.localized_fields, '{}'::jsonb), ARRAY[$6::text],
|
||||||
|
COALESCE(c.localized_fields -> ($6::text), '{}'::jsonb) ||
|
||||||
|
jsonb_strip_nulls(jsonb_build_object('name', NULLIF(v.name,''), 'description',NULLIF(v.description,''))), true),
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, description)
|
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, description)
|
||||||
WHERE c.id = v.id AND c.company_id = $1`,
|
WHERE c.id = v.id AND c.company_id = $1`,
|
||||||
companyID, updIDs, updNames, updDescs)
|
companyID, updIDs, updNames, updDescs, primary, lang)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -228,12 +232,13 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
|
|||||||
}
|
}
|
||||||
|
|
||||||
rows, err := tx.Query(ctx, `
|
rows, err := tx.Query(ctx, `
|
||||||
INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, level)
|
INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, level, localized_fields)
|
||||||
SELECT $1, v.name, v.unique_id, NULLIF(v.parent_unique_id, ''), NULLIF(v.description, ''), v.path, v.level
|
SELECT $1, v.name, v.unique_id, NULLIF(v.parent_unique_id, ''), NULLIF(v.description, ''), v.path, v.level,
|
||||||
|
jsonb_build_object($8::text, jsonb_strip_nulls(jsonb_build_object('name',v.name,'description',NULLIF(v.description,''))))
|
||||||
FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::int[])
|
FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::int[])
|
||||||
AS v(name, unique_id, parent_unique_id, description, path, level)
|
AS v(name, unique_id, parent_unique_id, description, path, level)
|
||||||
RETURNING id, unique_id, COALESCE(path, ''), level`,
|
RETURNING id, unique_id, COALESCE(path, ''), level`,
|
||||||
companyID, insNames, insUIDs, insParents, insDescs, insPaths, insLevels)
|
companyID, insNames, insUIDs, insParents, insDescs, insPaths, insLevels, lang)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -396,6 +401,7 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
|
|||||||
if len(batch) == 0 {
|
if len(batch) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
lang, primary := s.importLanguage(ctx, companyID)
|
||||||
|
|
||||||
byKey := make(map[string]attributeCSVRow, len(batch))
|
byKey := make(map[string]attributeCSVRow, len(batch))
|
||||||
order := make([]string, 0, len(batch))
|
order := make([]string, 0, len(batch))
|
||||||
@@ -465,12 +471,14 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
|
|||||||
if len(updIDs) > 0 {
|
if len(updIDs) > 0 {
|
||||||
_, err = tx.Exec(ctx, `
|
_, err = tx.Exec(ctx, `
|
||||||
UPDATE attributes AS a SET
|
UPDATE attributes AS a SET
|
||||||
name = CASE WHEN v.name <> '' THEN v.name ELSE a.name END,
|
name = CASE WHEN $5 AND v.name <> '' THEN v.name ELSE a.name END,
|
||||||
value_type = CASE WHEN v.value_type <> '' THEN v.value_type ELSE a.value_type END,
|
value_type = CASE WHEN v.value_type <> '' THEN v.value_type ELSE a.value_type END,
|
||||||
|
localized_fields = jsonb_set(COALESCE(a.localized_fields,'{}'::jsonb), ARRAY[$6::text],
|
||||||
|
COALESCE(a.localized_fields -> ($6::text),'{}'::jsonb) || jsonb_build_object('name',v.name), true),
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, value_type)
|
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, value_type)
|
||||||
WHERE a.id = v.id AND a.company_id = $1`,
|
WHERE a.id = v.id AND a.company_id = $1`,
|
||||||
companyID, updIDs, updNames, updTypes)
|
companyID, updIDs, updNames, updTypes, primary, lang)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -479,12 +487,13 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
|
|||||||
|
|
||||||
if len(insKeys) > 0 {
|
if len(insKeys) > 0 {
|
||||||
ct, err := tx.Exec(ctx, `
|
ct, err := tx.Exec(ctx, `
|
||||||
INSERT INTO attributes (company_id, attribute_key, name, value_type, unit, example, parent_key)
|
INSERT INTO attributes (company_id, attribute_key, name, value_type, unit, example, parent_key, localized_fields)
|
||||||
SELECT $1, v.attribute_key, v.name, v.value_type,
|
SELECT $1, v.attribute_key, v.name, v.value_type,
|
||||||
NULLIF(v.unit, ''), NULLIF(v.example, ''), NULLIF(v.parent_key, '')
|
NULLIF(v.unit, ''), NULLIF(v.example, ''), NULLIF(v.parent_key, ''),
|
||||||
|
jsonb_build_object($8::text, jsonb_build_object('name',v.name))
|
||||||
FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
||||||
AS v(attribute_key, name, value_type, unit, example, parent_key)`,
|
AS v(attribute_key, name, value_type, unit, example, parent_key)`,
|
||||||
companyID, insKeys, insNames, insTypes, insUnits, insExamples, insParents)
|
companyID, insKeys, insNames, insTypes, insUnits, insExamples, insParents, lang)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -500,6 +509,13 @@ func (s *Service) MergeProductsByGTIN(ctx context.Context, companyID uuid.UUID)
|
|||||||
return merge, err
|
return merge, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// shouldMergeProductCSV reuses an existing GTIN for regular merge-enabled feeds
|
||||||
|
// and for non-primary-language imports, which add localizations to the same product.
|
||||||
|
// Generated no-GTIN identifiers must always create separate products.
|
||||||
|
func shouldMergeProductCSV(allowMerge, isPrimary bool, gtin string) bool {
|
||||||
|
return (allowMerge || !isPrimary) && !strings.HasPrefix(gtin, "nogtin-")
|
||||||
|
}
|
||||||
|
|
||||||
type productCSVRow struct {
|
type productCSVRow struct {
|
||||||
gtin, productID, name, category, desc, status string
|
gtin, productID, name, category, desc, status string
|
||||||
rawJSON string
|
rawJSON string
|
||||||
@@ -508,6 +524,7 @@ type productCSVRow struct {
|
|||||||
|
|
||||||
func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r io.Reader, fileID *uuid.UUID) (ImportResult, error) {
|
func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r io.Reader, fileID *uuid.UUID) (ImportResult, error) {
|
||||||
res := ImportResult{}
|
res := ImportResult{}
|
||||||
|
_, primary := s.importLanguage(ctx, companyID)
|
||||||
merge, err := s.MergeProductsByGTIN(ctx, companyID)
|
merge, err := s.MergeProductsByGTIN(ctx, companyID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return res, err
|
return res, err
|
||||||
@@ -566,7 +583,7 @@ func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r
|
|||||||
batch = append(batch, productCSVRow{
|
batch = append(batch, productCSVRow{
|
||||||
gtin: gtin, productID: productID, name: name, category: category,
|
gtin: gtin, productID: productID, name: name, category: category,
|
||||||
desc: desc, status: status, rawJSON: string(rawData),
|
desc: desc, status: status, rawJSON: string(rawData),
|
||||||
mergeable: merge && !strings.HasPrefix(gtin, "nogtin-"),
|
mergeable: shouldMergeProductCSV(merge, primary, gtin),
|
||||||
})
|
})
|
||||||
if len(batch) >= importCSVBatchSize {
|
if len(batch) >= importCSVBatchSize {
|
||||||
if err := s.flushProductBatch(ctx, companyID, fileID, batch, &res); err != nil {
|
if err := s.flushProductBatch(ctx, companyID, fileID, batch, &res); err != nil {
|
||||||
@@ -585,6 +602,7 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
|
|||||||
if len(batch) == 0 {
|
if len(batch) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
lang, primary := s.importLanguage(ctx, companyID)
|
||||||
|
|
||||||
// Last row wins per GTIN so a single INSERT cannot hit the same unique key twice.
|
// Last row wins per GTIN so a single INSERT cannot hit the same unique key twice.
|
||||||
byGTIN := make(map[string]productCSVRow, len(batch))
|
byGTIN := make(map[string]productCSVRow, len(batch))
|
||||||
@@ -677,13 +695,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
|
|||||||
if len(updRawIDs) > 0 {
|
if len(updRawIDs) > 0 {
|
||||||
_, err = tx.Exec(ctx, `
|
_, err = tx.Exec(ctx, `
|
||||||
UPDATE raw_products AS r SET
|
UPDATE raw_products AS r SET
|
||||||
raw_data = v.raw_data::jsonb,
|
raw_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.raw_data END,
|
||||||
mapped_data = v.raw_data::jsonb,
|
mapped_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.mapped_data END,
|
||||||
|
source_localizations = jsonb_set(COALESCE(r.source_localizations,'{}'::jsonb), ARRAY[$5::text],
|
||||||
|
COALESCE(r.source_localizations -> ($5::text),'{}'::jsonb) || v.raw_data::jsonb, true),
|
||||||
file_id = COALESCE($3, r.file_id),
|
file_id = COALESCE($3, r.file_id),
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
FROM unnest($2::uuid[], $4::text[]) AS v(id, raw_data)
|
FROM unnest($2::uuid[], $4::text[]) AS v(id, raw_data)
|
||||||
WHERE r.id = v.id AND r.company_id = $1`,
|
WHERE r.id = v.id AND r.company_id = $1`,
|
||||||
companyID, updRawIDs, fileID, updRawJSON)
|
companyID, updRawIDs, fileID, updRawJSON, lang, primary)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -694,12 +714,13 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
|
|||||||
|
|
||||||
if len(insGTINs) > 0 {
|
if len(insGTINs) > 0 {
|
||||||
rows, err := tx.Query(ctx, `
|
rows, err := tx.Query(ctx, `
|
||||||
INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id)
|
INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id, source_localizations)
|
||||||
SELECT $1, v.gtin, v.raw_data::jsonb, v.raw_data::jsonb, 'unprocessed', $2
|
SELECT $1, v.gtin, v.raw_data::jsonb, v.raw_data::jsonb, 'unprocessed', $2,
|
||||||
|
jsonb_build_object($5::text, v.raw_data::jsonb)
|
||||||
FROM unnest($3::text[], $4::text[]) AS v(gtin, raw_data)
|
FROM unnest($3::text[], $4::text[]) AS v(gtin, raw_data)
|
||||||
ON CONFLICT (company_id, gtin) DO NOTHING
|
ON CONFLICT (company_id, gtin) DO NOTHING
|
||||||
RETURNING id, gtin`,
|
RETURNING id, gtin`,
|
||||||
companyID, fileID, insGTINs, insJSON)
|
companyID, fileID, insGTINs, insJSON, lang)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -803,15 +824,18 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
|
|||||||
_, err = tx.Exec(ctx, `
|
_, err = tx.Exec(ctx, `
|
||||||
UPDATE processed_products AS p SET
|
UPDATE processed_products AS p SET
|
||||||
product_id = COALESCE(NULLIF(v.product_id, ''), p.product_id),
|
product_id = COALESCE(NULLIF(v.product_id, ''), p.product_id),
|
||||||
name = COALESCE(NULLIF(v.name, ''), p.name),
|
name = CASE WHEN $9 THEN COALESCE(NULLIF(v.name, ''), p.name) ELSE p.name END,
|
||||||
category = COALESCE(NULLIF(v.category, ''), p.category),
|
category = CASE WHEN $9 THEN COALESCE(NULLIF(v.category, ''), p.category) ELSE p.category END,
|
||||||
description = COALESCE(NULLIF(v.description, ''), p.description),
|
description = CASE WHEN $9 THEN COALESCE(NULLIF(v.description, ''), p.description) ELSE p.description END,
|
||||||
status = COALESCE(NULLIF(v.status, ''), p.status),
|
status = CASE WHEN $9 THEN COALESCE(NULLIF(v.status, ''), p.status) ELSE p.status END,
|
||||||
|
source_localizations = jsonb_set(COALESCE(p.source_localizations,'{}'::jsonb), ARRAY[$8::text],
|
||||||
|
COALESCE(p.source_localizations -> ($8::text),'{}'::jsonb) || jsonb_strip_nulls(jsonb_build_object(
|
||||||
|
'name',NULLIF(v.name,''),'category',NULLIF(v.category,''),'description',NULLIF(v.description,''))),true),
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
||||||
AS v(id, product_id, name, category, description, status)
|
AS v(id, product_id, name, category, description, status)
|
||||||
WHERE p.id = v.id AND p.company_id = $1`,
|
WHERE p.id = v.id AND p.company_id = $1`,
|
||||||
companyID, updProcIDs, updPIDs, updNames, updCats, updDescs, updStatuses)
|
companyID, updProcIDs, updPIDs, updNames, updCats, updDescs, updStatuses, lang, primary)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -820,13 +844,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
|
|||||||
|
|
||||||
if len(insRawIDs) > 0 {
|
if len(insRawIDs) > 0 {
|
||||||
_, err = tx.Exec(ctx, `
|
_, err = tx.Exec(ctx, `
|
||||||
INSERT INTO processed_products (company_id, product_id, name, category, description, status, raw_product_id)
|
INSERT INTO processed_products (company_id, product_id, name, category, description, status, raw_product_id, source_localizations)
|
||||||
SELECT $1,
|
SELECT $1,
|
||||||
NULLIF(v.product_id, ''), NULLIF(v.name, ''), NULLIF(v.category, ''),
|
NULLIF(v.product_id, ''), NULLIF(v.name, ''), NULLIF(v.category, ''),
|
||||||
NULLIF(v.description, ''), v.status, v.raw_product_id
|
NULLIF(v.description, ''), v.status, v.raw_product_id,
|
||||||
|
jsonb_build_object($8::text, jsonb_strip_nulls(jsonb_build_object(
|
||||||
|
'name', NULLIF(v.name,''), 'category',NULLIF(v.category,''), 'description',NULLIF(v.description,''))))
|
||||||
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
||||||
AS v(raw_product_id, product_id, name, category, description, status)`,
|
AS v(raw_product_id, product_id, name, category, description, status)`,
|
||||||
companyID, insRawIDs, insPIDs, insNames, insCats, insDescs, insStatuses)
|
companyID, insRawIDs, insPIDs, insNames, insCats, insDescs, insStatuses, lang)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,37 @@ func TestHeaderIndexAndCell(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHeaderIndexUTF8BOM(t *testing.T) {
|
||||||
|
for _, name := range []string{"\uFEFFgtin", " \uFEFFname ", "\uFEFFattribute_key"} {
|
||||||
|
want := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(name), "\uFEFF"))
|
||||||
|
if got := headerIndex([]string{name, "other"}, want); got != 0 {
|
||||||
|
t.Fatalf("UTF-8 BOM column %q: got %d want 0", name, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShouldMergeProductCSV(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name, gtin string
|
||||||
|
allow, primary bool
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "primary feed without merging", gtin: "3830000000017", primary: true, want: false},
|
||||||
|
{name: "primary feed with merging", gtin: "3830000000017", allow: true, primary: true, want: true},
|
||||||
|
{name: "secondary language without merging configured", gtin: "3830000000017", primary: false, want: true},
|
||||||
|
{name: "secondary language with merging configured", gtin: "3830000000017", allow: true, primary: false, want: true},
|
||||||
|
{name: "generated GTIN primary", gtin: "nogtin-test", allow: true, primary: true, want: false},
|
||||||
|
{name: "generated GTIN secondary", gtin: "nogtin-test", allow: true, primary: false, want: false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := shouldMergeProductCSV(tt.allow, tt.primary, tt.gtin); got != tt.want {
|
||||||
|
t.Fatalf("mergeable = %t, want %t", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestImportResultAddErrorCaps(t *testing.T) {
|
func TestImportResultAddErrorCaps(t *testing.T) {
|
||||||
res := ImportResult{}
|
res := ImportResult{}
|
||||||
for i := 0; i < importCSVMaxErrors+20; i++ {
|
for i := 0; i < importCSVMaxErrors+20; i++ {
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/csv"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// JSONImportAsCSV maps JSON arrays (including wrapped nested arrays) onto the
|
||||||
|
// same validated batch import pipeline as CSV. Data must fit the catalog upload
|
||||||
|
// limit. All rows are processed by the normal company-scoped upsert routines.
|
||||||
|
func JSONImportAsCSV(r io.Reader, kind string) (io.Reader, error) {
|
||||||
|
source, err := io.ReadAll(io.LimitReader(r, (6<<20)+1))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(source) > 6<<20 {
|
||||||
|
return nil, ClientMsg("JSON catalog import exceeds 6 MiB")
|
||||||
|
}
|
||||||
|
var doc any
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(source))
|
||||||
|
dec.UseNumber()
|
||||||
|
if err := dec.Decode(&doc); err != nil {
|
||||||
|
return nil, ClientMsg("invalid JSON import: " + err.Error())
|
||||||
|
}
|
||||||
|
items := findImportJSONArray(doc, kind, 0)
|
||||||
|
if len(items) == 0 {
|
||||||
|
return nil, ClientMsg("JSON must contain an array of " + kind)
|
||||||
|
}
|
||||||
|
header := []string{}
|
||||||
|
switch kind {
|
||||||
|
case "categories":
|
||||||
|
header = []string{"name", "unique_id", "parent_unique_id", "description"}
|
||||||
|
case "attributes":
|
||||||
|
header = []string{"attribute_key", "name", "value_type", "unit", "example", "parent_key", "category_id"}
|
||||||
|
case "products":
|
||||||
|
header = []string{"gtin", "product_id", "name", "category", "description", "status"}
|
||||||
|
default:
|
||||||
|
return nil, ClientMsg("invalid catalog import kind")
|
||||||
|
}
|
||||||
|
// Keep original JSON keys too; importer uses known column names (GTIN/EAN, etc).
|
||||||
|
keys := map[string]struct{}{}
|
||||||
|
for _, k := range header {
|
||||||
|
keys[k] = struct{}{}
|
||||||
|
}
|
||||||
|
for _, v := range items {
|
||||||
|
if m, ok := v.(map[string]any); ok {
|
||||||
|
for k := range m {
|
||||||
|
keys[k] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
extras := make([]string, 0, len(keys))
|
||||||
|
for k := range keys {
|
||||||
|
found := false
|
||||||
|
for _, h := range header {
|
||||||
|
if k == h {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
extras = append(extras, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(extras)
|
||||||
|
header = append(header, extras...)
|
||||||
|
var buf bytes.Buffer
|
||||||
|
cw := csv.NewWriter(&buf)
|
||||||
|
if err := cw.Write(header); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, v := range items {
|
||||||
|
m, ok := v.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rec := make([]string, len(header))
|
||||||
|
for j, k := range header {
|
||||||
|
val, exists := m[k]
|
||||||
|
if !exists && (k == "gtin" || k == "product_id" || k == "name" || k == "unique_id" || k == "attribute_key") {
|
||||||
|
aliases := map[string][]string{"gtin": {"ean", "barcode", "gtin"}, "product_id": {"sku", "productno", "productno2", "id"}, "name": {"title", "product", "product_name", "productname"}, "unique_id": {"id", "category_id", "uniqueId"}, "attribute_key": {"key", "attributeKey", "id"}}
|
||||||
|
for _, alias := range aliases[k] {
|
||||||
|
for source, value := range m {
|
||||||
|
if strings.EqualFold(source, alias) && value != nil {
|
||||||
|
val = value
|
||||||
|
exists = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
for source, value := range m {
|
||||||
|
if strings.EqualFold(source, k) {
|
||||||
|
val = value
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if val == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch x := val.(type) {
|
||||||
|
case string:
|
||||||
|
rec[j] = x
|
||||||
|
case json.Number:
|
||||||
|
rec[j] = string(x)
|
||||||
|
case bool:
|
||||||
|
rec[j] = fmt.Sprint(x)
|
||||||
|
default:
|
||||||
|
b, _ := json.Marshal(x)
|
||||||
|
rec[j] = string(b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := cw.Write(rec); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cw.Flush()
|
||||||
|
if err := cw.Error(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return bytes.NewReader(buf.Bytes()), nil
|
||||||
|
}
|
||||||
|
func findImportJSONArray(doc any, kind string, depth int) []any {
|
||||||
|
if depth > 6 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if items, ok := doc.([]any); ok {
|
||||||
|
if len(items) > 0 {
|
||||||
|
if _, ok := items[0].(map[string]any); ok {
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m, ok := doc.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
keys := []string{kind, "items", "results", "data", "records", "rows"}
|
||||||
|
if kind == "products" {
|
||||||
|
keys = append([]string{"SHOPITEM", "products", "product"}, keys...)
|
||||||
|
}
|
||||||
|
if kind == "categories" {
|
||||||
|
keys = append([]string{"categories", "category"}, keys...)
|
||||||
|
}
|
||||||
|
if kind == "attributes" {
|
||||||
|
keys = append([]string{"attributes", "specifications"}, keys...)
|
||||||
|
}
|
||||||
|
for _, k := range keys {
|
||||||
|
for actual, value := range m {
|
||||||
|
if strings.EqualFold(actual, k) {
|
||||||
|
if a := findImportJSONArray(value, kind, depth+1); len(a) > 0 {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(m) == 1 {
|
||||||
|
for _, v := range m {
|
||||||
|
return findImportJSONArray(v, kind, depth+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type importLanguageContextKey struct{}
|
||||||
|
|
||||||
|
// WithImportLanguage marks the language of a supplier import. An empty code means
|
||||||
|
// the company primary language. The HTTP layer validates explicit codes.
|
||||||
|
func WithImportLanguage(ctx context.Context, lang string) context.Context {
|
||||||
|
return context.WithValue(ctx, importLanguageContextKey{}, lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) importLanguage(ctx context.Context, companyID uuid.UUID) (string, bool) {
|
||||||
|
primary := company.LoadLanguage(ctx, s.Pool, companyID)
|
||||||
|
lang, _ := ctx.Value(importLanguageContextKey{}).(string)
|
||||||
|
if lang == "" {
|
||||||
|
lang = primary
|
||||||
|
}
|
||||||
|
return lang, lang == primary
|
||||||
|
}
|
||||||
|
|
||||||
|
// localizeCatalogImportNames changes presentation only; it never overwrites
|
||||||
|
// the primary-language columns in storage. The full translations map remains
|
||||||
|
// present in API responses for clients that need several languages.
|
||||||
|
func localizeCatalogImportNames(ctx context.Context, items []map[string]any) {
|
||||||
|
lang, _ := ctx.Value(importLanguageContextKey{}).(string)
|
||||||
|
if lang == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, item := range items {
|
||||||
|
var all map[string]map[string]string
|
||||||
|
switch raw := item["localized_fields"].(type) {
|
||||||
|
case []byte:
|
||||||
|
_ = json.Unmarshal(raw, &all)
|
||||||
|
case string:
|
||||||
|
_ = json.Unmarshal([]byte(raw), &all)
|
||||||
|
default:
|
||||||
|
b, _ := json.Marshal(raw)
|
||||||
|
_ = json.Unmarshal(b, &all)
|
||||||
|
}
|
||||||
|
if fields := all[lang]; fields != nil {
|
||||||
|
if val := fields["name"]; val != "" {
|
||||||
|
item["name"] = val
|
||||||
|
}
|
||||||
|
if val := fields["description"]; val != "" {
|
||||||
|
item["description"] = val
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLocalizedImportViewPreservesPrimary(t *testing.T) {
|
||||||
|
rows := []map[string]any{{
|
||||||
|
"name": "Shower mixer", "description": "Chrome mixer",
|
||||||
|
"localized_fields": map[string]any{
|
||||||
|
"en": map[string]any{"name": "Shower mixer", "description": "Chrome mixer"},
|
||||||
|
"sl": map[string]any{"name": "Armatura za prho", "description": "Kromirana armatura"},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
localizeCatalogImportNames(WithImportLanguage(context.Background(), "sl"), rows)
|
||||||
|
if rows[0]["name"] != "Armatura za prho" || rows[0]["description"] != "Kromirana armatura" {
|
||||||
|
t.Fatalf("wrong Slovenian fields: %+v", rows[0])
|
||||||
|
}
|
||||||
|
localizeCatalogImportNames(WithImportLanguage(context.Background(), "en"), rows)
|
||||||
|
if rows[0]["name"] != "Shower mixer" {
|
||||||
|
t.Fatalf("English label not restored: %+v", rows[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -285,6 +285,7 @@ func loadA1CategoryPromptOverlays(path string) (byNorm map[string]string, byUID
|
|||||||
}
|
}
|
||||||
for _, e := range f.Entries {
|
for _, e := range f.Entries {
|
||||||
p := strings.TrimSpace(e.Prompt)
|
p := strings.TrimSpace(e.Prompt)
|
||||||
|
p, _ = aiprompts.NormalizeA1RepeatedBenefits(p)
|
||||||
if p == "" {
|
if p == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -410,7 +411,11 @@ func computeRepairedEnhancePrompt(current company.LangPromptMap, seedLegacy stri
|
|||||||
return "", false, false
|
return "", false, false
|
||||||
}
|
}
|
||||||
if aiprompts.IsLegacyCombinedEnhancePrompt(raw) {
|
if aiprompts.IsLegacyCombinedEnhancePrompt(raw) {
|
||||||
return aiprompts.SplitLegacyCombinedEnhancePrompt(raw), true, false
|
split := aiprompts.SplitLegacyCombinedEnhancePrompt(raw)
|
||||||
|
if fixed, ok := aiprompts.NormalizeA1MetaRole(split, "sl"); ok {
|
||||||
|
split = fixed
|
||||||
|
}
|
||||||
|
return split, true, false
|
||||||
}
|
}
|
||||||
if aiprompts.CategoryEnhanceHasRoleSections(raw) && !aiprompts.CategoryEnhancePromptNeedsRepair(raw) {
|
if aiprompts.CategoryEnhanceHasRoleSections(raw) && !aiprompts.CategoryEnhancePromptNeedsRepair(raw) {
|
||||||
return security.SanitizePrompt(raw, MaxCategoryPromptRunes), false, false
|
return security.SanitizePrompt(raw, MaxCategoryPromptRunes), false, false
|
||||||
@@ -424,12 +429,24 @@ func computeRepairedEnhancePrompt(current company.LangPromptMap, seedLegacy stri
|
|||||||
}
|
}
|
||||||
for _, lang := range []string{"sl", company.LangPromptAny} {
|
for _, lang := range []string{"sl", company.LangPromptAny} {
|
||||||
if cur := strings.TrimSpace(current[lang]); aiprompts.IsLegacyCombinedEnhancePrompt(cur) {
|
if cur := strings.TrimSpace(current[lang]); aiprompts.IsLegacyCombinedEnhancePrompt(cur) {
|
||||||
return aiprompts.SplitLegacyCombinedEnhancePrompt(cur), false, true, false
|
return func() string {
|
||||||
|
split := aiprompts.SplitLegacyCombinedEnhancePrompt(cur)
|
||||||
|
if fixed, ok := aiprompts.NormalizeA1MetaRole(split, "sl"); ok {
|
||||||
|
return fixed
|
||||||
|
}
|
||||||
|
return split
|
||||||
|
}(), false, true, false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, cur := range current {
|
for _, cur := range current {
|
||||||
if aiprompts.IsLegacyCombinedEnhancePrompt(cur) {
|
if aiprompts.IsLegacyCombinedEnhancePrompt(cur) {
|
||||||
return aiprompts.SplitLegacyCombinedEnhancePrompt(cur), false, true, false
|
return func() string {
|
||||||
|
split := aiprompts.SplitLegacyCombinedEnhancePrompt(cur)
|
||||||
|
if fixed, ok := aiprompts.NormalizeA1MetaRole(split, "sl"); ok {
|
||||||
|
return fixed
|
||||||
|
}
|
||||||
|
return split
|
||||||
|
}(), false, true, false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if seedLegacy != "" {
|
if seedLegacy != "" {
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ func (s *Service) ListCategories(ctx context.Context, companyID uuid.UUID, f Lis
|
|||||||
off := len(args)
|
off := len(args)
|
||||||
rows, err := s.Pool.Query(ctx, fmt.Sprintf(`
|
rows, err := s.Pool.Query(ctx, fmt.Sprintf(`
|
||||||
SELECT id, name, unique_id, parent_unique_id, path, level, position, is_active, description,
|
SELECT id, name, unique_id, parent_unique_id, path, level, position, is_active, description,
|
||||||
title_template, description_template,
|
title_template, description_template, COALESCE(localized_fields,'{}'::jsonb) AS localized_fields,
|
||||||
(title_template IS NOT NULL AND jsonb_typeof(title_template) = 'object'
|
(title_template IS NOT NULL AND jsonb_typeof(title_template) = 'object'
|
||||||
AND COALESCE(jsonb_array_length(title_template->'elements'), 0) > 0) AS has_title_formula,
|
AND COALESCE(jsonb_array_length(title_template->'elements'), 0) > 0) AS has_title_formula,
|
||||||
(description_template IS NOT NULL AND jsonb_typeof(description_template) = 'object'
|
(description_template IS NOT NULL AND jsonb_typeof(description_template) = 'object'
|
||||||
@@ -113,12 +113,13 @@ func (s *Service) ListCategories(ctx context.Context, companyID uuid.UUID, f Lis
|
|||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
items, err := scanMaps(rows, []string{
|
items, err := scanMaps(rows, []string{
|
||||||
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description",
|
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description",
|
||||||
"title_template", "description_template", "has_title_formula", "has_description_formula", "has_prompt",
|
"title_template", "description_template", "localized_fields", "has_title_formula", "has_description_formula", "has_prompt",
|
||||||
"created_at", "updated_at",
|
"created_at", "updated_at",
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
localizeCatalogImportNames(ctx, items)
|
||||||
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
|
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
|
||||||
return items, total, nil
|
return items, total, nil
|
||||||
}
|
}
|
||||||
@@ -186,15 +187,16 @@ func (s *Service) GetCategory(ctx context.Context, companyID, id uuid.UUID) (map
|
|||||||
SELECT 1 FROM jsonb_each_text(COALESCE(prompt, '{}'::jsonb)) kv
|
SELECT 1 FROM jsonb_each_text(COALESCE(prompt, '{}'::jsonb)) kv
|
||||||
WHERE length(trim(kv.value)) > 0
|
WHERE length(trim(kv.value)) > 0
|
||||||
)) AS has_prompt,
|
)) AS has_prompt,
|
||||||
title_template, description_template, created_at, updated_at
|
title_template, description_template, COALESCE(localized_fields,'{}'::jsonb), created_at, updated_at
|
||||||
FROM categories WHERE id = $1 AND company_id = $2`, id, companyID)
|
FROM categories WHERE id = $1 AND company_id = $2`, id, companyID)
|
||||||
item, err := scanMap(row, []string{
|
item, err := scanMap(row, []string{
|
||||||
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description",
|
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description",
|
||||||
"prompts", "has_prompt", "title_template", "description_template", "created_at", "updated_at",
|
"prompts", "has_prompt", "title_template", "description_template", "localized_fields", "created_at", "updated_at",
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
localizeCatalogImportNames(ctx, []map[string]any{item})
|
||||||
return enrichCategoryPrompts(ctx, s.Pool, companyID, item)
|
return enrichCategoryPrompts(ctx, s.Pool, companyID, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,8 +379,8 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis
|
|||||||
args := []any{companyID}
|
args := []any{companyID}
|
||||||
where := []string{"a.company_id = $1"}
|
where := []string{"a.company_id = $1"}
|
||||||
from := "attributes a"
|
from := "attributes a"
|
||||||
selectCols := "a.id, a.attribute_key, a.name, a.value_type, a.unit, a.example, a.parent_key, a.created_at, a.updated_at"
|
selectCols := "a.id, a.attribute_key, a.name, a.value_type, a.unit, a.example, a.parent_key, COALESCE(a.localized_fields,'{}'::jsonb), a.created_at, a.updated_at"
|
||||||
scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "created_at", "updated_at"}
|
scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "localized_fields", "created_at", "updated_at"}
|
||||||
if f.Category != "" {
|
if f.Category != "" {
|
||||||
from = `attributes a
|
from = `attributes a
|
||||||
INNER JOIN category_attributes ca
|
INNER JOIN category_attributes ca
|
||||||
@@ -417,6 +419,7 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
localizeCatalogImportNames(ctx, items)
|
||||||
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
|
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
|
||||||
return items, total, nil
|
return items, total, nil
|
||||||
}
|
}
|
||||||
@@ -1071,6 +1074,20 @@ func appendProcessedProductFilters(f ProductFilter, args []any, where []string)
|
|||||||
n, n, n, n, n))
|
n, n, n, n, n))
|
||||||
}
|
}
|
||||||
if f.Status != "" {
|
if f.Status != "" {
|
||||||
|
// The dashboard's Processed tab must also surface already-generated legacy
|
||||||
|
// API results. Pre-v16 jobs were not tagged with their origin, so we cannot
|
||||||
|
// safely approve them in a migration. Include only rows with actual generated
|
||||||
|
// fields, preserving their original needs_review status and actions.
|
||||||
|
if f.Status == "generated" {
|
||||||
|
where = append(where, `(p.status = 'completed' OR
|
||||||
|
(p.status IN ('needs_review', 'processed') AND (
|
||||||
|
NULLIF(BTRIM(COALESCE(p.processed_name, '')), '') IS NOT NULL OR
|
||||||
|
NULLIF(BTRIM(COALESCE(p.processed_description, '')), '') IS NOT NULL OR
|
||||||
|
NULLIF(BTRIM(COALESCE(p.meta_title, '')), '') IS NOT NULL OR
|
||||||
|
NULLIF(BTRIM(COALESCE(p.meta_description, '')), '') IS NOT NULL
|
||||||
|
)))`)
|
||||||
|
return args, where
|
||||||
|
}
|
||||||
// needs_review includes legacy pipeline status "processed" (pre-P0-8).
|
// needs_review includes legacy pipeline status "processed" (pre-P0-8).
|
||||||
if f.Status == "needs_review" {
|
if f.Status == "needs_review" {
|
||||||
where = append(where, "p.status IN ('needs_review', 'processed')")
|
where = append(where, "p.status IN ('needs_review', 'processed')")
|
||||||
@@ -1159,7 +1176,7 @@ func (s *Service) ListProcessedProducts(ctx context.Context, companyID uuid.UUID
|
|||||||
p.category,
|
p.category,
|
||||||
cat.name AS category_name,
|
cat.name AS category_name,
|
||||||
COALESCE(cat.unique_id, NULLIF(BTRIM(p.category), '')) AS category_unique_id,
|
COALESCE(cat.unique_id, NULLIF(BTRIM(p.category), '')) AS category_unique_id,
|
||||||
p.status, p.raw_product_id, COALESCE(p.feed_id, r.feed_id) AS feed_id, r.gtin,
|
p.status, p.processing_origin, p.raw_product_id, COALESCE(p.feed_id, r.feed_id) AS feed_id, r.gtin,
|
||||||
f.name AS feed_name,
|
f.name AS feed_name,
|
||||||
f.last_synced_at AS feed_last_synced_at,
|
f.last_synced_at AS feed_last_synced_at,
|
||||||
r.updated_at AS raw_updated_at,
|
r.updated_at AS raw_updated_at,
|
||||||
@@ -1184,7 +1201,7 @@ func (s *Service) ListProcessedProducts(ctx context.Context, companyID uuid.UUID
|
|||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
items, err := scanMaps(rows, []string{
|
items, err := scanMaps(rows, []string{
|
||||||
"id", "product_id", "name", "original_name", "processed_name", "category", "category_name", "category_unique_id",
|
"id", "product_id", "name", "original_name", "processed_name", "category", "category_name", "category_unique_id",
|
||||||
"status", "raw_product_id", "feed_id", "gtin",
|
"status", "processing_origin", "raw_product_id", "feed_id", "gtin",
|
||||||
"feed_name", "feed_last_synced_at", "raw_updated_at",
|
"feed_name", "feed_last_synced_at", "raw_updated_at",
|
||||||
"has_name", "has_processed_name", "has_description", "has_processed_description", "has_category", "has_attributes", "has_processed_attributes",
|
"has_name", "has_processed_name", "has_description", "has_processed_description", "has_category", "has_attributes", "has_processed_attributes",
|
||||||
"has_eprel",
|
"has_eprel",
|
||||||
@@ -1250,7 +1267,7 @@ func (s *Service) ListProcessedProductsDetailed(ctx context.Context, companyID u
|
|||||||
cat.name AS category_name,
|
cat.name AS category_name,
|
||||||
COALESCE(cat.unique_id, NULLIF(BTRIM(p.category), '')) AS category_unique_id,
|
COALESCE(cat.unique_id, NULLIF(BTRIM(p.category), '')) AS category_unique_id,
|
||||||
`+processedFeedCategorySQL+` AS feed_category,
|
`+processedFeedCategorySQL+` AS feed_category,
|
||||||
p.status, p.raw_product_id, p.feed_id, r.gtin,
|
p.status, p.processing_origin, p.raw_product_id, p.feed_id, r.gtin,
|
||||||
`+processedPreferredDescriptionSQL+` AS description,
|
`+processedPreferredDescriptionSQL+` AS description,
|
||||||
`+processedOriginalDescriptionSQL+` AS original_description,
|
`+processedOriginalDescriptionSQL+` AS original_description,
|
||||||
p.processed_name, p.processed_description,
|
p.processed_name, p.processed_description,
|
||||||
@@ -1268,7 +1285,7 @@ func (s *Service) ListProcessedProductsDetailed(ctx context.Context, companyID u
|
|||||||
items, err := scanMaps(rows, []string{
|
items, err := scanMaps(rows, []string{
|
||||||
"id", "product_id", "name", "original_name", "category", "category_name", "category_unique_id",
|
"id", "product_id", "name", "original_name", "category", "category_name", "category_unique_id",
|
||||||
"feed_category",
|
"feed_category",
|
||||||
"status", "raw_product_id", "feed_id", "gtin",
|
"status", "processing_origin", "raw_product_id", "feed_id", "gtin",
|
||||||
"description", "original_description", "processed_name", "processed_description",
|
"description", "original_description", "processed_name", "processed_description",
|
||||||
"meta_title", "meta_description",
|
"meta_title", "meta_description",
|
||||||
"attributes", "processed_attributes", "mapped_data",
|
"attributes", "processed_attributes", "mapped_data",
|
||||||
@@ -1299,7 +1316,8 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
|
|||||||
p.processed_name, p.processed_description,
|
p.processed_name, p.processed_description,
|
||||||
COALESCE(p.meta_title, '') AS meta_title,
|
COALESCE(p.meta_title, '') AS meta_title,
|
||||||
COALESCE(p.meta_description, '') AS meta_description,
|
COALESCE(p.meta_description, '') AS meta_description,
|
||||||
p.status, p.attributes, p.processed_attributes, r.gtin, r.mapped_data,
|
p.status, p.processing_origin, p.attributes, p.processed_attributes, r.gtin, r.mapped_data,
|
||||||
|
r.feed_field_sources,
|
||||||
COALESCE(p.feed_id, r.feed_id) AS feed_id,
|
COALESCE(p.feed_id, r.feed_id) AS feed_id,
|
||||||
f.name AS feed_name,
|
f.name AS feed_name,
|
||||||
f.last_synced_at AS feed_last_synced_at,
|
f.last_synced_at AS feed_last_synced_at,
|
||||||
@@ -1310,6 +1328,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
|
|||||||
`+processedHasProcessedAttributesSQL+` AS has_processed_attributes,
|
`+processedHasProcessedAttributesSQL+` AS has_processed_attributes,
|
||||||
`+processedHasEprelSQL+` AS has_eprel,
|
`+processedHasEprelSQL+` AS has_eprel,
|
||||||
COALESCE(p.localized_content, '{}'::jsonb) AS localized_content,
|
COALESCE(p.localized_content, '{}'::jsonb) AS localized_content,
|
||||||
|
COALESCE(r.source_localizations, '{}'::jsonb) || COALESCE(p.source_localizations, '{}'::jsonb) AS source_localizations,
|
||||||
p.created_at, p.updated_at
|
p.created_at, p.updated_at
|
||||||
FROM processed_products p
|
FROM processed_products p
|
||||||
LEFT JOIN raw_products r ON r.id = p.raw_product_id
|
LEFT JOIN raw_products r ON r.id = p.raw_product_id
|
||||||
@@ -1320,11 +1339,12 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
|
|||||||
"feed_category",
|
"feed_category",
|
||||||
"description", "original_description", "processed_name", "processed_description",
|
"description", "original_description", "processed_name", "processed_description",
|
||||||
"meta_title", "meta_description",
|
"meta_title", "meta_description",
|
||||||
"status", "attributes", "processed_attributes", "gtin", "mapped_data",
|
"status", "processing_origin", "attributes", "processed_attributes", "gtin", "mapped_data",
|
||||||
|
"feed_field_sources",
|
||||||
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
|
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
|
||||||
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
|
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
|
||||||
"has_eprel",
|
"has_eprel",
|
||||||
"localized_content",
|
"localized_content", "source_localizations",
|
||||||
"created_at", "updated_at",
|
"created_at", "updated_at",
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1360,6 +1380,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
|
|||||||
'{}'::jsonb AS processed_attributes,
|
'{}'::jsonb AS processed_attributes,
|
||||||
rp.gtin,
|
rp.gtin,
|
||||||
rp.mapped_data,
|
rp.mapped_data,
|
||||||
|
rp.feed_field_sources,
|
||||||
rp.feed_id,
|
rp.feed_id,
|
||||||
f.name AS feed_name,
|
f.name AS feed_name,
|
||||||
f.last_synced_at AS feed_last_synced_at,
|
f.last_synced_at AS feed_last_synced_at,
|
||||||
@@ -1370,6 +1391,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
|
|||||||
false AS has_processed_attributes,
|
false AS has_processed_attributes,
|
||||||
`+strings.ReplaceAll(processedHasEprelSQL, "r.mapped_data", "rp.mapped_data")+` AS has_eprel,
|
`+strings.ReplaceAll(processedHasEprelSQL, "r.mapped_data", "rp.mapped_data")+` AS has_eprel,
|
||||||
'{}'::jsonb AS localized_content,
|
'{}'::jsonb AS localized_content,
|
||||||
|
COALESCE(rp.source_localizations, '{}'::jsonb) AS source_localizations,
|
||||||
rp.created_at, rp.updated_at,
|
rp.created_at, rp.updated_at,
|
||||||
(COALESCE(NULLIF(trim(rp.mapped_data->>'name'), ''), NULLIF(trim(rp.mapped_data->>'title'), ''), '') <> '') AS has_name,
|
(COALESCE(NULLIF(trim(rp.mapped_data->>'name'), ''), NULLIF(trim(rp.mapped_data->>'title'), ''), '') <> '') AS has_name,
|
||||||
(COALESCE(NULLIF(trim(rp.mapped_data->>'description'), ''), '') <> '') AS has_description,
|
(COALESCE(NULLIF(trim(rp.mapped_data->>'description'), ''), '') <> '') AS has_description,
|
||||||
@@ -1382,10 +1404,11 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
|
|||||||
"id", "product_id", "name", "category", "category_name", "category_unique_id",
|
"id", "product_id", "name", "category", "category_name", "category_unique_id",
|
||||||
"description", "processed_name", "processed_description",
|
"description", "processed_name", "processed_description",
|
||||||
"status", "attributes", "processed_attributes", "gtin", "mapped_data",
|
"status", "attributes", "processed_attributes", "gtin", "mapped_data",
|
||||||
|
"feed_field_sources",
|
||||||
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
|
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
|
||||||
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
|
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
|
||||||
"has_eprel",
|
"has_eprel",
|
||||||
"localized_content",
|
"localized_content", "source_localizations",
|
||||||
"created_at", "updated_at",
|
"created_at", "updated_at",
|
||||||
"has_name", "has_description", "has_category",
|
"has_name", "has_description", "has_category",
|
||||||
"is_processed", "processing_status",
|
"is_processed", "processing_status",
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/csv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestV10JsonProducts(t *testing.T) {
|
||||||
|
r, e := JSONImportAsCSV(strings.NewReader(`{"data":{"products":[{"EAN":"8595025395184","PRODUCT":"Ročna LED svetilka","PRODUCTNO":"1440093109","category":"Svetilke"}]}}`), "products")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
cr := csv.NewReader(r)
|
||||||
|
h, _ := cr.Read()
|
||||||
|
values, e := cr.Read()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
m := map[string]string{}
|
||||||
|
for i, k := range h {
|
||||||
|
m[k] = values[i]
|
||||||
|
}
|
||||||
|
if m["gtin"] != "8595025395184" || m["name"] != "Ročna LED svetilka" || m["product_id"] != "1440093109" {
|
||||||
|
t.Fatalf("wrong fields %v", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestV10JsonCategories(t *testing.T) {
|
||||||
|
r, e := JSONImportAsCSV(strings.NewReader(`{"categories":[{"name":"Svetilke","id":50}]}`), "categories")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
cr := csv.NewReader(r)
|
||||||
|
h, _ := cr.Read()
|
||||||
|
v, _ := cr.Read()
|
||||||
|
m := map[string]string{}
|
||||||
|
for i, k := range h {
|
||||||
|
m[k] = v[i]
|
||||||
|
}
|
||||||
|
if m["unique_id"] != "50" {
|
||||||
|
t.Fatalf("unique_id: %v", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,8 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -157,6 +159,13 @@ func LoadWPCategoryPromptOverlaysFromBytes(raw []byte) (byNorm map[string]string
|
|||||||
}
|
}
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
p := strings.TrimSpace(e.Prompt)
|
p := strings.TrimSpace(e.Prompt)
|
||||||
|
p, _ = aiprompts.NormalizeA1RepeatedBenefits(p)
|
||||||
|
if aiprompts.IsLegacyCombinedEnhancePrompt(p) {
|
||||||
|
p = aiprompts.SplitLegacyCombinedEnhancePrompt(p)
|
||||||
|
}
|
||||||
|
if canonical, updated := aiprompts.NormalizeA1MetaRole(p, "sl"); updated {
|
||||||
|
p = canonical
|
||||||
|
}
|
||||||
if p == "" {
|
if p == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -98,12 +98,11 @@ func TestParseWPProductCategoriesSQL_RealSeedFile(t *testing.T) {
|
|||||||
if !ok {
|
if !ok {
|
||||||
t.Fatalf("Slušalke missing from %s (keys=%d)", path, len(byNorm))
|
t.Fatalf("Slušalke missing from %s (keys=%d)", path, len(byNorm))
|
||||||
}
|
}
|
||||||
split := aiprompts.SplitLegacyCombinedEnhancePrompt(raw)
|
if aiprompts.CategoryEnhancePromptNeedsRepair(raw) {
|
||||||
if aiprompts.CategoryEnhancePromptNeedsRepair(split) {
|
t.Fatal("normalized WP category prompt should not need repair")
|
||||||
t.Fatal("split of real dump Slušalke should not need repair")
|
|
||||||
}
|
}
|
||||||
if !strings.Contains(split, "tip izdelka lowercase") && !strings.Contains(split, "znamka") {
|
if !strings.Contains(raw, "tip izdelka lowercase") && !strings.Contains(raw, "znamka") {
|
||||||
t.Fatalf("unexpected Title rules in split: %s", split[:min(400, len(split))])
|
t.Fatalf("unexpected title rules in normalized prompt: %s", raw[:min(400, len(raw))])
|
||||||
}
|
}
|
||||||
if !strings.Contains(filepath.ToSlash(path), "scripts/seed/wp_product_categories.sql") &&
|
if !strings.Contains(filepath.ToSlash(path), "scripts/seed/wp_product_categories.sql") &&
|
||||||
filepath.Base(path) != "wp_product_categories.sql" {
|
filepath.Base(path) != "wp_product_categories.sql" {
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Requires the normal migrated test PostgreSQL schema (DATABASE_URL).
|
||||||
|
func TestDeleteFeedRemovesOnlyOwnedUnprocessedProducts(t *testing.T) {
|
||||||
|
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("DATABASE_URL is not configured")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
pg, err := pgxpool.New(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer pg.Close()
|
||||||
|
|
||||||
|
cid, otherCID := uuid.New(), uuid.New()
|
||||||
|
for _, id := range []uuid.UUID{cid, otherCID} {
|
||||||
|
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, id, "delete-cleanup-"+id.String()[:8]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
defer pg.Exec(context.Background(), `DELETE FROM companies WHERE id = ANY($1::uuid[])`, []uuid.UUID{cid, otherCID})
|
||||||
|
|
||||||
|
newFeed := func(c uuid.UUID) uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
var id uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `INSERT INTO input_feeds (company_id, name) VALUES ($1, 'test-feed') RETURNING id`, c).Scan(&id); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
feed := newFeed(cid)
|
||||||
|
survivor := newFeed(cid)
|
||||||
|
otherFeed := newFeed(otherCID)
|
||||||
|
|
||||||
|
newRaw := func(c uuid.UUID, name string, fid uuid.UUID, processed bool, status string, ids any) uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
var id uuid.UUID
|
||||||
|
err := pg.QueryRow(ctx, `
|
||||||
|
INSERT INTO raw_products (company_id, gtin, feed_id, feed_ids, is_processed, processing_status)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`, c, name, fid, ids, processed, status).Scan(&id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
unprocessed := newRaw(cid, "delete-new", feed, false, "unprocessed", nil)
|
||||||
|
failed := newRaw(cid, "delete-failed", feed, false, "failed", nil)
|
||||||
|
processed := newRaw(cid, "keep-processed", feed, true, "processed", nil)
|
||||||
|
processing := newRaw(cid, "keep-running", feed, false, "processing", nil)
|
||||||
|
shared := newRaw(cid, "keep-shared", feed, false, "unprocessed", []string{feed.String(), survivor.String()})
|
||||||
|
secondary := newRaw(cid, "keep-secondary", survivor, false, "unprocessed", []string{feed.String(), survivor.String()})
|
||||||
|
untouchedOther := newRaw(otherCID, "keep-other-company", otherFeed, false, "unprocessed", nil)
|
||||||
|
|
||||||
|
// A processed result linked to an unprocessed raw row survives with its FK cleared.
|
||||||
|
var resultID uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `
|
||||||
|
INSERT INTO processed_products (company_id, raw_product_id, feed_id, name)
|
||||||
|
VALUES ($1, $2, $3, 'retained') RETURNING id`, cid, unprocessed, feed).Scan(&resultID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := &Service{Pool: pg}
|
||||||
|
if _, err := svc.DeleteWithCleanup(ctx, otherCID, feed); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatalf("cross-tenant deletion must return not found, got %v", err)
|
||||||
|
}
|
||||||
|
count, err := svc.DeleteWithCleanup(ctx, cid, feed)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if count != 2 {
|
||||||
|
t.Fatalf("deleted raw count = %d, want 2", count)
|
||||||
|
}
|
||||||
|
|
||||||
|
var n int
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = ANY($1::uuid[])`, []uuid.UUID{unprocessed, failed}).Scan(&n); err != nil || n != 0 {
|
||||||
|
t.Fatalf("unprocessed rows still exist: count=%d err=%v", n, err)
|
||||||
|
}
|
||||||
|
for _, kept := range []uuid.UUID{processed, processing, shared, secondary, untouchedOther} {
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = $1`, kept).Scan(&n); err != nil || n != 1 {
|
||||||
|
t.Fatalf("preserved row %s count=%d err=%v", kept, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var newOwner uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT feed_id FROM raw_products WHERE id = $1`, shared).Scan(&newOwner); err != nil || newOwner != survivor {
|
||||||
|
t.Fatalf("shared row owner=%v err=%v", newOwner, err)
|
||||||
|
}
|
||||||
|
for _, kept := range []uuid.UUID{shared, secondary} {
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = $1 AND feed_ids @> jsonb_build_array($2::text)`, kept, feed).Scan(&n); err != nil || n != 0 {
|
||||||
|
t.Fatalf("stale secondary feed id in row %s: %d, %v", kept, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var rawLink *uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT raw_product_id FROM processed_products WHERE id = $1`, resultID).Scan(&rawLink); err != nil || rawLink != nil {
|
||||||
|
t.Fatalf("processed result must survive, detached from deleted raw: %v %v", rawLink, err)
|
||||||
|
}
|
||||||
|
if _, err := svc.DeleteWithCleanup(ctx, cid, feed); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatalf("second delete must be not found, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -172,6 +172,13 @@ func ValidateFeedURL(ctx context.Context, rawURL string) error {
|
|||||||
// downloadFeed streams an http(s) feed to a temp file with SSRF controls and a hard size cap.
|
// downloadFeed streams an http(s) feed to a temp file with SSRF controls and a hard size cap.
|
||||||
// Callers must Close the returned blob to remove the temp file.
|
// Callers must Close the returned blob to remove the temp file.
|
||||||
func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
|
func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
|
||||||
|
return downloadFeedWithHeaders(ctx, rawURL, nil)
|
||||||
|
}
|
||||||
|
func downloadFeedWithHeaders(ctx context.Context, rawURL string, extra map[string]string) (*feedBlob, error) {
|
||||||
|
extra, err := validatedFeedHeaders(extra)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
ensureAllowlist()
|
ensureAllowlist()
|
||||||
rawURL = strings.TrimSpace(rawURL)
|
rawURL = strings.TrimSpace(rawURL)
|
||||||
if rawURL == "" {
|
if rawURL == "" {
|
||||||
@@ -203,7 +210,15 @@ func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
|
|||||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||||
return errURLScheme
|
return errURLScheme
|
||||||
}
|
}
|
||||||
return assertPublicHost(req.Context(), req.URL.Hostname())
|
if err := assertPublicHost(req.Context(), req.URL.Hostname()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(via) > 0 && !strings.EqualFold(req.URL.Hostname(), via[0].URL.Hostname()) {
|
||||||
|
for name := range extra {
|
||||||
|
req.Header.Del(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,7 +227,10 @@ func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req.Header.Set("User-Agent", defaultUserAgent)
|
req.Header.Set("User-Agent", defaultUserAgent)
|
||||||
req.Header.Set("Accept", "text/csv,application/csv,application/xml,text/xml,application/atom+xml,*/*")
|
req.Header.Set("Accept", "application/json,text/csv,application/csv,application/xml,text/xml,application/atom+xml,*/*")
|
||||||
|
for name, value := range extra {
|
||||||
|
req.Header.Set(name, value)
|
||||||
|
}
|
||||||
|
|
||||||
res, err := client.Do(req)
|
res, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -402,3 +420,33 @@ func isBlockedIP(ip net.IP) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DownloadImportSource safely fetches a one-time catalog import URL with optional headers.
|
||||||
|
// The caller must close the returned reader, which removes the temporary file.
|
||||||
|
func DownloadImportSource(ctx context.Context, rawURL string, headers map[string]string, maxSize int64) (io.ReadCloser, error) {
|
||||||
|
b, err := downloadFeedWithHeaders(ctx, rawURL, headers)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if b.size > maxSize {
|
||||||
|
b.Close()
|
||||||
|
return nil, ClientMsg("catalog import exceeds size limit")
|
||||||
|
}
|
||||||
|
f, err := b.Open()
|
||||||
|
if err != nil {
|
||||||
|
b.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &cleanupImportReader{ReadCloser: f, blob: b}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type cleanupImportReader struct {
|
||||||
|
io.ReadCloser
|
||||||
|
blob *feedBlob
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *cleanupImportReader) Close() error {
|
||||||
|
err := r.ReadCloser.Close()
|
||||||
|
_ = r.blob.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,756 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
|
"encoding/csv"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"github.com/pbnjay/grate"
|
||||||
|
"github.com/pbnjay/grate/commonxl"
|
||||||
|
"github.com/pbnjay/grate/xls"
|
||||||
|
"github.com/xuri/excelize/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxExcelBytes bounds spreadsheet sources. Workbooks are decoded in memory (BIFF
|
||||||
|
// fully, OOXML shared strings), so the cap is far below maxDownloadBytes. It also
|
||||||
|
// bounds each workbook inside a zip archive.
|
||||||
|
const maxExcelBytes int64 = 64 << 20
|
||||||
|
|
||||||
|
const (
|
||||||
|
// excelHeaderScanRows is how many leading non-empty rows are buffered to find the
|
||||||
|
// header row (supplier exports often start with a title/date block).
|
||||||
|
excelHeaderScanRows = 20
|
||||||
|
// excelRecordScanRows bounds the per-sheet scan for a record-layout EAN row.
|
||||||
|
excelRecordScanRows = 600
|
||||||
|
// maxExcelArchiveEntries / maxExcelArchiveBytes bound zip uploads of workbooks.
|
||||||
|
maxExcelArchiveEntries = 2000
|
||||||
|
maxExcelArchiveBytes int64 = 512 << 20
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
oleMagic = []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}
|
||||||
|
zipMagic = []byte{'P', 'K', 0x03, 0x04}
|
||||||
|
|
||||||
|
errExcelStop = errors.New("excel: stop")
|
||||||
|
|
||||||
|
// excelBarcodeLabel matches the label cell of a record-layout barcode row.
|
||||||
|
excelBarcodeLabel = regexp.MustCompile(`(?i)^(ean|gtin|barcode|bar code|ean code|ean-code|ean koda|črtna koda)\b`)
|
||||||
|
excelBarcodeValue = regexp.MustCompile(`^[0-9]{8,14}$`)
|
||||||
|
excelGUID = regexp.MustCompile(`^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f-]{12,17}$`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// isExcelSample reports whether sample starts like a legacy .xls (OLE2) or a zip:
|
||||||
|
// an OOXML workbook or an archive of workbooks. Feeds are otherwise text.
|
||||||
|
func isExcelSample(sample []byte) bool {
|
||||||
|
return bytes.HasPrefix(sample, oleMagic) || bytes.HasPrefix(sample, zipMagic)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExcelName(name string) bool {
|
||||||
|
n := strings.ToLower(strings.TrimSpace(name))
|
||||||
|
if i := strings.IndexAny(n, "?#"); i >= 0 {
|
||||||
|
n = n[:i]
|
||||||
|
}
|
||||||
|
return isWorkbookName(n) || strings.HasSuffix(n, ".zip")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isWorkbookName(name string) bool {
|
||||||
|
n := strings.ToLower(name)
|
||||||
|
return strings.HasSuffix(n, ".xls") || strings.HasSuffix(n, ".xlsx") || strings.HasSuffix(n, ".xlsm")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExcelContentType(ct string) bool {
|
||||||
|
ct = strings.ToLower(ct)
|
||||||
|
return strings.Contains(ct, "spreadsheetml") || strings.Contains(ct, "ms-excel")
|
||||||
|
}
|
||||||
|
|
||||||
|
// excelSheetOption returns options.sheet; empty picks the visible sheet with the most rows.
|
||||||
|
func excelSheetOption(feed map[string]any) string {
|
||||||
|
if opts, ok := feed["options"].(map[string]any); ok {
|
||||||
|
if v, ok := opts["sheet"].(string); ok {
|
||||||
|
return strings.TrimSpace(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseExcel streams the products of a workbook (or zip of workbooks) as
|
||||||
|
// column-keyed feedRows, like parseCSV.
|
||||||
|
func parseExcel(path, sheet string, onRow func(feedRow) error) (int, error) {
|
||||||
|
count := 0
|
||||||
|
err := readExcelSource(path, sheet, func(cols, rec []string) error {
|
||||||
|
count++
|
||||||
|
if count > maxParseRows {
|
||||||
|
return parseTooManyRows()
|
||||||
|
}
|
||||||
|
row := make(feedRow, len(cols))
|
||||||
|
for i, col := range cols {
|
||||||
|
if col == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if i < len(rec) {
|
||||||
|
row[col] = rec[i]
|
||||||
|
} else {
|
||||||
|
row[col] = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expandSpecificationFields(row)
|
||||||
|
return onRow(row)
|
||||||
|
})
|
||||||
|
return count, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// excelSchemaCSV renders the first maxRows products as CSV (header = union of
|
||||||
|
// their columns, first-seen order) so the schema preview can reuse extractCSVSchema.
|
||||||
|
func excelSchemaCSV(path, sheet string, maxRows int) ([]byte, error) {
|
||||||
|
var (
|
||||||
|
header []string
|
||||||
|
index = map[string]int{}
|
||||||
|
rows []map[string]string
|
||||||
|
)
|
||||||
|
err := readExcelSource(path, sheet, func(cols, rec []string) error {
|
||||||
|
if len(rows) >= maxRows {
|
||||||
|
return errExcelStop
|
||||||
|
}
|
||||||
|
row := make(map[string]string, len(cols))
|
||||||
|
for i, col := range cols {
|
||||||
|
if col == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := index[col]; !ok {
|
||||||
|
index[col] = len(header)
|
||||||
|
header = append(header, col)
|
||||||
|
}
|
||||||
|
if i < len(rec) {
|
||||||
|
row[col] = rec[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil && !errors.Is(err, errExcelStop) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
w := csv.NewWriter(&buf)
|
||||||
|
if err := w.Write(header); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, row := range rows {
|
||||||
|
rec := make([]string, len(header))
|
||||||
|
for i, col := range header {
|
||||||
|
rec[i] = row[col]
|
||||||
|
}
|
||||||
|
if err := w.Write(rec); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.Flush()
|
||||||
|
return buf.Bytes(), w.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
// readExcelSource calls onData once per product with its column names and values.
|
||||||
|
// path is a workbook or a zip archive of workbooks (e.g. one file per product).
|
||||||
|
func readExcelSource(path, sheet string, onData func(cols, rec []string) error) error {
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sample, err := (&feedBlob{path: path}).Sniff(len(oleMagic))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if bytes.HasPrefix(sample, zipMagic) {
|
||||||
|
zr, err := zip.OpenReader(path)
|
||||||
|
if err != nil {
|
||||||
|
return ClientMsg(fmt.Sprintf("could not read Excel file: %v", err))
|
||||||
|
}
|
||||||
|
defer zr.Close()
|
||||||
|
if !isOOXMLPackage(&zr.Reader) {
|
||||||
|
return readExcelArchive(&zr.Reader, sheet, onData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if info.Size() > maxExcelBytes {
|
||||||
|
return ClientMsg(fmt.Sprintf("Excel file exceeds %d MiB; export the product sheet as CSV instead", maxExcelBytes>>20))
|
||||||
|
}
|
||||||
|
return readExcelWorkbook(path, sheet, onData)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isOOXMLPackage(zr *zip.Reader) bool {
|
||||||
|
for _, f := range zr.File {
|
||||||
|
if f.Name == "[Content_Types].xml" || strings.HasPrefix(f.Name, "xl/") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// readExcelArchive reads every workbook in a zip, in name order, as one feed.
|
||||||
|
func readExcelArchive(zr *zip.Reader, sheet string, onData func(cols, rec []string) error) error {
|
||||||
|
files := make([]*zip.File, 0, len(zr.File))
|
||||||
|
for _, f := range zr.File {
|
||||||
|
base := path.Base(f.Name)
|
||||||
|
if f.FileInfo().IsDir() || strings.HasPrefix(f.Name, "__MACOSX/") || strings.HasPrefix(base, ".") || strings.HasPrefix(base, "~$") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if isWorkbookName(base) {
|
||||||
|
files = append(files, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(files) == 0 {
|
||||||
|
return ClientMsg("zip contains no Excel files (.xls, .xlsx, .xlsm)")
|
||||||
|
}
|
||||||
|
if len(files) > maxExcelArchiveEntries {
|
||||||
|
return ClientMsg(fmt.Sprintf("zip contains more than %d Excel files", maxExcelArchiveEntries))
|
||||||
|
}
|
||||||
|
sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name })
|
||||||
|
var total int64
|
||||||
|
for _, f := range files {
|
||||||
|
tmp, n, err := extractZipEntry(f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
total += n
|
||||||
|
if total > maxExcelArchiveBytes {
|
||||||
|
_ = os.Remove(tmp)
|
||||||
|
return ClientMsg(fmt.Sprintf("zip content exceeds %d MiB", maxExcelArchiveBytes>>20))
|
||||||
|
}
|
||||||
|
err = readExcelWorkbook(tmp, sheet, onData)
|
||||||
|
_ = os.Remove(tmp)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, errExcelStop) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%s: %w", path.Base(f.Name), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractZipEntry(f *zip.File) (string, int64, error) {
|
||||||
|
rc, err := f.Open()
|
||||||
|
if err != nil {
|
||||||
|
return "", 0, ClientMsg(fmt.Sprintf("could not read %s from zip: %v", path.Base(f.Name), err))
|
||||||
|
}
|
||||||
|
defer rc.Close()
|
||||||
|
out, err := os.CreateTemp("", "descrybe-xl-*"+path.Ext(f.Name))
|
||||||
|
if err != nil {
|
||||||
|
return "", 0, err
|
||||||
|
}
|
||||||
|
n, err := io.Copy(out, io.LimitReader(rc, maxExcelBytes+1))
|
||||||
|
if cerr := out.Close(); err == nil {
|
||||||
|
err = cerr
|
||||||
|
}
|
||||||
|
if err == nil && n > maxExcelBytes {
|
||||||
|
err = ClientMsg(fmt.Sprintf("%s exceeds %d MiB", path.Base(f.Name), maxExcelBytes>>20))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
_ = os.Remove(out.Name())
|
||||||
|
return "", 0, err
|
||||||
|
}
|
||||||
|
return out.Name(), n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// readExcelWorkbook emits one product for record-layout workbooks (a product sheet
|
||||||
|
// of label | value rows, e.g. GroupeSeb), else one per data row of the chosen sheet.
|
||||||
|
func readExcelWorkbook(path, sheet string, onData func(cols, rec []string) error) error {
|
||||||
|
wb, err := openWorkbook(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer wb.Close()
|
||||||
|
names := wb.Sheets()
|
||||||
|
if len(names) == 0 {
|
||||||
|
return ClientMsg("Excel workbook has no visible sheets")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(sheet) == "" {
|
||||||
|
record, err := isRecordWorkbook(wb, names)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if record {
|
||||||
|
return readExcelRecord(wb, names, onData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name, err := pickSheet(wb, names, sheet)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return readExcelTable(wb, name, onData)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isRecordWorkbook looks for a two-cell "EAN Code | 3168430313385" row: a barcode
|
||||||
|
// labelled in one column with its value beside it, instead of a header row.
|
||||||
|
func isRecordWorkbook(wb workbook, names []string) (bool, error) {
|
||||||
|
found := false
|
||||||
|
for _, name := range names {
|
||||||
|
n := 0
|
||||||
|
err := wb.Rows(name, func(rec []string) error {
|
||||||
|
if n++; n > excelRecordScanRows {
|
||||||
|
return errExcelStop
|
||||||
|
}
|
||||||
|
cells := excelFilledCells(rec)
|
||||||
|
if len(cells) == 2 && excelBarcodeLabel.MatchString(cells[0]) && excelBarcodeValue.MatchString(cells[1]) {
|
||||||
|
found = true
|
||||||
|
return errExcelStop
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil && !errors.Is(err, errExcelStop) {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if found {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// readExcelRecord turns every sheet into label → value pairs. The sheet's value
|
||||||
|
// column is its rightmost used column; cells left of it form the label ("Product
|
||||||
|
// packshot - H1 Image Url"), and rows with no value there are skipped (MEDIA rows
|
||||||
|
// list "Media Id / Image Url / Picture …" slots, most of them empty). An all-caps
|
||||||
|
// title alone in the first column starts a section that prefixes the labels below
|
||||||
|
// it ("TECHNICAL CHARACTERISTICS/Dimenzija"), so a block maps as one source.
|
||||||
|
// GUID-only values (internal media ids) are dropped. Repeated labels collect their
|
||||||
|
// distinct values comma-separated.
|
||||||
|
func readExcelRecord(wb workbook, names []string, onData func(cols, rec []string) error) error {
|
||||||
|
var cols, vals []string
|
||||||
|
index := map[string]int{}
|
||||||
|
for _, name := range names {
|
||||||
|
valueCol := -1
|
||||||
|
if err := wb.Rows(name, func(rec []string) error {
|
||||||
|
if last := excelLastFilled(rec); last > valueCol && excelFilledCount(rec) >= 2 {
|
||||||
|
valueCol = last
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
section := ""
|
||||||
|
err := wb.Rows(name, func(rec []string) error {
|
||||||
|
cells := excelFilledCells(rec)
|
||||||
|
if len(cells) == 1 && excelFirstFilled(rec) == 0 && isExcelSectionTitle(cells[0]) {
|
||||||
|
section = strings.ReplaceAll(cells[0], "/", "-")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(cells) < 2 || excelLastFilled(rec) != valueCol || isGUIDList(cells[len(cells)-1]) {
|
||||||
|
return nil // sub-heading, label without a value, or media id
|
||||||
|
}
|
||||||
|
label := strings.Join(cells[:len(cells)-1], " ")
|
||||||
|
if section != "" {
|
||||||
|
label = section + "/" + strings.ReplaceAll(label, "/", "-")
|
||||||
|
}
|
||||||
|
value := cells[len(cells)-1]
|
||||||
|
i, ok := index[label]
|
||||||
|
if !ok {
|
||||||
|
index[label] = len(cols)
|
||||||
|
cols = append(cols, label)
|
||||||
|
vals = append(vals, value)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, prev := range strings.Split(vals[i], ",") {
|
||||||
|
if prev == value {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vals[i] += "," + value
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(cols) == 0 {
|
||||||
|
return ClientMsg("Excel sheet contains no rows")
|
||||||
|
}
|
||||||
|
return onData(cols, vals)
|
||||||
|
}
|
||||||
|
|
||||||
|
func excelFirstFilled(rec []string) int {
|
||||||
|
for i, v := range rec {
|
||||||
|
if strings.TrimSpace(v) != "" {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
func excelLastFilled(rec []string) int {
|
||||||
|
for i := len(rec) - 1; i >= 0; i-- {
|
||||||
|
if strings.TrimSpace(rec[i]) != "" {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
// isGUIDList matches "00C4DE5B-EB9B-4B3C-96E4931062A667CD" and ;/, lists of them.
|
||||||
|
func isGUIDList(v string) bool {
|
||||||
|
parts := strings.FieldsFunc(v, func(r rune) bool { return r == ';' || r == ',' || unicode.IsSpace(r) })
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, p := range parts {
|
||||||
|
if !excelGUID.MatchString(p) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// isExcelSectionTitle matches headings like "TECHNICAL CHARACTERISTICS" or "FAQ".
|
||||||
|
func isExcelSectionTitle(s string) bool {
|
||||||
|
hasLetter := false
|
||||||
|
for _, r := range s {
|
||||||
|
if unicode.IsLetter(r) {
|
||||||
|
hasLetter = true
|
||||||
|
if unicode.IsLower(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hasLetter
|
||||||
|
}
|
||||||
|
|
||||||
|
// excelFilledCells returns the trimmed non-empty cells with inner whitespace collapsed.
|
||||||
|
func excelFilledCells(rec []string) []string {
|
||||||
|
out := make([]string, 0, 4)
|
||||||
|
for _, v := range rec {
|
||||||
|
if v = strings.Join(strings.Fields(v), " "); v != "" {
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// readExcelTable finds the header row of the sheet and calls onData with the header
|
||||||
|
// columns and each following non-empty row.
|
||||||
|
func readExcelTable(wb workbook, sheet string, onData func(cols, rec []string) error) error {
|
||||||
|
var (
|
||||||
|
cols []string
|
||||||
|
pending [][]string
|
||||||
|
)
|
||||||
|
flushPending := func() error {
|
||||||
|
cols = excelHeaderColumns(pending)
|
||||||
|
for _, rec := range pending[excelHeaderIndex(pending)+1:] {
|
||||||
|
if err := onData(cols, rec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pending = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
err := wb.Rows(sheet, func(rec []string) error {
|
||||||
|
if excelRowEmpty(rec) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if cols != nil {
|
||||||
|
return onData(cols, rec)
|
||||||
|
}
|
||||||
|
pending = append(pending, append([]string(nil), rec...))
|
||||||
|
if len(pending) < excelHeaderScanRows {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return flushPending()
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if cols == nil {
|
||||||
|
if len(pending) == 0 {
|
||||||
|
return ClientMsg("Excel sheet contains no rows")
|
||||||
|
}
|
||||||
|
return flushPending()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// excelHeaderIndex picks the first row filled at least half as wide as the widest
|
||||||
|
// buffered row (and with 2+ cells when possible), skipping title/date lines above
|
||||||
|
// the real header.
|
||||||
|
func excelHeaderIndex(rows [][]string) int {
|
||||||
|
widest := 0
|
||||||
|
for _, r := range rows {
|
||||||
|
widest = max(widest, excelFilledCount(r))
|
||||||
|
}
|
||||||
|
need := max(min(widest, 2), (widest+1)/2)
|
||||||
|
for i, r := range rows {
|
||||||
|
if excelFilledCount(r) >= need {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// excelHeaderColumns trims header names and makes duplicates unique ("Opis", "Opis (2)").
|
||||||
|
func excelHeaderColumns(rows [][]string) []string {
|
||||||
|
header := rows[excelHeaderIndex(rows)]
|
||||||
|
cols := make([]string, len(header))
|
||||||
|
seen := make(map[string]int, len(header))
|
||||||
|
for i, h := range header {
|
||||||
|
name := strings.Join(strings.Fields(strings.TrimPrefix(h, string(rune(0xFEFF)))), " ")
|
||||||
|
if name == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[strings.ToLower(name)]++
|
||||||
|
if n := seen[strings.ToLower(name)]; n > 1 {
|
||||||
|
name = fmt.Sprintf("%s (%d)", name, n)
|
||||||
|
}
|
||||||
|
cols[i] = name
|
||||||
|
}
|
||||||
|
return cols
|
||||||
|
}
|
||||||
|
|
||||||
|
func excelFilledCount(rec []string) int {
|
||||||
|
n := 0
|
||||||
|
for _, v := range rec {
|
||||||
|
if strings.TrimSpace(v) != "" {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func excelRowEmpty(rec []string) bool { return excelFilledCount(rec) == 0 }
|
||||||
|
|
||||||
|
// pickSheet returns the requested sheet, else the visible sheet with the most rows.
|
||||||
|
func pickSheet(wb workbook, names []string, sheet string) (string, error) {
|
||||||
|
if sheet = strings.TrimSpace(sheet); sheet != "" {
|
||||||
|
for _, name := range names {
|
||||||
|
if strings.EqualFold(name, sheet) {
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", ClientMsg(fmt.Sprintf("Excel sheet %q not found", sheet))
|
||||||
|
}
|
||||||
|
best, bestRows := names[0], -1
|
||||||
|
for _, name := range names {
|
||||||
|
n, err := wb.RowCount(name)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if n > bestRows {
|
||||||
|
best, bestRows = name, n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// workbook is the read surface shared by OOXML (.xlsx/.xlsm) and BIFF (.xls).
|
||||||
|
type workbook interface {
|
||||||
|
// Sheets lists visible sheets in workbook order.
|
||||||
|
Sheets() []string
|
||||||
|
// Rows streams the cell strings of every row; returning an error stops early.
|
||||||
|
Rows(sheet string, onRow func([]string) error) error
|
||||||
|
RowCount(sheet string) (int, error)
|
||||||
|
Close() error
|
||||||
|
}
|
||||||
|
|
||||||
|
func openWorkbook(path string) (workbook, error) {
|
||||||
|
sample, err := (&feedBlob{path: path}).Sniff(len(oleMagic))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if bytes.HasPrefix(sample, oleMagic) {
|
||||||
|
wb, err := xls.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, ClientMsg(fmt.Sprintf("could not read Excel workbook: %v", err))
|
||||||
|
}
|
||||||
|
return &xlsWorkbook{src: wb}, nil
|
||||||
|
}
|
||||||
|
f, err := excelize.OpenFile(path, excelize.Options{
|
||||||
|
UnzipSizeLimit: 4 * maxExcelBytes,
|
||||||
|
UnzipXMLSizeLimit: 2 * maxExcelBytes,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, ClientMsg(fmt.Sprintf("could not read Excel workbook: %v", err))
|
||||||
|
}
|
||||||
|
return &xlsxWorkbook{f: f}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type xlsxWorkbook struct{ f *excelize.File }
|
||||||
|
|
||||||
|
func (w *xlsxWorkbook) Close() error { return w.f.Close() }
|
||||||
|
|
||||||
|
func (w *xlsxWorkbook) Sheets() []string {
|
||||||
|
var out []string
|
||||||
|
for _, name := range w.f.GetSheetList() {
|
||||||
|
if visible, err := w.f.GetSheetVisible(name); err == nil && !visible {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, name)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *xlsxWorkbook) RowCount(sheet string) (int, error) {
|
||||||
|
rows, err := w.f.Rows(sheet)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
n := 0
|
||||||
|
for rows.Next() {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
return n, rows.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rows runs two iterators in lockstep: formatted values are preferred (dates,
|
||||||
|
// percentages), raw values rescue long numeric codes shown as 3.83002E+12.
|
||||||
|
func (w *xlsxWorkbook) Rows(sheet string, onRow func([]string) error) error {
|
||||||
|
shown, err := w.f.Rows(sheet)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer shown.Close()
|
||||||
|
raw, err := w.f.Rows(sheet)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer raw.Close()
|
||||||
|
for shown.Next() && raw.Next() {
|
||||||
|
vals, err := shown.Columns()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
raws, err := raw.Columns(excelize.Options{RawCellValue: true})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i := range vals {
|
||||||
|
if i < len(raws) && preferRawExcelValue(vals[i], raws[i]) {
|
||||||
|
vals[i] = raws[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := onRow(vals); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return shown.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
// preferRawExcelValue keeps barcodes/SKUs intact when the display format rounds them.
|
||||||
|
func preferRawExcelValue(shown, raw string) bool {
|
||||||
|
if shown == raw || raw == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
digits := strings.TrimSuffix(raw, ".0")
|
||||||
|
if len(digits) < 8 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range digits {
|
||||||
|
if r < '0' || r > '9' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// xlsWorkbook reads legacy BIFF .xls via the vendored, patched grate
|
||||||
|
// (third_party/grate). Cells are formatted here instead of via grate's Strings()
|
||||||
|
// so integers stay plain digits (barcodes) and dates use ISO format.
|
||||||
|
type xlsWorkbook struct {
|
||||||
|
src grate.Source
|
||||||
|
sheets map[string]*commonxl.Sheet
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *xlsWorkbook) Close() error { return w.src.Close() }
|
||||||
|
|
||||||
|
func (w *xlsWorkbook) Sheets() []string {
|
||||||
|
names, err := w.src.List()
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *xlsWorkbook) sheet(name string) (*commonxl.Sheet, error) {
|
||||||
|
if s, ok := w.sheets[name]; ok {
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
c, err := w.src.Get(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
s, ok := c.(*commonxl.Sheet)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("excel: unexpected sheet type %T", c)
|
||||||
|
}
|
||||||
|
if w.sheets == nil {
|
||||||
|
w.sheets = map[string]*commonxl.Sheet{}
|
||||||
|
}
|
||||||
|
w.sheets[name] = s
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *xlsWorkbook) RowCount(sheet string) (int, error) {
|
||||||
|
s, err := w.sheet(sheet)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return s.NumRows, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *xlsWorkbook) Rows(sheet string, onRow func([]string) error) error {
|
||||||
|
s, err := w.sheet(sheet)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// Rewind: a sheet is cached and may be read twice (record scan, then table).
|
||||||
|
s.CurRow = 0
|
||||||
|
for s.Next() {
|
||||||
|
cells := s.Raw()
|
||||||
|
rec := make([]string, len(cells))
|
||||||
|
for i, c := range cells {
|
||||||
|
rec[i] = xlsCellString(s.Formatter, c)
|
||||||
|
}
|
||||||
|
if err := onRow(rec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func xlsCellString(f *commonxl.Formatter, c commonxl.Cell) string {
|
||||||
|
if c.Type() == commonxl.StaticCell {
|
||||||
|
return "" // merged-cell placeholder
|
||||||
|
}
|
||||||
|
switch v := c.Value().(type) {
|
||||||
|
case nil:
|
||||||
|
return ""
|
||||||
|
case string:
|
||||||
|
return strings.TrimSpace(v)
|
||||||
|
case bool:
|
||||||
|
if v {
|
||||||
|
return "TRUE"
|
||||||
|
}
|
||||||
|
return "FALSE"
|
||||||
|
case int64:
|
||||||
|
return strconv.FormatInt(v, 10)
|
||||||
|
case float64:
|
||||||
|
if c.Type() == commonxl.DateCell && f != nil {
|
||||||
|
return f.ConvertToDate(v).Format(time.DateOnly)
|
||||||
|
}
|
||||||
|
if v == math.Trunc(v) && math.Abs(v) < 1e15 {
|
||||||
|
return strconv.FormatInt(int64(v), 10)
|
||||||
|
}
|
||||||
|
return strconv.FormatFloat(v, 'f', -1, 64)
|
||||||
|
case time.Time:
|
||||||
|
return v.Format(time.DateOnly)
|
||||||
|
default:
|
||||||
|
return strings.TrimSpace(fmt.Sprint(v))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xuri/excelize/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
func writeTestXLSX(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
f := excelize.NewFile()
|
||||||
|
defer f.Close()
|
||||||
|
// A hidden helper sheet with more rows must not win the sheet pick.
|
||||||
|
if _, err := f.NewSheet("Lookup"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for i := 1; i <= 40; i++ {
|
||||||
|
_ = f.SetCellValue("Lookup", "A"+strconv.Itoa(i), "x")
|
||||||
|
}
|
||||||
|
if err := f.SetSheetVisible("Lookup", false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rows := [][]any{
|
||||||
|
{"Cenik dobavitelja 2026"},
|
||||||
|
{},
|
||||||
|
{"EAN", "Artikel", "Opis", "Opis", "Cena"},
|
||||||
|
{int64(3830023210103), "UMETNA ČREVA KAL.55", "Kolagena", "", 12.5},
|
||||||
|
{},
|
||||||
|
{int64(8595025338228), "VODNIK KOAKSIALNI", "", "75 OHM", 3},
|
||||||
|
}
|
||||||
|
for r, row := range rows {
|
||||||
|
for c, v := range row {
|
||||||
|
cell, _ := excelize.CoordinatesToCellName(c+1, r+1)
|
||||||
|
if err := f.SetCellValue("Sheet1", cell, v); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Scientific display format must not leak into barcodes.
|
||||||
|
style, err := f.NewStyle(&excelize.Style{NumFmt: 11})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := f.SetCellStyle("Sheet1", "A4", "A6", style); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
path := filepath.Join(t.TempDir(), "feed.xlsx")
|
||||||
|
if err := f.SaveAs(path); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseExcelXLSXFindsHeaderAndKeepsBarcodes(t *testing.T) {
|
||||||
|
path := writeTestXLSX(t)
|
||||||
|
mappings := []FieldMapping{{Source: "EAN", Target: "gtin"}, {Source: "Artikel", Target: "title"}}
|
||||||
|
var got []feedRow
|
||||||
|
n, err := parseExcel(path, "", func(row feedRow) error {
|
||||||
|
got = append(got, row)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil || n != 2 || len(got) != 2 {
|
||||||
|
t.Fatalf("n=%d rows=%v err=%v", n, got, err)
|
||||||
|
}
|
||||||
|
if _, gtin := applyMappings(got[0], mappings); gtin != "3830023210103" {
|
||||||
|
t.Fatalf("gtin = %q, row %v", gtin, got[0])
|
||||||
|
}
|
||||||
|
if got[0]["Artikel"] != "UMETNA ČREVA KAL.55" || got[1]["Opis (2)"] != "75 OHM" || got[0]["Cena"] != "12.5" {
|
||||||
|
t.Fatalf("unexpected rows: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExcelSchemaCSVPreview(t *testing.T) {
|
||||||
|
data, err := excelSchemaCSV(writeTestXLSX(t), "", schemaMaxRows)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fields, rows, _, err := extractCSVSchema(data)
|
||||||
|
if err != nil || rows != 2 {
|
||||||
|
t.Fatalf("rows=%d err=%v", rows, err)
|
||||||
|
}
|
||||||
|
names := map[string]bool{}
|
||||||
|
for _, f := range fields {
|
||||||
|
names[f.Path] = true
|
||||||
|
}
|
||||||
|
for _, want := range []string{"EAN", "Artikel", "Opis", "Opis (2)", "Cena"} {
|
||||||
|
if !names[want] {
|
||||||
|
t.Fatalf("missing field %q in %v", want, names)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDetectFeedFormatExcel(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
feedType, ct, url string
|
||||||
|
sample []byte
|
||||||
|
}{
|
||||||
|
{"csv", "text/csv", "", oleMagic}, // local upload labelled text/csv
|
||||||
|
{"", "", "", append([]byte(nil), zipMagic...)}, // xlsx sniff
|
||||||
|
{"", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "", nil},
|
||||||
|
{"", "", "https://example.com/cenik.XLSX?dl=1", nil},
|
||||||
|
{"excel", "", "", nil},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := detectFeedFormat(c.feedType, c.ct, c.url, c.sample); got != "excel" {
|
||||||
|
t.Errorf("detectFeedFormat(%q,%q,%q) = %q", c.feedType, c.ct, c.url, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := detectFeedFormat("", "text/csv", "feed.csv", []byte("gtin,title\n")); got != "csv" {
|
||||||
|
t.Errorf("csv detected as %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExcelHeaderIndexSkipsTitleRows(t *testing.T) {
|
||||||
|
rows := [][]string{{"Izpis cenika"}, {"Šifra", "ARTIKEL"}, {"3830023212305", "APARAT"}}
|
||||||
|
if i := excelHeaderIndex(rows); i != 1 {
|
||||||
|
t.Fatalf("header index = %d", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Real supplier workbooks from the pilot (repo-root examples/); skipped when absent.
|
||||||
|
func TestParseExcelSupplierExamples(t *testing.T) {
|
||||||
|
cases := map[string]struct{ gtinCol, wantGTIN string }{
|
||||||
|
"KOOPMAN.xls": {"Barcode", "8721461009242"},
|
||||||
|
"Kopija datoteke Trbovc_Izpis cenika za dobavitelja_22092026.xls": {"Šifra", "3830023212305"},
|
||||||
|
"Artikli za splet Mark01 Descrybe.xlsx": {"EAN", "3830023210103"},
|
||||||
|
}
|
||||||
|
for name, c := range cases {
|
||||||
|
path := filepath.Join("..", "..", "..", "..", "examples", name)
|
||||||
|
if _, err := os.Stat(path); err != nil {
|
||||||
|
t.Logf("skip %s: %v", name, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var first feedRow
|
||||||
|
n, err := parseExcel(path, "", func(row feedRow) error {
|
||||||
|
if first == nil {
|
||||||
|
first = row
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil || n == 0 {
|
||||||
|
t.Fatalf("%s: n=%d err=%v", name, n, err)
|
||||||
|
}
|
||||||
|
if first[c.gtinCol] != c.wantGTIN {
|
||||||
|
t.Fatalf("%s: %s = %q, row %v", name, c.gtinCol, first[c.gtinCol], first)
|
||||||
|
}
|
||||||
|
t.Logf("%s: %d rows, first %v", name, n, first)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeRecordXLSX(t *testing.T, dir, name, ean, title string) string {
|
||||||
|
t.Helper()
|
||||||
|
f := excelize.NewFile()
|
||||||
|
defer f.Close()
|
||||||
|
rows := [][]any{
|
||||||
|
{"RANGE TABLE"},
|
||||||
|
{"PRODUCT INFORMATION"},
|
||||||
|
{"Commercial Name", title},
|
||||||
|
{"Set description"},
|
||||||
|
{"EAN Code", ean},
|
||||||
|
{"Product packshot - H1", "00C4DE5B-EB9B-4B3C-96E4931062A667CD"},
|
||||||
|
{"TECHNICAL CHARACTERISTICS"},
|
||||||
|
{"", "GLAVNE LASTNOSTI"},
|
||||||
|
{"Dimenzija", "24 cm"},
|
||||||
|
}
|
||||||
|
for r, row := range rows {
|
||||||
|
for c, v := range row {
|
||||||
|
cell, _ := excelize.CoordinatesToCellName(c+1, r+1)
|
||||||
|
_ = f.SetCellValue("Sheet1", cell, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := f.NewSheet("MEDIA"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
media := [][]any{
|
||||||
|
{"Product packshot - H1", "Image Url", "https://cdn.example/a.jpg"},
|
||||||
|
{"Other packshots", "Image Url", "https://cdn.example/b.jpg"},
|
||||||
|
{"Other packshots", "Image Url", "https://cdn.example/c.jpg"},
|
||||||
|
{"Benefit image 11", "Media Id"},
|
||||||
|
}
|
||||||
|
for r, row := range media {
|
||||||
|
for c, v := range row {
|
||||||
|
cell, _ := excelize.CoordinatesToCellName(c+1, r+1)
|
||||||
|
_ = f.SetCellValue("MEDIA", cell, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p := filepath.Join(dir, name)
|
||||||
|
if err := f.SaveAs(p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseExcelRecordWorkbookIsOneProduct(t *testing.T) {
|
||||||
|
p := writeRecordXLSX(t, t.TempDir(), "B1.xlsm", "3168430313385", "SIMPLY CLEAN FRYPAN 24 CM")
|
||||||
|
var rows []feedRow
|
||||||
|
n, err := parseExcel(p, "", func(r feedRow) error { rows = append(rows, r); return nil })
|
||||||
|
if err != nil || n != 1 {
|
||||||
|
t.Fatalf("n=%d err=%v rows=%v", n, err, rows)
|
||||||
|
}
|
||||||
|
r := rows[0]
|
||||||
|
if r["PRODUCT INFORMATION/EAN Code"] != "3168430313385" || r["PRODUCT INFORMATION/Commercial Name"] != "SIMPLY CLEAN FRYPAN 24 CM" || r["TECHNICAL CHARACTERISTICS/Dimenzija"] != "24 cm" {
|
||||||
|
t.Fatalf("record fields: %v", r)
|
||||||
|
}
|
||||||
|
if r["Product packshot - H1 Image Url"] != "https://cdn.example/a.jpg" ||
|
||||||
|
r["Other packshots Image Url"] != "https://cdn.example/b.jpg,https://cdn.example/c.jpg" {
|
||||||
|
t.Fatalf("media fields: %v", r)
|
||||||
|
}
|
||||||
|
for _, junk := range []string{"PRODUCT INFORMATION/Set description", "Benefit image 11", "PRODUCT INFORMATION/Product packshot - H1"} {
|
||||||
|
if _, ok := r[junk]; ok {
|
||||||
|
t.Fatalf("%q must be skipped (no value / media id): %v", junk, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseExcelZipOfWorkbooks(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
a := writeRecordXLSX(t, dir, "A.xlsm", "3168430313385", "Pan A")
|
||||||
|
b := writeRecordXLSX(t, dir, "B.xlsm", "3168430313392", "Pan B")
|
||||||
|
zipPath := filepath.Join(dir, "groupeseb.zip")
|
||||||
|
out, err := os.Create(zipPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
zw := zip.NewWriter(out)
|
||||||
|
for _, p := range []string{b, a} {
|
||||||
|
w, err := zw.Create("seb/" + filepath.Base(p))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data, _ := os.ReadFile(p)
|
||||||
|
_, _ = w.Write(data)
|
||||||
|
}
|
||||||
|
_, _ = zw.Create("__MACOSX/seb/._A.xlsm")
|
||||||
|
if err := zw.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = out.Close()
|
||||||
|
|
||||||
|
if got := detectFeedFormat("", "", "", []byte(string(zipMagic))); got != "excel" {
|
||||||
|
t.Fatalf("zip detected as %q", got)
|
||||||
|
}
|
||||||
|
var eans []string
|
||||||
|
n, err := parseExcel(zipPath, "", func(r feedRow) error { eans = append(eans, r["PRODUCT INFORMATION/EAN Code"]); return nil })
|
||||||
|
if err != nil || n != 2 || eans[0] != "3168430313385" || eans[1] != "3168430313392" {
|
||||||
|
t.Fatalf("n=%d eans=%v err=%v", n, eans, err)
|
||||||
|
}
|
||||||
|
data, err := excelSchemaCSV(zipPath, "", schemaMaxRows)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, rows, _, err := extractCSVSchema(data); err != nil || rows != 2 {
|
||||||
|
t.Fatalf("schema rows=%d err=%v", rows, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseExcelGroupeSebExample(t *testing.T) {
|
||||||
|
p := filepath.Join("..", "..", "..", "..", "examples", "pilot-4-suppliers", "groupe-seb", "B5670453.xlsm")
|
||||||
|
if _, err := os.Stat(p); err != nil {
|
||||||
|
t.Skipf("example missing: %v", err)
|
||||||
|
}
|
||||||
|
var r feedRow
|
||||||
|
n, err := parseExcel(p, "", func(row feedRow) error { r = row; return nil })
|
||||||
|
if err != nil || n != 1 {
|
||||||
|
t.Fatalf("n=%d err=%v", n, err)
|
||||||
|
}
|
||||||
|
for k, want := range map[string]string{
|
||||||
|
"LOGISTICS DATA/EAN Code": "3168430313385",
|
||||||
|
"PRODUCT INFORMATION/Brand": "TEFAL",
|
||||||
|
"TECHNICAL CHARACTERISTICS/Dimenzija": "24 cm",
|
||||||
|
} {
|
||||||
|
if r[k] != want {
|
||||||
|
t.Fatalf("%s = %q want %q", k, r[k], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(r["Product packshot - H1 Image Url"], "https://") || r["MARKETING INFORMATION/Short description detail"] == "" {
|
||||||
|
t.Fatalf("missing media/short description: %v", r)
|
||||||
|
}
|
||||||
|
if specs := resolveSpecifications(r, "TECHNICAL CHARACTERISTICS"); len(specs) < 10 {
|
||||||
|
t.Fatalf("technical characteristics as specs: %v", specs)
|
||||||
|
}
|
||||||
|
t.Logf("%d fields", len(r))
|
||||||
|
}
|
||||||
@@ -80,6 +80,8 @@ type exportProduct struct {
|
|||||||
ProcessedAttributes []byte
|
ProcessedAttributes []byte
|
||||||
MappedData []byte
|
MappedData []byte
|
||||||
FeedID *uuid.UUID
|
FeedID *uuid.UUID
|
||||||
|
MetaTitle *string
|
||||||
|
MetaDescription *string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Known EPREL / energy-label source aliases resolved from processed JSON.
|
// Known EPREL / energy-label source aliases resolved from processed JSON.
|
||||||
@@ -296,7 +298,7 @@ func (s *Service) queryExportProductsBatch(
|
|||||||
return s.Pool.Query(ctx, `
|
return s.Pool.Query(ctx, `
|
||||||
SELECT p.id, p.updated_at, p.product_id, p.name, p.category, p.description, p.processed_description, p.processed_name,
|
SELECT p.id, p.updated_at, p.product_id, p.name, p.category, p.description, p.processed_description, p.processed_name,
|
||||||
p.status, p.attributes, p.processed_attributes,
|
p.status, p.attributes, p.processed_attributes,
|
||||||
COALESCE(r.mapped_data, '{}'::jsonb), p.feed_id
|
COALESCE(r.mapped_data, '{}'::jsonb), p.feed_id, p.meta_title, p.meta_description
|
||||||
FROM processed_products p
|
FROM processed_products p
|
||||||
LEFT JOIN raw_products r ON r.id = p.raw_product_id AND r.company_id = p.company_id
|
LEFT JOIN raw_products r ON r.id = p.raw_product_id AND r.company_id = p.company_id
|
||||||
WHERE p.company_id = $1
|
WHERE p.company_id = $1
|
||||||
@@ -402,6 +404,17 @@ func productFieldValue(p exportProduct, source string) string {
|
|||||||
return derefStr(p.ProcessedDescription)
|
return derefStr(p.ProcessedDescription)
|
||||||
case "processed_name":
|
case "processed_name":
|
||||||
return derefStr(p.ProcessedName)
|
return derefStr(p.ProcessedName)
|
||||||
|
case "meta_title":
|
||||||
|
return derefStr(p.MetaTitle)
|
||||||
|
case "meta_description":
|
||||||
|
return derefStr(p.MetaDescription)
|
||||||
|
case "short_description", "short_desc":
|
||||||
|
// Supplier-mapped short copy wins; else the generated meta description,
|
||||||
|
// matching the WooCommerce sync's short_description.
|
||||||
|
if v := lookupFlattened(flattenProductAttrs(p), "short_description"); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return derefStr(p.MetaDescription)
|
||||||
case "status":
|
case "status":
|
||||||
return derefStr(p.Status)
|
return derefStr(p.Status)
|
||||||
case "feed_id":
|
case "feed_id":
|
||||||
@@ -706,6 +719,7 @@ func scanExportProduct(rows pgx.Rows) (exportProduct, error) {
|
|||||||
err := rows.Scan(
|
err := rows.Scan(
|
||||||
&p.ProductID, &p.Name, &p.Category, &p.Description, &p.ProcessedDescription, &p.ProcessedName,
|
&p.ProductID, &p.Name, &p.Category, &p.Description, &p.ProcessedDescription, &p.ProcessedName,
|
||||||
&p.Status, &p.Attributes, &p.ProcessedAttributes, &p.MappedData, &p.FeedID,
|
&p.Status, &p.Attributes, &p.ProcessedAttributes, &p.MappedData, &p.FeedID,
|
||||||
|
&p.MetaTitle, &p.MetaDescription,
|
||||||
)
|
)
|
||||||
return p, err
|
return p, err
|
||||||
}
|
}
|
||||||
@@ -720,6 +734,7 @@ func scanExportProductWithCursor(rows pgx.Rows) (exportProduct, uuid.UUID, time.
|
|||||||
&id, &updatedAt,
|
&id, &updatedAt,
|
||||||
&p.ProductID, &p.Name, &p.Category, &p.Description, &p.ProcessedDescription, &p.ProcessedName,
|
&p.ProductID, &p.Name, &p.Category, &p.Description, &p.ProcessedDescription, &p.ProcessedName,
|
||||||
&p.Status, &p.Attributes, &p.ProcessedAttributes, &p.MappedData, &p.FeedID,
|
&p.Status, &p.Attributes, &p.ProcessedAttributes, &p.MappedData, &p.FeedID,
|
||||||
|
&p.MetaTitle, &p.MetaDescription,
|
||||||
)
|
)
|
||||||
return p, id, updatedAt, err
|
return p, id, updatedAt, err
|
||||||
}
|
}
|
||||||
@@ -759,6 +774,9 @@ func (s *Service) PublicExportXML(ctx context.Context, w io.Writer, token string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PublicExportCSV streams CSV for a public export token.
|
// PublicExportCSV streams CSV for a public export token.
|
||||||
|
func (s *Service) PublicExportJSON(ctx context.Context, w io.Writer, token string) error {
|
||||||
|
return s.StreamPublicExport(ctx, w, token, "json")
|
||||||
|
}
|
||||||
func (s *Service) PublicExportCSV(ctx context.Context, w io.Writer, token string) error {
|
func (s *Service) PublicExportCSV(ctx context.Context, w io.Writer, token string) error {
|
||||||
return s.StreamPublicExport(ctx, w, token, "csv")
|
return s.StreamPublicExport(ctx, w, token, "csv")
|
||||||
}
|
}
|
||||||
@@ -805,6 +823,8 @@ func (s *Service) streamExport(ctx context.Context, w io.Writer, row exportFeedR
|
|||||||
switch format {
|
switch format {
|
||||||
case "csv":
|
case "csv":
|
||||||
return streamCSV(w, seq, tpl)
|
return streamCSV(w, seq, tpl)
|
||||||
|
case "json":
|
||||||
|
return streamJSON(w, seq, tpl)
|
||||||
default:
|
default:
|
||||||
return streamXML(w, seq, tpl, row.Name)
|
return streamXML(w, seq, tpl, row.Name)
|
||||||
}
|
}
|
||||||
@@ -869,6 +889,11 @@ func writeXMLProduct(w io.Writer, item string, tpl exportTemplate, p exportProdu
|
|||||||
}
|
}
|
||||||
|
|
||||||
func streamCSV(w io.Writer, seq exportProductSeq, tpl exportTemplate) (int, error) {
|
func streamCSV(w io.Writer, seq exportProductSeq, tpl exportTemplate) (int, error) {
|
||||||
|
// UTF-8 BOM makes Excel detect Unicode without its locale-dependent CSV import.
|
||||||
|
// The BOM is emitted once per file and does not change the exported field data.
|
||||||
|
if _, err := io.WriteString(w, "\ufeff"); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
cw := csv.NewWriter(w)
|
cw := csv.NewWriter(w)
|
||||||
headers := make([]string, len(tpl.Fields))
|
headers := make([]string, len(tpl.Fields))
|
||||||
for i, f := range tpl.Fields {
|
for i, f := range tpl.Fields {
|
||||||
@@ -966,6 +991,9 @@ func (s *Service) ExportSelectedProducts(ctx context.Context, companyID, feedID
|
|||||||
case "csv":
|
case "csv":
|
||||||
count, err = streamCSV(&buf, seq, tpl)
|
count, err = streamCSV(&buf, seq, tpl)
|
||||||
mimeType = "text/csv; charset=utf-8"
|
mimeType = "text/csv; charset=utf-8"
|
||||||
|
case "json":
|
||||||
|
count, err = streamJSON(&buf, seq, tpl)
|
||||||
|
mimeType = "application/json; charset=utf-8"
|
||||||
default:
|
default:
|
||||||
count, err = streamXML(&buf, seq, tpl, row.Name)
|
count, err = streamXML(&buf, seq, tpl, row.Name)
|
||||||
mimeType = "application/xml; charset=utf-8"
|
mimeType = "application/xml; charset=utf-8"
|
||||||
@@ -987,7 +1015,7 @@ func (s *Service) queryExportProductsByIDs(ctx context.Context, companyID uuid.U
|
|||||||
return s.Pool.Query(ctx, `
|
return s.Pool.Query(ctx, `
|
||||||
SELECT p.product_id, p.name, p.category, p.description, p.processed_description, p.processed_name,
|
SELECT p.product_id, p.name, p.category, p.description, p.processed_description, p.processed_name,
|
||||||
p.status, p.attributes, p.processed_attributes,
|
p.status, p.attributes, p.processed_attributes,
|
||||||
COALESCE(r.mapped_data, '{}'::jsonb), p.feed_id
|
COALESCE(r.mapped_data, '{}'::jsonb), p.feed_id, p.meta_title, p.meta_description
|
||||||
FROM processed_products p
|
FROM processed_products p
|
||||||
LEFT JOIN raw_products r ON r.id = p.raw_product_id AND r.company_id = p.company_id
|
LEFT JOIN raw_products r ON r.id = p.raw_product_id AND r.company_id = p.company_id
|
||||||
WHERE p.company_id = $1
|
WHERE p.company_id = $1
|
||||||
@@ -1002,6 +1030,17 @@ func (s *Service) queryExportProductsByIDs(ctx context.Context, companyID uuid.U
|
|||||||
func renderExportSnippet(format string, tpl exportTemplate, products []exportProduct, feedName string) (string, int, error) {
|
func renderExportSnippet(format string, tpl exportTemplate, products []exportProduct, feedName string) (string, int, error) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
switch strings.ToLower(strings.TrimSpace(format)) {
|
switch strings.ToLower(strings.TrimSpace(format)) {
|
||||||
|
case "json":
|
||||||
|
seq := exportProductSeq(func(yield func(exportProduct) error) error {
|
||||||
|
for _, p := range products {
|
||||||
|
if err := yield(p); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
n, err := streamJSON(&buf, seq, tpl)
|
||||||
|
return buf.String(), n, err
|
||||||
case "csv":
|
case "csv":
|
||||||
cw := csv.NewWriter(&buf)
|
cw := csv.NewWriter(&buf)
|
||||||
headers := make([]string, len(tpl.Fields))
|
headers := make([]string, len(tpl.Fields))
|
||||||
@@ -1063,3 +1102,68 @@ func sanitizeExportFileName(name string) string {
|
|||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// streamJSON emits valid JSON objects one at a time with no catalog-wide buffering.
|
||||||
|
// The outer key follows the configured template root (products by default).
|
||||||
|
func streamJSON(w io.Writer, seq exportProductSeq, tpl exportTemplate) (int, error) {
|
||||||
|
root := strings.TrimSpace(tpl.Root)
|
||||||
|
if root == "" {
|
||||||
|
root = "products"
|
||||||
|
}
|
||||||
|
key, err := json.Marshal(root)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if _, err := fmt.Fprintf(w, "{%s:[", key); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
count := 0
|
||||||
|
err = seq(func(p exportProduct) error {
|
||||||
|
row := make(map[string]any, len(tpl.Fields))
|
||||||
|
for _, field := range tpl.Fields {
|
||||||
|
name := strings.TrimSpace(field.Key)
|
||||||
|
if name == "" {
|
||||||
|
name = field.Source
|
||||||
|
}
|
||||||
|
if isSpecExpandSource(field.Source) {
|
||||||
|
specs := map[string]string{}
|
||||||
|
for _, spec := range expandSpecFields(p) {
|
||||||
|
if val := productFieldValue(p, spec.Source); val != "" {
|
||||||
|
specs[spec.Key] = val
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(specs) > 0 {
|
||||||
|
row[name] = specs
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
row[name] = productFieldValue(p, field.Source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(row)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if count > 0 {
|
||||||
|
if _, err := io.WriteString(w, ","); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := w.Write(encoded); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
if count%exportChunkHint == 0 {
|
||||||
|
if f, ok := w.(interface{ Flush() }); ok {
|
||||||
|
f.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return count, err
|
||||||
|
}
|
||||||
|
_, err = io.WriteString(w, "]}\n")
|
||||||
|
return count, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestProductFieldValueShortDescription(t *testing.T) {
|
||||||
|
meta := "Ponev Tefal Simply Clean 24 cm z oblogo s titanom."
|
||||||
|
generated := exportProduct{MetaDescription: &meta, MappedData: []byte(`{"gtin":"3168430313385"}`)}
|
||||||
|
if got := productFieldValue(generated, "short_description"); got != meta {
|
||||||
|
t.Fatalf("fallback short_description = %q", got)
|
||||||
|
}
|
||||||
|
supplier := exportProduct{MetaDescription: &meta, MappedData: []byte(`{"short_description":"Vsi vemo, da je za okusno kuho potreben čas."}`)}
|
||||||
|
if got := productFieldValue(supplier, "short_description"); got != "Vsi vemo, da je za okusno kuho potreben čas." {
|
||||||
|
t.Fatalf("mapped short_description = %q", got)
|
||||||
|
}
|
||||||
|
if got := productFieldValue(generated, "meta_description"); got != meta {
|
||||||
|
t.Fatalf("meta_description = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -335,7 +335,10 @@ func TestStreamCSVUsesProductSeqWithoutCollecting(t *testing.T) {
|
|||||||
if n != 1 {
|
if n != 1 {
|
||||||
t.Fatalf("count=%d", n)
|
t.Fatalf("count=%d", n)
|
||||||
}
|
}
|
||||||
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
|
if !strings.HasPrefix(buf.String(), "\ufeff") {
|
||||||
|
t.Fatalf("downloadable CSV must start with UTF-8 BOM: %q", buf.Bytes()[:min(buf.Len(), 8)])
|
||||||
|
}
|
||||||
|
lines := strings.Split(strings.TrimSpace(strings.TrimPrefix(buf.String(), "\ufeff")), "\n")
|
||||||
if len(lines) != 2 {
|
if len(lines) != 2 {
|
||||||
t.Fatalf("lines=%v", lines)
|
t.Fatalf("lines=%v", lines)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/csv"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/xml"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExportUnicodeSurvivesEveryFormat(t *testing.T) {
|
||||||
|
name := "Črpalka, šoba Žuža – München 東京 Привет"
|
||||||
|
tpl := exportTemplate{Fields: []exportField{{Key: "Naziv č š ž", Source: "name"}}}
|
||||||
|
seq := func(yield func(exportProduct) error) error {
|
||||||
|
return yield(exportProduct{Name: &name})
|
||||||
|
}
|
||||||
|
for _, format := range []string{"csv", "xml", "json"} {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
var n int
|
||||||
|
var err error
|
||||||
|
switch format {
|
||||||
|
case "csv":
|
||||||
|
n, err = streamCSV(&buf, seq, tpl)
|
||||||
|
case "xml":
|
||||||
|
n, err = streamXML(&buf, seq, tpl, "Izvoz")
|
||||||
|
case "json":
|
||||||
|
n, err = streamJSON(&buf, seq, tpl)
|
||||||
|
}
|
||||||
|
if err != nil || n != 1 {
|
||||||
|
t.Fatalf("%s: count=%d err=%v", format, n, err)
|
||||||
|
}
|
||||||
|
if !utf8.Valid(buf.Bytes()) {
|
||||||
|
t.Fatalf("%s: invalid UTF-8", format)
|
||||||
|
}
|
||||||
|
switch format {
|
||||||
|
case "csv":
|
||||||
|
if !bytes.HasPrefix(buf.Bytes(), []byte("\ufeff")) {
|
||||||
|
t.Fatal("CSV has no UTF-8 BOM")
|
||||||
|
}
|
||||||
|
r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(buf.Bytes(), []byte("\ufeff"))))
|
||||||
|
rows, err := r.ReadAll()
|
||||||
|
if err != nil || len(rows) != 2 || rows[0][0] != "Naziv č š ž" || rows[1][0] != name {
|
||||||
|
t.Fatalf("CSV data lost Unicode: %v, %v", rows, err)
|
||||||
|
}
|
||||||
|
case "xml":
|
||||||
|
var out struct {
|
||||||
|
Name string `xml:"Naziv_č_š_ž"`
|
||||||
|
}
|
||||||
|
if !strings.Contains(buf.String(), name) {
|
||||||
|
t.Fatalf("XML missing Unicode: %s", buf.String())
|
||||||
|
}
|
||||||
|
if err := xml.Unmarshal(buf.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("XML invalid: %v", err)
|
||||||
|
}
|
||||||
|
case "json":
|
||||||
|
if !json.Valid(buf.Bytes()) || !bytes.Contains(buf.Bytes(), []byte(name)) {
|
||||||
|
t.Fatalf("JSON invalid or data lost: %s", buf.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -115,6 +115,39 @@ func (s *Service) ExtractSchema(ctx context.Context, companyID, feedID uuid.UUID
|
|||||||
out.Fields = fields
|
out.Fields = fields
|
||||||
out.SampleRows = rows
|
out.SampleRows = rows
|
||||||
out.Preview = buildXMLPreview(data, local)
|
out.Preview = buildXMLPreview(data, local)
|
||||||
|
case "json":
|
||||||
|
suggested := guessJSONItemPath(data)
|
||||||
|
out.SuggestedPath = suggested
|
||||||
|
path := itemPathHint
|
||||||
|
if path == "" {
|
||||||
|
path = suggested
|
||||||
|
out.ItemPath = path
|
||||||
|
}
|
||||||
|
fields, rows, err := extractJSONSchema(data, path)
|
||||||
|
if err != nil && !(truncated && rows > 0 && (errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) || strings.Contains(strings.ToLower(err.Error()), "unexpected eof"))) {
|
||||||
|
return nil, fmt.Errorf("JSON preview: %w; check the item path and response format", err)
|
||||||
|
}
|
||||||
|
out.Fields = fields
|
||||||
|
out.SampleRows = rows
|
||||||
|
preview := data
|
||||||
|
if len(preview) > 4096 {
|
||||||
|
preview = preview[:4096]
|
||||||
|
}
|
||||||
|
out.Preview = string(preview)
|
||||||
|
case "excel":
|
||||||
|
// Workbooks need the whole file (zip/OLE directory), so read from disk, not the sample.
|
||||||
|
sheetCSV, err := excelSchemaCSV(f.Name(), excelSheetOption(feed), schemaMaxRows)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
fields, rows, preview, err := extractCSVSchema(sheetCSV)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out.Fields = fields
|
||||||
|
out.SampleRows = rows
|
||||||
|
out.Preview = preview
|
||||||
|
out.PreviewTruncated = false
|
||||||
default:
|
default:
|
||||||
fields, rows, preview, err := extractCSVSchema(data)
|
fields, rows, preview, err := extractCSVSchema(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -221,6 +254,7 @@ func guessXMLItemPath(data []byte) string {
|
|||||||
full string
|
full string
|
||||||
}
|
}
|
||||||
cands := []cand{
|
cands := []cand{
|
||||||
|
{"shopitem", "shop/shopitem"},
|
||||||
{"item", "rss/channel/item"},
|
{"item", "rss/channel/item"},
|
||||||
{"product", "products/product"},
|
{"product", "products/product"},
|
||||||
{"entry", "feed/entry"},
|
{"entry", "feed/entry"},
|
||||||
@@ -232,9 +266,11 @@ func guessXMLItemPath(data []byte) string {
|
|||||||
if path := findFirstTagPath(data, c.local); path != "" {
|
if path := findFirstTagPath(data, c.local); path != "" {
|
||||||
return path
|
return path
|
||||||
}
|
}
|
||||||
return c.full
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if path := guessRepeatedXMLItemPath([]byte(sample)); path != "" {
|
||||||
|
return path
|
||||||
|
}
|
||||||
return "rss/channel/item"
|
return "rss/channel/item"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,7 +319,8 @@ func extractXMLSchema(data []byte, itemLocal string) ([]SchemaField, int, error)
|
|||||||
accumulateRowFields(acc, row)
|
accumulateRowFields(acc, row)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil && !errors.Is(err, errStopSchema) {
|
// The preview window cuts large feeds mid-record; rows read before the cut count.
|
||||||
|
if err != nil && !errors.Is(err, errStopSchema) && !(rows > 0 && strings.Contains(err.Error(), "unexpected EOF")) {
|
||||||
return nil, rows, err
|
return nil, rows, err
|
||||||
}
|
}
|
||||||
return finalizeSchema(acc), rows, nil
|
return finalizeSchema(acc), rows, nil
|
||||||
@@ -340,7 +377,7 @@ func extractCSVSchema(data []byte) ([]SchemaField, int, string, error) {
|
|||||||
}
|
}
|
||||||
cols := make([]string, len(header))
|
cols := make([]string, len(header))
|
||||||
for i, h := range header {
|
for i, h := range header {
|
||||||
cols[i] = strings.TrimSpace(h)
|
cols[i] = strings.TrimSpace(strings.TrimPrefix(h, "\uFEFF"))
|
||||||
}
|
}
|
||||||
|
|
||||||
acc := map[string]*fieldAcc{}
|
acc := map[string]*fieldAcc{}
|
||||||
@@ -527,3 +564,20 @@ func buildXMLPreview(data []byte, itemLocal string) string {
|
|||||||
_ = itemLocal
|
_ = itemLocal
|
||||||
return strings.Join(out, "\n")
|
return strings.Join(out, "\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func extractJSONSchema(data []byte, itemPath string) ([]SchemaField, int, error) {
|
||||||
|
acc := map[string]*fieldAcc{}
|
||||||
|
rows := 0
|
||||||
|
_, err := parseJSONItems(bytes.NewReader(data), itemPath, func(row feedRow) error {
|
||||||
|
rows++
|
||||||
|
if rows > schemaMaxRows {
|
||||||
|
return errStopSchema
|
||||||
|
}
|
||||||
|
accumulateRowFields(acc, row)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil && !errors.Is(err, errStopSchema) {
|
||||||
|
return nil, rows, err
|
||||||
|
}
|
||||||
|
return finalizeSchema(acc), rows, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/secretcrypto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Custom remote source headers are stored only as encrypted options; never in response DTOs.
|
||||||
|
func validatedFeedHeaders(input map[string]string) (map[string]string, error) {
|
||||||
|
if len(input) > 20 {
|
||||||
|
return nil, ClientMsg("at most 20 HTTP headers")
|
||||||
|
}
|
||||||
|
clean := make(map[string]string, len(input))
|
||||||
|
for name, value := range input {
|
||||||
|
name = http.CanonicalHeaderKey(strings.TrimSpace(name))
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if !httpValidHeaderName(name) || strings.ContainsAny(value, "\r\n") || len(value) > 4096 {
|
||||||
|
return nil, ClientMsg("invalid feed HTTP header")
|
||||||
|
}
|
||||||
|
switch strings.ToLower(name) {
|
||||||
|
case "host", "connection", "content-length", "transfer-encoding", "cookie", "proxy-authorization", "proxy-connection", "upgrade":
|
||||||
|
return nil, ClientMsg("unsafe feed HTTP header")
|
||||||
|
}
|
||||||
|
if value != "" {
|
||||||
|
clean[name] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return clean, nil
|
||||||
|
}
|
||||||
|
func httpValidHeaderName(name string) bool {
|
||||||
|
if name == "" || len(name) > 100 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range name {
|
||||||
|
if !(r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || strings.ContainsRune("!#$%&'*+-.^_`|~", r)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func secretEncryptionKey() []byte {
|
||||||
|
material := os.Getenv("APP_ENCRYPTION_KEY")
|
||||||
|
if material == "" {
|
||||||
|
material = os.Getenv("CREDENTIALS_ENCRYPTION_KEY")
|
||||||
|
}
|
||||||
|
return secretcrypto.DeriveKey(material, os.Getenv("TOKEN_SIGNING_SECRET"))
|
||||||
|
}
|
||||||
|
func encryptFeedHeaders(headers map[string]string) (string, error) {
|
||||||
|
clean, err := validatedFeedHeaders(headers)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(clean) == 0 {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
key := secretEncryptionKey()
|
||||||
|
if len(key) != 32 {
|
||||||
|
return "", errors.New("APP_ENCRYPTION_KEY is required for authenticated feed URLs")
|
||||||
|
}
|
||||||
|
b, err := json.Marshal(clean)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return secretcrypto.EncryptSecret(key, string(b))
|
||||||
|
}
|
||||||
|
func decryptFeedHeaders(options any) (map[string]string, error) {
|
||||||
|
opt, ok := options.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
encrypted, _ := opt["request_headers_encrypted"].(string)
|
||||||
|
if encrypted == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
plain, err := secretcrypto.DecryptSecret(secretEncryptionKey(), encrypted)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("cannot decrypt feed credentials; ensure same APP_ENCRYPTION_KEY on API and worker")
|
||||||
|
}
|
||||||
|
out := map[string]string{}
|
||||||
|
if err := json.Unmarshal([]byte(plain), &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return validatedFeedHeaders(out)
|
||||||
|
}
|
||||||
@@ -123,7 +123,6 @@ func parseMappings(raw any) []FieldMapping {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// fieldMappingFromUIEntry unwraps dashboard rows shaped like
|
// fieldMappingFromUIEntry unwraps dashboard rows shaped like
|
||||||
// {"key":"Export/Item/ID","mapping":{"fieldName":"id","xpath":"Export/Item/ID"}}.
|
// {"key":"Export/Item/ID","mapping":{"fieldName":"id","xpath":"Export/Item/ID"}}.
|
||||||
func fieldMappingFromUIEntry(item any) (FieldMapping, bool) {
|
func fieldMappingFromUIEntry(item any) (FieldMapping, bool) {
|
||||||
@@ -228,8 +227,34 @@ func isSpecificationsTarget(tgt string) bool {
|
|||||||
// CDATA HTML, or flat strings. Empty/missing yields nil.
|
// CDATA HTML, or flat strings. Empty/missing yields nil.
|
||||||
func resolveSpecifications(row map[string]string, src string) map[string]string {
|
func resolveSpecifications(row map[string]string, src string) map[string]string {
|
||||||
src = strings.Trim(strings.TrimSpace(src), "/")
|
src = strings.Trim(strings.TrimSpace(src), "/")
|
||||||
|
if strings.EqualFold(leafName(src), "PARAMS") {
|
||||||
|
specs := map[string]string{}
|
||||||
|
for k, v := range row {
|
||||||
|
if !strings.HasPrefix(strings.ToLower(k), strings.ToLower(src)+"/") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rel := k[len(src)+1:]
|
||||||
|
if strings.Contains(rel, "/") || strings.EqualFold(rel, "PARAM") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(v) != "" {
|
||||||
|
specs[rel] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(specs) > 0 {
|
||||||
|
return normalizeSpecKeys(specs)
|
||||||
|
}
|
||||||
|
}
|
||||||
if children := collectPrefixed(row, src); len(children) > 0 {
|
if children := collectPrefixed(row, src); len(children) > 0 {
|
||||||
return normalizeSpecKeys(children)
|
clean := map[string]string{}
|
||||||
|
for k, v := range children {
|
||||||
|
if !strings.Contains(k, "/") {
|
||||||
|
clean[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(clean) > 0 {
|
||||||
|
return normalizeSpecKeys(clean)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if val, ok := lookupRow(row, src); ok {
|
if val, ok := lookupRow(row, src); ok {
|
||||||
if pairs := ParseSpecifications(val); len(pairs) > 0 {
|
if pairs := ParseSpecifications(val); len(pairs) > 0 {
|
||||||
@@ -262,7 +287,7 @@ func normalizeSpecKeys(in map[string]string) map[string]string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func lookupRow(row map[string]string, key string) (string, bool) {
|
func lookupRow(row map[string]string, key string) (string, bool) {
|
||||||
key = strings.Trim(strings.TrimSpace(key), "/")
|
key = strings.Trim(strings.TrimSpace(strings.TrimPrefix(key, "\uFEFF")), "/")
|
||||||
if key == "" {
|
if key == "" {
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,356 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cross-feed merge.
|
||||||
|
//
|
||||||
|
// A product (company + EAN) can appear in several vendor feeds, each with partial data.
|
||||||
|
// Every feed keeps its own row (raw_product_feed_rows); raw_products.mapped_data is the
|
||||||
|
// merge of all of them and raw_products.feed_field_sources records which feed supplied
|
||||||
|
// each field.
|
||||||
|
//
|
||||||
|
// Rules:
|
||||||
|
// - A field that only one feed has is taken as is.
|
||||||
|
// - description / long_description: the feed with the most text wins.
|
||||||
|
// - image lists (more_images, …): union of every feed, duplicates removed.
|
||||||
|
// - specifications: union of the keys of every feed.
|
||||||
|
// - Any other field present in several feeds with different values is a conflict;
|
||||||
|
// the richest feed (most filled fields) wins and the others are listed as "also".
|
||||||
|
|
||||||
|
// feedRowInput is one feed's mapped data for a single EAN.
|
||||||
|
type feedRowInput struct {
|
||||||
|
FeedID uuid.UUID
|
||||||
|
FeedName string
|
||||||
|
Mapped map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
// sourceRef identifies a feed in the field-source map.
|
||||||
|
type sourceRef struct {
|
||||||
|
FeedID string `json:"feed_id"`
|
||||||
|
FeedName string `json:"feed_name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// fieldSource says where one merged field came from.
|
||||||
|
type fieldSource struct {
|
||||||
|
FeedID string `json:"feed_id"`
|
||||||
|
FeedName string `json:"feed_name"`
|
||||||
|
Conflict bool `json:"conflict,omitempty"`
|
||||||
|
Also []sourceRef `json:"also,omitempty"` // other feeds that had a different value
|
||||||
|
MergedBy []sourceRef `json:"merged_from,omitempty"` // lists/specs: every contributing feed
|
||||||
|
Keys map[string]string `json:"keys,omitempty"` // specifications: key -> feed name
|
||||||
|
}
|
||||||
|
|
||||||
|
// feedFieldSources is stored in raw_products.feed_field_sources.
|
||||||
|
type feedFieldSources struct {
|
||||||
|
Primary sourceRef `json:"primary"` // richest feed; becomes raw_products.feed_id
|
||||||
|
Feeds []sourceRef `json:"feeds"`
|
||||||
|
Fields map[string]fieldSource `json:"fields"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
listFieldKeys = map[string]bool{
|
||||||
|
"more_images": true, "moreimages": true, "images": true,
|
||||||
|
"additional_image_urls": true, "additional_image_link": true,
|
||||||
|
}
|
||||||
|
descriptionFieldKeys = map[string]bool{"description": true, "long_description": true}
|
||||||
|
htmlTagRe = regexp.MustCompile(`(?s)<[^>]*>`)
|
||||||
|
spaceRe = regexp.MustCompile(`\s+`)
|
||||||
|
listSplitRe = regexp.MustCompile(`[,;\n\r|]+`)
|
||||||
|
)
|
||||||
|
|
||||||
|
func filledValue(v any) bool {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case nil:
|
||||||
|
return false
|
||||||
|
case string:
|
||||||
|
s := strings.TrimSpace(t)
|
||||||
|
return s != "" && s != "<nil>"
|
||||||
|
case map[string]any:
|
||||||
|
return len(t) > 0
|
||||||
|
case map[string]string:
|
||||||
|
return len(t) > 0
|
||||||
|
case []any:
|
||||||
|
return len(t) > 0
|
||||||
|
default:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizedValue(v any) string {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case string:
|
||||||
|
return strings.ToLower(spaceRe.ReplaceAllString(strings.TrimSpace(t), " "))
|
||||||
|
default:
|
||||||
|
b, err := json.Marshal(t)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprint(t)
|
||||||
|
}
|
||||||
|
return strings.ToLower(string(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// plainTextLen measures description richness without HTML markup.
|
||||||
|
func plainTextLen(v any) int {
|
||||||
|
s, ok := v.(string)
|
||||||
|
if !ok {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
s = htmlTagRe.ReplaceAllString(s, " ")
|
||||||
|
s = html.UnescapeString(s)
|
||||||
|
return len([]rune(strings.TrimSpace(spaceRe.ReplaceAllString(s, " "))))
|
||||||
|
}
|
||||||
|
|
||||||
|
func asStringMap(v any) (map[string]any, bool) {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case map[string]any:
|
||||||
|
return t, true
|
||||||
|
case map[string]string:
|
||||||
|
out := make(map[string]any, len(t))
|
||||||
|
for k, val := range t {
|
||||||
|
out[k] = val
|
||||||
|
}
|
||||||
|
return out, true
|
||||||
|
}
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func rowFilledCount(m map[string]any) int {
|
||||||
|
n := 0
|
||||||
|
for k, v := range m {
|
||||||
|
if k == syncChangesMappedKey {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if specs, ok := asStringMap(v); ok && k == "specifications" {
|
||||||
|
n += len(specs)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if filledValue(v) {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func descriptionLen(m map[string]any) int {
|
||||||
|
best := 0
|
||||||
|
for k := range descriptionFieldKeys {
|
||||||
|
if n := plainTextLen(m[k]); n > best {
|
||||||
|
best = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitList(v any) []string {
|
||||||
|
s, ok := v.(string)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, part := range listSplitRe.Split(s, -1) {
|
||||||
|
if p := strings.TrimSpace(part); p != "" {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// mergeFeedRows merges the per-feed mapped data of one EAN. The result never mutates
|
||||||
|
// its inputs. With a single row it returns a copy plus a source map naming that feed.
|
||||||
|
func mergeFeedRows(rows []feedRowInput) (map[string]any, feedFieldSources) {
|
||||||
|
merged := map[string]any{}
|
||||||
|
src := feedFieldSources{Feeds: []sourceRef{}, Fields: map[string]fieldSource{}}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return merged, src
|
||||||
|
}
|
||||||
|
|
||||||
|
// Richest feed first: most filled fields, then longest description, then a stable
|
||||||
|
// tiebreak so repeated syncs always produce the same result.
|
||||||
|
ordered := append([]feedRowInput(nil), rows...)
|
||||||
|
sort.SliceStable(ordered, func(i, j int) bool {
|
||||||
|
a, b := ordered[i], ordered[j]
|
||||||
|
if ca, cb := rowFilledCount(a.Mapped), rowFilledCount(b.Mapped); ca != cb {
|
||||||
|
return ca > cb
|
||||||
|
}
|
||||||
|
if da, db := descriptionLen(a.Mapped), descriptionLen(b.Mapped); da != db {
|
||||||
|
return da > db
|
||||||
|
}
|
||||||
|
return a.FeedID.String() < b.FeedID.String()
|
||||||
|
})
|
||||||
|
ref := func(r feedRowInput) sourceRef {
|
||||||
|
return sourceRef{FeedID: r.FeedID.String(), FeedName: r.FeedName}
|
||||||
|
}
|
||||||
|
src.Primary = ref(ordered[0])
|
||||||
|
|
||||||
|
keySet := map[string]struct{}{}
|
||||||
|
for _, r := range ordered {
|
||||||
|
for k := range r.Mapped {
|
||||||
|
if k != syncChangesMappedKey {
|
||||||
|
keySet[k] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(keySet))
|
||||||
|
for k := range keySet {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
|
||||||
|
contributed := map[string]bool{}
|
||||||
|
for _, key := range keys {
|
||||||
|
lk := strings.ToLower(key)
|
||||||
|
var holders []feedRowInput
|
||||||
|
for _, r := range ordered {
|
||||||
|
if filledValue(r.Mapped[key]) {
|
||||||
|
holders = append(holders, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(holders) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
winner := holders[0]
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case lk == "specifications":
|
||||||
|
specs := map[string]any{}
|
||||||
|
keyFeed := map[string]string{}
|
||||||
|
var contributors []sourceRef
|
||||||
|
seenFeed := map[string]bool{}
|
||||||
|
var rawBlob feedRowInput
|
||||||
|
var haveBlob bool
|
||||||
|
for _, r := range holders {
|
||||||
|
m, ok := asStringMap(r.Mapped[key])
|
||||||
|
if !ok {
|
||||||
|
if !haveBlob {
|
||||||
|
rawBlob, haveBlob = r, true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for sk, sv := range m {
|
||||||
|
if !filledValue(sv) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, exists := specs[sk]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
specs[sk] = sv
|
||||||
|
keyFeed[sk] = r.FeedName
|
||||||
|
if !seenFeed[r.FeedID.String()] {
|
||||||
|
seenFeed[r.FeedID.String()] = true
|
||||||
|
contributors = append(contributors, ref(r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(specs) == 0 && haveBlob {
|
||||||
|
merged[key] = rawBlob.Mapped[key]
|
||||||
|
src.Fields[key] = fieldSource{FeedID: ref(rawBlob).FeedID, FeedName: rawBlob.FeedName}
|
||||||
|
contributed[rawBlob.FeedID.String()] = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
merged[key] = specs
|
||||||
|
first := contributors[0]
|
||||||
|
fs := fieldSource{FeedID: first.FeedID, FeedName: first.FeedName, Keys: keyFeed}
|
||||||
|
if len(contributors) > 1 {
|
||||||
|
fs.MergedBy = contributors
|
||||||
|
}
|
||||||
|
src.Fields[key] = fs
|
||||||
|
for _, c := range contributors {
|
||||||
|
contributed[c.FeedID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
case listFieldKeys[lk] && len(holders) == 1:
|
||||||
|
// Only one feed has the list: keep it byte-for-byte so single-feed
|
||||||
|
// products are never rewritten (and reprocessed) by the merge.
|
||||||
|
merged[key] = winner.Mapped[key]
|
||||||
|
src.Fields[key] = fieldSource{FeedID: ref(winner).FeedID, FeedName: winner.FeedName}
|
||||||
|
contributed[winner.FeedID.String()] = true
|
||||||
|
|
||||||
|
case listFieldKeys[lk]:
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var list []string
|
||||||
|
var contributors []sourceRef
|
||||||
|
seenFeed := map[string]bool{}
|
||||||
|
for _, r := range holders {
|
||||||
|
for _, item := range splitList(r.Mapped[key]) {
|
||||||
|
norm := strings.ToLower(item)
|
||||||
|
if seen[norm] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[norm] = true
|
||||||
|
list = append(list, item)
|
||||||
|
if !seenFeed[r.FeedID.String()] {
|
||||||
|
seenFeed[r.FeedID.String()] = true
|
||||||
|
contributors = append(contributors, ref(r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(list) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
merged[key] = strings.Join(list, ",")
|
||||||
|
fs := fieldSource{FeedID: contributors[0].FeedID, FeedName: contributors[0].FeedName}
|
||||||
|
if len(contributors) > 1 {
|
||||||
|
fs.MergedBy = contributors
|
||||||
|
}
|
||||||
|
src.Fields[key] = fs
|
||||||
|
for _, c := range contributors {
|
||||||
|
contributed[c.FeedID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
if descriptionFieldKeys[lk] {
|
||||||
|
// Most text wins; the richest-feed order breaks ties.
|
||||||
|
for _, r := range holders[1:] {
|
||||||
|
if plainTextLen(r.Mapped[key]) > plainTextLen(winner.Mapped[key]) {
|
||||||
|
winner = r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
merged[key] = winner.Mapped[key]
|
||||||
|
fs := fieldSource{FeedID: ref(winner).FeedID, FeedName: winner.FeedName}
|
||||||
|
winNorm := normalizedValue(winner.Mapped[key])
|
||||||
|
for _, r := range holders {
|
||||||
|
if r.FeedID == winner.FeedID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if normalizedValue(r.Mapped[key]) != winNorm {
|
||||||
|
fs.Conflict = true
|
||||||
|
fs.Also = append(fs.Also, ref(r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
src.Fields[key] = fs
|
||||||
|
contributed[winner.FeedID.String()] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range ordered {
|
||||||
|
if contributed[r.FeedID.String()] || len(ordered) == 1 {
|
||||||
|
src.Feeds = append(src.Feeds, ref(r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return merged, src
|
||||||
|
}
|
||||||
|
|
||||||
|
// feedIDsOf lists the feeds that have a row for the EAN, for raw_products.feed_ids.
|
||||||
|
func feedIDsOf(rows []feedRowInput) []string {
|
||||||
|
ids := make([]string, 0, len(rows))
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, r := range rows {
|
||||||
|
id := r.FeedID.String()
|
||||||
|
if !seen[id] {
|
||||||
|
seen[id] = true
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(ids)
|
||||||
|
return ids
|
||||||
|
}
|
||||||
@@ -0,0 +1,404 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type mergeFixture struct {
|
||||||
|
ctx context.Context
|
||||||
|
pg *pgxpool.Pool
|
||||||
|
svc *Service
|
||||||
|
companyID uuid.UUID
|
||||||
|
dir string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newMergeFixture(t *testing.T) *mergeFixture {
|
||||||
|
t.Helper()
|
||||||
|
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("DATABASE_URL not set")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||||
|
t.Cleanup(cancel)
|
||||||
|
pg, err := pgxpool.New(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(pg.Close)
|
||||||
|
companyID := uuid.New()
|
||||||
|
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, companyID, "merge-"+companyID.String()[:8]); err != nil {
|
||||||
|
t.Fatalf("seed company: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _, _ = pg.Exec(context.Background(), `DELETE FROM companies WHERE id = $1`, companyID) })
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.MkdirAll(filepath.Join(dir, companyID.String()), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return &mergeFixture{ctx: ctx, pg: pg, svc: &Service{Pool: pg, UploadDir: dir}, companyID: companyID, dir: dir}
|
||||||
|
}
|
||||||
|
|
||||||
|
// addFeed creates a CSV feed whose columns are mapped to the given canonical fields.
|
||||||
|
func (f *mergeFixture) addFeed(t *testing.T, name string, columns map[string]string) uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
rel := f.companyID.String() + "/" + strings.ReplaceAll(strings.ToLower(name), " ", "-") + ".csv"
|
||||||
|
opts, _ := json.Marshal(map[string]any{"source_path": rel})
|
||||||
|
var feedID uuid.UUID
|
||||||
|
if err := f.pg.QueryRow(f.ctx, `
|
||||||
|
INSERT INTO input_feeds (company_id, name, url, feed_type, status, sync_interval_minutes, options)
|
||||||
|
VALUES ($1, $2, '', 'csv', 'active', 60, $3::jsonb) RETURNING id`, f.companyID, name, string(opts)).Scan(&feedID); err != nil {
|
||||||
|
t.Fatalf("seed feed: %v", err)
|
||||||
|
}
|
||||||
|
var mappings []map[string]string
|
||||||
|
for src, tgt := range columns {
|
||||||
|
mappings = append(mappings, map[string]string{"source": src, "target": tgt})
|
||||||
|
}
|
||||||
|
mb, _ := json.Marshal(mappings)
|
||||||
|
if _, err := f.pg.Exec(f.ctx, `INSERT INTO feed_mappings (feed_id, company_id, mappings) VALUES ($1, $2, $3::jsonb)`,
|
||||||
|
feedID, f.companyID, string(mb)); err != nil {
|
||||||
|
t.Fatalf("seed mapping: %v", err)
|
||||||
|
}
|
||||||
|
return feedID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *mergeFixture) writeCSV(t *testing.T, name string, lines ...string) {
|
||||||
|
t.Helper()
|
||||||
|
p := filepath.Join(f.dir, f.companyID.String(), strings.ReplaceAll(strings.ToLower(name), " ", "-")+".csv")
|
||||||
|
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type rawState struct {
|
||||||
|
Mapped map[string]any
|
||||||
|
FeedID uuid.UUID
|
||||||
|
FeedIDs []string
|
||||||
|
Sources feedFieldSources
|
||||||
|
Status string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *mergeFixture) raw(t *testing.T, gtin string) rawState {
|
||||||
|
t.Helper()
|
||||||
|
var st rawState
|
||||||
|
var mapped, ids, src []byte
|
||||||
|
if err := f.pg.QueryRow(f.ctx, `
|
||||||
|
SELECT mapped_data, feed_id, COALESCE(feed_ids, '[]'::jsonb), COALESCE(feed_field_sources, '{}'::jsonb), processing_status
|
||||||
|
FROM raw_products WHERE company_id = $1 AND gtin = $2`, f.companyID, gtin).Scan(&mapped, &st.FeedID, &ids, &src, &st.Status); err != nil {
|
||||||
|
t.Fatalf("load raw %s: %v", gtin, err)
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(mapped, &st.Mapped)
|
||||||
|
_ = json.Unmarshal(ids, &st.FeedIDs)
|
||||||
|
_ = json.Unmarshal(src, &st.Sources)
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *mergeFixture) sync(t *testing.T, feedID uuid.UUID) time.Duration {
|
||||||
|
t.Helper()
|
||||||
|
start := time.Now()
|
||||||
|
if _, err := f.svc.Sync(f.ctx, f.companyID, feedID); err != nil {
|
||||||
|
t.Fatalf("sync: %v", err)
|
||||||
|
}
|
||||||
|
return time.Since(start)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncMergesSameEANAcrossFeeds(t *testing.T) {
|
||||||
|
f := newMergeFixture(t)
|
||||||
|
const ean = "4548736180307"
|
||||||
|
longDesc := strings.Repeat("Sony Bravia 4K z Google TV in HDR10 z 20 W zvokom. ", 12)
|
||||||
|
|
||||||
|
vendorA := f.addFeed(t, "Vendor A", map[string]string{
|
||||||
|
"EAN": "gtin", "Name": "name", "Brand": "brand", "Desc": "description", "Price": "price",
|
||||||
|
})
|
||||||
|
vendorB := f.addFeed(t, "Vendor B", map[string]string{
|
||||||
|
"EAN": "gtin", "Title": "name", "Description": "description", "Image": "main_image",
|
||||||
|
"More": "more_images", "EPREL": "eprel_id",
|
||||||
|
})
|
||||||
|
|
||||||
|
// 1) Vendor A alone: thin data.
|
||||||
|
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price", ean+",Sony TV 65,Sony,Kratek opis.,560")
|
||||||
|
f.sync(t, vendorA)
|
||||||
|
st := f.raw(t, ean)
|
||||||
|
if st.FeedID != vendorA || st.Mapped["description"] != "Kratek opis." {
|
||||||
|
t.Fatalf("after A: feed=%v mapped=%v", st.FeedID, st.Mapped)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pretend the product was already processed, to prove a content change resets it.
|
||||||
|
if _, err := f.pg.Exec(f.ctx, `UPDATE raw_products SET is_processed = true, processing_status = 'processed' WHERE company_id = $1 AND gtin = $2`, f.companyID, ean); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := f.pg.Exec(f.ctx, `INSERT INTO processed_products (company_id, raw_product_id, product_id, name) SELECT company_id, id, gtin, 'x' FROM raw_products WHERE company_id = $1 AND gtin = $2`, f.companyID, ean); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Vendor B brings the description, images and EPREL id.
|
||||||
|
f.writeCSV(t, "Vendor B",
|
||||||
|
"EAN,Title,Description,Image,More,EPREL",
|
||||||
|
ean+",TV SONY K65,"+longDesc+",https://img/main.jpg,https://img/1.jpg;https://img/2.jpg,2651553")
|
||||||
|
f.sync(t, vendorB)
|
||||||
|
st = f.raw(t, ean)
|
||||||
|
|
||||||
|
if got := st.Mapped["description"]; !strings.Contains(fmt.Sprint(got), "Google TV") {
|
||||||
|
t.Fatalf("richest description did not win: %v", got)
|
||||||
|
}
|
||||||
|
for k, want := range map[string]string{
|
||||||
|
"brand": "Sony", "price": "560", "main_image": "https://img/main.jpg", "eprel_id": "2651553",
|
||||||
|
"name": "TV SONY K65", // Vendor B has more filled fields (5 vs 4), so it wins the conflicting name
|
||||||
|
} {
|
||||||
|
if st.Mapped[k] != want {
|
||||||
|
t.Errorf("merged %s = %v, want %q", k, st.Mapped[k], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(st.FeedIDs) != 2 {
|
||||||
|
t.Errorf("feed_ids = %v, want both feeds", st.FeedIDs)
|
||||||
|
}
|
||||||
|
if st.FeedID != vendorB {
|
||||||
|
t.Errorf("owner feed = %v, want richest feed B", st.FeedID)
|
||||||
|
}
|
||||||
|
if st.Sources.Primary.FeedName != "Vendor B" || st.Sources.Fields["name"].FeedName != "Vendor B" ||
|
||||||
|
len(st.Sources.Fields["name"].Also) != 1 || st.Sources.Fields["name"].Also[0].FeedName != "Vendor A" {
|
||||||
|
t.Errorf("name conflict not recorded: primary=%+v name=%+v", st.Sources.Primary, st.Sources.Fields["name"])
|
||||||
|
}
|
||||||
|
if st.Sources.Fields["description"].FeedName != "Vendor B" || !st.Sources.Fields["description"].Conflict {
|
||||||
|
t.Errorf("description source = %+v", st.Sources.Fields["description"])
|
||||||
|
}
|
||||||
|
if st.Sources.Fields["eprel_id"].FeedName != "Vendor B" || st.Sources.Fields["brand"].FeedName != "Vendor A" {
|
||||||
|
t.Errorf("sources = %+v", st.Sources.Fields)
|
||||||
|
}
|
||||||
|
if n := f.count(t, `SELECT count(*) FROM raw_product_feed_rows WHERE company_id = $1 AND gtin = $2`, ean); n != 2 {
|
||||||
|
t.Errorf("feed rows = %d, want 2", n)
|
||||||
|
}
|
||||||
|
if st.Status != "unprocessed" {
|
||||||
|
t.Errorf("changed content must reset processing, got %q", st.Status)
|
||||||
|
}
|
||||||
|
if n := f.count(t, `SELECT count(*) FROM processed_products WHERE company_id = $1`, ""); n != 0 {
|
||||||
|
t.Errorf("stale processed_products row survived: %d", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) The regression the old code had: Vendor A re-syncs with a new price and must
|
||||||
|
// NOT wipe what Vendor B contributed.
|
||||||
|
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price", ean+",Sony TV 65,Sony,Kratek opis.,499")
|
||||||
|
f.sync(t, vendorA)
|
||||||
|
st = f.raw(t, ean)
|
||||||
|
if st.Mapped["price"] != "499" {
|
||||||
|
t.Errorf("price update from A lost: %v", st.Mapped["price"])
|
||||||
|
}
|
||||||
|
if st.Mapped["eprel_id"] != "2651553" || st.Mapped["main_image"] != "https://img/main.jpg" ||
|
||||||
|
!strings.Contains(fmt.Sprint(st.Mapped["description"]), "Google TV") {
|
||||||
|
t.Errorf("Vendor B data lost after Vendor A re-sync: %v", st.Mapped)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4) Re-syncing unchanged data is stable (no flip-flopping between feeds).
|
||||||
|
f.writeCSV(t, "Vendor B",
|
||||||
|
"EAN,Title,Description,Image,More,EPREL",
|
||||||
|
ean+",TV SONY K65,"+longDesc+",https://img/main.jpg,https://img/1.jpg;https://img/2.jpg,2651553 ")
|
||||||
|
f.sync(t, vendorB)
|
||||||
|
again := f.raw(t, ean)
|
||||||
|
if again.FeedID != vendorB || fmt.Sprint(again.Mapped) != fmt.Sprint(st.Mapped) {
|
||||||
|
t.Errorf("unchanged re-sync altered product:\nbefore=%v\nafter=%v", st.Mapped, again.Mapped)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A product only one feed carries is untouched by the merge.
|
||||||
|
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price",
|
||||||
|
ean+",Sony TV 65,Sony,Kratek opis.,499", "9999999999994,Solo,Acme,Samo A,1")
|
||||||
|
f.sync(t, vendorA)
|
||||||
|
solo := f.raw(t, "9999999999994")
|
||||||
|
if solo.Mapped["name"] != "Solo" || len(solo.FeedIDs) != 1 || solo.FeedID != vendorA {
|
||||||
|
t.Errorf("single-feed product wrong: %+v", solo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *mergeFixture) count(t *testing.T, q, gtin string) int {
|
||||||
|
t.Helper()
|
||||||
|
var n int
|
||||||
|
var err error
|
||||||
|
if gtin == "" {
|
||||||
|
err = f.pg.QueryRow(f.ctx, q, f.companyID).Scan(&n)
|
||||||
|
} else {
|
||||||
|
err = f.pg.QueryRow(f.ctx, q, f.companyID, gtin).Scan(&n)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSyncMergeTiming measures how long a resync takes with merging. Run with
|
||||||
|
// MERGE_TIMING_N=20000 for a bigger catalog; defaults to 5000 EANs per feed.
|
||||||
|
func TestSyncMergeTiming(t *testing.T) {
|
||||||
|
if os.Getenv("MERGE_TIMING") == "" {
|
||||||
|
t.Skip("set MERGE_TIMING=1 to run")
|
||||||
|
}
|
||||||
|
f := newMergeFixture(t)
|
||||||
|
n := 5000
|
||||||
|
if v, err := strconv.Atoi(os.Getenv("MERGE_TIMING_N")); err == nil && v > 0 {
|
||||||
|
n = v
|
||||||
|
}
|
||||||
|
a := f.addFeed(t, "Vendor A", map[string]string{"EAN": "gtin", "Name": "name", "Brand": "brand", "Desc": "description"})
|
||||||
|
b := f.addFeed(t, "Vendor B", map[string]string{"EAN": "gtin", "Title": "name", "Description": "description", "Image": "main_image", "EPREL": "eprel_id"})
|
||||||
|
|
||||||
|
var la, lb []string
|
||||||
|
la = append(la, "EAN,Name,Brand,Desc")
|
||||||
|
lb = append(lb, "EAN,Title,Description,Image,EPREL")
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
ean := fmt.Sprintf("%013d", 4000000000000+i)
|
||||||
|
la = append(la, fmt.Sprintf("%s,Product %d,Brand,Short %d", ean, i, i))
|
||||||
|
if i%2 == 0 { // half of the catalog is carried by both vendors
|
||||||
|
lb = append(lb, fmt.Sprintf("%s,Product %d full,%s,https://img/%d.jpg,%d", ean, i,
|
||||||
|
strings.Repeat("Long enriched description. ", 20), i, 1000000+i))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.writeCSV(t, "Vendor A", la...)
|
||||||
|
f.writeCSV(t, "Vendor B", lb...)
|
||||||
|
|
||||||
|
d1 := f.sync(t, a)
|
||||||
|
d2 := f.sync(t, b)
|
||||||
|
// Change every price/name so the resync is a full content update, not a hash skip.
|
||||||
|
for i := range la[1:] {
|
||||||
|
la[i+1] += "!"
|
||||||
|
}
|
||||||
|
f.writeCSV(t, "Vendor A", la...)
|
||||||
|
d3 := f.sync(t, a)
|
||||||
|
d4 := f.sync(t, a) // identical file: content-hash skip
|
||||||
|
t.Logf("EANs per feed: A=%d B=%d (overlap=%d)", n, len(lb)-1, len(lb)-1)
|
||||||
|
t.Logf("first sync A: %v (%.0f rows/s)", d1, float64(n)/d1.Seconds())
|
||||||
|
t.Logf("first sync B (merge): %v (%.0f rows/s)", d2, float64(len(lb)-1)/d2.Seconds())
|
||||||
|
t.Logf("changed resync A: %v (%.0f rows/s)", d3, float64(n)/d3.Seconds())
|
||||||
|
t.Logf("unchanged resync A: %v", d4)
|
||||||
|
merged := f.count(t, `SELECT count(*) FROM raw_products WHERE company_id = $1 AND jsonb_array_length(COALESCE(feed_ids,'[]'::jsonb)) = 2`, "")
|
||||||
|
if merged != len(lb)-1 {
|
||||||
|
t.Fatalf("merged products = %d, want %d", merged, len(lb)-1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *mergeFixture) setFeed(t *testing.T, id uuid.UUID, sql string, args ...any) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := f.pg.Exec(f.ctx, `UPDATE input_feeds SET `+sql+` WHERE id = $1`, append([]any{id}, args...)...); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *mergeFixture) jobsFor(t *testing.T, id uuid.UUID) int {
|
||||||
|
t.Helper()
|
||||||
|
var n int
|
||||||
|
if err := f.pg.QueryRow(f.ctx, `SELECT count(*) FROM feed_sync_jobs WHERE feed_id = $1`, id).Scan(&n); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// Feeds must sync by themselves once their interval has elapsed.
|
||||||
|
func TestEnqueueDueFeedsSchedulesOnlyDueFeeds(t *testing.T) {
|
||||||
|
f := newMergeFixture(t)
|
||||||
|
cols := map[string]string{"EAN": "gtin", "Name": "title"}
|
||||||
|
mk := func(name string) uuid.UUID { return f.addFeed(t, name, cols) }
|
||||||
|
|
||||||
|
due := mk("due") // synced 2h ago, interval 60
|
||||||
|
never := mk("never") // never synced
|
||||||
|
fresh := mk("fresh") // synced just now
|
||||||
|
pending := mk("pending") // already has a pending job
|
||||||
|
failed := mk("failed") // failed recently
|
||||||
|
paused := mk("paused") // not active
|
||||||
|
noInterval := mk("no interval") // interval 0 = manual only
|
||||||
|
noMapping := mk("no mapping") // never mapped
|
||||||
|
if _, err := f.pg.Exec(f.ctx, `DELETE FROM feed_mappings WHERE feed_id = $1`, noMapping); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
f.setFeed(t, due, `last_synced_at = now() - interval '2 hours'`)
|
||||||
|
f.setFeed(t, fresh, `last_synced_at = now()`)
|
||||||
|
f.setFeed(t, pending, `last_synced_at = now() - interval '2 hours'`)
|
||||||
|
f.setFeed(t, failed, `last_synced_at = now() - interval '2 hours'`)
|
||||||
|
f.setFeed(t, paused, `last_synced_at = now() - interval '2 hours', status = 'paused'`)
|
||||||
|
f.setFeed(t, noInterval, `last_synced_at = now() - interval '2 hours', sync_interval_minutes = 0`)
|
||||||
|
if _, err := f.pg.Exec(f.ctx, `INSERT INTO feed_sync_jobs (feed_id, company_id, status) VALUES ($1, $2, 'pending'), ($3, $2, 'failed')`,
|
||||||
|
pending, f.companyID, failed); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := f.svc.EnqueueDueFeeds(f.ctx, 50, f.companyID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n != 2 {
|
||||||
|
t.Errorf("queued %d feeds, want 2 (due + never)", n)
|
||||||
|
}
|
||||||
|
for name, id := range map[string]uuid.UUID{"due": due, "never": never} {
|
||||||
|
if f.jobsFor(t, id) != 1 {
|
||||||
|
t.Errorf("%s feed was not queued", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, id := range map[string]uuid.UUID{"fresh": fresh, "paused": paused, "no interval": noInterval, "no mapping": noMapping} {
|
||||||
|
if f.jobsFor(t, id) != 0 {
|
||||||
|
t.Errorf("%s feed must not be queued", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if f.jobsFor(t, pending) != 1 || f.jobsFor(t, failed) != 1 {
|
||||||
|
t.Error("feeds with a pending / recently failed job must not get another")
|
||||||
|
}
|
||||||
|
|
||||||
|
// A second scan does not stack duplicate jobs.
|
||||||
|
if n, _ := f.svc.EnqueueDueFeeds(f.ctx, 50, f.companyID); n != 0 {
|
||||||
|
t.Errorf("second scan queued %d, want 0", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Products synced BEFORE merging existed (single overwritten row, no per-feed rows, an
|
||||||
|
// "unchanged" file) must merge on the next scheduled sync without any file change.
|
||||||
|
func TestAlreadySyncedProductsMergeOnNextSync(t *testing.T) {
|
||||||
|
f := newMergeFixture(t)
|
||||||
|
const ean = "4548736180307"
|
||||||
|
longDesc := strings.Repeat("Sony Bravia 4K z Google TV in HDR10 z 20 W zvokom. ", 12)
|
||||||
|
a := f.addFeed(t, "Vendor A", map[string]string{"EAN": "gtin", "Name": "title", "Brand": "brand", "Desc": "description", "Price": "purchaseprice"})
|
||||||
|
b := f.addFeed(t, "Vendor B", map[string]string{"EAN": "gtin", "Title": "title", "Description": "description", "Image": "main_image", "EPREL": "eprel_id"})
|
||||||
|
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price", ean+",Sony TV 65,Sony,Kratek opis.,560")
|
||||||
|
f.writeCSV(t, "Vendor B", "EAN,Title,Description,Image,EPREL", ean+",TV SONY K65,"+longDesc+",https://img/main.jpg,2651553")
|
||||||
|
f.sync(t, a)
|
||||||
|
f.sync(t, b)
|
||||||
|
|
||||||
|
// Recreate the pre-merge world: Vendor B overwrote everything, nothing else stored,
|
||||||
|
// and both feeds remember hashes from the old algorithm.
|
||||||
|
if _, err := f.pg.Exec(f.ctx, `DELETE FROM raw_product_feed_rows WHERE company_id = $1`, f.companyID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := f.pg.Exec(f.ctx, `
|
||||||
|
UPDATE raw_products SET feed_id = $2, feed_ids = NULL, feed_field_sources = NULL,
|
||||||
|
mapped_data = jsonb_build_object('gtin', gtin, 'title', 'TV SONY K65', 'description', $3::text,
|
||||||
|
'main_image', 'https://img/main.jpg', 'eprel_id', '2651553')
|
||||||
|
WHERE company_id = $1`, f.companyID, b, longDesc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
f.setFeed(t, a, `options = options || '{"last_mapping_hash":"legacy"}'::jsonb`)
|
||||||
|
f.setFeed(t, b, `options = options || '{"last_mapping_hash":"legacy"}'::jsonb`)
|
||||||
|
if st := f.raw(t, ean); st.Mapped["brand"] != nil {
|
||||||
|
t.Fatalf("test setup wrong: %v", st.Mapped)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scheduled syncs: neither file changed.
|
||||||
|
f.sync(t, a)
|
||||||
|
f.sync(t, b)
|
||||||
|
st := f.raw(t, ean)
|
||||||
|
if st.Mapped["brand"] != "Sony" || st.Mapped["purchaseprice"] != "560" {
|
||||||
|
t.Fatalf("Vendor A data not merged into the existing product: %v", st.Mapped)
|
||||||
|
}
|
||||||
|
if st.Mapped["eprel_id"] != "2651553" || !strings.Contains(fmt.Sprint(st.Mapped["description"]), "Google TV") {
|
||||||
|
t.Errorf("Vendor B data lost: %v", st.Mapped)
|
||||||
|
}
|
||||||
|
if len(st.FeedIDs) != 2 || st.Sources.Fields["brand"].FeedName != "Vendor A" || st.Sources.Fields["eprel_id"].FeedName != "Vendor B" {
|
||||||
|
t.Errorf("sources not recorded: ids=%v sources=%+v", st.FeedIDs, st.Sources.Fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
// After that one-time re-parse, an unchanged file is skipped again (cheap).
|
||||||
|
var hash string
|
||||||
|
if err := f.pg.QueryRow(f.ctx, `SELECT options->>'last_mapping_hash' FROM input_feeds WHERE id = $1`, a).Scan(&hash); err != nil || hash == "legacy" || hash == "" {
|
||||||
|
t.Errorf("mapping hash not refreshed: %q %v", hash, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
const upsertFeedRowsSQL = `
|
||||||
|
INSERT INTO raw_product_feed_rows (company_id, gtin, feed_id, raw_data, mapped_data, content_hash)
|
||||||
|
SELECT $1, v.gtin, $2, v.raw_data::jsonb, v.mapped_data::jsonb, v.content_hash
|
||||||
|
FROM unnest($3::text[], $4::text[], $5::text[], $6::text[]) AS v(gtin, raw_data, mapped_data, content_hash)
|
||||||
|
ON CONFLICT (company_id, gtin, feed_id) DO UPDATE SET
|
||||||
|
raw_data = EXCLUDED.raw_data,
|
||||||
|
mapped_data = EXCLUDED.mapped_data,
|
||||||
|
content_hash = EXCLUDED.content_hash,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE raw_product_feed_rows.content_hash IS DISTINCT FROM EXCLUDED.content_hash`
|
||||||
|
|
||||||
|
// mergeChunkAcrossFeeds stores this feed's row for every EAN in the chunk, loads the
|
||||||
|
// rows other feeds hold for the same EANs, and rewrites each pending product's
|
||||||
|
// MappedData with the merge of all of them. It also fills the field-source metadata
|
||||||
|
// that upsertChunk writes to raw_products. A product only this feed carries is left
|
||||||
|
// exactly as the feed produced it.
|
||||||
|
func (s *Service) mergeChunkAcrossFeeds(ctx context.Context, companyID, feedID uuid.UUID, chunk []pendingProduct) error {
|
||||||
|
if len(chunk) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
gtins := make([]string, len(chunk))
|
||||||
|
rawCol := make([]string, len(chunk))
|
||||||
|
mappedCol := make([]string, len(chunk))
|
||||||
|
hashCol := make([]string, len(chunk))
|
||||||
|
for i, p := range chunk {
|
||||||
|
gtins[i] = p.GTIN
|
||||||
|
rb, err := json.Marshal(p.RawData)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
mb, err := json.Marshal(stripSyncChanges(p.MappedData))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rawCol[i], mappedCol[i], hashCol[i] = string(rb), string(mb), p.ContentHash
|
||||||
|
}
|
||||||
|
if _, err := s.Pool.Exec(ctx, upsertFeedRowsSQL, companyID, feedID, gtins, rawCol, mappedCol, hashCol); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rows other feeds hold for these EANs.
|
||||||
|
rows, err := s.Pool.Query(ctx, `
|
||||||
|
SELECT r.gtin, r.feed_id, COALESCE(f.name, ''), r.mapped_data
|
||||||
|
FROM raw_product_feed_rows r
|
||||||
|
JOIN input_feeds f ON f.id = r.feed_id AND f.company_id = r.company_id
|
||||||
|
WHERE r.company_id = $1 AND r.gtin = ANY($2::text[]) AND r.feed_id <> $3`, companyID, gtins, feedID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
others := map[string][]feedRowInput{}
|
||||||
|
for rows.Next() {
|
||||||
|
var gtin, name string
|
||||||
|
var fid uuid.UUID
|
||||||
|
var raw []byte
|
||||||
|
if err := rows.Scan(>in, &fid, &name, &raw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var mapped map[string]any
|
||||||
|
if err := json.Unmarshal(raw, &mapped); err != nil || mapped == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
others[gtin] = append(others[gtin], feedRowInput{FeedID: fid, FeedName: name, Mapped: mapped})
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var thisFeedName string
|
||||||
|
if err := s.Pool.QueryRow(ctx, `SELECT COALESCE(name, '') FROM input_feeds WHERE id = $1 AND company_id = $2`,
|
||||||
|
feedID, companyID).Scan(&thisFeedName); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range chunk {
|
||||||
|
p := &chunk[i]
|
||||||
|
all := append([]feedRowInput{{FeedID: feedID, FeedName: thisFeedName, Mapped: p.MappedData}}, others[p.GTIN]...)
|
||||||
|
merged, sources := mergeFeedRows(all)
|
||||||
|
if len(all) > 1 {
|
||||||
|
merged["gtin"] = p.GTIN
|
||||||
|
p.MappedData = merged
|
||||||
|
}
|
||||||
|
if sb, err := json.Marshal(sources); err == nil {
|
||||||
|
p.Sources = string(sb)
|
||||||
|
}
|
||||||
|
if ib, err := json.Marshal(feedIDsOf(all)); err == nil {
|
||||||
|
p.FeedIDsJSON = string(ib)
|
||||||
|
}
|
||||||
|
p.PrimaryFeed = sources.Primary.FeedID
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
feedA = uuid.MustParse("00000000-0000-0000-0000-00000000000a")
|
||||||
|
feedB = uuid.MustParse("00000000-0000-0000-0000-00000000000b")
|
||||||
|
feedC = uuid.MustParse("00000000-0000-0000-0000-00000000000c")
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMergeFeedRows_nonConflictingFieldsAreCombined(t *testing.T) {
|
||||||
|
a := feedRowInput{FeedID: feedA, FeedName: "Vendor A", Mapped: map[string]any{
|
||||||
|
"gtin": "4548736180307", "name": "Sony TV 65", "brand": "Sony",
|
||||||
|
}}
|
||||||
|
b := feedRowInput{FeedID: feedB, FeedName: "Vendor B", Mapped: map[string]any{
|
||||||
|
"gtin": "4548736180307", "main_image": "https://img/x.jpg", "eprel_id": "2651553",
|
||||||
|
}}
|
||||||
|
got, src := mergeFeedRows([]feedRowInput{a, b})
|
||||||
|
for k, want := range map[string]string{
|
||||||
|
"name": "Sony TV 65", "brand": "Sony", "main_image": "https://img/x.jpg", "eprel_id": "2651553",
|
||||||
|
} {
|
||||||
|
if got[k] != want {
|
||||||
|
t.Errorf("%s = %v, want %q", k, got[k], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if src.Fields["eprel_id"].FeedName != "Vendor B" || src.Fields["brand"].FeedName != "Vendor A" {
|
||||||
|
t.Errorf("wrong sources: %+v", src.Fields)
|
||||||
|
}
|
||||||
|
if src.Fields["name"].Conflict {
|
||||||
|
t.Error("a field only one feed has must not be a conflict")
|
||||||
|
}
|
||||||
|
if len(src.Feeds) != 2 {
|
||||||
|
t.Errorf("feeds = %v, want both feeds", src.Feeds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_longestDescriptionWins(t *testing.T) {
|
||||||
|
short := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
|
||||||
|
"name": "TV", "brand": "Sony", "stock": "5", "price": "9", "description": "Short.",
|
||||||
|
}}
|
||||||
|
long := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{
|
||||||
|
"name": "TV", "description": "<p>" + strings.Repeat("Ostra 4K slika z Google TV in HDR. ", 20) + "</p>",
|
||||||
|
}}
|
||||||
|
got, src := mergeFeedRows([]feedRowInput{short, long})
|
||||||
|
if !strings.Contains(got["description"].(string), "Google TV") {
|
||||||
|
t.Fatalf("richer description lost: %v", got["description"])
|
||||||
|
}
|
||||||
|
if src.Fields["description"].FeedName != "B" || !src.Fields["description"].Conflict {
|
||||||
|
t.Errorf("description source = %+v", src.Fields["description"])
|
||||||
|
}
|
||||||
|
// Feed A has more fields overall, so it stays primary for ordinary fields.
|
||||||
|
if src.Primary.FeedName != "A" {
|
||||||
|
t.Errorf("primary = %v, want A", src.Primary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_htmlMarkupDoesNotCountAsRichness(t *testing.T) {
|
||||||
|
markup := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
|
||||||
|
"description": "<div><p><span><b>Hi</b></span></p></div>" + strings.Repeat("<br/>", 50),
|
||||||
|
}}
|
||||||
|
text := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{
|
||||||
|
"description": "A genuinely longer plain sentence about the product.",
|
||||||
|
}}
|
||||||
|
got, _ := mergeFeedRows([]feedRowInput{markup, text})
|
||||||
|
if got["description"] != text.Mapped["description"] {
|
||||||
|
t.Errorf("markup-heavy but text-poor description won: %v", got["description"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_conflictRichestFeedWinsAndAlsoListed(t *testing.T) {
|
||||||
|
rich := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
|
||||||
|
"name": "Sony Bravia 65", "brand": "Sony", "color": "bela",
|
||||||
|
}}
|
||||||
|
poor := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{"name": "TV SONY"}}
|
||||||
|
got, src := mergeFeedRows([]feedRowInput{poor, rich}) // input order must not matter
|
||||||
|
if got["name"] != "Sony Bravia 65" {
|
||||||
|
t.Fatalf("name = %v", got["name"])
|
||||||
|
}
|
||||||
|
fs := src.Fields["name"]
|
||||||
|
if !fs.Conflict || len(fs.Also) != 1 || fs.Also[0].FeedName != "B" {
|
||||||
|
t.Errorf("name source = %+v", fs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_sameValueDifferentCaseIsNotConflict(t *testing.T) {
|
||||||
|
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{"brand": "Sony", "x": "1"}}
|
||||||
|
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{"brand": " SONY "}}
|
||||||
|
_, src := mergeFeedRows([]feedRowInput{a, b})
|
||||||
|
if src.Fields["brand"].Conflict {
|
||||||
|
t.Errorf("equal values flagged as conflict: %+v", src.Fields["brand"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_emptyValuesNeverWin(t *testing.T) {
|
||||||
|
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{"brand": " ", "name": "TV", "x": "1", "y": "2"}}
|
||||||
|
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{"brand": "Sony"}}
|
||||||
|
got, src := mergeFeedRows([]feedRowInput{a, b})
|
||||||
|
if got["brand"] != "Sony" || src.Fields["brand"].FeedName != "B" {
|
||||||
|
t.Errorf("brand = %v from %+v", got["brand"], src.Fields["brand"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_imagesAreUnioned(t *testing.T) {
|
||||||
|
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
|
||||||
|
"more_images": "https://i/1.jpg,https://i/2.jpg", "name": "x", "brand": "y",
|
||||||
|
}}
|
||||||
|
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{
|
||||||
|
"more_images": "https://i/2.jpg\nhttps://i/3.jpg",
|
||||||
|
}}
|
||||||
|
got, src := mergeFeedRows([]feedRowInput{a, b})
|
||||||
|
if got["more_images"] != "https://i/1.jpg,https://i/2.jpg,https://i/3.jpg" {
|
||||||
|
t.Errorf("more_images = %v", got["more_images"])
|
||||||
|
}
|
||||||
|
if len(src.Fields["more_images"].MergedBy) != 2 {
|
||||||
|
t.Errorf("merged_from = %+v", src.Fields["more_images"].MergedBy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_singleFeedListKeptVerbatim(t *testing.T) {
|
||||||
|
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
|
||||||
|
"more_images": "https://i/1.jpg https://i/2.jpg",
|
||||||
|
}}
|
||||||
|
got, _ := mergeFeedRows([]feedRowInput{a})
|
||||||
|
if got["more_images"] != "https://i/1.jpg https://i/2.jpg" {
|
||||||
|
t.Errorf("single-feed list was rewritten: %q", got["more_images"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_specificationsUnionPrimaryWinsOnKeyClash(t *testing.T) {
|
||||||
|
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
|
||||||
|
"name": "TV", "brand": "Sony",
|
||||||
|
"specifications": map[string]string{"diagonal": "65\"", "color": "bela"},
|
||||||
|
}}
|
||||||
|
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{
|
||||||
|
"specifications": map[string]any{"diagonal": "164 cm", "hdmi": "4", "empty": ""},
|
||||||
|
}}
|
||||||
|
got, src := mergeFeedRows([]feedRowInput{a, b})
|
||||||
|
specs := got["specifications"].(map[string]any)
|
||||||
|
if specs["diagonal"] != "65\"" || specs["hdmi"] != "4" || specs["color"] != "bela" {
|
||||||
|
t.Errorf("specs = %v", specs)
|
||||||
|
}
|
||||||
|
if _, ok := specs["empty"]; ok {
|
||||||
|
t.Error("empty spec value must be dropped")
|
||||||
|
}
|
||||||
|
fs := src.Fields["specifications"]
|
||||||
|
if fs.Keys["hdmi"] != "B" || fs.Keys["diagonal"] != "A" || len(fs.MergedBy) != 2 {
|
||||||
|
t.Errorf("spec sources = %+v", fs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_deterministicRegardlessOfOrder(t *testing.T) {
|
||||||
|
mk := func(id uuid.UUID, n string) feedRowInput {
|
||||||
|
return feedRowInput{FeedID: id, FeedName: n, Mapped: map[string]any{"name": n + " name", "brand": n}}
|
||||||
|
}
|
||||||
|
rows := []feedRowInput{mk(feedC, "C"), mk(feedA, "A"), mk(feedB, "B")}
|
||||||
|
first, _ := mergeFeedRows(rows)
|
||||||
|
rev := []feedRowInput{rows[2], rows[1], rows[0]}
|
||||||
|
second, _ := mergeFeedRows(rev)
|
||||||
|
if first["name"] != second["name"] || first["brand"] != second["brand"] {
|
||||||
|
t.Errorf("order-dependent merge: %v vs %v", first, second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_doesNotMutateInputs(t *testing.T) {
|
||||||
|
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{"name": "TV", "_sync_changes": []any{"new"}}}
|
||||||
|
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{"brand": "Sony"}}
|
||||||
|
merged, _ := mergeFeedRows([]feedRowInput{a, b})
|
||||||
|
if _, ok := merged[syncChangesMappedKey]; ok {
|
||||||
|
t.Error("_sync_changes must not be merged")
|
||||||
|
}
|
||||||
|
if _, ok := a.Mapped["brand"]; ok {
|
||||||
|
t.Error("input row mutated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeFeedRows_empty(t *testing.T) {
|
||||||
|
got, src := mergeFeedRows(nil)
|
||||||
|
if len(got) != 0 || len(src.Fields) != 0 {
|
||||||
|
t.Errorf("got %v %v", got, src)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,18 +31,29 @@ type feedRow map[string]string
|
|||||||
|
|
||||||
func detectFeedFormat(feedType, contentType, urlHint string, sample []byte) string {
|
func detectFeedFormat(feedType, contentType, urlHint string, sample []byte) string {
|
||||||
ft := strings.ToLower(strings.TrimSpace(feedType))
|
ft := strings.ToLower(strings.TrimSpace(feedType))
|
||||||
if ft == "csv" || ft == "xml" {
|
// Binary workbooks win over the declared type: local uploads default to text/csv.
|
||||||
|
if ft == "excel" || isExcelSample(sample) {
|
||||||
|
return "excel"
|
||||||
|
}
|
||||||
|
if ft == "csv" || ft == "xml" || ft == "json" {
|
||||||
return ft
|
return ft
|
||||||
}
|
}
|
||||||
ct := strings.ToLower(contentType)
|
ct := strings.ToLower(contentType)
|
||||||
u := strings.ToLower(urlHint)
|
u := strings.ToLower(urlHint)
|
||||||
switch {
|
switch {
|
||||||
|
case isExcelContentType(ct) || isExcelName(u):
|
||||||
|
return "excel"
|
||||||
|
case strings.Contains(ct, "json") || strings.Contains(u, ".json") || strings.Contains(u, "format=json"):
|
||||||
|
return "json"
|
||||||
case strings.Contains(ct, "csv") || strings.HasSuffix(u, ".csv"):
|
case strings.Contains(ct, "csv") || strings.HasSuffix(u, ".csv"):
|
||||||
return "csv"
|
return "csv"
|
||||||
case strings.Contains(ct, "xml") || strings.HasSuffix(u, ".xml"):
|
case strings.Contains(ct, "xml") || strings.HasSuffix(u, ".xml"):
|
||||||
return "xml"
|
return "xml"
|
||||||
}
|
}
|
||||||
trimmed := bytes.TrimSpace(sample)
|
trimmed := bytes.TrimSpace(sample)
|
||||||
|
if len(trimmed) > 0 && (trimmed[0] == '{' || trimmed[0] == '[') {
|
||||||
|
return "json"
|
||||||
|
}
|
||||||
if len(trimmed) > 0 && trimmed[0] == '<' {
|
if len(trimmed) > 0 && trimmed[0] == '<' {
|
||||||
return "xml"
|
return "xml"
|
||||||
}
|
}
|
||||||
@@ -64,7 +75,7 @@ func parseCSV(r io.Reader, onRow func(feedRow) error) (int, error) {
|
|||||||
}
|
}
|
||||||
cols := make([]string, len(header))
|
cols := make([]string, len(header))
|
||||||
for i, h := range header {
|
for i, h := range header {
|
||||||
cols[i] = strings.TrimSpace(h)
|
cols[i] = strings.TrimSpace(strings.TrimPrefix(h, "\uFEFF"))
|
||||||
}
|
}
|
||||||
count := 0
|
count := 0
|
||||||
for {
|
for {
|
||||||
@@ -173,18 +184,80 @@ func guessXMLItemLocal(data []byte) string {
|
|||||||
sample = sample[:xmlItemGuessBytes]
|
sample = sample[:xmlItemGuessBytes]
|
||||||
}
|
}
|
||||||
lower := strings.ToLower(sample)
|
lower := strings.ToLower(sample)
|
||||||
for _, cand := range []string{"item", "product", "entry", "offer", "row"} {
|
for _, cand := range []string{"shopitem", "item", "entry", "offer", "row", "product"} {
|
||||||
if strings.Contains(lower, "<"+cand) || strings.Contains(lower, ":"+cand) {
|
if strings.Contains(lower, "<"+cand) || strings.Contains(lower, ":"+cand) {
|
||||||
return cand
|
return cand
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if p := guessRepeatedXMLItemPath([]byte(sample)); p != "" {
|
||||||
|
return leafName(p)
|
||||||
|
}
|
||||||
return "item"
|
return "item"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// guessRepeatedXMLItemPath finds the record element of feeds with non-English tags
|
||||||
|
// (<izdelki><izdelek>…): the most repeated element that has child elements, the
|
||||||
|
// shallowest on ties. Tolerates a truncated sample.
|
||||||
|
func guessRepeatedXMLItemPath(data []byte) string {
|
||||||
|
dec := xml.NewDecoder(bytes.NewReader(data))
|
||||||
|
dec.Strict = false
|
||||||
|
var stack []string
|
||||||
|
counts := map[string]int{}
|
||||||
|
hasChildren := map[string]bool{}
|
||||||
|
for {
|
||||||
|
tok, err := dec.Token()
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch t := tok.(type) {
|
||||||
|
case xml.StartElement:
|
||||||
|
if len(stack) > 0 {
|
||||||
|
hasChildren[strings.Join(stack, "/")] = true
|
||||||
|
}
|
||||||
|
stack = append(stack, t.Name.Local)
|
||||||
|
counts[strings.Join(stack, "/")]++
|
||||||
|
case xml.EndElement:
|
||||||
|
if len(stack) > 0 {
|
||||||
|
stack = stack[:len(stack)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
best, bestN := "", 1
|
||||||
|
for p, n := range counts {
|
||||||
|
if !hasChildren[p] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
depth, bestDepth := strings.Count(p, "/"), strings.Count(best, "/")
|
||||||
|
if n > bestN || (n == bestN && best != "" && (depth < bestDepth || (depth == bestDepth && p < best))) {
|
||||||
|
best, bestN = p, n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
func localNameEquals(n xml.Name, local string) bool {
|
func localNameEquals(n xml.Name, local string) bool {
|
||||||
return strings.EqualFold(n.Local, local)
|
return strings.EqualFold(n.Local, local)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isXMLPropertyNameAttr lists attributes that name a property element
|
||||||
|
// (<lastnost naziv="…">, <param name="…">).
|
||||||
|
func isXMLPropertyNameAttr(local string) bool {
|
||||||
|
switch strings.ToLower(local) {
|
||||||
|
case "naziv", "name", "ime", "key", "label":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func xmlPropertyLabel(attrs []xml.Attr) string {
|
||||||
|
for _, a := range attrs {
|
||||||
|
if isXMLPropertyNameAttr(a.Name.Local) {
|
||||||
|
return sanitizePathSegment(a.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error) {
|
func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error) {
|
||||||
row := make(feedRow)
|
row := make(feedRow)
|
||||||
for _, a := range start.Attr {
|
for _, a := range start.Attr {
|
||||||
@@ -193,6 +266,13 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
|
|||||||
row[start.Name.Local+"/"+key] = a.Value
|
row[start.Name.Local+"/"+key] = a.Value
|
||||||
}
|
}
|
||||||
var path []string
|
var path []string
|
||||||
|
// propNames[i] is the label of path[i] when it is a named property inside a group,
|
||||||
|
// such as <dodatneLastnosti><lastnost naziv="Vrsta">Nahrbtnik</lastnost>… (else "").
|
||||||
|
// Its text is also stored under group/<label>; propCounts tracks group/leaf paths
|
||||||
|
// so the merged "all siblings" value can be dropped once two labels share it.
|
||||||
|
var propNames []string
|
||||||
|
propCounts := map[string]int{}
|
||||||
|
var paramName, paramValue string
|
||||||
for {
|
for {
|
||||||
tok, err := dec.Token()
|
tok, err := dec.Token()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -201,22 +281,88 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
|
|||||||
switch t := tok.(type) {
|
switch t := tok.(type) {
|
||||||
case xml.StartElement:
|
case xml.StartElement:
|
||||||
path = append(path, t.Name.Local)
|
path = append(path, t.Name.Local)
|
||||||
|
label := ""
|
||||||
|
if len(path) >= 2 {
|
||||||
|
label = xmlPropertyLabel(t.Attr)
|
||||||
|
}
|
||||||
|
if label != "" {
|
||||||
|
propCounts[strings.Join(path, "/")]++
|
||||||
|
}
|
||||||
|
propNames = append(propNames, label)
|
||||||
for _, a := range t.Attr {
|
for _, a := range t.Attr {
|
||||||
key := strings.Join(path, "/") + "/@" + a.Name.Local
|
key := strings.Join(path, "/") + "/@" + a.Name.Local
|
||||||
row["@"+a.Name.Local] = a.Value
|
row["@"+a.Name.Local] = a.Value
|
||||||
row[key] = a.Value
|
row[key] = a.Value
|
||||||
}
|
}
|
||||||
case xml.EndElement:
|
case xml.EndElement:
|
||||||
|
if strings.EqualFold(t.Name.Local, "PARAM") && len(path) >= 2 && strings.EqualFold(path[len(path)-2], "PARAMS") {
|
||||||
|
name := strings.TrimSpace(paramName)
|
||||||
|
value := strings.TrimSpace(paramValue)
|
||||||
|
if name != "" && value != "" {
|
||||||
|
key := "PARAMS/" + sanitizePathSegment(name)
|
||||||
|
if key != "PARAMS/" {
|
||||||
|
row[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paramName, paramValue = "", ""
|
||||||
|
}
|
||||||
if len(path) == 0 {
|
if len(path) == 0 {
|
||||||
|
for p, n := range propCounts {
|
||||||
|
if n > 1 {
|
||||||
|
delete(row, p) // "MicroUSB 1 m": every sibling's text merged
|
||||||
|
}
|
||||||
|
}
|
||||||
|
count := 0
|
||||||
|
for k := range row {
|
||||||
|
if strings.HasPrefix(k, "PARAMS/") && !strings.Contains(strings.TrimPrefix(k, "PARAMS/"), "/") {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count > 0 {
|
||||||
|
row["PARAMS"] = fmt.Sprintf("%d named attributes", count)
|
||||||
|
}
|
||||||
|
// Supplier feeds often publish additional images as numbered siblings.
|
||||||
|
images := make([]string, 0, 12)
|
||||||
|
for i := 1; i <= 50; i++ {
|
||||||
|
name := fmt.Sprintf("IMGURL_ALTERNATIVE_%02d", i)
|
||||||
|
if v := strings.TrimSpace(row[name]); v != "" {
|
||||||
|
images = append(images, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(images) > 0 {
|
||||||
|
row["ADDITIONAL_IMAGE_URLS"] = strings.Join(images, ",")
|
||||||
|
}
|
||||||
return row, nil
|
return row, nil
|
||||||
}
|
}
|
||||||
path = path[:len(path)-1]
|
path = path[:len(path)-1]
|
||||||
|
propNames = propNames[:len(propNames)-1]
|
||||||
case xml.CharData:
|
case xml.CharData:
|
||||||
text := strings.TrimSpace(string(t))
|
text := strings.TrimSpace(string(t))
|
||||||
if text == "" || len(path) == 0 {
|
if text == "" || len(path) == 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if label := propNames[len(propNames)-1]; label != "" {
|
||||||
|
key := strings.Join(append(path[:len(path)-1:len(path)-1], label), "/")
|
||||||
|
if prev := row[key]; prev != "" && prev != text {
|
||||||
|
row[key] = prev + " " + text
|
||||||
|
} else {
|
||||||
|
row[key] = text
|
||||||
|
}
|
||||||
|
}
|
||||||
leaf := path[len(path)-1]
|
leaf := path[len(path)-1]
|
||||||
|
if len(path) >= 3 && strings.EqualFold(path[len(path)-3], "PARAMS") && strings.EqualFold(path[len(path)-2], "PARAM") {
|
||||||
|
if strings.EqualFold(leaf, "PARAM_NAME") {
|
||||||
|
paramName += text
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.EqualFold(leaf, "VAL") {
|
||||||
|
paramValue += text
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.EqualFold(leaf, "ORDER") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
full := strings.Join(path, "/")
|
full := strings.Join(path, "/")
|
||||||
// Prefer nested path as source of truth; only set bare leaf when
|
// Prefer nested path as source of truth; only set bare leaf when
|
||||||
// unique (no other nested field already owns this leaf name).
|
// unique (no other nested field already owns this leaf name).
|
||||||
|
|||||||
@@ -0,0 +1,254 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// parseJSONItems consumes one object at a time from a root array or a nested array
|
||||||
|
// (data.products, results, items, SHOPITEM, etc). It does not buffer the catalog.
|
||||||
|
func parseJSONItems(r io.Reader, itemPath string, onRow func(feedRow) error) (int, error) {
|
||||||
|
dec := json.NewDecoder(bufio.NewReader(r))
|
||||||
|
dec.UseNumber()
|
||||||
|
first, err := dec.Token()
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("json: %w", err)
|
||||||
|
}
|
||||||
|
count := 0
|
||||||
|
var visit func(any, []string) error
|
||||||
|
visit = func(token any, path []string) error {
|
||||||
|
delim, ok := token.(json.Delim)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch delim {
|
||||||
|
case '[':
|
||||||
|
if jsonItemPathMatches(itemPath, path) || (itemPath == "" && isLikelyJSONItemArray(path)) {
|
||||||
|
for dec.More() {
|
||||||
|
var raw json.RawMessage
|
||||||
|
if err := dec.Decode(&raw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var obj any
|
||||||
|
d := json.NewDecoder(bytes.NewReader(raw))
|
||||||
|
d.UseNumber()
|
||||||
|
if err := d.Decode(&obj); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, ok := obj.(map[string]any); !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
row := feedRow{}
|
||||||
|
flattenJSONValue(row, "", obj, 0)
|
||||||
|
expandSpecificationFields(row)
|
||||||
|
count++
|
||||||
|
if count > maxParseRows {
|
||||||
|
return parseTooManyRows()
|
||||||
|
}
|
||||||
|
if err := onRow(row); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for dec.More() {
|
||||||
|
next, e := dec.Token()
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if err := visit(next, path); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case '{':
|
||||||
|
for dec.More() {
|
||||||
|
k, e := dec.Token()
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
key, _ := k.(string)
|
||||||
|
next, e := dec.Token()
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if err := visit(next, append(append([]string(nil), path...), key)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("invalid JSON document")
|
||||||
|
}
|
||||||
|
_, err := dec.Token()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := visit(first, nil); err != nil {
|
||||||
|
return count, fmt.Errorf("json: %w", err)
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
return 0, errors.New("JSON contained no product records; check item path (for example products or data/products)")
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonItemPathMatches(hint string, path []string) bool {
|
||||||
|
hint = strings.Trim(strings.ToLower(strings.TrimSpace(hint)), "/.")
|
||||||
|
if hint == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
hint = strings.ReplaceAll(hint, ".", "/")
|
||||||
|
actual := strings.ToLower(strings.Join(path, "/"))
|
||||||
|
return actual == hint || strings.HasSuffix(actual, "/"+hint)
|
||||||
|
}
|
||||||
|
func isLikelyJSONItemArray(path []string) bool {
|
||||||
|
if len(path) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
name := strings.ToLower(path[len(path)-1])
|
||||||
|
switch name {
|
||||||
|
case "products", "product", "items", "shopitem", "results", "entries", "offers", "rows", "records", "data":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func flattenJSONValue(row feedRow, prefix string, v any, depth int) {
|
||||||
|
if depth > 12 || len(row) > 4000 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch x := v.(type) {
|
||||||
|
case map[string]any:
|
||||||
|
keys := make([]string, 0, len(x))
|
||||||
|
for k := range x {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
for _, k := range keys {
|
||||||
|
path := k
|
||||||
|
if prefix != "" {
|
||||||
|
path = prefix + "/" + k
|
||||||
|
}
|
||||||
|
flattenJSONValue(row, path, x[k], depth+1)
|
||||||
|
}
|
||||||
|
case []any:
|
||||||
|
if len(x) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Attribute arrays [{name: ..., value: ...}] become named specification children.
|
||||||
|
for i, v := range x {
|
||||||
|
if i >= 250 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if m, ok := v.(map[string]any); ok {
|
||||||
|
name := jsonString(m["name"])
|
||||||
|
if name == "" {
|
||||||
|
name = jsonString(m["PARAM_NAME"])
|
||||||
|
}
|
||||||
|
value := jsonString(m["value"])
|
||||||
|
if value == "" {
|
||||||
|
value = jsonString(m["VAL"])
|
||||||
|
}
|
||||||
|
if name != "" && value != "" {
|
||||||
|
row[prefix] = "Nested attributes"
|
||||||
|
row[prefix+"/"+sanitizePathSegment(name)] = value
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s := jsonString(v); s != "" {
|
||||||
|
if _, ok := v.(map[string]any); !ok {
|
||||||
|
row[prefix+"/"+strconv.Itoa(i)] = s
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flattenJSONValue(row, prefix+"/"+strconv.Itoa(i), v, depth+1)
|
||||||
|
}
|
||||||
|
// For image galleries, keep the first URL in the parent path.
|
||||||
|
if _, ok := row[prefix]; !ok {
|
||||||
|
if first := jsonString(x[0]); first != "" {
|
||||||
|
row[prefix] = first
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case nil:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
value := jsonString(v)
|
||||||
|
if value == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
row[prefix] = value
|
||||||
|
leaf := leafName(prefix)
|
||||||
|
if _, ok := row[leaf]; !ok && leaf != "" {
|
||||||
|
row[leaf] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func jsonString(v any) string {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case string:
|
||||||
|
return x
|
||||||
|
case json.Number:
|
||||||
|
return string(x)
|
||||||
|
case bool:
|
||||||
|
return strconv.FormatBool(x)
|
||||||
|
case float64:
|
||||||
|
return strconv.FormatFloat(x, 'f', -1, 64)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// guessJSONItemPath picks a recognized list field in the preview; callers can override.
|
||||||
|
func guessJSONItemPath(data []byte) string {
|
||||||
|
var node any
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(data))
|
||||||
|
dec.UseNumber()
|
||||||
|
if dec.Decode(&node) != nil {
|
||||||
|
// Schema previews intentionally stop at 512 KiB, often halfway through
|
||||||
|
// large JSON documents. Recognize the first array property in the prefix.
|
||||||
|
re := regexp.MustCompile(`(?i)"([^"\\]+)"\s*:\s*\[\s*\{`)
|
||||||
|
if parts := re.FindSubmatch(data); len(parts) > 1 {
|
||||||
|
return string(parts[1])
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var find func(any, []string, int) string
|
||||||
|
find = func(v any, path []string, depth int) string {
|
||||||
|
if depth > 5 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
switch x := v.(type) {
|
||||||
|
case []any:
|
||||||
|
if len(x) > 0 {
|
||||||
|
if _, ok := x[0].(map[string]any); ok {
|
||||||
|
return strings.Join(path, "/")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case map[string]any:
|
||||||
|
for _, key := range []string{"products", "items", "SHOPITEM", "results", "data", "records", "product", "entries", "offers", "rows"} {
|
||||||
|
if n, ok := x[key]; ok {
|
||||||
|
if p := find(n, append(path, key), depth+1); p != "" || len(path) == 0 && key == "products" {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(x))
|
||||||
|
for k := range x {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
for _, k := range keys {
|
||||||
|
if p := find(x[k], append(path, k), depth+1); p != "" {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return find(node, nil, 0)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Janus Trade / Avtera: repeated <lastnost naziv="…"> siblings are separate specs.
|
||||||
|
func TestParseXMLNamedPropertiesBecomeSpecs(t *testing.T) {
|
||||||
|
body := `<podjetje><izdelki><izdelek st="1"><EAN>3567041102652</EAN>
|
||||||
|
<dodatneLastnosti><lastnost naziv="Vrsta priključka"><![CDATA[MicroUSB]]></lastnost><lastnost naziv="Dolžina kabla"><![CDATA[1 m]]></lastnost></dodatneLastnosti>
|
||||||
|
<kategorija id="NH99">Nahrbtniki</kategorija></izdelek></izdelki></podjetje>`
|
||||||
|
var row feedRow
|
||||||
|
if _, err := parseXMLItems(strings.NewReader(body), "izdelek", func(r feedRow) error { row = r; return nil }); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
specs := resolveSpecifications(row, "dodatneLastnosti")
|
||||||
|
if len(specs) != 2 || specs[CanonicalAttributeKey("Vrsta_priključka")] != "MicroUSB" || specs[CanonicalAttributeKey("Dolžina_kabla")] != "1 m" {
|
||||||
|
t.Fatalf("specs = %v (row %v)", specs, row)
|
||||||
|
}
|
||||||
|
// Elements merely carrying an id keep their old keys.
|
||||||
|
if row["kategorija"] != "Nahrbtniki" {
|
||||||
|
t.Fatalf("kategorija = %q", row["kategorija"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGuessXMLItemForNonEnglishTags(t *testing.T) {
|
||||||
|
body := `<?xml version="1.0"?><podjetje id="JANUS"><izdelki>
|
||||||
|
<izdelek st="1"><EAN>1</EAN><dodatneLastnosti><lastnost naziv="a">x</lastnost></dodatneLastnosti></izdelek>
|
||||||
|
<izdelek st="2"><EAN>2</EAN><dodatneLastnosti><lastnost naziv="a">y</lastnost></dodatneLastnosti></izdelek>
|
||||||
|
<izdelek st="3"><EAN>3</EAN><opis><![CDATA[cut off mid`
|
||||||
|
if got := guessXMLItemPath([]byte(body)); got != "podjetje/izdelki/izdelek" {
|
||||||
|
t.Fatalf("item path = %q", got)
|
||||||
|
}
|
||||||
|
if got := guessXMLItemLocal([]byte(body)); got != "izdelek" {
|
||||||
|
t.Fatalf("item local = %q", got)
|
||||||
|
}
|
||||||
|
fields, rows, err := extractXMLSchema([]byte(body), "izdelek")
|
||||||
|
if err != nil || rows != 2 || len(fields) == 0 {
|
||||||
|
t.Fatalf("truncated preview: rows=%d fields=%d err=%v", rows, len(fields), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,7 +61,8 @@ func PresentFeed(feed map[string]any) map[string]any {
|
|||||||
"last_synced_at": lastSynced,
|
"last_synced_at": lastSynced,
|
||||||
"products_updated_at": productsUpdated,
|
"products_updated_at": productsUpdated,
|
||||||
"last_data_at": lastDataAt,
|
"last_data_at": lastDataAt,
|
||||||
"options": opts,
|
"options": publicFeedOptions(opts),
|
||||||
|
"has_auth_headers": opts["request_headers_encrypted"] != nil && opts["request_headers_encrypted"] != "",
|
||||||
}
|
}
|
||||||
if deltas, ok := opts["last_sync_deltas"].(map[string]any); ok && deltas != nil {
|
if deltas, ok := opts["last_sync_deltas"].(map[string]any); ok && deltas != nil {
|
||||||
out["last_sync_deltas"] = deltas
|
out["last_sync_deltas"] = deltas
|
||||||
@@ -138,3 +139,13 @@ func formatAPITime(v any) any {
|
|||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func publicFeedOptions(opts map[string]any) map[string]any {
|
||||||
|
safe := make(map[string]any, len(opts))
|
||||||
|
for k, v := range opts {
|
||||||
|
if k != "request_headers_encrypted" && k != "request_headers" {
|
||||||
|
safe[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return safe
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// feedMergeVersion is mixed into the mapping hash. Bumping it makes every feed
|
||||||
|
// re-parse its file once, even when the file itself is unchanged, so rows written
|
||||||
|
// before cross-feed merging existed are merged without waiting for a file change.
|
||||||
|
const feedMergeVersion = "1"
|
||||||
|
|
||||||
|
// AutoSyncEnabled reports whether the worker schedules feed syncs by itself.
|
||||||
|
// On by default; FEED_AUTO_SYNC=0|false|off turns it off.
|
||||||
|
func AutoSyncEnabled() bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(os.Getenv("FEED_AUTO_SYNC"))) {
|
||||||
|
case "0", "false", "off", "no":
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// enqueueDueFeedsSQL queues one pending sync job per feed whose sync_interval_minutes
|
||||||
|
// has elapsed since its last sync. It skips feeds that:
|
||||||
|
// - are not active, have a zero interval, have no source or no active mapping
|
||||||
|
// - already have a pending or running job
|
||||||
|
// - failed within the last interval (so a broken feed is not retried every scan)
|
||||||
|
const enqueueDueFeedsSQL = `
|
||||||
|
INSERT INTO feed_sync_jobs (feed_id, company_id, status)
|
||||||
|
SELECT f.id, f.company_id, 'pending'
|
||||||
|
FROM input_feeds f
|
||||||
|
WHERE f.status = 'active'
|
||||||
|
AND f.sync_interval_minutes > 0
|
||||||
|
AND ($2::uuid IS NULL OR f.company_id = $2::uuid)
|
||||||
|
AND (f.last_synced_at IS NULL
|
||||||
|
OR f.last_synced_at + make_interval(mins => f.sync_interval_minutes) <= now())
|
||||||
|
AND (COALESCE(f.url, '') <> ''
|
||||||
|
OR COALESCE(f.options->>'source_path', f.options->>'local_path', f.options->>'file_path', '') <> '')
|
||||||
|
AND EXISTS (SELECT 1 FROM feed_mappings m WHERE m.feed_id = f.id AND m.is_active)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM feed_sync_jobs j
|
||||||
|
WHERE j.feed_id = f.id AND j.status IN ('pending', 'running'))
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM feed_sync_jobs j
|
||||||
|
WHERE j.feed_id = f.id AND j.status = 'failed'
|
||||||
|
AND j.created_at > now() - make_interval(mins => GREATEST(f.sync_interval_minutes, 15)))
|
||||||
|
ORDER BY f.last_synced_at ASC NULLS FIRST
|
||||||
|
LIMIT $1
|
||||||
|
RETURNING id`
|
||||||
|
|
||||||
|
// EnqueueDueFeeds queues sync jobs for feeds that are due (see enqueueDueFeedsSQL) and
|
||||||
|
// wakes the worker. companyID uuid.Nil means every company. It returns how many jobs
|
||||||
|
// were queued; the worker's sync slots then run them with the existing concurrency
|
||||||
|
// limits, so a large backlog drains gradually instead of all at once.
|
||||||
|
func (s *Service) EnqueueDueFeeds(ctx context.Context, limit int, companyID uuid.UUID) (int, error) {
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
var company any
|
||||||
|
if companyID != uuid.Nil {
|
||||||
|
company = companyID
|
||||||
|
}
|
||||||
|
rows, err := s.Pool.Query(ctx, enqueueDueFeedsSQL, limit, company)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
n := 0
|
||||||
|
var last uuid.UUID
|
||||||
|
for rows.Next() {
|
||||||
|
if err := rows.Scan(&last); err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
_, _ = s.Pool.Exec(ctx, `SELECT pg_notify('feed_sync_jobs', $1)`, last.String())
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
@@ -28,6 +28,8 @@ type CreateInput struct {
|
|||||||
SyncIntervalMinutes int
|
SyncIntervalMinutes int
|
||||||
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
|
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
|
||||||
Options map[string]any
|
Options map[string]any
|
||||||
|
RequestHeaders map[string]string
|
||||||
|
ContentLanguage string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) {
|
func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) {
|
||||||
@@ -120,6 +122,16 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
|
|||||||
if opts == nil {
|
if opts == nil {
|
||||||
opts = map[string]any{}
|
opts = map[string]any{}
|
||||||
}
|
}
|
||||||
|
if in.ContentLanguage != "" {
|
||||||
|
opts["content_language"] = in.ContentLanguage
|
||||||
|
}
|
||||||
|
if len(in.RequestHeaders) > 0 {
|
||||||
|
encrypted, err := encryptFeedHeaders(in.RequestHeaders)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
opts["request_headers_encrypted"] = encrypted
|
||||||
|
}
|
||||||
itemPath := strings.TrimSpace(in.ItemPath)
|
itemPath := strings.TrimSpace(in.ItemPath)
|
||||||
if itemPath == "" {
|
if itemPath == "" {
|
||||||
if p, ok := opts["item_path"].(string); ok {
|
if p, ok := opts["item_path"].(string); ok {
|
||||||
@@ -140,10 +152,13 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
|
|||||||
feedType = "csv"
|
feedType = "csv"
|
||||||
} else {
|
} else {
|
||||||
feedType = "xml"
|
feedType = "xml"
|
||||||
|
if strings.Contains(strings.ToLower(url), ".json") || strings.Contains(strings.ToLower(url), "format=json") {
|
||||||
|
feedType = "json"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if feedType != "xml" && feedType != "csv" {
|
}
|
||||||
return nil, ClientMsg("feed_type must be xml or csv")
|
if !isSupportedFeedType(feedType) {
|
||||||
|
return nil, ClientMsg("feed_type must be xml, csv, json or excel")
|
||||||
}
|
}
|
||||||
interval := in.SyncIntervalMinutes
|
interval := in.SyncIntervalMinutes
|
||||||
if interval <= 0 && in.SyncFrequencyHours > 0 {
|
if interval <= 0 && in.SyncFrequencyHours > 0 {
|
||||||
@@ -245,6 +260,14 @@ func (s *Service) attachMappingFieldCounts(ctx context.Context, companyID uuid.U
|
|||||||
return rows.Err()
|
return rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isSupportedFeedType(feedType string) bool {
|
||||||
|
switch feedType {
|
||||||
|
case "xml", "csv", "json", "excel":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func isCSVFeedType(feedType string) bool {
|
func isCSVFeedType(feedType string) bool {
|
||||||
t := strings.ToLower(strings.TrimSpace(feedType))
|
t := strings.ToLower(strings.TrimSpace(feedType))
|
||||||
return t == "csv" || t == "excel"
|
return t == "csv" || t == "excel"
|
||||||
@@ -273,7 +296,7 @@ func mappingDocIncomplete(item map[string]any, mappingsRaw any, mappings []Field
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
feedType, _ := item["feed_type"].(string)
|
feedType, _ := item["feed_type"].(string)
|
||||||
if !isCSVFeedType(feedType) && feedItemPathHint(item, mappingsRaw) == "" {
|
if !isCSVFeedType(feedType) && !strings.EqualFold(feedType, "json") && feedItemPathHint(item, mappingsRaw) == "" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
@@ -303,8 +326,8 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
feedType = strings.ToLower(strings.TrimSpace(feedType))
|
feedType = strings.ToLower(strings.TrimSpace(feedType))
|
||||||
if feedType != "" && feedType != "xml" && feedType != "csv" {
|
if feedType != "" && !isSupportedFeedType(feedType) {
|
||||||
return nil, ClientMsg("feed_type must be xml or csv")
|
return nil, ClientMsg("feed_type must be xml, csv, json or excel")
|
||||||
}
|
}
|
||||||
interval := 0
|
interval := 0
|
||||||
switch v := body["sync_interval_minutes"].(type) {
|
switch v := body["sync_interval_minutes"].(type) {
|
||||||
@@ -325,6 +348,25 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
contentLanguage := ""
|
||||||
|
if raw, ok := body["content_language"].(string); ok {
|
||||||
|
contentLanguage = strings.ToLower(strings.TrimSpace(raw))
|
||||||
|
}
|
||||||
|
var encryptedHeaders *string
|
||||||
|
if rawHeaders, exists := body["request_headers"]; exists {
|
||||||
|
headers := map[string]string{}
|
||||||
|
if rawHeaders != nil {
|
||||||
|
b, _ := json.Marshal(rawHeaders)
|
||||||
|
if err := json.Unmarshal(b, &headers); err != nil {
|
||||||
|
return nil, ClientMsg("invalid HTTP headers")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
encrypted, err := encryptFeedHeaders(headers)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
encryptedHeaders = &encrypted
|
||||||
|
}
|
||||||
ct, err := s.Pool.Exec(ctx, `
|
ct, err := s.Pool.Exec(ctx, `
|
||||||
UPDATE input_feeds SET
|
UPDATE input_feeds SET
|
||||||
name = CASE WHEN $3 <> '' THEN $3 ELSE name END,
|
name = CASE WHEN $3 <> '' THEN $3 ELSE name END,
|
||||||
@@ -332,13 +374,16 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
|
|||||||
status = CASE WHEN $5 <> '' THEN $5 ELSE status END,
|
status = CASE WHEN $5 <> '' THEN $5 ELSE status END,
|
||||||
feed_type = CASE WHEN $6 <> '' THEN $6 ELSE feed_type END,
|
feed_type = CASE WHEN $6 <> '' THEN $6 ELSE feed_type END,
|
||||||
sync_interval_minutes = CASE WHEN $7 > 0 THEN $7 ELSE sync_interval_minutes END,
|
sync_interval_minutes = CASE WHEN $7 > 0 THEN $7 ELSE sync_interval_minutes END,
|
||||||
options = CASE
|
options = CASE WHEN $9::text IS NULL THEN
|
||||||
WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text))
|
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE options END)
|
||||||
ELSE options
|
WHEN $9::text = '' THEN
|
||||||
END,
|
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE COALESCE(options, '{}'::jsonb) END) - 'request_headers_encrypted'
|
||||||
|
ELSE
|
||||||
|
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE COALESCE(options, '{}'::jsonb) END) || jsonb_build_object('request_headers_encrypted', $9::text)
|
||||||
|
END || CASE WHEN $10::text <> '' THEN jsonb_build_object('content_language', $10::text) ELSE '{}'::jsonb END,
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
WHERE id = $1 AND company_id = $2`,
|
WHERE id = $1 AND company_id = $2`,
|
||||||
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath))
|
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath), encryptedHeaders, contentLanguage)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -348,15 +393,94 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
|
|||||||
return s.Get(ctx, companyID, id)
|
return s.Get(ctx, companyID, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Delete removes a feed and its unprocessed raw catalog rows. Processed catalog
|
||||||
|
// entries are retained, and rows shared with another existing feed are reassigned.
|
||||||
func (s *Service) Delete(ctx context.Context, companyID, id uuid.UUID) error {
|
func (s *Service) Delete(ctx context.Context, companyID, id uuid.UUID) error {
|
||||||
ct, err := s.Pool.Exec(ctx, `DELETE FROM input_feeds WHERE id = $1 AND company_id = $2`, id, companyID)
|
_, err := s.DeleteWithCleanup(ctx, companyID, id)
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if ct.RowsAffected() == 0 {
|
|
||||||
return ErrNotFound
|
// DeleteWithCleanup executes the feed removal and raw-product cleanup atomically.
|
||||||
|
// It holds a row lock on the feed, which also serializes FK-checked sync writes
|
||||||
|
// against deletion; a concurrent worker cannot recreate rows for the deleted feed.
|
||||||
|
// The returned count includes only deleted raw products, never processed results.
|
||||||
|
func (s *Service) DeleteWithCleanup(ctx context.Context, companyID, id uuid.UUID) (int64, error) {
|
||||||
|
tx, err := s.Pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
}
|
}
|
||||||
return nil
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
var lockedID uuid.UUID
|
||||||
|
if err := tx.QueryRow(ctx, `
|
||||||
|
SELECT id FROM input_feeds
|
||||||
|
WHERE id = $1 AND company_id = $2
|
||||||
|
FOR UPDATE`, id, companyID).Scan(&lockedID); err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return 0, ErrNotFound
|
||||||
|
}
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy catalogs can associate one product with multiple feed IDs.
|
||||||
|
// Preserve any shared unprocessed row, but make a surviving feed its owner.
|
||||||
|
_, err = tx.Exec(ctx, `
|
||||||
|
WITH shared AS (
|
||||||
|
SELECT r.id AS raw_id, MIN(f.id::text)::uuid AS replacement
|
||||||
|
FROM raw_products r
|
||||||
|
JOIN LATERAL jsonb_array_elements_text(
|
||||||
|
CASE WHEN jsonb_typeof(r.feed_ids) = 'array' THEN r.feed_ids ELSE '[]'::jsonb END
|
||||||
|
) AS ids(value) ON true
|
||||||
|
JOIN input_feeds f ON f.id::text = ids.value
|
||||||
|
AND f.company_id = $1 AND f.id <> $2
|
||||||
|
WHERE r.company_id = $1 AND r.feed_id = $2
|
||||||
|
AND r.is_processed = false
|
||||||
|
AND r.processing_status IN ('unprocessed', 'failed')
|
||||||
|
GROUP BY r.id
|
||||||
|
)
|
||||||
|
UPDATE raw_products r SET feed_id = shared.replacement, updated_at = now()
|
||||||
|
FROM shared WHERE r.id = shared.raw_id AND r.company_id = $1`, companyID, id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only truly unprocessed/failed rows owned by this feed are removed.
|
||||||
|
// 'processing' rows are intentionally retained to avoid racing active AI jobs.
|
||||||
|
deleted, err := tx.Exec(ctx, `
|
||||||
|
DELETE FROM raw_products
|
||||||
|
WHERE company_id = $1 AND feed_id = $2
|
||||||
|
AND is_processed = false
|
||||||
|
AND processing_status IN ('unprocessed', 'failed')`, companyID, id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove references from secondary feed lists on retained products, too.
|
||||||
|
_, err = tx.Exec(ctx, `
|
||||||
|
UPDATE raw_products r SET feed_ids = COALESCE((
|
||||||
|
SELECT jsonb_agg(ids.value ORDER BY ids.ordinality)
|
||||||
|
FROM jsonb_array_elements_text(r.feed_ids) WITH ORDINALITY AS ids(value, ordinality)
|
||||||
|
WHERE ids.value <> $2::text
|
||||||
|
), '[]'::jsonb), updated_at = now()
|
||||||
|
WHERE r.company_id = $1 AND jsonb_typeof(r.feed_ids) = 'array'
|
||||||
|
AND r.feed_ids @> jsonb_build_array($2::text)`, companyID, id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// FK ON DELETE SET NULL preserves processed products, processing rows and
|
||||||
|
// export feed definitions; dependent mappings / sync jobs cascade as before.
|
||||||
|
ct, err := tx.Exec(ctx, `DELETE FROM input_feeds WHERE id = $1 AND company_id = $2`, id, companyID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if ct.RowsAffected() != 1 {
|
||||||
|
return 0, ErrNotFound
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return deleted.RowsAffected(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) GetMappings(ctx context.Context, companyID, feedID uuid.UUID) (map[string]any, error) {
|
func (s *Service) GetMappings(ctx context.Context, companyID, feedID uuid.UUID) (map[string]any, error) {
|
||||||
@@ -508,8 +632,8 @@ func (s *Service) CreateExportFeed(ctx context.Context, companyID uuid.UUID, in
|
|||||||
if format == "" {
|
if format == "" {
|
||||||
format = "xml"
|
format = "xml"
|
||||||
}
|
}
|
||||||
if format != "xml" && format != "csv" {
|
if format != "xml" && format != "csv" && format != "json" {
|
||||||
return nil, ClientMsg("format must be xml or csv")
|
return nil, ClientMsg("format must be xml, csv or json")
|
||||||
}
|
}
|
||||||
var src *uuid.UUID
|
var src *uuid.UUID
|
||||||
if in.SourceFeedID != nil && *in.SourceFeedID != "" {
|
if in.SourceFeedID != nil && *in.SourceFeedID != "" {
|
||||||
|
|||||||
@@ -77,7 +77,11 @@ func (s *Service) loadFeedSource(ctx context.Context, companyID uuid.UUID, feed
|
|||||||
if urlStr == "" {
|
if urlStr == "" {
|
||||||
return nil, errSourceRequired
|
return nil, errSourceRequired
|
||||||
}
|
}
|
||||||
return downloadFeed(ctx, urlStr)
|
headers, err := decryptFeedHeaders(feed["options"])
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return downloadFeedWithHeaders(ctx, urlStr, headers)
|
||||||
}
|
}
|
||||||
|
|
||||||
func sourcePathFromOptions(raw any) string {
|
func sourcePathFromOptions(raw any) string {
|
||||||
@@ -121,6 +125,10 @@ func (s *Service) readLocalFeed(companyID uuid.UUID, rel string) (*feedBlob, err
|
|||||||
lower := strings.ToLower(abs)
|
lower := strings.ToLower(abs)
|
||||||
if strings.HasSuffix(lower, ".xml") {
|
if strings.HasSuffix(lower, ".xml") {
|
||||||
ct = "application/xml"
|
ct = "application/xml"
|
||||||
|
} else if strings.HasSuffix(lower, ".json") {
|
||||||
|
ct = "application/json"
|
||||||
|
} else if isExcelName(lower) {
|
||||||
|
ct = "application/vnd.ms-excel"
|
||||||
}
|
}
|
||||||
return &feedBlob{
|
return &feedBlob{
|
||||||
path: abs,
|
path: abs,
|
||||||
|
|||||||
@@ -94,8 +94,10 @@ func isSpecFieldKey(key string) bool {
|
|||||||
leaf := strings.ToLower(leafName(key))
|
leaf := strings.ToLower(leafName(key))
|
||||||
leaf = strings.TrimPrefix(leaf, "@")
|
leaf = strings.TrimPrefix(leaf, "@")
|
||||||
switch leaf {
|
switch leaf {
|
||||||
case "specifications", "specification", "specs", "spec", "features", "feature", "attributes_raw":
|
case "specifications", "specification", "specs", "spec", "features", "feature", "attributes_raw", "params":
|
||||||
return true
|
return true
|
||||||
|
case "description":
|
||||||
|
return !strings.Contains(key, "/")
|
||||||
}
|
}
|
||||||
return strings.Contains(leaf, "specification")
|
return strings.Contains(leaf, "specification")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,12 @@ type MappingSuggestion struct {
|
|||||||
|
|
||||||
var sourceAliases = map[string][]string{
|
var sourceAliases = map[string][]string{
|
||||||
"gtin": {"gtin"},
|
"gtin": {"gtin"},
|
||||||
|
"productno": {"sku"}, "productno2": {"mpn"},
|
||||||
|
"product": {"title"}, "descriptionbasic": {"description"},
|
||||||
|
"pricevat": {"price"}, "priceeshopvat": {"price"},
|
||||||
|
"pricevoc": {"purchase_price"},
|
||||||
|
"imgurl": {"image_url"}, "params": {"specifications"},
|
||||||
|
"categoryid": {"category_id"},
|
||||||
"ean": {"gtin"},
|
"ean": {"gtin"},
|
||||||
"upc": {"gtin"},
|
"upc": {"gtin"},
|
||||||
"barcode": {"gtin"},
|
"barcode": {"gtin"},
|
||||||
|
|||||||
+219
-48
@@ -7,8 +7,11 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
@@ -22,8 +25,12 @@ type syncStats struct {
|
|||||||
Unchanged int
|
Unchanged int
|
||||||
Progress int
|
Progress int
|
||||||
ContentHash string
|
ContentHash string
|
||||||
|
MappingHash string
|
||||||
UnchangedFeed bool
|
UnchangedFeed bool
|
||||||
Deltas syncDeltaCounts
|
Deltas syncDeltaCounts
|
||||||
|
MissingGTIN int
|
||||||
|
MissingRows []int
|
||||||
|
SourceColumns []string
|
||||||
}
|
}
|
||||||
|
|
||||||
type pendingProduct struct {
|
type pendingProduct struct {
|
||||||
@@ -31,6 +38,10 @@ type pendingProduct struct {
|
|||||||
RawData map[string]string
|
RawData map[string]string
|
||||||
MappedData map[string]any
|
MappedData map[string]any
|
||||||
ContentHash string
|
ContentHash string
|
||||||
|
// Cross-feed merge result (primary locale only); empty means "leave as is".
|
||||||
|
Sources string // raw_products.feed_field_sources JSON
|
||||||
|
FeedIDsJSON string // raw_products.feed_ids JSON array
|
||||||
|
PrimaryFeed string // richest feed, becomes raw_products.feed_id
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sync downloads the feed URL, parses CSV/XML, applies mappings, and upserts raw_products
|
// Sync downloads the feed URL, parses CSV/XML, applies mappings, and upserts raw_products
|
||||||
@@ -180,9 +191,10 @@ func (s *Service) persistFeedSyncMeta(ctx context.Context, companyID, feedID, jo
|
|||||||
UPDATE input_feeds SET last_synced_at = now(), updated_at = now(),
|
UPDATE input_feeds SET last_synced_at = now(), updated_at = now(),
|
||||||
options = COALESCE(options, '{}'::jsonb) || jsonb_build_object(
|
options = COALESCE(options, '{}'::jsonb) || jsonb_build_object(
|
||||||
'last_content_hash', to_jsonb($2::text),
|
'last_content_hash', to_jsonb($2::text),
|
||||||
|
'last_mapping_hash', to_jsonb($5::text),
|
||||||
'last_sync_deltas', $3::jsonb
|
'last_sync_deltas', $3::jsonb
|
||||||
)
|
)
|
||||||
WHERE id = $1 AND company_id = $4`, feedID, stats.ContentHash, deltaJSON, companyID)
|
WHERE id = $1 AND company_id = $4`, feedID, stats.ContentHash, deltaJSON, companyID, stats.MappingHash)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,6 +273,14 @@ func (s *Service) ListSyncJobs(ctx context.Context, companyID, feedID uuid.UUID,
|
|||||||
|
|
||||||
func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUID, feed map[string]any) (syncStats, error) {
|
func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUID, feed map[string]any) (syncStats, error) {
|
||||||
var stats syncStats
|
var stats syncStats
|
||||||
|
primaryLanguage := company.LoadLanguage(ctx, s.Pool, companyID)
|
||||||
|
feedLanguage := primaryLanguage
|
||||||
|
if opts, ok := feed["options"].(map[string]any); ok {
|
||||||
|
if code, ok := opts["content_language"].(string); ok && company.IsAllowedLanguage(code) {
|
||||||
|
feedLanguage = company.NormalizeLanguage(code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx = context.WithValue(ctx, syncLocaleKey{}, syncLocale{code: feedLanguage, primary: feedLanguage == primaryLanguage})
|
||||||
urlStr, _ := feed["url"].(string)
|
urlStr, _ := feed["url"].(string)
|
||||||
feedType, _ := feed["feed_type"].(string)
|
feedType, _ := feed["feed_type"].(string)
|
||||||
|
|
||||||
@@ -276,14 +296,6 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
|
|||||||
}
|
}
|
||||||
stats.ContentHash = hash
|
stats.ContentHash = hash
|
||||||
|
|
||||||
prev, _ := s.lastContentHash(ctx, feedID)
|
|
||||||
if prev != "" && prev == hash {
|
|
||||||
stats.UnchangedFeed = true
|
|
||||||
stats.Progress = 100
|
|
||||||
_ = s.updateJobProgress(ctx, jobID, stats)
|
|
||||||
return stats, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
mappingsRaw, mapErr := s.loadMappingsRaw(ctx, companyID, feedID)
|
mappingsRaw, mapErr := s.loadMappingsRaw(ctx, companyID, feedID)
|
||||||
if mapErr != nil && !errors.Is(mapErr, pgx.ErrNoRows) {
|
if mapErr != nil && !errors.Is(mapErr, pgx.ErrNoRows) {
|
||||||
return stats, mapErr
|
return stats, mapErr
|
||||||
@@ -292,6 +304,28 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
|
|||||||
if len(mappings) == 0 {
|
if len(mappings) == 0 {
|
||||||
return stats, ClientMsg("no field mappings defined for feed")
|
return stats, ClientMsg("no field mappings defined for feed")
|
||||||
}
|
}
|
||||||
|
stats.MappingHash = sha256Hex([]byte(mustJSON(mappingsRaw) + "|language=" + feedLanguage + "|merge=" + feedMergeVersion))
|
||||||
|
|
||||||
|
prev, err := s.lastSuccessfulSync(ctx, feedID)
|
||||||
|
if err != nil {
|
||||||
|
return stats, err
|
||||||
|
}
|
||||||
|
previousMappingHash := ""
|
||||||
|
if opts, ok := feed["options"].(map[string]any); ok {
|
||||||
|
previousMappingHash, _ = opts["last_mapping_hash"].(string)
|
||||||
|
}
|
||||||
|
if prev.ContentHash != "" && prev.ContentHash == hash &&
|
||||||
|
previousMappingHash != "" && previousMappingHash == stats.MappingHash {
|
||||||
|
// Only bypass parsing if source AND mapping configuration match a valid
|
||||||
|
// previous sync. Legacy zero-import runs and changed mappings reprocess.
|
||||||
|
stats.UnchangedFeed = true
|
||||||
|
stats.Total = prev.Total
|
||||||
|
stats.Skipped = prev.Skipped
|
||||||
|
stats.Unchanged = prev.Total - prev.Skipped
|
||||||
|
stats.Progress = 100
|
||||||
|
_ = s.updateJobProgress(ctx, jobID, stats)
|
||||||
|
return stats, nil
|
||||||
|
}
|
||||||
|
|
||||||
itemPath := "item"
|
itemPath := "item"
|
||||||
if path := itemPathFromMappings(mappingsRaw); path != "" {
|
if path := itemPathFromMappings(mappingsRaw); path != "" {
|
||||||
@@ -349,6 +383,16 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
|
|||||||
mapped, gtin := applyMappings(row, mappings)
|
mapped, gtin := applyMappings(row, mappings)
|
||||||
if gtin == "" {
|
if gtin == "" {
|
||||||
stats.Skipped++
|
stats.Skipped++
|
||||||
|
stats.MissingGTIN++
|
||||||
|
if len(stats.MissingRows) < 5 {
|
||||||
|
stats.MissingRows = append(stats.MissingRows, stats.Total)
|
||||||
|
}
|
||||||
|
if len(stats.SourceColumns) == 0 {
|
||||||
|
for col := range row {
|
||||||
|
stats.SourceColumns = append(stats.SourceColumns, strings.TrimPrefix(col, "\uFEFF"))
|
||||||
|
}
|
||||||
|
sort.Strings(stats.SourceColumns)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
rawCopy := make(map[string]string, len(row))
|
rawCopy := make(map[string]string, len(row))
|
||||||
@@ -371,7 +415,25 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
|
|||||||
var parseCount int
|
var parseCount int
|
||||||
switch format {
|
switch format {
|
||||||
case "xml":
|
case "xml":
|
||||||
|
if itemPath == "item" {
|
||||||
|
itemPath = ""
|
||||||
|
}
|
||||||
parseCount, err = parseXMLItems(body, itemPath, onRow)
|
parseCount, err = parseXMLItems(body, itemPath, onRow)
|
||||||
|
case "json":
|
||||||
|
jsonPath := itemPath
|
||||||
|
if jsonPath == "item" {
|
||||||
|
jsonPath = ""
|
||||||
|
}
|
||||||
|
if v := itemPathFromMappings(mappingsRaw); v != "" {
|
||||||
|
jsonPath = v
|
||||||
|
} else if opts, ok := feed["options"].(map[string]any); ok {
|
||||||
|
if v, ok := opts["item_path"].(string); ok {
|
||||||
|
jsonPath = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parseCount, err = parseJSONItems(body, jsonPath, onRow)
|
||||||
|
case "excel":
|
||||||
|
parseCount, err = parseExcel(body.Name(), excelSheetOption(feed), onRow)
|
||||||
default:
|
default:
|
||||||
parseCount, err = parseCSV(body, onRow)
|
parseCount, err = parseCSV(body, onRow)
|
||||||
}
|
}
|
||||||
@@ -384,14 +446,24 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
|
|||||||
if err := flush(true); err != nil {
|
if err := flush(true); err != nil {
|
||||||
return stats, err
|
return stats, err
|
||||||
}
|
}
|
||||||
|
if stats.Synced+stats.Unchanged == 0 {
|
||||||
|
return stats, ClientMsg(syncSkipDiagnostics(stats))
|
||||||
|
}
|
||||||
stats.Progress = 100
|
stats.Progress = 100
|
||||||
_ = s.updateJobProgress(ctx, jobID, stats)
|
_ = s.updateJobProgress(ctx, jobID, stats)
|
||||||
return stats, nil
|
return stats, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type syncLocaleKey struct{}
|
||||||
|
type syncLocale struct {
|
||||||
|
code string
|
||||||
|
primary bool
|
||||||
|
}
|
||||||
|
|
||||||
type existingProduct struct {
|
type existingProduct struct {
|
||||||
ID uuid.UUID
|
ID uuid.UUID
|
||||||
MappedData []byte
|
MappedData []byte
|
||||||
|
SourceLocalizations []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -400,31 +472,50 @@ const (
|
|||||||
upsertSQLInsertSet = `
|
upsertSQLInsertSet = `
|
||||||
INSERT INTO raw_products (
|
INSERT INTO raw_products (
|
||||||
company_id, gtin, feed_id, raw_data, mapped_data, sync_job_id,
|
company_id, gtin, feed_id, raw_data, mapped_data, sync_job_id,
|
||||||
is_processed, processing_status, updated_at
|
is_processed, processing_status, updated_at, source_localizations,
|
||||||
|
feed_ids, feed_field_sources
|
||||||
)
|
)
|
||||||
SELECT $1, v.gtin, $2, v.raw_data::jsonb, v.mapped_data::jsonb, $3, false, 'unprocessed', now()
|
SELECT $1, v.gtin, COALESCE(NULLIF(v.primary_feed, '')::uuid, $2), v.raw_data::jsonb, v.mapped_data::jsonb, $3, false, 'unprocessed', now(),
|
||||||
FROM unnest($4::text[], $5::text[], $6::text[]) AS v(gtin, raw_data, mapped_data)
|
jsonb_build_object($7::text, v.mapped_data::jsonb),
|
||||||
|
NULLIF(v.feed_ids, '')::jsonb, NULLIF(v.sources, '')::jsonb
|
||||||
|
FROM unnest($4::text[], $5::text[], $6::text[], $9::text[], $10::text[], $11::text[])
|
||||||
|
AS v(gtin, raw_data, mapped_data, primary_feed, feed_ids, sources)
|
||||||
ON CONFLICT (company_id, gtin) DO UPDATE SET
|
ON CONFLICT (company_id, gtin) DO UPDATE SET
|
||||||
feed_id = EXCLUDED.feed_id,
|
feed_id = EXCLUDED.feed_id,
|
||||||
raw_data = EXCLUDED.raw_data,
|
raw_data = CASE WHEN $8 THEN EXCLUDED.raw_data ELSE raw_products.raw_data END,
|
||||||
mapped_data = EXCLUDED.mapped_data,
|
mapped_data = CASE WHEN $8 THEN EXCLUDED.mapped_data ELSE raw_products.mapped_data END,
|
||||||
|
source_localizations = jsonb_set(COALESCE(raw_products.source_localizations,'{}'::jsonb),ARRAY[$7::text],EXCLUDED.mapped_data,true),
|
||||||
|
feed_ids = CASE WHEN $8 AND EXCLUDED.feed_ids IS NOT NULL THEN EXCLUDED.feed_ids ELSE raw_products.feed_ids END,
|
||||||
|
feed_field_sources = CASE WHEN $8 AND EXCLUDED.feed_field_sources IS NOT NULL THEN EXCLUDED.feed_field_sources ELSE raw_products.feed_field_sources END,
|
||||||
sync_job_id = EXCLUDED.sync_job_id,
|
sync_job_id = EXCLUDED.sync_job_id,
|
||||||
is_processed = false,
|
is_processed = CASE WHEN $8 THEN false ELSE raw_products.is_processed END,
|
||||||
processing_status = 'unprocessed',
|
processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE raw_products.processing_status END,
|
||||||
updated_at = now()`
|
updated_at = now()`
|
||||||
|
// Touch: content unchanged, but the owning feed / contributing feeds / field
|
||||||
|
// sources may still have changed (another feed was added), so refresh those.
|
||||||
upsertSQLTouchSet = `
|
upsertSQLTouchSet = `
|
||||||
UPDATE raw_products SET sync_job_id = $3, feed_id = $4, updated_at = now()
|
UPDATE raw_products AS r SET
|
||||||
WHERE company_id = $1 AND id = ANY($2::uuid[])`
|
sync_job_id = $3,
|
||||||
|
feed_id = COALESCE(NULLIF(v.primary_feed, '')::uuid, $4),
|
||||||
|
feed_ids = CASE WHEN v.feed_ids <> '' THEN v.feed_ids::jsonb ELSE r.feed_ids END,
|
||||||
|
feed_field_sources = CASE WHEN v.sources <> '' THEN v.sources::jsonb ELSE r.feed_field_sources END,
|
||||||
|
updated_at = now()
|
||||||
|
FROM unnest($2::uuid[], $5::text[], $6::text[], $7::text[]) AS v(id, primary_feed, feed_ids, sources)
|
||||||
|
WHERE r.company_id = $1 AND r.id = v.id`
|
||||||
upsertSQLUpdateSet = `
|
upsertSQLUpdateSet = `
|
||||||
UPDATE raw_products AS r SET
|
UPDATE raw_products AS r SET
|
||||||
feed_id = $2,
|
feed_id = COALESCE(NULLIF(v.primary_feed, '')::uuid, $2),
|
||||||
raw_data = v.raw_data::jsonb,
|
raw_data = CASE WHEN $8 THEN v.raw_data::jsonb ELSE r.raw_data END,
|
||||||
mapped_data = v.mapped_data::jsonb,
|
mapped_data = CASE WHEN $8 THEN v.mapped_data::jsonb ELSE r.mapped_data END,
|
||||||
|
source_localizations = jsonb_set(COALESCE(r.source_localizations,'{}'::jsonb),ARRAY[$7::text],v.mapped_data::jsonb,true),
|
||||||
|
feed_ids = CASE WHEN $8 AND v.feed_ids <> '' THEN v.feed_ids::jsonb ELSE r.feed_ids END,
|
||||||
|
feed_field_sources = CASE WHEN $8 AND v.sources <> '' THEN v.sources::jsonb ELSE r.feed_field_sources END,
|
||||||
sync_job_id = $3,
|
sync_job_id = $3,
|
||||||
is_processed = false,
|
is_processed = CASE WHEN $8 THEN false ELSE r.is_processed END,
|
||||||
processing_status = 'unprocessed',
|
processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE r.processing_status END,
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
FROM unnest($4::uuid[], $5::text[], $6::text[]) AS v(id, raw_data, mapped_data)
|
FROM unnest($4::uuid[], $5::text[], $6::text[], $9::text[], $10::text[], $11::text[])
|
||||||
|
AS v(id, raw_data, mapped_data, primary_feed, feed_ids, sources)
|
||||||
WHERE r.id = v.id AND r.company_id = $1`
|
WHERE r.id = v.id AND r.company_id = $1`
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -443,13 +534,17 @@ type upsertOp struct {
|
|||||||
rawJSON []byte
|
rawJSON []byte
|
||||||
mappedJSON []byte
|
mappedJSON []byte
|
||||||
changes []string
|
changes []string
|
||||||
|
// Cross-feed merge metadata (empty when the merge did not run).
|
||||||
|
primaryFeed string
|
||||||
|
feedIDs string
|
||||||
|
sources string
|
||||||
}
|
}
|
||||||
|
|
||||||
// classifyUpsertOps decides insert / touch / update per row without DB I/O so a chunk
|
// classifyUpsertOps decides insert / touch / update per row without DB I/O so a chunk
|
||||||
// can be applied with set-based UNNEST statements (≤3) in one pgx.Batch round-trip.
|
// can be applied with set-based UNNEST statements (≤3) in one pgx.Batch round-trip.
|
||||||
// Touch keeps is_processed/processing_status when mapped_data is equal (canonical JSON).
|
// Touch keeps is_processed/processing_status when mapped_data is equal (canonical JSON).
|
||||||
// Updates/inserts stamp mapped_data._sync_changes for seller filters (price/stock/…).
|
// Updates/inserts stamp mapped_data._sync_changes for seller filters (price/stock/…).
|
||||||
func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProduct) (ops []upsertOp, skipped int) {
|
func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProduct, locale ...syncLocale) (ops []upsertOp, skipped int) {
|
||||||
ops = make([]upsertOp, 0, len(chunk))
|
ops = make([]upsertOp, 0, len(chunk))
|
||||||
for _, p := range chunk {
|
for _, p := range chunk {
|
||||||
rawJSON, err := json.Marshal(p.RawData)
|
rawJSON, err := json.Marshal(p.RawData)
|
||||||
@@ -469,21 +564,36 @@ func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProdu
|
|||||||
ops = append(ops, upsertOp{
|
ops = append(ops, upsertOp{
|
||||||
kind: upsertOpInsert, gtin: p.GTIN, rawJSON: rawJSON, mappedJSON: mappedJSON,
|
kind: upsertOpInsert, gtin: p.GTIN, rawJSON: rawJSON, mappedJSON: mappedJSON,
|
||||||
changes: []string{"new"},
|
changes: []string{"new"},
|
||||||
|
primaryFeed: p.PrimaryFeed, feedIDs: p.FeedIDsJSON, sources: p.Sources,
|
||||||
})
|
})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Category (and similar extras) live outside feed mappings — keep them.
|
// Category (and similar extras) live outside feed mappings — keep them.
|
||||||
cleanMapped = preserveSyncedExtras(ex.MappedData, cleanMapped)
|
existingMapped := ex.MappedData
|
||||||
|
if len(locale) > 0 && !locale[0].primary {
|
||||||
|
var all map[string]json.RawMessage
|
||||||
|
if json.Unmarshal(ex.SourceLocalizations, &all) == nil {
|
||||||
|
if val, exists := all[locale[0].code]; exists {
|
||||||
|
existingMapped = val
|
||||||
|
} else {
|
||||||
|
existingMapped = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cleanMapped = preserveSyncedExtras(existingMapped, cleanMapped)
|
||||||
plainJSON, err := json.Marshal(cleanMapped)
|
plainJSON, err := json.Marshal(cleanMapped)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
skipped++
|
skipped++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if bytesEqualJSON(stripSyncChangesBytes(ex.MappedData), plainJSON) {
|
if bytesEqualJSON(stripSyncChangesBytes(existingMapped), plainJSON) {
|
||||||
ops = append(ops, upsertOp{kind: upsertOpTouch, id: ex.ID})
|
ops = append(ops, upsertOp{
|
||||||
|
kind: upsertOpTouch, id: ex.ID,
|
||||||
|
primaryFeed: p.PrimaryFeed, feedIDs: p.FeedIDsJSON, sources: p.Sources,
|
||||||
|
})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
changes := detectMappedChanges(ex.MappedData, cleanMapped)
|
changes := detectMappedChanges(existingMapped, cleanMapped)
|
||||||
withFlags := withSyncChanges(cleanMapped, changes)
|
withFlags := withSyncChanges(cleanMapped, changes)
|
||||||
mappedJSON, err := json.Marshal(withFlags)
|
mappedJSON, err := json.Marshal(withFlags)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -493,6 +603,7 @@ func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProdu
|
|||||||
ops = append(ops, upsertOp{
|
ops = append(ops, upsertOp{
|
||||||
kind: upsertOpUpdate, id: ex.ID, rawJSON: rawJSON, mappedJSON: mappedJSON,
|
kind: upsertOpUpdate, id: ex.ID, rawJSON: rawJSON, mappedJSON: mappedJSON,
|
||||||
changes: changes,
|
changes: changes,
|
||||||
|
primaryFeed: p.PrimaryFeed, feedIDs: p.FeedIDsJSON, sources: p.Sources,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return ops, skipped
|
return ops, skipped
|
||||||
@@ -565,7 +676,18 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
|
|||||||
return 0, 0, 0, deltas, err
|
return 0, 0, 0, deltas, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ops, skipped := classifyUpsertOps(chunk, existing)
|
locale, ok := ctx.Value(syncLocaleKey{}).(syncLocale)
|
||||||
|
if !ok {
|
||||||
|
locale = syncLocale{code: company.LoadLanguage(ctx, s.Pool, companyID), primary: true}
|
||||||
|
}
|
||||||
|
// Several vendor feeds can carry the same EAN: store this feed's row and merge all
|
||||||
|
// feeds' data before comparing against the existing product.
|
||||||
|
if locale.primary {
|
||||||
|
if err := s.mergeChunkAcrossFeeds(ctx, companyID, feedID, chunk); err != nil {
|
||||||
|
return 0, 0, 0, deltas, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ops, skipped := classifyUpsertOps(chunk, existing, locale)
|
||||||
if len(ops) == 0 {
|
if len(ops) == 0 {
|
||||||
deltas.Skipped = skipped
|
deltas.Skipped = skipped
|
||||||
return 0, 0, skipped, deltas, nil
|
return 0, 0, skipped, deltas, nil
|
||||||
@@ -578,34 +700,40 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
|
|||||||
gtinCol := make([]string, len(inserts))
|
gtinCol := make([]string, len(inserts))
|
||||||
rawCol := make([]string, len(inserts))
|
rawCol := make([]string, len(inserts))
|
||||||
mappedCol := make([]string, len(inserts))
|
mappedCol := make([]string, len(inserts))
|
||||||
|
primCol, idsCol, srcCol := make([]string, len(inserts)), make([]string, len(inserts)), make([]string, len(inserts))
|
||||||
for i, op := range inserts {
|
for i, op := range inserts {
|
||||||
gtinCol[i] = op.gtin
|
gtinCol[i] = op.gtin
|
||||||
rawCol[i] = string(op.rawJSON)
|
rawCol[i] = string(op.rawJSON)
|
||||||
mappedCol[i] = string(op.mappedJSON)
|
mappedCol[i] = string(op.mappedJSON)
|
||||||
|
primCol[i], idsCol[i], srcCol[i] = op.primaryFeed, op.feedIDs, op.sources
|
||||||
deltas.addChanges(op.changes)
|
deltas.addChanges(op.changes)
|
||||||
}
|
}
|
||||||
batch.Queue(upsertSQLInsertSet, companyID, feedID, jobID, gtinCol, rawCol, mappedCol)
|
batch.Queue(upsertSQLInsertSet, companyID, feedID, jobID, gtinCol, rawCol, mappedCol, locale.code, locale.primary, primCol, idsCol, srcCol)
|
||||||
queued++
|
queued++
|
||||||
}
|
}
|
||||||
if len(touches) > 0 {
|
if len(touches) > 0 {
|
||||||
ids := make([]uuid.UUID, len(touches))
|
ids := make([]uuid.UUID, len(touches))
|
||||||
|
primCol, idsCol, srcCol := make([]string, len(touches)), make([]string, len(touches)), make([]string, len(touches))
|
||||||
for i, op := range touches {
|
for i, op := range touches {
|
||||||
ids[i] = op.id
|
ids[i] = op.id
|
||||||
|
primCol[i], idsCol[i], srcCol[i] = op.primaryFeed, op.feedIDs, op.sources
|
||||||
}
|
}
|
||||||
batch.Queue(upsertSQLTouchSet, companyID, ids, jobID, feedID)
|
batch.Queue(upsertSQLTouchSet, companyID, ids, jobID, feedID, primCol, idsCol, srcCol)
|
||||||
queued++
|
queued++
|
||||||
}
|
}
|
||||||
if len(updates) > 0 {
|
if len(updates) > 0 {
|
||||||
ids := make([]uuid.UUID, len(updates))
|
ids := make([]uuid.UUID, len(updates))
|
||||||
rawCol := make([]string, len(updates))
|
rawCol := make([]string, len(updates))
|
||||||
mappedCol := make([]string, len(updates))
|
mappedCol := make([]string, len(updates))
|
||||||
|
primCol, idsCol, srcCol := make([]string, len(updates)), make([]string, len(updates)), make([]string, len(updates))
|
||||||
for i, op := range updates {
|
for i, op := range updates {
|
||||||
ids[i] = op.id
|
ids[i] = op.id
|
||||||
rawCol[i] = string(op.rawJSON)
|
rawCol[i] = string(op.rawJSON)
|
||||||
mappedCol[i] = string(op.mappedJSON)
|
mappedCol[i] = string(op.mappedJSON)
|
||||||
|
primCol[i], idsCol[i], srcCol[i] = op.primaryFeed, op.feedIDs, op.sources
|
||||||
deltas.addChanges(op.changes)
|
deltas.addChanges(op.changes)
|
||||||
}
|
}
|
||||||
batch.Queue(upsertSQLUpdateSet, companyID, feedID, jobID, ids, rawCol, mappedCol)
|
batch.Queue(upsertSQLUpdateSet, companyID, feedID, jobID, ids, rawCol, mappedCol, locale.code, locale.primary, primCol, idsCol, srcCol)
|
||||||
queued++
|
queued++
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -619,7 +747,7 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
|
|||||||
// Content inserts/updates stamp raw as unprocessed — drop catalog rows so
|
// Content inserts/updates stamp raw as unprocessed — drop catalog rows so
|
||||||
// processed_products cannot outlive that reset (matches resetRawProducts).
|
// processed_products cannot outlive that reset (matches resetRawProducts).
|
||||||
// Touches keep processing_status and must not invalidate catalog.
|
// Touches keep processing_status and must not invalidate catalog.
|
||||||
if len(inserts) > 0 || len(updates) > 0 {
|
if (len(inserts) > 0 || len(updates) > 0) && locale.primary {
|
||||||
invalidateIDs := make([]uuid.UUID, 0, len(updates))
|
invalidateIDs := make([]uuid.UUID, 0, len(updates))
|
||||||
for _, op := range updates {
|
for _, op := range updates {
|
||||||
invalidateIDs = append(invalidateIDs, op.id)
|
invalidateIDs = append(invalidateIDs, op.id)
|
||||||
@@ -654,7 +782,7 @@ func (s *Service) loadExistingByGTIN(ctx context.Context, companyID uuid.UUID, g
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
rows, err := s.Pool.Query(ctx, `
|
rows, err := s.Pool.Query(ctx, `
|
||||||
SELECT id, gtin, mapped_data FROM raw_products
|
SELECT id, gtin, mapped_data, COALESCE(source_localizations,'{}'::jsonb) FROM raw_products
|
||||||
WHERE company_id = $1 AND gtin = ANY($2::text[])`, companyID, gtins)
|
WHERE company_id = $1 AND gtin = ANY($2::text[])`, companyID, gtins)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -663,7 +791,7 @@ func (s *Service) loadExistingByGTIN(ctx context.Context, companyID uuid.UUID, g
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var ex existingProduct
|
var ex existingProduct
|
||||||
var gtin string
|
var gtin string
|
||||||
if err := rows.Scan(&ex.ID, >in, &ex.MappedData); err != nil {
|
if err := rows.Scan(&ex.ID, >in, &ex.MappedData, &ex.SourceLocalizations); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
out[gtin] = ex
|
out[gtin] = ex
|
||||||
@@ -743,6 +871,10 @@ func (s *Service) updateJobProgress(ctx context.Context, jobID uuid.UUID, stats
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) completeJob(ctx context.Context, jobID uuid.UUID, stats syncStats) error {
|
func (s *Service) completeJob(ctx context.Context, jobID uuid.UUID, stats syncStats) error {
|
||||||
|
warning := ""
|
||||||
|
if stats.Skipped > 0 {
|
||||||
|
warning = syncSkipDiagnostics(stats)
|
||||||
|
}
|
||||||
_, err := s.Pool.Exec(ctx, `
|
_, err := s.Pool.Exec(ctx, `
|
||||||
UPDATE feed_sync_jobs SET
|
UPDATE feed_sync_jobs SET
|
||||||
status = 'completed',
|
status = 'completed',
|
||||||
@@ -753,9 +885,10 @@ func (s *Service) completeJob(ctx context.Context, jobID uuid.UUID, stats syncSt
|
|||||||
products_unchanged = $5,
|
products_unchanged = $5,
|
||||||
progress = 100,
|
progress = 100,
|
||||||
content_hash = NULLIF($6, ''),
|
content_hash = NULLIF($6, ''),
|
||||||
|
error = NULLIF($7, ''),
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
WHERE id = $1`,
|
WHERE id = $1`,
|
||||||
jobID, stats.Synced, stats.Total, stats.Skipped, stats.Unchanged, stats.ContentHash)
|
jobID, stats.Synced, stats.Total, stats.Skipped, stats.Unchanged, stats.ContentHash, truncateErr(warning))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -777,22 +910,60 @@ func (s *Service) failJob(ctx context.Context, jobID uuid.UUID, msg string, stat
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) lastContentHash(ctx context.Context, feedID uuid.UUID) (string, error) {
|
// lastSuccessfulSync only caches a file when at least one product was accepted.
|
||||||
var hash *string
|
// In particular, historical "completed 0 / 127 skipped" jobs must be reprocessed.
|
||||||
|
type syncedSourceSummary struct {
|
||||||
|
ContentHash string
|
||||||
|
Total int
|
||||||
|
Skipped int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) lastSuccessfulSync(ctx context.Context, feedID uuid.UUID) (syncedSourceSummary, error) {
|
||||||
|
var prev syncedSourceSummary
|
||||||
err := s.Pool.QueryRow(ctx, `
|
err := s.Pool.QueryRow(ctx, `
|
||||||
SELECT content_hash FROM feed_sync_jobs
|
SELECT content_hash, products_total, products_skipped FROM feed_sync_jobs
|
||||||
WHERE feed_id = $1 AND status = 'completed' AND content_hash IS NOT NULL AND content_hash <> ''
|
WHERE feed_id = $1 AND status = 'completed'
|
||||||
ORDER BY completed_at DESC NULLS LAST LIMIT 1`, feedID).Scan(&hash)
|
AND content_hash IS NOT NULL AND content_hash <> ''
|
||||||
|
AND products_total > 0
|
||||||
|
AND (products_synced > 0 OR products_unchanged > 0)
|
||||||
|
AND products_skipped = 0
|
||||||
|
ORDER BY completed_at DESC NULLS LAST LIMIT 1`, feedID).
|
||||||
|
Scan(&prev.ContentHash, &prev.Total, &prev.Skipped)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return "", nil
|
return syncedSourceSummary{}, nil
|
||||||
}
|
}
|
||||||
if err != nil {
|
return prev, err
|
||||||
return "", err
|
|
||||||
}
|
}
|
||||||
if hash == nil {
|
|
||||||
return "", nil
|
// syncSkipDiagnostics is persisted in feed_sync_jobs.error and displayed in Sync History.
|
||||||
|
// It intentionally reports source columns and row numbers, not individual product data.
|
||||||
|
func syncSkipDiagnostics(stats syncStats) string {
|
||||||
|
if stats.Skipped == 0 {
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
return *hash, nil
|
msg := strconv.Itoa(stats.Skipped) + " of " + strconv.Itoa(stats.Total) + " product rows skipped."
|
||||||
|
if stats.MissingGTIN > 0 {
|
||||||
|
msg += " " + strconv.Itoa(stats.MissingGTIN) + " rows have no recognized GTIN."
|
||||||
|
msg += " Map an identifier column to GTIN or supply a non-empty gtin/ean/upc/barcode column."
|
||||||
|
if len(stats.MissingRows) > 0 {
|
||||||
|
rows := make([]string, len(stats.MissingRows))
|
||||||
|
for i, row := range stats.MissingRows {
|
||||||
|
rows[i] = strconv.Itoa(row)
|
||||||
|
}
|
||||||
|
msg += " Example data rows: " + strings.Join(rows, ", ") + "."
|
||||||
|
}
|
||||||
|
if len(stats.SourceColumns) > 0 {
|
||||||
|
cols := stats.SourceColumns
|
||||||
|
if len(cols) > 12 {
|
||||||
|
cols = cols[:12]
|
||||||
|
}
|
||||||
|
msg += " Source columns include: " + strings.Join(cols, ", ") + "."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if other := stats.Skipped - stats.MissingGTIN; other > 0 {
|
||||||
|
msg += " " + strconv.Itoa(other) + " rows could not be serialized for import."
|
||||||
|
}
|
||||||
|
return msg
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) loadMappingsRaw(ctx context.Context, companyID, feedID uuid.UUID) (any, error) {
|
func (s *Service) loadMappingsRaw(ctx context.Context, companyID, feedID uuid.UUID) (any, error) {
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Regression: Excel/UTF-8-SIG CSV headers include a BOM on the first column.
|
||||||
|
// This silently skipped every Grohe row (127/127) when the first column was gtin.
|
||||||
|
func TestParseCSVStripsUTF8BOMFromGTIN(t *testing.T) {
|
||||||
|
csvBody := "\ufeffgtin,sku,title\r\n4005176980640,32917KS0,Grohe Minta\r\n4005176980641,32917KS1,Grohe Test\r\n"
|
||||||
|
mappings := []FieldMapping{
|
||||||
|
{Source: "gtin", Target: "gtin"},
|
||||||
|
{Source: "title", Target: "title"},
|
||||||
|
}
|
||||||
|
var got []string
|
||||||
|
count, err := parseCSV(strings.NewReader(csvBody), func(row feedRow) error {
|
||||||
|
if _, hasBOM := row["\ufeffgtin"]; hasBOM {
|
||||||
|
t.Fatal("BOM was not removed from first CSV header")
|
||||||
|
}
|
||||||
|
mapped, gtin := applyMappings(row, mappings)
|
||||||
|
if mapped["title"] == "" || gtin == "" {
|
||||||
|
t.Fatalf("missing recognized mapped values: %v, gtin %q", mapped, gtin)
|
||||||
|
}
|
||||||
|
got = append(got, gtin)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil || count != 2 || len(got) != 2 || got[0] != "4005176980640" {
|
||||||
|
t.Fatalf("count=%d gtins=%v err=%v", count, got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCSVLegacySavedBOMMappingIsRecognized(t *testing.T) {
|
||||||
|
mapping := []FieldMapping{{Source: "\ufeffgtin", Target: "gtin"}}
|
||||||
|
_, err := parseCSV(strings.NewReader("\ufeffgtin,title\n4005176980640,Grohe\n"), func(row feedRow) error {
|
||||||
|
_, gtin := applyMappings(row, mapping)
|
||||||
|
if gtin != "4005176980640" {
|
||||||
|
t.Fatalf("legacy BOM mapping could not read normalized header: %q", gtin)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExtractCSVSchemaStripsUTF8BOM(t *testing.T) {
|
||||||
|
fields, rows, _, err := extractCSVSchema([]byte("\ufeffgtin,title\n4005176980640,Grohe\n"))
|
||||||
|
if err != nil || rows != 1 {
|
||||||
|
t.Fatalf("rows=%d err=%v", rows, err)
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, field := range fields {
|
||||||
|
if strings.Contains(field.Path, "\ufeff") {
|
||||||
|
t.Fatalf("schema still exposes BOM: %q", field.Path)
|
||||||
|
}
|
||||||
|
if field.Path == "gtin" {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatalf("GTIN absent from schema fields: %v", fields)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncSkipDiagnosticsExplainsEmptyImport(t *testing.T) {
|
||||||
|
stats := syncStats{Total: 127, Skipped: 127, MissingGTIN: 127,
|
||||||
|
MissingRows: []int{1, 2, 3}, SourceColumns: []string{"sku", "title"}}
|
||||||
|
msg := syncSkipDiagnostics(stats)
|
||||||
|
for _, term := range []string{"127 of 127", "GTIN", "sku", "title", "1, 2, 3"} {
|
||||||
|
if !strings.Contains(msg, term) {
|
||||||
|
t.Fatalf("diagnostic %q missing %q", msg, term)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if syncSkipDiagnostics(syncStats{Total: 2}) != "" {
|
||||||
|
t.Fatal("no skipped rows should have no warning")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -290,16 +290,11 @@ func TestUpsertSQLIsSetBased(t *testing.T) {
|
|||||||
"update": upsertSQLUpdateSet,
|
"update": upsertSQLUpdateSet,
|
||||||
} {
|
} {
|
||||||
lower := strings.ToLower(sql)
|
lower := strings.ToLower(sql)
|
||||||
switch name {
|
// Touch also joins through unnest now: it refreshes the owning feed and the
|
||||||
case "insert", "update":
|
// per-field sources of every touched row in one statement.
|
||||||
if !strings.Contains(lower, "unnest(") {
|
if !strings.Contains(lower, "unnest(") {
|
||||||
t.Fatalf("%s missing unnest: %s", name, sql)
|
t.Fatalf("%s missing unnest: %s", name, sql)
|
||||||
}
|
}
|
||||||
case "touch":
|
|
||||||
if !strings.Contains(lower, "any(") {
|
|
||||||
t.Fatalf("touch missing ANY: %s", sql)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if strings.Contains(lower, "values ($1") {
|
if strings.Contains(lower, "values ($1") {
|
||||||
t.Fatalf("%s still per-row VALUES form", name)
|
t.Fatalf("%s still per-row VALUES form", name)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFeedLocaleSameProductIndependentMappings(t *testing.T) {
|
||||||
|
id := uuid.MustParse("12345678-1234-1234-1234-123456789abc")
|
||||||
|
old := map[string]existingProduct{"100": {
|
||||||
|
ID: id,
|
||||||
|
MappedData: []byte(`{"name":"English name"}`),
|
||||||
|
SourceLocalizations: []byte(`{"en":{"name":"English name"},"sl":{"name":"Slovensko ime"}}`),
|
||||||
|
}}
|
||||||
|
same := []pendingProduct{{GTIN: "100", RawData: map[string]string{"EAN": "100"}, MappedData: map[string]any{"name": "Slovensko ime"}}}
|
||||||
|
ops, skip := classifyUpsertOps(same, old, syncLocale{code: "sl", primary: false})
|
||||||
|
if skip != 0 || len(ops) != 1 || ops[0].kind != upsertOpTouch {
|
||||||
|
t.Fatalf("unchanged localized product should be touched, got %+v, skipped %d", ops, skip)
|
||||||
|
}
|
||||||
|
changed := []pendingProduct{{GTIN: "100", RawData: map[string]string{"EAN": "100"}, MappedData: map[string]any{"name": "Novejše ime"}}}
|
||||||
|
ops, skip = classifyUpsertOps(changed, old, syncLocale{code: "sl", primary: false})
|
||||||
|
if skip != 0 || len(ops) != 1 || ops[0].kind != upsertOpUpdate {
|
||||||
|
t.Fatalf("changed localized product should update, got %+v, skipped %d", ops, skip)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
const emos = `<?xml version="1.0"?><SHOP><SHOPITEM><PRODUCT>Ročna LED svetilka 9 LED 3×AAA</PRODUCT><PRODUCTNO>1440093109</PRODUCTNO><EAN>8595025395184</EAN><CATEGORY>Svetilke|Ročne svetilke</CATEGORY><DESCRIPTION>barva: mešanica barv|napajanje: 3× AAA|svetlobni tok: 50 lm</DESCRIPTION><DESCRIPTION_BASIC><p>Praktična LED svetilka</p></DESCRIPTION_BASIC><PARAMS><PARAM><PARAM_NAME>barva</PARAM_NAME><VAL>mešanica barv</VAL><ORDER>12</ORDER></PARAM><PARAM><PARAM_NAME>napajanje</PARAM_NAME><VAL>3× AAA</VAL></PARAM><PARAM><PARAM_NAME>vir svetlobe</PARAM_NAME><VAL>9× LED</VAL></PARAM></PARAMS><IMGURL>https://example.com/1.jpg</IMGURL><IMGURL_ALTERNATIVE_01>https://example.com/2.jpg</IMGURL_ALTERNATIVE_01></SHOPITEM></SHOP>`
|
||||||
|
|
||||||
|
func TestV10EMOSItemAndAttrs(t *testing.T) {
|
||||||
|
var got feedRow
|
||||||
|
n, e := parseXMLItems(strings.NewReader(emos), "", func(r feedRow) error { got = r; return nil })
|
||||||
|
if e != nil || n != 1 {
|
||||||
|
t.Fatalf("parse n=%d err=%v", n, e)
|
||||||
|
}
|
||||||
|
for k, v := range map[string]string{"PRODUCT": "Ročna LED svetilka 9 LED 3×AAA", "EAN": "8595025395184", "PARAMS/barva": "mešanica barv", "PARAMS/napajanje": "3× AAA", "PARAMS/vir_svetlobe": "9× LED", "DESCRIPTION/svetlobni_tok": "50 lm", "ADDITIONAL_IMAGE_URLS": "https://example.com/2.jpg"} {
|
||||||
|
if got[k] != v {
|
||||||
|
t.Errorf("%s=%q want %q", k, got[k], v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestV10NestedJSONWrappedData(t *testing.T) {
|
||||||
|
raw := `{"data":{"products":[{"name":"Demo 1","ean":"1234567890123","attributes":[{"name":"color","value":"green"}]},{"name":"Demo 2","ean":"1234567890999"}]},"page":1}`
|
||||||
|
var rows []feedRow
|
||||||
|
n, e := parseJSONItems(strings.NewReader(raw), "", func(r feedRow) error { rows = append(rows, r); return nil })
|
||||||
|
if e != nil || n != 2 {
|
||||||
|
t.Fatalf("parse n=%d err=%v", n, e)
|
||||||
|
}
|
||||||
|
if rows[0]["attributes/color"] != "green" {
|
||||||
|
t.Errorf("nested attrs lost: %v", rows[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestV10JSONRootAndData(t *testing.T) {
|
||||||
|
for _, raw := range []string{`[{"ean":"1"},{"ean":"2"}]`, `{"data":[{"ean":"1"},{"ean":"2"}]}`} {
|
||||||
|
n, e := parseJSONItems(strings.NewReader(raw), "", func(r feedRow) error { return nil })
|
||||||
|
if e != nil || n != 2 {
|
||||||
|
t.Fatalf("input=%s got n=%d err=%v", raw, n, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestV10PartialPreviewJSONGuess(t *testing.T) {
|
||||||
|
x := []byte(`{"data":{"products":[{"EAN":"123","sku":"demo"},`)
|
||||||
|
p := guessJSONItemPath(x)
|
||||||
|
if p != "products" {
|
||||||
|
t.Fatalf("guess=%q", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -116,13 +116,16 @@ func (s *Server) handleAdminListAICalls(w http.ResponseWriter, r *http.Request)
|
|||||||
var companyID, companyName, userID, userEmail, jobID, rawProductID string
|
var companyID, companyName, userID, userEmail, jobID, rawProductID string
|
||||||
var role, providerMode, model, callErr, finishReason string
|
var role, providerMode, model, callErr, finishReason string
|
||||||
var promptTokens, completionTokens, totalTokens, durationMS int
|
var promptTokens, completionTokens, totalTokens, durationMS int
|
||||||
|
var cachedTokens *int
|
||||||
|
var costMicros *int64
|
||||||
var createdAt time.Time
|
var createdAt time.Time
|
||||||
var sysLen, userLen, respLen int
|
var sysLen, userLen, respLen int
|
||||||
var userPreview, respPreview string
|
var userPreview, respPreview string
|
||||||
if err := rows.Scan(&id, &companyID, &companyName, &userID, &userEmail,
|
if err := rows.Scan(&id, &companyID, &companyName, &userID, &userEmail,
|
||||||
&jobID, &rawProductID, &role, &providerMode, &model, &callErr, &finishReason,
|
&jobID, &rawProductID, &role, &providerMode, &model, &callErr, &finishReason,
|
||||||
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt,
|
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt,
|
||||||
&sysLen, &userLen, &respLen, &userPreview, &respPreview); err != nil {
|
&sysLen, &userLen, &respLen, &userPreview, &respPreview,
|
||||||
|
&cachedTokens, &costMicros); err != nil {
|
||||||
Error(w, http.StatusInternalServerError, "scan ai calls failed")
|
Error(w, http.StatusInternalServerError, "scan ai calls failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -148,6 +151,8 @@ func (s *Server) handleAdminListAICalls(w http.ResponseWriter, r *http.Request)
|
|||||||
"prompt_tokens": promptTokens,
|
"prompt_tokens": promptTokens,
|
||||||
"completion_tokens": completionTokens,
|
"completion_tokens": completionTokens,
|
||||||
"total_tokens": totalTokens,
|
"total_tokens": totalTokens,
|
||||||
|
"cached_prompt_tokens": cachedTokens,
|
||||||
|
"cost_micros": costMicros,
|
||||||
"duration_ms": durationMS,
|
"duration_ms": durationMS,
|
||||||
"created_at": createdAt,
|
"created_at": createdAt,
|
||||||
"system_length": sysLen,
|
"system_length": sysLen,
|
||||||
@@ -187,7 +192,8 @@ func adminAICallsListSQL(where string, limitArg int) string {
|
|||||||
l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at,
|
l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at,
|
||||||
length(l.system_prompt), length(l.user_prompt), length(l.response_text),
|
length(l.system_prompt), length(l.user_prompt), length(l.response_text),
|
||||||
left(l.user_prompt, ` + preview + `),
|
left(l.user_prompt, ` + preview + `),
|
||||||
left(l.response_text, ` + preview + `)
|
left(l.response_text, ` + preview + `),
|
||||||
|
l.cached_prompt_tokens, l.cost_micros
|
||||||
FROM ai_call_logs l
|
FROM ai_call_logs l
|
||||||
LEFT JOIN companies c ON c.id = l.company_id
|
LEFT JOIN companies c ON c.id = l.company_id
|
||||||
LEFT JOIN users u ON u.id = l.user_id
|
LEFT JOIN users u ON u.id = l.user_id
|
||||||
@@ -212,6 +218,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) {
|
|||||||
var role, providerMode, model, callErr, finishReason string
|
var role, providerMode, model, callErr, finishReason string
|
||||||
var systemPrompt, userPrompt, responseText string
|
var systemPrompt, userPrompt, responseText string
|
||||||
var promptTokens, completionTokens, totalTokens, durationMS int
|
var promptTokens, completionTokens, totalTokens, durationMS int
|
||||||
|
var cachedTokens *int
|
||||||
|
var costMicros *int64
|
||||||
var createdAt time.Time
|
var createdAt time.Time
|
||||||
err = s.Pool.QueryRow(ctx, `
|
err = s.Pool.QueryRow(ctx, `
|
||||||
SELECT COALESCE(l.company_id::text, ''), COALESCE(c.name, ''),
|
SELECT COALESCE(l.company_id::text, ''), COALESCE(c.name, ''),
|
||||||
@@ -219,7 +227,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) {
|
|||||||
COALESCE(l.job_id::text, ''), COALESCE(l.raw_product_id::text, ''),
|
COALESCE(l.job_id::text, ''), COALESCE(l.raw_product_id::text, ''),
|
||||||
l.role, l.provider_mode, l.model, l.error, l.finish_reason,
|
l.role, l.provider_mode, l.model, l.error, l.finish_reason,
|
||||||
l.system_prompt, l.user_prompt, l.response_text,
|
l.system_prompt, l.user_prompt, l.response_text,
|
||||||
l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at
|
l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at,
|
||||||
|
l.cached_prompt_tokens, l.cost_micros
|
||||||
FROM ai_call_logs l
|
FROM ai_call_logs l
|
||||||
LEFT JOIN companies c ON c.id = l.company_id
|
LEFT JOIN companies c ON c.id = l.company_id
|
||||||
LEFT JOIN users u ON u.id = l.user_id
|
LEFT JOIN users u ON u.id = l.user_id
|
||||||
@@ -227,7 +236,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) {
|
|||||||
Scan(&companyID, &companyName, &userID, &userEmail, &jobID, &rawProductID,
|
Scan(&companyID, &companyName, &userID, &userEmail, &jobID, &rawProductID,
|
||||||
&role, &providerMode, &model, &callErr, &finishReason,
|
&role, &providerMode, &model, &callErr, &finishReason,
|
||||||
&systemPrompt, &userPrompt, &responseText,
|
&systemPrompt, &userPrompt, &responseText,
|
||||||
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt)
|
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt,
|
||||||
|
&cachedTokens, &costMicros)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
// Expired rows are the common case here, so say so rather than a bare 404.
|
// Expired rows are the common case here, so say so rather than a bare 404.
|
||||||
Error(w, http.StatusNotFound, "call not found (captured calls are kept for "+
|
Error(w, http.StatusNotFound, "call not found (captured calls are kept for "+
|
||||||
@@ -263,6 +273,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) {
|
|||||||
"prompt_tokens": promptTokens,
|
"prompt_tokens": promptTokens,
|
||||||
"completion_tokens": completionTokens,
|
"completion_tokens": completionTokens,
|
||||||
"total_tokens": totalTokens,
|
"total_tokens": totalTokens,
|
||||||
|
"cached_prompt_tokens": cachedTokens,
|
||||||
|
"cost_micros": costMicros,
|
||||||
"duration_ms": durationMS,
|
"duration_ms": durationMS,
|
||||||
"created_at": createdAt,
|
"created_at": createdAt,
|
||||||
"retention_days": aiaudit.RetentionDays,
|
"retention_days": aiaudit.RetentionDays,
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exports audited AI usage by company. This is an operational cost report, NOT
|
||||||
|
// a customer invoice or the amount charged by Stripe.
|
||||||
|
func (s *Server) handleAdminExportAICosts(w http.ResponseWriter, r *http.Request) {
|
||||||
|
q := r.URL.Query()
|
||||||
|
from, to, err := adminCostRange(q.Get("from"), q.Get("to"), q.Get("days"))
|
||||||
|
if err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
args := []any{from, to}
|
||||||
|
where := "day >= $1 AND day <= $2"
|
||||||
|
if raw := strings.TrimSpace(q.Get("company_id")); raw != "" {
|
||||||
|
cid, err := uuid.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "invalid company_id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
args = append(args, cid)
|
||||||
|
where += " AND company_id = $3"
|
||||||
|
}
|
||||||
|
result, err := s.scanCostGroup(r.Context(), costGroupCompany, where, args)
|
||||||
|
if err != nil {
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "could not export AI costs", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-ai-usage-costs.csv"`)
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
out, err := newUTF8CSVWriter(w)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = out.Write([]string{"from", "to", "company_id", "company", "calls", "failed_calls", "input_tokens", "cached_input_tokens", "output_tokens", "total_tokens", "provider_cost_usd", "notice"})
|
||||||
|
v := func(row map[string]any, key string) string { return strconv.FormatInt(int64(row[key].(int64)), 10) }
|
||||||
|
for _, row := range result {
|
||||||
|
cost := float64(row["cost_micros"].(int64)) / 1000000.0
|
||||||
|
_ = out.Write([]string{from.Format("2006-01-02"), to.Format("2006-01-02"), row["id"].(string), row["label"].(string),
|
||||||
|
v(row, "calls"), v(row, "failed_calls"), v(row, "prompt_tokens"), v(row, "cached_prompt_tokens"),
|
||||||
|
v(row, "completion_tokens"), v(row, "total_tokens"), strconv.FormatFloat(cost, 'f', 6, 64),
|
||||||
|
"Provider operating cost in USD; NOT client revenue, Stripe invoice, or payable total"})
|
||||||
|
}
|
||||||
|
out.Flush()
|
||||||
|
}
|
||||||
@@ -172,7 +172,7 @@ func (s *Server) scanCostGroup(ctx context.Context, group costGroup, whereSQL st
|
|||||||
COALESCE(sum(u.cost_micros),0)
|
COALESCE(sum(u.cost_micros),0)
|
||||||
FROM ai_usage_daily u
|
FROM ai_usage_daily u
|
||||||
LEFT JOIN companies c ON c.id = u.company_id
|
LEFT JOIN companies c ON c.id = u.company_id
|
||||||
WHERE ` + whereSQL + `
|
WHERE ` + strings.ReplaceAll(whereSQL, "company_id =", "u.company_id =") + `
|
||||||
GROUP BY u.company_id, c.name
|
GROUP BY u.company_id, c.name
|
||||||
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
||||||
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
||||||
@@ -186,7 +186,7 @@ func (s *Server) scanCostGroup(ctx context.Context, group costGroup, whereSQL st
|
|||||||
FROM ai_usage_daily u
|
FROM ai_usage_daily u
|
||||||
LEFT JOIN users usr ON usr.id = u.user_id
|
LEFT JOIN users usr ON usr.id = u.user_id
|
||||||
LEFT JOIN companies c ON c.id = u.company_id
|
LEFT JOIN companies c ON c.id = u.company_id
|
||||||
WHERE ` + whereSQL + `
|
WHERE ` + strings.ReplaceAll(whereSQL, "company_id =", "u.company_id =") + `
|
||||||
GROUP BY u.user_id, usr.email, u.company_id, c.name
|
GROUP BY u.user_id, usr.email, u.company_id, c.name
|
||||||
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
||||||
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
||||||
@@ -198,7 +198,7 @@ func (s *Server) scanCostGroup(ctx context.Context, group costGroup, whereSQL st
|
|||||||
COALESCE(sum(u.completion_tokens),0), COALESCE(sum(u.total_tokens),0),
|
COALESCE(sum(u.completion_tokens),0), COALESCE(sum(u.total_tokens),0),
|
||||||
COALESCE(sum(u.cost_micros),0)
|
COALESCE(sum(u.cost_micros),0)
|
||||||
FROM ai_usage_daily u
|
FROM ai_usage_daily u
|
||||||
WHERE ` + whereSQL + `
|
WHERE ` + strings.ReplaceAll(whereSQL, "company_id =", "u.company_id =") + `
|
||||||
GROUP BY u.model
|
GROUP BY u.model
|
||||||
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
||||||
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
||||||
|
|||||||
@@ -151,12 +151,15 @@ func (s *Server) handleAdminAnalytics(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
tokenByDay := map[string]adminDayPoint{}
|
tokenByDay := map[string]adminDayPoint{}
|
||||||
tokRows, err := s.Pool.Query(ctx, `
|
tokRows, err := s.Pool.Query(ctx, `
|
||||||
SELECT (created_at AT TIME ZONE 'UTC')::date AS d,
|
WITH tokens AS (
|
||||||
COALESCE(SUM(COALESCE(total_tokens, 0)), 0)::bigint,
|
SELECT day AS d, COALESCE(SUM(total_tokens),0)::bigint AS tok
|
||||||
COUNT(*)::bigint
|
FROM ai_usage_daily WHERE day >= $1::date GROUP BY 1
|
||||||
FROM processed_products
|
), products AS (
|
||||||
WHERE created_at >= $1
|
SELECT (created_at AT TIME ZONE 'UTC')::date AS d, COUNT(*)::bigint AS cnt
|
||||||
GROUP BY 1
|
FROM processed_products WHERE created_at >= $1 GROUP BY 1
|
||||||
|
)
|
||||||
|
SELECT COALESCE(t.d,p.d) AS d, COALESCE(t.tok,0)::bigint, COALESCE(p.cnt,0)::bigint
|
||||||
|
FROM tokens t FULL OUTER JOIN products p ON t.d=p.d
|
||||||
ORDER BY 1`, since)
|
ORDER BY 1`, since)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Error(w, http.StatusInternalServerError, "analytics token series failed")
|
Error(w, http.StatusInternalServerError, "analytics token series failed")
|
||||||
@@ -326,7 +329,7 @@ func (s *Server) handleAdminAnalytics(w http.ResponseWriter, r *http.Request) {
|
|||||||
"providers": providers,
|
"providers": providers,
|
||||||
"tokens_by_provider_detail": providerDetail,
|
"tokens_by_provider_detail": providerDetail,
|
||||||
"notes": []string{
|
"notes": []string{
|
||||||
"Tokens come from processed_products.total_tokens (LLM usage recorded per product).",
|
"Tokens come from the durable ai_usage_daily call ledger (input + output), including multiple calls per product.",
|
||||||
"Provider classes use processed_products.ai_provider_mode: internal | popular:<name> | custom (blank/unknown rolled into the internal card).",
|
"Provider classes use processed_products.ai_provider_mode: internal | popular:<name> | custom (blank/unknown rolled into the internal card).",
|
||||||
"Job tokens use processing_jobs.estimated_tokens (running tally during jobs).",
|
"Job tokens use processing_jobs.estimated_tokens (running tally during jobs).",
|
||||||
"Jobs stuck = status running with updated_at older than 2 hours (same threshold as diagnostics).",
|
"Jobs stuck = status running with updated_at older than 2 hours (same threshold as diagnostics).",
|
||||||
@@ -353,12 +356,12 @@ func (s *Server) loadAdminAnalyticsSummary(ctx context.Context, since time.Time)
|
|||||||
(SELECT COUNT(*)::bigint FROM companies WHERE created_at >= $1),
|
(SELECT COUNT(*)::bigint FROM companies WHERE created_at >= $1),
|
||||||
(SELECT COALESCE(SUM(total_credits), 0)::bigint FROM credit_balances),
|
(SELECT COALESCE(SUM(total_credits), 0)::bigint FROM credit_balances),
|
||||||
(SELECT COALESCE(SUM(used_credits), 0)::bigint FROM credit_balances),
|
(SELECT COALESCE(SUM(used_credits), 0)::bigint FROM credit_balances),
|
||||||
(SELECT COALESCE(SUM(COALESCE(total_tokens, 0)), 0)::bigint FROM processed_products),
|
(SELECT COALESCE(SUM(total_tokens), 0)::bigint FROM ai_usage_daily),
|
||||||
(SELECT COUNT(*)::bigint FROM processed_products),
|
(SELECT COUNT(*)::bigint FROM processed_products),
|
||||||
(SELECT COUNT(*)::bigint FROM raw_products),
|
(SELECT COUNT(*)::bigint FROM raw_products),
|
||||||
(SELECT COUNT(*)::bigint FROM input_feeds),
|
(SELECT COUNT(*)::bigint FROM input_feeds),
|
||||||
(SELECT COUNT(*)::bigint FROM export_feeds),
|
(SELECT COUNT(*)::bigint FROM export_feeds),
|
||||||
(SELECT COALESCE(SUM(COALESCE(total_tokens, 0)), 0)::bigint FROM processed_products WHERE created_at >= $1),
|
(SELECT COALESCE(SUM(total_tokens), 0)::bigint FROM ai_usage_daily WHERE day >= $1::date),
|
||||||
(SELECT COUNT(*)::bigint FROM processing_jobs WHERE created_at >= $1 AND status = 'failed'),
|
(SELECT COUNT(*)::bigint FROM processing_jobs WHERE created_at >= $1 AND status = 'failed'),
|
||||||
(SELECT COUNT(*)::bigint FROM processing_jobs WHERE created_at >= $1 AND status = 'completed'),
|
(SELECT COUNT(*)::bigint FROM processing_jobs WHERE created_at >= $1 AND status = 'completed'),
|
||||||
(SELECT COUNT(*)::bigint FROM processing_jobs
|
(SELECT COUNT(*)::bigint FROM processing_jobs
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Platform-admin export of actual Stripe invoice amounts (not estimated usage).
|
||||||
|
// Scope must be a single company; customer IDs are resolved server-side.
|
||||||
|
func (s *Server) handleAdminExportCompanyInvoices(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := uuid.Parse(strings.TrimSpace(r.URL.Query().Get("company_id")))
|
||||||
|
if err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "company_id is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows, err := s.stripeSvc().ListCompanyInvoices(r.Context(), id)
|
||||||
|
if err != nil {
|
||||||
|
LogAndError(w, http.StatusBadGateway, "could not export Stripe invoices", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-stripe-invoices.csv"`)
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
out, err := newUTF8CSVWriter(w)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = out.Write([]string{"company_id", "invoice_id", "number", "status", "currency", "created_unix", "amount_due_minor", "amount_paid_minor", "amount_remaining_minor", "hosted_invoice_url", "invoice_pdf"})
|
||||||
|
for _, row := range rows {
|
||||||
|
_ = out.Write([]string{id.String(), row.ID, row.Number, row.Status, row.Currency,
|
||||||
|
strconv.FormatInt(row.Created, 10), strconv.FormatInt(row.AmountDue, 10),
|
||||||
|
strconv.FormatInt(row.AmountPaid, 10), strconv.FormatInt(row.AmountRemaining, 10),
|
||||||
|
row.HostedInvoiceURL, row.InvoicePDF})
|
||||||
|
}
|
||||||
|
out.Flush()
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/platformsettings"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var editableCostFeatures = map[string]bool{
|
||||||
|
"title_ai": true,
|
||||||
|
"description_ai": true,
|
||||||
|
"seo_meta_ai": true,
|
||||||
|
"product_ai": true, // presence of a plan rule enables per-product pricing
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rows, err := s.Pool.Query(r.Context(), `
|
||||||
|
SELECT 'default', '', feature_name, cost_per_unit::text FROM processing_costs WHERE is_active = true AND feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai')
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'plan', plan_id::text, feature_name, cost_per_unit::text FROM plan_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai')
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'company', company_id::text, feature_name, cost_per_unit::text FROM company_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai')
|
||||||
|
ORDER BY 1, 2, 3`)
|
||||||
|
if err != nil {
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "could not load processing costs", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make([]map[string]any, 0, 16)
|
||||||
|
for rows.Next() {
|
||||||
|
var scope, id, feature, costText string
|
||||||
|
if err := rows.Scan(&scope, &id, &feature, &costText); err != nil {
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cost, parseErr := strconv.ParseFloat(costText, 64)
|
||||||
|
if parseErr != nil || math.IsNaN(cost) || math.IsInf(cost, 0) {
|
||||||
|
if parseErr == nil {
|
||||||
|
parseErr = errors.New("non-finite cost value")
|
||||||
|
}
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "invalid stored processing cost", parseErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out = append(out, map[string]any{"scope": scope, "id": id, "feature": feature, "cost_per_unit": cost})
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "could not read processing costs", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
JSON(w, http.StatusOK, map[string]any{"rules": out, "notes": "Company overrides take priority over plan rules. Changes affect future debits only."})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body struct {
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Feature string `json:"feature"`
|
||||||
|
Cost *float64 `json:"cost_per_unit"` // null removes an override; cannot remove global rule
|
||||||
|
}
|
||||||
|
if err := DecodeJSON(r, &body); err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "invalid json")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body.Scope = strings.TrimSpace(strings.ToLower(body.Scope))
|
||||||
|
body.Feature = strings.TrimSpace(body.Feature)
|
||||||
|
if !editableCostFeatures[body.Feature] || (body.Cost != nil && (math.IsNaN(*body.Cost) || math.IsInf(*body.Cost, 0) || *body.Cost < 0 || *body.Cost > 1000000 || math.Abs(*body.Cost*10000-math.Round(*body.Cost*10000)) > 0.000001)) {
|
||||||
|
Error(w, http.StatusBadRequest, "invalid feature or credit cost")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx := r.Context()
|
||||||
|
var err error
|
||||||
|
switch body.Scope {
|
||||||
|
case "company":
|
||||||
|
id, parseErr := uuid.Parse(body.ID)
|
||||||
|
if parseErr != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "invalid company id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if body.Cost == nil {
|
||||||
|
_, err = s.Pool.Exec(ctx, `DELETE FROM company_processing_costs WHERE company_id = $1 AND feature_name = $2`, id, body.Feature)
|
||||||
|
} else {
|
||||||
|
_, err = s.Pool.Exec(ctx, `INSERT INTO company_processing_costs (company_id,feature_name,cost_per_unit) VALUES ($1,$2,$3)
|
||||||
|
ON CONFLICT(company_id,feature_name) DO UPDATE SET cost_per_unit=EXCLUDED.cost_per_unit,updated_at=now()`, id, body.Feature, *body.Cost)
|
||||||
|
}
|
||||||
|
case "plan":
|
||||||
|
id, parseErr := strconv.ParseInt(body.ID, 10, 64)
|
||||||
|
if parseErr != nil || id <= 0 {
|
||||||
|
Error(w, http.StatusBadRequest, "invalid plan id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if body.Cost == nil {
|
||||||
|
_, err = s.Pool.Exec(ctx, `DELETE FROM plan_processing_costs WHERE plan_id = $1 AND feature_name = $2`, id, body.Feature)
|
||||||
|
} else {
|
||||||
|
_, err = s.Pool.Exec(ctx, `INSERT INTO plan_processing_costs (plan_id,feature_name,cost_per_unit) VALUES ($1,$2,$3)
|
||||||
|
ON CONFLICT(plan_id,feature_name) DO UPDATE SET cost_per_unit=EXCLUDED.cost_per_unit,updated_at=now()`, id, body.Feature, *body.Cost)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
Error(w, http.StatusBadRequest, "scope must be company or plan")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
LogAndError(w, http.StatusBadRequest, "could not save processing cost", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
JSON(w, http.StatusOK, map[string]any{"status": "ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleCompanyContentCosts returns effective plan/company rates to the dashboard.
|
||||||
|
// Never disclose other companies' pricing overrides.
|
||||||
|
func (s *Server) handleCompanyContentCosts(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cid, ok := CompanyIDFromContext(r.Context())
|
||||||
|
if !ok || cid == uuid.Nil {
|
||||||
|
Error(w, http.StatusUnauthorized, "unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Flat charge for one product in one selected language. Never derive a
|
||||||
|
// displayed estimate from per-output admin rates or the EUR/credit value.
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
JSON(w, http.StatusOK, map[string]any{
|
||||||
|
"mode": "product",
|
||||||
|
"credits": map[string]float64{"product": 1},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Monetary credit valuation is an admin reference rate. Stripe invoices, pack
|
||||||
|
// checkout prices and historic wallet ledger values are not changed by it.
|
||||||
|
const creditValueEURSetting = platformsettings.KeyBillingReferenceEURPerCredit
|
||||||
|
|
||||||
|
func (s *Server) handleAdminCreditValueEUR(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if s.PlatformSettings == nil {
|
||||||
|
Error(w, http.StatusServiceUnavailable, "platform settings unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == http.MethodGet {
|
||||||
|
saved, ok, err := s.PlatformSettings.GetKV(r.Context(), creditValueEURSetting)
|
||||||
|
if err != nil {
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "unable to load credit valuation", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var amount any
|
||||||
|
if ok && strings.TrimSpace(saved) != "" {
|
||||||
|
parsed, err := strconv.ParseFloat(saved, 64)
|
||||||
|
if err != nil {
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "invalid stored credit valuation", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
amount = parsed
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
JSON(w, http.StatusOK, map[string]any{"eur_per_credit": amount, "currency": "EUR", "note": "Reference valuation only; actual customer charges follow Stripe invoices and purchased credit pack prices."})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != http.MethodPut {
|
||||||
|
Error(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
Value *float64 `json:"eur_per_credit"`
|
||||||
|
}
|
||||||
|
if err := DecodeJSON(r, &body); err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "invalid json")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if body.Value == nil || math.IsNaN(*body.Value) || math.IsInf(*body.Value, 0) || *body.Value < 0 || *body.Value > 10000 || math.Abs(*body.Value*1000000-math.Round(*body.Value*1000000)) > 0.000001 {
|
||||||
|
Error(w, http.StatusBadRequest, "EUR per credit must be between 0 and 10000 with up to six decimals")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.PlatformSettings.SetKV(r.Context(), creditValueEURSetting, strconv.FormatFloat(*body.Value, 'f', -1, 64)); err != nil {
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "unable to save credit valuation", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
JSON(w, http.StatusOK, map[string]any{"status": "ok", "eur_per_credit": *body.Value})
|
||||||
|
}
|
||||||
@@ -61,7 +61,7 @@ func (s *Server) handleAdminSyncStripeCreditPacks(w http.ResponseWriter, r *http
|
|||||||
"product_id": row.ProductID,
|
"product_id": row.ProductID,
|
||||||
"price_id": row.PriceID,
|
"price_id": row.PriceID,
|
||||||
"credits": row.Credits,
|
"credits": row.Credits,
|
||||||
"price_usd": row.PriceUSD,
|
"price_eur": row.PriceEUR,
|
||||||
"created": row.Created,
|
"created": row.Created,
|
||||||
"settings_key": key,
|
"settings_key": key,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -155,3 +155,19 @@ func (s *Server) handleRunBillingCycles(w http.ResponseWriter, r *http.Request)
|
|||||||
}
|
}
|
||||||
JSON(w, http.StatusOK, out)
|
JSON(w, http.StatusOK, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// handleListBillingInvoices lists genuine Stripe invoices for the active company.
|
||||||
|
// Private Stripe payment and PDF links are only accessible to company owners.
|
||||||
|
func (s *Server) handleListBillingInvoices(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !s.allowCompanyOwnerOrPlatform(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cid, _ := CompanyIDFromContext(r.Context())
|
||||||
|
invoices, err := s.stripeSvc().ListCompanyInvoices(r.Context(), cid)
|
||||||
|
if err != nil {
|
||||||
|
LogAndError(w, http.StatusBadGateway, "could not load invoices", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
JSON(w, http.StatusOK, map[string]any{"invoices": invoices, "source": "stripe"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Usage statements are informational exports, not tax invoices or payment records.
|
||||||
|
func (s *Server) handleBillingUsageExport(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cid, _ := CompanyIDFromContext(r.Context())
|
||||||
|
if cid == uuid.Nil {
|
||||||
|
Error(w, http.StatusUnauthorized, "company required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
usage, err := s.Billing.UsageSummary(r.Context(), cid, r.URL.Query().Get("range"))
|
||||||
|
if err != nil {
|
||||||
|
LogAndError(w, http.StatusInternalServerError, "could not export usage", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-usage.csv"`)
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
out, err := newUTF8CSVWriter(w)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = out.Write([]string{"company_id", "range", "metric", "value", "notes"})
|
||||||
|
rows := []struct {
|
||||||
|
label string
|
||||||
|
value float64
|
||||||
|
notes string
|
||||||
|
}{
|
||||||
|
{"ai_calls", float64(usage.AICalls), "Recorded provider calls in period"},
|
||||||
|
{"input_tokens", float64(usage.InputTokens), "Includes cached input"},
|
||||||
|
{"cached_input_tokens", float64(usage.CachedInputTokens), "Subset of input"},
|
||||||
|
{"output_tokens", float64(usage.OutputTokens), ""},
|
||||||
|
{"products_processed", float64(usage.ProductsProcessed), "Period"},
|
||||||
|
{"credits_used_wallet", usage.CreditsUsed, "All-time wallet balance, not period credits"},
|
||||||
|
{"credits_remaining", usage.CreditsRemaining, "Current wallet"},
|
||||||
|
}
|
||||||
|
for _, v := range rows {
|
||||||
|
_ = out.Write([]string{cid.String(), usage.Range, v.label, strconv.FormatFloat(v.value, 'f', -1, 64), v.notes})
|
||||||
|
}
|
||||||
|
out.Flush()
|
||||||
|
}
|
||||||
@@ -15,6 +15,15 @@ import (
|
|||||||
|
|
||||||
func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
|
||||||
cid, _ := CompanyIDFromContext(r.Context())
|
cid, _ := CompanyIDFromContext(r.Context())
|
||||||
|
ctx := r.Context()
|
||||||
|
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
|
||||||
|
parsed, err := company.ParseLanguage(lang, false)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "unsupported language")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx = catalog.WithImportLanguage(ctx, parsed)
|
||||||
|
}
|
||||||
max := maxPageLimit
|
max := maxPageLimit
|
||||||
if r.URL.Query().Get("tree") == "1" {
|
if r.URL.Query().Get("tree") == "1" {
|
||||||
max = maxTreePageLimit
|
max = maxTreePageLimit
|
||||||
@@ -25,7 +34,7 @@ func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
|
|||||||
Limit: limit,
|
Limit: limit,
|
||||||
Offset: offset,
|
Offset: offset,
|
||||||
}
|
}
|
||||||
items, total, err := s.Catalog.ListCategories(r.Context(), cid, f)
|
items, total, err := s.Catalog.ListCategories(ctx, cid, f)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Error(w, http.StatusInternalServerError, "list failed")
|
Error(w, http.StatusInternalServerError, "list failed")
|
||||||
return
|
return
|
||||||
@@ -55,12 +64,21 @@ func (s *Server) handleCreateCategory(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (s *Server) handleGetCategory(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleGetCategory(w http.ResponseWriter, r *http.Request) {
|
||||||
cid, _ := CompanyIDFromContext(r.Context())
|
cid, _ := CompanyIDFromContext(r.Context())
|
||||||
|
ctx := r.Context()
|
||||||
|
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
|
||||||
|
parsed, err := company.ParseLanguage(lang, false)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "unsupported language")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx = catalog.WithImportLanguage(ctx, parsed)
|
||||||
|
}
|
||||||
id, err := uuid.Parse(chi.URLParam(r, "id"))
|
id, err := uuid.Parse(chi.URLParam(r, "id"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Error(w, http.StatusBadRequest, "invalid id")
|
Error(w, http.StatusBadRequest, "invalid id")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
item, err := s.Catalog.GetCategory(r.Context(), cid, id)
|
item, err := s.Catalog.GetCategory(ctx, cid, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Error(w, http.StatusNotFound, "not found")
|
Error(w, http.StatusNotFound, "not found")
|
||||||
return
|
return
|
||||||
@@ -256,6 +274,15 @@ func (s *Server) handleDeleteVariable(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
|
||||||
cid, _ := CompanyIDFromContext(r.Context())
|
cid, _ := CompanyIDFromContext(r.Context())
|
||||||
|
ctx := r.Context()
|
||||||
|
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
|
||||||
|
parsed, err := company.ParseLanguage(lang, false)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "unsupported language")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx = catalog.WithImportLanguage(ctx, parsed)
|
||||||
|
}
|
||||||
limit, offset := ParseLimitOffset(r)
|
limit, offset := ParseLimitOffset(r)
|
||||||
f := catalog.ListFilter{
|
f := catalog.ListFilter{
|
||||||
Query: QuerySearch(r),
|
Query: QuerySearch(r),
|
||||||
@@ -264,7 +291,7 @@ func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
|
|||||||
RootsOnly: r.URL.Query().Get("roots") == "1",
|
RootsOnly: r.URL.Query().Get("roots") == "1",
|
||||||
ParentKey: r.URL.Query().Get("parent_key"),
|
ParentKey: r.URL.Query().Get("parent_key"),
|
||||||
}
|
}
|
||||||
items, total, err := s.Catalog.ListAttributes(r.Context(), cid, f)
|
items, total, err := s.Catalog.ListAttributes(ctx, cid, f)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Error(w, http.StatusInternalServerError, "list failed")
|
Error(w, http.StatusInternalServerError, "list failed")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -78,7 +78,9 @@ func TestStripCatalogSEOMetaIfOmitted(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
stripCatalogSEOMetaIfOmitted(processing.CompanyOmitsSEOMetaLookup(a1, "", ""), item)
|
stripCatalogSEOMetaIfOmitted(processing.CompanyOmitsSEOMetaLookup(a1, "", ""), item)
|
||||||
assertCatalogSEOOmitted(t, item)
|
if item["seo_meta_omitted"] == true || item["meta_title"] != "T" || item["meta_description"] != "D" {
|
||||||
|
t.Fatalf("A1 must retain its generated SEO metadata: %v", item)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStripCatalogSEOMetaIfOmitted_demoByName(t *testing.T) {
|
func TestStripCatalogSEOMetaIfOmitted_demoByName(t *testing.T) {
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
||||||
@@ -191,10 +196,67 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "application/json") {
|
||||||
|
var req struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
RequestHeaders map[string]string `json:"request_headers"`
|
||||||
|
Format string `json:"format"`
|
||||||
|
Language string `json:"language"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, "invalid JSON request")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.URL) == "" {
|
||||||
|
Error(w, http.StatusBadRequest, "url required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lang, err := importLanguageParam(req.Language, r.URL.Query().Get("language"), company.LoadLanguage(r.Context(), s.Pool, cid))
|
||||||
|
if err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx := catalog.WithImportLanguage(r.Context(), lang)
|
||||||
|
source, err := feeds.DownloadImportSource(r.Context(), req.URL, req.RequestHeaders, catalogMaxUpload)
|
||||||
|
if err != nil {
|
||||||
|
ClientOrLog(w, http.StatusBadRequest, "could not download import URL", err, feeds.ClientError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer source.Close()
|
||||||
|
var data io.Reader = source
|
||||||
|
if strings.EqualFold(req.Format, "json") || strings.Contains(strings.ToLower(req.URL), "json") {
|
||||||
|
data, err = catalog.JSONImportAsCSV(source, kind)
|
||||||
|
if err != nil {
|
||||||
|
ClientOrLog(w, http.StatusBadRequest, "invalid JSON import", err, catalog.ClientError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var result catalog.ImportResult
|
||||||
|
switch kind {
|
||||||
|
case "categories":
|
||||||
|
result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, data)
|
||||||
|
case "attributes":
|
||||||
|
result, err = s.Catalog.ImportAttributesCSV(ctx, cid, data)
|
||||||
|
case "products":
|
||||||
|
result, err = s.Catalog.ImportProductsCSV(ctx, cid, data, nil)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
ClientOrLog(w, http.StatusBadRequest, "import failed", err, catalog.ClientError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
JSON(w, http.StatusOK, map[string]any{"kind": kind, "import": result, "source": "url", "language": lang})
|
||||||
|
return
|
||||||
|
}
|
||||||
if err := r.ParseMultipartForm(catalogMaxUpload); err != nil {
|
if err := r.ParseMultipartForm(catalogMaxUpload); err != nil {
|
||||||
Error(w, http.StatusBadRequest, "invalid multipart form")
|
Error(w, http.StatusBadRequest, "invalid multipart form")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
lang, langErr := importLanguageParam(r.FormValue("language"), r.URL.Query().Get("language"), company.LoadLanguage(r.Context(), s.Pool, cid))
|
||||||
|
if langErr != nil {
|
||||||
|
Error(w, http.StatusBadRequest, langErr.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx := catalog.WithImportLanguage(r.Context(), lang)
|
||||||
file, header, err := r.FormFile("file")
|
file, header, err := r.FormFile("file")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Error(w, http.StatusBadRequest, "file field required")
|
Error(w, http.StatusBadRequest, "file field required")
|
||||||
@@ -228,14 +290,22 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
|||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
var result any
|
var result any
|
||||||
|
var input io.Reader = f
|
||||||
|
if strings.EqualFold(filepath.Ext(header.Filename), ".json") || strings.Contains(strings.ToLower(header.Header.Get("Content-Type")), "application/json") {
|
||||||
|
input, err = catalog.JSONImportAsCSV(f, kind)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
switch kind {
|
switch kind {
|
||||||
case "categories":
|
case "categories":
|
||||||
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, f)
|
result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, input)
|
||||||
case "attributes":
|
case "attributes":
|
||||||
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, f)
|
result, err = s.Catalog.ImportAttributesCSV(ctx, cid, input)
|
||||||
case "products":
|
case "products":
|
||||||
fid := fileID
|
fid := fileID
|
||||||
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, f, &fid)
|
result, err = s.Catalog.ImportProductsCSV(ctx, cid, input, &fid)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
public := "import failed"
|
public := "import failed"
|
||||||
@@ -261,7 +331,7 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
meta, _ = s.Catalog.UpdateFileStatus(r.Context(), cid, fileID, "completed", importMeta)
|
meta, _ = s.Catalog.UpdateFileStatus(r.Context(), cid, fileID, "completed", importMeta)
|
||||||
JSON(w, http.StatusOK, map[string]any{"file": meta, "import": result, "kind": kind})
|
JSON(w, http.StatusOK, map[string]any{"file": meta, "import": result, "kind": kind, "language": lang})
|
||||||
}
|
}
|
||||||
|
|
||||||
func importKindFromPath(r *http.Request) string {
|
func importKindFromPath(r *http.Request) string {
|
||||||
@@ -285,3 +355,16 @@ func importKindFromPath(r *http.Request) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// importLanguageParam accepts explicit dashboard/API language, otherwise uses the
|
||||||
|
// company primary language. Never silently import to an unsupported locale.
|
||||||
|
func importLanguageParam(body, query, primary string) (string, error) {
|
||||||
|
requested := strings.TrimSpace(body)
|
||||||
|
if requested == "" {
|
||||||
|
requested = strings.TrimSpace(query)
|
||||||
|
}
|
||||||
|
if requested == "" {
|
||||||
|
requested = primary
|
||||||
|
}
|
||||||
|
return company.ParseLanguage(requested, false)
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestImportLanguageParam(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
body, query, primary, want string
|
||||||
|
valid bool
|
||||||
|
}{
|
||||||
|
{"", "", "sl", "sl", true},
|
||||||
|
{"hr", "", "sl", "hr", true},
|
||||||
|
{"", "JA", "en", "ja", true},
|
||||||
|
{"xx", "", "en", "", false},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
got, err := importLanguageParam(tc.body, tc.query, tc.primary)
|
||||||
|
if (err == nil) != tc.valid || (tc.valid && got != tc.want) {
|
||||||
|
t.Fatalf("importLanguageParam(%q,%q,%q) = %q, %v", tc.body, tc.query, tc.primary, got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/csv"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newUTF8CSVWriter writes the UTF-8 signature so Excel can recognize characters
|
||||||
|
// such as č, š and ž when opening exported CSVs directly.
|
||||||
|
func newUTF8CSVWriter(w io.Writer) (*csv.Writer, error) {
|
||||||
|
if _, err := io.WriteString(w, "\ufeff"); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return csv.NewWriter(w), nil
|
||||||
|
}
|
||||||
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user