Files
zarinpal-analytics-backend/internal/eventcatalog/import.go

135 lines
6.5 KiB
Go

package eventcatalog
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type Import struct {
Version string `json:"version"`
CoverageStartJalaliYear int `json:"coverageStartJalaliYear"`
CoverageEndJalaliYear int `json:"coverageEndJalaliYear"`
SourceURI string `json:"sourceUri"`
SourceVersion string `json:"sourceVersion"`
SourceChecksum string `json:"sourceChecksum"`
ImportedBy string `json:"importedBy"`
Events []Event `json:"events"`
}
func ValidateImport(input Import, currentJalaliYear int) error {
if strings.TrimSpace(input.Version) == "" || strings.TrimSpace(input.SourceURI) == "" || strings.TrimSpace(input.SourceVersion) == "" || strings.TrimSpace(input.SourceChecksum) == "" || strings.TrimSpace(input.ImportedBy) == "" {
return errors.New("event catalog: import metadata is incomplete")
}
if input.CoverageStartJalaliYear > currentJalaliYear-3 || input.CoverageEndJalaliYear < currentJalaliYear+2 {
return fmt.Errorf("event catalog: coverage must include Jalali years %d through %d", currentJalaliYear-3, currentJalaliYear+2)
}
if len(input.Events) == 0 {
return errors.New("event catalog: import contains no events")
}
return ValidateEvents(input.Events)
}
func ValidateApproval(importedBy, reviewedBy string) error {
if strings.TrimSpace(reviewedBy) == "" {
return errors.New("event catalog: reviewer is required")
}
if strings.EqualFold(strings.TrimSpace(importedBy), strings.TrimSpace(reviewedBy)) {
return errors.New("event catalog: importer cannot approve the same catalog")
}
return nil
}
type Repository struct{ pool *pgxpool.Pool }
func NewRepository(pool *pgxpool.Pool) *Repository { return &Repository{pool: pool} }
func (r *Repository) ImportDraft(ctx context.Context, input Import) error {
tx, err := r.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return fmt.Errorf("starting calendar import: %w", err)
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
var versionID int64
err = tx.QueryRow(ctx, `INSERT INTO calendar_catalog_versions(version,status,coverage_start_jalali_year,coverage_end_jalali_year,source_uri,source_version,source_checksum,imported_by)
VALUES($1,'DRAFT',$2,$3,$4,$5,$6,$7) RETURNING id`, input.Version, input.CoverageStartJalaliYear, input.CoverageEndJalaliYear, input.SourceURI, input.SourceVersion, input.SourceChecksum, input.ImportedBy).Scan(&versionID)
if err != nil {
return fmt.Errorf("creating calendar catalog version: %w", err)
}
for _, event := range input.Events {
categories, err := json.Marshal(event.MerchantCategories)
if err != nil {
return fmt.Errorf("encoding calendar event categories: %w", err)
}
channels, err := json.Marshal(event.BehavioralChannels)
if err != nil {
return fmt.Errorf("encoding calendar event channels: %w", err)
}
_, err = tx.Exec(ctx, `INSERT INTO calendar_events(catalog_version_id,event_key,title_fa,title_en,start_date,end_date,recurrence_rule,event_type,tone,commercial_posture,official_holiday,source_uri,source_version,source_checksum,inclusion_rationale,geographic_scope,merchant_categories,behavioral_channels,lead_days,lag_days,relevance_bps,confidence_bps)
VALUES($1,$2,$3,nullif($4,''),$5,$6,nullif($7,''),$8,$9,$10,$11,$12,$13,nullif($14,''),$15,$16,$17,$18,$19,$20,$21,$22)`, versionID, event.ID, event.TitleFA, event.TitleEN, event.StartDate, event.EndDate, event.Recurrence, event.Type, event.Tone, event.CommercialPosture, event.OfficialHoliday, event.SourceURI, event.SourceVersion, event.SourceChecksum, event.InclusionRationale, event.GeographicScope, categories, channels, event.LeadDays, event.LagDays, event.RelevanceBPS, event.ConfidenceBPS)
if err != nil {
return fmt.Errorf("inserting calendar event %q: %w", event.ID, err)
}
}
if _, err := tx.Exec(ctx, `INSERT INTO calendar_catalog_audit(catalog_version_id,action,actor) VALUES($1,'IMPORTED',$2)`, versionID, input.ImportedBy); err != nil {
return fmt.Errorf("auditing calendar import: %w", err)
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("committing calendar import: %w", err)
}
return nil
}
func (r *Repository) Approve(ctx context.Context, version, reviewer string) error {
tx, err := r.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return fmt.Errorf("starting calendar approval: %w", err)
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
var id int64
var importedBy string
if err := tx.QueryRow(ctx, `SELECT id,imported_by FROM calendar_catalog_versions WHERE version=$1 AND status='DRAFT' FOR UPDATE`, version).Scan(&id, &importedBy); err != nil {
return fmt.Errorf("loading draft calendar catalog: %w", err)
}
if err := ValidateApproval(importedBy, reviewer); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE calendar_catalog_versions SET status='APPROVED',reviewed_by=$2,reviewed_at=now() WHERE id=$1`, id, reviewer); err != nil {
return fmt.Errorf("approving calendar catalog: %w", err)
}
if _, err := tx.Exec(ctx, `INSERT INTO calendar_catalog_audit(catalog_version_id,action,actor) VALUES($1,'APPROVED',$2)`, id, reviewer); err != nil {
return fmt.Errorf("auditing calendar approval: %w", err)
}
return tx.Commit(ctx)
}
func (r *Repository) Activate(ctx context.Context, version, actor string) error {
tx, err := r.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return fmt.Errorf("starting calendar activation: %w", err)
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended('calendar-catalog-activation',0))`); err != nil {
return fmt.Errorf("locking calendar activation: %w", err)
}
var id int64
if err := tx.QueryRow(ctx, `SELECT id FROM calendar_catalog_versions WHERE version=$1 AND status='APPROVED' FOR UPDATE`, version).Scan(&id); err != nil {
return fmt.Errorf("loading approved calendar catalog: %w", err)
}
if _, err := tx.Exec(ctx, `UPDATE calendar_catalog_versions SET status='RETIRED' WHERE status='ACTIVE'`); err != nil {
return fmt.Errorf("retiring active calendar catalog: %w", err)
}
if _, err := tx.Exec(ctx, `UPDATE calendar_catalog_versions SET status='ACTIVE',activated_at=now() WHERE id=$1`, id); err != nil {
return fmt.Errorf("activating calendar catalog: %w", err)
}
if _, err := tx.Exec(ctx, `INSERT INTO calendar_catalog_audit(catalog_version_id,action,actor) VALUES($1,'ACTIVATED',$2)`, id, actor); err != nil {
return fmt.Errorf("auditing calendar activation: %w", err)
}
return tx.Commit(ctx)
}