Add project files
This commit is contained in:
parent
c4b3d15693
commit
0e4eef5d38
|
|
@ -0,0 +1,52 @@
|
|||
linters-settings:
|
||||
errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются
|
||||
check-type-assertions: true # Не проверять утверждения типов на ошибки
|
||||
check-blank: true # Проверять игнорирование ошибок через присваивание в _
|
||||
prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов
|
||||
simple: true # Простой режим, предлагает предварительное выделение для простых циклов
|
||||
range-loops: true # Предлагает предварительное выделение для циклов range
|
||||
for-loops: false # Не предлагает предварительное выделение для обычных for-циклов
|
||||
gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций
|
||||
min-complexity: 15 # Установите порог сложности, который считаете приемлемым
|
||||
|
||||
linters:
|
||||
enable: # Список линтеров, которые будут включены
|
||||
- noctx # Находит отправку HTTP-запроса без контекста.Контекст.
|
||||
- protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры.
|
||||
- reassign # Проверяет, что переменные пакета не переназначаются.
|
||||
- rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк.
|
||||
- sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты.
|
||||
- ineffassign # Обнаруживает, когда назначения существующим переменным не используются.
|
||||
- nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю.
|
||||
- makezero # Проверяет, что нулевые значения создаются правильно
|
||||
- gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому
|
||||
- copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов
|
||||
- exhaustive # Проверьте полноту операторов перечисления.
|
||||
- errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить.
|
||||
- durationcheck # Проверяет, что длительность таймаута не равна 0
|
||||
- contextcheck # Проверяет, что контекст не игнорируется
|
||||
- bodyclose # Проверяет, что тело запроса закрывается
|
||||
- bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков
|
||||
- govet # Проверяет код на наличие конструкций, которые могут быть ошибочными
|
||||
- errcheck # Проверяет, что ошибки не игнорируются
|
||||
- staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д.
|
||||
- unused # Проверяет на неиспользуемые переменные, функции, константы
|
||||
- gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля
|
||||
- stylecheck # Проверяет стиль кодирования
|
||||
- whitespace # Проверяет проблемы с пробелами в коде
|
||||
- gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей
|
||||
- prealloc # Предлагает предварительное выделение памяти для срезов
|
||||
|
||||
- dupl # Находит дублирующийся код
|
||||
- gocyclo # Проверяет сложность функций
|
||||
- ineffassign # Обнаруживает неэффективные присваивания
|
||||
- unparam # Находит неиспользуемые параметры функций
|
||||
|
||||
- gosimple # Предлагает упрощения кода
|
||||
|
||||
disable: # Список линтеров, которые будут отключены
|
||||
- gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования
|
||||
# - golint # Отключает golint, который проверяет стиль написания кода на Go
|
||||
|
||||
run:
|
||||
timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="Go" enabled="true" />
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="ruspetportal@localhost" uuid="f2f4a203-9ea3-4b6e-93e3-97ceee97f62b">
|
||||
<driver-ref>postgresql</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
|
||||
<jdbc-url>jdbc:postgresql://localhost:5432/ruspetportal</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/bitrix_balancer_api.iml" filepath="$PROJECT_DIR$/.idea/bitrix_balancer_api.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="file://$PROJECT_DIR$/core/db/db_migration/triggers.go" dialect="GenericSQL" />
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
trap 'echo "🔴 Error build core"; exit 1' ERR
|
||||
|
||||
THIS_PATH=$(dirname "$(realpath "$0")")
|
||||
CORE_PATH="$THIS_PATH/core"
|
||||
|
||||
echo "CORE_PATH: $CORE_PATH"
|
||||
|
||||
cd "$CORE_PATH"
|
||||
go vet ./...
|
||||
go mod tidy
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
linters-settings:
|
||||
errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются
|
||||
check-type-assertions: true # Не проверять утверждения типов на ошибки
|
||||
check-blank: true # Проверять игнорирование ошибок через присваивание в _
|
||||
prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов
|
||||
simple: true # Простой режим, предлагает предварительное выделение для простых циклов
|
||||
range-loops: true # Предлагает предварительное выделение для циклов range
|
||||
for-loops: false # Не предлагает предварительное выделение для обычных for-циклов
|
||||
gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций
|
||||
min-complexity: 15 # Установите порог сложности, который считаете приемлемым
|
||||
|
||||
linters:
|
||||
enable: # Список линтеров, которые будут включены
|
||||
- noctx # Находит отправку HTTP-запроса без контекста.Контекст.
|
||||
- protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры.
|
||||
- reassign # Проверяет, что переменные пакета не переназначаются.
|
||||
- rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк.
|
||||
- sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты.
|
||||
- ineffassign # Обнаруживает, когда назначения существующим переменным не используются.
|
||||
- nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю.
|
||||
- makezero # Проверяет, что нулевые значения создаются правильно
|
||||
- gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому
|
||||
- copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов
|
||||
- exhaustive # Проверьте полноту операторов перечисления.
|
||||
- errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить.
|
||||
- durationcheck # Проверяет, что длительность таймаута не равна 0
|
||||
- contextcheck # Проверяет, что контекст не игнорируется
|
||||
- bodyclose # Проверяет, что тело запроса закрывается
|
||||
- bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков
|
||||
- govet # Проверяет код на наличие конструкций, которые могут быть ошибочными
|
||||
- errcheck # Проверяет, что ошибки не игнорируются
|
||||
- staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д.
|
||||
- unused # Проверяет на неиспользуемые переменные, функции, константы
|
||||
- gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля
|
||||
- stylecheck # Проверяет стиль кодирования
|
||||
- whitespace # Проверяет проблемы с пробелами в коде
|
||||
- gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей
|
||||
- prealloc # Предлагает предварительное выделение памяти для срезов
|
||||
|
||||
- dupl # Находит дублирующийся код
|
||||
- gocyclo # Проверяет сложность функций
|
||||
- ineffassign # Обнаруживает неэффективные присваивания
|
||||
- unparam # Находит неиспользуемые параметры функций
|
||||
|
||||
- gosimple # Предлагает упрощения кода
|
||||
|
||||
disable: # Список линтеров, которые будут отключены
|
||||
- gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования
|
||||
# - golint # Отключает golint, который проверяет стиль написания кода на Go
|
||||
|
||||
run:
|
||||
timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package configcore
|
||||
|
||||
// ExposedServiceOptions определяет, какие сервисы нужно загружать
|
||||
type ExposedServiceOptions struct {
|
||||
TelegramService bool
|
||||
RESTBaseService bool
|
||||
}
|
||||
|
||||
// ConfigLoadOptions определяет, какие группы конфигурации нужно загружать
|
||||
type ConfigLoadOptions struct {
|
||||
Redis bool
|
||||
Database bool
|
||||
Bitrix bool
|
||||
Secrets bool
|
||||
Telegram bool
|
||||
Server ExposedServiceOptions
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
package configcore
|
||||
|
||||
// RedisConfig конфигурация Redis
|
||||
type RedisConfig struct {
|
||||
Host string `yaml:"host" env-required:"true"`
|
||||
Port int `yaml:"port" env-required:"true"`
|
||||
User string `yaml:"user" env-required:"true"`
|
||||
Password string `yaml:"password" env-required:"true"`
|
||||
}
|
||||
|
||||
// DatabaseConfig конфигурация базы данных
|
||||
type DatabaseConfig struct {
|
||||
Host string `yaml:"host" env-required:"true"`
|
||||
User string `yaml:"user" env-required:"true"`
|
||||
Password string `yaml:"password" env-required:"true"`
|
||||
DB string `yaml:"methods" env-required:"true"`
|
||||
Port int `yaml:"port" env-required:"true"`
|
||||
SSL string `yaml:"ssl" env-required:"true" default:"disable"`
|
||||
}
|
||||
|
||||
// TelegramConfig конфигурация Telegram
|
||||
type TelegramConfig struct {
|
||||
BotToken string `yaml:"bot_token"`
|
||||
WebAppUrl string `yaml:"web_app_url"`
|
||||
}
|
||||
|
||||
// ServiceConfig конфигурация сервиса
|
||||
type ServiceConfig struct {
|
||||
Host string `yaml:"host" env-required:"true"`
|
||||
Port int `yaml:"port" env-required:"true"`
|
||||
}
|
||||
|
||||
// CorsConfig конфигурация CORS
|
||||
type CorsConfig struct {
|
||||
AllowedOrigins []string `yaml:"allowed_origins"`
|
||||
}
|
||||
|
||||
// SwaggerConfig конфигурация Swagger
|
||||
type SwaggerConfig struct {
|
||||
User string `yaml:"user" env-required:"true"`
|
||||
Pass string `yaml:"pass" env-required:"true"`
|
||||
}
|
||||
|
||||
// RestServiceConfig конфигурация REST сервиса
|
||||
type RestServiceConfig struct {
|
||||
PortRest int `yaml:"port_rest" env-required:"true"`
|
||||
BindRest string `yaml:"bind_rest" env-required:"true"`
|
||||
PortSocket int `yaml:"port_socket" env-required:"true"`
|
||||
Cors CorsConfig `yaml:"cors"`
|
||||
Swagger SwaggerConfig `yaml:"swagger"`
|
||||
Internal string `yaml:"internally"`
|
||||
MaxHttpBufferSize int64 `yaml:"max_http_buffer_size"`
|
||||
MessageTimeout int64 `yaml:"message_timeout"`
|
||||
}
|
||||
|
||||
// GrpcServiceConfig конфигурация gRPC сервиса
|
||||
type GrpcServiceConfig struct {
|
||||
GrpcPort int `yaml:"grpc_port" env-required:"true"`
|
||||
CertFileName string
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
RESTBaseService RestServiceConfig `yaml:"rest_base_service"`
|
||||
Telegram GrpcServiceConfig `yaml:"telegram_service"`
|
||||
}
|
||||
|
||||
type Bitrix struct {
|
||||
PortalID string `yaml:"portal_id"`
|
||||
IsEnterprise bool `yaml:"is_enterprise"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
Bind string `yaml:"bind"`
|
||||
Port int `yaml:"port"`
|
||||
Internal string `yaml:"internally"`
|
||||
MaxHttpBufferSize int64 `yaml:"max_http_buffer_size"`
|
||||
MessageTimeout int64 `yaml:"message_timeout"`
|
||||
}
|
||||
|
||||
// SecretsConfig конфигурация секретов
|
||||
type SecretsConfig struct {
|
||||
ApiPublicBase string `yaml:"api_public_base"`
|
||||
ApiPrivateBase string `yaml:"api_private_base"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Redis RedisConfig `yaml:"redis"`
|
||||
Database DatabaseConfig `yaml:"database"`
|
||||
Telegram TelegramConfig `yaml:"telegram"`
|
||||
Server Server `yaml:"server"`
|
||||
Secrets SecretsConfig `yaml:"secrets"`
|
||||
Bitrix Bitrix `yaml:"bitrix"`
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
redis:
|
||||
addr: ""
|
||||
username: ""
|
||||
password: "" # Password for the Redis server (if required)
|
||||
port: 0 # Redis server port, default is 6379
|
||||
db: 0
|
||||
secrets:
|
||||
api_public_base: "test"
|
||||
api_private_base: "testtest"
|
||||
bitrix:
|
||||
portal_id: ""
|
||||
is_enterprise: false
|
||||
database:
|
||||
host: "localhost"
|
||||
port: 5432
|
||||
methods: "ruspetportal"
|
||||
user: "postgres"
|
||||
password: "root"
|
||||
telegram: # Telegram settings
|
||||
bot_token: "19191919191:******-******************" # Telegram bot token
|
||||
web_app_url: "https://google.com/"# Telegram web app URL
|
||||
server:
|
||||
rest_base_service: # Base service address
|
||||
bind_rest: "0.0.0.0"
|
||||
port_rest: 15000
|
||||
internal: "rest_base_service_balancer_c"
|
||||
telegram_service:
|
||||
grpc_port: 4553
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
redis:
|
||||
addr: "127.0.0.1" # Redis server address, typically 'localhost' or a remote server IP
|
||||
username: "" # Username for the Redis server (if required)
|
||||
password: "" # Password for the Redis server (if required)
|
||||
port: 6379 # Redis server port, default is 6379
|
||||
db: 0
|
||||
bitrix:
|
||||
portal_id: "thebest"
|
||||
is_enterprise: false
|
||||
database:
|
||||
host: "localhost" # 72.56.235.246
|
||||
port: 5432
|
||||
methods: "ruspetportal"
|
||||
user: "postgres"
|
||||
password: "root"
|
||||
telegram: # Telegram settings
|
||||
bot_token: "8581818011:AAGq7kx2N0BL5CSYkPMZjtXWeB9xvJgOK8U" # Telegram bot token
|
||||
web_app_url: "https://google.com/"# Telegram web app URL
|
||||
secrets:
|
||||
api_public_base: "test"
|
||||
api_private_base: "testtest"
|
||||
server:
|
||||
rest_base_service: # Base service address
|
||||
bind_rest: "0.0.0.0"
|
||||
port_rest: 15000
|
||||
internal: "rest_base_service_balancer_c"
|
||||
telegram_service:
|
||||
grpc_port: 4553
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
package configcore
|
||||
|
||||
import (
|
||||
cfgldrlib "bitrix_balancer_api/core/lib/internally/config-loader"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
//go:embed config.yml
|
||||
var configYML string
|
||||
|
||||
// LoadConfig загружает конфигурацию из встраиваемого YAML файла
|
||||
func LoadConfig(options *ConfigLoadOptions) (*Config, error) {
|
||||
params := &cfgldrlib.ConfigLoaders{
|
||||
ConfigYml: &configYML,
|
||||
}
|
||||
|
||||
var fullConfig Config
|
||||
config, err := cfgldrlib.LoadConfig[Config](params)
|
||||
if err != nil {
|
||||
return nil, errors.New(fmt.Sprintf("failed to load config using cfg-ldr: %v", err))
|
||||
}
|
||||
fullConfig = *config
|
||||
result := &Config{}
|
||||
copyConfigFields(options, &fullConfig, result)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// copyConfigFields копирует поля из source в target на основе опций options
|
||||
func copyConfigFields(options *ConfigLoadOptions, source, target *Config) {
|
||||
// Копируем Redis
|
||||
if options.Redis {
|
||||
target.Redis = source.Redis
|
||||
}
|
||||
|
||||
// Копируем Database
|
||||
if options.Database {
|
||||
target.Database = source.Database
|
||||
}
|
||||
|
||||
// Копируем Telegram
|
||||
if options.Telegram {
|
||||
target.Telegram = source.Telegram
|
||||
}
|
||||
|
||||
// Копируем Bitrix
|
||||
if options.Bitrix {
|
||||
target.Bitrix = source.Bitrix
|
||||
}
|
||||
|
||||
if options.Secrets {
|
||||
target.Secrets = source.Secrets
|
||||
}
|
||||
|
||||
// Копируем ExposedServiceConfig
|
||||
if options.Server.RESTBaseService {
|
||||
target.Server.RESTBaseService = source.Server.RESTBaseService
|
||||
}
|
||||
if options.Server.TelegramService {
|
||||
target.Server.Telegram = source.Server.Telegram
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
dbmigration "bitrix_balancer_api/core/db/db_migration"
|
||||
dbcore "bitrix_balancer_api/core/db/methods"
|
||||
gormmodule "bitrix_balancer_api/core/lib/external/gorm"
|
||||
pgxpoolmodule "bitrix_balancer_api/core/lib/external/pgxpool"
|
||||
redismodule "bitrix_balancer_api/core/lib/internally/redis"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ModuleDB struct {
|
||||
Pool *pgxpool.Pool
|
||||
gormDB *gorm.DB
|
||||
|
||||
User *dbcore.UserDB
|
||||
Approval *dbcore.ApprovalDB
|
||||
ApprovalFile *dbcore.ApprovalFileDB
|
||||
ApprovalStep *dbcore.ApprovalStepDB
|
||||
ApprovalTopic *dbcore.ApprovalTopicDB
|
||||
ApprovalTopicCategory *dbcore.ApprovalTopicCategoryDB
|
||||
Department *dbcore.DepartmentDB
|
||||
Permission *dbcore.PermissionDB
|
||||
Role *dbcore.RoleDB
|
||||
UserRole *dbcore.UserRoleDB
|
||||
UserHierarchy *dbcore.UserHierarchyDB
|
||||
ApprovalDelegation *dbcore.ApprovalDelegationDB
|
||||
ApprovalAdditionalApprover *dbcore.ApprovalAdditionalApproverDB
|
||||
ApprovalTasks *dbcore.ApprovalTaskDB
|
||||
}
|
||||
|
||||
func NewModuleDB(
|
||||
config *pgxpoolmodule.ConfigConnectPgxPool,
|
||||
redisClient *redismodule.ModuleRedis,
|
||||
) (*ModuleDB, error) {
|
||||
pool, err := pgxpoolmodule.ConnectDB(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gormDataBase, _, err := gormmodule.GormDatabaseConnect(&gormmodule.ConfigConnectGorm{
|
||||
Host: config.Host,
|
||||
Port: config.Port,
|
||||
User: config.User,
|
||||
Password: config.Password,
|
||||
Name: config.Name,
|
||||
SslMode: config.SSLMode,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
moduleDB := &ModuleDB{Pool: pool, gormDB: gormDataBase}
|
||||
moduleDB = initDBModules(moduleDB, redisClient)
|
||||
|
||||
return moduleDB, nil
|
||||
}
|
||||
|
||||
func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *ModuleDB {
|
||||
modules.User = dbcore.NewUserDB(modules.Pool)
|
||||
modules.Approval = dbcore.NewApprovalDB(modules.Pool)
|
||||
modules.ApprovalStep = dbcore.NewApprovalStepDB(modules.Pool)
|
||||
modules.ApprovalTopic = dbcore.NewApprovalTopicDB(modules.Pool)
|
||||
modules.ApprovalTopicCategory = dbcore.NewApprovalTopicCategoryDB(modules.Pool)
|
||||
modules.Department = dbcore.NewDepartmentDB(modules.Pool)
|
||||
modules.Permission = dbcore.NewPermissionDB(modules.Pool)
|
||||
modules.Role = dbcore.NewRoleDB(modules.Pool)
|
||||
modules.UserHierarchy = dbcore.NewUserHierarchyDB(modules.Pool)
|
||||
modules.UserRole = dbcore.NewUserRoleDB(modules.Pool)
|
||||
modules.ApprovalFile = dbcore.NewApprovalFileDB(modules.Pool)
|
||||
modules.ApprovalDelegation = dbcore.NewApprovalDelegationDB(modules.Pool)
|
||||
modules.ApprovalAdditionalApprover = dbcore.NewApprovalAdditionalApproverDB(modules.Pool)
|
||||
modules.ApprovalTasks = dbcore.NewApprovalTaskDB(modules.Pool)
|
||||
|
||||
return modules
|
||||
}
|
||||
|
||||
func (m *ModuleDB) Migrate() *dbmigration.MigrationFunctions {
|
||||
return dbmigration.NewMigrationFunctions(m.Pool, m.gormDB)
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package dbmigration
|
||||
|
||||
import (
|
||||
gormmodule "bitrix_balancer_api/core/lib/external/gorm"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type MigrationFunctions struct {
|
||||
pool *pgxpool.Pool
|
||||
gormDB *gorm.DB
|
||||
}
|
||||
|
||||
func NewMigrationFunctions(pool *pgxpool.Pool, gorm *gorm.DB) *MigrationFunctions {
|
||||
return &MigrationFunctions{
|
||||
pool: pool,
|
||||
gormDB: gorm,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MigrationFunctions) MigrateDB() error {
|
||||
m.DropAllTriggers()
|
||||
|
||||
err := m.migrateTables()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.TriggerMigrations()
|
||||
m.DefaultDataSet()
|
||||
// Закрытие соединения с базой данных
|
||||
gormmodule.GormDatabaseDisconnect()
|
||||
|
||||
logrus.Info("🟢🟢🟢 Database migration completed successfully")
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package dbmigration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gorm.io/gorm"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func CreateEnumType(db *gorm.DB, typeName string, values []string, comment string) error {
|
||||
valuesStr := "'" + strings.Join(values, "', '") + "'"
|
||||
createQuery := fmt.Sprintf(`
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = '%s') THEN
|
||||
CREATE TYPE %s AS ENUM (%s);
|
||||
COMMENT ON TYPE %s IS '%s';
|
||||
END IF;
|
||||
END $$;
|
||||
`, typeName, typeName, valuesStr, typeName, comment)
|
||||
return db.Exec(createQuery).Error
|
||||
}
|
||||
|
|
@ -0,0 +1,315 @@
|
|||
package dbmigration
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
_ "embed"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
//go:embed default_data/approval_topic_categories.csv
|
||||
var approvalCategoriesCSV string
|
||||
|
||||
//go:embed default_data/approval_topics.csv
|
||||
var approvalTopicsCSV string
|
||||
|
||||
// identifierRe is compiled once and reused across all sanitizeIdentifier calls.
|
||||
var identifierRe = regexp.MustCompile(`[^a-z0-9_]`)
|
||||
|
||||
// timeFormats lists candidate layouts tried in order when parsing a CSV time cell.
|
||||
var timeFormats = []string{
|
||||
"2006-01-02 15:04:05.999999",
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02T15:04:05Z",
|
||||
"2006-01-02T15:04:05.999Z",
|
||||
"2006-01-02",
|
||||
}
|
||||
|
||||
// dataEntry associates a table name, its model type, and its embedded CSV source.
|
||||
type dataEntry struct {
|
||||
table string
|
||||
model interface{}
|
||||
csv string
|
||||
}
|
||||
|
||||
// defaultDataEntries defines the ordered list of tables to seed.
|
||||
// Adding a new table only requires appending one entry here.
|
||||
var defaultDataEntries = []dataEntry{
|
||||
{"approval_topic_categories", &typescore.ApprovalTopicCategory{}, approvalCategoriesCSV},
|
||||
{"approval_topics", &typescore.ApprovalTopic{}, approvalTopicsCSV},
|
||||
}
|
||||
|
||||
// DefaultDataSet seeds every table defined in defaultDataEntries.
|
||||
// It attempts all tables and returns a combined error if any fail.
|
||||
func (m *MigrationFunctions) DefaultDataSet() error {
|
||||
if m.gormDB == nil {
|
||||
return fmt.Errorf("DefaultDataSet: gormDB is nil")
|
||||
}
|
||||
|
||||
logrus.Infof("🚀 Start db default data set: %s", time.Now().UTC())
|
||||
|
||||
var errs []error
|
||||
for _, entry := range defaultDataEntries {
|
||||
if err := m.seedTable(entry); err != nil {
|
||||
logrus.Errorf("❌ seeding table %q: %v", entry.table, err)
|
||||
errs = append(errs, fmt.Errorf("table %q: %w", entry.table, err))
|
||||
}
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// seedTable handles the full pipeline for a single table:
|
||||
// parse CSV → build field index → map to structs → upsert.
|
||||
func (m *MigrationFunctions) seedTable(entry dataEntry) error {
|
||||
headers, records, err := readCSV(entry.csv)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading CSV: %w", err)
|
||||
}
|
||||
|
||||
fieldIndex := buildFieldIndexMap(entry.model)
|
||||
|
||||
objects, err := mapRecordsToStructs(headers, records, fieldIndex, entry.model)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping records: %w", err)
|
||||
}
|
||||
|
||||
return m.upsertRecords(entry.table, objects)
|
||||
}
|
||||
|
||||
// buildFieldIndexMap returns a map of sanitized db-tag → struct field index.
|
||||
func buildFieldIndexMap(model interface{}) map[string]int {
|
||||
t := reflect.TypeOf(model).Elem()
|
||||
index := make(map[string]int, t.NumField())
|
||||
for i := range t.NumField() {
|
||||
if tag := sanitizeIdentifier(t.Field(i).Tag.Get("db")); tag != "" {
|
||||
index[tag] = i
|
||||
}
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
// mapRecordsToStructs converts raw CSV rows into a slice of model instances.
|
||||
func mapRecordsToStructs(
|
||||
headers []string,
|
||||
records [][]string,
|
||||
fieldIndex map[string]int,
|
||||
model interface{},
|
||||
) ([]interface{}, error) {
|
||||
modelType := reflect.TypeOf(model).Elem()
|
||||
results := make([]interface{}, 0, len(records))
|
||||
|
||||
for _, record := range records {
|
||||
data := make(map[string]interface{}, len(headers))
|
||||
|
||||
for i, raw := range headers {
|
||||
key := sanitizeIdentifier(raw)
|
||||
if record[i] == "" {
|
||||
continue
|
||||
}
|
||||
idx, ok := fieldIndex[key]
|
||||
if !ok {
|
||||
logrus.Errorf("❌ CSV column %q has no matching db tag in %s", key, modelType.Name())
|
||||
continue
|
||||
}
|
||||
data[key] = convertType(key, record[i], modelType.Field(idx).Type)
|
||||
}
|
||||
|
||||
// reflect.New returns a *T; pass it directly so mapstructure decodes into *T,
|
||||
// not into a double pointer (**T).
|
||||
obj := reflect.New(modelType).Interface()
|
||||
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
|
||||
TagName: "db",
|
||||
Result: obj,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("creating decoder: %w", err)
|
||||
}
|
||||
if err := dec.Decode(data); err != nil {
|
||||
logrus.Errorf("❌ decoding CSV record into %s: %v", modelType.Name(), err)
|
||||
continue
|
||||
}
|
||||
results = append(results, obj)
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// upsertRecords inserts each object if it doesn't already exist in the given table.
|
||||
// Duplicate-key conflicts are silently skipped; all other errors are logged and collected.
|
||||
func (m *MigrationFunctions) upsertRecords(table string, objects []interface{}) error {
|
||||
var errs []error
|
||||
for _, obj := range objects {
|
||||
err := m.gormDB.Table(table).FirstOrCreate(obj).Error
|
||||
switch {
|
||||
case err == nil:
|
||||
// inserted or already existed — nothing to do
|
||||
case errors.Is(err, gorm.ErrDuplicatedKey):
|
||||
logrus.Warnf("⚠️ duplicate key in %q — skipping", table)
|
||||
default:
|
||||
logrus.Errorf("❌ inserting record into %q: %v", table, err)
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// sanitizeIdentifier lowercases s, trims whitespace, and removes any character
|
||||
// that is not a lowercase letter, digit, or underscore.
|
||||
func sanitizeIdentifier(s string) string {
|
||||
return identifierRe.ReplaceAllString(strings.ToLower(strings.TrimSpace(s)), "")
|
||||
}
|
||||
|
||||
// readCSV parses a CSV string and returns the header row and all data rows.
|
||||
func readCSV(data string) (headers []string, records [][]string, err error) {
|
||||
r := csv.NewReader(strings.NewReader(data))
|
||||
|
||||
headers, err = r.Read()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("reading headers: %w", err)
|
||||
}
|
||||
|
||||
for line := 2; ; line++ {
|
||||
row, err := r.Read()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("line %d: %w", line, err)
|
||||
}
|
||||
records = append(records, row)
|
||||
}
|
||||
|
||||
if len(records) == 0 {
|
||||
return nil, nil, errors.New("CSV contains no data rows")
|
||||
}
|
||||
return headers, records, nil
|
||||
}
|
||||
|
||||
// convertType converts a CSV cell string to the Go type required by the struct field.
|
||||
// Pointer fields are handled by wrapping the converted base value.
|
||||
func convertType(field, value string, target reflect.Type) interface{} {
|
||||
base := target
|
||||
if base.Kind() == reflect.Ptr {
|
||||
base = base.Elem()
|
||||
}
|
||||
|
||||
result := convertValue(field, value, base)
|
||||
|
||||
if target.Kind() != reflect.Ptr || result == nil {
|
||||
return result
|
||||
}
|
||||
|
||||
// Wrap result in a pointer to base.
|
||||
ptr := reflect.New(base)
|
||||
v := reflect.ValueOf(result)
|
||||
switch {
|
||||
case v.Type().AssignableTo(base):
|
||||
ptr.Elem().Set(v)
|
||||
case v.Type().ConvertibleTo(base):
|
||||
ptr.Elem().Set(v.Convert(base))
|
||||
default:
|
||||
logrus.Errorf("❌ cannot assign %v to *%v for field %q", v.Type(), base, field)
|
||||
return nil
|
||||
}
|
||||
return ptr.Interface()
|
||||
}
|
||||
|
||||
// convertValue converts value to the concrete (non-pointer) type t.
|
||||
func convertValue(field, value string, t reflect.Type) interface{} {
|
||||
switch {
|
||||
case t == reflect.TypeOf(decimal.Decimal{}):
|
||||
d, err := decimal.NewFromString(value)
|
||||
if err != nil {
|
||||
logrus.Errorf("❌ %s → decimal: %v", field, err)
|
||||
return decimal.Zero
|
||||
}
|
||||
return d
|
||||
|
||||
case t == reflect.TypeOf(json.RawMessage{}):
|
||||
return json.RawMessage(value)
|
||||
|
||||
case t == reflect.TypeOf(time.Time{}):
|
||||
return parseTime(field, value)
|
||||
|
||||
case t.Kind() == reflect.Slice, t.Kind() == reflect.Struct, t.Kind() == reflect.Map:
|
||||
return unmarshalJSON(field, value, t)
|
||||
|
||||
default:
|
||||
return convertPrimitive(field, value, t)
|
||||
}
|
||||
}
|
||||
|
||||
func parseTime(field, value string) time.Time {
|
||||
for _, layout := range timeFormats {
|
||||
if t, err := time.Parse(layout, value); err == nil {
|
||||
return t
|
||||
}
|
||||
}
|
||||
logrus.Errorf("❌ %s: cannot parse %q as time.Time", field, value)
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
func unmarshalJSON(field, value string, t reflect.Type) interface{} {
|
||||
target := reflect.New(t).Interface()
|
||||
if err := json.Unmarshal([]byte(value), target); err != nil {
|
||||
logrus.Errorf("❌ %s: JSON unmarshal into %s: %v", field, t, err)
|
||||
return reflect.Zero(t).Interface()
|
||||
}
|
||||
return reflect.ValueOf(target).Elem().Interface()
|
||||
}
|
||||
|
||||
func convertPrimitive(field, value string, t reflect.Type) interface{} {
|
||||
switch t.Kind() {
|
||||
case reflect.String:
|
||||
return value
|
||||
|
||||
case reflect.Bool:
|
||||
b, err := strconv.ParseBool(strings.ToLower(value))
|
||||
if err != nil {
|
||||
logrus.Errorf("❌ %s → bool: %v", field, err)
|
||||
return false
|
||||
}
|
||||
return b
|
||||
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
n, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil {
|
||||
logrus.Errorf("❌ %s → int: %v", field, err)
|
||||
return reflect.Zero(t).Interface()
|
||||
}
|
||||
return reflect.ValueOf(n).Convert(t).Interface()
|
||||
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
n, err := strconv.ParseUint(value, 10, 64)
|
||||
if err != nil {
|
||||
logrus.Errorf("❌ %s → uint: %v", field, err)
|
||||
return reflect.Zero(t).Interface()
|
||||
}
|
||||
return reflect.ValueOf(n).Convert(t).Interface()
|
||||
|
||||
case reflect.Float32, reflect.Float64:
|
||||
n, err := strconv.ParseFloat(value, 64)
|
||||
if err != nil {
|
||||
logrus.Errorf("❌ %s → float: %v", field, err)
|
||||
return reflect.Zero(t).Interface()
|
||||
}
|
||||
return reflect.ValueOf(n).Convert(t).Interface()
|
||||
|
||||
default:
|
||||
return unmarshalJSON(field, value, t)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
id,name,code,description,is_active,created_at,updated_at
|
||||
2,Отпуск,vacation,Отпуск,true,2026-03-19 14:24:15.864523,2026-03-19 14:24:15.864523
|
||||
1,Отгул,timeoff,Отгул,true,2026-03-19 14:24:15.864523,2026-03-19 14:24:15.864523
|
||||
3,Больничный,sickleave,Больничный,true,2026-03-19 14:24:15.864523,2026-03-19 14:24:15.864523
|
||||
19,Альфапэт доставка,alphapet_delivery,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
20,В. Отгрузки,v_shipments,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
21,Внебюджетные расходы,non_budget_expenses,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
22,Внебюджетные расходы ПЭТ Лайн,non_budget_expenses_pet_line,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
23,Возвраты,returns,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
24,Заведение новых клиентов,new_clients,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
25,Заказы. Краснодар,orders_krasnodar,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
26,Заказы. Крым,orders_crimea,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
27,Менеджерские расходы,manager_expenses,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
28,Отгрузки на СОХ,shipments_soh,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
29,Отгрузки,shipments,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
30,Нестандартные условия договора поставки,nonstandard_contract,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
31,Расходы АЛЬФАПЭТ,expenses_alphapet,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
32,Расходы склад Гвардейское,expenses_warehouse_gvardeysk,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
33,РУСПЭТ ДОСТАВКА + НАПРЯМУЮ К КЛИЕНТУ,ruspet_delivery,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
34,Вакансии,vacancies,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
37,ПС Беларусь,ps_belarus,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
38,ПС Краснодар,ps_krasnodar,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
39,ПС Крым,ps_crimea,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
40,Ставки доставки АП,delivery_rates_ap,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
41,Утверждение оплат безнал,payments_cashless,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
43,Утверждение фрилансеров,freelancers_approval,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
42,Утверждение ставок,rates_logistics,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
|
||||
|
|
|
@ -0,0 +1,48 @@
|
|||
id,category_id,name,code,duration_type,time_type,payment_type,template,allows_file,is_active,created_at,updated_at
|
||||
1,1,"Отгул — несколько дней, частично",timeoff_multi_day_partial_own_expense,multi_day,partial,own_expense,"22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00",false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
2,1,"Отгул — несколько дней, весь день, в счёт отпуска",timeoff_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
3,1,"Отгул — несколько дней, весь день, за свой счёт",timeoff_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
4,1,"Отгул — диапазон, частично",timeoff_date_range_partial_own_expense,date_range,partial,own_expense,22.02.2022 - 25.02.2022 с 16:00 по 18:00,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
5,1,"Отгул — диапазон, весь день, в счёт отпуска",timeoff_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
6,1,"Отгул — диапазон, весь день, за свой счёт",timeoff_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
7,1,"Отгул — один день, частично",timeoff_single_day_partial_own_expense,single_day,partial,own_expense,22.02.2022 с 16:00 по 18:00,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
8,1,"Отгул — один день, весь день, в счёт отпуска",timeoff_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
9,1,"Отгул — один день, весь день, за свой счёт",timeoff_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
|
||||
28,2,"Отпуск — несколько дней, в счёт отпуска",vacation_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
|
||||
29,2,"Отпуск — несколько дней, за свой счёт",vacation_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
|
||||
30,2,"Отпуск — диапазон дат, в счёт отпуска",vacation_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
|
||||
31,2,"Отпуск — диапазон дат, за свой счёт",vacation_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
|
||||
32,2,"Отпуск — один день, в счёт отпуска",vacation_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
|
||||
33,2,"Отпуск — один день, за свой счёт",vacation_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
|
||||
34,3,"Больничный — несколько дней, официальный",sickleave_multi_day_full_day_official,multi_day,full_day,official,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
35,3,"Больничный — несколько дней, в счёт отпуска",sickleave_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
36,3,"Больничный — несколько дней, за свой счёт",sickleave_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
37,3,"Больничный — диапазон дат, официальный",sickleave_date_range_full_day_official,date_range,full_day,official,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
38,3,"Больничный — диапазон дат, в счёт отпуска",sickleave_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
39,3,"Больничный — диапазон дат, за свой счёт",sickleave_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
40,3,"Больничный — один день, официальный",sickleave_single_day_full_day_official,single_day,full_day,official,22.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
41,3,"Больничный — один день, в счёт отпуска",sickleave_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
42,3,"Больничный — один день, за свой счёт",sickleave_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
|
||||
117,19,Альфапэт доставка,alphapet_delivery,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
118,20,В. Отгрузки,v_shipments,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
119,21,Внебюджетные расходы,non_budget_expenses,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
120,22,Внебюджетные расходы ПЭТ Лайн,non_budget_expenses_pet_line,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
121,23,Возвраты,returns,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
122,24,Заведение новых клиентов,new_clients,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
124,26,Заказы. Крым,orders_crimea,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
125,27,Менеджерские расходы,manager_expenses,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
126,28,Отгрузки на СОХ,shipments_soh,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
127,29,Отгрузки,shipments,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
128,30,Нестандартные условия договора поставки,nonstandard_contract,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
129,31,Расходы АЛЬФАПЭТ,expenses_alphapet,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
130,32,Расходы склад Гвардейское,expenses_warehouse_gvardeysk,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
131,33,РУСПЭТ ДОСТАВКА + НАПРЯМУЮ К КЛИЕНТУ,ruspet_delivery,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
132,34,Вакансии,vacancies,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
133,37,ПС Беларусь,ps_belarus,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
134,38,ПС Краснодар,ps_krasnodar,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
135,39,ПС Крым,ps_crimea,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
136,40,Ставки доставки АП,delivery_rates_ap,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
137,41,Утверждение оплат безнал,payments_cashless,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
138,43,Утверждение фрилансеров,freelancers_approval,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
139,42,Утверждение ставок,rates_logistics,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
123,25,Заказы. Краснодар,orders_krasnodar,,,,Опишите запрос в свободной форме,true,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
package dbmigration
|
||||
|
||||
import (
|
||||
tablesmigration "bitrix_balancer_api/core/db/db_migration/tables"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (m *MigrationFunctions) migrateTables() error {
|
||||
logrus.Warningln("🔍 Initialize db migration...")
|
||||
|
||||
migrations := []func(*gorm.DB) error{
|
||||
// Независимые справочники
|
||||
tablesmigration.DepartmentsTableMigrate,
|
||||
tablesmigration.RolesTableMigrate,
|
||||
tablesmigration.ApprovalTopicCategoriesTableMigrate,
|
||||
|
||||
// Зависят от справочников
|
||||
tablesmigration.UsersTableMigrate, // → departments
|
||||
tablesmigration.ApprovalTopicsTableMigrate, // → approval_topic_categories
|
||||
tablesmigration.PermissionsTableMigrate, // → roles, approval_topic_categories, approval_topics
|
||||
|
||||
// Зависят от users
|
||||
tablesmigration.UserRolesTableMigrate, // → users, roles
|
||||
tablesmigration.UserHierarchyTableMigrate, // → users, departments
|
||||
|
||||
// Зависят от всего выше
|
||||
tablesmigration.ApprovalsTableMigrate, // → users, approval_topics, departments
|
||||
tablesmigration.ApprovalStepsTableMigrate, // → approvals, users
|
||||
tablesmigration.ApprovalsFilesTableMigrate, // → approvals
|
||||
|
||||
tablesmigration.ApprovalDelegationTableMigrate,
|
||||
tablesmigration.ApprovalAdditionalApproverTableMigrate,
|
||||
tablesmigration.ApprovalTasksTableMigrate,
|
||||
}
|
||||
|
||||
for _, migrate := range migrations {
|
||||
if err := migrate(m.gormDB); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_initiator_id FOREIGN KEY (initiator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_revoked_by_id FOREIGN KEY (revoked_by_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approvals" IS 'Заявки на согласование, поданные сотрудниками';
|
||||
COMMENT ON COLUMN "approvals".id IS 'Внутренний ID заявки';
|
||||
COMMENT ON COLUMN "approvals".initiator_id IS 'Сотрудник, подавший заявку';
|
||||
COMMENT ON COLUMN "approvals".topic_id IS 'Тема заявки';
|
||||
COMMENT ON COLUMN "approvals".department_id IS 'Снимок отдела инициатора на момент подачи. Не меняется при переводе сотрудника';
|
||||
COMMENT ON COLUMN "approvals".content IS 'Данные, введённые пользователем по шаблону темы';
|
||||
COMMENT ON COLUMN "approvals".status IS 'Статус заявки: draft | pending | approved | rejected | revoked';
|
||||
COMMENT ON COLUMN "approvals".file_base64 IS 'Прикреплённый файл в формате base64. Заполняется только если тема допускает файл';
|
||||
COMMENT ON COLUMN "approvals".file_name IS 'Оригинальное имя прикреплённого файла';
|
||||
COMMENT ON COLUMN "approvals".revoked_by_id IS 'Кто отозвал заявку: сам инициатор или директор';
|
||||
COMMENT ON COLUMN "approvals".revoked_at IS 'Дата и время отзыва заявки';
|
||||
COMMENT ON COLUMN "approvals".created_at IS 'Дата подачи заявки';
|
||||
COMMENT ON COLUMN "approvals".updated_at IS 'Дата последнего изменения заявки';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&ApprovalAdditionalApprover{})
|
||||
|
||||
if err := db.AutoMigrate(&ApprovalAdditionalApprover{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key constraints
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
// Comments
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_additional_approvers" IS 'Дополнительные согласующие заявки: кто добавлен для согласования конкретной заявки';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".id IS 'Внутренний уникальный идентификатор записи';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".approval_id IS 'ID заявки, к которой добавлен согласующий (ссылка на approvals.id)';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".approver_id IS 'ID сотрудника, добавленного как дополнительный согласующий (ссылка на users.id)';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".added_by_id IS 'ID сотрудника, который добавил этого согласующего (ссылка на users.id)';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".status IS 'Статус действия согласующего: pending, approved, rejected';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".comment IS 'Комментарий согласующего к своему решению (опционально)';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".acted_at IS 'Дата и время, когда согласующий принял решение (опционально)';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".created_at IS 'Дата и время создания записи';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".updated_at IS 'Дата и время последнего изменения записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalDelegationTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalDelegationProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalDelegationProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key constraints
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegator_id FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegate_id FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
|
||||
// Comments
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_delegations" IS 'Делегирование прав согласования: кто кому может согласовывать заявки по определённым темам';
|
||||
COMMENT ON COLUMN "approval_delegations".id IS 'Внутренний уникальный идентификатор записи делегирования';
|
||||
COMMENT ON COLUMN "approval_delegations".delegator_id IS 'ID сотрудника, который делегирует право согласования (ссылка на users.id)';
|
||||
COMMENT ON COLUMN "approval_delegations".delegate_id IS 'ID сотрудника, получающего право согласования вместо делегатора (ссылка на users.id)';
|
||||
COMMENT ON COLUMN "approval_delegations".topic_id IS 'ID темы заявки, на которую распространяется делегирование (ссылка на approval_topics.id)';
|
||||
COMMENT ON COLUMN "approval_delegations".valid_until IS 'Дата и время, до которого действует делегирование (включительно)';
|
||||
COMMENT ON COLUMN "approval_delegations".is_active IS 'Флаг активности: true — делегирование применяется, false — временно отключено';
|
||||
COMMENT ON COLUMN "approval_delegations".notified_day IS 'Флаг: отправлено ли уведомление делегатору за 1 день до истечения срока';
|
||||
COMMENT ON COLUMN "approval_delegations".notified_2h IS 'Флаг: отправлено ли уведомление делегатору за 2 часа до истечения срока';
|
||||
COMMENT ON COLUMN "approval_delegations".created_at IS 'Дата и время создания записи делегирования';
|
||||
COMMENT ON COLUMN "approval_delegations".updated_at IS 'Дата и время последнего изменения записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalsFilesTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalFileProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalFileProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_files ADD CONSTRAINT fk_approval_id FOREIGN KEY (initiator_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_files" IS 'Файлы, приложенные к заявкам на согласование';
|
||||
COMMENT ON COLUMN "approval_files".id IS 'Внутренний ID файла';
|
||||
COMMENT ON COLUMN "approval_files".approval_id IS 'ID заявки, к которой привязаны файлы';
|
||||
COMMENT ON COLUMN "approval_files".file_base64 IS 'Прикреплённый файл в формате base64. Заполняется только если тема допускает файл';
|
||||
COMMENT ON COLUMN "approval_files".file_name IS 'Оригинальное имя прикреплённого файла';
|
||||
COMMENT ON COLUMN "approval_files".created_at IS 'Дата создания файла';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalStepsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalStepProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalStepProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_steps ADD CONSTRAINT fk_approval_steps_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_steps ADD CONSTRAINT fk_approval_steps_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_steps" IS 'Шаги согласования по каждой заявке. Один шаг — один согласующий';
|
||||
COMMENT ON COLUMN "approval_steps".id IS 'Внутренний ID шага';
|
||||
COMMENT ON COLUMN "approval_steps".approval_id IS 'Ссылка на заявку';
|
||||
COMMENT ON COLUMN "approval_steps".approver_id IS 'Согласующий на данном шаге';
|
||||
COMMENT ON COLUMN "approval_steps".step_order IS 'Порядковый номер шага. 1 = первый согласующий';
|
||||
COMMENT ON COLUMN "approval_steps".status IS 'Статус шага: pending | approved | rejected';
|
||||
COMMENT ON COLUMN "approval_steps".comment IS 'Комментарий согласующего при отклонении. Может быть пустым';
|
||||
COMMENT ON COLUMN "approval_steps".approver_name_snapshot IS 'Снимок имени согласующего на момент действия. Для корректных исторических отчётов';
|
||||
COMMENT ON COLUMN "approval_steps".approver_department_snapshot IS 'Снимок отдела согласующего на момент действия. Для корректных исторических отчётов';
|
||||
COMMENT ON COLUMN "approval_steps".acted_at IS 'Дата и время принятия решения по шагу';
|
||||
COMMENT ON COLUMN "approval_steps".created_at IS 'Дата создания шага';
|
||||
COMMENT ON COLUMN "approval_steps".updated_at IS 'Дата последнего обновления шага';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalTasksTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&ApprovalTaskProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&ApprovalTaskProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Внешние ключи
|
||||
db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_executor_id FOREIGN KEY (executor_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
|
||||
// Комментарии к таблице и колонкам
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_tasks" IS 'Задачи согласования, назначенные исполнителям';
|
||||
COMMENT ON COLUMN "approval_tasks".id IS 'Внутренний ID задачи';
|
||||
COMMENT ON COLUMN "approval_tasks".approval_id IS 'Связанная заявка на согласование';
|
||||
COMMENT ON COLUMN "approval_tasks".executor_id IS 'Сотрудник-исполнитель задачи';
|
||||
COMMENT ON COLUMN "approval_tasks".task_text IS 'Текст или описание задачи';
|
||||
COMMENT ON COLUMN "approval_tasks".status IS 'Статус задачи: pending | completed | rejected';
|
||||
COMMENT ON COLUMN "approval_tasks".completed_at IS 'Дата и время выполнения задачи';
|
||||
COMMENT ON COLUMN "approval_tasks".created_at IS 'Дата создания задачи';
|
||||
COMMENT ON COLUMN "approval_tasks".updated_at IS 'Дата последнего изменения задачи';
|
||||
`)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalTopicsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalTopicProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalTopicProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_topics ADD CONSTRAINT fk_approval_topics_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_topics" IS 'Конкретные темы согласований внутри категорий';
|
||||
COMMENT ON COLUMN "approval_topics".id IS 'Внутренний ID темы';
|
||||
COMMENT ON COLUMN "approval_topics".category_id IS 'Ссылка на категорию';
|
||||
COMMENT ON COLUMN "approval_topics".name IS 'Название темы';
|
||||
COMMENT ON COLUMN "approval_topics".code IS 'Уникальный код темы: otgul_single_full_own, otgul_single_partial и т.д.';
|
||||
COMMENT ON COLUMN "approval_topics".duration_type IS 'Тип длительности: single_day | date_range | multi_day';
|
||||
COMMENT ON COLUMN "approval_topics".time_type IS 'Тип времени: full_day | partial';
|
||||
COMMENT ON COLUMN "approval_topics".payment_type IS 'Тип оплаты: own_expense | vacation_account | not_applicable';
|
||||
COMMENT ON COLUMN "approval_topics".template IS 'Шаблон ввода для пользователя: 22.02.2022 или 22.02.2022 с 16:00 по 18:00';
|
||||
COMMENT ON COLUMN "approval_topics".allows_file IS 'Разрешено ли прикрепление файла к заявке по этой теме';
|
||||
COMMENT ON COLUMN "approval_topics".is_active IS 'Активна ли тема. Неактивная тема скрыта из меню бота';
|
||||
COMMENT ON COLUMN "approval_topics".created_at IS 'Дата создания записи';
|
||||
COMMENT ON COLUMN "approval_topics".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalTopicCategoriesTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalTopicCategoryProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalTopicCategoryProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_topic_categories" IS 'Категории тем согласований: Отгул, Отпуск, Больничный и т.д.';
|
||||
COMMENT ON COLUMN "approval_topic_categories".id IS 'Внутренний ID категории';
|
||||
COMMENT ON COLUMN "approval_topic_categories".name IS 'Название категории: Отгул, Отпуск, Больничный';
|
||||
COMMENT ON COLUMN "approval_topic_categories".code IS 'Уникальный код категории: otgul, vacation, sick_leave';
|
||||
COMMENT ON COLUMN "approval_topic_categories".description IS 'Описание категории';
|
||||
COMMENT ON COLUMN "approval_topic_categories".is_active IS 'Активна ли категория. Неактивная категория скрыта из меню бота';
|
||||
COMMENT ON COLUMN "approval_topic_categories".created_at IS 'Дата создания записи';
|
||||
COMMENT ON COLUMN "approval_topic_categories".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func DepartmentsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalDepartmentProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalDepartmentProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "departments" IS 'Отделы компании';
|
||||
COMMENT ON COLUMN "departments".id IS 'Внутренний ID отдела';
|
||||
COMMENT ON COLUMN "departments".name IS 'Название отдела: Финансовый отдел, IT отдел и т.д.';
|
||||
COMMENT ON COLUMN "departments".code IS 'Уникальный код отдела: finance, hr, it и т.д.';
|
||||
COMMENT ON COLUMN "departments".description IS 'Описание отдела';
|
||||
COMMENT ON COLUMN "departments".is_active IS 'Активен ли отдел. Неактивный отдел скрыт из интерфейса';
|
||||
COMMENT ON COLUMN "departments".created_at IS 'Дата создания записи';
|
||||
COMMENT ON COLUMN "departments".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func execComments(db *gorm.DB, sql string) {
|
||||
for i := range 3 {
|
||||
if err := db.Exec(sql).Error; err == nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Duration(i+1) * time.Second)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func PermissionsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalPermissionProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalPermissionProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_role_id FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_topic_category_id FOREIGN KEY (topic_category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE permissions ADD CONSTRAINT uq_permissions_role_category_action UNIQUE (role_id, topic_category_id, action)`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "permissions" IS 'Права ролей на действия в рамках тем или категорий согласований';
|
||||
COMMENT ON COLUMN "permissions".id IS 'Внутренний ID записи';
|
||||
COMMENT ON COLUMN "permissions".role_id IS 'Роль, которой выдано право';
|
||||
COMMENT ON COLUMN "permissions".topic_category_id IS 'Категория тем. Если заполнено и topic_id = NULL — право на все темы категории';
|
||||
COMMENT ON COLUMN "permissions".topic_id IS 'Конкретная тема. Если заполнено — право только на эту тему';
|
||||
COMMENT ON COLUMN "permissions".action IS 'Действие: create | read | update | delete | approve | revoke';
|
||||
COMMENT ON COLUMN "permissions".created_at IS 'Дата создания записи';
|
||||
COMMENT ON COLUMN "permissions".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
)
|
||||
|
||||
type LocalUserProvider typescore.User
|
||||
type LocalDepartmentProvider typescore.Department
|
||||
type LocalRoleProvider typescore.Role
|
||||
type LocalUserRoleProvider typescore.UserRole
|
||||
type LocalUserHierarchyProvider typescore.UserHierarchy
|
||||
type LocalPermissionProvider typescore.Permission
|
||||
type LocalApprovalTopicCategoryProvider typescore.ApprovalTopicCategory
|
||||
type LocalApprovalTopicProvider typescore.ApprovalTopic
|
||||
type LocalApprovalProvider typescore.Approval
|
||||
type LocalApprovalDelegationProvider typescore.ApprovalDelegation
|
||||
type LocalApprovalFileProvider typescore.ApprovalFile
|
||||
type LocalApprovalStepProvider typescore.ApprovalStep
|
||||
type ApprovalAdditionalApprover typescore.ApprovalAdditionalApprover
|
||||
type ApprovalTaskProvider typescore.ApprovalTask
|
||||
|
||||
func (LocalUserProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameUsers.ToString()
|
||||
}
|
||||
func (LocalDepartmentProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameDepartments.ToString()
|
||||
}
|
||||
func (LocalRoleProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameRoles.ToString()
|
||||
}
|
||||
func (LocalUserRoleProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameUserRoles.ToString()
|
||||
}
|
||||
func (LocalUserHierarchyProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameUserHierarchy.ToString()
|
||||
}
|
||||
func (LocalPermissionProvider) TableName() string {
|
||||
return dbcoretablenames.TableNamePermissions.ToString()
|
||||
}
|
||||
func (LocalApprovalTopicCategoryProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalTopicCategories.ToString()
|
||||
}
|
||||
func (LocalApprovalTopicProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalTopics.ToString()
|
||||
}
|
||||
func (LocalApprovalProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovals.ToString()
|
||||
}
|
||||
func (LocalApprovalStepProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalSteps.ToString()
|
||||
}
|
||||
func (LocalApprovalFileProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalFiles.ToString()
|
||||
}
|
||||
func (LocalApprovalDelegationProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalDelegations.ToString()
|
||||
}
|
||||
func (ApprovalAdditionalApprover) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()
|
||||
}
|
||||
func (ApprovalTaskProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalTasks.ToString()
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func RolesTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalRoleProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalRoleProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "roles" IS 'Роли пользователей в системе согласований';
|
||||
COMMENT ON COLUMN "roles".id IS 'Внутренний ID роли';
|
||||
COMMENT ON COLUMN "roles".name IS 'Название роли: Сотрудник, Согласующий, Директор';
|
||||
COMMENT ON COLUMN "roles".code IS 'Уникальный код роли: employee, approver, director';
|
||||
COMMENT ON COLUMN "roles".is_default IS 'Назначается ли роль автоматически при регистрации пользователя';
|
||||
COMMENT ON COLUMN "roles".is_director IS 'Получает финальные уведомления по всем отделам. Может отозвать любое согласование';
|
||||
COMMENT ON COLUMN "roles".is_approver IS 'Может согласовывать заявки своих подчинённых';
|
||||
COMMENT ON COLUMN "roles".description IS 'Описание роли';
|
||||
COMMENT ON COLUMN "roles".created_at IS 'Дата создания записи';
|
||||
COMMENT ON COLUMN "roles".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func UsersTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalUserProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalUserProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE users ADD CONSTRAINT fk_users_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "users" IS 'Сотрудники компании РусПЭТ';
|
||||
COMMENT ON COLUMN "users".id IS 'Внутренний ID пользователя';
|
||||
COMMENT ON COLUMN "users".telegram_id IS 'Уникальный Telegram ID пользователя';
|
||||
COMMENT ON COLUMN "users".username IS 'Telegram @username, может быть NULL';
|
||||
COMMENT ON COLUMN "users".full_name IS 'Полное имя сотрудника';
|
||||
COMMENT ON COLUMN "users".language_code IS 'Языковой код клиента: ru, en и т.д.';
|
||||
COMMENT ON COLUMN "users".department_id IS 'Основной отдел сотрудника. NULL — бот пуст, функционал недоступен';
|
||||
COMMENT ON COLUMN "users".is_blocked IS 'Заблокирован ли пользователь';
|
||||
COMMENT ON COLUMN "users".blocked_at IS 'Дата блокировки';
|
||||
COMMENT ON COLUMN "users".last_login IS 'Дата последнего входа';
|
||||
COMMENT ON COLUMN "users".created_at IS 'Дата регистрации';
|
||||
COMMENT ON COLUMN "users".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func UserHierarchyTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalUserHierarchyProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalUserHierarchyProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_subordinate_id FOREIGN KEY (subordinate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "user_hierarchy" IS 'Иерархия согласования. Определяет кто кому подчиняется в рамках отдела';
|
||||
COMMENT ON COLUMN "user_hierarchy".id IS 'Внутренний ID записи';
|
||||
COMMENT ON COLUMN "user_hierarchy".subordinate_id IS 'Подчинённый — инициатор согласования';
|
||||
COMMENT ON COLUMN "user_hierarchy".approver_id IS 'Согласующий. Может быть привязан к нескольким отделам через разные записи';
|
||||
COMMENT ON COLUMN "user_hierarchy".department_id IS 'Контекст связи — в рамках какого отдела действует иерархия';
|
||||
COMMENT ON COLUMN "user_hierarchy".priority IS 'Порядок шага согласования. 1 = первый согласующий';
|
||||
COMMENT ON COLUMN "user_hierarchy".created_at IS 'Дата создания записи';
|
||||
COMMENT ON COLUMN "user_hierarchy".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func UserRolesTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalUserRoleProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalUserRoleProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE user_roles ADD CONSTRAINT fk_user_roles_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE user_roles ADD CONSTRAINT fk_user_roles_role_id FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "user_roles" IS 'Связь пользователей и ролей. Один пользователь может иметь несколько ролей';
|
||||
COMMENT ON COLUMN "user_roles".id IS 'Внутренний ID записи';
|
||||
COMMENT ON COLUMN "user_roles".user_id IS 'Ссылка на пользователя';
|
||||
COMMENT ON COLUMN "user_roles".role_id IS 'Ссылка на роль';
|
||||
COMMENT ON COLUMN "user_roles".created_at IS 'Дата назначения роли';
|
||||
COMMENT ON COLUMN "user_roles".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
package dbmigration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (m *MigrationFunctions) TriggerMigrations() {
|
||||
logrus.Info(fmt.Sprintf(" Start db triggers creation: %s", time.Now().UTC()))
|
||||
|
||||
// Функция: назначает роль is_default=true пользователю если её ещё нет
|
||||
m.gormDB.Exec(`
|
||||
CREATE OR REPLACE FUNCTION assign_default_role_on_department()
|
||||
RETURNS TRIGGER AS $$
|
||||
DECLARE
|
||||
v_default_role_id BIGINT;
|
||||
BEGIN
|
||||
-- Срабатываем только когда department_id впервые становится не NULL
|
||||
-- или меняется с NULL на значение
|
||||
IF (OLD.department_id IS NOT DISTINCT FROM NEW.department_id) THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
IF NEW.department_id IS NULL THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
-- Ищем роль с is_default = true
|
||||
SELECT id INTO v_default_role_id
|
||||
FROM roles
|
||||
WHERE is_default = true
|
||||
LIMIT 1;
|
||||
|
||||
IF v_default_role_id IS NULL THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
-- Вставляем связь только если её ещё нет
|
||||
INSERT INTO user_roles (user_id, role_id, created_at, updated_at)
|
||||
VALUES (NEW.id, v_default_role_id, NOW(), NOW())
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
`)
|
||||
|
||||
m.gormDB.Exec(`
|
||||
DROP TRIGGER IF EXISTS trg_assign_default_role_on_department ON users;
|
||||
CREATE TRIGGER trg_assign_default_role_on_department
|
||||
AFTER UPDATE OF department_id ON users
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION assign_default_role_on_department();
|
||||
`)
|
||||
|
||||
// ─── Seed: базовые права для роли employee если permissions пусты ────────
|
||||
|
||||
// выдаёт права create на timeoff/vacation/sick_leave для роли employee
|
||||
// Срабатывает при INSERT в roles — один раз при создании роли employee
|
||||
m.gormDB.Exec(`
|
||||
CREATE OR REPLACE FUNCTION seed_default_permissions_on_role()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
-- Только для роли с is_default = true
|
||||
IF NEW.is_default IS NOT TRUE THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
-- Вставляем права на базовые категории если их ещё нет
|
||||
INSERT INTO permissions (role_id, topic_category_id, action, created_at, updated_at)
|
||||
SELECT
|
||||
NEW.id,
|
||||
tc.id,
|
||||
'create',
|
||||
NOW(),
|
||||
NOW()
|
||||
FROM approval_topic_categories tc
|
||||
WHERE tc.code IN ('timeoff', 'vacation', 'sick_leave')
|
||||
AND tc.is_active = true
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM permissions p
|
||||
WHERE p.role_id = NEW.id
|
||||
AND p.topic_category_id = tc.id
|
||||
AND p.action = 'create'
|
||||
);
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
`)
|
||||
|
||||
m.gormDB.Exec(`
|
||||
DROP TRIGGER IF EXISTS trg_seed_default_permissions_on_role ON roles;
|
||||
CREATE TRIGGER trg_seed_default_permissions_on_role
|
||||
AFTER INSERT ON roles
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION seed_default_permissions_on_role();
|
||||
`)
|
||||
|
||||
// ─── Страховка: выдать права если permissions пусты для existing ролей ───
|
||||
m.gormDB.Exec(`
|
||||
INSERT INTO permissions (role_id, topic_category_id, action, created_at, updated_at)
|
||||
SELECT
|
||||
r.id,
|
||||
tc.id,
|
||||
'create',
|
||||
NOW(),
|
||||
NOW()
|
||||
FROM roles r
|
||||
CROSS JOIN approval_topic_categories tc
|
||||
WHERE r.is_default = true
|
||||
AND tc.code IN ('timeoff', 'vacation', 'sick_leave')
|
||||
AND tc.is_active = true
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM permissions p
|
||||
WHERE p.role_id = r.id
|
||||
AND p.topic_category_id = tc.id
|
||||
AND p.action = 'create'
|
||||
);
|
||||
`)
|
||||
}
|
||||
|
||||
func (m *MigrationFunctions) DropAllTriggers() {
|
||||
logrus.Info(fmt.Sprintf("🧹 Start dropping all database triggers: %s", time.Now().UTC()))
|
||||
|
||||
// Получаем список всех триггеров в схеме public
|
||||
m.gormDB.Exec(`
|
||||
DO $$
|
||||
DECLARE
|
||||
trigger_record RECORD;
|
||||
BEGIN
|
||||
-- Получаем все триггеры из схемы public
|
||||
FOR trigger_record IN
|
||||
SELECT
|
||||
ns.nspname as schema_name,
|
||||
tg.tgname as trigger_name,
|
||||
rel.relname as table_name
|
||||
FROM pg_trigger tg
|
||||
JOIN pg_class rel ON tg.tgrelid = rel.oid
|
||||
JOIN pg_namespace ns ON rel.relnamespace = ns.oid
|
||||
WHERE ns.nspname = 'public'
|
||||
AND NOT tg.tgisinternal -- исключаем системные триггеры
|
||||
AND tg.tgname NOT LIKE 'pg_%' -- исключаем системные триггеры
|
||||
LOOP
|
||||
-- Формируем и выполняем DROP TRIGGER
|
||||
EXECUTE format('DROP TRIGGER IF EXISTS %I ON %I.%I CASCADE',
|
||||
trigger_record.trigger_name,
|
||||
trigger_record.schema_name,
|
||||
trigger_record.table_name
|
||||
);
|
||||
END LOOP;
|
||||
END $$;
|
||||
`)
|
||||
|
||||
logrus.Info(fmt.Sprintf("✅ All database triggers have been dropped: %s", time.Now().UTC()))
|
||||
}
|
||||
|
|
@ -0,0 +1,424 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ApprovalDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalDB(pool *pgxpool.Pool) *ApprovalDB {
|
||||
return &ApprovalDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type ApprovalDBI interface {
|
||||
GetApprovalsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error)
|
||||
CreateApprovalDB(ctx context.Context, tx pgx.Tx, ApprovalObj *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error)
|
||||
UpdateApprovalDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error)
|
||||
DeleteApprovalDB(ctx context.Context, params *typescore.Approval) error
|
||||
GetApprovalByIDDB(ctx context.Context, id uint64) (*typescore.Approval, error)
|
||||
GetActiveApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error)
|
||||
GetPendingApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.Approval, error)
|
||||
GetApprovalsByInitiatorAndCategoryDB(ctx context.Context, initiatorID uint64, categoryCode string) ([]*typescore.Approval, error)
|
||||
GetPendingApprovalsByApproverAndCategoryDB(ctx context.Context, approverID uint64, categoryCode string) ([]*typescore.Approval, error)
|
||||
GetApprovalsByCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.Approval, error)
|
||||
GetClosedApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalDB) GetApprovalsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.Approval](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovals.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovals.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var Approvals []*typescore.Approval
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
Approval := &typescore.Approval{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, Approval, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalsListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
Approvals = append(Approvals, Approval)
|
||||
}
|
||||
|
||||
return Approvals, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalDB) CreateApprovalDB(ctx context.Context, tx pgx.Tx, ApprovalObj *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error) {
|
||||
if ApprovalObj == nil {
|
||||
return nil, nil, errors.New("approval obj is nil")
|
||||
}
|
||||
|
||||
var insertedID uint64
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovals.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
created, err := u.GetApprovalByIDDB(ctx, insertedID)
|
||||
return created, tx, err
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalDB) UpdateApprovalDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("approval obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovals.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.Approval{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetApprovalsListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalDB) DeleteApprovalDB(ctx context.Context, params *typescore.Approval) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovals.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("approval obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ApprovalDB) GetApprovalByIDDB(ctx context.Context, id uint64) (*typescore.Approval, error) {
|
||||
approvals, _, err := u.GetApprovalsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(approvals) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return approvals[0], nil
|
||||
}
|
||||
|
||||
// GetActiveApprovalsByInitiatorDB — активные заявки инициатора (не закрытые)
|
||||
func (u *ApprovalDB) GetActiveApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString())...).
|
||||
From(dbcoretablenames.TableNameApprovals.ToString()).
|
||||
Where(squirrel.Eq{"initiator_id": initiatorID}).
|
||||
// Показываем pending и approved — закрытые (revoked, rejected) не показываем
|
||||
Where(squirrel.Eq{"status": []string{"pending", "approved"}}).
|
||||
OrderBy("created_at DESC").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.Approval
|
||||
for rows.Next() {
|
||||
a := &typescore.Approval{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
|
||||
logrus.Warn("GetActiveApprovalsByInitiatorDB:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, a)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetPendingApprovalsByApproverDB — заявки ожидающие действия от согласующего
|
||||
func (u *ApprovalDB) GetPendingApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.Approval, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT a.*").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString() + " a").
|
||||
Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id").
|
||||
Where(squirrel.Eq{"s.approver_id": approverID}).
|
||||
Where(squirrel.Eq{"s.status": "pending"}).
|
||||
Where(squirrel.Eq{"a.status": "pending"}).
|
||||
OrderBy("a.created_at DESC").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.Approval
|
||||
for rows.Next() {
|
||||
a := &typescore.Approval{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
|
||||
logrus.Warn("GetPendingApprovalsByApproverDB:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, a)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetApprovalsByInitiatorAndCategoryDB — заявки инициатора по категории
|
||||
func (u *ApprovalDB) GetApprovalsByInitiatorAndCategoryDB(ctx context.Context, initiatorID uint64, categoryCode string) ([]*typescore.Approval, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("a.*").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString() + " a").
|
||||
Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
|
||||
Where(squirrel.Eq{"a.initiator_id": initiatorID}).
|
||||
Where(squirrel.Eq{"c.code": categoryCode}).
|
||||
Where(squirrel.Eq{"a.status": []string{"pending", "approved"}}).
|
||||
OrderBy("a.created_at DESC").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.queryApprovals(ctx, sql, args)
|
||||
}
|
||||
|
||||
// GetPendingApprovalsByApproverAndCategoryDB — входящие по категории для согласующего
|
||||
func (u *ApprovalDB) GetPendingApprovalsByApproverAndCategoryDB(ctx context.Context, approverID uint64, categoryCode string) ([]*typescore.Approval, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT a.*").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString() + " a").
|
||||
Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
|
||||
Where(squirrel.Eq{"s.approver_id": approverID}).
|
||||
Where(squirrel.Eq{"s.status": "pending"}).
|
||||
Where(squirrel.Eq{"a.status": "pending"}).
|
||||
Where(squirrel.Eq{"c.code": categoryCode}).
|
||||
OrderBy("a.created_at DESC").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.queryApprovals(ctx, sql, args)
|
||||
}
|
||||
|
||||
// GetApprovalsByCategoryDB — все заявки по категории для наблюдателя
|
||||
func (u *ApprovalDB) GetApprovalsByCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.Approval, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("a.*").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString() + " a").
|
||||
Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
|
||||
Where(squirrel.Eq{"c.code": categoryCode}).
|
||||
OrderBy("a.created_at DESC").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.queryApprovals(ctx, sql, args)
|
||||
}
|
||||
|
||||
// queryApprovals — общий сканер строк
|
||||
func (u *ApprovalDB) queryApprovals(ctx context.Context, sql string, args []interface{}) ([]*typescore.Approval, error) {
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.Approval
|
||||
for rows.Next() {
|
||||
a := &typescore.Approval{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
|
||||
logrus.Warn("queryApprovals:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, a)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetClosedApprovalsByInitiatorDB — отклонённые и отозванные заявки инициатора.
|
||||
func (u *ApprovalDB) GetClosedApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString())...).
|
||||
From(dbcoretablenames.TableNameApprovals.ToString()).
|
||||
Where(squirrel.Eq{"initiator_id": initiatorID}).
|
||||
Where(squirrel.Eq{"status": []string{"rejected", "revoked"}}).
|
||||
OrderBy("updated_at DESC").
|
||||
Limit(50).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.queryApprovals(ctx, sql, args)
|
||||
}
|
||||
|
||||
// GetApprovalsForReportDB — получение согласований для отчёта с учётом всех ролей пользователя.
|
||||
// Пользователь видит согласования где он: инициатор, согласующий, наблюдатель или исполнитель.
|
||||
func (u *ApprovalDB) GetApprovalsForReportDB(ctx context.Context, filter typescore.ReportFilter) ([]*typescore.Approval, error) {
|
||||
q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT a.*").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString() + " a").
|
||||
OrderBy("a.created_at DESC")
|
||||
|
||||
if !filter.AllAccess && filter.UserID != nil {
|
||||
subQ1 := buildApprovalIdSubquery("initiator", filter.UserID)
|
||||
subQ2 := buildApprovalIdSubquery("approver", filter.UserID)
|
||||
subQ3 := buildApprovalIdSubquery("observer", filter.UserID)
|
||||
subQ4 := buildApprovalIdSubquery("executor", filter.UserID)
|
||||
|
||||
s1, a1, _ := subQ1.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s2, a2, _ := subQ2.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s3, a3, _ := subQ3.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s4, a4, _ := subQ4.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
|
||||
unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4)
|
||||
allArgs := append(append(append(a1, a2...), a3...), a4...)
|
||||
|
||||
q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...))
|
||||
}
|
||||
|
||||
if filter.DateFrom != nil {
|
||||
q = q.Where(squirrel.GtOrEq{"a.created_at": filter.DateFrom})
|
||||
}
|
||||
if filter.DateTo != nil {
|
||||
endOfDay := filter.DateTo.Add(24*time.Hour - time.Second)
|
||||
q = q.Where(squirrel.LtOrEq{"a.created_at": endOfDay})
|
||||
}
|
||||
|
||||
sql, args, err := q.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.queryApprovals(ctx, sql, args)
|
||||
}
|
||||
|
||||
func buildApprovalIdSubquery(role string, userID *uint64) squirrel.SelectBuilder {
|
||||
q := squirrel.Select("a.id").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString() + " a")
|
||||
|
||||
switch role {
|
||||
case "initiator":
|
||||
return q.Where(squirrel.Eq{"a.initiator_id": userID})
|
||||
|
||||
case "approver":
|
||||
return q.
|
||||
Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id").
|
||||
Where(squirrel.Eq{"s.approver_id": userID})
|
||||
|
||||
case "executor":
|
||||
return q.
|
||||
Join(dbcoretablenames.TableNameApprovalTasks.ToString() + " task ON task.approval_id = a.id").
|
||||
Where(squirrel.Eq{"task.executor_id": userID})
|
||||
|
||||
case "observer":
|
||||
return q.
|
||||
Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
|
||||
Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.topic_category_id = c.id").
|
||||
Join("user_roles ur ON ur.role_id = p.role_id").
|
||||
Where(squirrel.And{
|
||||
squirrel.Eq{"ur.user_id": userID},
|
||||
squirrel.Eq{"p.action": "observe"},
|
||||
})
|
||||
|
||||
default:
|
||||
return q.Where(squirrel.Expr("false"))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,186 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type ApprovalAdditionalApproverDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalAdditionalApproverDB(pool *pgxpool.Pool) *ApprovalAdditionalApproverDB {
|
||||
return &ApprovalAdditionalApproverDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type ApprovalAdditionalApproverDBI interface {
|
||||
GetApprovalAdditionalApproversListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalApprover, uint64, error)
|
||||
CreateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalApproverObj *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error)
|
||||
UpdateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error)
|
||||
DeleteApprovalAdditionalApproverDB(ctx context.Context, params *typescore.ApprovalAdditionalApprover) error
|
||||
GetApprovalAdditionalApproverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalApprover, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalAdditionalApproverDB) GetApprovalAdditionalApproversListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalApprover, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalAdditionalApprover{}, dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalAdditionalApprover](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ApprovalAdditionalApprovers []*typescore.ApprovalAdditionalApprover
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
ApprovalAdditionalApprover := &typescore.ApprovalAdditionalApprover{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, ApprovalAdditionalApprover, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalAdditionalApproversListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
ApprovalAdditionalApprovers = append(ApprovalAdditionalApprovers, ApprovalAdditionalApprover)
|
||||
}
|
||||
|
||||
return ApprovalAdditionalApprovers, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalAdditionalApproverDB) CreateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalApproverObj *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error) {
|
||||
if ApprovalAdditionalApproverObj == nil {
|
||||
return nil, nil, errors.New("ApprovalAdditionalApprover obj is nil")
|
||||
}
|
||||
|
||||
var insertedID uint64
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalAdditionalApproverObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
created, err := u.GetApprovalAdditionalApproverByIDDB(ctx, insertedID)
|
||||
return created, tx, err
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalAdditionalApproverDB) UpdateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalAdditionalApprover obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.ApprovalAdditionalApprover{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetApprovalAdditionalApproversListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalAdditionalApproverDB) DeleteApprovalAdditionalApproverDB(ctx context.Context, params *typescore.ApprovalAdditionalApprover) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("ApprovalAdditionalApprover obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ApprovalAdditionalApproverDB) GetApprovalAdditionalApproverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalApprover, error) {
|
||||
ApprovalAdditionalApprovers, _, err := u.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalAdditionalApprover{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(ApprovalAdditionalApprovers) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return ApprovalAdditionalApprovers[0], nil
|
||||
}
|
||||
|
|
@ -0,0 +1,186 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type ApprovalDelegationDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalDelegationDB(pool *pgxpool.Pool) *ApprovalDelegationDB {
|
||||
return &ApprovalDelegationDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type ApprovalDelegationDBI interface {
|
||||
GetApprovalDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalDelegation, uint64, error)
|
||||
CreateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, ApprovalDelegationObj *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error)
|
||||
UpdateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error)
|
||||
DeleteApprovalDelegationDB(ctx context.Context, params *typescore.ApprovalDelegation) error
|
||||
GetApprovalDelegationByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalDelegation, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalDelegationDB) GetApprovalDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalDelegation, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalDelegation{}, dbcoretablenames.TableNameApprovalDelegations.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalDelegation](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalDelegations.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalDelegations.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ApprovalDelegations []*typescore.ApprovalDelegation
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
ApprovalDelegation := &typescore.ApprovalDelegation{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, ApprovalDelegation, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalDelegationsListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
ApprovalDelegations = append(ApprovalDelegations, ApprovalDelegation)
|
||||
}
|
||||
|
||||
return ApprovalDelegations, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalDelegationDB) CreateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, ApprovalDelegationObj *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error) {
|
||||
if ApprovalDelegationObj == nil {
|
||||
return nil, nil, errors.New("ApprovalDelegation obj is nil")
|
||||
}
|
||||
|
||||
var insertedID uint64
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalDelegations.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalDelegationObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
created, err := u.GetApprovalDelegationByIDDB(ctx, insertedID)
|
||||
return created, tx, err
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalDelegationDB) UpdateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalDelegation obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalDelegations.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.ApprovalDelegation{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetApprovalDelegationsListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalDelegationDB) DeleteApprovalDelegationDB(ctx context.Context, params *typescore.ApprovalDelegation) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalDelegations.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("ApprovalDelegation obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ApprovalDelegationDB) GetApprovalDelegationByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalDelegation, error) {
|
||||
approvals, _, err := u.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalDelegation{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(approvals) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return approvals[0], nil
|
||||
}
|
||||
|
|
@ -0,0 +1,217 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type ApprovalFileDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalFileDB(pool *pgxpool.Pool) *ApprovalFileDB {
|
||||
return &ApprovalFileDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type ApprovalFileDBI interface {
|
||||
GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error)
|
||||
CreateApprovalFileDB(ctx context.Context, tx pgx.Tx, ApprovalFileObj *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error)
|
||||
UpdateApprovalFileDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error)
|
||||
DeleteApprovalFileDB(ctx context.Context, params *typescore.ApprovalFile) error
|
||||
GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error)
|
||||
GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFile{}, dbcoretablenames.TableNameApprovalFiles.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalFile](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalFiles.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalFiles.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ApprovalFiles []*typescore.ApprovalFile
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
ApprovalFile := &typescore.ApprovalFile{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, ApprovalFile, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalFilesListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
ApprovalFiles = append(ApprovalFiles, ApprovalFile)
|
||||
}
|
||||
|
||||
return ApprovalFiles, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) CreateApprovalFileDB(ctx context.Context, tx pgx.Tx, ApprovalFileObj *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error) {
|
||||
if ApprovalFileObj == nil {
|
||||
return nil, nil, errors.New("ApprovalFile obj is nil")
|
||||
}
|
||||
|
||||
var insertedID uint64
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalFiles.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalFileObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
created, err := u.GetApprovalFileByIDDB(ctx, insertedID)
|
||||
return created, tx, err
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) UpdateApprovalFileDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalFile obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalFiles.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.ApprovalFile{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetApprovalFilesListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) DeleteApprovalFileDB(ctx context.Context, params *typescore.ApprovalFile) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalFiles.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("ApprovalFile obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error) {
|
||||
ApprovalFiles, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalFile{ApprovalID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ApprovalFiles, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error) {
|
||||
approvals, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(approvals) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return approvals[0], nil
|
||||
}
|
||||
|
||||
// queryApprovalFiles — общий сканер строк
|
||||
func (u *ApprovalFileDB) queryApprovalFiles(ctx context.Context, sql string, args []interface{}) ([]*typescore.ApprovalFile, error) {
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.ApprovalFile
|
||||
for rows.Next() {
|
||||
a := &typescore.ApprovalFile{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
|
||||
logrus.Warn("queryApprovalFiles:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, a)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,234 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ApprovalStepDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalStepDB(pool *pgxpool.Pool) *ApprovalStepDB {
|
||||
return &ApprovalStepDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type ApprovalStepDBI interface {
|
||||
GetApprovalStepsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error)
|
||||
CreateApprovalStepDB(ctx context.Context, tx pgx.Tx, ApprovalStepObj *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error)
|
||||
UpdateApprovalStepDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error)
|
||||
DeleteApprovalStepDB(ctx context.Context, params *typescore.ApprovalStep) error
|
||||
|
||||
GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error)
|
||||
GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalStepDB) GetApprovalStepsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalStep](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalSteps.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalSteps.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ApprovalSteps []*typescore.ApprovalStep
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
ApprovalStep := &typescore.ApprovalStep{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, ApprovalStep, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalStepsListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
ApprovalSteps = append(ApprovalSteps, ApprovalStep)
|
||||
}
|
||||
|
||||
return ApprovalSteps, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalStepDB) CreateApprovalStepDB(ctx context.Context, tx pgx.Tx, ApprovalStepObj *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error) {
|
||||
if ApprovalStepObj == nil {
|
||||
return nil, nil, errors.New("ApprovalStep obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalSteps.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalStepObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
ApprovalStep, _, err := u.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalStepObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(ApprovalStep) > 0 {
|
||||
return ApprovalStep[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalStepDB) UpdateApprovalStepDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalStep obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalSteps.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.ApprovalStep{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetApprovalStepsListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalStepDB) DeleteApprovalStepDB(ctx context.Context, params *typescore.ApprovalStep) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalSteps.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("approvalStep obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
// GetActiveStepDB возвращает текущий активный шаг — первый pending по порядку.
|
||||
func (u *ApprovalStepDB) GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error) {
|
||||
pendingStatus := "pending"
|
||||
steps, _, err := u.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{
|
||||
ApprovalID: &approvalID,
|
||||
Status: &pendingStatus,
|
||||
},
|
||||
Limit: func() *uint64 { v := uint64(1); return &v }(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(steps) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return steps[0], nil
|
||||
}
|
||||
|
||||
// GetNextStepDB возвращает следующий шаг после текущего (status = waiting, step_order > current).
|
||||
func (u *ApprovalStepDB) GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString())...).
|
||||
From(dbcoretablenames.TableNameApprovalSteps.ToString()).
|
||||
Where(squirrel.Eq{"approval_id": approvalID}).
|
||||
Where(squirrel.Eq{"status": "waiting"}).
|
||||
Where(squirrel.Gt{"step_order": currentOrder}).
|
||||
OrderBy("step_order ASC").
|
||||
Limit(1).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if rows.Next() {
|
||||
step := &typescore.ApprovalStep{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, step, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return step, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,249 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalTaskDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalTaskDB(pool *pgxpool.Pool) *ApprovalTaskDB {
|
||||
return &ApprovalTaskDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type ApprovalTaskDBI interface {
|
||||
GetApprovalTasksListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTask, uint64, error)
|
||||
CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, ApprovalTaskObj *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error)
|
||||
UpdateApprovalTaskDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error)
|
||||
DeleteApprovalTaskDB(ctx context.Context, params *typescore.ApprovalTask) error
|
||||
GetApprovalTaskByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskDB) GetApprovalTasksListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTask, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTask{}, dbcoretablenames.TableNameApprovalTasks.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTask](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTasks.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTasks.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ApprovalTasks []*typescore.ApprovalTask
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
ApprovalTask := &typescore.ApprovalTask{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, ApprovalTask, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalTasksListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
ApprovalTasks = append(ApprovalTasks, ApprovalTask)
|
||||
}
|
||||
|
||||
return ApprovalTasks, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskDB) CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, ApprovalTaskObj *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) {
|
||||
if ApprovalTaskObj == nil {
|
||||
return nil, nil, errors.New("ApprovalTask obj is nil")
|
||||
}
|
||||
|
||||
var insertedID uint64
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalTasks.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTaskObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
created, err := u.GetApprovalTaskByIDDB(ctx, insertedID)
|
||||
return created, tx, err
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskDB) UpdateApprovalTaskDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalTask obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTasks.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTask{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetApprovalTasksListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskDB) DeleteApprovalTaskDB(ctx context.Context, params *typescore.ApprovalTask) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalTasks.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("ApprovalTask obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskDB) GetApprovalTaskByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error) {
|
||||
ApprovalTasks, _, err := u.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTask{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(ApprovalTasks) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return ApprovalTasks[0], nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskDB) GetTasksForReportDB(ctx context.Context, filter typescore.TaskReportFilter) ([]*typescore.ApprovalTask, error) {
|
||||
q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT t.*").
|
||||
From(dbcoretablenames.TableNameApprovalTasks.ToString() + " t").
|
||||
Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.id = t.approval_id").
|
||||
OrderBy("t.created_at DESC")
|
||||
|
||||
if !filter.AllAccess && filter.UserID != nil {
|
||||
subQ1 := buildApprovalIdSubquery("initiator", filter.UserID)
|
||||
subQ2 := buildApprovalIdSubquery("approver", filter.UserID)
|
||||
subQ3 := buildApprovalIdSubquery("observer", filter.UserID)
|
||||
subQ4 := buildApprovalIdSubquery("executor", filter.UserID)
|
||||
|
||||
s1, a1, _ := subQ1.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s2, a2, _ := subQ2.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s3, a3, _ := subQ3.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s4, a4, _ := subQ4.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
|
||||
unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4)
|
||||
allArgs := append(append(append(a1, a2...), a3...), a4...)
|
||||
|
||||
q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...))
|
||||
}
|
||||
|
||||
// Применяем фильтр по датам (по дате создания задачи)
|
||||
if filter.DateFrom != nil {
|
||||
q = q.Where(squirrel.GtOrEq{"t.created_at": filter.DateFrom})
|
||||
}
|
||||
if filter.DateTo != nil {
|
||||
// До конца дня
|
||||
endOfDay := filter.DateTo.Add(24*time.Hour - time.Second)
|
||||
q = q.Where(squirrel.LtOrEq{"t.created_at": endOfDay})
|
||||
}
|
||||
|
||||
sql, args, err := q.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.queryTasks(ctx, sql, args)
|
||||
}
|
||||
|
||||
// queryTasks — вспомогательная функция для выполнения запроса задач.
|
||||
func (u *ApprovalTaskDB) queryTasks(ctx context.Context, sql string, args []interface{}) ([]*typescore.ApprovalTask, error) {
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.ApprovalTask
|
||||
for rows.Next() {
|
||||
task := &typescore.ApprovalTask{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, task, nil); err != nil {
|
||||
logrus.Warn("queryTasks:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, task)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,210 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ApprovalTopicDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalTopicDB(pool *pgxpool.Pool) *ApprovalTopicDB {
|
||||
return &ApprovalTopicDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type ApprovalTopicDBI interface {
|
||||
GetApprovalTopicsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error)
|
||||
CreateApprovalTopicDB(ctx context.Context, tx pgx.Tx, ApprovalTopicObj *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error)
|
||||
UpdateApprovalTopicDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error)
|
||||
DeleteApprovalTopicDB(ctx context.Context, params *typescore.ApprovalTopic) error
|
||||
|
||||
GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error)
|
||||
GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicDB) GetApprovalTopicsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopic{}, dbcoretablenames.TableNameApprovalTopics.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopic](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopics.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopics.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ApprovalTopics []*typescore.ApprovalTopic
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
ApprovalTopic := &typescore.ApprovalTopic{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, ApprovalTopic, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalTopicsListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
ApprovalTopics = append(ApprovalTopics, ApprovalTopic)
|
||||
}
|
||||
|
||||
return ApprovalTopics, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicDB) CreateApprovalTopicDB(ctx context.Context, tx pgx.Tx, ApprovalTopicObj *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error) {
|
||||
if ApprovalTopicObj == nil {
|
||||
return nil, nil, errors.New("ApprovalTopic obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalTopics.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTopicObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
ApprovalTopic, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalTopicObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(ApprovalTopic) > 0 {
|
||||
return ApprovalTopic[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicDB) UpdateApprovalTopicDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalTopic obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTopics.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTopic{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetApprovalTopicsListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicDB) DeleteApprovalTopicDB(ctx context.Context, params *typescore.ApprovalTopic) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalTopics.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("approvalTopic obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicDB) GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error) {
|
||||
topics, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTopic{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(topics) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return topics[0], nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicDB) GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error) {
|
||||
topics, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTopic{Code: &code},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(topics) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return topics[0], nil
|
||||
}
|
||||
|
|
@ -0,0 +1,209 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ApprovalTopicCategoryDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalTopicCategoryDB(pool *pgxpool.Pool) *ApprovalTopicCategoryDB {
|
||||
return &ApprovalTopicCategoryDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type ApprovalTopicCategoryDBI interface {
|
||||
GetApprovalTopicCategoryListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicCategory, uint64, error)
|
||||
CreateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, ApprovalTopicCategoryObj *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error)
|
||||
UpdateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error)
|
||||
DeleteApprovalTopicCategoryDB(ctx context.Context, params *typescore.ApprovalTopicCategory) error
|
||||
GetApprovalTopicCategoryByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopicCategory, error)
|
||||
GetApprovalTopicCategoryByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopicCategory, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicCategory, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicCategory{}, dbcoretablenames.TableNameApprovalTopicCategories.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicCategory](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopicCategories.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicCategories.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ApprovalTopicCategorys []*typescore.ApprovalTopicCategory
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
ApprovalTopicCategory := &typescore.ApprovalTopicCategory{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, ApprovalTopicCategory, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalTopicCategorysListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
ApprovalTopicCategorys = append(ApprovalTopicCategorys, ApprovalTopicCategory)
|
||||
}
|
||||
|
||||
return ApprovalTopicCategorys, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicCategoryDB) CreateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, ApprovalTopicCategoryObj *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error) {
|
||||
if ApprovalTopicCategoryObj == nil {
|
||||
return nil, nil, errors.New("ApprovalTopicCategory obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalTopicCategories.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTopicCategoryObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
ApprovalTopicCategory, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalTopicCategoryObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(ApprovalTopicCategory) > 0 {
|
||||
return ApprovalTopicCategory[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicCategoryDB) UpdateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalTopicCategory obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTopicCategories.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTopicCategory{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetApprovalTopicCategoryListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicCategoryDB) DeleteApprovalTopicCategoryDB(ctx context.Context, params *typescore.ApprovalTopicCategory) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalTopicCategories.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("approvalTopicCategory obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopicCategory, error) {
|
||||
categories, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTopicCategory{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(categories) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return categories[0], nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopicCategory, error) {
|
||||
categories, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTopicCategory{Code: &code},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(categories) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return categories[0], nil
|
||||
}
|
||||
|
|
@ -0,0 +1,192 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type DepartmentDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewDepartmentDB(pool *pgxpool.Pool) *DepartmentDB {
|
||||
return &DepartmentDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type DepartmentDBI interface {
|
||||
GetDepartmentsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error)
|
||||
CreateDepartmentDB(ctx context.Context, tx pgx.Tx, DepartmentObj *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error)
|
||||
UpdateDepartmentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error)
|
||||
DeleteDepartmentDB(ctx context.Context, params *typescore.Department) error
|
||||
GetDepartmentByIDDB(ctx context.Context, id uint64) (*typescore.Department, error)
|
||||
}
|
||||
|
||||
func (u *DepartmentDB) GetDepartmentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Department{}, dbcoretablenames.TableNameDepartments.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.Department](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameDepartments.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameDepartments.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var Departments []*typescore.Department
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
Department := &typescore.Department{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, Department, &totalCount); err != nil {
|
||||
logrus.Warn("GetDepartmentsListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
Departments = append(Departments, Department)
|
||||
}
|
||||
|
||||
return Departments, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *DepartmentDB) CreateDepartmentDB(ctx context.Context, tx pgx.Tx, DepartmentObj *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error) {
|
||||
if DepartmentObj == nil {
|
||||
return nil, nil, errors.New("Department obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameDepartments.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, DepartmentObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
Department, _, err := u.GetDepartmentsListDB(ctx, typescore.ListDbOptions{Filtering: DepartmentObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(Department) > 0 {
|
||||
return Department[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *DepartmentDB) UpdateDepartmentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("Department obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameDepartments.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.Department{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetDepartmentsListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *DepartmentDB) DeleteDepartmentDB(ctx context.Context, params *typescore.Department) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameDepartments.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("department obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *DepartmentDB) GetDepartmentByIDDB(ctx context.Context, id uint64) (*typescore.Department, error) {
|
||||
deps, _, err := u.GetDepartmentsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Department{ID: &id},
|
||||
})
|
||||
if err != nil || len(deps) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
return deps[0], nil
|
||||
}
|
||||
|
|
@ -0,0 +1,221 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type PermissionDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewPermissionDB(pool *pgxpool.Pool) *PermissionDB {
|
||||
return &PermissionDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type PermissionDBI interface {
|
||||
GetPermissionsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Permission, uint64, error)
|
||||
CreatePermissionDB(ctx context.Context, tx pgx.Tx, PermissionObj *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error)
|
||||
UpdatePermissionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error)
|
||||
DeletePermissionDB(ctx context.Context, params *typescore.Permission) error
|
||||
GetUserPermissionsDB(ctx context.Context, userID uint64, action string) ([]*typescore.Permission, error)
|
||||
}
|
||||
|
||||
func (u *PermissionDB) GetPermissionsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Permission, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Permission{}, dbcoretablenames.TableNamePermissions.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.Permission](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNamePermissions.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNamePermissions.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var Permissions []*typescore.Permission
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
Permission := &typescore.Permission{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, Permission, &totalCount); err != nil {
|
||||
logrus.Warn("GetPermissionsListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
Permissions = append(Permissions, Permission)
|
||||
}
|
||||
|
||||
return Permissions, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *PermissionDB) CreatePermissionDB(ctx context.Context, tx pgx.Tx, PermissionObj *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error) {
|
||||
if PermissionObj == nil {
|
||||
return nil, nil, errors.New("Permission obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNamePermissions.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, PermissionObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
Permission, _, err := u.GetPermissionsListDB(ctx, typescore.ListDbOptions{Filtering: PermissionObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(Permission) > 0 {
|
||||
return Permission[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *PermissionDB) UpdatePermissionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("Permission obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNamePermissions.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.Permission{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetPermissionsListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *PermissionDB) DeletePermissionDB(ctx context.Context, params *typescore.Permission) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNamePermissions.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("permission obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserPermissionsDB возвращает все permissions для пользователя через его роли.
|
||||
// action — фильтр: create | approve | revoke | "" (все)
|
||||
func (u *PermissionDB) GetUserPermissionsDB(ctx context.Context, userID uint64, action string) ([]*typescore.Permission, error) {
|
||||
// Используем алиас "p" и в GetStructFieldsDB тоже
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Permission{}, "p")
|
||||
|
||||
q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNamePermissions.ToString() + " p").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.role_id = p.role_id").
|
||||
Where(squirrel.Eq{"ur.user_id": userID})
|
||||
|
||||
if action != "" {
|
||||
q = q.Where(squirrel.Eq{"p.action": action})
|
||||
}
|
||||
|
||||
sql, args, err := q.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var perms []*typescore.Permission
|
||||
for rows.Next() {
|
||||
p := &typescore.Permission{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, p, nil); err != nil {
|
||||
logrus.Warn("GetUserPermissionsDB:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
perms = append(perms, p)
|
||||
}
|
||||
return perms, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type RoleDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRoleDB(pool *pgxpool.Pool) *RoleDB {
|
||||
return &RoleDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type RoleDBI interface {
|
||||
GetRolesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error)
|
||||
CreateRoleDB(ctx context.Context, tx pgx.Tx, RoleObj *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error)
|
||||
UpdateRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error)
|
||||
DeleteRoleDB(ctx context.Context, params *typescore.Role) error
|
||||
}
|
||||
|
||||
func (u *RoleDB) GetRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Role{}, dbcoretablenames.TableNameRoles.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.Role](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameRoles.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameRoles.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var Roles []*typescore.Role
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
Role := &typescore.Role{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, Role, &totalCount); err != nil {
|
||||
logrus.Warn("GetRolesListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
Roles = append(Roles, Role)
|
||||
}
|
||||
|
||||
return Roles, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *RoleDB) CreateRoleDB(ctx context.Context, tx pgx.Tx, RoleObj *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error) {
|
||||
if RoleObj == nil {
|
||||
return nil, nil, errors.New("Role obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameRoles.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, RoleObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
Role, _, err := u.GetRolesListDB(ctx, typescore.ListDbOptions{Filtering: RoleObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(Role) > 0 {
|
||||
return Role[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *RoleDB) UpdateRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("Role obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameRoles.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.Role{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetRolesListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *RoleDB) DeleteRoleDB(ctx context.Context, params *typescore.Role) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameRoles.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("role obj is nil")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,359 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type UserDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserDB(pool *pgxpool.Pool) *UserDB {
|
||||
return &UserDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type UserDBI interface {
|
||||
GetUsersListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.User, uint64, error)
|
||||
CreateUserDB(ctx context.Context, tx pgx.Tx, UserObj *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error)
|
||||
UpdateUserDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error)
|
||||
DeleteUserDB(ctx context.Context, params *typescore.User) error
|
||||
|
||||
GetUserByTelegramIDDB(ctx context.Context, telegramID int64) (*typescore.User, error)
|
||||
GetUserByIDDB(ctx context.Context, id uint64) (*typescore.User, error)
|
||||
GetDirectorsDB(ctx context.Context) ([]*typescore.User, error)
|
||||
IsDirectorDB(ctx context.Context, userID uint64) (bool, error)
|
||||
IsApproverDB(ctx context.Context, userID uint64) (bool, error)
|
||||
IsExecutorDB(ctx context.Context, userID uint64) (bool, error)
|
||||
GetObserversForCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.User, error)
|
||||
}
|
||||
|
||||
func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.User](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUsers.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var Users []*typescore.User
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
User := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, User, &totalCount); err != nil {
|
||||
logrus.Warn("GetUsersListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
Users = append(Users, User)
|
||||
}
|
||||
|
||||
return Users, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *UserDB) CreateUserDB(ctx context.Context, tx pgx.Tx, UserObj *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error) {
|
||||
if UserObj == nil {
|
||||
return nil, nil, errors.New("user obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUsers.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, UserObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
User, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{Filtering: UserObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(User) > 0 {
|
||||
return User[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *UserDB) UpdateUserDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("user obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUsers.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.User{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetUsersListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *UserDB) DeleteUserDB(ctx context.Context, params *typescore.User) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameUsers.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("user obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UserDB) GetUserByTelegramIDDB(ctx context.Context, telegramID int64) (*typescore.User, error) {
|
||||
users, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.User{TelegramID: &telegramID},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(users) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return users[0], nil
|
||||
}
|
||||
|
||||
func (u *UserDB) GetUserByIDDB(ctx context.Context, id uint64) (*typescore.User, error) {
|
||||
users, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.User{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(users) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return users[0], nil
|
||||
}
|
||||
|
||||
// GetDirectorsDB возвращает всех пользователей у которых есть роль с is_director = true.
|
||||
func (u *UserDB) GetDirectorsDB(ctx context.Context) ([]*typescore.User, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT u.*").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Where(squirrel.Eq{"r.is_director": true}).
|
||||
Where(squirrel.Eq{"u.is_blocked": false}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil, nil); err != nil {
|
||||
logrus.Warn("GetDirectorsDB:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// IsDirectorDB проверяет наличие директорской роли у конкретного пользователя.
|
||||
func (u *UserDB) IsDirectorDB(ctx context.Context, userID uint64) (bool, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Where(squirrel.Eq{"ur.user_id": userID}).
|
||||
Where(squirrel.Eq{"r.is_director": true}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var count int
|
||||
if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// IsApproverDB проверяет есть ли у пользователя роль с is_approver = true
|
||||
func (u *UserDB) IsApproverDB(ctx context.Context, userID uint64) (bool, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Where(squirrel.Eq{"ur.user_id": userID}).
|
||||
Where(squirrel.Eq{"r.is_approver": true}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var count int
|
||||
if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (u *UserDB) IsObserverDB(ctx context.Context, userID uint64) (bool, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Where(squirrel.Eq{"ur.user_id": userID}).
|
||||
Where(squirrel.Eq{"r.is_observer": true}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var count int
|
||||
if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (u *UserDB) IsExecutorDB(ctx context.Context, userID uint64) (bool, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Where(squirrel.Eq{"ur.user_id": userID}).
|
||||
Where(squirrel.Eq{"r.is_executor": true}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var count int
|
||||
if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// GetObserversForCategoryDB — пользователи с ролью наблюдателя и правом observe на категорию.
|
||||
func (u *UserDB) GetObserversForCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.User, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT u.*").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.role_id = r.id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = p.topic_category_id").
|
||||
Where(squirrel.Eq{"r.is_observer": true}).
|
||||
Where(squirrel.Eq{"p.action": "observe"}).
|
||||
Where(squirrel.Eq{"c.code": categoryCode}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.User
|
||||
for rows.Next() {
|
||||
usr := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
|
||||
logrus.Warn("GetObserversForCategoryDB:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, usr)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,302 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type UserHierarchyDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserHierarchyDB(pool *pgxpool.Pool) *UserHierarchyDB {
|
||||
return &UserHierarchyDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type UserHierarchyDBI interface {
|
||||
GetUserHierarchyListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error)
|
||||
CreateUserHierarchyDB(ctx context.Context, tx pgx.Tx, UserHierarchyObj *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error)
|
||||
UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error)
|
||||
DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error
|
||||
|
||||
GetApproversDB(ctx context.Context, subordinateID uint64, departmentID uint64) ([]*typescore.User, error)
|
||||
GetExecutorDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) (*typescore.User, error)
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) GetUserHierarchyListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.UserHierarchy{}, dbcoretablenames.TableNameUserHierarchy.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUserHierarchy.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUserHierarchy.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var UserHierarchys []*typescore.UserHierarchy
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
UserHierarchy := &typescore.UserHierarchy{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, UserHierarchy, &totalCount); err != nil {
|
||||
logrus.Warn("GetUserHierarchysListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
UserHierarchys = append(UserHierarchys, UserHierarchy)
|
||||
}
|
||||
|
||||
return UserHierarchys, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) CreateUserHierarchyDB(ctx context.Context, tx pgx.Tx, UserHierarchyObj *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error) {
|
||||
if UserHierarchyObj == nil {
|
||||
return nil, nil, errors.New("UserHierarchy obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUserHierarchy.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, UserHierarchyObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
UserHierarchy, _, err := u.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{Filtering: UserHierarchyObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(UserHierarchy) > 0 {
|
||||
return UserHierarchy[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("UserHierarchy obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUserHierarchy.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.UserHierarchy{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetUserHierarchyListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameUserHierarchy.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("userHierarchy obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) GetApproversDB(
|
||||
ctx context.Context,
|
||||
subordinateID uint64,
|
||||
departmentID uint64,
|
||||
topicID uint64,
|
||||
topicCategoryID uint64,
|
||||
) ([]*typescore.User, error) {
|
||||
|
||||
// Ищем наиболее специфичное правило для этой тройки (subordinate, dept, тема).
|
||||
// Приоритет: topic_id > topic_category_id > общее правило (оба NULL).
|
||||
// Берём только правила одного уровня специфичности — наиболее точного.
|
||||
rawSQL := `
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
uh.approver_id,
|
||||
uh.priority,
|
||||
CASE
|
||||
WHEN uh.topic_id = $3 THEN 1
|
||||
WHEN uh.topic_category_id = $4 THEN 2
|
||||
WHEN uh.topic_id IS NULL
|
||||
AND uh.topic_category_id IS NULL THEN 3
|
||||
END AS specificity
|
||||
FROM user_hierarchy uh
|
||||
WHERE uh.subordinate_id = $1
|
||||
AND uh.department_id = $2
|
||||
AND (
|
||||
uh.topic_id = $3
|
||||
OR uh.topic_category_id = $4
|
||||
OR (uh.topic_id IS NULL AND uh.topic_category_id IS NULL)
|
||||
)
|
||||
),
|
||||
best AS (
|
||||
-- берём только уровень с наивысшей специфичностью
|
||||
SELECT MIN(specificity) AS min_spec FROM ranked
|
||||
)
|
||||
SELECT u.*
|
||||
FROM ranked r
|
||||
JOIN best b ON r.specificity = b.min_spec
|
||||
JOIN users u ON u.id = r.approver_id
|
||||
ORDER BY r.priority ASC
|
||||
`
|
||||
|
||||
rows, err := u.pool.Query(ctx, rawSQL,
|
||||
subordinateID,
|
||||
departmentID,
|
||||
topicID,
|
||||
topicCategoryID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.User
|
||||
for rows.Next() {
|
||||
usr := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
|
||||
logrus.Warn("GetApproversDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, usr)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) GetExecutorDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) (*typescore.User, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.User{}, "u")
|
||||
|
||||
queryUser := func(where squirrel.Sqlizer) (*typescore.User, error) {
|
||||
baseQuery := squirrel.Select(fields...).
|
||||
From(dbcoretablenames.TableNameUserHierarchy.ToString() + " uh").
|
||||
Join(dbcoretablenames.TableNameUsers.ToString() + " u ON u.id = uh.executor_id").
|
||||
Where(squirrel.Eq{"uh.subordinate_id": subordinateID}).
|
||||
Where(squirrel.Eq{"uh.department_id": departmentID}).
|
||||
Where(squirrel.Expr("uh.executor_id IS NOT NULL")).
|
||||
Where(where).
|
||||
Limit(1)
|
||||
|
||||
sql, args, err := baseQuery.PlaceholderFormat(squirrel.Dollar).ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logrus.Debugf("Generated SQL: %s, Args: %v", sql, args) // <-- добавь это
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if !rows.Next() {
|
||||
return nil, rows.Err()
|
||||
}
|
||||
|
||||
user := &typescore.User{}
|
||||
var totalCount uint64
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, &totalCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
if topicID > 0 {
|
||||
user, err := queryUser(squirrel.Eq{"uh.topic_id": topicID})
|
||||
if err == nil && user != nil {
|
||||
return user, nil
|
||||
}
|
||||
}
|
||||
|
||||
user, err := queryUser(squirrel.Eq{"uh.topic_category_id": categoryID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type UserRoleDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRoleDB(pool *pgxpool.Pool) *UserRoleDB {
|
||||
return &UserRoleDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type UserRoleDBI interface {
|
||||
GetUserRolesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error)
|
||||
CreateUserRoleDB(ctx context.Context, tx pgx.Tx, UserRoleObj *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error)
|
||||
UpdateUserRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error)
|
||||
DeleteUserRoleDB(ctx context.Context, params *typescore.UserRole) error
|
||||
}
|
||||
|
||||
func (u *UserRoleDB) GetUserRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.UserRole{}, dbcoretablenames.TableNameUserRoles.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.UserRole](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUserRoles.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUserRoles.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var UserRoles []*typescore.UserRole
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
UserRole := &typescore.UserRole{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, UserRole, &totalCount); err != nil {
|
||||
logrus.Warn("GetUserRolesListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
UserRoles = append(UserRoles, UserRole)
|
||||
}
|
||||
|
||||
return UserRoles, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *UserRoleDB) CreateUserRoleDB(ctx context.Context, tx pgx.Tx, UserRoleObj *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error) {
|
||||
if UserRoleObj == nil {
|
||||
return nil, nil, errors.New("UserRole obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUserRoles.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, UserRoleObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
UserRole, _, err := u.GetUserRolesListDB(ctx, typescore.ListDbOptions{Filtering: UserRoleObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
if len(UserRole) > 0 {
|
||||
return UserRole[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *UserRoleDB) UpdateUserRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("UserRole obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUserRoles.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.UserRole{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetUserRolesListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *UserRoleDB) DeleteUserRoleDB(ctx context.Context, params *typescore.UserRole) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameUserRoles.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("userRole obj is nil")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package dbcoretablenames
|
||||
|
||||
type TableName string
|
||||
|
||||
const (
|
||||
TableNameApprovals TableName = "approvals"
|
||||
TableNameApprovalSteps TableName = "approval_steps"
|
||||
TableNameApprovalTopics TableName = "approval_topics"
|
||||
TableNameApprovalTopicCategories TableName = "approval_topic_categories"
|
||||
TableNameDepartments TableName = "departments"
|
||||
TableNamePermissions TableName = "permissions"
|
||||
TableNameRoles TableName = "roles"
|
||||
TableNameUsers TableName = "users"
|
||||
TableNameUserHierarchy TableName = "user_hierarchy"
|
||||
TableNameUserRoles TableName = "user_roles"
|
||||
TableNameApprovalFiles TableName = "approval_files"
|
||||
TableNameApprovalDelegations TableName = "approval_delegations"
|
||||
TableNameApprovalAdditionalApprovers TableName = "approval_additional_approvers"
|
||||
TableNameApprovalTasks TableName = "approval_tasks"
|
||||
)
|
||||
|
||||
func (t TableName) ToString() string {
|
||||
return string(t)
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
module bitrix_balancer_api/core
|
||||
|
||||
go 1.25.6
|
||||
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/hashicorp/vault/api v1.22.0
|
||||
github.com/jackc/pgx/v5 v5.8.0
|
||||
github.com/mitchellh/mapstructure v1.5.0
|
||||
github.com/redis/go-redis/v9 v9.18.0
|
||||
github.com/shopspring/decimal v1.4.0
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.1 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
|
||||
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
|
||||
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect
|
||||
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
|
||||
github.com/hashicorp/go-sockaddr v1.0.7 // indirect
|
||||
github.com/hashicorp/hcl v1.0.1-vault-7 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/ryanuber/go-glob v1.0.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/crypto v0.40.0 // indirect
|
||||
golang.org/x/net v0.42.0 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
golang.org/x/time v0.12.0 // indirect
|
||||
)
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
|
||||
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI=
|
||||
github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA=
|
||||
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
|
||||
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
|
||||
github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
|
||||
github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
|
||||
github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
|
||||
github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
|
||||
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
|
||||
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=
|
||||
github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc=
|
||||
github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=
|
||||
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 h1:U+kC2dOhMFQctRfhK0gRctKAPTloZdMU5ZJxaesJ/VM=
|
||||
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0/go.mod h1:Ll013mhdmsVDuoIXVfBtvgGJsXDYkTw1kooNcoCXuE0=
|
||||
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 h1:kes8mmyCpxJsI7FTwtzRqEy9CdjCtrXrXGuOpxEA7Ts=
|
||||
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2/go.mod h1:Gou2R9+il93BqX25LAKCLuM+y9U2T4hlwvT1yprcna4=
|
||||
github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw=
|
||||
github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw=
|
||||
github.com/hashicorp/hcl v1.0.1-vault-7 h1:ag5OxFVy3QYTFTJODRzTKVZ6xvdfLLCA1cy/Y6xGI0I=
|
||||
github.com/hashicorp/hcl v1.0.1-vault-7/go.mod h1:XYhtn6ijBSAj6n4YqAaf7RBPS4I06AItNorpy+MoQNM=
|
||||
github.com/hashicorp/vault/api v1.22.0 h1:+HYFquE35/B74fHoIeXlZIP2YADVboaPjaSicHEZiH0=
|
||||
github.com/hashicorp/vault/api v1.22.0/go.mod h1:IUZA2cDvr4Ok3+NtK2Oq/r+lJeXkeCrHRmqdyWfpmGM=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
|
||||
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
|
||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
|
||||
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk=
|
||||
github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
||||
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
|
||||
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
|
||||
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
|
||||
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
|
||||
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
package gormmodule
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
type ConfigConnectGorm struct {
|
||||
Host string
|
||||
Port string
|
||||
User string
|
||||
Password string
|
||||
Name string
|
||||
SslMode string
|
||||
}
|
||||
|
||||
var (
|
||||
gormDB *gorm.DB
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func connectGormDB(configObj *ConfigConnectGorm) (*gorm.DB, error) {
|
||||
if configObj == nil {
|
||||
return nil, errors.New("connectGormDB: configObj is nil")
|
||||
}
|
||||
|
||||
log.Println("🚀 ConnectGormDB")
|
||||
sslMode := "disable"
|
||||
if configObj.SslMode != "" {
|
||||
sslMode = configObj.SslMode
|
||||
}
|
||||
|
||||
// Поддерживаем только disable и require
|
||||
if sslMode != "disable" && sslMode != "require" {
|
||||
return nil, errors.New("ConnectDB: unsupported sslmode, only 'disable' and 'require' are allowed")
|
||||
}
|
||||
|
||||
connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
|
||||
configObj.Host,
|
||||
configObj.Port,
|
||||
configObj.User,
|
||||
configObj.Password,
|
||||
configObj.Name,
|
||||
sslMode)
|
||||
|
||||
newLogger := logger.New(
|
||||
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
|
||||
logger.Config{
|
||||
SlowThreshold: time.Second, // медленный SQL порог
|
||||
LogLevel: logger.Silent, // уровень логирования
|
||||
IgnoreRecordNotFoundError: true, // игнорировать ошибки записи не найдены
|
||||
Colorful: false, // отключить цвет
|
||||
},
|
||||
)
|
||||
|
||||
db, err := gorm.Open(postgres.Open(connStr), &gorm.Config{
|
||||
Logger: newLogger,
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorf("🔴 error: %s: %+v", "connectGormDB-Open", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// Подключение к базе данных GORM с использованием Singleton
|
||||
func GormDatabaseConnect(configObj *ConfigConnectGorm) (*gorm.DB, *sql.DB, error) {
|
||||
logrus.Info("🚀 GormDatabaseConnect")
|
||||
if configObj == nil {
|
||||
return nil, nil, errors.New("configObj is nil")
|
||||
}
|
||||
|
||||
var err error
|
||||
once.Do(func() {
|
||||
gormDB, err = connectGormDB(configObj)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if gormDB == nil {
|
||||
return nil, nil, errors.New("failed to connect database: GormDB instance is nil")
|
||||
}
|
||||
|
||||
sqlDB, err := gormDB.DB()
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("failed to get DB from GORM")
|
||||
}
|
||||
|
||||
// SetMaxIdleConns устанавливает максимальное количество соединений в пуле простаивающих соединений.
|
||||
sqlDB.SetMaxIdleConns(2)
|
||||
|
||||
// SetMaxOpenConns устанавливает максимальное количество открытых соединений с базой данных.
|
||||
sqlDB.SetMaxOpenConns(10)
|
||||
|
||||
// SetConnMaxLifetime устанавливает максимальное время, в течение которого может быть повторно использовано соединение.
|
||||
sqlDB.SetConnMaxLifetime(5 * time.Minute)
|
||||
|
||||
gormDB.Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";")
|
||||
return gormDB, sqlDB, nil
|
||||
}
|
||||
|
||||
// Отключение от базы данных GORM
|
||||
func GormDatabaseDisconnect() error {
|
||||
if gormDB == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
sqlDB, err := gormDB.DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Закрываем все открытые соединения
|
||||
if err := sqlDB.Close(); err != nil {
|
||||
return errors.New(fmt.Sprintf("failed to close database connections: %v", err))
|
||||
}
|
||||
|
||||
// Очищаем пул соединений
|
||||
sqlDB.SetMaxIdleConns(0)
|
||||
sqlDB.SetMaxOpenConns(0)
|
||||
|
||||
// Обнуляем глобальную переменную
|
||||
gormDB = nil
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
package pgxpoolmodule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ConfigConnectPgxPool struct {
|
||||
Host string
|
||||
Port string
|
||||
User string
|
||||
Password string
|
||||
Name string
|
||||
SSLMode string
|
||||
}
|
||||
|
||||
var (
|
||||
pool *pgxpool.Pool
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func ConnectDB(configObj *ConfigConnectPgxPool) (*pgxpool.Pool, error) {
|
||||
var err error
|
||||
once.Do(func() {
|
||||
if configObj == nil {
|
||||
err = errors.New("ConnectDB: configObj is nil")
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("🚀 ConnectDB")
|
||||
sslMode := "disable"
|
||||
if configObj.SSLMode != "" {
|
||||
sslMode = configObj.SSLMode
|
||||
}
|
||||
|
||||
// Поддерживаем только disable и require
|
||||
if sslMode != "disable" && sslMode != "require" {
|
||||
err = errors.New("ConnectDB: unsupported sslmode, only 'disable' and 'require' are allowed")
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("🚀 sslMode: ", sslMode)
|
||||
connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s target_session_attrs=read-write",
|
||||
configObj.Host,
|
||||
configObj.Port,
|
||||
configObj.User,
|
||||
configObj.Password,
|
||||
configObj.Name,
|
||||
sslMode)
|
||||
|
||||
configDB, err := pgxpool.ParseConfig(connStr)
|
||||
if err != nil {
|
||||
err = errors.New("ConnectDB: failed to parse config: " + err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// настройки пула
|
||||
configDB.MaxConns = 2 // Максимальное количество открытых соединений в пуле
|
||||
configDB.MinConns = 1 // Минимальное количество открытых соединений, которое пул будет поддерживать
|
||||
configDB.MaxConnLifetime = time.Second * 45 // Максимальное время жизни соединения. После этого времени соединение будет закрыто
|
||||
configDB.MaxConnIdleTime = time.Second * 45 // Максимальное время простоя соединения. Если соединение не используется в течение этого времени, оно будет закрыто
|
||||
configDB.HealthCheckPeriod = time.Second * 15 // Периодичность проверки состояния соединений в пуле
|
||||
|
||||
pool, err = pgxpool.NewWithConfig(context.Background(), configDB)
|
||||
if err != nil {
|
||||
err = errors.New("ConnectDB: failed to connect to database: " + err.Error())
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if pool == nil {
|
||||
return nil, errors.New("ConnectDB: failed to connect to database: pool is nil")
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
package telegram
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type TgBotClient struct {
|
||||
bot *tgbotapi.BotAPI
|
||||
config *BotConfig
|
||||
}
|
||||
|
||||
var (
|
||||
onceTgBotClient sync.Once
|
||||
tgBotClientInstance *TgBotClient
|
||||
)
|
||||
|
||||
// NewTgBotClient создает новый экземпляр Client с заданным API ключом.
|
||||
func NewTgBotClient(config *BotConfig) (*TgBotClient, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New("failed to init TgBotClient: Api key is nil")
|
||||
}
|
||||
if config.BotKey == "" {
|
||||
return nil, errors.New("failed to init TgBotClient: Api key is nil")
|
||||
}
|
||||
|
||||
onceTgBotClient.Do(func() {
|
||||
bot, err := tgbotapi.NewBotAPI(config.BotKey)
|
||||
if err != nil {
|
||||
println(errors.New(fmt.Sprintf("🔴 error failed to setup telegram bot: %v", err)))
|
||||
return
|
||||
}
|
||||
|
||||
tgBotClientInstance = &TgBotClient{
|
||||
bot: bot,
|
||||
config: config,
|
||||
}
|
||||
|
||||
logrus.Info("✅ Telegram BOT API success connected")
|
||||
})
|
||||
|
||||
return tgBotClientInstance, nil
|
||||
}
|
||||
|
||||
func (client *TgBotClient) GetBot() *tgbotapi.BotAPI {
|
||||
return client.bot
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package telegram
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// SendMessageToTelegramBot отправляет сообщение в указанный чат.
|
||||
func (client *TgBotClient) SendMessageToTelegramBot(title, text *string, ChatID *int64, photoReader io.ReadCloser, buttonText, buttonURL *string) error {
|
||||
if text == nil || ChatID == nil || title == nil {
|
||||
logrus.Error("🔴 error SendMessageToTelegramBot: invalid parameter")
|
||||
return errors.New("invalid parameter")
|
||||
}
|
||||
|
||||
var markup *tgbotapi.InlineKeyboardMarkup
|
||||
if buttonText != nil && *buttonText != "" && buttonURL != nil {
|
||||
button := tgbotapi.NewInlineKeyboardButtonURL(*buttonText, *buttonURL)
|
||||
row := tgbotapi.NewInlineKeyboardRow(button)
|
||||
markup = &tgbotapi.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{row},
|
||||
}
|
||||
}
|
||||
|
||||
if photoReader != nil {
|
||||
photoMsg := tgbotapi.NewPhoto(*ChatID, tgbotapi.FileReader{
|
||||
Name: "photo",
|
||||
Reader: photoReader,
|
||||
})
|
||||
photoMsg.Caption = fmt.Sprintf("<b>%s</b>\n\n%s", *title, *text)
|
||||
photoMsg.ParseMode = "HTML"
|
||||
if markup != nil {
|
||||
photoMsg.ReplyMarkup = markup
|
||||
}
|
||||
|
||||
if _, err := client.bot.Send(photoMsg); err != nil {
|
||||
logrus.Error("🔴 error SendMessageToTelegramBot: Failed to send photo with message", err)
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
msg := tgbotapi.NewMessage(*ChatID, fmt.Sprintf("<b>%s</b>\n\n%s", *title, *text))
|
||||
msg.ParseMode = "HTML"
|
||||
if markup != nil {
|
||||
msg.ReplyMarkup = markup
|
||||
}
|
||||
|
||||
if _, err := client.bot.Send(msg); err != nil {
|
||||
logrus.Error("🔴 error SendMessageToTelegramBot: Failed to send message", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// apiResponse описывает ответ API Telegram
|
||||
type apiResponse struct {
|
||||
Ok bool `json:"ok"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
}
|
||||
|
||||
// sendRequest отправляет запрос к API Telegram и возвращает ответ
|
||||
func (client *TgBotClient) sendRequest(method string, requestBody interface{}) (*apiResponse, error) {
|
||||
var reqBody []byte
|
||||
var err error
|
||||
if requestBody != nil {
|
||||
reqBody, err = json.Marshal(requestBody)
|
||||
if err != nil {
|
||||
return nil, errors.New(fmt.Sprintf("marshaling request body: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("https://api.telegram.org/bot%s/%s", client.config.BotKey, method), bytes.NewReader(reqBody))
|
||||
if err != nil {
|
||||
return nil, errors.New(fmt.Sprintf("creating request: %v", err))
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Telegram-Bot-Api-Secret-Token", client.config.BotKey)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, errors.New(fmt.Sprintf("sending request error: %v", err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
println(errors.New(fmt.Sprintf("🔴 error reading response body: %v", err)))
|
||||
} else {
|
||||
bodyString := string(bodyBytes)
|
||||
println(errors.New(fmt.Sprintf("🔴 unexpected status body: %v", bodyString)))
|
||||
}
|
||||
|
||||
return nil, errors.New(fmt.Sprintf("unexpected status code: %d", resp.StatusCode))
|
||||
}
|
||||
|
||||
var apiResponse apiResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
|
||||
return nil, errors.New(fmt.Sprintf("decoding response: %v", err))
|
||||
}
|
||||
|
||||
return &apiResponse, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package telegram
|
||||
|
||||
import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
|
||||
type BotConfig struct {
|
||||
BotKey string
|
||||
ApiURL string
|
||||
}
|
||||
|
||||
type InvoiceRequestAmount struct {
|
||||
Amount *int `json:"amount"`
|
||||
}
|
||||
|
||||
type InvoiceLink struct {
|
||||
Link *string `json:"link"`
|
||||
}
|
||||
|
||||
type InvoiceRequest struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Payload string `json:"payload"`
|
||||
Currency string `json:"currency"`
|
||||
Prices []tgbotapi.LabeledPrice `json:"prices"`
|
||||
SubscriptionPeriod *int `json:"subscription_period"` //The currency must be set to “XTR” (Telegram Stars) if the parameter is used. Currently, it must always be 2592000 (30 days) if specified.
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
package clientcontrollers
|
||||
|
||||
import (
|
||||
configcore "bitrix_balancer_api/core/config"
|
||||
database "bitrix_balancer_api/core/db"
|
||||
redismodule "bitrix_balancer_api/core/lib/internally/redis"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type ClientsExternal struct {
|
||||
Config *configcore.Config
|
||||
Redis *redismodule.ModuleRedis
|
||||
DB *database.ModuleDB
|
||||
}
|
||||
|
||||
func ReturnClientsExternal(cfgOptions *configcore.ConfigLoadOptions) (ClientsExternal, error) {
|
||||
clientsExternal := ClientsExternal{}
|
||||
if cfgOptions == nil {
|
||||
cfgOptions = &configcore.ConfigLoadOptions{}
|
||||
return clientsExternal, errors.New("cfgOptions is nil")
|
||||
}
|
||||
cfg, err := configcore.LoadConfig(cfgOptions)
|
||||
if err != nil {
|
||||
return clientsExternal, errors.New(fmt.Sprintf("failed to load config file: %v", err))
|
||||
}
|
||||
|
||||
clientsExternal.Config = cfg
|
||||
|
||||
if cfgOptions.Redis {
|
||||
redisClient, err = getRedisClient(cfg)
|
||||
if err != nil {
|
||||
return clientsExternal, errors.New(fmt.Sprintf("failed to get redis client: %v", err))
|
||||
}
|
||||
clientsExternal.Redis = redisClient
|
||||
}
|
||||
|
||||
if cfgOptions.Database {
|
||||
dbClient, err = getDbClient(cfg)
|
||||
if err != nil {
|
||||
return clientsExternal, errors.New(fmt.Sprintf("failed to get db client: %v", err))
|
||||
}
|
||||
clientsExternal.DB = dbClient
|
||||
}
|
||||
|
||||
return clientsExternal, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package clientcontrollers
|
||||
|
||||
import (
|
||||
configcore "bitrix_balancer_api/core/config"
|
||||
database "bitrix_balancer_api/core/db"
|
||||
pgxpoolmodule "bitrix_balancer_api/core/lib/external/pgxpool"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
dbOnce sync.Once
|
||||
dbClient *database.ModuleDB
|
||||
)
|
||||
|
||||
func getDbClient(cfg *configcore.Config) (*database.ModuleDB, error) {
|
||||
var err error
|
||||
|
||||
if redisClient == nil {
|
||||
cfg0, err := configcore.LoadConfig(&configcore.ConfigLoadOptions{
|
||||
Redis: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
redisClient, err = getRedisClient(cfg0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
dbOnce.Do(func() {
|
||||
var initErr error
|
||||
dbClient, initErr = database.NewModuleDB(&pgxpoolmodule.ConfigConnectPgxPool{
|
||||
Host: cfg.Database.Host,
|
||||
Port: fmt.Sprintf("%d", cfg.Database.Port),
|
||||
User: cfg.Database.User,
|
||||
Password: cfg.Database.Password,
|
||||
Name: cfg.Database.DB,
|
||||
SSLMode: cfg.Database.SSL,
|
||||
}, redisClient)
|
||||
if initErr != nil {
|
||||
err = initErr
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
return dbClient, err
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
package clientcontrollers
|
||||
|
||||
import (
|
||||
configcore "bitrix_balancer_api/core/config"
|
||||
redismodule "bitrix_balancer_api/core/lib/internally/redis"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
redisOnce sync.Once
|
||||
|
||||
redisClient *redismodule.ModuleRedis
|
||||
)
|
||||
|
||||
func getRedisClient(cfg *configcore.Config) (*redismodule.ModuleRedis, error) {
|
||||
var err error
|
||||
|
||||
redisOnce.Do(func() {
|
||||
redisClient = redismodule.GetRedisModuleInstance(&redismodule.RedisConfig{
|
||||
Host: cfg.Redis.Host,
|
||||
Port: fmt.Sprintf("%d", cfg.Redis.Port),
|
||||
User: cfg.Redis.User,
|
||||
Password: cfg.Redis.Password,
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorln("🔴 failed to get Redis client: ", err)
|
||||
}
|
||||
})
|
||||
|
||||
return redisClient, err
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package cfgldrlib
|
||||
|
||||
import "errors"
|
||||
|
||||
func LoadConfig[T any](params *ConfigLoaders) (*T, error) {
|
||||
err := validateParams(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
configProvider, err := loadConfigProvider(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if configProvider == ConfigProviderYml {
|
||||
return loadConfigFromYml[T](params.ConfigYml)
|
||||
} else if configProvider == ConfigProviderVault {
|
||||
return loadConfigFromVault[T](params.VaultParams)
|
||||
}
|
||||
|
||||
return nil, errors.New("config error detected")
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package cfgldrlib
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func loadConfigFromYml[T any](configYML *string) (*T, error) {
|
||||
readerConfig := strings.NewReader(*configYML)
|
||||
decoder := yaml.NewDecoder(readerConfig)
|
||||
|
||||
var config T
|
||||
if err := decoder.Decode(&config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
func loadConfigFromVault[T any](vaultParams *VaultParamsT) (*T, error) {
|
||||
var config T
|
||||
err := fillStructFromVault(&config, vaultParams.VaultClient, *vaultParams.KvName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,290 @@
|
|||
package cfgldrlib
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/vault/api"
|
||||
)
|
||||
|
||||
func buildDataVaultPath(basePath string) (string, error) {
|
||||
if basePath == "" {
|
||||
return "", fmt.Errorf("basePath is empty")
|
||||
}
|
||||
|
||||
slashIndex := strings.Index(basePath, "/")
|
||||
if slashIndex == -1 {
|
||||
return basePath + "/data", nil
|
||||
}
|
||||
|
||||
return basePath[:slashIndex+1] + "data" + basePath[slashIndex:], nil
|
||||
}
|
||||
|
||||
func getVaultValue(client *api.Client, vaultPath, key string) (any, error) {
|
||||
|
||||
secret, err := client.Logical().Read(vaultPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if secret == nil || secret.Data == nil {
|
||||
return nil, fmt.Errorf("vault: secret not found at path %s", vaultPath)
|
||||
}
|
||||
|
||||
data, ok := secret.Data["data"].(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("vault: failed to get data from secret %s", vaultPath)
|
||||
}
|
||||
|
||||
if key == "" {
|
||||
return data, nil
|
||||
}
|
||||
val, ok := data[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("vault: key %s not found in secret %s", key, vaultPath)
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
|
||||
func fillStructFromVault(v any, client *api.Client, basePath string) error {
|
||||
val := reflect.ValueOf(v)
|
||||
if val.Kind() != reflect.Ptr || val.IsNil() {
|
||||
return fmt.Errorf("expected pointer to struct, got %T", v)
|
||||
}
|
||||
val = val.Elem()
|
||||
typ := val.Type()
|
||||
if typ.Kind() != reflect.Struct {
|
||||
return fmt.Errorf("expected struct, got %T", v)
|
||||
}
|
||||
|
||||
for _, field := range reflect.VisibleFields(typ) {
|
||||
fieldVal := val.FieldByName(field.Name)
|
||||
cfgldrTag := field.Tag.Get(TagName)
|
||||
if cfgldrTag == "-" {
|
||||
continue
|
||||
}
|
||||
vaultKey := field.Name
|
||||
if cfgldrTag != "" {
|
||||
for part := range strings.SplitSeq(cfgldrTag, ",") {
|
||||
if v, ok := strings.CutPrefix(part, ValTagParam); ok {
|
||||
vaultKey = v
|
||||
}
|
||||
}
|
||||
}
|
||||
if fieldVal.Kind() == reflect.Struct {
|
||||
nextPath := vaultKey
|
||||
if basePath != "" {
|
||||
nextPath = basePath + "/" + vaultKey
|
||||
}
|
||||
err := fillStructFromVault(fieldVal.Addr().Interface(), client, nextPath)
|
||||
if err != nil {
|
||||
fmt.Printf("⚠️ Error processing nested struct at path %s: %v\n", nextPath, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
vaultPath, err := buildDataVaultPath(basePath)
|
||||
if err != nil {
|
||||
fmt.Printf("⚠️ Error building vault path: %s, %v\n", basePath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
valFromVault, err := getVaultValue(client, vaultPath, vaultKey)
|
||||
if err != nil {
|
||||
fmt.Printf("⚠️ Value not found for key: %s (field: %s) — %v\n", basePath, vaultKey, err)
|
||||
continue
|
||||
}
|
||||
if fieldVal.CanSet() {
|
||||
err = setValue(fieldVal, valFromVault)
|
||||
if err != nil {
|
||||
fmt.Printf("⚠️ Failed to set value for %s (field: %s): %v\n", basePath, vaultKey, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setValue(fieldVal reflect.Value, val any) error {
|
||||
switch fieldVal.Kind() {
|
||||
case reflect.String:
|
||||
str, ok := val.(string)
|
||||
if !ok {
|
||||
str = fmt.Sprintf("%v", val)
|
||||
}
|
||||
fieldVal.SetString(str)
|
||||
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
|
||||
var intVal int64
|
||||
switch v := val.(type) {
|
||||
case int:
|
||||
intVal = int64(v)
|
||||
case int64:
|
||||
intVal = v
|
||||
case float64:
|
||||
intVal = int64(v)
|
||||
case string:
|
||||
var err error
|
||||
intVal, err = parseStringToInt64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
str := fmt.Sprintf("%v", v)
|
||||
var err error
|
||||
intVal, err = parseStringToInt64(str)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fieldVal.SetInt(intVal)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
var floatVal float64
|
||||
switch v := val.(type) {
|
||||
case float64:
|
||||
floatVal = v
|
||||
case float32:
|
||||
floatVal = float64(v)
|
||||
case int:
|
||||
floatVal = float64(v)
|
||||
case int64:
|
||||
floatVal = float64(v)
|
||||
case string:
|
||||
var err error
|
||||
floatVal, err = parseStringToFloat64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
str := fmt.Sprintf("%v", v)
|
||||
var err error
|
||||
floatVal, err = parseStringToFloat64(str)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fieldVal.SetFloat(floatVal)
|
||||
case reflect.Bool:
|
||||
var boolVal bool
|
||||
switch v := val.(type) {
|
||||
case bool:
|
||||
boolVal = v
|
||||
case string:
|
||||
var err error
|
||||
boolVal, err = parseStringToBool(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
str := fmt.Sprintf("%v", v)
|
||||
var err error
|
||||
boolVal, err = parseStringToBool(str)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fieldVal.SetBool(boolVal)
|
||||
case reflect.Slice:
|
||||
return setSliceValue(fieldVal, val)
|
||||
default:
|
||||
return fmt.Errorf("unsupported field type: %s", fieldVal.Kind())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setSliceValue(fieldVal reflect.Value, val any) error {
|
||||
elemType := fieldVal.Type().Elem()
|
||||
|
||||
if slice, ok := val.([]any); ok {
|
||||
result := reflect.MakeSlice(fieldVal.Type(), len(slice), len(slice))
|
||||
|
||||
for i, item := range slice {
|
||||
elem := reflect.New(elemType).Elem()
|
||||
|
||||
err := setValue(elem, item)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to set slice element %d: %v", i, err)
|
||||
}
|
||||
|
||||
result.Index(i).Set(elem)
|
||||
}
|
||||
|
||||
fieldVal.Set(result)
|
||||
return nil
|
||||
}
|
||||
|
||||
if str, ok := val.(string); ok {
|
||||
if strings.HasPrefix(strings.TrimSpace(str), "[") && strings.HasSuffix(strings.TrimSpace(str), "]") {
|
||||
if elemType.Kind() == reflect.String {
|
||||
content := strings.TrimSpace(str[1 : len(str)-1])
|
||||
if content == "" {
|
||||
fieldVal.Set(reflect.MakeSlice(fieldVal.Type(), 0, 0))
|
||||
return nil
|
||||
}
|
||||
|
||||
items := strings.Split(content, ",")
|
||||
result := reflect.MakeSlice(fieldVal.Type(), len(items), len(items))
|
||||
|
||||
for i, item := range items {
|
||||
cleanItem := strings.Trim(strings.TrimSpace(item), `"'`)
|
||||
result.Index(i).SetString(cleanItem)
|
||||
}
|
||||
|
||||
fieldVal.Set(result)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if elemType.Kind() == reflect.String {
|
||||
items := strings.Split(str, ",")
|
||||
result := reflect.MakeSlice(fieldVal.Type(), len(items), len(items))
|
||||
|
||||
for i, item := range items {
|
||||
cleanItem := strings.TrimSpace(item)
|
||||
result.Index(i).SetString(cleanItem)
|
||||
}
|
||||
|
||||
fieldVal.Set(result)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
elem := reflect.New(elemType).Elem()
|
||||
err := setValue(elem, val)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to set single element in slice: %v", err)
|
||||
}
|
||||
|
||||
result := reflect.MakeSlice(fieldVal.Type(), 1, 1)
|
||||
result.Index(0).Set(elem)
|
||||
fieldVal.Set(result)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseStringToInt64(s string) (int64, error) {
|
||||
var i int64
|
||||
_, err := fmt.Sscanf(s, "%d", &i)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse int from string: %s", s)
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
|
||||
func parseStringToFloat64(s string) (float64, error) {
|
||||
var f float64
|
||||
_, err := fmt.Sscanf(s, "%f", &f)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse float from string: %s", s)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func parseStringToBool(s string) (bool, error) {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
if s == "true" || s == "1" {
|
||||
return true, nil
|
||||
}
|
||||
if s == "false" || s == "0" {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("failed to parse bool from string: %s", s)
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package cfgldrlib
|
||||
|
||||
import (
|
||||
"github.com/hashicorp/vault/api"
|
||||
)
|
||||
|
||||
const TagName = "cfgldr"
|
||||
const ValTagParam = "val="
|
||||
|
||||
type ConfigProvider string
|
||||
|
||||
const (
|
||||
ConfigProviderYml ConfigProvider = "yml"
|
||||
ConfigProviderVault ConfigProvider = "vault"
|
||||
)
|
||||
|
||||
type ConfigLoaders struct {
|
||||
ConfigYml *string
|
||||
ConfigProvider *ConfigProvider
|
||||
VaultParams *VaultParamsT
|
||||
}
|
||||
|
||||
type VaultParamsT struct {
|
||||
KvName *string
|
||||
VaultClient *api.Client
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package cfgldrlib
|
||||
|
||||
import "errors"
|
||||
|
||||
func validateParams(params *ConfigLoaders) error {
|
||||
if params == nil {
|
||||
return errors.New("params is nil")
|
||||
}
|
||||
if params.ConfigYml == nil && params.VaultParams == nil {
|
||||
return errors.New("config yml or vault client is nil")
|
||||
}
|
||||
|
||||
// Проверяем VaultParams только если они предоставлены
|
||||
if params.VaultParams != nil {
|
||||
if params.VaultParams.KvName == nil {
|
||||
return errors.New("vault kv name is nil")
|
||||
}
|
||||
if params.VaultParams.VaultClient == nil {
|
||||
return errors.New("vault client is nil")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadConfigProvider(params *ConfigLoaders) (ConfigProvider, error) {
|
||||
if params.ConfigProvider != nil {
|
||||
return *params.ConfigProvider, nil
|
||||
}
|
||||
|
||||
if params.ConfigYml != nil {
|
||||
return ConfigProviderYml, nil
|
||||
}
|
||||
|
||||
if params.VaultParams != nil && params.VaultParams.VaultClient != nil {
|
||||
return ConfigProviderVault, nil
|
||||
}
|
||||
|
||||
return "", errors.New("config provider error detected")
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package internalservices
|
||||
|
||||
import redismodule "bitrix_balancer_api/core/lib/internally/redis"
|
||||
|
||||
func InitRedisModule(redisConfigObj *redismodule.RedisConfig) *redismodule.ModuleRedis {
|
||||
return redismodule.GetRedisModuleInstance(redisConfigObj)
|
||||
}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
package redismodule
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
onceRedisModule sync.Once
|
||||
redisModuleInstance *ModuleRedis
|
||||
)
|
||||
|
||||
type ModuleRedis struct {
|
||||
RedisConfig *RedisConfig
|
||||
RedisClient *redis.Client
|
||||
}
|
||||
|
||||
func GetRedisModuleInstance(redisConfigObj *RedisConfig) *ModuleRedis {
|
||||
onceRedisModule.Do(func() {
|
||||
redisClient := CreateRedisClient(redisConfigObj, 0)
|
||||
redisModuleInstance = &ModuleRedis{
|
||||
RedisConfig: redisConfigObj,
|
||||
RedisClient: redisClient,
|
||||
}
|
||||
})
|
||||
return redisModuleInstance
|
||||
}
|
||||
|
||||
func CreateRedisClient(redisConfigObj *RedisConfig, redisNDb int) *redis.Client {
|
||||
redisHost := os.Getenv("REDISHOST")
|
||||
redisPort := os.Getenv("REDISPORT")
|
||||
redisUser := ""
|
||||
redisPassword := ""
|
||||
redisConnectURI := ""
|
||||
|
||||
if redisHost == "" || redisPort == "" {
|
||||
redisHost = redisConfigObj.Host
|
||||
redisPort = redisConfigObj.Port
|
||||
}
|
||||
if redisConfigObj.User != "" {
|
||||
redisUser = redisConfigObj.User
|
||||
}
|
||||
if redisConfigObj.Password != "" {
|
||||
redisPassword = redisConfigObj.Password
|
||||
} else {
|
||||
if redisConfigObj.ConnectURI != "" {
|
||||
redisConnectURI = redisConfigObj.ConnectURI
|
||||
} else {
|
||||
redisConnectURI = fmt.Sprintf("%s:%s", redisHost, redisPort)
|
||||
}
|
||||
}
|
||||
|
||||
var opts *redis.Options
|
||||
if redisConnectURI != "" {
|
||||
opts = &redis.Options{
|
||||
Addr: redisConnectURI,
|
||||
Username: redisUser,
|
||||
Password: redisPassword,
|
||||
DB: redisNDb,
|
||||
}
|
||||
} else { // Обычное подключение
|
||||
opts = &redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%s", redisHost, redisPort),
|
||||
Username: redisUser,
|
||||
Password: redisPassword,
|
||||
DB: redisNDb,
|
||||
DialTimeout: 10 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
PoolSize: 20,
|
||||
PoolTimeout: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
return redis.NewClient(opts)
|
||||
}
|
||||
|
||||
func (m *ModuleRedis) GetClient() *redis.Client {
|
||||
return m.RedisClient
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
package redismodule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Проверка и удаление временных данных данных из Redis
|
||||
func (m *ModuleRedis) CheckAndDeleteFromRedis(userIdent, expectedValue, identType string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
userIdentCustom := fmt.Sprintf("%s:%s", identType, userIdent)
|
||||
|
||||
result, err := m.RedisClient.Get(ctx, userIdentCustom).Result()
|
||||
if err == redis.Nil {
|
||||
logrus.Error("🛑 error CheckAndDeleteFromRedis 1: ", err)
|
||||
return errors.New("not_found")
|
||||
} else if err != nil {
|
||||
logrus.Error("🛑 error CheckAndDeleteFromRedis 0: ", err)
|
||||
return errors.New("not_found")
|
||||
}
|
||||
|
||||
if result != expectedValue {
|
||||
return errors.New("invalid_code")
|
||||
}
|
||||
|
||||
_, err = m.RedisClient.Del(ctx, userIdentCustom).Result()
|
||||
if err != nil {
|
||||
logrus.Error("🛑 error CheckAndDeleteFromRedis: ", err)
|
||||
return errors.New("not_found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package redismodule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Set сохраняет значение по ключу с TTL. ttl=0 — без истечения.
|
||||
func (m *ModuleRedis) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error {
|
||||
return m.RedisClient.Set(ctx, key, value, ttl).Err()
|
||||
}
|
||||
|
||||
// Get возвращает значение по ключу. Если ключ не найден — возвращает redis.Nil.
|
||||
func (m *ModuleRedis) Get(ctx context.Context, key string) (string, error) {
|
||||
result, err := m.RedisClient.Get(ctx, key).Result()
|
||||
if err == redis.Nil {
|
||||
return "", err // пробрасываем redis.Nil как есть — caller сам решает
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Del удаляет ключ. Не возвращает ошибку если ключа нет.
|
||||
func (m *ModuleRedis) Del(ctx context.Context, key string) error {
|
||||
return m.RedisClient.Del(ctx, key).Err()
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
package redismodule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (m *ModuleRedis) GetRedisMemoryUsage() (*RedisMemoryInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
result, err := m.RedisClient.Info(ctx, "memory").Result()
|
||||
if err != nil {
|
||||
logrus.Error("🛑 error GetRedisMemoryUsage: ", err)
|
||||
return nil, errors.New("not_found")
|
||||
}
|
||||
|
||||
lines := strings.Split(result, "\n")
|
||||
info := &RedisMemoryInfo{}
|
||||
v := reflect.ValueOf(info).Elem()
|
||||
|
||||
for _, line := range lines {
|
||||
parts := strings.Split(line, ":")
|
||||
if len(parts) != 2 {
|
||||
logrus.Error("🛑 error GetRedisMemoryUsage: invalid line")
|
||||
continue
|
||||
}
|
||||
|
||||
fieldName := strings.ReplaceAll(parts[0], "-", "")
|
||||
field := v.FieldByName(fieldName)
|
||||
if field.IsValid() && field.CanSet() && field.Kind() == reflect.String {
|
||||
field.SetString(parts[1])
|
||||
}
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
package redismodule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Параметры Leaky Bucket из документации Bitrix24
|
||||
// Non-enterprise: X=50, Y=2/sec
|
||||
// Enterprise: X=250, Y=5/sec
|
||||
const (
|
||||
QuotaLimitDefault = int64(50) // порог до блокировки (X)
|
||||
QuotaDecreaseDefault = int64(2) // декремент в секунду (Y)
|
||||
QuotaLimitEnterprise = int64(250)
|
||||
QuotaDecreaseEnterprise = int64(5)
|
||||
)
|
||||
|
||||
// QuotaKey — ключ счётчика в Redis для конкретного портала
|
||||
func QuotaKey(portalID string) string {
|
||||
return fmt.Sprintf("bitrix_quota:%s", portalID)
|
||||
}
|
||||
|
||||
// GetQuotaCounter возвращает текущее значение счётчика квоты
|
||||
func (m *ModuleRedis) GetQuotaCounter(ctx context.Context, portalID string) (int64, error) {
|
||||
val, err := m.RedisClient.Get(ctx, QuotaKey(portalID)).Int64()
|
||||
if err == redis.Nil {
|
||||
return 0, nil // ключа нет — счётчик нулевой
|
||||
}
|
||||
return val, err
|
||||
}
|
||||
|
||||
// GetFreeQuota возвращает сколько запросов ещё можно отправить до блокировки
|
||||
func (m *ModuleRedis) GetFreeQuota(ctx context.Context, portalID string, limit int64) (int64, error) {
|
||||
counter, err := m.GetQuotaCounter(ctx, portalID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
free := limit - counter
|
||||
if free < 0 {
|
||||
free = 0
|
||||
}
|
||||
return free, nil
|
||||
}
|
||||
|
||||
// TryAcquireQuota атомарно проверяет и инкрементит счётчик.
|
||||
// Возвращает true если запрос разрешён, false если квота исчерпана.
|
||||
func (m *ModuleRedis) TryAcquireQuota(ctx context.Context, portalID string, limit int64) (bool, error) {
|
||||
key := QuotaKey(portalID)
|
||||
|
||||
// Lua-скрипт: атомарно читаем, сравниваем и инкрементим
|
||||
// Возвращает новое значение счётчика или -1 если квота исчерпана
|
||||
script := redis.NewScript(`
|
||||
local current = redis.call('GET', KEYS[1])
|
||||
if current == false then current = 0 else current = tonumber(current) end
|
||||
if current >= tonumber(ARGV[1]) then
|
||||
return -1
|
||||
end
|
||||
local new = redis.call('INCR', KEYS[1])
|
||||
-- TTL 60 секунд — страховка от зависшего счётчика
|
||||
redis.call('EXPIRE', KEYS[1], 60)
|
||||
return new
|
||||
`)
|
||||
|
||||
result, err := script.Run(ctx, m.RedisClient, []string{key}, limit).Int64()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return result != -1, nil
|
||||
}
|
||||
|
||||
// DecrementQuota уменьшает счётчик на delta (вызывается background-job каждую секунду)
|
||||
func (m *ModuleRedis) DecrementQuota(ctx context.Context, portalID string, delta int64) error {
|
||||
key := QuotaKey(portalID)
|
||||
|
||||
script := redis.NewScript(`
|
||||
local current = redis.call('GET', KEYS[1])
|
||||
if current == false then return 0 end
|
||||
local new = tonumber(current) - tonumber(ARGV[1])
|
||||
if new <= 0 then
|
||||
redis.call('DEL', KEYS[1])
|
||||
return 0
|
||||
end
|
||||
redis.call('SET', KEYS[1], new)
|
||||
return new
|
||||
`)
|
||||
|
||||
return script.Run(ctx, m.RedisClient, []string{key}, delta).Err()
|
||||
}
|
||||
|
||||
// StartQuotaLeaker запускает background-job который освобождает квоту
|
||||
// согласно алгоритму Leaky Bucket из документации Bitrix24.
|
||||
// Вызывать один раз при старте сервера в горутине.
|
||||
func (m *ModuleRedis) StartQuotaLeaker(portalID string, decreasePerSec int64) {
|
||||
ticker := time.NewTicker(1 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
logrus.Infof("🪣 QuotaLeaker started for portal %s (-%d/sec)", portalID, decreasePerSec)
|
||||
|
||||
for range ticker.C {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
if err := m.DecrementQuota(ctx, portalID, decreasePerSec); err != nil {
|
||||
logrus.Errorf("🛑 QuotaLeaker: DecrementQuota: %v", err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package redismodule
|
||||
|
||||
type RedisConfig struct {
|
||||
Host string
|
||||
Port string
|
||||
User string
|
||||
Password string
|
||||
ConnectURI string
|
||||
}
|
||||
|
||||
type RedisMemoryInfo struct {
|
||||
UsedMemory string // Общее количество байтов, выделенных Redis
|
||||
UsedMemoryHuman string // Человеко-читаемое представление UsedMemory
|
||||
UsedMemoryRss string // Количество памяти, которое Redis занимает в оперативной памяти
|
||||
UsedMemoryRssHuman string // Человеко-читаемое представление UsedMemoryRss
|
||||
UsedMemoryPeak string // Максимальное количество памяти, использованное Redis
|
||||
UsedMemoryPeakHuman string // Человеко-читаемое представление UsedMemoryPeak
|
||||
UsedMemoryPeakPerc string // Процент пикового использования памяти от текущего использования
|
||||
UsedMemoryOverhead string // Общее количество памяти, используемое для внутренних механизмов Redis
|
||||
UsedMemoryStartup string // Количество памяти, использованное Redis при запуске
|
||||
UsedMemoryDataset string // Общее количество памяти, используемое для хранения данных
|
||||
UsedMemoryDatasetPerc string // Процент использования памяти, занимаемый данными
|
||||
AllocatorAllocated string // Общее количество памяти, выделенное аллокатором
|
||||
AllocatorActive string // Общее количество памяти, выделенное и активно используемое аллокатором
|
||||
AllocatorResident string // Общее количество памяти, выделенное аллокатором и занимаемое в оперативной памяти
|
||||
TotalSystemMemory string // Общее количество оперативной памяти в системе
|
||||
TotalSystemMemoryHuman string // Человеко-читаемое представление TotalSystemMemory
|
||||
UsedMemoryLua string // Общее количество памяти, используемое движком Lua в Redis
|
||||
UsedMemoryLuaHuman string // Человеко-читаемое представление UsedMemoryLua
|
||||
Maxmemory string // Максимальное количество памяти, которое Redis может использовать
|
||||
MaxmemoryHuman string // Человеко-читаемое представление Maxmemory
|
||||
MaxmemoryPolicy string // Политика, которую Redis будет следовать при достижении Maxmemory
|
||||
MemFragmentationRatio string // Отношение памяти RSS к памяти, выделенной аллокатором
|
||||
MemFragmentationBytes string // Разница между памятью RSS и памятью, выделенной аллокатором
|
||||
MemAllocator string // Аллокатор, используемый Redis (jemalloc или glibc)
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// Approval — заявка на согласование.
|
||||
// Status: draft | pending | approved | rejected | revoked
|
||||
// DepartmentID копируется с инициатора в момент создания — для отчётов и изоляции без JOIN.
|
||||
// FileBase64 и FileName заполняются только если ApprovalTopic.AllowsFile = true.
|
||||
type Approval struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
InitiatorID *uint64 `gorm:"type:bigint;not null;index;column:initiator_id" json:"initiator_id" db:"initiator_id" mapstructure:"initiator_id"`
|
||||
TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"`
|
||||
DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"` // снимок отдела на момент создания
|
||||
Content *string `gorm:"type:text;not null;column:content" json:"content" db:"content" mapstructure:"content"` // введённые пользователем данные по шаблону
|
||||
Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"`
|
||||
RevokedByID *uint64 `gorm:"type:bigint;index;column:revoked_by_id" json:"revoked_by_id,omitempty" db:"revoked_by_id" mapstructure:"revoked_by_id"`
|
||||
RevokedAt *time.Time `gorm:"type:timestamp;column:revoked_at" json:"revoked_at,omitempty" db:"revoked_at"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Files []*ApprovalFile `gorm:"-" json:"files,omitempty"`
|
||||
Initiator *User `gorm:"-" json:"initiator,omitempty"`
|
||||
Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"`
|
||||
Department *Department `gorm:"-" json:"department,omitempty"`
|
||||
RevokedBy *User `gorm:"-" json:"revoked_by,omitempty"`
|
||||
Steps []*ApprovalStep `gorm:"-" json:"steps,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalAdditionalApprover struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
|
||||
ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id"`
|
||||
AddedByID *uint64 `gorm:"type:bigint;not null;column:added_by_id" json:"added_by_id" db:"added_by_id"`
|
||||
Status *string `gorm:"type:text;not null;default:'pending';column:status" json:"status" db:"status"`
|
||||
Comment *string `gorm:"type:text;column:comment" json:"comment,omitempty" db:"comment"`
|
||||
ActedAt *time.Time `gorm:"type:timestamp;column:acted_at" json:"acted_at,omitempty" db:"acted_at"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Approval *Approval `gorm:"-" json:"approval,omitempty"`
|
||||
Approver *User `gorm:"-" json:"approver,omitempty"`
|
||||
AddedBy *User `gorm:"-" json:"added_by,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalDelegation struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
|
||||
DelegatorID *uint64 `gorm:"type:bigint;not null;index;column:delegator_id" json:"delegator_id" db:"delegator_id"`
|
||||
DelegateID *uint64 `gorm:"type:bigint;not null;index;column:delegate_id" json:"delegate_id" db:"delegate_id"`
|
||||
CategoryID *uint64 `gorm:"type:bigint;index;column:category_id" json:"category_id,omitempty" db:"category_id"`
|
||||
TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id"`
|
||||
ValidUntil *time.Time `gorm:"type:timestamp;not null;column:valid_until" json:"valid_until" db:"valid_until"`
|
||||
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active"`
|
||||
NotifiedDay *bool `gorm:"type:boolean;not null;default:false;column:notified_day" json:"notified_day" db:"notified_day"`
|
||||
Notified2h *bool `gorm:"type:boolean;not null;default:false;column:notified_2h" json:"notified_2h" db:"notified_2h"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Delegator *User `gorm:"-" json:"delegator,omitempty"`
|
||||
Delegate *User `gorm:"-" json:"delegate,omitempty"`
|
||||
Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"`
|
||||
Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalFile struct {
|
||||
ID *uint64 `gorm:"column:id;autoIncrement;not null;unique" json:"id" db:"id"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
|
||||
FileBase64 *string `gorm:"type:text;not null;column:file_base64" json:"file_base64" db:"file_base64"`
|
||||
FileName *string `gorm:"type:text;not null;column:file_name" json:"file_name" db:"file_name"`
|
||||
CreatedAt *time.Time `gorm:"default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// ApprovalStep — один шаг согласования.
|
||||
// Status: pending | approved | rejected
|
||||
// Comment заполняется согласующим при отклонении (может быть пустым).
|
||||
// StepOrder определяет порядок (1 = первый согласующий).
|
||||
// ApproverNameSnapshot и ApproverDepartmentSnapshot — снимок данных согласующего
|
||||
// на момент действия, чтобы отчёты не ломались при изменении оргструктуры.
|
||||
type ApprovalStep struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id" mapstructure:"approval_id"`
|
||||
ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id" mapstructure:"approver_id"`
|
||||
StepOrder *int `gorm:"type:int;not null;column:step_order" json:"step_order" db:"step_order" mapstructure:"step_order"`
|
||||
Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"`
|
||||
Comment *string `gorm:"type:text;column:comment" json:"comment,omitempty" db:"comment" mapstructure:"comment"`
|
||||
ApproverNameSnapshot *string `gorm:"type:text;column:approver_name_snapshot" json:"approver_name_snapshot,omitempty" db:"approver_name_snapshot" mapstructure:"approver_name_snapshot"`
|
||||
ApproverDepartmentSnapshot *string `gorm:"type:text;column:approver_department_snapshot" json:"approver_department_snapshot,omitempty" db:"approver_department_snapshot" mapstructure:"approver_department_snapshot"`
|
||||
ActedAt *time.Time `gorm:"type:timestamp;column:acted_at" json:"acted_at,omitempty" db:"acted_at"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Approval *Approval `gorm:"-" json:"approval,omitempty"`
|
||||
Approver *User `gorm:"-" json:"approver,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalTask struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
|
||||
ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id"`
|
||||
TaskText *string `gorm:"type:text;not null;column:task_text" json:"task_text" db:"task_text"`
|
||||
Status *string `gorm:"type:text;not null;default:'pending';column:status" json:"status" db:"status"`
|
||||
CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at" json:"completed_at,omitempty" db:"completed_at"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Approval *Approval `gorm:"-" json:"approval,omitempty"`
|
||||
Executor *User `gorm:"-" json:"executor,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// ApprovalTopic — конкретная тема внутри категории.
|
||||
// DurationType: single_day | date_range | multi_day
|
||||
// TimeType: full_day | partial
|
||||
// PaymentType: own_expense | vacation_account | not_applicable (для partial)
|
||||
// Template хранит шаблон строки для подсказки пользователю при вводе.
|
||||
type ApprovalTopic struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
CategoryID *uint64 `gorm:"type:bigint;not null;index;column:category_id" json:"category_id" db:"category_id" mapstructure:"category_id"`
|
||||
Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
|
||||
Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"`
|
||||
DurationType *string `gorm:"type:text;column:duration_type" json:"duration_type,omitempty" db:"duration_type" mapstructure:"duration_type"`
|
||||
TimeType *string `gorm:"type:text;column:time_type" json:"time_type,omitempty" db:"time_type" mapstructure:"time_type"`
|
||||
PaymentType *string `gorm:"type:text;column:payment_type" json:"payment_type,omitempty" db:"payment_type" mapstructure:"payment_type"`
|
||||
Template *string `gorm:"type:text;not null;column:template" json:"template" db:"template" mapstructure:"template"`
|
||||
TaskTemplate *string `gorm:"type:text;column:task_template" json:"task_template,omitempty" db:"task_template" mapstructure:"task_template"`
|
||||
AllowsFile *bool `gorm:"type:boolean;not null;default:false;column:allows_file" json:"allows_file" db:"allows_file" mapstructure:"allows_file"`
|
||||
AllowApproverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_approver_selection" json:"allow_approver_selection" db:"allow_approver_selection" mapstructure:"allow_approver_selection"`
|
||||
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalTopicCategory struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
|
||||
Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` // otgul, vacation, sick_leave
|
||||
Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
|
||||
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Topics []*ApprovalTopic `gorm:"-" json:"topics,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package typescore
|
||||
|
||||
// BalancerRequest — тело запроса на /api/balancer/send
|
||||
type BalancerRequest struct {
|
||||
URL *string `json:"url"` // URL метода Bitrix24
|
||||
Method *string `json:"method"` // HTTP метод (GET, POST)
|
||||
Headers map[string]string `json:"headers,omitempty"` // Заголовки для Bitrix24
|
||||
Body map[string]interface{} `json:"body,omitempty"` // Тело запроса
|
||||
|
||||
// IsRecurrent — если true, бэк автоматически загружает ВСЕ записи
|
||||
// постранично (по 50 за запрос) и возвращает одним массивом.
|
||||
// Nil/false = обычный разовый запрос.
|
||||
IsRecurrent bool `json:"is_recurrent,omitempty"`
|
||||
|
||||
// ResultKey — ключ внутри result где лежит массив.
|
||||
// "tasks" для tasks.task.list, пусто для crm.lead.list и др.
|
||||
ResultKey *string `json:"result_key,omitempty"`
|
||||
}
|
||||
|
||||
// BalancerResponse — ответ от Bitrix24 проксированный клиенту
|
||||
type BalancerResponse struct {
|
||||
StatusCode *int `json:"status_code"`
|
||||
Body interface{} `json:"body"`
|
||||
QuotaLeft *int64 `json:"quota_left"`
|
||||
IsRecurrent bool `json:"is_recurrent,omitempty"`
|
||||
TotalFetched *int `json:"total_fetched,omitempty"`
|
||||
}
|
||||
|
||||
// QuotaResponse — ответ на /api/balancer/quota
|
||||
type QuotaResponse struct {
|
||||
PortalID *string `json:"portal_id"`
|
||||
Counter *int64 `json:"counter"` // текущий счётчик
|
||||
Limit *int64 `json:"limit"` // порог блокировки (X)
|
||||
FreeSlots *int64 `json:"free_slots"` // доступные слоты
|
||||
DecreasePerSec *int64 `json:"decrease_per_sec"` // скорость освобождения (Y)
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// объединяет общие параметры запроса.
|
||||
type ListDbOptions struct {
|
||||
Filtering interface{}
|
||||
LikeFields map[string]string
|
||||
Offset *uint64
|
||||
Limit *uint64
|
||||
FromDate *time.Time
|
||||
ToDate *time.Time
|
||||
NotNullFields map[string]bool // поля, не нулевые(при запросе ставит where на эти поля not null) bool-true для числовых полей
|
||||
SortingParams map[string]string // поля, по которым сортируется
|
||||
SortBy string // поля, по которым сортируется
|
||||
}
|
||||
|
||||
type InsertOptions struct {
|
||||
Prefix string // Префикс для запроса (например, WITH)
|
||||
Suffix string // Суффикс для запроса (например, ON CONFLICT, RETURNING)
|
||||
IgnoreConflict bool // Флаг игнорирования конфликтов
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type Department struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
|
||||
Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` // finance, hr, it
|
||||
Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
|
||||
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package typescore
|
||||
|
||||
type Response struct {
|
||||
Success bool `json:"success"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Error error `json:"error,omitempty"`
|
||||
Count int `json:"count,omitempty"`
|
||||
TotalCount *uint64 `json:"total_count,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// Permission — право роли на действие в рамках категории или конкретной темы.
|
||||
// Action: create | read | update | delete | approve | revoke
|
||||
// Если TopicCategoryID заполнен, а TopicID = nil — право на все темы категории.
|
||||
// Если TopicID заполнен — право только на конкретную тему.
|
||||
type Permission struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
RoleID *uint64 `gorm:"type:bigint;not null;index;column:role_id" json:"role_id" db:"role_id" mapstructure:"role_id"`
|
||||
TopicCategoryID *uint64 `gorm:"type:bigint;index;column:topic_category_id" json:"topic_category_id,omitempty" db:"topic_category_id" mapstructure:"topic_category_id"`
|
||||
TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"`
|
||||
Action *string `gorm:"type:text;not null;column:action" json:"action" db:"action" mapstructure:"action"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Role *Role `gorm:"-" json:"role,omitempty"`
|
||||
TopicCategory *ApprovalTopicCategory `gorm:"-" json:"topic_category,omitempty"`
|
||||
Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// ReportFilter — фильтр для выгрузки отчёта по согласованиям
|
||||
type ReportFilter struct {
|
||||
AllAccess bool // true для директора (видит всё)
|
||||
UserID *uint64 // ID пользователя для фильтрации по ролям
|
||||
CategoryCodes []string // DEPRECATED: теперь не используется, роли определяются через UserID
|
||||
DateFrom *time.Time // начало периода
|
||||
DateTo *time.Time // конец периода
|
||||
}
|
||||
|
||||
// TaskReportFilter — фильтр для выгрузки отчёта по задачам
|
||||
type TaskReportFilter struct {
|
||||
AllAccess bool // true для директора (видит всё)
|
||||
UserID *uint64 // ID пользователя для фильтрации по ролям
|
||||
DateFrom *time.Time // начало периода
|
||||
DateTo *time.Time // конец периода
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type Role struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
|
||||
Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"`
|
||||
IsDefault *bool `gorm:"type:boolean;not null;default:false;column:is_default" json:"is_default" db:"is_default" mapstructure:"is_default"`
|
||||
IsDirector *bool `gorm:"type:boolean;not null;default:false;column:is_director" json:"is_director" db:"is_director" mapstructure:"is_director"`
|
||||
IsApprover *bool `gorm:"type:boolean;not null;default:false;column:is_approver" json:"is_approver" db:"is_approver" mapstructure:"is_approver"`
|
||||
IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"`
|
||||
IsExecutor *bool `gorm:"type:boolean;not null;default:false;column:is_executor" json:"is_executor" db:"is_executor" mapstructure:"is_executor"`
|
||||
Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Permissions []*Permission `gorm:"-" json:"permissions,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
TelegramID *int64 `gorm:"type:numeric;not null;unique;column:telegram_id" json:"telegram_id" db:"telegram_id" mapstructure:"telegram_id"`
|
||||
Username *string `gorm:"type:text;column:username" json:"username,omitempty" db:"username" mapstructure:"username"`
|
||||
FullName *string `gorm:"type:text;not null;column:full_name" json:"full_name" db:"full_name" mapstructure:"full_name"`
|
||||
//FirstName *string `gorm:"type:text;not null;column:first_name" json:"first_name" db:"first_name" mapstructure:"first_name"`
|
||||
//LastName *string `gorm:"type:text;not null;column:last_name" json:"last_name" db:"last_name" mapstructure:"last_name"`
|
||||
//Patronymic *string `gorm:"type:text;column:patronymic" json:"patronymic,omitempty" db:"patronymic" mapstructure:"patronymic"`
|
||||
LanguageCode *string `gorm:"type:text;not null;default:'ru';column:language_code" json:"language_code" db:"language_code" mapstructure:"language_code"`
|
||||
DepartmentID *uint64 `gorm:"type:bigint;index;column:department_id" json:"department_id,omitempty" db:"department_id" mapstructure:"department_id"`
|
||||
IsBlocked *bool `gorm:"type:boolean;not null;default:false;index;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"`
|
||||
IsFired *bool `gorm:"type:boolean;not null;default:false;index;column:is_fired" json:"is_fired" db:"is_fired" mapstructure:"is_fired"`
|
||||
BlockedAt *time.Time `gorm:"type:timestamp;column:blocked_at" json:"blocked_at,omitempty" db:"blocked_at"`
|
||||
LastLogin *time.Time `gorm:"type:timestamp;column:last_login" json:"last_login,omitempty" db:"last_login"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Department *Department `gorm:"-" json:"department,omitempty"`
|
||||
UserRoles []*UserRole `gorm:"-" json:"user_roles,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type UserAuth struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"`
|
||||
PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"password_hash" db:"password_hash"`
|
||||
Salt *string `gorm:"type:text;not null;column:salt" json:"-" db:"salt"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// UserHierarchy — связь подчинённого и его согласующего.
|
||||
// Согласующий может быть привязан к нескольким отделам через разные записи.
|
||||
// Priority определяет порядок шагов согласования (1 = первый).
|
||||
type UserHierarchy struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
SubordinateID *uint64 `gorm:"type:bigint;not null;index;column:subordinate_id" json:"subordinate_id" db:"subordinate_id" mapstructure:"subordinate_id"`
|
||||
ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id" mapstructure:"approver_id"`
|
||||
ExecutorID *uint64 `gorm:"type:bigint;index;column:executor_id" json:"executor_id,omitempty" db:"executor_id" mapstructure:"executor_id"`
|
||||
DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"`
|
||||
TopicCategoryID *uint64 `gorm:"type:bigint;index;column:topic_category_id" json:"topic_category_id,omitempty" db:"topic_category_id" mapstructure:"topic_category_id"`
|
||||
TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"`
|
||||
Priority *int `gorm:"type:int;not null;default:1;column:priority" json:"priority" db:"priority" mapstructure:"priority"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Subordinate *User `gorm:"-" json:"subordinate,omitempty"`
|
||||
Approver *User `gorm:"-" json:"approver,omitempty"`
|
||||
Executor *User `gorm:"-" json:"executor,omitempty"`
|
||||
Department *Department `gorm:"-" json:"department,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// UserRole — связь пользователя с ролью.
|
||||
// Один пользователь может иметь несколько ролей (например, сотрудник и согласующий одновременно).
|
||||
type UserRole struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` // Автоматически заполняемое уникальное поле для большого числа записей
|
||||
UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"`
|
||||
RoleID *uint64 `gorm:"type:bigint;not null;index;column:role_id" json:"role_id" db:"role_id" mapstructure:"role_id"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
User *User `gorm:"-" json:"user,omitempty"` // ← добавить gorm:"-"
|
||||
Role *Role `gorm:"-" json:"role,omitempty"` // ← добавить gorm:"-"
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
package utilscore
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
func PointerToBool(b bool) *bool {
|
||||
return &b
|
||||
}
|
||||
|
||||
func PointerToUint32(i uint32) *uint32 {
|
||||
return &i
|
||||
}
|
||||
|
||||
func PointerToDecimal(i decimal.Decimal) *decimal.Decimal {
|
||||
return &i
|
||||
}
|
||||
|
||||
func PointerToUint64(i uint64) *uint64 {
|
||||
return &i
|
||||
}
|
||||
|
||||
func PointerToString(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
func PointerToFloat64(f float64) *float64 {
|
||||
return &f
|
||||
}
|
||||
|
||||
func PointerToFloat32(f float32) *float32 {
|
||||
return &f
|
||||
}
|
||||
|
||||
func PointerToInt(i int) *int {
|
||||
return &i
|
||||
}
|
||||
func PointerToTime(t time.Time) *time.Time {
|
||||
return &t
|
||||
}
|
||||
|
||||
func PointerToInt64(i int64) *int64 {
|
||||
return &i
|
||||
}
|
||||
|
||||
func PointerToInt32(i int32) *int32 {
|
||||
return &i
|
||||
}
|
||||
|
||||
// GetStringValue получает значение из указателя на строку
|
||||
func GetStringValue(ptr *string) string {
|
||||
if ptr == nil {
|
||||
return ""
|
||||
}
|
||||
return *ptr
|
||||
}
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
package dbutils
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
fieldsCache sync.Map // Используем sync.Map для кэширования
|
||||
)
|
||||
|
||||
type cacheKey struct {
|
||||
typ reflect.Type
|
||||
dbName string
|
||||
}
|
||||
|
||||
// GetOptionsDB обобщённая функция для разбора опций.
|
||||
// Если Filtering не передан, создаётся новый объект типа T.
|
||||
// Если передан, то выполняется проверка соответствия типу *T.
|
||||
func GetOptionsDB[T any](opts ...typescore.ListDbOptions) (typescore.ListDbOptions, *T, error) {
|
||||
var options typescore.ListDbOptions
|
||||
if len(opts) > 0 {
|
||||
options = opts[0]
|
||||
}
|
||||
|
||||
var filter *T
|
||||
if options.Filtering == nil {
|
||||
filter = new(T)
|
||||
} else {
|
||||
var ok bool
|
||||
filter, ok = options.Filtering.(*T)
|
||||
if !ok {
|
||||
return typescore.ListDbOptions{}, nil, errors.New("expected *T")
|
||||
}
|
||||
}
|
||||
return options, filter, nil
|
||||
}
|
||||
|
||||
func GetStructFieldsDB(processor interface{}, dbName ...string) []string {
|
||||
if processor == nil || reflect.ValueOf(processor).Kind() != reflect.Ptr || reflect.ValueOf(processor).Elem().Kind() != reflect.Struct {
|
||||
logrus.Error("🔴 error GetStructFieldsDB: processor must be a non-nil pointer to a struct")
|
||||
return nil
|
||||
}
|
||||
|
||||
procType := reflect.TypeOf(processor).Elem()
|
||||
nameDB := ""
|
||||
if len(dbName) > 0 {
|
||||
nameDB = dbName[0]
|
||||
}
|
||||
key := cacheKey{
|
||||
typ: procType,
|
||||
dbName: nameDB,
|
||||
}
|
||||
|
||||
if fields, exists := fieldsCache.Load(key); exists {
|
||||
return fields.([]string)
|
||||
}
|
||||
|
||||
val := reflect.ValueOf(processor).Elem()
|
||||
|
||||
var fields []string
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
typeField := procType.Field(i)
|
||||
dbTag := typeField.Tag.Get("db")
|
||||
if dbTag != "" {
|
||||
if typeField.Tag.Get("ignore_db") == "true" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Добавляем alias, чтобы исключить конфликты при одинаковых именах полей
|
||||
if nameDB != "" {
|
||||
fullField := fmt.Sprintf("%s.%s", nameDB, dbTag)
|
||||
fields = append(fields, fullField)
|
||||
} else {
|
||||
fields = append(fields, dbTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fieldsCache.Store(key, fields)
|
||||
return fields
|
||||
}
|
||||
|
||||
func AddNonNullFieldsToQueryUpdate(query squirrel.UpdateBuilder, paramsUpdate interface{}) squirrel.UpdateBuilder {
|
||||
v := reflect.ValueOf(paramsUpdate)
|
||||
t := v.Type()
|
||||
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
field := v.Field(i)
|
||||
if (field.Kind() == reflect.Ptr && !field.IsNil()) || (field.Kind() != reflect.Ptr && !field.IsZero()) {
|
||||
// Проверяем тег ignore_update_db для игнорирования полей при обновлении
|
||||
ignoreUpdateDbTag := t.Field(i).Tag.Get("ignore_update_db")
|
||||
if ignoreUpdateDbTag == "true" {
|
||||
continue
|
||||
}
|
||||
ignoreDbTag := t.Field(i).Tag.Get("ignore_db")
|
||||
if ignoreDbTag == "true" {
|
||||
continue
|
||||
}
|
||||
dbTag := t.Field(i).Tag.Get("db")
|
||||
if dbTag != "system_id" && dbTag != "role" && dbTag != "created_at" {
|
||||
query = query.Set(dbTag, field.Interface())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
// Создаем два списка для хранения названий столбцов и соответствующих значений
|
||||
func GenerateInsertRequest(query squirrel.InsertBuilder, processor interface{}, options ...typescore.InsertOptions) (*string, []interface{}, error) {
|
||||
var columns []string
|
||||
var values []interface{}
|
||||
v := reflect.ValueOf(processor).Elem()
|
||||
t := v.Type()
|
||||
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
field := v.Field(i)
|
||||
ignoreDbTag := t.Field(i).Tag.Get("ignore_db")
|
||||
if ignoreDbTag == "true" {
|
||||
continue
|
||||
}
|
||||
dbTag := t.Field(i).Tag.Get("db")
|
||||
if dbTag == "" {
|
||||
continue
|
||||
}
|
||||
if dbTag == "serial_id" || dbTag == "system_id" {
|
||||
continue
|
||||
}
|
||||
|
||||
if (field.Kind() == reflect.Ptr && !field.IsNil()) || (field.Kind() != reflect.Ptr && !field.IsZero()) {
|
||||
columns = append(columns, dbTag)
|
||||
values = append(values, field.Interface())
|
||||
}
|
||||
}
|
||||
|
||||
if len(columns) == 0 {
|
||||
logrus.Error("🔴 error GenerateInsertRequest: all fields are zero")
|
||||
return nil, nil, errors.New("all fields are zero")
|
||||
}
|
||||
|
||||
// Применяем опции, если они есть
|
||||
if len(options) > 0 {
|
||||
for _, opt := range options {
|
||||
if opt.Prefix != "" {
|
||||
query = query.Prefix(opt.Prefix)
|
||||
}
|
||||
if opt.Suffix != "" {
|
||||
query = query.Suffix(opt.Suffix)
|
||||
} else if opt.IgnoreConflict {
|
||||
query = query.Suffix("ON CONFLICT DO NOTHING")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
query = query.Columns(columns...).Values(values...)
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
logrus.Error("🔴 error GenerateInsertRequest: ", err)
|
||||
return nil, nil, err
|
||||
}
|
||||
if sql == "" {
|
||||
logrus.Error("🔴 error GenerateInsertRequest: sql is empty")
|
||||
return nil, nil, errors.New("sql is empty")
|
||||
}
|
||||
return &sql, args, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
package dbutils
|
||||
|
||||
import (
|
||||
"github.com/Masterminds/squirrel"
|
||||
)
|
||||
|
||||
// SetterLimitAndOffsetQuery применяет limit и offset к переданному SelectBuilder, если они не nil.
|
||||
func SetterLimitAndOffsetQuery(query squirrel.SelectBuilder, offset *uint64, limit *uint64) squirrel.SelectBuilder {
|
||||
if limit != nil {
|
||||
query = query.Limit(*limit)
|
||||
}
|
||||
if offset != nil {
|
||||
query = query.Offset(*offset)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
package dbutils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Кэш для функции prepareFieldMap
|
||||
var prepareFieldMapCache sync.Map // Используем sync.Map для кэширования
|
||||
|
||||
type cachedFieldInfo struct {
|
||||
dbTag string
|
||||
fieldPath []int
|
||||
}
|
||||
|
||||
// ScanRowsToStructRows сканирует строки из pgx.Rows в структуру и totalCount.
|
||||
func ScanRowsToStructRows(rows pgx.Rows, dest interface{}, totalCount *uint64, totalAmount ...*float64) error {
|
||||
if dest == nil {
|
||||
return errors.New("dest must not be nil")
|
||||
}
|
||||
|
||||
val := reflect.ValueOf(dest)
|
||||
if val.Kind() != reflect.Ptr || val.IsNil() {
|
||||
return errors.New("dest must be a non-nil pointer")
|
||||
}
|
||||
|
||||
elem := val.Elem()
|
||||
if elem.Kind() != reflect.Struct {
|
||||
return errors.New("dest must be a pointer to a struct")
|
||||
}
|
||||
|
||||
typ := elem.Type()
|
||||
fieldMap := prepareFieldMap(elem, typ)
|
||||
|
||||
columns := getColumnsFromRows(rows)
|
||||
args := getScanArgs(columns, fieldMap, totalCount, totalAmount...)
|
||||
|
||||
err := rows.Scan(args...)
|
||||
if err != nil {
|
||||
logrus.Error("🔴 error ScanRowsToStructRows: ", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getColumnsFromRows(rows pgx.Rows) []string {
|
||||
fieldDescriptions := rows.FieldDescriptions()
|
||||
columns := make([]string, len(fieldDescriptions))
|
||||
for i, fd := range fieldDescriptions {
|
||||
columns[i] = string(fd.Name)
|
||||
}
|
||||
return columns
|
||||
}
|
||||
|
||||
func getScanArgs(columns []string, fieldMap map[string]interface{}, totalCount *uint64, totalAmount ...*float64) []interface{} {
|
||||
scanArgs := make([]interface{}, len(columns))
|
||||
|
||||
for i, col := range columns {
|
||||
switch col {
|
||||
case "total_count":
|
||||
if totalCount != nil {
|
||||
scanArgs[i] = totalCount
|
||||
} else {
|
||||
scanArgs[i] = new(uint64)
|
||||
}
|
||||
case "total_amount":
|
||||
if totalAmount[0] != nil {
|
||||
scanArgs[i] = totalAmount[0]
|
||||
} else {
|
||||
dummy := new(float64)
|
||||
scanArgs[i] = dummy
|
||||
}
|
||||
default:
|
||||
if field, ok := fieldMap[col]; ok {
|
||||
scanArgs[i] = field
|
||||
} else {
|
||||
dummy := new(interface{})
|
||||
scanArgs[i] = dummy
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return scanArgs
|
||||
}
|
||||
|
||||
func prepareFieldMap(val reflect.Value, typ reflect.Type) map[string]interface{} {
|
||||
if cachedFields, ok := prepareFieldMapCache.Load(typ); ok {
|
||||
fieldMap := make(map[string]interface{})
|
||||
// Используем закешированные данные
|
||||
for _, info := range cachedFields.([]cachedFieldInfo) {
|
||||
field := val.FieldByIndex(info.fieldPath)
|
||||
if field.CanAddr() {
|
||||
fieldMap[info.dbTag] = field.Addr().Interface()
|
||||
}
|
||||
}
|
||||
return fieldMap
|
||||
}
|
||||
|
||||
// Если тип не закеширован, собираем информацию о полях
|
||||
var cachedFieldsInfo []cachedFieldInfo
|
||||
fieldMap := make(map[string]interface{})
|
||||
if val.Kind() == reflect.Ptr {
|
||||
val = val.Elem()
|
||||
}
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
field := val.Field(i)
|
||||
fieldType := typ.Field(i)
|
||||
|
||||
if fieldType.Tag.Get("ignore_db_select") == "true" {
|
||||
continue
|
||||
}
|
||||
if tag := fieldType.Tag.Get("db"); tag != "" {
|
||||
if field.Type() == reflect.TypeOf(json.RawMessage{}) {
|
||||
fieldMap[tag] = field.Addr().Interface()
|
||||
} else if field.Kind() == reflect.Slice && field.Type().Elem() == reflect.TypeOf(json.RawMessage{}) {
|
||||
fieldMap[tag] = &json.RawMessage{}
|
||||
} else if field.Kind() == reflect.Struct && field.Type() == reflect.TypeOf(json.RawMessage{}) {
|
||||
fieldMap[tag] = &json.RawMessage{}
|
||||
} else {
|
||||
fieldMap[tag] = field.Addr().Interface()
|
||||
}
|
||||
cachedFieldsInfo = append(cachedFieldsInfo, cachedFieldInfo{
|
||||
dbTag: tag,
|
||||
fieldPath: fieldType.Index,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем информацию в кэше
|
||||
prepareFieldMapCache.Store(typ, cachedFieldsInfo)
|
||||
|
||||
return fieldMap
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package dbutils
|
||||
|
||||
import (
|
||||
"github.com/Masterminds/squirrel"
|
||||
)
|
||||
|
||||
// BuildSelectQuery создает базовый SELECT-запрос.
|
||||
func BuildSelectQuery(table string, fields []string) squirrel.SelectBuilder {
|
||||
return squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).From(table)
|
||||
}
|
||||
|
||||
// ApplyFilters добавляет фильтры к запросу
|
||||
func ApplyFilters(query squirrel.SelectBuilder, paramsFiltering interface{}, likeFields map[string]string, baseName ...string) squirrel.SelectBuilder {
|
||||
var baseNamePtr *string
|
||||
if len(baseName) > 0 {
|
||||
baseNamePtr = &baseName[0]
|
||||
} else {
|
||||
baseNamePtr = nil
|
||||
}
|
||||
return AddNonNullFieldsToQueryWhere(query, paramsFiltering, likeFields, baseNamePtr)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue