diff --git a/bin/copy/rapira/templates/.gitignore b/bin/copy/rapira/templates/.gitignore new file mode 100644 index 0000000..c270948 --- /dev/null +++ b/bin/copy/rapira/templates/.gitignore @@ -0,0 +1,7 @@ +.env +/bin/.env + +/.idea/ +.vscode +/log.txt +cover.out diff --git a/bin/copy/rapira/templates/Makefile_ b/bin/copy/rapira/templates/Makefile_ new file mode 100644 index 0000000..455fcb8 --- /dev/null +++ b/bin/copy/rapira/templates/Makefile_ @@ -0,0 +1,55 @@ +SERVICENAME=sync_service +SERVICEURL=github.com/ManyakRus/$(SERVICENAME) + +FILEMAIN=./cmd/$(SERVICENAME)/main.go +FILEAPP=./bin/$(SERVICENAME) + +NEW_REPO=$(SERVICENAME) + + +run: + clear + go build -race -o $(FILEAPP) $(FILEMAIN) + # cd ./bin && \ + ./bin/$(SERVICENAME) +mod: + clear + go get -u ./... + go mod tidy -compat=1.18 + go mod vendor + go fmt ./... +build: + clear + go build -race -o $(FILEAPP) $(FILEMAIN) + cd ./scripts && \ + ./VersionToFile.py + +lint: + clear + go fmt ./... + golangci-lint run ./internal/... + golangci-lint run ./pkg/... + gocyclo -over 10 ./internal + gocyclo -over 10 ./pkg + gocritic check ./internal/... + gocritic check ./pkg/... + staticcheck ./internal/... + staticcheck ./pkg/... +run.test: + clear + go fmt ./... + go test -coverprofile cover.out ./internal/v0/app/... + go tool cover -func=cover.out +newrepo: + sed -i 's+$(SERVICEURL)+$(NEW_REPO)+g' go.mod + find -name *.go -not -path "*/vendor/*"|xargs sed -i 's+$(SERVICEURL)+$(NEW_REPO)+g' +graph: + clear + image_packages ./ docs/packages.graphml +conn: + clear + image_connections ./internal docs/connections.graphml $(SERVICENAME) +init: + clear + go mod init gitlab.aescorp.ru/dsp_dev/claim/sync_service + go mod tidy \ No newline at end of file diff --git a/bin/copy/rapira/templates/bin/date.txt b/bin/copy/rapira/templates/bin/date.txt new file mode 100644 index 0000000..99a18f2 --- /dev/null +++ b/bin/copy/rapira/templates/bin/date.txt @@ -0,0 +1 @@ +2023-11-15 12:11:15.838 \ No newline at end of file diff --git a/bin/copy/rapira/templates/bin/settings.txt b/bin/copy/rapira/templates/bin/settings.txt new file mode 100644 index 0000000..01ca9cb --- /dev/null +++ b/bin/copy/rapira/templates/bin/settings.txt @@ -0,0 +1,29 @@ +STAGE="local" +LOG_LEVEL="debug" + +#---------------------Database settings--------------------- +#DB_HOST - Database server name or ip-address. Only Postgres SQL +DB_HOST="" + +#DB_NAME - Database table name +DB_NAME="" + +#DB_SCHEME - Database schema name +DB_SCHEME="public" + +#DB_PORT - Database port number +DB_PORT="5432" + +#DB_USER - Database login (user) +DB_USER="" + +#DB_PASSWORD - Database login password +DB_PASSWORD="" + + +#---------------------NATS messages broker settings--------------------- +NATS_HOST="" +NATS_PORT="" +NATS_LOGIN="" +NATS_PASSWORD="" + diff --git a/bin/copy/rapira/templates/bin/subversion.txt b/bin/copy/rapira/templates/bin/subversion.txt new file mode 100644 index 0000000..4424fb1 --- /dev/null +++ b/bin/copy/rapira/templates/bin/subversion.txt @@ -0,0 +1 @@ +00133 \ No newline at end of file diff --git a/bin/copy/rapira/templates/bin/version.txt b/bin/copy/rapira/templates/bin/version.txt new file mode 100644 index 0000000..a5e11e5 --- /dev/null +++ b/bin/copy/rapira/templates/bin/version.txt @@ -0,0 +1 @@ +v0 \ No newline at end of file diff --git a/bin/copy/rapira/templates/cmd/main.go_ b/bin/copy/rapira/templates/cmd/main.go_ new file mode 100644 index 0000000..f7e8337 --- /dev/null +++ b/bin/copy/rapira/templates/cmd/main.go_ @@ -0,0 +1,27 @@ +package main + +import ( + configmain "github.com/ManyakRus/starter/config" + "github.com/ManyakRus/starter/stopapp" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/crud_starter" +) + +// main - старт приложения +func main() { + StartApp() +} + +// StartApp - выполнение всех операций для старта приложения +func StartApp() { + configmain.LoadEnv() + + stopapp.StartWaitStop() + crud_starter.InitCrudTransport_DB() + postgres_gorm.StartDB() + server_grpc.Start() + server_nrpc.Start() + + stopapp.GetWaitGroup_Main().Wait() + +} + diff --git a/bin/copy/rapira/templates/configs_/convert_id.json b/bin/copy/rapira/templates/configs_/convert_id.json new file mode 100644 index 0000000..20cdc5b --- /dev/null +++ b/bin/copy/rapira/templates/configs_/convert_id.json @@ -0,0 +1,11 @@ +{ + "lawsuit_payments.id": "alias.PaymentId", + "invoice_debt_type_stats.invoice_id": "alias.InvoiceId", + "invoice_debt_type_stats.lawsuit_id": "alias.LawsuitId", + "contract_black_items.contract_number": "alias.ContractNumber", + "contract_white_items.contract_number": "alias.ContractNumber", + "lawsuits.number_claim": "alias.ClaimNumber", + "lawsuits.number": "alias.LawsuitNumber", + "contracts.number": "alias.ContractNumber" +} + diff --git a/bin/copy/rapira/templates/configs_/mapping.json b/bin/copy/rapira/templates/configs_/mapping.json new file mode 100644 index 0000000..7f5fd24 --- /dev/null +++ b/bin/copy/rapira/templates/configs_/mapping.json @@ -0,0 +1,571 @@ +{ + "mappings": [ + { + "sql_type": "bit", + "go_type": "bool", + "json_type": "Boolean", + "protobuf_type": "bool", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullBool", + "swagger_type": "bool" + }, + { + "sql_type": "bool", + "go_type": "bool", + "json_type": "Boolean", + "protobuf_type": "bool", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullBool", + "swagger_type": "bool" + }, + { + "sql_type": "tinyint", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "int", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "smallint", + "size": 2, + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "mediumint", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "int4", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "int2", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "integer", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "bigint", + "go_type": "int64", + "json_type": "Integer", + "protobuf_type": "int64", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int64" + }, + { + "sql_type": "int8", + "go_type": "int64", + "json_type": "Integer", + "protobuf_type": "int64", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int64" + }, + { + "sql_type": "char", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "enum", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "varchar", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "nvarchar", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "longtext", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "mediumtext", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "text", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "tinytext", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "varchar2", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "inet", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "json", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "datatypes.JSON", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "jsonb", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "datatypes.JSON", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "nchar", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "date", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "datetime2", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "datetime", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "time", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "timestamp", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "uint64", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "timestamptz", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "uint64", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "smalldatetime", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "decimal", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "double", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "money", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "real", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "float4", + "go_type": "float32", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float32" + }, + + { + "sql_type": "float", + "go_type": "float32", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float32" + }, + { + "sql_type": "float8", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + + { + "sql_type": "binary", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "blob", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "longblob", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "mediumblob", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "varbinary", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "numeric", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "bpchar", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "tsvector", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "_text", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "bytea", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "USER_DEFINED", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "interface{}", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "uuid", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "interface{}", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "utinyint", + "go_type": "uint32", + "json_type": "Integer", + "protobuf_type": "uint32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "usmallint", + "go_type": "uint32", + "json_type": "Integer", + "protobuf_type": "uint32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "umediumint", + "go_type": "uint32", + "json_type": "Integer", + "protobuf_type": "uint32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "uint", + "go_type": "uint32", + "json_type": "Integer", + "protobuf_type": "uint32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "ubigint", + "go_type": "uint64", + "json_type": "Integer", + "protobuf_type": "uint64", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int64" + }, + { + "sql_type": "udecimal", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "udouble", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "ufloat", + "go_type": "float32", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float32" + }, + { + "sql_type": "smallserial", + "size": 2, + "custom": "postgres", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "serial", + "size": 4, + "custom": "postgres", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "bigserial", + "size": 8, + "custom": "postgres", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + } + ] +} diff --git a/bin/copy/rapira/templates/configs_/name_replace.json b/bin/copy/rapira/templates/configs_/name_replace.json new file mode 100644 index 0000000..cab0526 --- /dev/null +++ b/bin/copy/rapira/templates/configs_/name_replace.json @@ -0,0 +1,19 @@ +{ + "inn": "INN", + "kpp": "KPP", + "okpo": "OKPO", + "ogrn": "OGRN", + "okato": "OKATO", + "nsi_flat": "NSIFlat", + "nsi_flat_id": "NSIFlatID", + "nsi_id": "NSIID", + "www": "WWW", + "bik": "BIK", + "city_name": "City", + "edms_link": "EDMSLink", + "code_nsi": "CodeNSI", + "json_updated_at": "JSONUpdatedAt", + "pdf_updated_at": "PDFUpdatedAt", + "pdf_file_id": "PDFFileID", + "json_file_id": "JSONFileID" +} \ No newline at end of file diff --git a/bin/copy/rapira/templates/configs_/nullable.json b/bin/copy/rapira/templates/configs_/nullable.json new file mode 100644 index 0000000..1e5062a --- /dev/null +++ b/bin/copy/rapira/templates/configs_/nullable.json @@ -0,0 +1,4 @@ +{ + "ExtID": true, + "CreatedAt": false +} diff --git a/bin/copy/rapira/templates/configs_/readme.txt b/bin/copy/rapira/templates/configs_/readme.txt new file mode 100644 index 0000000..ce1442e --- /dev/null +++ b/bin/copy/rapira/templates/configs_/readme.txt @@ -0,0 +1,21 @@ +convert_id.json: +Mapping database table name . field name = field type in golang. +For model file. +For non standart rare case or type aliases + + +mapping.json +Mapping Postgres types to Golang types + + +name_replace.json +Mapping database field name = golang field name +For model file. +Replace standart field name to filled name +For non standart rare case. + + +nullable.json +List of golang field names, which need change 0 to null. +true = need change 0 to null +For non standart rare case. diff --git a/bin/copy/rapira/templates/internal/server_grpc/server_grpc.go_ b/bin/copy/rapira/templates/internal/server_grpc/server_grpc.go_ new file mode 100644 index 0000000..a6b7695 --- /dev/null +++ b/bin/copy/rapira/templates/internal/server_grpc/server_grpc.go_ @@ -0,0 +1,283 @@ +package server_grpc + +import ( + "context" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" +) + +// LawsuitStatusType_Read - читает и возвращает модель из БД +func (s *ServerGRPC) LawsuitStatusType_Read(ctx context.Context, Request *grpc_proto.RequestId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ID = Request.Id + err = Model.Read() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Delete - записывает в БД is_deleted = true и возвращает модель из БД +func (s *ServerGRPC) LawsuitStatusType_Delete(ctx context.Context, Request *grpc_proto.RequestId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ID = Request.Id + err = Model.Delete() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Restore - записывает в БД is_deleted = false и возвращает модель из БД +func (s *ServerGRPC) LawsuitStatusType_Restore(ctx context.Context, Request *grpc_proto.RequestId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ID = Request.Id + err = Model.Restore() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Create - создаёт новую запись в БД +func (s *ServerGRPC) LawsuitStatusType_Create(ctx context.Context, Request *grpc_proto.RequestModel) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //получим модель из строки JSON + Model := &lawsuit_status_types.LawsuitStatusType{} + err = Model.GetModelFromJSON(Request.ModelString) + if err != nil { + return &Otvet, err + } + + //запрос в БД + err = Model.Create() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Update - обновляет новую запись в БД +func (s *ServerGRPC) LawsuitStatusType_Update(ctx context.Context, Request *grpc_proto.RequestModel) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //получим модель из строки JSON + Model := &lawsuit_status_types.LawsuitStatusType{} + err = Model.GetModelFromJSON(Request.ModelString) + if err != nil { + return &Otvet, err + } + + //запрос в БД + err = Model.Update() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Save - записывает (создаёт или обновляет) запись в БД +func (s *ServerGRPC) LawsuitStatusType_Save(ctx context.Context, Request *grpc_proto.RequestModel) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //получим модель из строки JSON + Model := lawsuit_status_types.LawsuitStatusType{} + err = Model.GetModelFromJSON(Request.ModelString) + if err != nil { + return &Otvet, err + } + + //запрос в БД + err = Model.Save() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_FindByExtID - возвращает запись из БД по ext_id и connection_id +func (s *ServerGRPC) LawsuitStatusType_FindByExtID(ctx context.Context, Request *grpc_proto.RequestExtId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ExtID = Request.ExtId + Model.ConnectionID = Request.ConnectionId + err = Model.Find_ByExtID() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + diff --git a/bin/copy/rapira/templates/internal/server_grpc/server_grpc_func.go b/bin/copy/rapira/templates/internal/server_grpc/server_grpc_func.go new file mode 100644 index 0000000..f964de6 --- /dev/null +++ b/bin/copy/rapira/templates/internal/server_grpc/server_grpc_func.go @@ -0,0 +1,18 @@ +package server_grpc + +import ( + "errors" + "github.com/ManyakRus/starter/micro" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client/constants" +) + +// ErrorModelVersion +func ErrorModelVersion(Model interface{}) error { + var err error + + TypeName := micro.GetType(Model) + + s := constants.TEXT_ERROR_MODEL_VERSION + " " + TypeName + err = errors.New(s) + return err +} diff --git a/bin/copy/rapira/templates/internal/server_grpc/server_grpc_starter.go_ b/bin/copy/rapira/templates/internal/server_grpc/server_grpc_starter.go_ new file mode 100644 index 0000000..0f0b134 --- /dev/null +++ b/bin/copy/rapira/templates/internal/server_grpc/server_grpc_starter.go_ @@ -0,0 +1,95 @@ +package server_grpc + +import ( + "github.com/ManyakRus/starter/contextmain" + "github.com/ManyakRus/starter/log" + "github.com/ManyakRus/starter/stopapp" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "google.golang.org/grpc" + "net" + "os" +) + +// ServerGRPC is used to implement UnimplementedSyncServiceServer. +type ServerGRPC struct { + grpc_proto.UnimplementedSyncServiceServer +} + +type SettingsINI struct { + GRPC_PORT string +} + +var Settings SettingsINI + +var Conn *grpc.Server + +func Connect() { + //var err error + + if Settings.GRPC_PORT == "" { + FillSettings() + } + + Conn = grpc.NewServer() + grpc_proto.RegisterSyncServiceServer(Conn, &ServerGRPC{}) + + stopapp.GetWaitGroup_Main().Add(1) + go serve_go() + +} + +func serve_go() { + defer stopapp.GetWaitGroup_Main().Done() + + lis, err := net.Listen("tcp", ":"+Settings.GRPC_PORT) + if err != nil { + log.Fatalf("failed to listen: %v", err) + } + + log.Printf("Server GRPC listening at %v", lis.Addr()) + if err := Conn.Serve(lis); err != nil { + log.Fatalf("failed to serve: %v", err) + } + + return +} + +func FillSettings() { + Settings = SettingsINI{} + Settings.GRPC_PORT = os.Getenv("GRPC_PORT") + if Settings.GRPC_PORT == "" { + log.Panic("Need fill GRPC_PORT ! in OS Environment ") + } + +} + +// WaitStop - ожидает отмену глобального контекста +func WaitStop() { + defer stopapp.GetWaitGroup_Main().Done() + + select { + case <-contextmain.GetContext().Done(): + log.Warn("Context app is canceled. grpc_connect") + } + + //ждём пока отправляемых сейчас сообщений будет =0 + stopapp.WaitTotalMessagesSendingNow("grpc_connect") + + //закрываем соединение + CloseConnection() + +} + +// Start - необходимые процедуры для запуска сервера GRPC +func Start() { + Connect() + + stopapp.GetWaitGroup_Main().Add(1) + go WaitStop() + +} + +func CloseConnection() { + Conn.Stop() +} + diff --git a/bin/copy/rapira/templates/internal/server_grpc/server_grpc_test.go_ b/bin/copy/rapira/templates/internal/server_grpc/server_grpc_test.go_ new file mode 100644 index 0000000..edcc42c --- /dev/null +++ b/bin/copy/rapira/templates/internal/server_grpc/server_grpc_test.go_ @@ -0,0 +1,193 @@ +package server_grpc + +import ( + "context" + "github.com/ManyakRus/starter/config" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/crud_starter" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" + "testing" +) + +// LawsuitStatusType_ID_Test - ID таблицы для тестирования +const LawsuitStatusType_ID_Test = 1 + +func Test_server_LawsuitStatusType_Read(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Otvet, err := server1.LawsuitStatusType_Read(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Read() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Read() error: ModelString=''") + } +} + +func Test_server_LawsuitStatusType_Delete(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Otvet, err := server1.LawsuitStatusType_Delete(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Delete() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Delete() error: ModelString=''") + } + Otvet, err = server1.LawsuitStatusType_Restore(ctx, &Request) +} + +func Test_server_LawsuitStatusType_Create(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + var ModelString string + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = 1 + ModelString, err := Model.GetJSON() + if err != nil { + t.Error("Test_server_LawsuitStatusType_Create() error: ", err) + return + } + + RequestModel := grpc_proto.RequestModel{} + RequestModel.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + RequestModel.ModelString = ModelString + + ctx := context.Background() + server1 := &ServerGRPC{} + Otvet, err := server1.LawsuitStatusType_Create(ctx, &RequestModel) + if err == nil { + t.Error("Test_server_LawsuitStatusType_Create() error: ", err) + } + if Otvet.ModelString != "" { + t.Error("Test_server_LawsuitStatusType_Create() error: ModelString !=''") + } +} + +func Test_server_LawsuitStatusType_Update(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Response1, err := server1.LawsuitStatusType_Read(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Update() error: ", err) + return + } + if Response1.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Update() error: ModelString=''") + } + + var ModelString string + ModelString = Response1.ModelString + + RequestModel := grpc_proto.RequestModel{} + RequestModel.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + RequestModel.ModelString = ModelString + + Otvet, err := server1.LawsuitStatusType_Update(ctx, &RequestModel) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Update() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Update() error: ModelString=''") + } + +} + +func Test_server_LawsuitStatusType_Save(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Response1, err := server1.LawsuitStatusType_Read(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Save() error: ", err) + return + } + + var ModelString string + ModelString = Response1.ModelString + + // sModel, _ := GetJSON(Otvet) + RequestModel := grpc_proto.RequestModel{} + RequestModel.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + RequestModel.ModelString = ModelString + + Otvet, err := server1.LawsuitStatusType_Save(ctx, &RequestModel) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Save() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Save() error: ModelString=''") + } + +} + +func Test_server_LawsuitStatusType_FindByExtID(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Otvet1, err := server1.LawsuitStatusType_Read(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_FindByExtID() error: ", err) + } + + // получим модель из строки JSON + Model := lawsuit_status_types.LawsuitStatusType{} + err = Model.GetModelFromJSON(Otvet1.ModelString) + if err != nil { + t.Error("Test_server_LawsuitStatusType_FindByExtID() GetModelFromJSON() error: ", err) + } + + if Model.ExtID == 0 { + return + } + + + ctx = context.Background() + RequestExtId:= grpc_proto.RequestExtId{} + RequestExtId.ExtId = Model.ExtID + RequestExtId.ConnectionId = Model.ConnectionID + RequestExtId.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + Otvet, err := server1.LawsuitStatusType_FindByExtID(ctx, &RequestExtId) + if err != nil { + t.Error("Test_server_LawsuitStatusType_FindByExtId() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_FindByExtId() error: ModelString=''") + } +} + diff --git a/bin/copy/rapira/templates/internal/server_nrpc/server_nrpc_starter.go_ b/bin/copy/rapira/templates/internal/server_nrpc/server_nrpc_starter.go_ new file mode 100644 index 0000000..0c69729 --- /dev/null +++ b/bin/copy/rapira/templates/internal/server_nrpc/server_nrpc_starter.go_ @@ -0,0 +1,117 @@ +package server_grpc + +import ( + "github.com/ManyakRus/starter/contextmain" + "github.com/ManyakRus/starter/log" + "github.com/ManyakRus/starter/stopapp" + "github.com/nats-io/nats.go" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/internal/app/grpc/server_grpc" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "os" + "time" +) + +type SettingsINI struct { + NATS_HOST string + NATS_PORT string +} + +var Settings SettingsINI + +// Conn - подключение к NATS +var Conn *nats.Conn + +// NRPCSubscription - подписка на топик NATS +var NRPCSubscription *nats.Subscription + +type server struct{} + +func Connect() { + var err error + + if Settings.NATS_HOST == "" { + FillSettings() + } + + NatsURL := "nats://" + Settings.NATS_HOST + ":" + Settings.NATS_PORT + // Connect to the NATS server. + Conn, err := nats.Connect(NatsURL, nats.Timeout(60*time.Second)) + if err != nil { + log.Panic(err) + } + //defer Conn.Close() + + // Our server implementation. + s := &server_grpc.ServerGRPC{} + //s := &server{} + + // The NATS handler from the helloworld.nrpc.proto file. + h := grpc_proto.NewSync_serviceHandler(contextmain.GetContext(), Conn, s) + + // Start a NATS subscription using the handler. You can also use the + // QueueSubscribe() method for a load-balanced set of servers. + NRPCSubscription2, err := Conn.Subscribe(h.Subject(), h.Handler) + if err != nil { + log.Panic(err) + } + if NRPCSubscription2 == nil { + log.Panic(err) + } + NRPCSubscription = NRPCSubscription2 + + log.Info("Server NRPC started. NATS: ", NatsURL) +} + +// FillSettings - заполняет настройки из переменных окружения +func FillSettings() { + Settings = SettingsINI{} + Settings.NATS_HOST = os.Getenv("BUS_LOCAL_HOST") + Settings.NATS_PORT = os.Getenv("BUS_LOCAL_PORT") + + if Settings.NATS_HOST == "" { + log.Panic("Need fill BUS_LOCAL_HOST ! in OS Environment ") + } + + if Settings.NATS_PORT == "" { + log.Panic("Need fill BUS_LOCAL_PORT ! in OS Environment ") + } +} + +// WaitStop - ожидает отмену глобального контекста +func WaitStop() { + + select { + case <-contextmain.GetContext().Done(): + log.Warn("Context app is canceled. nrpc server connect") + } + + //ждём пока отправляемых сейчас сообщений будет =0 + stopapp.WaitTotalMessagesSendingNow("nrpc server connect") + + //закрываем соединение + CloseConnection() + stopapp.GetWaitGroup_Main().Done() +} + +// Start - необходимые процедуры для запуска сервера GRPC +func Start() { + Connect() + + stopapp.GetWaitGroup_Main().Add(1) + go WaitStop() + +} + +func CloseConnection() { + if NRPCSubscription != nil { + NRPCSubscription.Unsubscribe() + } + Conn.Close() + log.Info("Server NRPC connection closed") +} + +//func (s *server) Read(ctx context.Context, Reques *grpc_proto.RequestId) *grpc_proto.Response { +// var Otvet *grpc_proto.Response +// +// return Otvet +//} diff --git a/bin/copy/rapira/templates/internal/server_nrpc/server_nrpc_starter_test.go b/bin/copy/rapira/templates/internal/server_nrpc/server_nrpc_starter_test.go new file mode 100644 index 0000000..1d47b1f --- /dev/null +++ b/bin/copy/rapira/templates/internal/server_nrpc/server_nrpc_starter_test.go @@ -0,0 +1,14 @@ +package server_grpc + +import ( + config_main "github.com/ManyakRus/starter/config" + "testing" +) + +func TestConnect(t *testing.T) { + config_main.LoadEnv() + FillSettings() + + Connect() + CloseConnection() +} diff --git a/bin/copy/rapira/templates/pkg/crud_starter/crud_starter_manual.go b/bin/copy/rapira/templates/pkg/crud_starter/crud_starter_manual.go new file mode 100644 index 0000000..f647a6c --- /dev/null +++ b/bin/copy/rapira/templates/pkg/crud_starter/crud_starter_manual.go @@ -0,0 +1,15 @@ +package crud_starter + +import () + +// initCrudTransport_manual_DB - заполняет объекты crud для работы с БД напрямую +func initCrudTransport_manual_DB() { +} + +// initCrudTransport_manual_GRPC - заполняет объекты crud для работы с БД напрямую +func initCrudTransport_manual_GRPC() { +} + +// initCrudTransport_manual_NRPC - заполняет объекты crud для работы с БД напрямую +func initCrudTransport_manual_NRPC() { +} diff --git a/bin/copy/rapira/templates/pkg/db/constants/constants.go b/bin/copy/rapira/templates/pkg/db/constants/constants.go new file mode 100644 index 0000000..d8a63a6 --- /dev/null +++ b/bin/copy/rapira/templates/pkg/db/constants/constants.go @@ -0,0 +1,7 @@ +package constants + +const CONNECTION_ID_TEST = 3 + +const TIMEOUT_DB_SECONDS = 30 + +const TEXT_RECORD_NOT_FOUND = "record not found" diff --git a/bin/copy/rapira/templates/pkg/db/db.go_ b/bin/copy/rapira/templates/pkg/db/db.go_ new file mode 100644 index 0000000..52e2c1b --- /dev/null +++ b/bin/copy/rapira/templates/pkg/db/db.go_ @@ -0,0 +1,317 @@ +package db_lawsuit_status_types + +import ( + "context" + "errors" + "fmt" + "github.com/ManyakRus/starter/micro" + "github.com/ManyakRus/starter/postgres_gorm" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" + "gorm.io/gorm" + "time" + "github.com/ManyakRus/starter/contextmain" +) + +// TableName - имя таблицы в БД Postgres +const TableName string = "lawsuit_status_types" + +// Crud_DB - объект для CRUD операций через БД +type Crud_DB struct { +} + +// Read - находит запись в БД по ID +func (crud Crud_DB) Read(m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err = crud.Read_ctx(ctx, m) + return err +} + +// Read_ctx - находит запись в БД по ID +func (crud Crud_DB) Read_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + id := int64(m.ID) + + db := postgres_gorm.GetConnection() + db.WithContext(ctx) + + tx := db.First(m, id) + err = tx.Error + + return err +} + +// Save - записывает новый или существующий объект в базу данных +func (crud Crud_DB) Save(m *lawsuit_status_types.LawsuitStatusType) error { + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err := crud.Save_ctx(ctx, m) + return err +} + +// Save_ctx - записывает новый или существующий объект в базу данных +func (crud Crud_DB) Save_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + is_create := !micro.BoolFromInt64(int64(m.ID)) + err = crud.create_update_ctx(ctx, m, is_create) + return err +} + +// Update - записывает существующий объект в базу данных +func (crud Crud_DB) Update(m *lawsuit_status_types.LawsuitStatusType) error { + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err := crud.Update_ctx(ctx, m) + return err +} + +// Update_ctx - записывает существующий объект в базу данных +func (crud Crud_DB) Update_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + err = crud.create_update_ctx(ctx, m, false) + return err +} + +// Create - записывает новый объект в базу данных +func (crud Crud_DB) Create(m *lawsuit_status_types.LawsuitStatusType) error { + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err := crud.Create_ctx(ctx, m) + return err +} + +// Create_ctx - записывает новый объект в базу данных +func (crud Crud_DB) Create_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + err = crud.create_update_ctx(ctx, m, true) + return err +} + +// create_update - записывает объект в базу данных +func (crud Crud_DB) create_update(m *lawsuit_status_types.LawsuitStatusType, is_create bool) error { + var err error + + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err = crud.create_update_ctx(ctx, m, is_create) + return err +} + +// create_update_ctx - записывает объект в базу данных +func (crud Crud_DB) create_update_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType, is_create bool) error { + var err error + + // log.Trace("start Save() ", TableName, " id: ", int64(m.ID)) + + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + // проверка ID + if is_create == true { + if int64(m.ID) != 0 { + TextError := fmt.Sprint("db.Save() ", TableName, " error: id !=0") + // log.Panic(sError) + err = errors.New(TextError) + return err + } + } else if int64(m.ID) == 0 { + TextError := fmt.Sprint("db.Save() ", TableName, " error: id =0") + err = errors.New(TextError) + // log.Panic(sError) + return err + } + + // + db := postgres_gorm.GetConnection() + db.WithContext(ctx) + + // заполним даты + //Text_modified_at + //Text_is_deleted_deleted_at + + //колонки с null + tx := db + MassOmit := make([]string, 0) + var ColumnName string + + + //игнор пустых колонок + tx = tx.Omit(MassOmit...) + + // запись + if is_create == true { + tx = tx.Create(&m) + } else { + tx = tx.Save(&m) + } + err = tx.Error + if err != nil { + return err + } + + // запишем NULL в пустые колонки + for f := 0; f < len(MassOmit); f++ { + ColumnName := MassOmit[f] + tx = db.Model(&m).Update(ColumnName, gorm.Expr("NULL")) + + err = tx.Error + if err != nil { + TextError := fmt.Sprint("db.Update() ", TableName, " id: ", m.ID, " error: ", err) + err = errors.New(TextError) + return err + // log.Panic(sError) + } + } + + return err +} + +// Delete - записывает is_deleted = true +func (crud Crud_DB) Delete(m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err = crud.Delete_ctx(ctx, m) + return err +} + +// Delete_ctx - записывает is_deleted = true +func (crud Crud_DB) Delete_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + m2 := lawsuit_status_types.LawsuitStatusType{} + m2.ID = m.ID + err = crud.Read_ctx(ctx, &m2) + if err != nil { + return err + } + + m2.IsDeleted = true + m.IsDeleted = true + + err = crud.Save_ctx(ctx, &m2) + + return err +} + +// Restore - записывает is_deleted = true +func (crud Crud_DB) Restore(m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err = crud.Restore_ctx(ctx, m) + return err +} + +// Restore_ctx - записывает is_deleted = true +func (crud Crud_DB) Restore_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + m2 := lawsuit_status_types.LawsuitStatusType{} + m2.ID = m.ID + err = crud.Read_ctx(ctx, &m2) + if err != nil { + return err + } + + m2.IsDeleted = false + m.IsDeleted = false + + err = crud.Save_ctx(ctx, &m2) + + return err +} + +// Find_ByExtID - находит запись в БД по ext_id и connection_id +func (crud Crud_DB) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if m.ExtID == 0 { + err = errors.New("Error: ext_id =0") + return err + } + + // + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err = crud.Find_ByExtID_ctx(ctx, m) + + return err +} + +// Find_ByExtID_ctx - находит запись в БД по ext_id и connection_id +func (crud Crud_DB) Find_ByExtID_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + if m.ExtID == 0 { + err = errors.New("Error: ExtID=0") + return err + } + + db := postgres_gorm.GetConnection() + db.WithContext(ctx) + + tx := db.Where("ext_id = ?", m.ExtID).Where("connection_id = ?", m.ConnectionID).First(m) + err = tx.Error + + return err +} diff --git a/bin/copy/rapira/templates/pkg/db/db_test.go_ b/bin/copy/rapira/templates/pkg/db/db_test.go_ new file mode 100644 index 0000000..e943429 --- /dev/null +++ b/bin/copy/rapira/templates/pkg/db/db_test.go_ @@ -0,0 +1,124 @@ +package db_lawsuit_status_types + +import ( + "github.com/ManyakRus/starter/config" + "github.com/ManyakRus/starter/postgres_gorm" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" + "testing" +) + +const Postgres_ID_Test = 1 + +func TestRead(t *testing.T) { + config.LoadEnv() + + postgres_gorm.Connect() + defer postgres_gorm.CloseConnection() + + crud := Crud_DB{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestRead() error: ", err) + } + + if Otvet.ID == 0 { + t.Error(TableName + "_test.TestRead() error ID=0 ") + } else { + t.Log(TableName+"_test.TestRead() Otvet: ", Otvet.ID) + } +} + +func TestSave(t *testing.T) { + config.LoadEnv() + + postgres_gorm.Connect() + defer postgres_gorm.CloseConnection() + + crud := Crud_DB{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestSave() error: ", err) + } + + if Otvet.ID == 0 { + t.Error(TableName + "_test.TestSave() error ID=0 ") + } + + err = crud.Save(&Otvet) + if err != nil { + t.Error("TestSave() error: ", err) + } + t.Log(TableName+"_test.TestSave() Otvet: ", Otvet.ID) + +} + +func TestDelete(t *testing.T) { + config.LoadEnv() + + postgres_gorm.Connect() + defer postgres_gorm.CloseConnection() + + crud := Crud_DB{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + + if Otvet.IsDeleted == false { + err = crud.Delete(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + + err = crud.Restore(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + } else { + err = crud.Restore(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + + err = crud.Delete(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + + } + +} + + +func TestFind_ByExtID(t *testing.T) { + config.LoadEnv() + postgres_gorm.Connect() + defer postgres_gorm.CloseConnection() + + crud := Crud_DB{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestFind_ByExtID() error: ", err) + } + + if Otvet.ExtID ==0 { + return + } + + err = crud.Find_ByExtID(&Otvet) + if err != nil { + t.Error("TestFind_ByExtID() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestFind_ByExtID() error: ID =0") + } +} diff --git a/bin/copy/rapira/templates/pkg/db/is_deleted.go_ b/bin/copy/rapira/templates/pkg/db/is_deleted.go_ new file mode 100644 index 0000000..adc19f4 --- /dev/null +++ b/bin/copy/rapira/templates/pkg/db/is_deleted.go_ @@ -0,0 +1,5 @@ +if m.IsDeleted == true && m.DeletedAt.IsZero() == true { + m.DeletedAt = time.Now() + } else if m.IsDeleted == false && m.DeletedAt.IsZero() == false { + m.DeletedAt = time.Time{} + } diff --git a/bin/copy/rapira/templates/pkg/db/modified_at.go_ b/bin/copy/rapira/templates/pkg/db/modified_at.go_ new file mode 100644 index 0000000..f648e98 --- /dev/null +++ b/bin/copy/rapira/templates/pkg/db/modified_at.go_ @@ -0,0 +1 @@ +m.ModifiedAt = time.Now() \ No newline at end of file diff --git a/bin/copy/rapira/templates/pkg/functions/calc_struct_version/calc_struct_version.go b/bin/copy/rapira/templates/pkg/functions/calc_struct_version/calc_struct_version.go new file mode 100644 index 0000000..ea44705 --- /dev/null +++ b/bin/copy/rapira/templates/pkg/functions/calc_struct_version/calc_struct_version.go @@ -0,0 +1,24 @@ +package calc_struct_version + +import ( + "github.com/ManyakRus/starter/micro" + "reflect" +) + +// CalcStructVersion - вычисляет версию модели +func CalcStructVersion(t reflect.Type) uint32 { + var ReturnVar uint32 + + names := make([]string, t.NumField()) + + // имя + тип поля + s := "" + for i := range names { + s = s + t.Field(i).Name + s = s + t.Field(i).Type.Name() + } + + ReturnVar = micro.Hash(s) + + return ReturnVar +} diff --git a/bin/copy/rapira/templates/pkg/functions/calc_struct_version/calc_struct_version_test.go b/bin/copy/rapira/templates/pkg/functions/calc_struct_version/calc_struct_version_test.go new file mode 100644 index 0000000..b94001d --- /dev/null +++ b/bin/copy/rapira/templates/pkg/functions/calc_struct_version/calc_struct_version_test.go @@ -0,0 +1 @@ +package calc_struct_version diff --git a/bin/copy/rapira/templates/pkg/network/grpc/constants/constants.go b/bin/copy/rapira/templates/pkg/network/grpc/constants/constants.go new file mode 100644 index 0000000..809887d --- /dev/null +++ b/bin/copy/rapira/templates/pkg/network/grpc/constants/constants.go @@ -0,0 +1,5 @@ +package constants + +var TIMEOUT_SECONDS = 30 + +const TEXT_ERROR_MODEL_VERSION = "Error: wrong version object model" diff --git a/bin/templates/api/generation_code.sh_ b/bin/copy/rapira/templates/pkg/network/grpc/generation_code.sh_ similarity index 100% rename from bin/templates/api/generation_code.sh_ rename to bin/copy/rapira/templates/pkg/network/grpc/generation_code.sh_ diff --git a/bin/copy/rapira/templates/pkg/network/grpc/grpc_client/grpc_client.go_ b/bin/copy/rapira/templates/pkg/network/grpc/grpc_client/grpc_client.go_ new file mode 100644 index 0000000..9c298e2 --- /dev/null +++ b/bin/copy/rapira/templates/pkg/network/grpc/grpc_client/grpc_client.go_ @@ -0,0 +1,322 @@ +package grpc_lawsuit_status_types + +import ( + "context" + "encoding/json" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client/constants" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" + "log" + "time" +) + +// VersionModel - хранит версию структуры модели +var VersionModel uint32 + +// TableName - имя таблицы в БД Postgres +const TableName string = "lawsuit_status_types" + +// объект для CRUD операций через GRPC +type Crud_GRPC struct { +} + +// GetVersionModel - возвращает хэш версии структуры модели +func (crud Crud_GRPC) GetVersionModel() uint32 { + if VersionModel == 0 { + VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + } + return VersionModel +} + +// Read - возвращает модель из БД +func (crud Crud_GRPC) Read(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + Response, err := grpc_client.Client.LawsuitStatusType_Read(ctx, Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Create - записывает новую модель в БД +func (crud Crud_GRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + Response, err := grpc_client.Client.LawsuitStatusType_Create(ctx, Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Update - обновляет модель в БД +func (crud Crud_GRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + Response, err := grpc_client.Client.LawsuitStatusType_Update(ctx, Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Save - обновляет (или создаёт) модель в БД +func (crud Crud_GRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + Response, err := grpc_client.Client.LawsuitStatusType_Save(ctx, Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Delete - устанавливает is_deleted = true в БД +func (crud Crud_GRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + Response, err := grpc_client.Client.LawsuitStatusType_Delete(ctx, Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Restore - устанавливает is_deleted = false в БД +func (crud Crud_GRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + Response, err := grpc_client.Client.LawsuitStatusType_Restore(ctx, Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Find_ByExtID - находит модель в БД по ext_id и connection_id +func (crud Crud_GRPC) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error { + //подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + //подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestExtId{} + Request.ExtId = m.ExtID + Request.ConnectionId = m.ConnectionID + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + //запрос + Response, err := grpc_client.Client.LawsuitStatusType_FindByExtID(ctx, Request) + if err != nil { + sError := err.Error() + if sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + //ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + diff --git a/bin/copy/rapira/templates/pkg/network/grpc/grpc_client/grpc_client_test.go_ b/bin/copy/rapira/templates/pkg/network/grpc/grpc_client/grpc_client_test.go_ new file mode 100644 index 0000000..cf7637d --- /dev/null +++ b/bin/copy/rapira/templates/pkg/network/grpc/grpc_client/grpc_client_test.go_ @@ -0,0 +1,185 @@ +package grpc_lawsuit_status_types + +import ( + config "github.com/ManyakRus/starter/config" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" + "testing" +) + +// Postgres_ID_Test - ID таблицы для тестирования +const Postgres_ID_Test = 1 + +func TestGetVersionModel(t *testing.T) { + + crud := Crud_GRPC{} + Otvet := crud.GetVersionModel() + if Otvet == 0 { + t.Error("TestGetVersionModel() error: Otvet =0") + } +} + +func TestRead(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + crud := Crud_GRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + + if err != nil { + t.Error("TestRead() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestRead() error: ID =0") + } +} + +func TestCreate(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = -1 + + crud := Crud_GRPC{} + err := crud.Create(&Model) + + if err == nil { + t.Error("TestCreate() error: ", err) + } + + if Model.ID > 0 { + t.Error("TestCreate() error: ID >0") + } +} + +func TestUpdate(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = 0 + + crud := Crud_GRPC{} + err := crud.Update(&Model) + + if err == nil { + t.Error("TestUpdate() error: ", err) + } + + if Model.ID != 0 { + t.Error("TestUpdate() error: ID =0") + } +} + +func TestSave(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + crud := Crud_GRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestSave() error: ", err) + return + } + + err = crud.Save(&Otvet) + + if err != nil { + t.Error("TestSave() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestSave() error: ID =0") + } +} + +func TestDelete(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + crud := Crud_GRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestRead() error: ", err) + } + + if Otvet.IsDeleted == false { + err = crud.Delete(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + if Otvet.ID == 0 { + t.Error("TestDelete() error: ID =0") + } + + err = crud.Restore(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + if Otvet.ID == 0 { + t.Error("TestDelete() error: ID =0") + } + } else { + err = crud.Restore(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + if Otvet.ID == 0 { + t.Error("TestDelete() error: ID =0") + } + + err = crud.Delete(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + if Otvet.ID == 0 { + t.Error("TestDelete() error: ID =0") + } + } +} + +func TestFindByExtID(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + crud := Crud_GRPC{} + Otvet1 := lawsuit_status_types.LawsuitStatusType{} + Otvet1.ID = Postgres_ID_Test + err := crud.Read(&Otvet1) + + if err != nil { + t.Error("TestFind_ByExtID() error: ", err) + } + + if Otvet1.ExtID == 0 { + return + } + + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ExtID = Otvet1.ExtID + Otvet.ConnectionID = Otvet1.ConnectionID + err = crud.Find_ByExtID(&Otvet) + + if err != nil { + t.Error("TestFindByExtID() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestFindByExtID() error: ID =0") + } +} + diff --git a/bin/templates/api/service.proto_ b/bin/copy/rapira/templates/pkg/network/grpc/service.proto_ similarity index 100% rename from bin/templates/api/service.proto_ rename to bin/copy/rapira/templates/pkg/network/grpc/service.proto_ diff --git a/bin/copy/rapira/templates/pkg/network/grpc/service_client.go_ b/bin/copy/rapira/templates/pkg/network/grpc/service_client.go_ new file mode 100644 index 0000000..ecb859e --- /dev/null +++ b/bin/copy/rapira/templates/pkg/network/grpc/service_client.go_ @@ -0,0 +1,106 @@ +package grpc_client + +import ( + "github.com/ManyakRus/starter/contextmain" + "github.com/ManyakRus/starter/log" + "github.com/ManyakRus/starter/stopapp" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "os" + "strings" +) + +type SettingsINI struct { + SYNC_SERVICE_HOST string + SYNC_SERVICE_PORT string +} + +var Settings SettingsINI + +var Conn *grpc.ClientConn +var Client grpc_proto.SyncServiceClient + +func Connect() { + var err error + + if Settings.SYNC_SERVICE_HOST == "" { + FillSettings() + } + + addr := Settings.SYNC_SERVICE_HOST + ":" + Settings.SYNC_SERVICE_PORT + Conn, err = grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + log.Fatalf("did not connect: %v", err) + } + + log.Info("GRPC client connected. Address: ", addr) + + Client = grpc_proto.NewSyncServiceClient(Conn) +} + +func FillSettings() { + Settings = SettingsINI{} + Settings.SYNC_SERVICE_HOST = os.Getenv("SYNC_SERVICE_HOST") + Settings.SYNC_SERVICE_PORT = os.Getenv("SYNC_SERVICE_PORT") + + if Settings.SYNC_SERVICE_HOST == "" { + log.Panic("Need fill SYNC_SERVICE_HOST ! in OS Environment ") + } + + if Settings.SYNC_SERVICE_PORT == "" { + log.Panic("Need fill SYNC_SERVICE_PORT ! in OS Environment ") + } +} + +// WaitStop - ожидает отмену глобального контекста +func WaitStop() { + + select { + case <-contextmain.GetContext().Done(): + log.Warn("Context app is canceled. grpc_connect") + } + + // ждём пока отправляемых сейчас сообщений будет =0 + stopapp.WaitTotalMessagesSendingNow("sync_service_client") + + // закрываем соединение + CloseConnection() + stopapp.GetWaitGroup_Main().Done() +} + +// Start - необходимые процедуры для запуска сервера GRPC +func Start() { + Connect() + + stopapp.GetWaitGroup_Main().Add(1) + go WaitStop() + +} + +func CloseConnection() { + err := Conn.Close() + if err != nil { + log.Panic("GRPC client CloseConnection() error: ", err) + } else { + log.Info("GRPC client connection closed") + } +} + +// IsRecordNotFound - возвращает true если ошибка = "record not found" +func IsRecordNotFound(err error) bool { + Otvet := false + + if err == nil { + return Otvet + } + + TextErr := err.Error() + pos1 := strings.Index(TextErr, constants.TEXT_RECORD_NOT_FOUND) + if pos1 >= 0 { + Otvet = true + } + + return Otvet +} diff --git a/bin/copy/rapira/templates/pkg/network/grpc/service_client_test.go_ b/bin/copy/rapira/templates/pkg/network/grpc/service_client_test.go_ new file mode 100644 index 0000000..cf46fa7 --- /dev/null +++ b/bin/copy/rapira/templates/pkg/network/grpc/service_client_test.go_ @@ -0,0 +1,23 @@ +package grpc_client + +import ( + "errors" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants" + "testing" +) + +func TestIsRecordNotFound(t *testing.T) { + + err := errors.New(constants.TEXT_RECORD_NOT_FOUND + " !") + Otvet := IsRecordNotFound(err) + if Otvet != true { + t.Error("TestIsRecordNotFound() error: false") + } + + err = errors.New("rpc error: code = Unknown desc = record not found") + Otvet = IsRecordNotFound(err) + if Otvet != true { + t.Error("TestIsRecordNotFound() error: false") + } + +} diff --git a/bin/copy/rapira/templates/pkg/network/nrpc/nrpc_client/nrpc_client.go_ b/bin/copy/rapira/templates/pkg/network/nrpc/nrpc_client/nrpc_client.go_ new file mode 100644 index 0000000..cbdc28a --- /dev/null +++ b/bin/copy/rapira/templates/pkg/network/nrpc/nrpc_client/nrpc_client.go_ @@ -0,0 +1,292 @@ +package nrpc_lawsuit_status_types + +import ( + "encoding/json" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/nrpc_client" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/grpc_client/constants" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" + "log" +) + +// VersionModel - хранит версию структуры модели +var VersionModel uint32 + +// TableName - имя таблицы в БД Postgres +const TableName string = "lawsuit_status_types" + +// объект для CRUD операций через GRPC +type Crud_NRPC struct { +} + +// GetVersionModel - возвращает хэш версии структуры модели +func (crud Crud_NRPC) GetVersionModel() uint32 { + if VersionModel == 0 { + VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + } + return VersionModel +} + +// Read - возвращает модель из БД +func (crud Crud_NRPC) Read(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_Read(Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Create - записывает новую модель в БД +func (crud Crud_NRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_Create(Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Update - обновляет модель в БД +func (crud Crud_NRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_Update(Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Save - обновляет (или создаёт) модель в БД +func (crud Crud_NRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_Save(Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Delete - устанавливает is_deleted = true в БД +func (crud Crud_NRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_Delete(Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Restore - устанавливает is_deleted = false в БД +func (crud Crud_NRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_Restore(Request) + if err != nil { + sError := err.Error() + if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Find_ByExtID - находит модель в БД по ext_id и connection_id +func (crud Crud_NRPC) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error { + //подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + //подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestExtId{} + Request.ExtId = m.ExtID + Request.ConnectionId = m.ConnectionID + Request.VersionModel = VersionModel + + //запрос + Response, err := nrpc_client.Client.LawsuitStatusType_FindByExtID(Request) + if err != nil { + sError := err.Error() + if sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + //ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + diff --git a/bin/copy/rapira/templates/pkg/network/nrpc/nrpc_client/nrpc_client_test.go_ b/bin/copy/rapira/templates/pkg/network/nrpc/nrpc_client/nrpc_client_test.go_ new file mode 100644 index 0000000..74d2d14 --- /dev/null +++ b/bin/copy/rapira/templates/pkg/network/nrpc/nrpc_client/nrpc_client_test.go_ @@ -0,0 +1,185 @@ +package nrpc_lawsuit_status_types + +import ( + config "github.com/ManyakRus/starter/config" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/nrpc_client" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" + "testing" +) + +// Postgres_ID_Test - ID таблицы для тестирования +const Postgres_ID_Test = 1 + +func TestGetVersionModel(t *testing.T) { + + crud := Crud_NRPC{} + Otvet := crud.GetVersionModel() + if Otvet == 0 { + t.Error("TestGetVersionModel() error: Otvet =0") + } +} + +func TestRead(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + crud := Crud_NRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + + if err != nil { + t.Error("TestRead() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestRead() error: ID =0") + } +} + +func TestCreate(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = -1 + + crud := Crud_NRPC{} + err := crud.Create(&Model) + + if err == nil { + t.Error("TestCreate() error: ", err) + } + + if Model.ID > 0 { + t.Error("TestCreate() error: ID >0") + } +} + +func TestUpdate(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = 0 + + crud := Crud_NRPC{} + err := crud.Update(&Model) + + if err == nil { + t.Error("TestUpdate() error: ", err) + } + + if Model.ID != 0 { + t.Error("TestUpdate() error: ID =0") + } +} + +func TestSave(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + crud := Crud_NRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestSave() error: ", err) + return + } + + err = crud.Save(&Otvet) + + if err != nil { + t.Error("TestSave() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestSave() error: ID =0") + } +} + +func TestDelete(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + crud := Crud_NRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestRead() error: ", err) + } + + if Otvet.IsDeleted == false { + err = crud.Delete(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + if Otvet.ID == 0 { + t.Error("TestDelete() error: ID =0") + } + + err = crud.Restore(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + if Otvet.ID == 0 { + t.Error("TestDelete() error: ID =0") + } + } else { + err = crud.Restore(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + if Otvet.ID == 0 { + t.Error("TestDelete() error: ID =0") + } + + err = crud.Delete(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + if Otvet.ID == 0 { + t.Error("TestDelete() error: ID =0") + } + } +} + +func TestFindByExtID(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + crud := Crud_NRPC{} + Otvet1 := lawsuit_status_types.LawsuitStatusType{} + Otvet1.ID = Postgres_ID_Test + err := crud.Read(&Otvet1) + + if err != nil { + t.Error("TestFind_ByExtID() error: ", err) + } + + if Otvet1.ExtID == 0 { + return + } + + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ExtID = Otvet1.ExtID + Otvet.ConnectionID = Otvet1.ConnectionID + err = crud.Find_ByExtID(&Otvet) + + if err != nil { + t.Error("TestFindByExtId() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestFindByExtId() error: ID =0") + } +} + diff --git a/bin/copy/rapira/templates/pkg/object_model/entities/model.go_ b/bin/copy/rapira/templates/pkg/object_model/entities/model.go_ new file mode 100644 index 0000000..7170e8b --- /dev/null +++ b/bin/copy/rapira/templates/pkg/object_model/entities/model.go_ @@ -0,0 +1,13 @@ +package lawsuit_status_types + +import ( + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities" +) + +// LawsuitStatusType +type LawsuitStatusType struct { + entities.CommonStruct + entities.NameStruct + Code string `json:"code" gorm:"column:code;default:0"` +} + diff --git a/bin/copy/rapira/templates/pkg/object_model/entities/model_crud.go_ b/bin/copy/rapira/templates/pkg/object_model/entities/model_crud.go_ new file mode 100644 index 0000000..a8008fb --- /dev/null +++ b/bin/copy/rapira/templates/pkg/object_model/entities/model_crud.go_ @@ -0,0 +1,148 @@ +package lawsuit_status_types + +import ( + "encoding/json" + "github.com/vmihailenco/msgpack/v5" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/functions/calc_struct_version" + "reflect" +) + +// versionLawsuitStatusType - версия структуры модели, с учётом имен и типов полей +var versionLawsuitStatusType uint32 + +// crud_LawsuitStatusType - объект контроллер crud операций +var crud_LawsuitStatusType ICrud_LawsuitStatusType + +// интерфейс стандартных CRUD операций, для использования в DB или GRPC или NRPC +type ICrud_LawsuitStatusType interface { + Read(*LawsuitStatusType) error + Save(*LawsuitStatusType) error + Update(*LawsuitStatusType) error + Create(*LawsuitStatusType) error + Delete(*LawsuitStatusType) error + Restore(*LawsuitStatusType) error + Find_ByExtID(*LawsuitStatusType) error +} + +// TableName - возвращает имя таблицы в БД, нужен для gorm +func (m LawsuitStatusType) TableNameDB() string { + return "lawsuit_status_types" +} + +// NewLawsuitStatusType - возвращает новый объект +func NewLawsuitStatusType() LawsuitStatusType { + return LawsuitStatusType{} +} + +// AsLawsuitStatusType - создаёт объект из упакованного объекта в массиве байтов +func AsLawsuitStatusType(b []byte) (LawsuitStatusType, error) { + c := NewLawsuitStatusType() + err := msgpack.Unmarshal(b, &c) + if err != nil { + return NewLawsuitStatusType(), err + } + return c, nil +} + +// LawsuitStatusTypeAsBytes - упаковывает объект в массив байтов +func LawsuitStatusTypeAsBytes(m *LawsuitStatusType) ([]byte, error) { + b, err := msgpack.Marshal(m) + if err != nil { + return nil, err + } + return b, nil +} + +// GetStructVersion - возвращает версию модели +func (m LawsuitStatusType) GetStructVersion() uint32 { + if versionLawsuitStatusType == 0 { + versionLawsuitStatusType = calc_struct_version.CalcStructVersion(reflect.TypeOf(m)) + } + + return versionLawsuitStatusType +} + +// GetModelFromJSON - создаёт модель из строки json +func (m *LawsuitStatusType) GetModelFromJSON(sModel string) error { + var err error + + var bytes []byte + bytes = []byte(sModel) + + err = json.Unmarshal(bytes, m) + + return err +} + +// GetJSON - возвращает строку json из модели +func (m LawsuitStatusType) GetJSON() (string, error) { + var ReturnVar string + var err error + + bytes, err := json.Marshal(m) + if err != nil { + return ReturnVar, err + } + ReturnVar = string(bytes) + return ReturnVar, err +} + +// ---------------------------- CRUD операции ------------------------------------------------------------ + +// Read - находит запись в БД по ID, и заполняет в объект +func (m *LawsuitStatusType) Read() error { + err := crud_LawsuitStatusType.Read(m) + + return err +} + +// Save - записывает объект в БД по ID +func (m *LawsuitStatusType) Save() error { + err := crud_LawsuitStatusType.Save(m) + + return err +} + +// Update - обновляет объект в БД по ID +func (m *LawsuitStatusType) Update() error { + err := crud_LawsuitStatusType.Update(m) + + return err +} + +// Create - создаёт объект в БД с новым ID +func (m *LawsuitStatusType) Create() error { + err := crud_LawsuitStatusType.Create(m) + + return err +} + +// Delete - устанавливает признак пометки удаления в БД +func (m *LawsuitStatusType) Delete() error { + err := crud_LawsuitStatusType.Delete(m) + + return err +} + +// Restore - снимает признак пометки удаления в БД +func (m *LawsuitStatusType) Restore() error { + err := crud_LawsuitStatusType.Restore(m) + + return err +} + +// Find_ByExtID - находит объект по ExtID +func (m *LawsuitStatusType) Find_ByExtID() error { + err := crud_LawsuitStatusType.Find_ByExtID(m) + + return err +} + +// SetCrudInterface - заполняет интерфейс crud: DB, GRPC, NRPC +func (m LawsuitStatusType) SetCrudInterface(crud ICrud_LawsuitStatusType) { + crud_LawsuitStatusType = crud + + return +} + +// ---------------------------- конец CRUD операции ------------------------------------------------------------ diff --git a/bin/copy/rapira/templates/pkg/object_model/types/alias/alias.go b/bin/copy/rapira/templates/pkg/object_model/types/alias/alias.go new file mode 100644 index 0000000..4007f5d --- /dev/null +++ b/bin/copy/rapira/templates/pkg/object_model/types/alias/alias.go @@ -0,0 +1,35 @@ +// Package alias -- специальные типы РАПИРы +package alias + +// PaymentId -- ID платёжки +type PaymentId int64 + +// InvoiceId -- ID счёт-фактуры +type InvoiceId int64 + +// LawsuitId -- ID претензии +type LawsuitId int64 + +// LawsuitNumber -- номер претензии +type LawsuitNumber string + +// ClaimNumber -- Номер дела +type ClaimNumber string + +// TrialNumber -- Номер иска +type TrialNumber string + +// ContractNumber -- Номер договора +type ContractNumber string + +// FrontDate -- специальный тип даты для фронта +type FrontDate string + +// FrontTime -- специальный тип даты-времени для фронта +type FrontTime string + +// PaymentRegisteredAt -- тип даты времени при регистрации в системе +type PaymentRegisteredAt string + +// IsAfterNotify -- признак регистрации документа после уведомления +type IsAfterNotify bool diff --git a/bin/copy/rapira/templates/scripts/VersionToFile.py b/bin/copy/rapira/templates/scripts/VersionToFile.py new file mode 100755 index 0000000..c768562 --- /dev/null +++ b/bin/copy/rapira/templates/scripts/VersionToFile.py @@ -0,0 +1,52 @@ +#!/usr/bin/python3 +# Python script to create an empty file +# with current date as name. + +# importing datetime module +from datetime import datetime +import os + +# datetime.datetime.now() to get +# current date as filename. +# TimeNow = datetime.datetime.now() + +FILESUBVERSION="../bin/subversion.txt" +FILEDATE="../bin/date.txt" + +# create empty file +def create_file(): + fmt = "%Y-%m-%d %H:%M:%S.%f" + str1 = datetime.utcnow().strftime(fmt)[:-3] + + # Function creates an empty file + # %d - date, %B - month, %Y - Year + with open(FILEDATE, "w") as file: + file.write(str1) + file.close() + +def set_version(): + filename=FILESUBVERSION + build=0 + mode = 'r' if os.path.exists(filename) else 'w+' + with open(filename, encoding="utf8", mode=mode) as file_in: + _str_build = file_in.read() + file_in.close() + try: + build = int(_str_build) + except ValueError as err: + print("Build.__setVers(): при конвертировании строки в число, err=", err) + finally: + pass + build += 1 + str_build = str(build) + while len(str_build) < 5: + str_build = "0" + str_build + print("Build.set_version(): new build=", str_build) + with open(filename, "w", encoding="utf8") as file_in: + file_in.write(str_build) + file_in.close() + + +# Driver Code +create_file() +set_version() \ No newline at end of file diff --git a/bin/templates/configs_/nullable.json b/bin/templates/configs_/nullable.json index 4cbce43..1e5062a 100644 --- a/bin/templates/configs_/nullable.json +++ b/bin/templates/configs_/nullable.json @@ -1,3 +1,4 @@ { - "ExtID": "0" + "ExtID": true, + "CreatedAt": false } diff --git a/bin/templates/configs_/readme.txt b/bin/templates/configs_/readme.txt index 4869a84..ce1442e 100644 --- a/bin/templates/configs_/readme.txt +++ b/bin/templates/configs_/readme.txt @@ -16,5 +16,6 @@ For non standart rare case. nullable.json -List of golang field names, which not need change 0 to null. +List of golang field names, which need change 0 to null. +true = need change 0 to null For non standart rare case. diff --git a/bin/templates/pkg/db/db.go_ b/bin/templates/pkg/db/db.go_ index db3082a..52e2c1b 100644 --- a/bin/templates/pkg/db/db.go_ +++ b/bin/templates/pkg/db/db.go_ @@ -188,9 +188,6 @@ func (crud Crud_DB) create_update_ctx(ctx context.Context, m *lawsuit_status_typ // запишем NULL в пустые колонки for f := 0; f < len(MassOmit); f++ { ColumnName := MassOmit[f] - if ColumnName == "CreatedAt" { - continue - } tx = db.Model(&m).Update(ColumnName, gorm.Expr("NULL")) err = tx.Error diff --git a/bin/templates/pkg/network/grpc/generation_code.sh_ b/bin/templates/pkg/network/grpc/generation_code.sh_ new file mode 100755 index 0000000..7c46f85 --- /dev/null +++ b/bin/templates/pkg/network/grpc/generation_code.sh_ @@ -0,0 +1,6 @@ +#!/bin/bash + +ADAPT_PATH=./ + +clear +protoc --go_out=${ADAPT_PATH} --nrpc_out=./ --go_opt=paths=import --go-grpc_out=${ADAPT_PATH} --go-grpc_opt=paths=import ${ADAPT_PATH}sync_service.proto diff --git a/bin/templates/pkg/network/grpc/service.proto_ b/bin/templates/pkg/network/grpc/service.proto_ new file mode 100644 index 0000000..99d9d88 --- /dev/null +++ b/bin/templates/pkg/network/grpc/service.proto_ @@ -0,0 +1,186 @@ +syntax = "proto3"; + +/* + Файл содержит описание сервиса Sync_service +*/ + + +package grpc; + +option go_package = "./grpc_proto"; + +// sync_service - сервис обмена с Базой данных +service Sync_service { + // + rpc Organization_Read(RequestId) returns (Response) {} + rpc Organization_Create(RequestModel) returns (Response) {} + rpc Organization_Update(RequestModel) returns (Response) {} + rpc Organization_Save(RequestModel) returns (Response) {} + rpc Organization_Delete(RequestId) returns (Response) {} + rpc Organization_Restore(RequestId) returns (Response) {} + rpc Organization_FindByInnKpp(RequestInnKpp) returns (Response) {} + rpc Organization_FindByExtId(RequestExtId) returns (Response) {} + + // + rpc File_Read(RequestId) returns (Response) {} + rpc File_Create(RequestModel) returns (Response) {} + rpc File_Update(RequestModel) returns (Response) {} + rpc File_Save(RequestModel) returns (Response) {} + rpc File_Delete(RequestId) returns (Response) {} + rpc File_Restore(RequestId) returns (Response) {} + rpc File_FindByFileID(RequestString) returns (Response) {} + rpc File_FindByFullName(RequestString) returns (Response) {} + + // + rpc OrganizationCasebook_Read(RequestId) returns (Response) {} + rpc OrganizationCasebook_Create(RequestModel) returns (Response) {} + rpc OrganizationCasebook_Update(RequestModel) returns (Response) {} + rpc OrganizationCasebook_Save(RequestModel) returns (Response) {} + rpc OrganizationCasebook_Delete(RequestId) returns (Response) {} + rpc OrganizationCasebook_Restore(RequestId) returns (Response) {} + rpc OrganizationCasebook_FindByInnKpp(RequestInnKpp) returns (Response) {} + rpc OrganizationCasebook_FindByInn(RequestString) returns (Response) {} + rpc OrganizationCasebook_FindByOrganizationId(RequestId) returns (Response) {} + + // + rpc Connection_Read(RequestId) returns (Response) {} + rpc Connection_Create(RequestModel) returns (Response) {} + rpc Connection_Update(RequestModel) returns (Response) {} + rpc Connection_Save(RequestModel) returns (Response) {} + + // + rpc Employee_Read(RequestId) returns (Response) {} + rpc Employee_Create(RequestModel) returns (Response) {} + rpc Employee_Update(RequestModel) returns (Response) {} + rpc Employee_Save(RequestModel) returns (Response) {} + rpc Employee_Delete(RequestId) returns (Response) {} + rpc Employee_Restore(RequestId) returns (Response) {} + rpc Employee_FindByExtId(RequestExtId) returns (Response) {} + rpc Employee_FindByLogin(RequestString) returns (Response) {} + rpc Employee_FindByEMail(RequestString) returns (Response) {} + rpc Employee_FindByFIO(RequestString3) returns (Response) {} + + // + rpc LawsuitStatusState_Read(RequestId) returns (Response) {} + rpc LawsuitStatusState_Create(RequestModel) returns (Response) {} + rpc LawsuitStatusState_Update(RequestModel) returns (Response) {} + rpc LawsuitStatusState_Save(RequestModel) returns (Response) {} + rpc LawsuitStatusState_Delete(RequestId) returns (Response) {} + rpc LawsuitStatusState_Restore(RequestId) returns (Response) {} + rpc LawsuitStatusState_FillFromLawsuit(RequestIdId) returns (ResponseEmpty) {} + rpc LawsuitStatusState_FindDebtSum(RequestIdId) returns (ResponseFloat64) {} + + // + rpc LawsuitStatusType_Read(RequestId) returns (Response) {} + rpc LawsuitStatusType_Create(RequestModel) returns (Response) {} + rpc LawsuitStatusType_Update(RequestModel) returns (Response) {} + rpc LawsuitStatusType_Save(RequestModel) returns (Response) {} + rpc LawsuitStatusType_Delete(RequestId) returns (Response) {} + rpc LawsuitStatusType_Restore(RequestId) returns (Response) {} + + // + rpc Lawsuit_Read(RequestId) returns (Response) {} + rpc Lawsuit_Create(RequestModel) returns (Response) {} + rpc Lawsuit_Update(RequestModel) returns (Response) {} + rpc Lawsuit_Save(RequestModel) returns (Response) {} + rpc Lawsuit_Delete(RequestId) returns (Response) {} + rpc Lawsuit_Restore(RequestId) returns (Response) {} + + // + rpc MessageAttachement_Read(RequestId) returns (Response) {} + rpc MessageAttachement_Create(RequestModel) returns (Response) {} + rpc MessageAttachement_Update(RequestModel) returns (Response) {} + rpc MessageAttachement_Save(RequestModel) returns (Response) {} + rpc MessageAttachement_Delete(RequestId) returns (Response) {} + rpc MessageAttachement_Restore(RequestId) returns (Response) {} + + // + rpc MessageSendStatuse_Read(RequestId) returns (Response) {} + rpc MessageSendStatuse_Create(RequestModel) returns (Response) {} + rpc MessageSendStatuse_Update(RequestModel) returns (Response) {} + rpc MessageSendStatuse_Save(RequestModel) returns (Response) {} + rpc MessageSendStatuse_Delete(RequestId) returns (Response) {} + rpc MessageSendStatuse_Restore(RequestId) returns (Response) {} + + // + rpc MessageType_Read(RequestId) returns (Response) {} + rpc MessageType_Create(RequestModel) returns (Response) {} + rpc MessageType_Update(RequestModel) returns (Response) {} + rpc MessageType_Save(RequestModel) returns (Response) {} + rpc MessageType_Delete(RequestId) returns (Response) {} + rpc MessageType_Restore(RequestId) returns (Response) {} + + // + rpc Message_Read(RequestId) returns (Response) {} + rpc Message_Create(RequestModel) returns (Response) {} + rpc Message_Update(RequestModel) returns (Response) {} + rpc Message_Save(RequestModel) returns (Response) {} + rpc Message_Delete(RequestId) returns (Response) {} + rpc Message_Restore(RequestId) returns (Response) {} + rpc Message_FindBy_LawsuitID_MessageTypeID(RequestIdId) returns (Response) {} + +} + +// RequestId - параметры запроса на сервер +message RequestId { + uint32 VersionModel= 1; //версия структуры модели + int64 id = 2; // id записи в БД +} + +// RequestString - параметры запроса на сервер +message RequestString { + uint32 VersionModel= 1; //версия структуры модели + string StringFind = 2; // строка поиска +} + +// RequestString3 - параметры запроса на сервер +message RequestString3 { + uint32 VersionModel= 1; //версия структуры модели + string StringFind1 = 2; // строка поиска + string StringFind2 = 3; // строка поиска + string StringFind3 = 4; // строка поиска +} + +// RequestId - параметры запроса на сервер +message RequestExtId { + uint32 VersionModel= 1; //версия структуры модели + int64 Ext_id = 2; // ext_id записи в БД + int64 Connection_id =3; // Connection_id записи в БД +} + +// RequestModel - параметры запроса на сервер +message RequestModel { + uint32 VersionModel= 1; //версия структуры модели + string ModelString = 2; //объект-модель в формате json +} + +// RequestInnKpp - параметры запроса на сервер +message RequestInnKpp { + uint32 VersionModel= 1; //версия структуры модели + string Inn = 2; // ИНН + string Kpp =3; // КПП +} + +// RequestId - параметры запроса на сервер +message RequestIdId { + uint32 VersionModel= 1; //версия структуры модели + int64 id1 = 2; // id записи в БД + int64 id2 = 3; // id записи в БД +} + + + +// Response - параметры ответа на клиент +message Response { + string ModelString = 1; //объект-модель в формате json +} + +// ResponseFloat64 - параметры ответа на клиент +message ResponseFloat64 { + double Otvet = 1; //Ответ - число +} + +// Response - параметры ответа на клиент +message ResponseEmpty { +} + diff --git a/internal/create_files/db/db.go b/internal/create_files/db/db.go index b79804f..3acef3c 100644 --- a/internal/create_files/db/db.go +++ b/internal/create_files/db/db.go @@ -25,7 +25,7 @@ func CreateAllFiles(MapAll map[string]*types.Table) error { } //файлы db - if config.Settings.NEED_CREATE_DB_TEST == true { + if config.Settings.NEED_CREATE_DB == true { err = CreateFiles(Table1) if err != nil { log.Error("CreateFiles() table: ", Table1.Name, " error: ", err) @@ -321,12 +321,17 @@ func AddTextOmit(TextDB string, Table1 *types.Table) string { ColumnNameGo := Column1.NameGo TypeGo := Column1.TypeGo - _, is_nullable_config := types.MapNullableFileds[ColumnNameGo] - if Column1.IsNullable == false { continue } + //ищем в файле настроек nullable.json + is_nullable_config, has_is_nullable_config := types.MapNullableFileds[ColumnNameGo] + if has_is_nullable_config == true && is_nullable_config == false { + continue + } + + // if TypeGo == "time.Time" { NullableCount = NullableCount + 1 TextFind := `if m.` + ColumnNameGo + `.IsZero() == true {` diff --git a/internal/create_files/model/model.go b/internal/create_files/model/model.go index c7eaa4b..5cbd3f3 100644 --- a/internal/create_files/model/model.go +++ b/internal/create_files/model/model.go @@ -243,7 +243,10 @@ func FindTextColumn(TextModel string, Table1 *types.Table, Column1 *types.Column Type_go := Column1.TypeGo TextModel, Type_go = FindColumnTypeGoImport(TextModel, Table1, Column1) //Column1.TypeGo = Type_go - TextDefaultValue := create_files.FindTextDefaultValue(Type_go) + TextDefaultValue := "" + if Column1.IsIdentity == false { + TextDefaultValue = create_files.FindTextDefaultValue(Type_go) + } TextPrimaryKey := FindTextPrimaryKey(Column1.IsIdentity) Description := Column1.Description Description = create_files.PrintableString(Description) //экранирование символов @@ -263,7 +266,7 @@ func FindTextColumn(TextModel string, Table1 *types.Table, Column1 *types.Column Otvet = Otvet + "\t" + ColumnModelName + " " + Type_go + "\t" Otvet = Otvet + "`json:\"" + ColumnName + "\"" Otvet = Otvet + " gorm:\"column:" + ColumnName + TextPrimaryKey + TextDefaultValue + TextAutoCreateTime + TextAutoUpdateTime + "\"" - Otvet = Otvet + " db:\"" + ColumnName + "\"" + //Otvet = Otvet + " db:\"" + ColumnName + "\"" Otvet = Otvet + "`" Otvet = Otvet + "\t//" + Description diff --git a/internal/types/types.go b/internal/types/types.go index 4a555a9..7b41926 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -26,6 +26,6 @@ type Table struct { var MapReplaceName = make(map[string]string, 0) -var MapNullableFileds = make(map[string]string, 0) +var MapNullableFileds = make(map[string]bool, 0) var MapConvertID = make(map[string]string, 0)