fix-permissions #196

Merged
romanskijdev merged 2 commits from fix-permissions into main 2026-10-15 11:18:41 +03:00
2 changed files with 13 additions and 74 deletions

View File

@ -199,73 +199,6 @@ func (u *UserHierarchyDB) GetApproversDB(
system = systems[0]
}
logrus.Infof("🔍 GetApproversDB START: subordinateID=%d, departmentID=%d, topicID=%d, categoryID=%d, system='%s'",
subordinateID, departmentID, topicID, categoryID, system)
// ==========================================
// 🐛 БЛОК ОТЛАДОЧНОГО ЛОГИРОВАНИЯ (DEBUG)
// ==========================================
debugSQL := `
WITH target_topic AS (
SELECT code, category_id FROM approval_topics WHERE id = $3
),
matching_topics AS (
SELECT t.id, t.code, LENGTH(t.code) as spec_score
FROM approval_topics t
CROSS JOIN target_topic tt
WHERE strpos(tt.code || '_', t.code || '_') = 1
AND t.category_id = tt.category_id
),
ranked AS (
SELECT
uh.id as hierarchy_id,
uh.approver_id,
uh.priority,
mt.code as matched_code,
CASE
WHEN mt.id IS NOT NULL THEN 1000 - mt.spec_score
WHEN uh.topic_category_id = $4 AND uh.topic_id IS NULL THEN 2000
WHEN uh.topic_id IS NULL AND uh.topic_category_id IS NULL THEN 3000
END AS specificity
FROM user_hierarchy uh
LEFT JOIN matching_topics mt ON uh.topic_id = mt.id
WHERE uh.subordinate_id = $1
AND uh.department_id = $2
AND (
mt.id IS NOT NULL
OR (uh.topic_category_id = $4 AND uh.topic_id IS NULL)
OR (uh.topic_id IS NULL AND uh.topic_category_id IS NULL)
)
)
SELECT hierarchy_id, approver_id, priority, COALESCE(matched_code, 'CATEGORY_OR_GLOBAL'), specificity
FROM ranked
ORDER BY specificity ASC, priority ASC
`
dRows, dErr := u.pool.Query(ctx, debugSQL, subordinateID, departmentID, topicID, categoryID)
if dErr == nil {
logrus.Infof(" 📊 [DEBUG] Список найденных правил для пользователя:")
foundRules := false
for dRows.Next() {
var hID, apprID uint64
var prio, spec int
var mCode string
if err := dRows.Scan(&hID, &apprID, &prio, &mCode, &spec); err == nil {
foundRules = true
logrus.Infof(" ---> Правило ID=%d | Согласующий=%d | Priority=%d | Совпадение='%s' | SCORE=%d (меньше=важнее)",
hID, apprID, prio, mCode, spec)
}
}
dRows.Close()
if !foundRules {
logrus.Infof(" ---> ⚠️ Для связки subordinateID=%d и departmentID=%d не найдено ни одного правила!", subordinateID, departmentID)
}
} else {
logrus.Warnf(" ❌ [DEBUG] Ошибка при выполнении отладочного запроса: %v", dErr)
}
// ==========================================
// КОНЕЦ БЛОКА ОТЛАДКИ
// ==========================================
rawSQL := `
WITH target_topic AS (
SELECT code, category_id FROM approval_topics WHERE id = $3

View File

@ -130,9 +130,6 @@ func (d *DynamicTopic) BuildTree() *FlowNode {
return root
}
// TopicCodeFromCollected: если задан codeTemplate на корневом узле дерева
// категории — используем его; иначе прежняя дефолтная генерация кода
// (актуально для delivery_clients и goods_order, где дефолт и так совпадает).
func (d *DynamicTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
baseCode := d.Code()
@ -187,19 +184,28 @@ func createTemplateFuncMap() template.FuncMap {
func (d *DynamicTopic) applyCodeTemplate(tmpl string, data map[string]string) (string, error) {
logrus.Printf("🔍 DEBUG applyCodeTemplate: шаблон = %q", tmpl)
t, err := template.New("code").Funcs(createTemplateFuncMap()).Parse(tmpl)
t, err := template.New("code").Option("missingkey=zero").Funcs(createTemplateFuncMap()).Parse(tmpl)
if err != nil {
return "", fmt.Errorf("parse code template: %w", err)
}
// Шаблон кода работает с map[string]string напрямую (а не interface{}),
// т.к. использует только .field и eq/ne без доп. переменных.
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
return "", fmt.Errorf("execute code template: %w", err)
}
return strings.TrimSpace(buf.String()), nil
result := buf.String()
result = strings.ReplaceAll(result, "<no value>", "")
for strings.Contains(result, "__") {
result = strings.ReplaceAll(result, "__", "_")
}
result = strings.TrimSuffix(result, "_")
return strings.TrimSpace(result), nil
}
func (d *DynamicTopic) applyMessageTemplate(tmpl, initiatorName string, data map[string]string) string {