feature/core-service-api-structure #3

Merged
aep merged 17 commits from feature/core-service-api-structure into master 2025-08-27 15:11:10 +03:00
13 changed files with 1920 additions and 79 deletions
Showing only changes of commit f99db54c03 - Show all commits

View File

@@ -5,6 +5,7 @@ import (
"strings" "strings"
"erp-mvp/core-service/internal/auth" "erp-mvp/core-service/internal/auth"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -63,22 +64,22 @@ func GetClaims(c *gin.Context) *auth.Claims {
if !exists { if !exists {
return nil return nil
} }
orgID, exists := c.Get("organization_id") orgID, exists := c.Get("organization_id")
if !exists { if !exists {
return nil return nil
} }
email, exists := c.Get("email") email, exists := c.Get("email")
if !exists { if !exists {
return nil return nil
} }
role, exists := c.Get("role") role, exists := c.Get("role")
if !exists { if !exists {
return nil return nil
} }
return &auth.Claims{ return &auth.Claims{
UserID: userID.(uuid.UUID), UserID: userID.(uuid.UUID),
OrganizationID: orgID.(uuid.UUID), OrganizationID: orgID.(uuid.UUID),

View File

@@ -5,13 +5,13 @@ import (
"database/sql" "database/sql"
"net/http" "net/http"
"erp-mvp/core-service/internal/api/handlers"
"erp-mvp/core-service/internal/api/middleware"
"erp-mvp/core-service/internal/auth" "erp-mvp/core-service/internal/auth"
"erp-mvp/core-service/internal/config" "erp-mvp/core-service/internal/config"
"erp-mvp/core-service/internal/logger" "erp-mvp/core-service/internal/logger"
"erp-mvp/core-service/internal/repository" "erp-mvp/core-service/internal/repository"
"erp-mvp/core-service/internal/service" "erp-mvp/core-service/internal/service"
"erp-mvp/core-service/internal/api/handlers"
"erp-mvp/core-service/internal/api/middleware"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -23,15 +23,15 @@ type Server struct {
router *gin.Engine router *gin.Engine
// Services // Services
authService service.AuthService authService service.AuthService
locationService service.LocationService locationService service.LocationService
itemService service.ItemService itemService service.ItemService
operationsService service.OperationsService operationsService service.OperationsService
// Handlers // Handlers
authHandler *handlers.AuthHandler authHandler *handlers.AuthHandler
locationHandler *handlers.LocationHandler locationHandler *handlers.LocationHandler
itemHandler *handlers.ItemHandler itemHandler *handlers.ItemHandler
operationsHandler *handlers.OperationsHandler operationsHandler *handlers.OperationsHandler
// Middleware // Middleware
@@ -140,7 +140,7 @@ func (s *Server) setupRoutes() {
func (s *Server) healthCheck(c *gin.Context) { func (s *Server) healthCheck(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"status": "ok", "status": "ok",
"service": "erp-mvp-core", "service": "erp-mvp-core",
}) })
} }

View File

@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"erp-mvp/core-service/internal/models" "erp-mvp/core-service/internal/models"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -31,7 +32,7 @@ func (r *itemRepository) Create(ctx context.Context, item *models.Item) error {
INSERT INTO items (id, organization_id, name, description, category, created_at) INSERT INTO items (id, organization_id, name, description, category, created_at)
VALUES ($1, $2, $3, $4, $5, $6) VALUES ($1, $2, $3, $4, $5, $6)
` `
_, err := r.db.ExecContext(ctx, query, _, err := r.db.ExecContext(ctx, query,
item.ID, item.ID,
item.OrganizationID, item.OrganizationID,
@@ -43,7 +44,7 @@ func (r *itemRepository) Create(ctx context.Context, item *models.Item) error {
if err != nil { if err != nil {
return fmt.Errorf("failed to create item: %w", err) return fmt.Errorf("failed to create item: %w", err)
} }
return nil return nil
} }
@@ -53,7 +54,7 @@ func (r *itemRepository) GetByID(ctx context.Context, id uuid.UUID, orgID uuid.U
FROM items FROM items
WHERE id = $1 AND organization_id = $2 WHERE id = $1 AND organization_id = $2
` `
item := &models.Item{} item := &models.Item{}
err := r.db.QueryRowContext(ctx, query, id, orgID).Scan( err := r.db.QueryRowContext(ctx, query, id, orgID).Scan(
&item.ID, &item.ID,
@@ -63,14 +64,14 @@ func (r *itemRepository) GetByID(ctx context.Context, id uuid.UUID, orgID uuid.U
&item.Category, &item.Category,
&item.CreatedAt, &item.CreatedAt,
) )
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return nil, fmt.Errorf("item not found") return nil, fmt.Errorf("item not found")
} }
return nil, fmt.Errorf("failed to get item: %w", err) return nil, fmt.Errorf("failed to get item: %w", err)
} }
return item, nil return item, nil
} }
@@ -81,13 +82,13 @@ func (r *itemRepository) GetByOrganization(ctx context.Context, orgID uuid.UUID)
WHERE organization_id = $1 WHERE organization_id = $1
ORDER BY name ORDER BY name
` `
rows, err := r.db.QueryContext(ctx, query, orgID) rows, err := r.db.QueryContext(ctx, query, orgID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to query items: %w", err) return nil, fmt.Errorf("failed to query items: %w", err)
} }
defer rows.Close() defer rows.Close()
var items []*models.Item var items []*models.Item
for rows.Next() { for rows.Next() {
item := &models.Item{} item := &models.Item{}
@@ -102,14 +103,14 @@ func (r *itemRepository) GetByOrganization(ctx context.Context, orgID uuid.UUID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to scan item: %w", err) return nil, fmt.Errorf("failed to scan item: %w", err)
} }
items = append(items, item) items = append(items, item)
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating items: %w", err) return nil, fmt.Errorf("error iterating items: %w", err)
} }
return items, nil return items, nil
} }
@@ -119,7 +120,7 @@ func (r *itemRepository) Update(ctx context.Context, item *models.Item) error {
SET name = $3, description = $4, category = $5 SET name = $3, description = $4, category = $5
WHERE id = $1 AND organization_id = $2 WHERE id = $1 AND organization_id = $2
` `
result, err := r.db.ExecContext(ctx, query, result, err := r.db.ExecContext(ctx, query,
item.ID, item.ID,
item.OrganizationID, item.OrganizationID,
@@ -130,16 +131,16 @@ func (r *itemRepository) Update(ctx context.Context, item *models.Item) error {
if err != nil { if err != nil {
return fmt.Errorf("failed to update item: %w", err) return fmt.Errorf("failed to update item: %w", err)
} }
rowsAffected, err := result.RowsAffected() rowsAffected, err := result.RowsAffected()
if err != nil { if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err) return fmt.Errorf("failed to get rows affected: %w", err)
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Errorf("item not found") return fmt.Errorf("item not found")
} }
return nil return nil
} }
@@ -148,21 +149,21 @@ func (r *itemRepository) Delete(ctx context.Context, id uuid.UUID, orgID uuid.UU
DELETE FROM items DELETE FROM items
WHERE id = $1 AND organization_id = $2 WHERE id = $1 AND organization_id = $2
` `
result, err := r.db.ExecContext(ctx, query, id, orgID) result, err := r.db.ExecContext(ctx, query, id, orgID)
if err != nil { if err != nil {
return fmt.Errorf("failed to delete item: %w", err) return fmt.Errorf("failed to delete item: %w", err)
} }
rowsAffected, err := result.RowsAffected() rowsAffected, err := result.RowsAffected()
if err != nil { if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err) return fmt.Errorf("failed to get rows affected: %w", err)
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Errorf("item not found") return fmt.Errorf("item not found")
} }
return nil return nil
} }
@@ -172,31 +173,31 @@ func (r *itemRepository) Search(ctx context.Context, orgID uuid.UUID, query stri
FROM items FROM items
WHERE organization_id = $1 WHERE organization_id = $1
` `
var args []interface{} var args []interface{}
args = append(args, orgID) args = append(args, orgID)
argIndex := 2 argIndex := 2
if query != "" { if query != "" {
baseQuery += fmt.Sprintf(" AND (name ILIKE $%d OR description ILIKE $%d)", argIndex, argIndex) baseQuery += fmt.Sprintf(" AND (name ILIKE $%d OR description ILIKE $%d)", argIndex, argIndex)
args = append(args, "%"+query+"%") args = append(args, "%"+query+"%")
argIndex++ argIndex++
} }
if category != "" { if category != "" {
baseQuery += fmt.Sprintf(" AND category = $%d", argIndex) baseQuery += fmt.Sprintf(" AND category = $%d", argIndex)
args = append(args, category) args = append(args, category)
argIndex++ argIndex++
} }
baseQuery += " ORDER BY name" baseQuery += " ORDER BY name"
rows, err := r.db.QueryContext(ctx, baseQuery, args...) rows, err := r.db.QueryContext(ctx, baseQuery, args...)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to search items: %w", err) return nil, fmt.Errorf("failed to search items: %w", err)
} }
defer rows.Close() defer rows.Close()
var items []*models.Item var items []*models.Item
for rows.Next() { for rows.Next() {
item := &models.Item{} item := &models.Item{}
@@ -211,13 +212,13 @@ func (r *itemRepository) Search(ctx context.Context, orgID uuid.UUID, query stri
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to scan item: %w", err) return nil, fmt.Errorf("failed to scan item: %w", err)
} }
items = append(items, item) items = append(items, item)
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating search results: %w", err) return nil, fmt.Errorf("error iterating search results: %w", err)
} }
return items, nil return items, nil
} }

