Add znzt module
This commit is contained in:
parent
38820b69e4
commit
790c8bd82f
|
|
@ -78,8 +78,9 @@ func (db *MonthlyOrderDB) SaveClientOrder(ctx context.Context, tx pgx.Tx, order
|
|||
return nil, errors.New("order is nil")
|
||||
}
|
||||
|
||||
if order.ClientName == nil {
|
||||
return nil, errors.New("не указано имя клиента (client_name)")
|
||||
// 1. Защита от паники: проверяем обязательные поля перед разыменованием
|
||||
if order.ClientName == nil || *order.ClientName == "" {
|
||||
return nil, errors.New("client_name is required")
|
||||
}
|
||||
if order.Status == nil {
|
||||
defaultStatus := "draft"
|
||||
|
|
@ -88,46 +89,83 @@ func (db *MonthlyOrderDB) SaveClientOrder(ctx context.Context, tx pgx.Tx, order
|
|||
|
||||
var insertedID uint64
|
||||
err := dbutils.ExecuteTx(ctx, db.pool, tx, func(tx pgx.Tx) error {
|
||||
// 1. Вставляем или обновляем основу заказа
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Columns("manager_id", "month", "year", "client_name", "manager_comment", "custom_reason", "free_form_comment", "decade", "delivery", "conditions", "payment_form", "status").
|
||||
Values(*order.ManagerID, *order.Month, *order.Year, *order.ClientName, order.ManagerComment, order.CustomReason, order.FreeFormComment, order.Decade, order.Delivery, order.Conditions, order.PaymentForm, *order.Status).
|
||||
Suffix("ON CONFLICT (manager_id, month, year, client_name) DO UPDATE SET manager_comment = EXCLUDED.manager_comment, custom_reason = EXCLUDED.custom_reason, free_form_comment = EXCLUDED.free_form_comment, decade = EXCLUDED.decade, delivery = EXCLUDED.delivery, conditions = EXCLUDED.conditions, payment_form = EXCLUDED.payment_form, status = EXCLUDED.status, updated_at = NOW() RETURNING id")
|
||||
// 2. Ищем существующий заказ для этого клиента в текущем месяце
|
||||
querySelect := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("id").
|
||||
From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Where(squirrel.Eq{
|
||||
"manager_id": *order.ManagerID,
|
||||
"month": *order.Month,
|
||||
"year": *order.Year,
|
||||
"client_name": *order.ClientName,
|
||||
})
|
||||
|
||||
sqlV, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
sqlS, argsS, _ := querySelect.ToSql()
|
||||
var existingID uint64
|
||||
err := tx.QueryRow(ctx, sqlS, argsS...).Scan(&existingID)
|
||||
|
||||
if err != nil && err != pgx.ErrNoRows {
|
||||
return err // Реальная ошибка БД
|
||||
}
|
||||
|
||||
err = tx.QueryRow(ctx, sqlV, args...).Scan(&insertedID)
|
||||
if err != nil {
|
||||
return err
|
||||
if err == pgx.ErrNoRows {
|
||||
// Записи нет -> Делаем безопасный INSERT
|
||||
queryInsert := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Columns("manager_id", "month", "year", "client_name", "manager_comment", "custom_reason", "free_form_comment", "decade", "delivery", "conditions", "payment_form", "status").
|
||||
Values(*order.ManagerID, *order.Month, *order.Year, *order.ClientName, order.ManagerComment, order.CustomReason, order.FreeFormComment, order.Decade, order.Delivery, order.Conditions, order.PaymentForm, *order.Status).
|
||||
Suffix("RETURNING id")
|
||||
|
||||
sqlI, argsI, _ := queryInsert.ToSql()
|
||||
if err := tx.QueryRow(ctx, sqlI, argsI...).Scan(&insertedID); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Запись есть -> Делаем UPDATE
|
||||
queryUpdate := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Set("manager_comment", order.ManagerComment).
|
||||
Set("custom_reason", order.CustomReason).
|
||||
Set("free_form_comment", order.FreeFormComment).
|
||||
Set("decade", order.Decade).
|
||||
Set("delivery", order.Delivery).
|
||||
Set("conditions", order.Conditions).
|
||||
Set("payment_form", order.PaymentForm).
|
||||
Set("status", *order.Status).
|
||||
Set("updated_at", squirrel.Expr("NOW()")).
|
||||
Where(squirrel.Eq{"id": existingID})
|
||||
|
||||
sqlU, argsU, _ := queryUpdate.ToSql()
|
||||
if _, err := tx.Exec(ctx, sqlU, argsU...); err != nil {
|
||||
return err
|
||||
}
|
||||
insertedID = existingID
|
||||
}
|
||||
|
||||
order.ID = &insertedID
|
||||
|
||||
// 2. Удаляем старые Items
|
||||
// 3. Перезаписываем товары (сначала удаляем старые, потом пишем новые)
|
||||
delSQL, delArgs, _ := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(string(dbcoretablenames.TableNameMonthlyOrderItems)).
|
||||
Where(squirrel.Eq{"order_client_id": insertedID}).ToSql()
|
||||
tx.Exec(ctx, delSQL, delArgs...)
|
||||
|
||||
// 3. Вставляем новые Items
|
||||
if len(order.Items) > 0 {
|
||||
insertItems := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(string(dbcoretablenames.TableNameMonthlyOrderItems)).
|
||||
Columns("order_client_id", "nomenclature_name", "nomenclature_type", "quantity")
|
||||
|
||||
hasValidItems := false
|
||||
for _, item := range order.Items {
|
||||
if item.Quantity != nil && *item.Quantity > 0 {
|
||||
insertItems = insertItems.Values(insertedID, item.NomenclatureName, item.NomenclatureType, item.Quantity)
|
||||
hasValidItems = true
|
||||
}
|
||||
}
|
||||
|
||||
iSQL, iArgs, _ := insertItems.ToSql()
|
||||
if iSQL != "" { // Защита от пустых инсертов
|
||||
_, err = tx.Exec(ctx, iSQL, iArgs...)
|
||||
if err != nil {
|
||||
if hasValidItems {
|
||||
iSQL, iArgs, _ := insertItems.ToSql()
|
||||
if _, err = tx.Exec(ctx, iSQL, iArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,11 +75,16 @@ func (s *MonthlyOrderService) GetMyOrderData(ctx context.Context, managerID uint
|
|||
}
|
||||
|
||||
// 3. Достаем черновики из нашей БД
|
||||
dbOrders, _ := s.ipc.Database.MonthlyOrders.GetClientOrdersByManagerDB(ctx, managerID, month, year)
|
||||
ordersMap := make(map[string]*typescore.MonthlyOrderClient)
|
||||
// 🔴 ЗАМЕНЯЕМ "_" НА "err" И ЛОГИРУЕМ ЕЁ!
|
||||
dbOrders, err := s.ipc.Database.MonthlyOrders.GetClientOrdersByManagerDB(ctx, managerID, month, year)
|
||||
if err != nil {
|
||||
fmt.Printf("🚨 ОШИБКА ЧТЕНИЯ ЗАКАЗОВ ИЗ БД: %v\n", err)
|
||||
}
|
||||
|
||||
ordersMap := make(map[string]*typescore.MonthlyOrderClient)
|
||||
for _, o := range dbOrders {
|
||||
if o.ID != nil {
|
||||
// Достаем цифры по номенклатуре из базы
|
||||
items, err := s.ipc.Database.MonthlyOrders.GetItemsByOrderIDDB(ctx, *o.ID)
|
||||
if err == nil && len(items) > 0 {
|
||||
for _, item := range items {
|
||||
|
|
@ -89,16 +94,20 @@ func (s *MonthlyOrderService) GetMyOrderData(ctx context.Context, managerID uint
|
|||
}
|
||||
|
||||
if o.ClientName != nil {
|
||||
ordersMap[*o.ClientName] = o
|
||||
// 🟢 Защита от невидимых пробелов (TrimSpace)
|
||||
cleanName := strings.TrimSpace(*o.ClientName)
|
||||
ordersMap[cleanName] = o
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Сливаем данные
|
||||
var clientDataList []FrontendClientData
|
||||
for _, gsc := range gsClients {
|
||||
// 🟢 Очищаем имя и со стороны Google Sheets тоже
|
||||
cleanName := strings.TrimSpace(gsc.Name)
|
||||
clientDataList = append(clientDataList, FrontendClientData{
|
||||
GoogleData: gsc,
|
||||
DBOrder: ordersMap[gsc.Name],
|
||||
DBOrder: ordersMap[cleanName],
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -174,18 +174,19 @@ func (s *MonthlyOrdersReg) SaveOrdersHandler(w http.ResponseWriter, r *http.Requ
|
|||
order.Month = &month
|
||||
order.Year = &year
|
||||
|
||||
if order.Status == nil {
|
||||
status := "draft"
|
||||
order.Status = &status
|
||||
}
|
||||
|
||||
if order.ClientName == nil || *order.ClientName == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if order.Status == nil {
|
||||
st := "draft"
|
||||
order.Status = &st
|
||||
}
|
||||
|
||||
_, err := s.ipc.Database.MonthlyOrders.SaveClientOrder(ctx, nil, &order)
|
||||
if err != nil {
|
||||
return nil, err // Здесь теперь вернется внятная ошибка, а не 500 panic
|
||||
logrus.Errorf("Не удалось сохранить заказ для клиента %s: %v", *order.ClientName, err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue