This commit is contained in:
greeneclipse committed 2026-10-15 21:22:43 +02:00
1 parent 04794aea54
commit cfd31f398c
61 files changed
+2062 -254

No files matched your search

+125 -17
View File
@@ -28,6 +28,7 @@ type CreateInput struct {
SyncIntervalMinutes int
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
Options map[string]any
RequestHeaders map[string]string
}
func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) {
@@ -120,6 +121,13 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
if opts == nil {
opts = map[string]any{}
}
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)
if itemPath == "" {
if p, ok := opts["item_path"].(string); ok {
@@ -140,10 +148,13 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
feedType = "csv"
} else {
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 feedType != "xml" && feedType != "csv" && feedType != "json" {
return nil, ClientMsg("feed_type must be xml, csv or json")
}
interval := in.SyncIntervalMinutes
if interval <= 0 && in.SyncFrequencyHours > 0 {
@@ -273,7 +284,7 @@ func mappingDocIncomplete(item map[string]any, mappingsRaw any, mappings []Field
return true
}
feedType, _ := item["feed_type"].(string)
if !isCSVFeedType(feedType) && feedItemPathHint(item, mappingsRaw) == "" {
if !isCSVFeedType(feedType) && !strings.EqualFold(feedType, "json") && feedItemPathHint(item, mappingsRaw) == "" {
return true
}
return false
@@ -303,8 +314,8 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
return nil, err
}
feedType = strings.ToLower(strings.TrimSpace(feedType))
if feedType != "" && feedType != "xml" && feedType != "csv" {
return nil, ClientMsg("feed_type must be xml or csv")
if feedType != "" && feedType != "xml" && feedType != "csv" && feedType != "json" {
return nil, ClientMsg("feed_type must be xml, csv or json")
}
interval := 0
switch v := body["sync_interval_minutes"].(type) {
@@ -325,6 +336,21 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
}
}
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, `
UPDATE input_feeds SET
name = CASE WHEN $3 <> '' THEN $3 ELSE name END,
@@ -332,13 +358,16 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
status = CASE WHEN $5 <> '' THEN $5 ELSE status 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,
options = CASE
WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text))
ELSE options
END,
options = CASE WHEN $9::text IS NULL THEN
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE options END)
WHEN $9::text = '' THEN
(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,
updated_at = now()
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)
if err != nil {
return nil, err
}
@@ -348,15 +377,94 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
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 {
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)
return err
}
// 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 err
return 0, err
}
if ct.RowsAffected() == 0 {
return ErrNotFound
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
}
return nil
// 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) {
@@ -508,8 +616,8 @@ func (s *Service) CreateExportFeed(ctx context.Context, companyID uuid.UUID, in
if format == "" {
format = "xml"
}
if format != "xml" && format != "csv" {
return nil, ClientMsg("format must be xml or csv")
if format != "xml" && format != "csv" && format != "json" {
return nil, ClientMsg("format must be xml, csv or json")
}
var src *uuid.UUID
if in.SourceFeedID != nil && *in.SourceFeedID != "" {