Update monthly order app
Deploy / deploy (push) Failing after 32s
Details
Deploy / deploy (push) Failing after 32s
Details
This commit is contained in:
parent
3a147729ef
commit
e7f3e4604b
|
|
@ -7,25 +7,37 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MasterReportSpreadsheetID = "1wMyQIA-ShXE0TzHcjadMxkN1eu_637SflFHrUJjRuQw"
|
||||
|
||||
type ApprovalFlowStarter interface {
|
||||
StartFlowForOrder(ctx context.Context, approval *typescore.Approval) error
|
||||
}
|
||||
|
||||
type MonthlyOrderService struct {
|
||||
ipc *types.InternalProviderControl
|
||||
gsClient *googlesheets.Client
|
||||
clientsSheet string
|
||||
nomSheet string
|
||||
flowStarter ApprovalFlowStarter // 2. НОВОЕ: Добавляем зависимость
|
||||
}
|
||||
|
||||
func NewMonthlyOrderService(ipc *types.InternalProviderControl, gsClient *googlesheets.Client, clientsSheetID, nomSheetID string) *MonthlyOrderService {
|
||||
func NewMonthlyOrderService(
|
||||
ipc *types.InternalProviderControl,
|
||||
gsClient *googlesheets.Client,
|
||||
clientsSheetID, nomSheetID string,
|
||||
flowStarter ApprovalFlowStarter,
|
||||
) *MonthlyOrderService {
|
||||
return &MonthlyOrderService{
|
||||
ipc: ipc,
|
||||
gsClient: gsClient,
|
||||
clientsSheet: clientsSheetID,
|
||||
nomSheet: nomSheetID,
|
||||
flowStarter: flowStarter,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -173,6 +185,7 @@ func (s *MonthlyOrderService) ExportGoogleReport(ctx context.Context) (string, e
|
|||
return s.gsClient.ExportMonthlyReportToMasterSheet(ctx, MasterReportSpreadsheetID, sheet1Data, sheet2Data)
|
||||
}
|
||||
|
||||
// SubmitOrdersToTelegram превращает отправленные заказы в Telegram-заявки
|
||||
// SubmitOrdersToTelegram превращает отправленные заказы в Telegram-заявки
|
||||
func (s *MonthlyOrderService) SubmitOrdersToTelegram(ctx context.Context, managerID uint64) error {
|
||||
now := time.Now()
|
||||
|
|
@ -184,27 +197,61 @@ func (s *MonthlyOrderService) SubmitOrdersToTelegram(ctx context.Context, manage
|
|||
return err
|
||||
}
|
||||
|
||||
manager, _ := s.ipc.Database.User.GetUserByIDDB(ctx, managerID)
|
||||
manager, err := s.ipc.Database.User.GetUserByIDDB(ctx, managerID)
|
||||
if err != nil || manager == nil || manager.FullName == nil {
|
||||
return errors.New("менеджер не найден")
|
||||
}
|
||||
|
||||
// Находим нужную тему в БД по коду (предварительно вам нужно создать в боте тему с кодом "monthly_order")
|
||||
topic, _ := s.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, "monthly_order")
|
||||
if topic == nil {
|
||||
return errors.New("тема 'Заказ на месяц' (monthly_order) не найдена в БД")
|
||||
// 1. Получаем актуальный список клиентов из Google Sheets для определения филиала (Крым / Краснодар)
|
||||
gsClients, err := s.gsClient.FetchActiveClientsForManager(s.clientsSheet, *manager.FullName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ошибка получения клиентов из Google Sheets: %v", err)
|
||||
}
|
||||
|
||||
// Создаем мапу для быстрого поиска филиала по имени клиента (очищаем от лишних пробелов)
|
||||
branchMap := make(map[string]string)
|
||||
for _, c := range gsClients {
|
||||
branchMap[strings.TrimSpace(c.Name)] = strings.TrimSpace(c.Branch)
|
||||
}
|
||||
|
||||
for _, order := range dbOrders {
|
||||
if order.ClientName == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Требование: Отправлять ТОЛЬКО заполненные (где есть номенклатура)
|
||||
items, _ := s.ipc.Database.MonthlyOrders.GetItemsByOrderIDDB(ctx, *order.ID)
|
||||
if len(items) == 0 {
|
||||
continue // Пустой заказ, пропускаем (останется только для отчета)
|
||||
}
|
||||
|
||||
// Заявка уже была отправлена
|
||||
// Защита от дублей: заявка уже была отправлена
|
||||
if order.ApprovalID != nil && *order.ApprovalID > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Формируем текст заявки
|
||||
clientNameClean := strings.TrimSpace(*order.ClientName)
|
||||
branch := branchMap[clientNameClean]
|
||||
|
||||
// 2. Определяем нужную тему (Topic) на основе филиала
|
||||
topicCode := ""
|
||||
branchLower := strings.ToLower(branch)
|
||||
if strings.Contains(branchLower, "краснодар") {
|
||||
topicCode = "goods_order_monthly_krasnodar"
|
||||
} else if strings.Contains(branchLower, "крым") || strings.Contains(branchLower, "симферополь") {
|
||||
topicCode = "goods_order_monthly_crimea"
|
||||
} else {
|
||||
logrus.Warnf("SubmitOrdersToTelegram: не удалось определить филиал для клиента %s (Branch: '%s'). Пропускаем.", clientNameClean, branch)
|
||||
continue
|
||||
}
|
||||
|
||||
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
|
||||
if err != nil || topic == nil || topic.ID == nil {
|
||||
logrus.Errorf("SubmitOrdersToTelegram: тема '%s' не найдена в БД. Заявка для %s не создана.", topicCode, clientNameClean)
|
||||
continue
|
||||
}
|
||||
|
||||
// 3. Формируем текст заявки
|
||||
var contentBuilder strings.Builder
|
||||
contentBuilder.WriteString(fmt.Sprintf("🏢 Клиент: %s\n", *order.ClientName))
|
||||
|
||||
|
|
@ -236,27 +283,35 @@ func (s *MonthlyOrderService) SubmitOrdersToTelegram(ctx context.Context, manage
|
|||
contentStr := contentBuilder.String()
|
||||
status := "pending"
|
||||
|
||||
// Создаем заявку в БД
|
||||
// 4. Создаем заявку в БД с привязкой к конкретной теме
|
||||
approval := &typescore.Approval{
|
||||
InitiatorID: manager.ID,
|
||||
DepartmentID: manager.DepartmentID,
|
||||
TopicID: topic.ID,
|
||||
Content: &contentStr,
|
||||
Status: &status,
|
||||
// Метаданные (регион и прочее) можно запаковать в Metadata JSON
|
||||
}
|
||||
|
||||
createdApproval, _, err := s.ipc.Database.Approval.CreateApprovalDB(ctx, nil, approval, true)
|
||||
if err == nil && createdApproval != nil {
|
||||
// Привязываем созданную заявку к заказу
|
||||
// Привязываем созданную заявку к заказу (защита от дублей на будущее)
|
||||
order.ApprovalID = createdApproval.ID
|
||||
orderStatus := "submitted"
|
||||
order.Status = &orderStatus
|
||||
s.ipc.Database.MonthlyOrders.SaveClientOrder(ctx, nil, order) // Обновляем заказ
|
||||
|
||||
// Тут нужно вызвать флоу создания шагов (SubmitApprovalForSystem из handler.go),
|
||||
// чтобы заявка полетела по цепочке согласований.
|
||||
// Так как это внешний модуль, проще всего интегрировать это через Event Bus или вызов функции роутера.
|
||||
// 5. Запускаем генерацию шагов и рассылку уведомлений в Telegram
|
||||
if s.flowStarter != nil {
|
||||
if err := s.flowStarter.StartFlowForOrder(ctx, createdApproval); err != nil {
|
||||
logrus.Errorf("SubmitOrdersToTelegram: ошибка запуска флоу согласования для заявки %d: %v", *createdApproval.ID, err)
|
||||
} else {
|
||||
logrus.Infof("✅ Флоу согласования успешно запущен для заявки %d (Клиент: %s, Тема: %s)", *createdApproval.ID, clientNameClean, topicCode)
|
||||
}
|
||||
} else {
|
||||
logrus.Warn("SubmitOrdersToTelegram: flowStarter не передан, шаги не созданы")
|
||||
}
|
||||
} else {
|
||||
logrus.Errorf("SubmitOrdersToTelegram: ошибка создания заявки для клиента %s: %v", clientNameClean, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -28,7 +28,6 @@ func main() {
|
|||
}
|
||||
|
||||
func initService() error {
|
||||
// Получение конфигурации приложения
|
||||
clientsExternal, err := getClientsExternal()
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -51,22 +50,25 @@ func initService() error {
|
|||
logrus.Errorf("Не удалось инициализировать Google Sheets API: %v", err)
|
||||
}
|
||||
|
||||
// НОВОЕ: Перенесли создание UpdateHandler ВЫШЕ
|
||||
update := tgupdatehandler.NewUpdateHandler(ipc)
|
||||
go func() {
|
||||
defer handlePanic("update.GetUpdateTelegram goroutine")
|
||||
update.GetUpdateTelegram()
|
||||
}()
|
||||
|
||||
// НОВОЕ: Передаем update.GetApprovalHandler() как интерфейс
|
||||
moService := monthly_orders.NewMonthlyOrderService(
|
||||
ipc,
|
||||
gsClient,
|
||||
"1F1ansQeSuAwhe3Y_mhfm4ja370k5hq67RruE-CVp83w",
|
||||
"1C4Tl-AQRJENW4THzwH-7yP2Ni0ckMSdm3ndLCrdKr2Y",
|
||||
update.GetApprovalHandler(), // <-- Инъекция зависимости
|
||||
)
|
||||
|
||||
monthlyOrderChecker := scheduler.NewMonthlyOrderChecker(ipc, moService)
|
||||
monthlyOrderChecker.Start()
|
||||
|
||||
update := tgupdatehandler.NewUpdateHandler(ipc)
|
||||
go func() {
|
||||
defer handlePanic("update.GetUpdateTelegram goroutine") // Обработка паник в горутине
|
||||
update.GetUpdateTelegram()
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,10 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
func (s *UpdateHandler) GetApprovalHandler() *approval.Handler {
|
||||
return s.approvalHandler
|
||||
}
|
||||
|
||||
type UpdateHandler struct {
|
||||
ipc *types.InternalProviderControl
|
||||
approvalHandler *approval.Handler
|
||||
|
|
|
|||
|
|
@ -0,0 +1,140 @@
|
|||
package approval
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// StartFlowForOrder реализует интерфейс monthly_orders.ApprovalFlowStarter
|
||||
func (h *Handler) StartFlowForOrder(ctx context.Context, approval *typescore.Approval) error {
|
||||
if approval == nil || approval.ID == nil {
|
||||
return fmt.Errorf("invalid approval")
|
||||
}
|
||||
|
||||
initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
|
||||
if err != nil || initiator == nil {
|
||||
return fmt.Errorf("initiator not found")
|
||||
}
|
||||
|
||||
topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
if err != nil || topic == nil || topic.CategoryID == nil {
|
||||
return fmt.Errorf("topic or category not found")
|
||||
}
|
||||
|
||||
// 1. Получаем согласующих из матрицы по иерархии (systems = nil, так как ИТ-систем нет)
|
||||
approvers, err := h.ipc.Database.UserHierarchy.GetApproversDB(
|
||||
ctx,
|
||||
*initiator.ID,
|
||||
*initiator.DepartmentID,
|
||||
*topic.ID,
|
||||
*topic.CategoryID,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetApproversDB err: %w", err)
|
||||
}
|
||||
if len(approvers) == 0 {
|
||||
return fmt.Errorf("нет согласующих в иерархии для пользователя %d", *initiator.ID)
|
||||
}
|
||||
|
||||
// 2. Распределяем по приоритетам (учитывая режим any_of, если он включен)
|
||||
priorityGroups := make(map[int][]*typescore.User)
|
||||
for i, approver := range approvers {
|
||||
p := i
|
||||
if topic.ApprovalMode != nil && *topic.ApprovalMode == "any_of" {
|
||||
p = 0
|
||||
}
|
||||
priorityGroups[p] = append(priorityGroups[p], approver)
|
||||
}
|
||||
|
||||
// 3. Создаем шаги согласования (ApprovalStep) в БД
|
||||
stepOrder := 0
|
||||
for priority := 0; priority <= len(priorityGroups); priority++ {
|
||||
group, ok := priorityGroups[priority]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, approver := range group {
|
||||
if approver.ID == nil {
|
||||
continue
|
||||
}
|
||||
stepStatus := "waiting"
|
||||
if priority == 0 {
|
||||
stepStatus = "pending"
|
||||
}
|
||||
order := stepOrder
|
||||
approverName := ""
|
||||
if approver.FullName != nil {
|
||||
approverName = *approver.FullName
|
||||
}
|
||||
|
||||
step := &typescore.ApprovalStep{
|
||||
ApprovalID: approval.ID,
|
||||
ApproverID: approver.ID,
|
||||
StepOrder: &order,
|
||||
Status: &stepStatus,
|
||||
ApproverNameSnapshot: &approverName,
|
||||
}
|
||||
h.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, step) //nolint:errcheck
|
||||
stepOrder++
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Отправляем уведомления первым согласующим
|
||||
bot := h.ipc.TGBotClient.Bot()
|
||||
if bot == nil {
|
||||
return fmt.Errorf("bot client is nil")
|
||||
}
|
||||
|
||||
topicCode := "monthly_order"
|
||||
if topic.Code != nil {
|
||||
topicCode = *topic.Code
|
||||
}
|
||||
|
||||
flowTopic, _ := h.Registry.Get(topicCode)
|
||||
if flowTopic == nil {
|
||||
logrus.Warnf("StartFlowForOrder: тема %s не найдена в Registry", topicCode)
|
||||
return nil // Без Registry не сможем собрать красивую карточку, но шаги уже созданы
|
||||
}
|
||||
|
||||
notifier := NewNotifier(h.ipc, flowTopic)
|
||||
collected := h.getCollectedFromApproval(ctx, approval)
|
||||
firstGroup := priorityGroups[0]
|
||||
|
||||
for _, approver := range firstGroup {
|
||||
actualApprover := approver
|
||||
|
||||
if actualApprover.TelegramID == nil && actualApprover.ID != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Проверка на делегирование прав
|
||||
if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalDelegation{
|
||||
IsActive: utilscore.PointerToBool(true),
|
||||
TopicID: topic.ID,
|
||||
}}); err == nil && len(delegations) > 0 {
|
||||
for _, deleg := range delegations {
|
||||
if deleg.DelegatorID != nil && *deleg.DelegatorID == *actualApprover.ID && deleg.DelegateID != nil {
|
||||
if delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); delegate != nil && delegate.TelegramID != nil {
|
||||
actualApprover = delegate
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
notifier.NotifyApprover(bot, actualApprover, initiator, approval, collected)
|
||||
}
|
||||
|
||||
// 5. Уведомляем контроллеров (наблюдателей)
|
||||
controllers, _ := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, topicCode, topic.ID)
|
||||
for _, controller := range controllers {
|
||||
h.notifyControllerAboutCreation(bot, ctx, controller, initiator, approval, collected)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Loading…
Reference in New Issue