View File

@@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"erp-mvp/core-service/internal/models" "erp-mvp/core-service/internal/models"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -32,7 +33,7 @@ func (r *locationRepository) Create(ctx context.Context, location *models.Storag
INSERT INTO storage_locations (id, organization_id, parent_id, name, address, type, coordinates, created_at) INSERT INTO storage_locations (id, organization_id, parent_id, name, address, type, coordinates, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
` `
// Конвертируем JSON в строку // Конвертируем JSON в строку
var coordinatesJSON string var coordinatesJSON string
if location.Coordinates != nil { if location.Coordinates != nil {
@@ -42,7 +43,7 @@ func (r *locationRepository) Create(ctx context.Context, location *models.Storag
} }
coordinatesJSON = string(coords) coordinatesJSON = string(coords)
} }
_, err := r.db.ExecContext(ctx, query, _, err := r.db.ExecContext(ctx, query,
location.ID, location.ID,
location.OrganizationID, location.OrganizationID,
@@ -56,7 +57,7 @@ func (r *locationRepository) Create(ctx context.Context, location *models.Storag
if err != nil { if err != nil {
return fmt.Errorf("failed to create storage location: %w", err) return fmt.Errorf("failed to create storage location: %w", err)
} }
return nil return nil
} }
@@ -66,7 +67,7 @@ func (r *locationRepository) GetByID(ctx context.Context, id uuid.UUID, orgID uu
FROM storage_locations FROM storage_locations
WHERE id = $1 AND organization_id = $2 WHERE id = $1 AND organization_id = $2
` `
var coordinatesJSON []byte var coordinatesJSON []byte
location := &models.StorageLocation{} location := &models.StorageLocation{}
err := r.db.QueryRowContext(ctx, query, id, orgID).Scan( err := r.db.QueryRowContext(ctx, query, id, orgID).Scan(
@@ -79,14 +80,14 @@ func (r *locationRepository) GetByID(ctx context.Context, id uuid.UUID, orgID uu
&coordinatesJSON, &coordinatesJSON,
&location.CreatedAt, &location.CreatedAt,
) )
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return nil, fmt.Errorf("storage location not found") return nil, fmt.Errorf("storage location not found")
} }
return nil, fmt.Errorf("failed to get storage location: %w", err) return nil, fmt.Errorf("failed to get storage location: %w", err)
} }
// Конвертируем JSON строку в map // Конвертируем JSON строку в map
if len(coordinatesJSON) > 0 { if len(coordinatesJSON) > 0 {
err = json.Unmarshal(coordinatesJSON, &location.Coordinates) err = json.Unmarshal(coordinatesJSON, &location.Coordinates)
@@ -96,7 +97,7 @@ func (r *locationRepository) GetByID(ctx context.Context, id uuid.UUID, orgID uu
} else { } else {
location.Coordinates = make(models.JSON) location.Coordinates = make(models.JSON)
} }
return location, nil return location, nil
} }
@@ -107,13 +108,13 @@ func (r *locationRepository) GetByOrganization(ctx context.Context, orgID uuid.U
WHERE organization_id = $1 WHERE organization_id = $1
ORDER BY name ORDER BY name
` `
rows, err := r.db.QueryContext(ctx, query, orgID) rows, err := r.db.QueryContext(ctx, query, orgID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to query storage locations: %w", err) return nil, fmt.Errorf("failed to query storage locations: %w", err)
} }
defer rows.Close() defer rows.Close()
var locations []*models.StorageLocation var locations []*models.StorageLocation
for rows.Next() { for rows.Next() {
var coordinatesJSON []byte var coordinatesJSON []byte
@@ -131,7 +132,7 @@ func (r *locationRepository) GetByOrganization(ctx context.Context, orgID uuid.U
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to scan storage location: %w", err) return nil, fmt.Errorf("failed to scan storage location: %w", err)
} }
// Конвертируем JSON строку в map // Конвертируем JSON строку в map
if len(coordinatesJSON) > 0 { if len(coordinatesJSON) > 0 {
err = json.Unmarshal(coordinatesJSON, &location.Coordinates) err = json.Unmarshal(coordinatesJSON, &location.Coordinates)
@@ -141,14 +142,14 @@ func (r *locationRepository) GetByOrganization(ctx context.Context, orgID uuid.U
} else { } else {
location.Coordinates = make(models.JSON) location.Coordinates = make(models.JSON)
} }
locations = append(locations, location) locations = append(locations, location)
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating storage locations: %w", err) return nil, fmt.Errorf("error iterating storage locations: %w", err)
} }
return locations, nil return locations, nil
} }
@@ -158,7 +159,7 @@ func (r *locationRepository) Update(ctx context.Context, location *models.Storag
SET parent_id = $3, name = $4, address = $5, type = $6, coordinates = $7 SET parent_id = $3, name = $4, address = $5, type = $6, coordinates = $7
WHERE id = $1 AND organization_id = $2 WHERE id = $1 AND organization_id = $2
` `
// Конвертируем JSON в строку // Конвертируем JSON в строку
var coordinatesJSON string var coordinatesJSON string
if location.Coordinates != nil { if location.Coordinates != nil {
@@ -168,7 +169,7 @@ func (r *locationRepository) Update(ctx context.Context, location *models.Storag
} }
coordinatesJSON = string(coords) coordinatesJSON = string(coords)
} }
result, err := r.db.ExecContext(ctx, query, result, err := r.db.ExecContext(ctx, query,
location.ID, location.ID,
location.OrganizationID, location.OrganizationID,
@@ -181,16 +182,16 @@ func (r *locationRepository) Update(ctx context.Context, location *models.Storag
if err != nil { if err != nil {
return fmt.Errorf("failed to update storage location: %w", err) return fmt.Errorf("failed to update storage location: %w", err)
} }
rowsAffected, err := result.RowsAffected() rowsAffected, err := result.RowsAffected()
if err != nil { if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err) return fmt.Errorf("failed to get rows affected: %w", err)
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Errorf("storage location not found") return fmt.Errorf("storage location not found")
} }
return nil return nil
} }
@@ -199,21 +200,21 @@ func (r *locationRepository) Delete(ctx context.Context, id uuid.UUID, orgID uui
DELETE FROM storage_locations DELETE FROM storage_locations
WHERE id = $1 AND organization_id = $2 WHERE id = $1 AND organization_id = $2
` `
result, err := r.db.ExecContext(ctx, query, id, orgID) result, err := r.db.ExecContext(ctx, query, id, orgID)
if err != nil { if err != nil {
return fmt.Errorf("failed to delete storage location: %w", err) return fmt.Errorf("failed to delete storage location: %w", err)
} }
rowsAffected, err := result.RowsAffected() rowsAffected, err := result.RowsAffected()
if err != nil { if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err) return fmt.Errorf("failed to get rows affected: %w", err)
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Errorf("storage location not found") return fmt.Errorf("storage location not found")
} }
return nil return nil
} }
@@ -224,13 +225,13 @@ func (r *locationRepository) GetChildren(ctx context.Context, parentID uuid.UUID
WHERE parent_id = $1 AND organization_id = $2 WHERE parent_id = $1 AND organization_id = $2
ORDER BY name ORDER BY name
` `
rows, err := r.db.QueryContext(ctx, query, parentID, orgID) rows, err := r.db.QueryContext(ctx, query, parentID, orgID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to query child locations: %w", err) return nil, fmt.Errorf("failed to query child locations: %w", err)
} }
defer rows.Close() defer rows.Close()
var locations []*models.StorageLocation var locations []*models.StorageLocation
for rows.Next() { for rows.Next() {
var coordinatesJSON []byte var coordinatesJSON []byte
@@ -248,7 +249,7 @@ func (r *locationRepository) GetChildren(ctx context.Context, parentID uuid.UUID
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to scan child location: %w", err) return nil, fmt.Errorf("failed to scan child location: %w", err)
} }
// Конвертируем JSON строку в map // Конвертируем JSON строку в map
if len(coordinatesJSON) > 0 { if len(coordinatesJSON) > 0 {
err = json.Unmarshal(coordinatesJSON, &location.Coordinates) err = json.Unmarshal(coordinatesJSON, &location.Coordinates)
@@ -258,13 +259,13 @@ func (r *locationRepository) GetChildren(ctx context.Context, parentID uuid.UUID
} else { } else {
location.Coordinates = make(models.JSON) location.Coordinates = make(models.JSON)
} }
locations = append(locations, location) locations = append(locations, location)
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating child locations: %w", err) return nil, fmt.Errorf("error iterating child locations: %w", err)
} }
return locations, nil return locations, nil
} }

