This commit is contained in:
@@ -41,3 +41,25 @@ func (s *CategoryService) AddCategory(ctx context.Context, category *CategoryEnt
|
||||
}
|
||||
return category, nil
|
||||
}
|
||||
|
||||
func (s *CategoryService) GetCategory(ctx context.Context, categoryId int) (*CategoryEntity, error) {
|
||||
query := `SELECT id, name, budget_id, favorite, monthly_limit FROM categories WHERE id = @id`
|
||||
args := pgx.NamedArgs{
|
||||
"id": categoryId,
|
||||
}
|
||||
rows, err := s.db.Query(ctx, query, args)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
categories := []*CategoryEntity{}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
category := &CategoryEntity{}
|
||||
err = rows.Scan(&category.Id, &category.Name, &category.BudgetId, &category.Favorite, &category.MonthlyLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
categories = append(categories, category)
|
||||
}
|
||||
return categories[0], nil
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,54 @@
|
||||
package waste
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.3crabs.ru/save_my_money/smm_core/internal/services/category"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type WasteEntity struct {
|
||||
Id int
|
||||
Name string
|
||||
Price int
|
||||
Amount float32
|
||||
BudgetId int
|
||||
CategoryId int
|
||||
}
|
||||
|
||||
type WasteService struct {
|
||||
db *pgxpool.Pool
|
||||
categoryService *category.CategoryService
|
||||
}
|
||||
|
||||
func NewWasteService(
|
||||
db *pgxpool.Pool,
|
||||
categoryService *category.CategoryService,
|
||||
) *WasteService {
|
||||
return &WasteService{
|
||||
db: db,
|
||||
categoryService: categoryService,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WasteService) AddWaste(ctx context.Context, waste *WasteEntity) (*WasteEntity, error) {
|
||||
category, err := s.categoryService.GetCategory(ctx, waste.CategoryId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
query := `INSERT INTO wastes (name, price, amount, budget_id, category_id) VALUES (@name, @price, @amount, @budget_id, @category_id) RETURNING id`
|
||||
args := pgx.NamedArgs{
|
||||
"name": waste.Name,
|
||||
"price": waste.Price,
|
||||
"amount": waste.Amount,
|
||||
"budget_id": category.BudgetId,
|
||||
"category_id": waste.CategoryId,
|
||||
}
|
||||
if err := s.db.QueryRow(ctx, query, args).Scan(&waste.Id); err != nil {
|
||||
return nil, fmt.Errorf("unable to insert row: %w", err)
|
||||
}
|
||||
return waste, nil
|
||||
}
|
||||
Reference in New Issue
Block a user