This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.3crabs.ru/save_my_money/smm_core/internal/services/context_utils"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type BudgetEntity struct {
|
||||
Id int
|
||||
Name string
|
||||
StartDay int
|
||||
MonthlyLimit int
|
||||
}
|
||||
|
||||
type BudgetService struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewBudgetService(
|
||||
db *pgxpool.Pool,
|
||||
) *BudgetService {
|
||||
return &BudgetService{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BudgetService) AddBudget(ctx context.Context, budget *BudgetEntity) (*BudgetEntity, error) {
|
||||
userId, err := context_utils.GetUserId(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
query := `INSERT INTO budgets (name, start_day, monthly_limit) VALUES (@name, @start_day, @monthly_limit) RETURNING id`
|
||||
args := pgx.NamedArgs{
|
||||
"name": budget.Name,
|
||||
"start_day": budget.StartDay,
|
||||
"monthly_limit": budget.MonthlyLimit,
|
||||
}
|
||||
if err := s.db.QueryRow(ctx, query, args).Scan(&budget.Id); err != nil {
|
||||
return nil, fmt.Errorf("unable to insert row: %w", err)
|
||||
}
|
||||
|
||||
query = `INSERT INTO users_budgets (user_id, budget_id) VALUES (@user_id, @budget_id) RETURNING id`
|
||||
args = pgx.NamedArgs{
|
||||
"user_id": userId,
|
||||
"budget_id": budget.Id,
|
||||
}
|
||||
if err := s.db.QueryRow(ctx, query, args).Scan(&budget.Id); err != nil {
|
||||
return nil, fmt.Errorf("unable to insert row: %w", err)
|
||||
}
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return budget, nil
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user