380 lines
17 KiB
Go
380 lines
17 KiB
Go
package migrate
|
||
|
||
import (
|
||
"bitrix_balancer_api/core/typescore"
|
||
"bitrix_balancer_api/telegram_service/approvalflow"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/absence"
|
||
clientchanges "bitrix_balancer_api/telegram_service/handlers/approval/topics/client_changes"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/dealautoapproval"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/deliveryclients"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/free"
|
||
goodsorder "bitrix_balancer_api/telegram_service/handlers/approval/topics/goods_order"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/inventory"
|
||
managerexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/manager_expenses"
|
||
nonbudgetexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses"
|
||
nonbudgetexpensespetline "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line"
|
||
nonstandardcontract "bitrix_balancer_api/telegram_service/handlers/approval/topics/nonstandard_contract"
|
||
otkconditions "bitrix_balancer_api/telegram_service/handlers/approval/topics/otk_conditions"
|
||
paymentscashless "bitrix_balancer_api/telegram_service/handlers/approval/topics/payments_cashless"
|
||
rateslogistics "bitrix_balancer_api/telegram_service/handlers/approval/topics/rates_logistics"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/receipts"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/returns"
|
||
shipmentssoh "bitrix_balancer_api/telegram_service/handlers/approval/topics/shipments_soh"
|
||
transactionpassport "bitrix_balancer_api/telegram_service/handlers/approval/topics/transaction_passport"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/vshipments"
|
||
"bitrix_balancer_api/telegram_service/types"
|
||
"context"
|
||
"fmt"
|
||
)
|
||
|
||
// ===== helpers =====
|
||
|
||
func nilIfEmpty(s string) *string {
|
||
if s == "" {
|
||
return nil
|
||
}
|
||
return &s
|
||
}
|
||
|
||
// insertNode рекурсивно вставляет узел и его детей, сохраняя порядок
|
||
// (SortOrder = индекс среди сиблингов).
|
||
func insertNode(ctx context.Context, ipc *types.InternalProviderControl, categoryID uint64, parentID *uint64, sortOrder int, n *approvalflow.FlowNode) (*typescore.ApprovalFlowNode, error) {
|
||
key, label := n.Key, n.Label
|
||
isInput, isMulti := n.IsInput, n.IsMultiSelect
|
||
so := sortOrder
|
||
|
||
dbNode := &typescore.ApprovalFlowNode{
|
||
CategoryID: &categoryID,
|
||
ParentID: parentID,
|
||
Key: &key,
|
||
Label: &label,
|
||
DataKey: nilIfEmpty(n.DataKey),
|
||
DataValue: nilIfEmpty(n.DataValue),
|
||
IsInput: &isInput,
|
||
InputKey: nilIfEmpty(n.InputKey),
|
||
InputHint: nilIfEmpty(n.InputHint),
|
||
IsMultiSelect: &isMulti,
|
||
MultiSelectKey: nilIfEmpty(n.MultiSelectKey),
|
||
MultiSelectValue: nilIfEmpty(n.MultiSelectValue),
|
||
TopicCode: nilIfEmpty(n.TopicCode),
|
||
SortOrder: &so,
|
||
}
|
||
|
||
// returnObj=false: не полагаемся на встроенный lookup CreateApprovalFlowNodeDB —
|
||
// он фильтрует по ВСЕМ полям переданного объекта, а у сиблингов (например
|
||
// "✅ Нужна ПП" под разными родителями) совпадают Label/DataKey/DataValue/SortOrder,
|
||
// из-за чего lookup либо не находит строку, либо потенциально мог бы найти чужую.
|
||
_, _, err := ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, dbNode, false)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("insert node %s: %w", key, err)
|
||
}
|
||
|
||
// Ищем свежесозданную запись сами, по минимальному уникальному триплету:
|
||
// category_id + parent_id + key. Этого достаточно, т.к. Key уникален в
|
||
// пределах дерева категории по построению (см. BuildTree каждой темы).
|
||
lookup := &typescore.ApprovalFlowNode{
|
||
CategoryID: &categoryID,
|
||
ParentID: parentID,
|
||
Key: &key,
|
||
}
|
||
found, _, err := ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{Filtering: lookup})
|
||
if err != nil {
|
||
return nil, fmt.Errorf("insert node %s: lookup after insert: %w", key, err)
|
||
}
|
||
if len(found) == 0 {
|
||
return nil, fmt.Errorf("insert node %s: not found after insert", key)
|
||
}
|
||
if len(found) > 1 {
|
||
return nil, fmt.Errorf("insert node %s: ambiguous lookup after insert (%d matches, category_id+parent_id+key not unique)", key, len(found))
|
||
}
|
||
created := found[0]
|
||
|
||
for i, child := range n.Children {
|
||
if _, err := insertNode(ctx, ipc, categoryID, created.ID, i, child); err != nil {
|
||
return nil, err
|
||
}
|
||
}
|
||
return created, nil
|
||
}
|
||
|
||
// SeedCategoryTree создаёт дерево узлов для категории categoryCode из tree,
|
||
// затем проставляет code_template/message_template на корневой узел.
|
||
// codeTemplate == "" оставляет дефолтный фолбэк в DynamicTopic.TopicCodeFromCollected
|
||
// (baseCode + отсортированные непустые значения collected).
|
||
func SeedCategoryTree(
|
||
ctx context.Context,
|
||
ipc *types.InternalProviderControl,
|
||
categoryCode string,
|
||
tree *approvalflow.FlowNode,
|
||
codeTemplate string,
|
||
messageTemplate string,
|
||
) error {
|
||
category, err := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, categoryCode)
|
||
if err != nil {
|
||
return fmt.Errorf("get category %s: %w", categoryCode, err)
|
||
}
|
||
if category == nil || category.ID == nil {
|
||
return fmt.Errorf("category not found: %s", categoryCode)
|
||
}
|
||
|
||
root, err := insertNode(ctx, ipc, *category.ID, nil, 0, tree)
|
||
if err != nil {
|
||
return fmt.Errorf("insert tree for %s: %w", categoryCode, err)
|
||
}
|
||
|
||
ct, mt := codeTemplate, messageTemplate
|
||
root.CodeTemplate = &ct
|
||
root.MessageTemplate = &mt
|
||
if _, _, err := ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, root); err != nil {
|
||
return fmt.Errorf("set templates for %s: %w", categoryCode, err)
|
||
}
|
||
|
||
return nil
|
||
}
|
||
|
||
// freeMessageTemplate воспроизводит FreeTopic.FormatApproverMessage дословно,
|
||
// включая опциональный блок инструкций (сейчас недостижим в живом флоу,
|
||
// т.к. collected["instructions"] не заполняется при подаче заявки, но
|
||
// сохраняем на случай если это изменится).
|
||
const freeMessageTemplate = `📋 <b>Заявка на согласование</b>
|
||
|
||
👤 <b>От:</b> {{.initiator_name}}
|
||
📂 <b>Тема:</b> {{.topic_name}}
|
||
📝 <b>Текст:</b>
|
||
{{if .content}}{{.content}}{{else}}—{{end}}{{if .instructions}}
|
||
|
||
💡 <b>Инструкция:</b>
|
||
<i>{{.instructions}}</i>{{end}}`
|
||
|
||
// ===== entry point =====
|
||
|
||
// SeedAllTopics переносит статические деревья тем в approval_flow_nodes,
|
||
// разбитые по approval_topic_categories. Идемпотентности намеренно нет —
|
||
// запускать один раз на чистых категориях (без существующих узлов).
|
||
//
|
||
// approval_topics и approval_topic_categories нигде здесь не изменяются —
|
||
// только читаются (Get...ByCodeDB) для получения category_id.
|
||
//
|
||
// НЕ мигрировано — источника дерева не было прислано:
|
||
// - new_clients (category_id=27): в старом Registry вообще не регистрировался.
|
||
//
|
||
// НЕ создаётся отдельным деревом (сознательно, алиасинг хардкодом в Registry):
|
||
// - timeoff (category_id=1), vacation (2), sickleave (3) — их узлы объединены
|
||
// в дерево категории "absence" (345) через AbsenceTopic.BuildTree().
|
||
// Registry должен резолвить коды "timeoff"/"vacation"/"sickleave" в topics["absence"].
|
||
func SeedAllTopics(ctx context.Context, ipc *types.InternalProviderControl) error {
|
||
type seed struct {
|
||
categoryCode string
|
||
tree *approvalflow.FlowNode
|
||
codeTemplate string
|
||
messageTemplate string
|
||
}
|
||
|
||
seeds := []seed{
|
||
{
|
||
"non_budget_expenses",
|
||
nonbudgetexpenses.NewNonBudgetExpensesTopic().BuildTree(),
|
||
`non_budget_expenses_{{.branch}}_{{.expense_type}}{{if .pp_required}}_pp_{{.pp_required}}{{end}}`,
|
||
`📋 <b>Внебюджетные расходы — {{.branch_label}} ({{.expense_type_label}})</b>{{if .pp_required}}
|
||
💳 <b>ПП:</b> {{.pp_required_label}}{{end}}
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"client_changes",
|
||
clientchanges.NewClientChangesTopic().BuildTree(),
|
||
`client_changes_{{.change_type}}_{{.region}}`,
|
||
`📋 <b>Изменение клиентов в ОКБ и 1С: – {{.change_type_label}}</b>
|
||
🖥 <b>Системы:</b> {{.systems_label}}
|
||
📍 <b>Регион:</b> {{.region_label}}
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"deal_auto_approval_conditions",
|
||
dealautoapproval.NewDealAutoApprovalTopic().BuildTree(),
|
||
`deal_auto_approval_{{.condition_type}}`,
|
||
`📋 <b>Смена условий автосогласования сделок - {{if eq .condition_type "receivable_limit_vladimir"}}Повышение лимита ДЗ (от Владимира лично){{else if eq .condition_type "document_limits"}}Расширение лимитов по документам и просрочке{{else}}Смена условий автосогласования сделок{{end}}</b>
|
||
|
||
👤 <b>Инициатор:</b> {{.initiator_name}}
|
||
📝 <b>Текст:</b>
|
||
{{if .content}}{{.content}}{{else}}—{{end}}`,
|
||
},
|
||
{
|
||
"delivery_clients",
|
||
deliveryclients.NewDeliveryClientsTopic().BuildTree(),
|
||
`delivery_clients_{{.delivery_type}}{{if eq .delivery_type "warehouse"}}_{{.region}}{{end}}`,
|
||
`📋 <b>{{if eq .delivery_type "direct"}}Доставка: Напрямую клиенту{{else}}Доставка: На склад, {{.region_label}}{{end}}</b>
|
||
|
||
👤 <b>Инициатор:</b> {{.initiator_name}}
|
||
📝 <b>Текст:</b>
|
||
{{if .content}}{{.content}}{{else}}—{{end}}`,
|
||
},
|
||
{
|
||
"goods_order",
|
||
goodsorder.NewGoodsOrderTopic().BuildTree(),
|
||
`goods_order_{{.order_type}}{{if .region}}_{{.region}}{{end}}`,
|
||
`📋 <b>Заказ товаров — {{.order_type_label}}</b>
|
||
📍 <b>Регион:</b> {{if .region}}{{.region_label}}{{else}}—{{end}}
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"inventory",
|
||
inventory.NewInventoryTopic().BuildTree(),
|
||
`inventory_{{.region}}{{if ne .region "krasnodar"}}_{{.location}}{{end}}`,
|
||
`📋 <b>Инвентаризация: {{.region_label}}{{if eq .location "19l"}}, 19л{{else if eq .location "gvardeyskoe"}}, Гвардейское{{end}}</b>
|
||
|
||
👤 <b>Инициатор:</b> {{.initiator_name}}
|
||
📝 <b>Текст:</b>
|
||
{{if .content}}{{.content}}{{else}}—{{end}}`,
|
||
},
|
||
{
|
||
// Единственное дерево на всю категорию absence (345).
|
||
// timeoff/vacation/sickleave как категории (1/2/3) своих узлов не получают.
|
||
"absence",
|
||
absence.NewAbsenceTopic().BuildTree(),
|
||
`{{.absence_type}}_{{trimPrefix .duration_type "sl_"}}_{{.time_type}}_{{.payment_type}}`,
|
||
`📋 <b>{{if eq .absence_type "timeoff"}}Тип: Отгул{{else if eq .absence_type "vacation"}}Тип: Отпуск{{else}}Тип: Официальный больничный{{end}}</b>
|
||
|
||
<b>{{.initiator_name}}</b>: прошу согласовать {{if eq .absence_type "timeoff"}}отгул{{else if eq .absence_type "vacation"}}отпуск{{else}}больничный{{end}}
|
||
{{if .open_date}}Дата открытия больничного листа - {{.open_date}}.
|
||
{{end}}{{.content}}
|
||
<i>{{.payment_type_label}}</i>`,
|
||
},
|
||
{
|
||
"returns",
|
||
returns.NewReturnsTopic().BuildTree(),
|
||
`returns_{{.return_type}}_{{.region}}`,
|
||
`📋 Возвраты: <b>{{.return_type_label}} — {{.region_label}}</b>
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"manager_expenses",
|
||
managerexpenses.NewManagerExpensesTopic().BuildTree(),
|
||
`manager_expenses_{{.region}}`,
|
||
`📋 <b>Менеджерские расходы — {{.region_label}}</b>
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"non_budget_expenses_pet_line",
|
||
nonbudgetexpensespetline.NewNonBudgetExpensesPetLineTopic().BuildTree(),
|
||
`non_budget_expenses_pet_line_{{.branch}}_{{.expense_type}}`,
|
||
`📋 <b>Внебюджетные расходы ПЭТ Лайн — {{.branch_label}} ({{.expense_type_label}})</b>
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"nonstandard_contract",
|
||
nonstandardcontract.NewNonstandardContractTopic().BuildTree(),
|
||
`nonstandard_contract_{{.region}}`,
|
||
`📋 <b>Нестандартные условия договора поставки — {{.region_label}}</b>
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"otk_conditions",
|
||
otkconditions.NewOtkConditionsTopic().BuildTree(),
|
||
`otk_conditions_{{.region}}`,
|
||
`📋 <b>Долгосрочные условия ОТК — {{.region_label}}</b>
|
||
|
||
👤 <b>Инициатор:</b> {{.initiator_name}}
|
||
📝 <b>Текст:</b>
|
||
{{if .content}}{{.content}}{{else}}—{{end}}`,
|
||
},
|
||
{
|
||
"payments_cashless",
|
||
paymentscashless.NewPaymentsCashlessTopic().BuildTree(),
|
||
`payments_cashless_{{.payment_category}}{{if .pp_required}}_pp_{{.pp_required}}{{end}}`,
|
||
`📋 <b>Утверждение оплат безнал — {{.payment_category_label}}</b>{{if .pp_required}}
|
||
💳 <b>ПП:</b> {{.pp_required_label}}{{end}}
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"rates_logistics",
|
||
rateslogistics.NewRatesLogisticsTopic().BuildTree(),
|
||
`rates_logistics_{{.rate_type}}`,
|
||
`📋 <b>Утверждение ставок логистики — {{if eq .rate_type "long_term"}}Надолго{{else if eq .rate_type "once_head_approval"}}Разово (с рук. отдела логистики){{else}}Разово{{end}}</b>
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"receipts",
|
||
receipts.NewReceiptsTopic().BuildTree(),
|
||
`receipts_{{.branch}}`,
|
||
`📋 <b>Поступления — {{.branch_label}}</b>
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"shipments_soh",
|
||
shipmentssoh.NewShipmentsSOHTopic().BuildTree(),
|
||
`shipments_soh_{{.region}}_{{.shipment_type}}`,
|
||
`📋 <b>Отгрузки на СОХ — {{.region_label}} ({{.shipment_type_label}})</b>
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"transaction_passport",
|
||
transactionpassport.NewTransactionPassportTopic().BuildTree(),
|
||
`transaction_passport_{{.region}}`,
|
||
`📋 <b>Паспорт сделки — {{.region_label}}</b>
|
||
|
||
<b>{{.initiator_name}}</b>:
|
||
{{.content}}`,
|
||
},
|
||
{
|
||
"v_shipments",
|
||
vshipments.NewVShipmentsTopic().BuildTree(),
|
||
`v_shipments_{{.subtype}}{{if eq .subtype "advance"}}_{{.advance_type}}{{end}}`,
|
||
`📋 <b>В. Отгрузки - {{if eq .subtype "shipment"}}В. Отгрузки{{else if eq .subtype "receipt"}}В. Поступления{{else if eq .subtype "advance"}}{{if eq .advance_type "amount"}}Авансовая отгрузка (по сумме){{else if eq .advance_type "goods"}}Авансовая отгрузка (по товару){{else}}Авансовая отгрузка{{end}}{{else}}В. Отгрузки{{end}}</b>
|
||
|
||
👤 <b>Инициатор:</b> {{.initiator_name}}
|
||
📝 <b>Текст:</b>
|
||
{{if .content}}{{.content}}{{else}}—{{end}}`,
|
||
},
|
||
}
|
||
|
||
// 10 тем без развилок (один шаг: свободный текстовый ввод).
|
||
// codeTemplate == "" -> дефолтный фолбэк в DynamicTopic даёт ровно Code()
|
||
// категории, как и раньше отдавал FreeTopic.TopicCodeFromCollected.
|
||
freeTopics := []struct{ code, name, template string }{
|
||
{"shipments", "Отгрузки", ""},
|
||
{"vacancies", "Вакансии", ""},
|
||
{"delivery_rates_ap", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб."},
|
||
{"freelancers_approval", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день"},
|
||
{"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04"},
|
||
{"suggestions", "Предложения и пожелания", ""},
|
||
{"cash_balance", "Остаток в кассах", ""},
|
||
{"client_sales", "Продажи по клиенту", ""},
|
||
{"manager_expenses_report", "Проведенные расходы по менеджеру", ""},
|
||
{"remote_access", "Согласование удаленной работы", "Прошу согласовать удалённый выход на работу 06.06.2026"},
|
||
}
|
||
for _, t := range freeTopics {
|
||
topic := free.NewFreeTopic(t.code, t.name, t.template)
|
||
seeds = append(seeds, seed{t.code, topic.BuildTree(), "", freeMessageTemplate})
|
||
}
|
||
|
||
for _, s := range seeds {
|
||
if err := SeedCategoryTree(ctx, ipc, s.categoryCode, s.tree, s.codeTemplate, s.messageTemplate); err != nil {
|
||
return fmt.Errorf("seed %s: %w", s.categoryCode, err)
|
||
}
|
||
}
|
||
|
||
return nil
|
||
}
|