Merge remote-tracking branch 'origin/master'

This commit is contained in:
M_Kececi
2026-03-03 13:29:17 +03:00
parent 4805216808
commit d355ef7acd
21 changed files with 279 additions and 227 deletions

View File

@@ -1,6 +1,7 @@
package authz
import (
"bssapp-backend/auth"
"context"
"fmt"
"strings"
@@ -10,23 +11,53 @@ func BuildMSSQLPiyasaFilter(
ctx context.Context,
column string,
) string {
claims, ok := auth.GetClaimsFromContext(ctx)
if ok && claims != nil && claims.IsAdmin() {
return "1=1"
}
codes := GetPiyasaCodesFromCtx(ctx)
if len(codes) == 0 {
return "1=1"
return "1=0"
}
return BuildMSSQLPiyasaFilterWithCodes(column, codes)
}
var quoted []string
func BuildMSSQLPiyasaFilterWithCodes(column string, codes []string) string {
normalizedCol := fmt.Sprintf("UPPER(LTRIM(RTRIM(%s)))", column)
exact := BuildINClause(normalizedCol, codes)
prefixCodes := first3Codes(codes)
if len(prefixCodes) == 0 {
return exact
}
prefix := BuildINClause(
fmt.Sprintf("LEFT(%s, 3)", normalizedCol),
prefixCodes,
)
return fmt.Sprintf("(%s OR %s)", exact, prefix)
}
func first3Codes(codes []string) []string {
seen := make(map[string]struct{}, len(codes))
out := make([]string, 0, len(codes))
for _, c := range codes {
quoted = append(quoted, "'"+c+"'")
n := strings.ToUpper(strings.TrimSpace(c))
if len(n) < 3 {
continue
}
n = n[:3]
if _, ok := seen[n]; ok {
continue
}
seen[n] = struct{}{}
out = append(out, n)
}
return fmt.Sprintf(
"%s IN (%s)",
column,
strings.Join(quoted, ","),
)
return out
}

View File

@@ -3,6 +3,7 @@ package authz
import (
"database/sql"
"fmt"
"strings"
"sync"
)
@@ -35,10 +36,21 @@ func GetUserPiyasaCodes(pg *sql.DB, userID int) ([]string, error) {
// DB QUERY
// -----------------------------
rows, err := pg.Query(`
SELECT piyasa_code
FROM dfusr_piyasa
WHERE dfusr_id = $1
AND is_allowed = true
WITH user_piyasa AS (
SELECT TRIM(up.piyasa_code) AS raw_code
FROM dfusr_piyasa up
WHERE up.dfusr_id = $1
AND up.is_allowed = true
)
SELECT DISTINCT
COALESCE(p_code.code, p_title.code, u.raw_code) AS piyasa_code
FROM user_piyasa u
LEFT JOIN mk_sales_piy p_code
ON UPPER(translate(TRIM(p_code.code), 'çğıöşüÇĞİÖŞÜ', 'CGIOSUCGIOSU'))
= UPPER(translate(TRIM(u.raw_code), 'çğıöşüÇĞİÖŞÜ', 'CGIOSUCGIOSU'))
LEFT JOIN mk_sales_piy p_title
ON UPPER(translate(TRIM(p_title.title),'çğıöşüÇĞİÖŞÜ', 'CGIOSUCGIOSU'))
= UPPER(translate(TRIM(u.raw_code), 'çğıöşüÇĞİÖŞÜ', 'CGIOSUCGIOSU'))
`, userID)
if err != nil {
return nil, fmt.Errorf("pg piyasa query error: %w", err)
@@ -46,10 +58,18 @@ func GetUserPiyasaCodes(pg *sql.DB, userID int) ([]string, error) {
defer rows.Close()
var out []string
seen := make(map[string]struct{})
for rows.Next() {
var code string
if err := rows.Scan(&code); err == nil {
out = append(out, code)
code = strings.ToUpper(strings.TrimSpace(code))
if code != "" {
if _, ok := seen[code]; ok {
continue
}
seen[code] = struct{}{}
out = append(out, code)
}
}
}