View File

@@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"erp-mvp/core-service/internal/models" "erp-mvp/core-service/internal/models"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -34,7 +35,7 @@ func (r *operationsRepository) PlaceItem(ctx context.Context, placement *models.
INSERT INTO item_placements (id, organization_id, item_id, location_id, quantity, created_at) INSERT INTO item_placements (id, organization_id, item_id, location_id, quantity, created_at)
VALUES ($1, $2, $3, $4, $5, $6) VALUES ($1, $2, $3, $4, $5, $6)
` `
_, err := r.db.ExecContext(ctx, query, _, err := r.db.ExecContext(ctx, query,
placement.ID, placement.ID,
placement.OrganizationID, placement.OrganizationID,
@@ -46,7 +47,7 @@ func (r *operationsRepository) PlaceItem(ctx context.Context, placement *models.
if err != nil { if err != nil {
return fmt.Errorf("failed to place item: %w", err) return fmt.Errorf("failed to place item: %w", err)
} }
return nil return nil
} }
@@ -56,21 +57,21 @@ func (r *operationsRepository) MoveItem(ctx context.Context, placementID uuid.UU
SET location_id = $2 SET location_id = $2
WHERE id = $1 AND organization_id = $3 WHERE id = $1 AND organization_id = $3
` `
result, err := r.db.ExecContext(ctx, query, placementID, newLocationID, orgID) result, err := r.db.ExecContext(ctx, query, placementID, newLocationID, orgID)
if err != nil { if err != nil {
return fmt.Errorf("failed to move item: %w", err) return fmt.Errorf("failed to move item: %w", err)
} }
rowsAffected, err := result.RowsAffected() rowsAffected, err := result.RowsAffected()
if err != nil { if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err) return fmt.Errorf("failed to get rows affected: %w", err)
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Errorf("item placement not found") return fmt.Errorf("item placement not found")
} }
return nil return nil
} }
@@ -81,13 +82,13 @@ func (r *operationsRepository) GetByItem(ctx context.Context, itemID uuid.UUID,
WHERE item_id = $1 AND organization_id = $2 WHERE item_id = $1 AND organization_id = $2
ORDER BY created_at DESC ORDER BY created_at DESC
` `
rows, err := r.db.QueryContext(ctx, query, itemID, orgID) rows, err := r.db.QueryContext(ctx, query, itemID, orgID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to query item placements: %w", err) return nil, fmt.Errorf("failed to query item placements: %w", err)
} }
defer rows.Close() defer rows.Close()
var placements []*models.ItemPlacement var placements []*models.ItemPlacement
for rows.Next() { for rows.Next() {
placement := &models.ItemPlacement{} placement := &models.ItemPlacement{}
@@ -102,14 +103,14 @@ func (r *operationsRepository) GetByItem(ctx context.Context, itemID uuid.UUID,
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to scan item placement: %w", err) return nil, fmt.Errorf("failed to scan item placement: %w", err)
} }
placements = append(placements, placement) placements = append(placements, placement)
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating item placements: %w", err) return nil, fmt.Errorf("error iterating item placements: %w", err)
} }
return placements, nil return placements, nil
} }
@@ -120,13 +121,13 @@ func (r *operationsRepository) GetByLocation(ctx context.Context, locationID uui
WHERE location_id = $1 AND organization_id = $2 WHERE location_id = $1 AND organization_id = $2
ORDER BY created_at DESC ORDER BY created_at DESC
` `
rows, err := r.db.QueryContext(ctx, query, locationID, orgID) rows, err := r.db.QueryContext(ctx, query, locationID, orgID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to query location placements: %w", err) return nil, fmt.Errorf("failed to query location placements: %w", err)
} }
defer rows.Close() defer rows.Close()
var placements []*models.ItemPlacement var placements []*models.ItemPlacement
for rows.Next() { for rows.Next() {
placement := &models.ItemPlacement{} placement := &models.ItemPlacement{}
@@ -141,14 +142,14 @@ func (r *operationsRepository) GetByLocation(ctx context.Context, locationID uui
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to scan item placement: %w", err) return nil, fmt.Errorf("failed to scan item placement: %w", err)
} }
placements = append(placements, placement) placements = append(placements, placement)
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating location placements: %w", err) return nil, fmt.Errorf("error iterating location placements: %w", err)
} }
return placements, nil return placements, nil
} }
@@ -158,7 +159,7 @@ func (r *operationsRepository) GetByID(ctx context.Context, id uuid.UUID, orgID
FROM item_placements FROM item_placements
WHERE id = $1 AND organization_id = $2 WHERE id = $1 AND organization_id = $2
` `
placement := &models.ItemPlacement{} placement := &models.ItemPlacement{}
err := r.db.QueryRowContext(ctx, query, id, orgID).Scan( err := r.db.QueryRowContext(ctx, query, id, orgID).Scan(
&placement.ID, &placement.ID,
@@ -168,14 +169,14 @@ func (r *operationsRepository) GetByID(ctx context.Context, id uuid.UUID, orgID
&placement.Quantity, &placement.Quantity,
&placement.CreatedAt, &placement.CreatedAt,
) )
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return nil, fmt.Errorf("item placement not found") return nil, fmt.Errorf("item placement not found")
} }
return nil, fmt.Errorf("failed to get item placement: %w", err) return nil, fmt.Errorf("failed to get item placement: %w", err)
} }
return placement, nil return placement, nil
} }
@@ -185,21 +186,21 @@ func (r *operationsRepository) UpdateQuantity(ctx context.Context, id uuid.UUID,
SET quantity = $2 SET quantity = $2
WHERE id = $1 AND organization_id = $3 WHERE id = $1 AND organization_id = $3
` `
result, err := r.db.ExecContext(ctx, query, id, quantity, orgID) result, err := r.db.ExecContext(ctx, query, id, quantity, orgID)
if err != nil { if err != nil {
return fmt.Errorf("failed to update quantity: %w", err) return fmt.Errorf("failed to update quantity: %w", err)
} }
rowsAffected, err := result.RowsAffected() rowsAffected, err := result.RowsAffected()
if err != nil { if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err) return fmt.Errorf("failed to get rows affected: %w", err)
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Errorf("item placement not found") return fmt.Errorf("item placement not found")
} }
return nil return nil
} }
@@ -208,21 +209,21 @@ func (r *operationsRepository) Delete(ctx context.Context, id uuid.UUID, orgID u
DELETE FROM item_placements DELETE FROM item_placements
WHERE id = $1 AND organization_id = $2 WHERE id = $1 AND organization_id = $2
` `
result, err := r.db.ExecContext(ctx, query, id, orgID) result, err := r.db.ExecContext(ctx, query, id, orgID)
if err != nil { if err != nil {
return fmt.Errorf("failed to delete item placement: %w", err) return fmt.Errorf("failed to delete item placement: %w", err)
} }
rowsAffected, err := result.RowsAffected() rowsAffected, err := result.RowsAffected()
if err != nil { if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err) return fmt.Errorf("failed to get rows affected: %w", err)
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Errorf("item placement not found") return fmt.Errorf("item placement not found")
} }
return nil return nil
} }
@@ -237,42 +238,42 @@ func (r *operationsRepository) Search(ctx context.Context, orgID uuid.UUID, quer
JOIN storage_locations sl ON ip.location_id = sl.id JOIN storage_locations sl ON ip.location_id = sl.id
WHERE i.organization_id = $1 AND sl.organization_id = $1 WHERE i.organization_id = $1 AND sl.organization_id = $1
` `
var args []interface{} var args []interface{}
args = append(args, orgID) args = append(args, orgID)
argIndex := 2 argIndex := 2
if query != "" { if query != "" {
baseQuery += fmt.Sprintf(" AND (i.name ILIKE $%d OR i.description ILIKE $%d)", argIndex, argIndex) baseQuery += fmt.Sprintf(" AND (i.name ILIKE $%d OR i.description ILIKE $%d)", argIndex, argIndex)
args = append(args, "%"+query+"%") args = append(args, "%"+query+"%")
argIndex++ argIndex++
} }
if category != "" { if category != "" {
baseQuery += fmt.Sprintf(" AND i.category = $%d", argIndex) baseQuery += fmt.Sprintf(" AND i.category = $%d", argIndex)
args = append(args, category) args = append(args, category)
argIndex++ argIndex++
} }
if address != "" { if address != "" {
baseQuery += fmt.Sprintf(" AND sl.address ILIKE $%d", argIndex) baseQuery += fmt.Sprintf(" AND sl.address ILIKE $%d", argIndex)
args = append(args, "%"+address+"%") args = append(args, "%"+address+"%")
argIndex++ argIndex++
} }
baseQuery += " ORDER BY i.name, sl.name" baseQuery += " ORDER BY i.name, sl.name"
rows, err := r.db.QueryContext(ctx, baseQuery, args...) rows, err := r.db.QueryContext(ctx, baseQuery, args...)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to search items with locations: %w", err) return nil, fmt.Errorf("failed to search items with locations: %w", err)
} }
defer rows.Close() defer rows.Close()
var results []*models.ItemWithLocation var results []*models.ItemWithLocation
for rows.Next() { for rows.Next() {
var coordinatesJSON []byte var coordinatesJSON []byte
itemWithLocation := &models.ItemWithLocation{} itemWithLocation := &models.ItemWithLocation{}
err := rows.Scan( err := rows.Scan(
&itemWithLocation.Item.ID, &itemWithLocation.Item.ID,
&itemWithLocation.Item.OrganizationID, &itemWithLocation.Item.OrganizationID,
@@ -293,7 +294,7 @@ func (r *operationsRepository) Search(ctx context.Context, orgID uuid.UUID, quer
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to scan item with location: %w", err) return nil, fmt.Errorf("failed to scan item with location: %w", err)
} }
// Конвертируем JSON строку в map // Конвертируем JSON строку в map
if len(coordinatesJSON) > 0 { if len(coordinatesJSON) > 0 {
err = json.Unmarshal(coordinatesJSON, &itemWithLocation.Location.Coordinates) err = json.Unmarshal(coordinatesJSON, &itemWithLocation.Location.Coordinates)
@@ -303,13 +304,13 @@ func (r *operationsRepository) Search(ctx context.Context, orgID uuid.UUID, quer
} else { } else {
itemWithLocation.Location.Coordinates = make(models.JSON) itemWithLocation.Location.Coordinates = make(models.JSON)
} }
results = append(results, itemWithLocation) results = append(results, itemWithLocation)
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating search results: %w", err) return nil, fmt.Errorf("error iterating search results: %w", err)
} }
return results, nil return results, nil
} }

