Настройки работают

Иерархия групп работает
Полностью завязано на пользователя и серверы
This commit is contained in:
2025-12-18 07:21:31 +03:00
parent 542beafe0e
commit 4e4571b3db
23 changed files with 1572 additions and 385 deletions

View File

@@ -108,6 +108,56 @@ func (s *Service) UpdateDraftHeader(id uuid.UUID, storeID *uuid.UUID, supplierID
return s.draftRepo.Update(draft)
}
// AddItem добавляет пустую строку в черновик
func (s *Service) AddItem(draftID uuid.UUID) (*drafts.DraftInvoiceItem, error) {
// Проверка статуса драфта (можно добавить)
newItem := &drafts.DraftInvoiceItem{
ID: uuid.New(),
DraftID: draftID,
RawName: "Новая позиция",
RawAmount: decimal.NewFromFloat(1),
RawPrice: decimal.Zero,
Quantity: decimal.NewFromFloat(1),
Price: decimal.Zero,
Sum: decimal.Zero,
IsMatched: false,
}
if err := s.draftRepo.CreateItem(newItem); err != nil {
return nil, err
}
return newItem, nil
}
// DeleteItem удаляет строку и возвращает обновленную сумму черновика
func (s *Service) DeleteItem(draftID, itemID uuid.UUID) (float64, error) {
// 1. Удаляем
if err := s.draftRepo.DeleteItem(itemID); err != nil {
return 0, err
}
// 2. Получаем драфт заново для пересчета суммы
// Это самый надежный способ, чем считать в памяти
draft, err := s.draftRepo.GetByID(draftID)
if err != nil {
return 0, err
}
// 3. Считаем сумму
var totalSum decimal.Decimal
for _, item := range draft.Items {
if !item.Sum.IsZero() {
totalSum = totalSum.Add(item.Sum)
} else {
totalSum = totalSum.Add(item.Quantity.Mul(item.Price))
}
}
sumFloat, _ := totalSum.Float64()
return sumFloat, nil
}
func (s *Service) UpdateItem(draftID, itemID uuid.UUID, productID *uuid.UUID, containerID *uuid.UUID, qty, price decimal.Decimal) error {
draft, err := s.draftRepo.GetByID(draftID)
if err != nil {
@@ -137,6 +187,16 @@ func (s *Service) CommitDraft(draftID, userID uuid.UUID) (string, error) {
return "", errors.New("накладная уже отправлена")
}
server, err := s.accountRepo.GetActiveServer(userID)
if err != nil {
return "", fmt.Errorf("active server not found: %w", err)
}
targetStatus := "NEW"
if server.AutoProcess {
targetStatus = "PROCESSED"
}
// 3. Сборка Invoice
inv := invoices.Invoice{
ID: uuid.Nil,
@@ -144,7 +204,8 @@ func (s *Service) CommitDraft(draftID, userID uuid.UUID) (string, error) {
DateIncoming: *draft.DateIncoming,
SupplierID: *draft.SupplierID,
DefaultStoreID: *draft.StoreID,
Status: "NEW",
Status: targetStatus, // <-- Передаем статус из настроек
Comment: draft.Comment, // <-- Передаем комментарий из черновика
Items: make([]invoices.InvoiceItem, 0, len(draft.Items)),
}
@@ -179,19 +240,15 @@ func (s *Service) CommitDraft(draftID, userID uuid.UUID) (string, error) {
return "", err
}
// 5. Обновление статуса
// 5. Обновление статуса черновика
draft.Status = drafts.StatusCompleted
s.draftRepo.Update(draft)
// 6. БИЛЛИНГ: Увеличиваем счетчик накладных
server, _ := s.accountRepo.GetActiveServer(userID)
if server != nil {
if err := s.accountRepo.IncrementInvoiceCount(server.ID); err != nil {
logger.Log.Error("Billing increment failed", zap.Error(err))
}
// 7. Обучение (передаем ID сервера для сохранения маппинга)
go s.learnFromDraft(draft, server.ID)
// 6. БИЛЛИНГ и Обучение
if err := s.accountRepo.IncrementInvoiceCount(server.ID); err != nil {
logger.Log.Error("Billing increment failed", zap.Error(err))
}
go s.learnFromDraft(draft, server.ID)
return docNum, nil
}

View File

@@ -49,9 +49,10 @@ func (s *Service) ProcessReceiptImage(ctx context.Context, userID uuid.UUID, img
// 2. Создаем черновик
draft := &drafts.DraftInvoice{
UserID: userID, // <-- Исправлено с ChatID на UserID
RMSServerID: serverID, // <-- NEW
UserID: userID,
RMSServerID: serverID,
Status: drafts.StatusProcessing,
StoreID: server.DefaultStoreID,
}
if err := s.draftRepo.Create(draft); err != nil {
return nil, fmt.Errorf("failed to create draft: %w", err)
@@ -79,7 +80,7 @@ func (s *Service) ProcessReceiptImage(ctx context.Context, userID uuid.UUID, img
Sum: decimal.NewFromFloat(rawItem.Sum),
}
match, _ := s.ocrRepo.FindMatch(serverID, rawItem.RawName) // <-- ServerID
match, _ := s.ocrRepo.FindMatch(serverID, rawItem.RawName)
if match != nil {
item.IsMatched = true
@@ -97,6 +98,8 @@ func (s *Service) ProcessReceiptImage(ctx context.Context, userID uuid.UUID, img
s.draftRepo.Update(draft)
s.draftRepo.CreateItems(draftItems)
draft.Items = draftItems
return draft, nil
}
@@ -122,7 +125,7 @@ func (s *Service) GetCatalogForIndexing(userID uuid.UUID) ([]ProductForIndex, er
return nil, fmt.Errorf("no server")
}
products, err := s.catalogRepo.GetActiveGoods(server.ID)
products, err := s.catalogRepo.GetActiveGoods(server.ID, server.RootGroupGUID)
if err != nil {
return nil, err
}
@@ -163,7 +166,7 @@ func (s *Service) SearchProducts(userID uuid.UUID, query string) ([]catalog.Prod
if err != nil || server == nil {
return nil, fmt.Errorf("no server")
}
return s.catalogRepo.Search(server.ID, query)
return s.catalogRepo.Search(server.ID, query, server.RootGroupGUID)
}
func (s *Service) SaveMapping(userID uuid.UUID, rawName string, productID uuid.UUID, quantity decimal.Decimal, containerID *uuid.UUID) error {