Skip to content

Commit

Permalink
add legal entities
Browse files Browse the repository at this point in the history
  • Loading branch information
orainmers committed Mar 2, 2025
1 parent 35bfafa commit aab3d74
Show file tree
Hide file tree
Showing 18 changed files with 6,809 additions and 52 deletions.
45 changes: 0 additions & 45 deletions .env.example

This file was deleted.

3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ github:

.PHONY: gen
gen:
for tag in omain oprofile ofederation oproject otask oreminder ocatalog; do \
for tag in omain oprofile ofederation oproject otask oreminder ocatalog olegalentities; do \
rm -rf ./internal/web/$$tag/; \
mkdir -p ./internal/web/$$tag; \
done
Expand All @@ -114,6 +114,7 @@ gen:
oapi-codegen -config openapi/.openapi -include-tags task -package otask openapi/openapi.yaml > ./internal/web/otask/api.gen.go
oapi-codegen -config openapi/.openapi -include-tags reminder -package oreminder openapi/openapi.yaml > ./internal/web/oreminder/api.gen.go
oapi-codegen -config openapi/.openapi -include-tags catalog -package ocatalog openapi/openapi.yaml > ./internal/web/ocatalog/api.gen.go
oapi-codegen -config openapi/.openapi -include-tags federation -package olegalentities openapi/openapi.yaml > ./internal/web/olegalentities/api.gen.go

.PHONY: registry-init
registry-init:
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ require (
golang.org/x/crypto v0.22.0
golang.org/x/sync v0.7.0
golang.org/x/time v0.5.0
gorm.io/gorm v1.25.9
gorm.io/gorm v1.25.12
)