View File

@@ -34,7 +34,7 @@ func NewItemService(itemRepo repository.ItemRepository) ItemService {
func (s *itemService) CreateItem(ctx context.Context, orgID uuid.UUID, req *models.CreateItemRequest) (*models.Item, error) { func (s *itemService) CreateItem(ctx context.Context, orgID uuid.UUID, req *models.CreateItemRequest) (*models.Item, error) {
s.logger.Info("Creating item for organization: ", orgID) s.logger.Info("Creating item for organization: ", orgID)
item := &models.Item{ item := &models.Item{
ID: uuid.New(), ID: uuid.New(),
OrganizationID: orgID, OrganizationID: orgID,
@@ -43,84 +43,84 @@ func (s *itemService) CreateItem(ctx context.Context, orgID uuid.UUID, req *mode
Category: req.Category, Category: req.Category,
CreatedAt: time.Now(), CreatedAt: time.Now(),
} }
if err := s.itemRepo.Create(ctx, item); err != nil { if err := s.itemRepo.Create(ctx, item); err != nil {
s.logger.Error("Failed to create item: ", err) s.logger.Error("Failed to create item: ", err)
return nil, err return nil, err
} }
s.logger.Info("Item created successfully: ", item.ID) s.logger.Info("Item created successfully: ", item.ID)
return item, nil return item, nil
} }
func (s *itemService) GetItem(ctx context.Context, id uuid.UUID, orgID uuid.UUID) (*models.Item, error) { func (s *itemService) GetItem(ctx context.Context, id uuid.UUID, orgID uuid.UUID) (*models.Item, error) {
s.logger.Info("Getting item: ", id, " for organization: ", orgID) s.logger.Info("Getting item: ", id, " for organization: ", orgID)
item, err := s.itemRepo.GetByID(ctx, id, orgID) item, err := s.itemRepo.GetByID(ctx, id, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get item: ", err) s.logger.Error("Failed to get item: ", err)
return nil, err return nil, err
} }
return item, nil return item, nil
} }
func (s *itemService) GetItems(ctx context.Context, orgID uuid.UUID) ([]*models.Item, error) { func (s *itemService) GetItems(ctx context.Context, orgID uuid.UUID) ([]*models.Item, error) {
s.logger.Info("Getting all items for organization: ", orgID) s.logger.Info("Getting all items for organization: ", orgID)
items, err := s.itemRepo.GetByOrganization(ctx, orgID) items, err := s.itemRepo.GetByOrganization(ctx, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get items: ", err) s.logger.Error("Failed to get items: ", err)
return nil, err return nil, err
} }
return items, nil return items, nil
} }
func (s *itemService) UpdateItem(ctx context.Context, id uuid.UUID, orgID uuid.UUID, req *models.CreateItemRequest) (*models.Item, error) { func (s *itemService) UpdateItem(ctx context.Context, id uuid.UUID, orgID uuid.UUID, req *models.CreateItemRequest) (*models.Item, error) {
s.logger.Info("Updating item: ", id, " for organization: ", orgID) s.logger.Info("Updating item: ", id, " for organization: ", orgID)
// Сначала получаем существующий товар // Сначала получаем существующий товар
item, err := s.itemRepo.GetByID(ctx, id, orgID) item, err := s.itemRepo.GetByID(ctx, id, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get item for update: ", err) s.logger.Error("Failed to get item for update: ", err)
return nil, err return nil, err
} }
// Обновляем поля // Обновляем поля
item.Name = req.Name item.Name = req.Name
item.Description = req.Description item.Description = req.Description
item.Category = req.Category item.Category = req.Category
if err := s.itemRepo.Update(ctx, item); err != nil { if err := s.itemRepo.Update(ctx, item); err != nil {
s.logger.Error("Failed to update item: ", err) s.logger.Error("Failed to update item: ", err)
return nil, err return nil, err
} }
s.logger.Info("Item updated successfully: ", item.ID) s.logger.Info("Item updated successfully: ", item.ID)
return item, nil return item, nil
} }
func (s *itemService) DeleteItem(ctx context.Context, id uuid.UUID, orgID uuid.UUID) error { func (s *itemService) DeleteItem(ctx context.Context, id uuid.UUID, orgID uuid.UUID) error {
s.logger.Info("Deleting item: ", id, " for organization: ", orgID) s.logger.Info("Deleting item: ", id, " for organization: ", orgID)
if err := s.itemRepo.Delete(ctx, id, orgID); err != nil { if err := s.itemRepo.Delete(ctx, id, orgID); err != nil {
s.logger.Error("Failed to delete item: ", err) s.logger.Error("Failed to delete item: ", err)
return err return err
} }
s.logger.Info("Item deleted successfully: ", id) s.logger.Info("Item deleted successfully: ", id)
return nil return nil
} }
func (s *itemService) SearchItems(ctx context.Context, orgID uuid.UUID, query string, category string) ([]*models.Item, error) { func (s *itemService) SearchItems(ctx context.Context, orgID uuid.UUID, query string, category string) ([]*models.Item, error) {
s.logger.Info("Searching items for organization: ", orgID, " query: ", query, " category: ", category) s.logger.Info("Searching items for organization: ", orgID, " query: ", query, " category: ", category)
items, err := s.itemRepo.Search(ctx, orgID, query, category) items, err := s.itemRepo.Search(ctx, orgID, query, category)
if err != nil { if err != nil {
s.logger.Error("Failed to search items: ", err) s.logger.Error("Failed to search items: ", err)
return nil, err return nil, err
} }
return items, nil return items, nil
} }

