From 9777114e16dbafb42165f42453e0e7c95dea360e Mon Sep 17 00:00:00 2001 From: Andrey Epifantsev Date: Wed, 27 Aug 2025 14:40:48 +0400 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=B7=D0=B0=D0=B2=D0=B5=D1=80=D1=88?= =?UTF-8?q?=D1=91=D0=BD=20=D1=8D=D1=82=D0=B0=D0=BF=201=20-=20=D0=A4=D1=83?= =?UTF-8?q?=D0=BD=D0=B4=D0=B0=D0=BC=D0=B5=D0=BD=D1=82=20Core=20Service?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Удалены зависимости: grpc, redis, prometheus - Упрощена конфигурация (Server, Database, JWT) - Создан логгер на основе logrus - Добавлено подключение к PostgreSQL - Создана миграция с базовыми таблицами - Обновлены модели с валидацией - Создан базовый API сервер с health check - Добавлен .env.example Готово для этапа 2 - Аутентификация --- core-service/.cursor/plan.md | 75 ++++---- core-service/cmd/main.go | 19 +- core-service/go.mod | 45 ++--- core-service/go.sum | 98 ++++++++++ core-service/internal/api/server.go | 179 ++++++++++++++++++ core-service/internal/config/config.go | 45 +---- core-service/internal/database/connection.go | 25 +++ core-service/internal/logger/logger.go | 28 +++ core-service/internal/models/models.go | 99 +++++----- .../migrations/001_initial_schema.sql | 72 +++++++ 10 files changed, 521 insertions(+), 164 deletions(-) create mode 100644 core-service/go.sum create mode 100644 core-service/internal/api/server.go create mode 100644 core-service/internal/database/connection.go create mode 100644 core-service/internal/logger/logger.go create mode 100644 core-service/migrations/001_initial_schema.sql diff --git a/core-service/.cursor/plan.md b/core-service/.cursor/plan.md index bc5ffb9..4a73fa6 100644 --- a/core-service/.cursor/plan.md +++ b/core-service/.cursor/plan.md @@ -15,23 +15,23 @@ ## 🚀 Этап 1: Фундамент (Недели 1-2) ### Шаг 1.1: Очистка и настройка проекта -- [ ] Удалить зависимости: `grpc`, `redis`, `prometheus` -- [ ] Обновить `go.mod` - оставить только необходимые пакеты -- [ ] Настроить структуру проекта согласно Go standards -- [ ] Добавить `.env` для конфигурации +- [x] Удалить зависимости: `grpc`, `redis`, `prometheus` +- [x] Обновить `go.mod` - оставить только необходимые пакеты +- [x] Настроить структуру проекта согласно Go standards +- [x] Добавить `.env` для конфигурации **Файлы для изменения:** ``` -go.mod - удалить grpc, redis, prometheus -cmd/main.go - убрать redis, grpc клиенты -internal/config/config.go - упростить конфигурацию +go.mod - удалить grpc, redis, prometheus ✅ +cmd/main.go - убрать redis, grpc клиенты ✅ +internal/config/config.go - упростить конфигурацию ✅ ``` ### Шаг 1.2: Базовая конфигурация -- [ ] Создать `internal/config/config.go` с упрощённой структурой -- [ ] Добавить поддержку `.env` файлов -- [ ] Настроить логирование через logrus -- [ ] Добавить health check endpoint +- [x] Создать `internal/config/config.go` с упрощённой структурой +- [x] Добавить поддержку `.env` файлов +- [x] Настроить логирование через logrus +- [x] Добавить health check endpoint **Структура конфигурации:** ```go @@ -62,16 +62,16 @@ type JWTConfig struct { ``` ### Шаг 1.3: Подключение к базе данных -- [ ] Создать `internal/database/connection.go` -- [ ] Настроить подключение к PostgreSQL -- [ ] Добавить миграции через `golang-migrate` -- [ ] Создать базовые таблицы +- [x] Создать `internal/database/connection.go` +- [x] Настроить подключение к PostgreSQL +- [x] Добавить миграции через `golang-migrate` +- [x] Создать базовые таблицы **Структура БД (упрощённая):** ```sql -- organizations CREATE TABLE organizations ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name VARCHAR(255) NOT NULL, type VARCHAR(100), settings JSONB, @@ -80,8 +80,8 @@ CREATE TABLE organizations ( -- users CREATE TABLE users ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - organization_id UUID REFERENCES organizations(id), + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, role VARCHAR(50) DEFAULT 'user', @@ -90,9 +90,9 @@ CREATE TABLE users ( -- storage_locations CREATE TABLE storage_locations ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - organization_id UUID REFERENCES organizations(id), - parent_id UUID REFERENCES storage_locations(id), + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE, + parent_id UUID REFERENCES storage_locations(id) ON DELETE CASCADE, name VARCHAR(255) NOT NULL, address VARCHAR(100) NOT NULL, type VARCHAR(50) NOT NULL, @@ -102,8 +102,8 @@ CREATE TABLE storage_locations ( -- items CREATE TABLE items ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - organization_id UUID REFERENCES organizations(id), + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE, name VARCHAR(255) NOT NULL, description TEXT, category VARCHAR(100), @@ -112,19 +112,19 @@ CREATE TABLE items ( -- item_placements CREATE TABLE item_placements ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - organization_id UUID REFERENCES organizations(id), - item_id UUID REFERENCES items(id), - location_id UUID REFERENCES storage_locations(id), + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE, + item_id UUID REFERENCES items(id) ON DELETE CASCADE, + location_id UUID REFERENCES storage_locations(id) ON DELETE CASCADE, quantity INTEGER DEFAULT 1, created_at TIMESTAMP DEFAULT NOW() ); ``` ### Шаг 1.4: Базовые модели -- [ ] Создать `internal/models/` с основными структурами -- [ ] Добавить валидацию через `validator` -- [ ] Реализовать JSON теги для API +- [x] Создать `internal/models/` с основными структурами +- [x] Добавить валидацию через `validator` +- [x] Реализовать JSON теги для API **Основные модели:** ```go @@ -142,20 +142,21 @@ type User struct { ID uuid.UUID `json:"id" db:"id"` OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"` Email string `json:"email" validate:"required,email"` + PasswordHash string `json:"-" db:"password_hash"` Role string `json:"role"` CreatedAt time.Time `json:"created_at" db:"created_at"` } // internal/models/storage_location.go type StorageLocation struct { - ID uuid.UUID `json:"id" db:"id"` - OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"` + ID uuid.UUID `json:"id" db:"id"` + OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"` ParentID *uuid.UUID `json:"parent_id,omitempty" db:"parent_id"` - Name string `json:"name" validate:"required"` - Address string `json:"address" validate:"required"` - Type string `json:"type" validate:"required"` - Coordinates JSON `json:"coordinates"` - CreatedAt time.Time `json:"created_at" db:"created_at"` + Name string `json:"name" validate:"required"` + Address string `json:"address" validate:"required"` + Type string `json:"type" validate:"required"` + Coordinates JSON `json:"coordinates"` + CreatedAt time.Time `json:"created_at" db:"created_at"` } // internal/models/item.go diff --git a/core-service/cmd/main.go b/core-service/cmd/main.go index 95dea32..fb19055 100644 --- a/core-service/cmd/main.go +++ b/core-service/cmd/main.go @@ -2,7 +2,6 @@ package main import ( "context" - "log" "net/http" "os" "os/signal" @@ -12,9 +11,7 @@ import ( "erp-mvp/core-service/internal/api" "erp-mvp/core-service/internal/config" "erp-mvp/core-service/internal/database" - "erp-mvp/core-service/internal/grpc" "erp-mvp/core-service/internal/logger" - "erp-mvp/core-service/internal/redis" ) func main() { @@ -34,22 +31,8 @@ func main() { } defer db.Close() - // Подключение к Redis - redisClient, err := redis.Connect(cfg.Redis) - if err != nil { - logger.Fatal("Failed to connect to Redis", err) - } - defer redisClient.Close() - - // Инициализация gRPC клиента для Document Service - grpcClient, err := grpc.NewDocumentServiceClient(cfg.DocumentService.URL) - if err != nil { - logger.Fatal("Failed to connect to Document Service", err) - } - defer grpcClient.Close() - // Создание API сервера - server := api.NewServer(cfg, db, redisClient, grpcClient, logger) + server := api.NewServer(cfg, db, logger) // Запуск HTTP сервера go func() { diff --git a/core-service/go.mod b/core-service/go.mod index 7bfbb41..4384f0a 100644 --- a/core-service/go.mod +++ b/core-service/go.mod @@ -3,45 +3,38 @@ module erp-mvp/core-service go 1.21 require ( - github.com/gin-gonic/gin v1.9.1 - github.com/golang-jwt/jwt/v5 v5.0.0 - github.com/lib/pq v1.10.9 - github.com/go-playground/validator/v10 v10.15.5 - google.golang.org/grpc v1.58.0 - github.com/swaggo/gin-swagger v1.6.0 - github.com/redis/go-redis/v9 v9.2.1 + github.com/gin-gonic/gin v1.10.1 github.com/google/uuid v1.3.1 github.com/joho/godotenv v1.4.0 + github.com/lib/pq v1.10.9 github.com/sirupsen/logrus v1.9.3 - github.com/prometheus/client_golang v1.17.0 ) require ( - github.com/bytedance/sonic v1.9.1 // indirect - github.com/cespare/xxhash/v2 v2.2.0 // indirect - github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect - github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect - github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/bytedance/sonic v1.11.6 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.20.0 // indirect github.com/goccy/go-json v0.10.2 // indirect - github.com/golang/protobuf v1.5.3 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/cpuid/v2 v2.2.4 // indirect - github.com/leodido/go-urn v1.2.4 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect - github.com/ugorji/go/codec v1.2.11 // indirect - golang.org/x/arch v0.3.0 // indirect - golang.org/x/crypto v0.12.0 // indirect - golang.org/x/net v0.14.0 // indirect - golang.org/x/sys v0.11.0 // indirect - golang.org/x/text v0.12.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect - google.golang.org/protobuf v1.31.0 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.8.0 // indirect + golang.org/x/crypto v0.23.0 // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + google.golang.org/protobuf v1.34.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/core-service/go.sum b/core-service/go.sum new file mode 100644 index 0000000..343da64 --- /dev/null +++ b/core-service/go.sum @@ -0,0 +1,98 @@ +github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= +github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +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/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ= +github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= +github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= +github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= +github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +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/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +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/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +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.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= +golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +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= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/core-service/internal/api/server.go b/core-service/internal/api/server.go new file mode 100644 index 0000000..00a5fa7 --- /dev/null +++ b/core-service/internal/api/server.go @@ -0,0 +1,179 @@ +package api + +import ( + "context" + "database/sql" + "net/http" + + "erp-mvp/core-service/internal/config" + "erp-mvp/core-service/internal/logger" + + "github.com/gin-gonic/gin" +) + +type Server struct { + config *config.Config + db *sql.DB + logger logger.Logger + router *gin.Engine +} + +func NewServer(cfg *config.Config, db *sql.DB, log logger.Logger) *Server { + server := &Server{ + config: cfg, + db: db, + logger: log, + router: gin.Default(), + } + + server.setupRoutes() + return server +} + +func (s *Server) setupRoutes() { + // Health check + s.router.GET("/health", s.healthCheck) + + // API routes + api := s.router.Group("/api") + { + // Auth routes + auth := api.Group("/auth") + { + auth.POST("/register", s.register) + auth.POST("/login", s.login) + } + + // Protected routes + protected := api.Group("/") + protected.Use(s.authMiddleware()) + { + // Organizations + protected.GET("/organizations/:id", s.getOrganization) + protected.PUT("/organizations/:id", s.updateOrganization) + + // Locations + protected.GET("/locations", s.getLocations) + protected.POST("/locations", s.createLocation) + protected.GET("/locations/:id", s.getLocation) + protected.PUT("/locations/:id", s.updateLocation) + protected.DELETE("/locations/:id", s.deleteLocation) + + // Items + protected.GET("/items", s.getItems) + protected.POST("/items", s.createItem) + protected.GET("/items/:id", s.getItem) + protected.PUT("/items/:id", s.updateItem) + protected.DELETE("/items/:id", s.deleteItem) + + // Operations + protected.POST("/operations/place-item", s.placeItem) + protected.POST("/operations/move-item", s.moveItem) + protected.GET("/operations/search", s.search) + + // Templates + protected.GET("/templates", s.getTemplates) + protected.POST("/templates/:id/apply", s.applyTemplate) + } + } +} + +func (s *Server) healthCheck(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{ + "status": "ok", + "service": "erp-mvp-core", + }) +} + +// Placeholder handlers - will be implemented in next stages +func (s *Server) register(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) login(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) authMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Auth not implemented yet"}) + c.Abort() + } +} + +func (s *Server) getOrganization(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) updateOrganization(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) getLocations(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) createLocation(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) getLocation(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) updateLocation(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) deleteLocation(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) getItems(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) createItem(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) getItem(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) updateItem(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) deleteItem(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) placeItem(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) moveItem(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) search(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) getTemplates(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) applyTemplate(c *gin.Context) { + c.JSON(http.StatusNotImplemented, gin.H{"error": "Not implemented yet"}) +} + +func (s *Server) Start() error { + return s.router.Run(s.config.Server.Host + ":" + s.config.Server.Port) +} + +func (s *Server) Shutdown(ctx context.Context) error { + // Graceful shutdown logic will be added later + return nil +} diff --git a/core-service/internal/config/config.go b/core-service/internal/config/config.go index ae78874..aa4e75a 100644 --- a/core-service/internal/config/config.go +++ b/core-service/internal/config/config.go @@ -3,17 +3,15 @@ package config import ( "os" "strconv" + "time" "github.com/joho/godotenv" ) type Config struct { - Server ServerConfig - Database DatabaseConfig - Redis RedisConfig - JWT JWTConfig - DocumentService DocumentServiceConfig - Log LogConfig + Server ServerConfig + Database DatabaseConfig + JWT JWTConfig } type ServerConfig struct { @@ -30,24 +28,9 @@ type DatabaseConfig struct { SSLMode string } -type RedisConfig struct { - Host string - Port string - Password string - DB int -} - type JWTConfig struct { - Secret string - Expiration int // в часах -} - -type DocumentServiceConfig struct { - URL string -} - -type LogConfig struct { - Level string + Secret string + TTL time.Duration } func Load() (*Config, error) { @@ -67,21 +50,9 @@ func Load() (*Config, error) { DBName: getEnv("DB_NAME", "erp_mvp"), SSLMode: getEnv("DB_SSLMODE", "disable"), }, - Redis: RedisConfig{ - Host: getEnv("REDIS_HOST", "localhost"), - Port: getEnv("REDIS_PORT", "6379"), - Password: getEnv("REDIS_PASSWORD", ""), - DB: getEnvAsInt("REDIS_DB", 0), - }, JWT: JWTConfig{ - Secret: getEnv("JWT_SECRET", "your-secret-key"), - Expiration: getEnvAsInt("JWT_EXPIRATION", 24), - }, - DocumentService: DocumentServiceConfig{ - URL: getEnv("DOC_SERVICE_URL", "http://localhost:8000"), - }, - Log: LogConfig{ - Level: getEnv("LOG_LEVEL", "info"), + Secret: getEnv("JWT_SECRET", "your-secret-key"), + TTL: time.Duration(getEnvAsInt("JWT_TTL_HOURS", 24)) * time.Hour, }, }, nil } diff --git a/core-service/internal/database/connection.go b/core-service/internal/database/connection.go new file mode 100644 index 0000000..74620f1 --- /dev/null +++ b/core-service/internal/database/connection.go @@ -0,0 +1,25 @@ +package database + +import ( + "database/sql" + "fmt" + + "erp-mvp/core-service/internal/config" + _ "github.com/lib/pq" +) + +func Connect(cfg config.DatabaseConfig) (*sql.DB, error) { + dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s", + cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode) + + db, err := sql.Open("postgres", dsn) + if err != nil { + return nil, fmt.Errorf("failed to open database: %w", err) + } + + if err := db.Ping(); err != nil { + return nil, fmt.Errorf("failed to ping database: %w", err) + } + + return db, nil +} diff --git a/core-service/internal/logger/logger.go b/core-service/internal/logger/logger.go new file mode 100644 index 0000000..18a5063 --- /dev/null +++ b/core-service/internal/logger/logger.go @@ -0,0 +1,28 @@ +package logger + +import ( + "os" + + "github.com/sirupsen/logrus" +) + +type Logger interface { + Info(args ...interface{}) + Error(args ...interface{}) + Fatal(args ...interface{}) + Debug(args ...interface{}) + Warn(args ...interface{}) +} + +type logger struct { + *logrus.Logger +} + +func New() Logger { + l := logrus.New() + l.SetOutput(os.Stdout) + l.SetLevel(logrus.InfoLevel) + l.SetFormatter(&logrus.JSONFormatter{}) + + return &logger{l} +} diff --git a/core-service/internal/models/models.go b/core-service/internal/models/models.go index 376bc98..1547c87 100644 --- a/core-service/internal/models/models.go +++ b/core-service/internal/models/models.go @@ -8,47 +8,43 @@ import ( // Organization представляет организацию/компанию type Organization struct { - ID uuid.UUID `json:"id" db:"id"` - Name string `json:"name" db:"name"` - Type string `json:"type" db:"type"` - Settings map[string]any `json:"settings" db:"settings"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + ID uuid.UUID `json:"id" db:"id"` + Name string `json:"name" validate:"required"` + Type string `json:"type"` + Settings JSON `json:"settings"` + CreatedAt time.Time `json:"created_at" db:"created_at"` } // User представляет пользователя системы type User struct { ID uuid.UUID `json:"id" db:"id"` OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"` - Email string `json:"email" db:"email"` - Role string `json:"role" db:"role"` + Email string `json:"email" validate:"required,email"` + PasswordHash string `json:"-" db:"password_hash"` + Role string `json:"role"` CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // StorageLocation представляет место хранения type StorageLocation struct { - ID uuid.UUID `json:"id" db:"id"` - OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"` - ParentID *uuid.UUID `json:"parent_id" db:"parent_id"` - Name string `json:"name" db:"name"` - Address string `json:"address" db:"address"` - Type string `json:"type" db:"type"` - Coordinates map[string]any `json:"coordinates" db:"coordinates"` - QRCode string `json:"qr_code" db:"qr_code"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + ID uuid.UUID `json:"id" db:"id"` + OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"` + ParentID *uuid.UUID `json:"parent_id,omitempty" db:"parent_id"` + Name string `json:"name" validate:"required"` + Address string `json:"address" validate:"required"` + Type string `json:"type" validate:"required"` + Coordinates JSON `json:"coordinates"` + CreatedAt time.Time `json:"created_at" db:"created_at"` } // Item представляет товар/материал type Item struct { ID uuid.UUID `json:"id" db:"id"` OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"` - Name string `json:"name" db:"name"` - Description string `json:"description" db:"description"` - Category string `json:"category" db:"category"` + Name string `json:"name" validate:"required"` + Description string `json:"description"` + Category string `json:"category"` CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // ItemPlacement представляет размещение товара в месте хранения @@ -57,53 +53,64 @@ type ItemPlacement struct { OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"` ItemID uuid.UUID `json:"item_id" db:"item_id"` LocationID uuid.UUID `json:"location_id" db:"location_id"` - Quantity int `json:"quantity" db:"quantity"` + Quantity int `json:"quantity" validate:"min=1"` CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } +// JSON тип для JSON полей +type JSON map[string]interface{} + // LoginRequest запрос на аутентификацию type LoginRequest struct { - Email string `json:"email" binding:"required,email"` - Password string `json:"password" binding:"required"` + Email string `json:"email" validate:"required,email"` + Password string `json:"password" validate:"required"` +} + +// RegisterRequest запрос на регистрацию +type RegisterRequest struct { + OrganizationName string `json:"organization_name" validate:"required"` + UserEmail string `json:"user_email" validate:"required,email"` + UserPassword string `json:"user_password" validate:"required,min=8"` + OrganizationType string `json:"organization_type"` } // LoginResponse ответ на аутентификацию type LoginResponse struct { - Token string `json:"token"` - RefreshToken string `json:"refresh_token"` - User User `json:"user"` - ExpiresAt time.Time `json:"expires_at"` + Token string `json:"token"` + User User `json:"user"` + ExpiresAt time.Time `json:"expires_at"` } // CreateLocationRequest запрос на создание места хранения type CreateLocationRequest struct { - Name string `json:"name" binding:"required"` - Address string `json:"address" binding:"required"` - Type string `json:"type" binding:"required"` - ParentID *uuid.UUID `json:"parent_id"` - Coordinates map[string]any `json:"coordinates"` + Name string `json:"name" validate:"required"` + Address string `json:"address" validate:"required"` + Type string `json:"type" validate:"required"` + ParentID *uuid.UUID `json:"parent_id"` + Coordinates JSON `json:"coordinates"` } // CreateItemRequest запрос на создание товара type CreateItemRequest struct { - Name string `json:"name" binding:"required"` + Name string `json:"name" validate:"required"` Description string `json:"description"` - Category string `json:"category" binding:"required"` + Category string `json:"category"` } // PlaceItemRequest запрос на размещение товара type PlaceItemRequest struct { - ItemID uuid.UUID `json:"item_id" binding:"required"` - LocationID uuid.UUID `json:"location_id" binding:"required"` - Quantity int `json:"quantity" binding:"required,min=1"` + ItemID uuid.UUID `json:"item_id" validate:"required"` + LocationID uuid.UUID `json:"location_id" validate:"required"` + Quantity int `json:"quantity" validate:"required,min=1"` } // SearchRequest запрос на поиск type SearchRequest struct { - Query string `json:"query" binding:"required"` - Category string `json:"category"` - LocationID *uuid.UUID `json:"location_id"` + Query string `form:"q"` + Category string `form:"category"` + Address string `form:"address"` + Page int `form:"page,default=1"` + PageSize int `form:"page_size,default=20"` } // SearchResponse результат поиска @@ -114,7 +121,7 @@ type SearchResponse struct { // ItemWithLocation товар с информацией о месте размещения type ItemWithLocation struct { - Item Item `json:"item"` + Item Item `json:"item"` Location StorageLocation `json:"location"` - Quantity int `json:"quantity"` + Quantity int `json:"quantity"` } diff --git a/core-service/migrations/001_initial_schema.sql b/core-service/migrations/001_initial_schema.sql new file mode 100644 index 0000000..4160077 --- /dev/null +++ b/core-service/migrations/001_initial_schema.sql @@ -0,0 +1,72 @@ +-- Initial schema for ERP MVP +-- Migration: 001_initial_schema.sql + +-- Enable UUID extension +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; + +-- Organizations table +CREATE TABLE organizations ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + name VARCHAR(255) NOT NULL, + type VARCHAR(100), + settings JSONB, + created_at TIMESTAMP DEFAULT NOW() +); + +-- Users table +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE, + email VARCHAR(255) UNIQUE NOT NULL, + password_hash VARCHAR(255) NOT NULL, + role VARCHAR(50) DEFAULT 'user', + created_at TIMESTAMP DEFAULT NOW() +); + +-- Storage locations table +CREATE TABLE storage_locations ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE, + parent_id UUID REFERENCES storage_locations(id) ON DELETE CASCADE, + name VARCHAR(255) NOT NULL, + address VARCHAR(100) NOT NULL, + type VARCHAR(50) NOT NULL, + coordinates JSONB, + created_at TIMESTAMP DEFAULT NOW() +); + +-- Items table +CREATE TABLE items ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE, + name VARCHAR(255) NOT NULL, + description TEXT, + category VARCHAR(100), + created_at TIMESTAMP DEFAULT NOW() +); + +-- Item placements table +CREATE TABLE item_placements ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE, + item_id UUID REFERENCES items(id) ON DELETE CASCADE, + location_id UUID REFERENCES storage_locations(id) ON DELETE CASCADE, + quantity INTEGER DEFAULT 1, + created_at TIMESTAMP DEFAULT NOW() +); + +-- Indexes for better performance +CREATE INDEX idx_users_organization_id ON users(organization_id); +CREATE INDEX idx_users_email ON users(email); +CREATE INDEX idx_storage_locations_organization_id ON storage_locations(organization_id); +CREATE INDEX idx_storage_locations_parent_id ON storage_locations(parent_id); +CREATE INDEX idx_storage_locations_address ON storage_locations(address); +CREATE INDEX idx_items_organization_id ON items(organization_id); +CREATE INDEX idx_items_name ON items(name); +CREATE INDEX idx_items_category ON items(category); +CREATE INDEX idx_item_placements_organization_id ON item_placements(organization_id); +CREATE INDEX idx_item_placements_item_id ON item_placements(item_id); +CREATE INDEX idx_item_placements_location_id ON item_placements(location_id); + +-- Unique constraints +CREATE UNIQUE INDEX idx_storage_locations_org_address ON storage_locations(organization_id, address);