require (
Expand All @@ -44,7 +44,7 @@ require (
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
github.com/jackc/pgx/v5 v5.5.2 // indirect
github.com/jackc/pgx/v5 v5.5.5 // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
Expand Down Expand Up @@ -105,7 +105,7 @@ require (
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
gorm.io/datatypes v1.2.0
gorm.io/driver/postgres v1.5.4
gorm.io/driver/postgres v1.5.11
gorm.io/plugin/prometheus v0.1.0
)

Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.5.2 h1:iLlpgp4Cp/gC9Xuscl7lFL1PhhW+ZLtXZcrfCt4C3tA=
github.com/jackc/pgx/v5 v5.5.2/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jellydator/ttlcache/v3 v3.1.1 h1:RCgYJqo3jgvhl+fEWvjNW8thxGWsgxi+TPhRir1Y9y8=
Expand Down Expand Up @@ -778,6 +780,8 @@ gorm.io/driver/mysql v1.5.2 h1:QC2HRskSE75wBuOxe0+iCkyJZ+RqpudsQtqkp+IMuXs=
gorm.io/driver/mysql v1.5.2/go.mod h1:pQLhh1Ut/WUAySdTHwBpBv6+JKcj+ua4ZFx1QQTBzb8=
gorm.io/driver/postgres v1.5.4 h1:Iyrp9Meh3GmbSuyIAGyjkN+n9K+GHX9b9MqsTL4EJCo=
gorm.io/driver/postgres v1.5.4/go.mod h1:Bgo89+h0CRcdA33Y6frlaHHVuTdOf87pmyzwW9C/BH0=
gorm.io/driver/postgres v1.5.11 h1:ubBVAfbKEUld/twyKZ0IYn9rSQh448EdelLYk9Mv314=
gorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU=
gorm.io/driver/sqlite v1.4.3/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
gorm.io/driver/sqlserver v1.4.1 h1:t4r4r6Jam5E6ejqP7N82qAJIJAht27EGT41HyPfXRw0=
Expand All @@ -786,6 +790,8 @@ gorm.io/gorm v1.25.0/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.9 h1:wct0gxZIELDk8+ZqF/MVnHLkA1rvYlBWUMv2EdsK1g8=
gorm.io/gorm v1.25.9/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
gorm.io/plugin/prometheus v0.1.0 h1:kDQwAfCUsT9D6jDUpIp7pnc7bCJu/6voM8I/BmFjxUQ=
gorm.io/plugin/prometheus v0.1.0/go.mod h1:5nrc/JrWCUNoDXCY4eOae/FK/J5WjQ0axXuFusCzdTc=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
2 changes: 2 additions & 0 deletions internal/app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/krisch/crm-backend/internal/health"
"github.com/krisch/crm-backend/internal/helpers"
"github.com/krisch/crm-backend/internal/jwt"
"github.com/krisch/crm-backend/internal/legalentities"
"github.com/krisch/crm-backend/internal/logs"
"github.com/krisch/crm-backend/internal/notifications"
"github.com/krisch/crm-backend/internal/permissions"
Expand Down Expand Up @@ -61,6 +62,7 @@ type App struct {
JWT jwt.IJWT
AgentsService *agents.Service
PermissionsService *permissions.Service
LegalEntitiesService *legalentities.Service

MetricsCounters *helpers.MetricsCounters
}
Expand Down
15 changes: 14 additions & 1 deletion internal/app/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/krisch/crm-backend/internal/health"
"github.com/krisch/crm-backend/internal/helpers"
"github.com/krisch/crm-backend/internal/jwt"
"github.com/krisch/crm-backend/internal/legalentities"
"github.com/krisch/crm-backend/internal/logs"
"github.com/krisch/crm-backend/internal/notifications"
"github.com/krisch/crm-backend/internal/permissions"
Expand Down Expand Up @@ -61,6 +62,7 @@ func InitApp(name string, creds postgres.Creds, metrics bool, rc redis.Creds) (*
wire.Build(
configs.NewConfigsFromEnv,
postgres.NewGDB,
postgres.ProvideGormDB,
redis.New,

health.NewHealthService,
Expand Down Expand Up @@ -130,6 +132,10 @@ func InitApp(name string, creds postgres.Creds, metrics bool, rc redis.Creds) (*
catalogs.NewRepository,
catalogs.New,

// Подключаем репозиторий и сервис для legalentities
legalentities.NewRepository,
legalentities.NewService,

NewApp,
)

Expand All @@ -140,13 +146,19 @@ func Configs() *configs.Configs {
return &configs.Configs{}
}

func NewApp(name string, conf *configs.Configs, gdb *postgres.GDB, rds *redis.RDS,
func NewApp(
name string,
conf *configs.Configs,
gdb *postgres.GDB,
rds *redis.RDS,

healthService *health.Service,
notificationsService *notifications.Service,
logService logs.ILogService,
profileService *profile.Service,
emailService emails.IEmailsService,
federationService *federation.Service,
legalEntitiesService *legalentities.Service,
taskService *task.Service,
commentService *comments.Service,
dictionaryService *dictionary.Service,
Expand Down Expand Up @@ -206,6 +218,7 @@ func NewApp(name string, conf *configs.Configs, gdb *postgres.GDB, rds *redis.RD
w.SMSService = smsService
w.AgentsService = agentsService
w.PermissionsService = permissionsService
w.LegalEntitiesService = legalEntitiesService

return w
}
15 changes: 13 additions & 2 deletions internal/app/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

56 changes: 56 additions & 0 deletions internal/legalentities/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package legalentities

import (
"context"

"github.com/google/uuid"
)

// Service содержит бизнес-логику для работы с LegalEntity.
type Service struct {
repo *Repository
}

// NewService возвращает новый экземпляр Service.
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
}

// CreateLegalEntity создаёт новую запись LegalEntity.
func (s *Service) CreateLegalEntity(ctx context.Context, name string) (uuid.UUID, error) {
entity := &LegalEntity{
Name: name,
}
err := s.repo.Create(ctx, entity)
return entity.UUID, err
}

// GetAllLegalEntities возвращает список всех LegalEntity (не удалённых).
func (s *Service) GetAllLegalEntities(ctx context.Context) ([]LegalEntity, error) {
return s.repo.GetAll(ctx)
}

// GetLegalEntity возвращает конкретную LegalEntity по UUID.
func (s *Service) GetLegalEntity(ctx context.Context, id uuid.UUID) (LegalEntity, error) {
return s.repo.GetByUUID(ctx, id)
}

// UpdateLegalEntity обновляет поля существующей записи LegalEntity.
func (s *Service) UpdateLegalEntity(ctx context.Context, id uuid.UUID, newName string) error {
// Сначала получаем существующую запись
entity, err := s.repo.GetByUUID(ctx, id)
if err != nil {
return err
}

// Меняем поля
entity.Name = newName

// Сохраняем изменения
return s.repo.Update(ctx, &entity)
}

// DeleteLegalEntity «мягко» удаляет LegalEntity (soft delete).
func (s *Service) DeleteLegalEntity(ctx context.Context, id uuid.UUID) error {
return s.repo.Delete(ctx, id)
}
22 changes: 22 additions & 0 deletions internal/legalentities/orm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package legalentities

import (
"time"

"github.com/google/uuid"
)

// LegalEntity представляет ORM-модель для юридических лиц
// с полями: uuid, name, created_at, updated_at, deleted_at.
type LegalEntity struct {
UUID uuid.UUID `json:"uuid" gorm:"primaryKey;type:uuid;default:uuid_generate_v4()"`
Name string `json:"name" gorm:"not null;type:varchar(255)"`
CreatedAt time.Time `json:"created_at" gorm:"<-:create;autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
DeletedAt *time.Time `json:"deleted_at"`
}

// TableName указывает, какую таблицу в БД будет использовать ORM.
func (LegalEntity) TableName() string {
return "legal_entities"
}
66 changes: 66 additions & 0 deletions internal/legalentities/repository.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package legalentities

import (
"context"
"time"

"github.com/google/uuid"
"gorm.io/gorm"
)

// Repository предоставляет методы для работы с сущностями LegalEntity в БД.
type Repository struct {
db *gorm.DB
}

// NewRepository возвращает новый экземпляр репозитория.
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}

// Create добавляет новую сущность LegalEntity в БД.
func (r *Repository) Create(ctx context.Context, entity *LegalEntity) error {
return r.db.WithContext(ctx).Create(entity).Error
}

// GetByUUID возвращает LegalEntity по его UUID.
func (r *Repository) GetByUUID(ctx context.Context, id uuid.UUID) (LegalEntity, error) {
var entity LegalEntity
err := r.db.WithContext(ctx).
Where("uuid = ?", id).
First(&entity).Error
return entity, err
}

// GetAll возвращает все LegalEntity, у которых нет метки удалённости (deleted_at).
func (r *Repository) GetAll(ctx context.Context) ([]LegalEntity, error) {
var entities []LegalEntity
err := r.db.WithContext(ctx).
Where("deleted_at IS NULL").
Find(&entities).Error
return entities, err
}

// Update обновляет существующую запись LegalEntity.
func (r *Repository) Update(ctx context.Context, entity *LegalEntity) error {
// Если вам нужно полностью перезаписать все поля, можно использовать сохранение.
// Если только отдельные поля, используйте Updates или конкретно UpdateColumn.
return r.db.WithContext(ctx).Save(entity).Error
}

// Delete помечает LegalEntity как удалённую (soft delete), устанавливая deleted_at.
func (r *Repository) Delete(ctx context.Context, id uuid.UUID) error {
now := time.Now()
result := r.db.WithContext(ctx).
Model(&LegalEntity{}).
Where("uuid = ?", id).
Where("deleted_at IS NULL").
Update("deleted_at", &now)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
Loading

0 comments on commit aab3d74

Please sign in to comment.