|
|
|
|
@ -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
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|