View File

@@ -34,7 +34,7 @@ func NewLocationService(locationRepo repository.LocationRepository) LocationServ
func (s *locationService) CreateLocation(ctx context.Context, orgID uuid.UUID, req *models.CreateLocationRequest) (*models.StorageLocation, error) { func (s *locationService) CreateLocation(ctx context.Context, orgID uuid.UUID, req *models.CreateLocationRequest) (*models.StorageLocation, error) {
s.logger.Info("Creating location for organization: ", orgID) s.logger.Info("Creating location for organization: ", orgID)
location := &models.StorageLocation{ location := &models.StorageLocation{
ID: uuid.New(), ID: uuid.New(),
OrganizationID: orgID, OrganizationID: orgID,
@@ -45,86 +45,86 @@ func (s *locationService) CreateLocation(ctx context.Context, orgID uuid.UUID, r
Coordinates: req.Coordinates, Coordinates: req.Coordinates,
CreatedAt: time.Now(), CreatedAt: time.Now(),
} }
if err := s.locationRepo.Create(ctx, location); err != nil { if err := s.locationRepo.Create(ctx, location); err != nil {
s.logger.Error("Failed to create location: ", err) s.logger.Error("Failed to create location: ", err)
return nil, err return nil, err
} }
s.logger.Info("Location created successfully: ", location.ID) s.logger.Info("Location created successfully: ", location.ID)
return location, nil return location, nil
} }
func (s *locationService) GetLocation(ctx context.Context, id uuid.UUID, orgID uuid.UUID) (*models.StorageLocation, error) { func (s *locationService) GetLocation(ctx context.Context, id uuid.UUID, orgID uuid.UUID) (*models.StorageLocation, error) {
s.logger.Info("Getting location: ", id, " for organization: ", orgID) s.logger.Info("Getting location: ", id, " for organization: ", orgID)
location, err := s.locationRepo.GetByID(ctx, id, orgID) location, err := s.locationRepo.GetByID(ctx, id, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get location: ", err) s.logger.Error("Failed to get location: ", err)
return nil, err return nil, err
} }
return location, nil return location, nil
} }
func (s *locationService) GetLocations(ctx context.Context, orgID uuid.UUID) ([]*models.StorageLocation, error) { func (s *locationService) GetLocations(ctx context.Context, orgID uuid.UUID) ([]*models.StorageLocation, error) {
s.logger.Info("Getting all locations for organization: ", orgID) s.logger.Info("Getting all locations for organization: ", orgID)
locations, err := s.locationRepo.GetByOrganization(ctx, orgID) locations, err := s.locationRepo.GetByOrganization(ctx, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get locations: ", err) s.logger.Error("Failed to get locations: ", err)
return nil, err return nil, err
} }
return locations, nil return locations, nil
} }
func (s *locationService) UpdateLocation(ctx context.Context, id uuid.UUID, orgID uuid.UUID, req *models.CreateLocationRequest) (*models.StorageLocation, error) { func (s *locationService) UpdateLocation(ctx context.Context, id uuid.UUID, orgID uuid.UUID, req *models.CreateLocationRequest) (*models.StorageLocation, error) {
s.logger.Info("Updating location: ", id, " for organization: ", orgID) s.logger.Info("Updating location: ", id, " for organization: ", orgID)
// Сначала получаем существующую локацию // Сначала получаем существующую локацию
location, err := s.locationRepo.GetByID(ctx, id, orgID) location, err := s.locationRepo.GetByID(ctx, id, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get location for update: ", err) s.logger.Error("Failed to get location for update: ", err)
return nil, err return nil, err
} }
// Обновляем поля // Обновляем поля
location.ParentID = req.ParentID location.ParentID = req.ParentID
location.Name = req.Name location.Name = req.Name
location.Address = req.Address location.Address = req.Address
location.Type = req.Type location.Type = req.Type
location.Coordinates = req.Coordinates location.Coordinates = req.Coordinates
if err := s.locationRepo.Update(ctx, location); err != nil { if err := s.locationRepo.Update(ctx, location); err != nil {
s.logger.Error("Failed to update location: ", err) s.logger.Error("Failed to update location: ", err)
return nil, err return nil, err
} }
s.logger.Info("Location updated successfully: ", location.ID) s.logger.Info("Location updated successfully: ", location.ID)
return location, nil return location, nil
} }
func (s *locationService) DeleteLocation(ctx context.Context, id uuid.UUID, orgID uuid.UUID) error { func (s *locationService) DeleteLocation(ctx context.Context, id uuid.UUID, orgID uuid.UUID) error {
s.logger.Info("Deleting location: ", id, " for organization: ", orgID) s.logger.Info("Deleting location: ", id, " for organization: ", orgID)
if err := s.locationRepo.Delete(ctx, id, orgID); err != nil { if err := s.locationRepo.Delete(ctx, id, orgID); err != nil {
s.logger.Error("Failed to delete location: ", err) s.logger.Error("Failed to delete location: ", err)
return err return err
} }
s.logger.Info("Location deleted successfully: ", id) s.logger.Info("Location deleted successfully: ", id)
return nil return nil
} }
func (s *locationService) GetChildren(ctx context.Context, parentID uuid.UUID, orgID uuid.UUID) ([]*models.StorageLocation, error) { func (s *locationService) GetChildren(ctx context.Context, parentID uuid.UUID, orgID uuid.UUID) ([]*models.StorageLocation, error) {
s.logger.Info("Getting children for location: ", parentID, " in organization: ", orgID) s.logger.Info("Getting children for location: ", parentID, " in organization: ", orgID)
children, err := s.locationRepo.GetChildren(ctx, parentID, orgID) children, err := s.locationRepo.GetChildren(ctx, parentID, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get children: ", err) s.logger.Error("Failed to get children: ", err)
return nil, err return nil, err
} }
return children, nil return children, nil
} }

View File

@@ -39,21 +39,21 @@ func NewOperationsService(operationsRepo repository.OperationsRepository, itemRe
func (s *operationsService) PlaceItem(ctx context.Context, orgID uuid.UUID, req *models.PlaceItemRequest) (*models.ItemPlacement, error) { func (s *operationsService) PlaceItem(ctx context.Context, orgID uuid.UUID, req *models.PlaceItemRequest) (*models.ItemPlacement, error) {
s.logger.Info("Placing item: ", req.ItemID, " in location: ", req.LocationID, " for organization: ", orgID) s.logger.Info("Placing item: ", req.ItemID, " in location: ", req.LocationID, " for organization: ", orgID)
// Проверяем, что товар существует и принадлежит организации // Проверяем, что товар существует и принадлежит организации
_, err := s.itemRepo.GetByID(ctx, req.ItemID, orgID) _, err := s.itemRepo.GetByID(ctx, req.ItemID, orgID)
if err != nil { if err != nil {
s.logger.Error("Item not found or not accessible: ", err) s.logger.Error("Item not found or not accessible: ", err)
return nil, err return nil, err
} }
// Проверяем, что место хранения существует и принадлежит организации // Проверяем, что место хранения существует и принадлежит организации
_, err = s.locationRepo.GetByID(ctx, req.LocationID, orgID) _, err = s.locationRepo.GetByID(ctx, req.LocationID, orgID)
if err != nil { if err != nil {
s.logger.Error("Location not found or not accessible: ", err) s.logger.Error("Location not found or not accessible: ", err)
return nil, err return nil, err
} }
placement := &models.ItemPlacement{ placement := &models.ItemPlacement{
ID: uuid.New(), ID: uuid.New(),
OrganizationID: orgID, OrganizationID: orgID,
@@ -62,131 +62,131 @@ func (s *operationsService) PlaceItem(ctx context.Context, orgID uuid.UUID, req
Quantity: req.Quantity, Quantity: req.Quantity,
CreatedAt: time.Now(), CreatedAt: time.Now(),
} }
if err := s.operationsRepo.PlaceItem(ctx, placement); err != nil { if err := s.operationsRepo.PlaceItem(ctx, placement); err != nil {
s.logger.Error("Failed to place item: ", err) s.logger.Error("Failed to place item: ", err)
return nil, err return nil, err
} }
s.logger.Info("Item placed successfully: ", placement.ID) s.logger.Info("Item placed successfully: ", placement.ID)
return placement, nil return placement, nil
} }
func (s *operationsService) MoveItem(ctx context.Context, placementID uuid.UUID, newLocationID uuid.UUID, orgID uuid.UUID) error { func (s *operationsService) MoveItem(ctx context.Context, placementID uuid.UUID, newLocationID uuid.UUID, orgID uuid.UUID) error {
s.logger.Info("Moving item placement: ", placementID, " to location: ", newLocationID, " for organization: ", orgID) s.logger.Info("Moving item placement: ", placementID, " to location: ", newLocationID, " for organization: ", orgID)
// Проверяем, что размещение существует и принадлежит организации // Проверяем, что размещение существует и принадлежит организации
placement, err := s.operationsRepo.GetByID(ctx, placementID, orgID) placement, err := s.operationsRepo.GetByID(ctx, placementID, orgID)
if err != nil { if err != nil {
s.logger.Error("Item placement not found or not accessible: ", err) s.logger.Error("Item placement not found or not accessible: ", err)
return err return err
} }
// Проверяем, что новое место хранения существует и принадлежит организации // Проверяем, что новое место хранения существует и принадлежит организации
_, err = s.locationRepo.GetByID(ctx, newLocationID, orgID) _, err = s.locationRepo.GetByID(ctx, newLocationID, orgID)
if err != nil { if err != nil {
s.logger.Error("New location not found or not accessible: ", err) s.logger.Error("New location not found or not accessible: ", err)
return err return err
} }
if err := s.operationsRepo.MoveItem(ctx, placementID, newLocationID, orgID); err != nil { if err := s.operationsRepo.MoveItem(ctx, placementID, newLocationID, orgID); err != nil {
s.logger.Error("Failed to move item: ", err) s.logger.Error("Failed to move item: ", err)
return err return err
} }
s.logger.Info("Item moved successfully from location: ", placement.LocationID, " to: ", newLocationID) s.logger.Info("Item moved successfully from location: ", placement.LocationID, " to: ", newLocationID)
return nil return nil
} }
func (s *operationsService) GetItemPlacements(ctx context.Context, itemID uuid.UUID, orgID uuid.UUID) ([]*models.ItemPlacement, error) { func (s *operationsService) GetItemPlacements(ctx context.Context, itemID uuid.UUID, orgID uuid.UUID) ([]*models.ItemPlacement, error) {
s.logger.Info("Getting placements for item: ", itemID, " in organization: ", orgID) s.logger.Info("Getting placements for item: ", itemID, " in organization: ", orgID)
// Проверяем, что товар существует и принадлежит организации // Проверяем, что товар существует и принадлежит организации
_, err := s.itemRepo.GetByID(ctx, itemID, orgID) _, err := s.itemRepo.GetByID(ctx, itemID, orgID)
if err != nil { if err != nil {
s.logger.Error("Item not found or not accessible: ", err) s.logger.Error("Item not found or not accessible: ", err)
return nil, err return nil, err
} }
placements, err := s.operationsRepo.GetByItem(ctx, itemID, orgID) placements, err := s.operationsRepo.GetByItem(ctx, itemID, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get item placements: ", err) s.logger.Error("Failed to get item placements: ", err)
return nil, err return nil, err
} }
return placements, nil return placements, nil
} }
func (s *operationsService) GetLocationPlacements(ctx context.Context, locationID uuid.UUID, orgID uuid.UUID) ([]*models.ItemPlacement, error) { func (s *operationsService) GetLocationPlacements(ctx context.Context, locationID uuid.UUID, orgID uuid.UUID) ([]*models.ItemPlacement, error) {
s.logger.Info("Getting placements for location: ", locationID, " in organization: ", orgID) s.logger.Info("Getting placements for location: ", locationID, " in organization: ", orgID)
// Проверяем, что место хранения существует и принадлежит организации // Проверяем, что место хранения существует и принадлежит организации
_, err := s.locationRepo.GetByID(ctx, locationID, orgID) _, err := s.locationRepo.GetByID(ctx, locationID, orgID)
if err != nil { if err != nil {
s.logger.Error("Location not found or not accessible: ", err) s.logger.Error("Location not found or not accessible: ", err)
return nil, err return nil, err
} }
placements, err := s.operationsRepo.GetByLocation(ctx, locationID, orgID) placements, err := s.operationsRepo.GetByLocation(ctx, locationID, orgID)
if err != nil { if err != nil {
s.logger.Error("Failed to get location placements: ", err) s.logger.Error("Failed to get location placements: ", err)
return nil, err return nil, err
} }
return placements, nil return placements, nil
} }
func (s *operationsService) UpdateQuantity(ctx context.Context, placementID uuid.UUID, quantity int, orgID uuid.UUID) error { func (s *operationsService) UpdateQuantity(ctx context.Context, placementID uuid.UUID, quantity int, orgID uuid.UUID) error {
s.logger.Info("Updating quantity for placement: ", placementID, " to: ", quantity, " in organization: ", orgID) s.logger.Info("Updating quantity for placement: ", placementID, " to: ", quantity, " in organization: ", orgID)
// Проверяем, что размещение существует и принадлежит организации // Проверяем, что размещение существует и принадлежит организации
_, err := s.operationsRepo.GetByID(ctx, placementID, orgID) _, err := s.operationsRepo.GetByID(ctx, placementID, orgID)
if err != nil { if err != nil {
s.logger.Error("Item placement not found or not accessible: ", err) s.logger.Error("Item placement not found or not accessible: ", err)
return err return err
} }
if err := s.operationsRepo.UpdateQuantity(ctx, placementID, quantity, orgID); err != nil { if err := s.operationsRepo.UpdateQuantity(ctx, placementID, quantity, orgID); err != nil {
s.logger.Error("Failed to update quantity: ", err) s.logger.Error("Failed to update quantity: ", err)
return err return err
} }
s.logger.Info("Quantity updated successfully for placement: ", placementID) s.logger.Info("Quantity updated successfully for placement: ", placementID)
return nil return nil
} }
func (s *operationsService) DeletePlacement(ctx context.Context, placementID uuid.UUID, orgID uuid.UUID) error { func (s *operationsService) DeletePlacement(ctx context.Context, placementID uuid.UUID, orgID uuid.UUID) error {
s.logger.Info("Deleting placement: ", placementID, " for organization: ", orgID) s.logger.Info("Deleting placement: ", placementID, " for organization: ", orgID)
// Проверяем, что размещение существует и принадлежит организации // Проверяем, что размещение существует и принадлежит организации
_, err := s.operationsRepo.GetByID(ctx, placementID, orgID) _, err := s.operationsRepo.GetByID(ctx, placementID, orgID)
if err != nil { if err != nil {
s.logger.Error("Item placement not found or not accessible: ", err) s.logger.Error("Item placement not found or not accessible: ", err)
return err return err
} }
if err := s.operationsRepo.Delete(ctx, placementID, orgID); err != nil { if err := s.operationsRepo.Delete(ctx, placementID, orgID); err != nil {
s.logger.Error("Failed to delete placement: ", err) s.logger.Error("Failed to delete placement: ", err)
return err return err
} }
s.logger.Info("Placement deleted successfully: ", placementID) s.logger.Info("Placement deleted successfully: ", placementID)
return nil return nil
} }
func (s *operationsService) Search(ctx context.Context, orgID uuid.UUID, req *models.SearchRequest) (*models.SearchResponse, error) { func (s *operationsService) Search(ctx context.Context, orgID uuid.UUID, req *models.SearchRequest) (*models.SearchResponse, error) {
s.logger.Info("Searching items with locations for organization: ", orgID, " query: ", req.Query) s.logger.Info("Searching items with locations for organization: ", orgID, " query: ", req.Query)
results, err := s.operationsRepo.Search(ctx, orgID, req.Query, req.Category, req.Address) results, err := s.operationsRepo.Search(ctx, orgID, req.Query, req.Category, req.Address)
if err != nil { if err != nil {
s.logger.Error("Failed to search items with locations: ", err) s.logger.Error("Failed to search items with locations: ", err)
return nil, err return nil, err
} }
response := &models.SearchResponse{ response := &models.SearchResponse{
Items: results, Items: results,
TotalCount: len(results), TotalCount: len(results),
} }
return response, nil return response, nil
} }