From 0253b146a2a8a6bcb2f6b11aa1f7067cf1f93706 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Fri, 6 Sep 2024 17:10:34 +0800 Subject: [PATCH 01/24] feat(openapi): add openapi auth and version ,echo apis --- api/powerx.api | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/api/powerx.api b/api/powerx.api index 7202be62..207cc989 100644 --- a/api/powerx.api +++ b/api/powerx.api @@ -15,7 +15,8 @@ import "admin.wechat.offiaccount.api" import "mp.api" import "web.api" import "openapi.api" -//import "custom.api" + +import "custom.api" import "plugin.api" import "health.api" From e8767245ccdee34558c837ee763e577d1ec00402 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Mon, 9 Sep 2024 23:24:15 +0800 Subject: [PATCH 02/24] refact(redis): upgrade option to UniversalOptions --- go.mod | 7 +++---- go.sum | 10 ++++------ internal/uc/powerx.go | 8 ++++---- 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/go.mod b/go.mod index a5a5da81..495fba4c 100644 --- a/go.mod +++ b/go.mod @@ -1,13 +1,13 @@ module PowerX -go 1.21.0 +go 1.23 //replace github.com/ArtisanCloud/PowerWeChat/v3 => ../../../PowerWechat/PowerWeChat require ( - github.com/ArtisanCloud/PowerLibs/v3 v3.0.16 + github.com/ArtisanCloud/PowerLibs/v3 v3.2.6 github.com/ArtisanCloud/PowerSocialite/v3 v3.0.7 - github.com/ArtisanCloud/PowerWeChat/v3 v3.1.15 + github.com/ArtisanCloud/PowerWeChat/v3 v3.2.42 github.com/Blank-Xu/sql-adapter v0.0.0-20210714092925-0bdd0d548758 github.com/brianvoe/gofakeit/v6 v6.21.0 github.com/casbin/casbin/v2 v2.60.0 @@ -121,6 +121,5 @@ require ( google.golang.org/grpc v1.66.0 // indirect google.golang.org/protobuf v1.34.2 // indirect gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 5eb94045..c5609ce5 100644 --- a/go.sum +++ b/go.sum @@ -387,12 +387,12 @@ cloud.google.com/go/workflows v1.9.0/go.mod h1:ZGkj1aFIOd9c8Gerkjjq7OW7I5+l6cSvT dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -github.com/ArtisanCloud/PowerLibs/v3 v3.0.16 h1:LBgAuPIkNKGh0fL/HK4HHSqWuoMIbRtfFVMHwl2cAsc= -github.com/ArtisanCloud/PowerLibs/v3 v3.0.16/go.mod h1:nuUJGlLNKhBmo5nLBqJOuKD2+oDoJkWaqzxxhkLPo5s= +github.com/ArtisanCloud/PowerLibs/v3 v3.2.6 h1:xNDXBJ1VNYAEgs4UG/lSygzU66/XG3mTA7mm/qE//NY= +github.com/ArtisanCloud/PowerLibs/v3 v3.2.6/go.mod h1:xFGsskCnzAu+6rFEJbGVAlwhrwZPXAny6m7j71S/B5k= github.com/ArtisanCloud/PowerSocialite/v3 v3.0.7 h1:P+erNlErr+X2v7Et+yTWaTfIRhw+HfpAPdvNIEwk9Gw= github.com/ArtisanCloud/PowerSocialite/v3 v3.0.7/go.mod h1:VZQNCvcK/rldF3QaExiSl1gJEAkyc5/I8RLOd3WFZq4= -github.com/ArtisanCloud/PowerWeChat/v3 v3.1.15 h1:QK8/v5pNyzgiYx6A7BJcoNxLIPkNUVnOQvVfTKG9j9c= -github.com/ArtisanCloud/PowerWeChat/v3 v3.1.15/go.mod h1:i4quVLQxrTJ4Yg5A5ZKvmkH+P+8VP6+2VzJPc3B6qTo= +github.com/ArtisanCloud/PowerWeChat/v3 v3.2.42 h1:fU+/xJPGTAsSCyoeCn036VLBLUNjDnVrH0bls9HS9hg= +github.com/ArtisanCloud/PowerWeChat/v3 v3.2.42/go.mod h1:8GMw0a41XWr5EWpV/uXOluLCdOSMShgDLReH5FgxKZ8= github.com/Blank-Xu/sql-adapter v0.0.0-20210714092925-0bdd0d548758 h1:L4iwZiJYTNirz4Er7Bw2+AVzW8VCpCGYc8luHc3y5lU= github.com/Blank-Xu/sql-adapter v0.0.0-20210714092925-0bdd0d548758/go.mod h1:GlBcPpgzETyqz83HIUFEMobVY38h1fOFXgwpy7T64xE= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= @@ -1718,8 +1718,6 @@ gopkg.in/h2non/gock.v1 v1.1.2/go.mod h1:n7UGz/ckNChHiK05rDoiC4MYSunEC/lyaUm2WWaD gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= -gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/internal/uc/powerx.go b/internal/uc/powerx.go index f67a385f..eb38d90d 100644 --- a/internal/uc/powerx.go +++ b/internal/uc/powerx.go @@ -98,11 +98,11 @@ func NewPowerXUseCase(conf *config.Config) (uc *PowerXUseCase, clean func()) { } // 加载Cache对象 - cacheOption := &kernel.RedisOptions{ - Addr: conf.RedisBase.Host, - //Username: conf.RedisBase.Username, + cacheOption := &kernel.UniversalOptions{ + Addrs: []string{conf.RedisBase.Host}, + Username: conf.RedisBase.Username, Password: conf.RedisBase.Password, - //DB: conf.RedisBase.DB, + DB: conf.RedisBase.DB, } uc.Cache = kernel.NewRedisClient(cacheOption) From 6f7de868b254197f38d77f6d16e6b18234de8407 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Thu, 12 Sep 2024 22:13:04 +0800 Subject: [PATCH 03/24] fix(token): expire with seconds --- internal/middleware/webcustomerjwtauthmiddleware.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/middleware/webcustomerjwtauthmiddleware.go b/internal/middleware/webcustomerjwtauthmiddleware.go index d013458c..d29d1dee 100644 --- a/internal/middleware/webcustomerjwtauthmiddleware.go +++ b/internal/middleware/webcustomerjwtauthmiddleware.go @@ -6,6 +6,7 @@ import ( "PowerX/internal/types/errorx" "PowerX/internal/uc" "PowerX/internal/uc/powerx/crm/customerdomain" + fmt "PowerX/pkg/printx" "context" "github.com/golang-jwt/jwt/v4" "github.com/pkg/errors" @@ -35,6 +36,7 @@ func (m *WebCustomerJWTAuthMiddleware) Handle(next http.HandlerFunc) http.Handle return func(writer http.ResponseWriter, request *http.Request) { authorization := request.Header.Get("Authorization") + fmt.Dump(authorization) splits := strings.Split(authorization, "Bearer") if len(splits) != 2 { httpx.Error(writer, unAuth) @@ -46,6 +48,7 @@ func (m *WebCustomerJWTAuthMiddleware) Handle(next http.HandlerFunc) http.Handle token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) { return []byte(secret), nil }) + fmt.Dump(token, err) if err != nil || !token.Valid { if errors.Is(err, jwt.ErrTokenMalformed) { httpx.Error(writer, unAuth) From d10d8a0cc1aefb6603cd4559f01669cff20e3796 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Thu, 12 Sep 2024 22:25:37 +0800 Subject: [PATCH 04/24] feat(openapi): apqp list logic --- internal/middleware/webcustomerjwtauthmiddleware.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/middleware/webcustomerjwtauthmiddleware.go b/internal/middleware/webcustomerjwtauthmiddleware.go index d29d1dee..a4b5ba30 100644 --- a/internal/middleware/webcustomerjwtauthmiddleware.go +++ b/internal/middleware/webcustomerjwtauthmiddleware.go @@ -48,7 +48,7 @@ func (m *WebCustomerJWTAuthMiddleware) Handle(next http.HandlerFunc) http.Handle token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) { return []byte(secret), nil }) - fmt.Dump(token, err) + if err != nil || !token.Valid { if errors.Is(err, jwt.ErrTokenMalformed) { httpx.Error(writer, unAuth) From 5b4ef02fafbc14e8c36c81484620dd86b51ab929 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Fri, 20 Sep 2024 12:20:03 +0800 Subject: [PATCH 05/24] feat(pro): add pro migrate and seed --- cmd/ctl/database/migrate/powerx.go | 4 ++++ cmd/ctl/database/pro/migrate/custom.go | 12 ++++++++++++ cmd/ctl/database/pro/seed/datadictionary.go | 17 +++++++++++++++++ cmd/ctl/database/pro/seed/pro.go | 9 +++++++++ .../seed/datadictionary/datadictionary.go | 8 +++++--- cmd/ctl/database/seed/powerx.go | 8 ++++++-- 6 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 cmd/ctl/database/pro/migrate/custom.go create mode 100644 cmd/ctl/database/pro/seed/datadictionary.go create mode 100644 cmd/ctl/database/pro/seed/pro.go diff --git a/cmd/ctl/database/migrate/powerx.go b/cmd/ctl/database/migrate/powerx.go index 99fe1fdf..d2c856a5 100644 --- a/cmd/ctl/database/migrate/powerx.go +++ b/cmd/ctl/database/migrate/powerx.go @@ -2,6 +2,7 @@ package migrate import ( "PowerX/cmd/ctl/database/custom/migrate" + migratePro "PowerX/cmd/ctl/database/pro/migrate" "PowerX/internal/config" "PowerX/internal/model" "PowerX/internal/model/crm/customerdomain" @@ -92,6 +93,9 @@ func (m *PowerMigrator) AutoMigrate() { trade.TokenReservation{}, trade.TokenTransaction{}, ) + // pro + migratePro.AutoMigratePro(m.db) + // custom migrate.AutoMigrateCustom(m.db) diff --git a/cmd/ctl/database/pro/migrate/custom.go b/cmd/ctl/database/pro/migrate/custom.go new file mode 100644 index 00000000..b78e3b2d --- /dev/null +++ b/cmd/ctl/database/pro/migrate/custom.go @@ -0,0 +1,12 @@ +package migrate + +import ( + "gorm.io/gorm" +) + +func AutoMigratePro(db *gorm.DB) { + // migrate your pro models + + _ = db.AutoMigrate() + +} diff --git a/cmd/ctl/database/pro/seed/datadictionary.go b/cmd/ctl/database/pro/seed/datadictionary.go new file mode 100644 index 00000000..e01a29a5 --- /dev/null +++ b/cmd/ctl/database/pro/seed/datadictionary.go @@ -0,0 +1,17 @@ +package seed + +import ( + "PowerX/internal/model" + "PowerX/internal/uc/powerx" + "gorm.io/gorm" +) + +var UseCaseDD *powerx.DataDictionaryUseCase + +func ProDataDictionary(db *gorm.DB) (data []*model.DataDictionaryType) { + + UseCaseDD = powerx.NewDataDictionaryUseCase(db) + + return data + +} diff --git a/cmd/ctl/database/pro/seed/pro.go b/cmd/ctl/database/pro/seed/pro.go new file mode 100644 index 00000000..fb1e8f34 --- /dev/null +++ b/cmd/ctl/database/pro/seed/pro.go @@ -0,0 +1,9 @@ +package seed + +import ( + "gorm.io/gorm" +) + +func CreateProSeeds(db *gorm.DB) { + +} diff --git a/cmd/ctl/database/seed/datadictionary/datadictionary.go b/cmd/ctl/database/seed/datadictionary/datadictionary.go index 6f979d28..9078a2fb 100644 --- a/cmd/ctl/database/seed/datadictionary/datadictionary.go +++ b/cmd/ctl/database/seed/datadictionary/datadictionary.go @@ -1,7 +1,8 @@ package datadictionary import ( - "PowerX/cmd/ctl/database/custom/seed" + seedCustom "PowerX/cmd/ctl/database/custom/seed" + seedPro "PowerX/cmd/ctl/database/pro/seed" "PowerX/internal/model" "PowerX/internal/uc/powerx" "PowerX/pkg/slicex" @@ -20,8 +21,9 @@ func CreateDataDictionaries(db *gorm.DB) (err error) { UseCaseDD = powerx.NewDataDictionaryUseCase(db) data := DefaultDataDictionary() - customData := seed.CustomDataDictionary(db) - data = slicex.Concatenate(data, customData) + proData := seedPro.ProDataDictionary(db) + customData := seedCustom.CustomDataDictionary(db) + data = slicex.Concatenate(data, proData, customData) if count == 0 { if err = db.Model(&model.DataDictionaryType{}).Create(data).Error; err != nil { diff --git a/cmd/ctl/database/seed/powerx.go b/cmd/ctl/database/seed/powerx.go index cdc50ad1..adc26829 100644 --- a/cmd/ctl/database/seed/powerx.go +++ b/cmd/ctl/database/seed/powerx.go @@ -1,7 +1,8 @@ package seed import ( - "PowerX/cmd/ctl/database/custom/seed" + seedCustom "PowerX/cmd/ctl/database/custom/seed" + seedPro "PowerX/cmd/ctl/database/pro/seed" "PowerX/cmd/ctl/database/seed/datadictionary" "PowerX/internal/config" "gorm.io/driver/mysql" @@ -60,8 +61,11 @@ func (s *PowerSeeder) CreatePowerX() (err error) { // Marketing _ = CreateMGMRules(s.db) + // pro + seedPro.CreateProSeeds(s.db) + // custom - seed.CreateCustomSeeds(s.db) + seedCustom.CreateCustomSeeds(s.db) return } From bacfeded709261347d73fb3df067fa28cd6c1abd Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Fri, 20 Sep 2024 12:22:57 +0800 Subject: [PATCH 06/24] feat(update) --- cmd/ctl/database/pro/migrate/{custom.go => pro.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename cmd/ctl/database/pro/migrate/{custom.go => pro.go} (100%) diff --git a/cmd/ctl/database/pro/migrate/custom.go b/cmd/ctl/database/pro/migrate/pro.go similarity index 100% rename from cmd/ctl/database/pro/migrate/custom.go rename to cmd/ctl/database/pro/migrate/pro.go From d149c78a0e5ec19109c0c486f849f41759299393 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Fri, 20 Sep 2024 12:38:21 +0800 Subject: [PATCH 07/24] feat(api): pro module --- api/pro/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 api/pro/README.md diff --git a/api/pro/README.md b/api/pro/README.md new file mode 100644 index 00000000..4543f7b7 --- /dev/null +++ b/api/pro/README.md @@ -0,0 +1,7 @@ +# Pro模块开发 + +## 项目模块 + +## 全渠道模块 + +## AI模块 \ No newline at end of file From ca29002a256bbc32cc6977030a8ca5f2eefede24 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Fri, 20 Sep 2024 12:38:54 +0800 Subject: [PATCH 08/24] feat(api): pro module --- api/powerx.api | 1 + api/pro.api | 0 2 files changed, 1 insertion(+) create mode 100644 api/pro.api diff --git a/api/powerx.api b/api/powerx.api index 207cc989..db8f42d1 100644 --- a/api/powerx.api +++ b/api/powerx.api @@ -16,6 +16,7 @@ import "mp.api" import "web.api" import "openapi.api" +import "pro.api" import "custom.api" import "plugin.api" import "health.api" diff --git a/api/pro.api b/api/pro.api new file mode 100644 index 00000000..e69de29b From bf8784737fa27b54b5b609b3e45f254ce2dda4e4 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Fri, 20 Sep 2024 15:28:42 +0800 Subject: [PATCH 09/24] feat(pro): add uc --- internal/svc/servicecontext.go | 3 +++ internal/uc/pro.go | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 internal/uc/pro.go diff --git a/internal/svc/servicecontext.go b/internal/svc/servicecontext.go index 74b730bc..c62b7b23 100644 --- a/internal/svc/servicecontext.go +++ b/internal/svc/servicecontext.go @@ -12,6 +12,7 @@ type ServiceContext struct { Config config.Config PowerX *uc.PowerXUseCase OpenAPI *uc.OpenAPIUseCase + Pro *uc.ProUseCase Custom *uc.CustomUseCase MPCustomerJWTAuth rest.Middleware @@ -29,6 +30,7 @@ type ServiceContext struct { func NewServiceContext(c config.Config, opts ...Option) *ServiceContext { powerx, _ := uc.NewPowerXUseCase(&c) openapi, _ := uc.NewOpenAPIUseCase(&c, powerx) + pro, _ := uc.NewProUseCase(&c, powerx) custom, _ := uc.NewCustomUseCase(&c, powerx) svcCtx := ServiceContext{ @@ -43,6 +45,7 @@ func NewServiceContext(c config.Config, opts ...Option) *ServiceContext { UserNoPermJWTAuth: middleware.NewUserNoPermJWTAuthMiddleware(&c, powerx).Handle, OpenAPIJWTAuth: middleware.NewOpenAPIJWTAuthMiddleware(&c, powerx).Handle, OpenAPIPlatformGet: middleware.NewOpenAPIPlatformGetMiddleware(&c, powerx).Handle, + Pro: pro, Custom: custom, } diff --git a/internal/uc/pro.go b/internal/uc/pro.go new file mode 100644 index 00000000..2ad740ac --- /dev/null +++ b/internal/uc/pro.go @@ -0,0 +1,20 @@ +package uc + +import ( + "PowerX/internal/config" + "gorm.io/gorm" +) + +type ProUseCase struct { + db *gorm.DB +} + +func NewProUseCase(conf *config.Config, pxUseCase *PowerXUseCase) (uc *ProUseCase, clean func()) { + + uc = &ProUseCase{} + + // 需要打印当时系统的Timezone + return uc, func() { + + } +} From 5ec7969606de9aa00c6ec19bd13f2cd96f077273 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Mon, 23 Sep 2024 15:56:29 +0800 Subject: [PATCH 10/24] feat(openapi): add brainx provider hello world --- api/custom.api | 1 + api/openapi.api | 5 +- api/openapi/provider/brainx/demo.api | 27 +++ api/powerx.api | 1 - api/pro.api | 1 + go.mod | 10 +- go.sum | 16 +- internal/config/openapiprovider/brainx.go | 7 +- .../provider/brainx/helloworldhandler.go | 22 +++ internal/handler/routes.go | 173 ++++++++-------- .../provider/brainx/helloworldlogic.go | 35 ++++ .../openapi/provider/brainx/schema/auth.go | 13 ++ .../provider/brainx/schema/helloworld.go | 5 + internal/provider/brainx/client.go | 186 ++++++++++++++++++ internal/provider/brainx/service.go | 38 ++++ internal/provider/providerclient.go | 8 + internal/types/types.go | 4 + 17 files changed, 455 insertions(+), 97 deletions(-) create mode 100644 api/openapi/provider/brainx/demo.api create mode 100644 internal/handler/openapi/provider/brainx/helloworldhandler.go create mode 100644 internal/logic/openapi/provider/brainx/helloworldlogic.go create mode 100644 internal/logic/openapi/provider/brainx/schema/auth.go create mode 100644 internal/logic/openapi/provider/brainx/schema/helloworld.go create mode 100644 internal/provider/brainx/client.go create mode 100644 internal/provider/brainx/service.go create mode 100644 internal/provider/providerclient.go diff --git a/api/custom.api b/api/custom.api index e69de29b..e063e1d0 100644 --- a/api/custom.api +++ b/api/custom.api @@ -0,0 +1 @@ +// Custom APis \ No newline at end of file diff --git a/api/openapi.api b/api/openapi.api index b0335ac3..d0fd2be2 100644 --- a/api/openapi.api +++ b/api/openapi.api @@ -1,2 +1,5 @@ import "openapi/auth.api" -import "openapi/demo.api" \ No newline at end of file +import "openapi/demo.api" + +// provider +import "openapi/provider/brainx/demo.api" diff --git a/api/openapi/provider/brainx/demo.api b/api/openapi/provider/brainx/demo.api new file mode 100644 index 00000000..96446e13 --- /dev/null +++ b/api/openapi/provider/brainx/demo.api @@ -0,0 +1,27 @@ +syntax = "v1" + +info( + title: "Provider Demo Open API of BrainX" + desc: "This is a api of Open API in Artisan Cloud" + author: "Matrix-X" + email: "matrix-x@artisan-cloud.com" + version: "v1" +) + +@server( + group: openapi/provider/brainx + prefix: /openapi/v1/provider/brainx +) + +service PowerX { + @doc "hello world api for provider demo" + @handler HelloWorld + get /hello-world returns (HelloWorldResponse) +} + + +type ( + HelloWorldResponse { + Message string `json:"message"` + } +) \ No newline at end of file diff --git a/api/powerx.api b/api/powerx.api index db8f42d1..f4295657 100644 --- a/api/powerx.api +++ b/api/powerx.api @@ -15,7 +15,6 @@ import "admin.wechat.offiaccount.api" import "mp.api" import "web.api" import "openapi.api" - import "pro.api" import "custom.api" import "plugin.api" diff --git a/api/pro.api b/api/pro.api index e69de29b..34472b11 100644 --- a/api/pro.api +++ b/api/pro.api @@ -0,0 +1 @@ +// Pro APis \ No newline at end of file diff --git a/go.mod b/go.mod index 495fba4c..f142e6a6 100644 --- a/go.mod +++ b/go.mod @@ -2,12 +2,14 @@ module PowerX go 1.23 +//replace github.com/ArtisanCloud/PowerLibs/v3 => ../../../PowerWechat/PowerLibs + //replace github.com/ArtisanCloud/PowerWeChat/v3 => ../../../PowerWechat/PowerWeChat require ( github.com/ArtisanCloud/PowerLibs/v3 v3.2.6 github.com/ArtisanCloud/PowerSocialite/v3 v3.0.7 - github.com/ArtisanCloud/PowerWeChat/v3 v3.2.42 + github.com/ArtisanCloud/PowerWeChat/v3 v3.2.45 github.com/Blank-Xu/sql-adapter v0.0.0-20210714092925-0bdd0d548758 github.com/brianvoe/gofakeit/v6 v6.21.0 github.com/casbin/casbin/v2 v2.60.0 @@ -25,7 +27,7 @@ require ( github.com/zeromicro/go-zero v1.7.2 github.com/zeromicro/go-zero/tools/goctl v1.7.2 github.com/zeromicro/zero-contrib/router/gin v0.0.0-20230708101417-16e73a5d116c - golang.org/x/crypto v0.26.0 + golang.org/x/crypto v0.27.0 golang.org/x/oauth2 v0.22.0 gopkg.in/yaml.v3 v3.0.1 gorm.io/datatypes v1.1.1 @@ -114,8 +116,8 @@ require ( golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect golang.org/x/net v0.28.0 // indirect golang.org/x/sync v0.8.0 // indirect - golang.org/x/sys v0.24.0 // indirect - golang.org/x/text v0.17.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20240903143218-8af14fe29dc1 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 // indirect google.golang.org/grpc v1.66.0 // indirect diff --git a/go.sum b/go.sum index c5609ce5..a253270b 100644 --- a/go.sum +++ b/go.sum @@ -391,8 +391,8 @@ github.com/ArtisanCloud/PowerLibs/v3 v3.2.6 h1:xNDXBJ1VNYAEgs4UG/lSygzU66/XG3mTA github.com/ArtisanCloud/PowerLibs/v3 v3.2.6/go.mod h1:xFGsskCnzAu+6rFEJbGVAlwhrwZPXAny6m7j71S/B5k= github.com/ArtisanCloud/PowerSocialite/v3 v3.0.7 h1:P+erNlErr+X2v7Et+yTWaTfIRhw+HfpAPdvNIEwk9Gw= github.com/ArtisanCloud/PowerSocialite/v3 v3.0.7/go.mod h1:VZQNCvcK/rldF3QaExiSl1gJEAkyc5/I8RLOd3WFZq4= -github.com/ArtisanCloud/PowerWeChat/v3 v3.2.42 h1:fU+/xJPGTAsSCyoeCn036VLBLUNjDnVrH0bls9HS9hg= -github.com/ArtisanCloud/PowerWeChat/v3 v3.2.42/go.mod h1:8GMw0a41XWr5EWpV/uXOluLCdOSMShgDLReH5FgxKZ8= +github.com/ArtisanCloud/PowerWeChat/v3 v3.2.45 h1:Wi8+OTRowLI82kBZfTg9DMyiZKWuUalU7B2BkshsQHE= +github.com/ArtisanCloud/PowerWeChat/v3 v3.2.45/go.mod h1:HgdxYE6yV9OAMKIvHNRHUShq6auhFK0T2sIpUd1dG5o= github.com/Blank-Xu/sql-adapter v0.0.0-20210714092925-0bdd0d548758 h1:L4iwZiJYTNirz4Er7Bw2+AVzW8VCpCGYc8luHc3y5lU= github.com/Blank-Xu/sql-adapter v0.0.0-20210714092925-0bdd0d548758/go.mod h1:GlBcPpgzETyqz83HIUFEMobVY38h1fOFXgwpy7T64xE= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= @@ -1094,8 +1094,8 @@ golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw golang.org/x/crypto v0.4.0/go.mod h1:3quD/ATkf6oY+rnes5c3ExXTbLc8mueNue5/DoinL80= golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw= -golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1357,8 +1357,8 @@ golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= -golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220526004731-065cf7ba2467/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -1385,8 +1385,8 @@ golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= -golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= diff --git a/internal/config/openapiprovider/brainx.go b/internal/config/openapiprovider/brainx.go index cec7217d..829cc689 100644 --- a/internal/config/openapiprovider/brainx.go +++ b/internal/config/openapiprovider/brainx.go @@ -1,7 +1,8 @@ package openapiprovider type BrainX struct { - BaseUrl string - AccessKey string - SecretKey string + BaseUrl string + AccessKey string + SecretKey string + ProviderName string } diff --git a/internal/handler/openapi/provider/brainx/helloworldhandler.go b/internal/handler/openapi/provider/brainx/helloworldhandler.go new file mode 100644 index 00000000..22f3f6b7 --- /dev/null +++ b/internal/handler/openapi/provider/brainx/helloworldhandler.go @@ -0,0 +1,22 @@ +package brainx + +import ( + "net/http" + + "PowerX/internal/logic/openapi/provider/brainx" + "PowerX/internal/svc" + "github.com/zeromicro/go-zero/rest/httpx" +) + +// hello world api for provider demo +func HelloWorldHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + l := brainx.NewHelloWorldLogic(r.Context(), svcCtx) + resp, err := l.HelloWorld() + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/internal/handler/routes.go b/internal/handler/routes.go index 552067c9..815d39e3 100644 --- a/internal/handler/routes.go +++ b/internal/handler/routes.go @@ -68,6 +68,7 @@ import ( mpinfoorganizationcategory "PowerX/internal/handler/mp/infoorganization/category" openapi "PowerX/internal/handler/openapi" openapiauth "PowerX/internal/handler/openapi/auth" + openapiproviderbrainx "PowerX/internal/handler/openapi/provider/brainx" plugin "PowerX/internal/handler/plugin" systemhealth "PowerX/internal/handler/system/health" webcustomerauth "PowerX/internal/handler/web/customer/auth" @@ -1419,10 +1420,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // App发送图文信息 - Method: http.MethodPost, - Path: "/message/articles", - Handler: adminscrmapp.SendWeWorkAppArticleMessageHandler(serverCtx), + // App详情 + Method: http.MethodGet, + Path: "/detail", + Handler: adminscrmapp.DetailWeWorkAppHandler(serverCtx), + }, + { + // App列表/options + Method: http.MethodGet, + Path: "/options", + Handler: adminscrmapp.ListWeWorkAppOptionHandler(serverCtx), }, }..., ), @@ -1461,16 +1468,10 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // App详情 - Method: http.MethodGet, - Path: "/detail", - Handler: adminscrmapp.DetailWeWorkAppHandler(serverCtx), - }, - { - // App列表/options - Method: http.MethodGet, - Path: "/options", - Handler: adminscrmapp.ListWeWorkAppOptionHandler(serverCtx), + // App发送图文信息 + Method: http.MethodPost, + Path: "/message/articles", + Handler: adminscrmapp.SendWeWorkAppArticleMessageHandler(serverCtx), }, }..., ), @@ -1542,16 +1543,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 所有客户列表/page + // 客户群列表/limit Method: http.MethodPost, - Path: "/page", - Handler: adminscrmcustomer.ListWeWorkCustomerPageHandler(serverCtx), + Path: "/group/list", + Handler: adminscrmcustomer.ListWeWorkCustomerGroupLimitHandler(serverCtx), }, { - // 批量同步客户信息(根据员工ID同步/节流) + // 客户群发信息 Method: http.MethodPost, - Path: "/sync", - Handler: adminscrmcustomer.SyncWeWorkCustomerOptionHandler(serverCtx), + Path: "/group/message/template", + Handler: adminscrmcustomer.SendWeWorkCustomerGroupMessageHandler(serverCtx), }, }..., ), @@ -1563,16 +1564,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 客户群列表/limit + // 所有客户列表/page Method: http.MethodPost, - Path: "/group/list", - Handler: adminscrmcustomer.ListWeWorkCustomerGroupLimitHandler(serverCtx), + Path: "/page", + Handler: adminscrmcustomer.ListWeWorkCustomerPageHandler(serverCtx), }, { - // 客户群发信息 + // 批量同步客户信息(根据员工ID同步/节流) Method: http.MethodPost, - Path: "/group/message/template", - Handler: adminscrmcustomer.SendWeWorkCustomerGroupMessageHandler(serverCtx), + Path: "/sync", + Handler: adminscrmcustomer.SyncWeWorkCustomerOptionHandler(serverCtx), }, }..., ), @@ -1584,16 +1585,10 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 同步组织架构/department&user - Method: http.MethodGet, - Path: "/sync", - Handler: adminscrmorganization.SyncWeWorkUserHandler(serverCtx), - }, - { - // 员工列表/page + // 部门列表/page Method: http.MethodPost, - Path: "/user/page", - Handler: adminscrmorganization.ListWeWorkUserPageHandler(serverCtx), + Path: "/partment/page", + Handler: adminscrmorganization.ListWeWorkDepartMentPageHandler(serverCtx), }, }..., ), @@ -1605,10 +1600,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 部门列表/page + // 同步组织架构/department&user + Method: http.MethodGet, + Path: "/sync", + Handler: adminscrmorganization.SyncWeWorkUserHandler(serverCtx), + }, + { + // 员工列表/page Method: http.MethodPost, - Path: "/partment/page", - Handler: adminscrmorganization.ListWeWorkDepartMentPageHandler(serverCtx), + Path: "/user/page", + Handler: adminscrmorganization.ListWeWorkUserPageHandler(serverCtx), }, }..., ), @@ -2056,16 +2057,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { server.AddRoutes( []rest.Route{ { - // 查询产品详情 + // 查询产品品类列表 Method: http.MethodGet, - Path: "/products/:id", - Handler: mpcrmproduct.GetProductHandler(serverCtx), + Path: "/product-categories", + Handler: mpcrmproduct.ListProductCategoriesHandler(serverCtx), }, { - // 产品列表 + // 查询产品品类树形表 Method: http.MethodGet, - Path: "/products/page-list", - Handler: mpcrmproduct.ListProductsPageHandler(serverCtx), + Path: "/product-category-tree", + Handler: mpcrmproduct.ListProductCategoryTreeHandler(serverCtx), }, }, rest.WithPrefix("/api/v1/mp/product"), @@ -2074,16 +2075,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { server.AddRoutes( []rest.Route{ { - // 查询产品品类列表 + // 查询产品详情 Method: http.MethodGet, - Path: "/product-categories", - Handler: mpcrmproduct.ListProductCategoriesHandler(serverCtx), + Path: "/products/:id", + Handler: mpcrmproduct.GetProductHandler(serverCtx), }, { - // 查询产品品类树形表 + // 产品列表 Method: http.MethodGet, - Path: "/product-category-tree", - Handler: mpcrmproduct.ListProductCategoryTreeHandler(serverCtx), + Path: "/products/page-list", + Handler: mpcrmproduct.ListProductsPageHandler(serverCtx), }, }, rest.WithPrefix("/api/v1/mp/product"), @@ -2394,36 +2395,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/mp/trade/token"), ) - server.AddRoutes( - []rest.Route{ - { - // 获取字典项列表 - Method: http.MethodGet, - Path: "/items", - Handler: mpdictionary.ListDictionaryItemsHandler(serverCtx), - }, - { - // 获取字典项 - Method: http.MethodGet, - Path: "/items/:type/:key", - Handler: mpdictionary.GetDictionaryItemHandler(serverCtx), - }, - { - // 获取字典类型 - Method: http.MethodGet, - Path: "/types/:type", - Handler: mpdictionary.GetDictionaryTypeHandler(serverCtx), - }, - { - // 获取字典类型列表 - Method: http.MethodGet, - Path: "/types/page-list", - Handler: mpdictionary.ListDictionaryPageTypesHandler(serverCtx), - }, - }, - rest.WithPrefix("/api/v1/mp/dictionary"), - ) - server.AddRoutes( rest.WithMiddlewares( []rest.Middleware{serverCtx.WebCustomerJWTAuth}, @@ -2457,6 +2428,36 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/web/dictionary"), ) + server.AddRoutes( + []rest.Route{ + { + // 获取字典项列表 + Method: http.MethodGet, + Path: "/items", + Handler: mpdictionary.ListDictionaryItemsHandler(serverCtx), + }, + { + // 获取字典项 + Method: http.MethodGet, + Path: "/items/:type/:key", + Handler: mpdictionary.GetDictionaryItemHandler(serverCtx), + }, + { + // 获取字典类型 + Method: http.MethodGet, + Path: "/types/:type", + Handler: mpdictionary.GetDictionaryTypeHandler(serverCtx), + }, + { + // 获取字典类型列表 + Method: http.MethodGet, + Path: "/types/page-list", + Handler: mpdictionary.ListDictionaryPageTypesHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1/mp/dictionary"), + ) + server.AddRoutes( []rest.Route{ { @@ -2532,6 +2533,18 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/openapi/v1/auth"), ) + server.AddRoutes( + []rest.Route{ + { + // hello world api for provider demo + Method: http.MethodGet, + Path: "/hello-world", + Handler: openapiproviderbrainx.HelloWorldHandler(serverCtx), + }, + }, + rest.WithPrefix("/openapi/v1/provider/brainx"), + ) + server.AddRoutes( []rest.Route{ { diff --git a/internal/logic/openapi/provider/brainx/helloworldlogic.go b/internal/logic/openapi/provider/brainx/helloworldlogic.go new file mode 100644 index 00000000..efc86617 --- /dev/null +++ b/internal/logic/openapi/provider/brainx/helloworldlogic.go @@ -0,0 +1,35 @@ +package brainx + +import ( + "PowerX/internal/provider/brainx" + "context" + + "PowerX/internal/svc" + "PowerX/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type HelloWorldLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// hello world api for provider demo +func NewHelloWorldLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HelloWorldLogic { + return &HelloWorldLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *HelloWorldLogic) HelloWorld() (resp *types.HelloWorldResponse, err error) { + brainXService := brainx.NewBrainXServiceProvider(l.svcCtx) + message, err := brainXService.HelloWorld() + + return &types.HelloWorldResponse{ + Message: message, + }, err +} diff --git a/internal/logic/openapi/provider/brainx/schema/auth.go b/internal/logic/openapi/provider/brainx/schema/auth.go new file mode 100644 index 00000000..32602da8 --- /dev/null +++ b/internal/logic/openapi/provider/brainx/schema/auth.go @@ -0,0 +1,13 @@ +package schema + +type AccessToken struct { + TokenType string `json:"token_type"` + ExpiresIn int64 `json:"expires_in"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` +} + +type ResponseAuthToken struct { + Platform string `json:"platform"` + Token AccessToken `json:"token"` +} diff --git a/internal/logic/openapi/provider/brainx/schema/helloworld.go b/internal/logic/openapi/provider/brainx/schema/helloworld.go new file mode 100644 index 00000000..a1a2e484 --- /dev/null +++ b/internal/logic/openapi/provider/brainx/schema/helloworld.go @@ -0,0 +1,5 @@ +package schema + +type ResponseHelloWorld struct { + Message string `json:"message"` +} diff --git a/internal/provider/brainx/client.go b/internal/provider/brainx/client.go new file mode 100644 index 00000000..c2658dc7 --- /dev/null +++ b/internal/provider/brainx/client.go @@ -0,0 +1,186 @@ +package brainx + +import ( + "PowerX/internal/config" + "PowerX/internal/logic/openapi/provider/brainx/schema" + providerclient "PowerX/internal/provider" + "bytes" + "encoding/json" + "fmt" + "github.com/ArtisanCloud/PowerLibs/v3/cache" + "github.com/pkg/errors" + "io" + "net/http" + "time" +) + +type BrainXProviderClient struct { + providerclient.ProviderClientInterface + + AuthToken *schema.ResponseAuthToken + BaseURL string + httpClient *http.Client + conf *config.Config + cache cache.CacheInterface + tokenKey string +} + +func NewBrainXProviderClient(config *config.Config, cache cache.CacheInterface) *BrainXProviderClient { + + return &BrainXProviderClient{ + BaseURL: config.OpenAPI.Providers.BrainX.BaseUrl, + httpClient: &http.Client{Timeout: 10 * time.Second}, + conf: config, + cache: cache, + tokenKey: "provider.brainx.access_token", + } +} + +func (sp *BrainXProviderClient) Auth() (*schema.ResponseAuthToken, error) { + url := "/auth" + + // 构造请求 body + body := map[string]string{ + "access_key": sp.conf.OpenAPI.Providers.BrainX.AccessKey, // 从配置中获取 + "secret_key": sp.conf.OpenAPI.Providers.BrainX.SecretKey, // 从配置中获取 + "platform": sp.conf.OpenAPI.Providers.BrainX.ProviderName, // 从配置中获取 + } + + // 发起 POST 请求 + resp, err := sp.HTTPPost(url, body, false, nil) // use_auth 设置为 false + if err != nil { + return nil, err + } + + // 将 JSON 响应转换为 ResponseAuthToken 对象 + var token *schema.ResponseAuthToken + err = json.Unmarshal(resp, &token) + if err != nil { + return nil, err + } + if token.Token.AccessToken == "" { + return nil, errors.New("auth returned invalid access token") + } + + return token, nil +} + +func (sp *BrainXProviderClient) GetAccessToken() (string, error) { + // 从缓存中获取 token + token, err := sp.cache.Get(sp.tokenKey, nil) + if err != nil { + if !errors.Is(err, cache.ErrCacheMiss) { + return "", err + } + } + + if token == nil { + // 如果缓存中没有 token,则调用 Auth 获取新的 token + sp.AuthToken, err = sp.Auth() + if err != nil { + return "", fmt.Errorf("request powerx provider auth error: %v", err) + } + + // 将 token 存入缓存,设置过期时间 + expiredIn := sp.AuthToken.Token.ExpiresIn + err = sp.cache.Set(sp.tokenKey, sp.AuthToken, time.Duration(expiredIn)*time.Second) + if err != nil { + return "", err + } + } else { + // 从 map[string]interface{} 转换到 ResponseAuthToken + tokenMap, ok := token.(map[string]interface{}) + if !ok { + return "", fmt.Errorf("invalid token type in cache") + } + + // Marshal and Unmarshal to convert + tokenBytes, err := json.Marshal(tokenMap) + if err != nil { + return "", err + } + + var authToken schema.ResponseAuthToken + if err := json.Unmarshal(tokenBytes, &authToken); err != nil { + return "", err + } + sp.AuthToken = &authToken + } + + // 返回 accessToken + return sp.AuthToken.Token.AccessToken, nil +} +func (sp *BrainXProviderClient) doRequest(req *http.Request, useAuth bool) ([]byte, error) { + // 如果需要授权,添加 Authorization 头部 + if useAuth { + token, err := sp.GetAccessToken() + if err != nil { + return nil, err + } + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) + } + + // 发起 HTTP 请求 + resp, err := sp.httpClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + // 检查 HTTP 响应状态码 + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("HTTP error: status code %d", resp.StatusCode) + } + + // 读取响应体 + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + return respBody, nil +} + +func (sp *BrainXProviderClient) HTTPGet(uri string, params map[string]string, useAuth bool, headers map[string]string) ([]byte, error) { + url := sp.BaseURL + uri + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, err + } + + // 添加查询参数 + q := req.URL.Query() + for k, v := range params { + q.Add(k, v) + } + req.URL.RawQuery = q.Encode() + + // 添加自定义头部信息 + for key, value := range headers { + req.Header.Set(key, value) + } + + return sp.doRequest(req, useAuth) +} + +func (sp *BrainXProviderClient) HTTPPost(uri string, jsonData interface{}, useAuth bool, headers map[string]string) ([]byte, error) { + // 将 jsonData 转换为 JSON 格式的字节流 + body, err := json.Marshal(jsonData) + if err != nil { + return nil, err + } + + url := sp.BaseURL + uri + req, err := http.NewRequest("POST", url, bytes.NewBuffer(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + + // 添加自定义头部信息 + for key, value := range headers { + req.Header.Set(key, value) + } + + return sp.doRequest(req, useAuth) +} diff --git a/internal/provider/brainx/service.go b/internal/provider/brainx/service.go new file mode 100644 index 00000000..3a887762 --- /dev/null +++ b/internal/provider/brainx/service.go @@ -0,0 +1,38 @@ +package brainx + +import ( + "PowerX/internal/logic/openapi/provider/brainx/schema" + "PowerX/internal/svc" + "encoding/json" +) + +type BrainXServiceProvider struct { + client *BrainXProviderClient +} + +func NewBrainXServiceProvider(svcCtx *svc.ServiceContext) *BrainXServiceProvider { + + return &BrainXServiceProvider{ + client: NewBrainXProviderClient(&svcCtx.Config, svcCtx.PowerX.Cache), + } +} + +func (sp *BrainXServiceProvider) HelloWorld() (message string, err error) { + url := "/demo/hello-world" + jsonBody := map[string]string{ + "name": "powerx", + "message": "hello", + } + resp, err := sp.client.HTTPPost(url, jsonBody, true, nil) + if err != nil { + return "", err + } + + result := schema.ResponseHelloWorld{} + err = json.Unmarshal(resp, &result) + if err != nil { + return "", err + } + + return result.Message, err +} diff --git a/internal/provider/providerclient.go b/internal/provider/providerclient.go new file mode 100644 index 00000000..07f79df0 --- /dev/null +++ b/internal/provider/providerclient.go @@ -0,0 +1,8 @@ +package providerclient + +type ProviderClientInterface interface { + Auth() error + GetAccessToken() (string, error) + HTTPGet(url string, params map[string]string, useAuth bool, headers map[string]string) (map[string]interface{}, error) + HTTPPost(url string, jsonData interface{}, useAuth bool, headers map[string]string) (map[string]interface{}, error) +} diff --git a/internal/types/types.go b/internal/types/types.go index 8acdef4a..678937bf 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -1662,6 +1662,10 @@ type HealthCheckReply struct { type HealthCheckRequest struct { } +type HelloWorldResponse struct { + Message string `json:"message"` +} + type Image struct { MediaId string `json:"mediaId,optional"` // 不填 PicUrl string `json:"picUrl,optional"` // 图片地址 From ab31569e6a0d9dcbb1db81bd5df9377722cf7d52 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 25 Sep 2024 13:35:59 +0800 Subject: [PATCH 11/24] update --- internal/provider/brainx/service.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/provider/brainx/service.go b/internal/provider/brainx/service.go index 3a887762..7ca4c604 100644 --- a/internal/provider/brainx/service.go +++ b/internal/provider/brainx/service.go @@ -7,13 +7,13 @@ import ( ) type BrainXServiceProvider struct { - client *BrainXProviderClient + Client *BrainXProviderClient } func NewBrainXServiceProvider(svcCtx *svc.ServiceContext) *BrainXServiceProvider { return &BrainXServiceProvider{ - client: NewBrainXProviderClient(&svcCtx.Config, svcCtx.PowerX.Cache), + Client: NewBrainXProviderClient(&svcCtx.Config, svcCtx.PowerX.Cache), } } @@ -23,7 +23,7 @@ func (sp *BrainXServiceProvider) HelloWorld() (message string, err error) { "name": "powerx", "message": "hello", } - resp, err := sp.client.HTTPPost(url, jsonBody, true, nil) + resp, err := sp.Client.HTTPPost(url, jsonBody, true, nil) if err != nil { return "", err } From 9e46e3e20aeeca7bf4b5a43f82caa2376903d178 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 25 Sep 2024 21:27:44 +0800 Subject: [PATCH 12/24] feat(openapi): timeout with context --- api/openapi/provider/brainx/demo.api | 12 ++ .../provider/brainx/echolongtimehandler.go | 29 ++++ internal/handler/routes.go | 136 +++++++++--------- .../provider/brainx/echolongtimelogic.go | 40 ++++++ .../provider/brainx/helloworldlogic.go | 2 +- .../brainx/schema/{helloworld.go => demo.go} | 4 + internal/provider/brainx/client.go | 31 ++-- internal/provider/brainx/service.go | 26 +++- internal/types/types.go | 8 ++ 9 files changed, 208 insertions(+), 80 deletions(-) create mode 100644 internal/handler/openapi/provider/brainx/echolongtimehandler.go create mode 100644 internal/logic/openapi/provider/brainx/echolongtimelogic.go rename internal/logic/openapi/provider/brainx/schema/{helloworld.go => demo.go} (54%) diff --git a/api/openapi/provider/brainx/demo.api b/api/openapi/provider/brainx/demo.api index 96446e13..c7776147 100644 --- a/api/openapi/provider/brainx/demo.api +++ b/api/openapi/provider/brainx/demo.api @@ -17,11 +17,23 @@ service PowerX { @doc "hello world api for provider demo" @handler HelloWorld get /hello-world returns (HelloWorldResponse) + + @doc "timeout api for provider demo" + @handler EchoLongTime + post /echo-long-time (EchoLongTimeRequest) returns (EchoLongTimeResponse) } + type ( HelloWorldResponse { Message string `json:"message"` } + + EchoLongTimeRequest { + Timeout int `json:"timeout"` + } + EchoLongTimeResponse { + Message string `json:"message"` + } ) \ No newline at end of file diff --git a/internal/handler/openapi/provider/brainx/echolongtimehandler.go b/internal/handler/openapi/provider/brainx/echolongtimehandler.go new file mode 100644 index 00000000..df4433fc --- /dev/null +++ b/internal/handler/openapi/provider/brainx/echolongtimehandler.go @@ -0,0 +1,29 @@ +package brainx + +import ( + "net/http" + + "PowerX/internal/logic/openapi/provider/brainx" + "PowerX/internal/svc" + "PowerX/internal/types" + "github.com/zeromicro/go-zero/rest/httpx" +) + +// timeout api for provider demo +func EchoLongTimeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.EchoLongTimeRequest + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := brainx.NewEchoLongTimeLogic(r.Context(), svcCtx) + resp, err := l.EchoLongTime(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/internal/handler/routes.go b/internal/handler/routes.go index 815d39e3..51599573 100644 --- a/internal/handler/routes.go +++ b/internal/handler/routes.go @@ -1420,16 +1420,22 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // App详情 - Method: http.MethodGet, - Path: "/detail", - Handler: adminscrmapp.DetailWeWorkAppHandler(serverCtx), + // App创建企业群 + Method: http.MethodPost, + Path: "/group/create", + Handler: adminscrmapp.CreateWeWorkAppGroupHandler(serverCtx), }, { - // App列表/options + // App企业群列表/list Method: http.MethodGet, - Path: "/options", - Handler: adminscrmapp.ListWeWorkAppOptionHandler(serverCtx), + Path: "/group/list", + Handler: adminscrmapp.ListWeWorkAppGroupHandler(serverCtx), + }, + { + // App企业群推送图文信息 + Method: http.MethodPost, + Path: "/group/message/articles", + Handler: adminscrmapp.SendWeWorkAppGroupArticleMessageHandler(serverCtx), }, }..., ), @@ -1441,22 +1447,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // App创建企业群 - Method: http.MethodPost, - Path: "/group/create", - Handler: adminscrmapp.CreateWeWorkAppGroupHandler(serverCtx), - }, - { - // App企业群列表/list + // App详情 Method: http.MethodGet, - Path: "/group/list", - Handler: adminscrmapp.ListWeWorkAppGroupHandler(serverCtx), + Path: "/detail", + Handler: adminscrmapp.DetailWeWorkAppHandler(serverCtx), }, { - // App企业群推送图文信息 - Method: http.MethodPost, - Path: "/group/message/articles", - Handler: adminscrmapp.SendWeWorkAppGroupArticleMessageHandler(serverCtx), + // App列表/options + Method: http.MethodGet, + Path: "/options", + Handler: adminscrmapp.ListWeWorkAppOptionHandler(serverCtx), }, }..., ), @@ -1543,16 +1543,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 客户群列表/limit + // 所有客户列表/page Method: http.MethodPost, - Path: "/group/list", - Handler: adminscrmcustomer.ListWeWorkCustomerGroupLimitHandler(serverCtx), + Path: "/page", + Handler: adminscrmcustomer.ListWeWorkCustomerPageHandler(serverCtx), }, { - // 客户群发信息 + // 批量同步客户信息(根据员工ID同步/节流) Method: http.MethodPost, - Path: "/group/message/template", - Handler: adminscrmcustomer.SendWeWorkCustomerGroupMessageHandler(serverCtx), + Path: "/sync", + Handler: adminscrmcustomer.SyncWeWorkCustomerOptionHandler(serverCtx), }, }..., ), @@ -1564,16 +1564,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 所有客户列表/page + // 客户群列表/limit Method: http.MethodPost, - Path: "/page", - Handler: adminscrmcustomer.ListWeWorkCustomerPageHandler(serverCtx), + Path: "/group/list", + Handler: adminscrmcustomer.ListWeWorkCustomerGroupLimitHandler(serverCtx), }, { - // 批量同步客户信息(根据员工ID同步/节流) + // 客户群发信息 Method: http.MethodPost, - Path: "/sync", - Handler: adminscrmcustomer.SyncWeWorkCustomerOptionHandler(serverCtx), + Path: "/group/message/template", + Handler: adminscrmcustomer.SendWeWorkCustomerGroupMessageHandler(serverCtx), }, }..., ), @@ -1585,10 +1585,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 部门列表/page + // 同步组织架构/department&user + Method: http.MethodGet, + Path: "/sync", + Handler: adminscrmorganization.SyncWeWorkUserHandler(serverCtx), + }, + { + // 员工列表/page Method: http.MethodPost, - Path: "/partment/page", - Handler: adminscrmorganization.ListWeWorkDepartMentPageHandler(serverCtx), + Path: "/user/page", + Handler: adminscrmorganization.ListWeWorkUserPageHandler(serverCtx), }, }..., ), @@ -1600,16 +1606,10 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 同步组织架构/department&user - Method: http.MethodGet, - Path: "/sync", - Handler: adminscrmorganization.SyncWeWorkUserHandler(serverCtx), - }, - { - // 员工列表/page + // 部门列表/page Method: http.MethodPost, - Path: "/user/page", - Handler: adminscrmorganization.ListWeWorkUserPageHandler(serverCtx), + Path: "/partment/page", + Handler: adminscrmorganization.ListWeWorkDepartMentPageHandler(serverCtx), }, }..., ), @@ -2535,6 +2535,12 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { server.AddRoutes( []rest.Route{ + { + // timeout api for provider demo + Method: http.MethodPost, + Path: "/echo-long-time", + Handler: openapiproviderbrainx.EchoLongTimeHandler(serverCtx), + }, { // hello world api for provider demo Method: http.MethodGet, @@ -2581,27 +2587,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/system"), ) - server.AddRoutes( - rest.WithMiddlewares( - []rest.Middleware{serverCtx.WebCustomerJWTAuth, serverCtx.WebCustomerGet}, - []rest.Route{ - { - // 客户信息更新 - Method: http.MethodPost, - Path: "/updateCustomerProfile/:id", - Handler: webcustomerauth.UpdateCustomerProfileHandler(serverCtx), - }, - { - // 获取用户信息 - Method: http.MethodGet, - Path: "/user-info", - Handler: webcustomerauth.GetUserInfoHandler(serverCtx), - }, - }..., - ), - rest.WithPrefix("/api/v1/web/customer"), - ) - server.AddRoutes( []rest.Route{ { @@ -2632,6 +2617,27 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/web/customer"), ) + server.AddRoutes( + rest.WithMiddlewares( + []rest.Middleware{serverCtx.WebCustomerJWTAuth, serverCtx.WebCustomerGet}, + []rest.Route{ + { + // 客户信息更新 + Method: http.MethodPost, + Path: "/updateCustomerProfile/:id", + Handler: webcustomerauth.UpdateCustomerProfileHandler(serverCtx), + }, + { + // 获取用户信息 + Method: http.MethodGet, + Path: "/user-info", + Handler: webcustomerauth.GetUserInfoHandler(serverCtx), + }, + }..., + ), + rest.WithPrefix("/api/v1/web/customer"), + ) + server.AddRoutes( []rest.Route{ { diff --git a/internal/logic/openapi/provider/brainx/echolongtimelogic.go b/internal/logic/openapi/provider/brainx/echolongtimelogic.go new file mode 100644 index 00000000..e9414cfe --- /dev/null +++ b/internal/logic/openapi/provider/brainx/echolongtimelogic.go @@ -0,0 +1,40 @@ +package brainx + +import ( + "PowerX/internal/provider/brainx" + "context" + "time" + + "PowerX/internal/svc" + "PowerX/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type EchoLongTimeLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// timeout api for provider demo +func NewEchoLongTimeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EchoLongTimeLogic { + return &EchoLongTimeLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *EchoLongTimeLogic) EchoLongTime(req *types.EchoLongTimeRequest) (resp *types.EchoLongTimeResponse, err error) { + + time.Sleep(60 * time.Second) + + return nil, nil + brainXService := brainx.NewBrainXServiceProvider(l.svcCtx) + message, err := brainXService.EchoLongTime(l.ctx, req.Timeout) + + return &types.EchoLongTimeResponse{ + Message: message, + }, err +} diff --git a/internal/logic/openapi/provider/brainx/helloworldlogic.go b/internal/logic/openapi/provider/brainx/helloworldlogic.go index efc86617..8f77ec7c 100644 --- a/internal/logic/openapi/provider/brainx/helloworldlogic.go +++ b/internal/logic/openapi/provider/brainx/helloworldlogic.go @@ -27,7 +27,7 @@ func NewHelloWorldLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HelloW func (l *HelloWorldLogic) HelloWorld() (resp *types.HelloWorldResponse, err error) { brainXService := brainx.NewBrainXServiceProvider(l.svcCtx) - message, err := brainXService.HelloWorld() + message, err := brainXService.HelloWorld(l.ctx) return &types.HelloWorldResponse{ Message: message, diff --git a/internal/logic/openapi/provider/brainx/schema/helloworld.go b/internal/logic/openapi/provider/brainx/schema/demo.go similarity index 54% rename from internal/logic/openapi/provider/brainx/schema/helloworld.go rename to internal/logic/openapi/provider/brainx/schema/demo.go index a1a2e484..1591f397 100644 --- a/internal/logic/openapi/provider/brainx/schema/helloworld.go +++ b/internal/logic/openapi/provider/brainx/schema/demo.go @@ -3,3 +3,7 @@ package schema type ResponseHelloWorld struct { Message string `json:"message"` } + +type ResponseEchoLongTime struct { + Message string `json:"message"` +} diff --git a/internal/provider/brainx/client.go b/internal/provider/brainx/client.go index c2658dc7..06da1368 100644 --- a/internal/provider/brainx/client.go +++ b/internal/provider/brainx/client.go @@ -5,10 +5,12 @@ import ( "PowerX/internal/logic/openapi/provider/brainx/schema" providerclient "PowerX/internal/provider" "bytes" + "context" "encoding/json" "fmt" "github.com/ArtisanCloud/PowerLibs/v3/cache" "github.com/pkg/errors" + "github.com/zeromicro/go-zero/core/contextx" "io" "net/http" "time" @@ -29,14 +31,14 @@ func NewBrainXProviderClient(config *config.Config, cache cache.CacheInterface) return &BrainXProviderClient{ BaseURL: config.OpenAPI.Providers.BrainX.BaseUrl, - httpClient: &http.Client{Timeout: 10 * time.Second}, + httpClient: &http.Client{Timeout: 60 * time.Second}, conf: config, cache: cache, tokenKey: "provider.brainx.access_token", } } -func (sp *BrainXProviderClient) Auth() (*schema.ResponseAuthToken, error) { +func (sp *BrainXProviderClient) Auth(ctx context.Context) (*schema.ResponseAuthToken, error) { url := "/auth" // 构造请求 body @@ -47,7 +49,7 @@ func (sp *BrainXProviderClient) Auth() (*schema.ResponseAuthToken, error) { } // 发起 POST 请求 - resp, err := sp.HTTPPost(url, body, false, nil) // use_auth 设置为 false + resp, err := sp.HTTPPost(ctx, url, body, false, nil) // use_auth 设置为 false if err != nil { return nil, err } @@ -65,7 +67,7 @@ func (sp *BrainXProviderClient) Auth() (*schema.ResponseAuthToken, error) { return token, nil } -func (sp *BrainXProviderClient) GetAccessToken() (string, error) { +func (sp *BrainXProviderClient) GetAccessToken(ctx context.Context) (string, error) { // 从缓存中获取 token token, err := sp.cache.Get(sp.tokenKey, nil) if err != nil { @@ -76,7 +78,7 @@ func (sp *BrainXProviderClient) GetAccessToken() (string, error) { if token == nil { // 如果缓存中没有 token,则调用 Auth 获取新的 token - sp.AuthToken, err = sp.Auth() + sp.AuthToken, err = sp.Auth(ctx) if err != nil { return "", fmt.Errorf("request powerx provider auth error: %v", err) } @@ -110,10 +112,10 @@ func (sp *BrainXProviderClient) GetAccessToken() (string, error) { // 返回 accessToken return sp.AuthToken.Token.AccessToken, nil } -func (sp *BrainXProviderClient) doRequest(req *http.Request, useAuth bool) ([]byte, error) { +func (sp *BrainXProviderClient) doRequest(ctx context.Context, req *http.Request, useAuth bool) ([]byte, error) { // 如果需要授权,添加 Authorization 头部 if useAuth { - token, err := sp.GetAccessToken() + token, err := sp.GetAccessToken(ctx) if err != nil { return nil, err } @@ -122,6 +124,7 @@ func (sp *BrainXProviderClient) doRequest(req *http.Request, useAuth bool) ([]by // 发起 HTTP 请求 resp, err := sp.httpClient.Do(req) + print(resp) if err != nil { return nil, err } @@ -141,7 +144,7 @@ func (sp *BrainXProviderClient) doRequest(req *http.Request, useAuth bool) ([]by return respBody, nil } -func (sp *BrainXProviderClient) HTTPGet(uri string, params map[string]string, useAuth bool, headers map[string]string) ([]byte, error) { +func (sp *BrainXProviderClient) HTTPGet(ctx context.Context, uri string, params map[string]string, useAuth bool, headers map[string]string) ([]byte, error) { url := sp.BaseURL + uri req, err := http.NewRequest("GET", url, nil) if err != nil { @@ -160,10 +163,14 @@ func (sp *BrainXProviderClient) HTTPGet(uri string, params map[string]string, us req.Header.Set(key, value) } - return sp.doRequest(req, useAuth) + return sp.doRequest(ctx, req, useAuth) } -func (sp *BrainXProviderClient) HTTPPost(uri string, jsonData interface{}, useAuth bool, headers map[string]string) ([]byte, error) { +func (sp *BrainXProviderClient) HTTPPost(ctx context.Context, uri string, jsonData interface{}, useAuth bool, headers map[string]string) ([]byte, error) { + newCtx := contextx.ValueOnlyFrom(ctx) + timeoutCtx, cancel := context.WithTimeout(newCtx, 60*time.Second) + defer cancel() + // 将 jsonData 转换为 JSON 格式的字节流 body, err := json.Marshal(jsonData) if err != nil { @@ -171,7 +178,7 @@ func (sp *BrainXProviderClient) HTTPPost(uri string, jsonData interface{}, useAu } url := sp.BaseURL + uri - req, err := http.NewRequest("POST", url, bytes.NewBuffer(body)) + req, err := http.NewRequestWithContext(timeoutCtx, "POST", url, bytes.NewBuffer(body)) if err != nil { return nil, err } @@ -182,5 +189,5 @@ func (sp *BrainXProviderClient) HTTPPost(uri string, jsonData interface{}, useAu req.Header.Set(key, value) } - return sp.doRequest(req, useAuth) + return sp.doRequest(timeoutCtx, req, useAuth) } diff --git a/internal/provider/brainx/service.go b/internal/provider/brainx/service.go index 7ca4c604..02def711 100644 --- a/internal/provider/brainx/service.go +++ b/internal/provider/brainx/service.go @@ -3,6 +3,7 @@ package brainx import ( "PowerX/internal/logic/openapi/provider/brainx/schema" "PowerX/internal/svc" + "context" "encoding/json" ) @@ -17,13 +18,13 @@ func NewBrainXServiceProvider(svcCtx *svc.ServiceContext) *BrainXServiceProvider } } -func (sp *BrainXServiceProvider) HelloWorld() (message string, err error) { +func (sp *BrainXServiceProvider) HelloWorld(ctx context.Context) (message string, err error) { url := "/demo/hello-world" jsonBody := map[string]string{ "name": "powerx", "message": "hello", } - resp, err := sp.Client.HTTPPost(url, jsonBody, true, nil) + resp, err := sp.Client.HTTPPost(ctx, url, jsonBody, true, nil) if err != nil { return "", err } @@ -36,3 +37,24 @@ func (sp *BrainXServiceProvider) HelloWorld() (message string, err error) { return result.Message, err } + +func (sp *BrainXServiceProvider) EchoLongTime(ctx context.Context, timeout int) (message string, err error) { + url := "/demo/echo-long-time" + jsonBody := map[string]int{ + "timeout": timeout, + } + + resp, err := sp.Client.HTTPPost(ctx, url, jsonBody, true, nil) + + if err != nil { + return "", err + } + + result := schema.ResponseEchoLongTime{} + err = json.Unmarshal(resp, &result) + if err != nil { + return "", err + } + + return result.Message, err +} diff --git a/internal/types/types.go b/internal/types/types.go index 678937bf..fe1c0125 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -1143,6 +1143,14 @@ type DisableProductRequest struct { ProductId int64 `path:"id"` } +type EchoLongTimeRequest struct { + Timeout int `json:"timeout"` +} + +type EchoLongTimeResponse struct { + Message string `json:"message"` +} + type ExchangeReply struct { Token string `json:"token"` RefreshToken string `json:"refreshToken"` From de8536cc65d3a93cb0316485dfad4425e9166201 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 25 Sep 2024 22:06:34 +0800 Subject: [PATCH 13/24] feat(openapi): timeout with context --- internal/provider/brainx/client.go | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/internal/provider/brainx/client.go b/internal/provider/brainx/client.go index 06da1368..8c893b07 100644 --- a/internal/provider/brainx/client.go +++ b/internal/provider/brainx/client.go @@ -10,7 +10,6 @@ import ( "fmt" "github.com/ArtisanCloud/PowerLibs/v3/cache" "github.com/pkg/errors" - "github.com/zeromicro/go-zero/core/contextx" "io" "net/http" "time" @@ -167,10 +166,6 @@ func (sp *BrainXProviderClient) HTTPGet(ctx context.Context, uri string, params } func (sp *BrainXProviderClient) HTTPPost(ctx context.Context, uri string, jsonData interface{}, useAuth bool, headers map[string]string) ([]byte, error) { - newCtx := contextx.ValueOnlyFrom(ctx) - timeoutCtx, cancel := context.WithTimeout(newCtx, 60*time.Second) - defer cancel() - // 将 jsonData 转换为 JSON 格式的字节流 body, err := json.Marshal(jsonData) if err != nil { @@ -178,7 +173,7 @@ func (sp *BrainXProviderClient) HTTPPost(ctx context.Context, uri string, jsonDa } url := sp.BaseURL + uri - req, err := http.NewRequestWithContext(timeoutCtx, "POST", url, bytes.NewBuffer(body)) + req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(body)) if err != nil { return nil, err } @@ -189,5 +184,5 @@ func (sp *BrainXProviderClient) HTTPPost(ctx context.Context, uri string, jsonDa req.Header.Set(key, value) } - return sp.doRequest(timeoutCtx, req, useAuth) + return sp.doRequest(ctx, req, useAuth) } From 295d7e004ebb0f55c75d5fd7534fc2766e8b2c4e Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 25 Sep 2024 22:42:47 +0800 Subject: [PATCH 14/24] feat(openapi): timeout with context --- .../logic/openapi/provider/brainx/echolongtimelogic.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/internal/logic/openapi/provider/brainx/echolongtimelogic.go b/internal/logic/openapi/provider/brainx/echolongtimelogic.go index e9414cfe..7ecc10eb 100644 --- a/internal/logic/openapi/provider/brainx/echolongtimelogic.go +++ b/internal/logic/openapi/provider/brainx/echolongtimelogic.go @@ -2,11 +2,9 @@ package brainx import ( "PowerX/internal/provider/brainx" - "context" - "time" - "PowerX/internal/svc" "PowerX/internal/types" + "context" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,9 +26,9 @@ func NewEchoLongTimeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Echo func (l *EchoLongTimeLogic) EchoLongTime(req *types.EchoLongTimeRequest) (resp *types.EchoLongTimeResponse, err error) { - time.Sleep(60 * time.Second) + //time.Sleep(60 * time.Second) + //return nil, nil - return nil, nil brainXService := brainx.NewBrainXServiceProvider(l.svcCtx) message, err := brainXService.EchoLongTime(l.ctx, req.Timeout) From 201e935a7c558b85a345f093f65af3f6300b6ed1 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Sun, 29 Sep 2024 00:37:34 +0800 Subject: [PATCH 15/24] fix(openapi): provider demo need auth with openapi token --- api/openapi/provider/brainx/demo.api | 1 + internal/handler/routes.go | 109 ++++++++++++++------------- 2 files changed, 57 insertions(+), 53 deletions(-) diff --git a/api/openapi/provider/brainx/demo.api b/api/openapi/provider/brainx/demo.api index c7776147..5a0613a9 100644 --- a/api/openapi/provider/brainx/demo.api +++ b/api/openapi/provider/brainx/demo.api @@ -11,6 +11,7 @@ info( @server( group: openapi/provider/brainx prefix: /openapi/v1/provider/brainx + middleware: OpenAPIJWTAuth ) service PowerX { diff --git a/internal/handler/routes.go b/internal/handler/routes.go index 51599573..29118615 100644 --- a/internal/handler/routes.go +++ b/internal/handler/routes.go @@ -1415,6 +1415,21 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/admin/position"), ) + server.AddRoutes( + rest.WithMiddlewares( + []rest.Middleware{serverCtx.UserJWTAuth}, + []rest.Route{ + { + // App发送图文信息 + Method: http.MethodPost, + Path: "/message/articles", + Handler: adminscrmapp.SendWeWorkAppArticleMessageHandler(serverCtx), + }, + }..., + ), + rest.WithPrefix("/api/v1/admin/scrm/app/wechat"), + ) + server.AddRoutes( rest.WithMiddlewares( []rest.Middleware{serverCtx.UserJWTAuth}, @@ -1463,21 +1478,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/admin/scrm/app/wechat"), ) - server.AddRoutes( - rest.WithMiddlewares( - []rest.Middleware{serverCtx.UserJWTAuth}, - []rest.Route{ - { - // App发送图文信息 - Method: http.MethodPost, - Path: "/message/articles", - Handler: adminscrmapp.SendWeWorkAppArticleMessageHandler(serverCtx), - }, - }..., - ), - rest.WithPrefix("/api/v1/admin/scrm/app/wechat"), - ) - server.AddRoutes( rest.WithMiddlewares( []rest.Middleware{serverCtx.UserJWTAuth}, @@ -1543,16 +1543,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 所有客户列表/page + // 客户群列表/limit Method: http.MethodPost, - Path: "/page", - Handler: adminscrmcustomer.ListWeWorkCustomerPageHandler(serverCtx), + Path: "/group/list", + Handler: adminscrmcustomer.ListWeWorkCustomerGroupLimitHandler(serverCtx), }, { - // 批量同步客户信息(根据员工ID同步/节流) + // 客户群发信息 Method: http.MethodPost, - Path: "/sync", - Handler: adminscrmcustomer.SyncWeWorkCustomerOptionHandler(serverCtx), + Path: "/group/message/template", + Handler: adminscrmcustomer.SendWeWorkCustomerGroupMessageHandler(serverCtx), }, }..., ), @@ -1564,16 +1564,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 客户群列表/limit + // 所有客户列表/page Method: http.MethodPost, - Path: "/group/list", - Handler: adminscrmcustomer.ListWeWorkCustomerGroupLimitHandler(serverCtx), + Path: "/page", + Handler: adminscrmcustomer.ListWeWorkCustomerPageHandler(serverCtx), }, { - // 客户群发信息 + // 批量同步客户信息(根据员工ID同步/节流) Method: http.MethodPost, - Path: "/group/message/template", - Handler: adminscrmcustomer.SendWeWorkCustomerGroupMessageHandler(serverCtx), + Path: "/sync", + Handler: adminscrmcustomer.SyncWeWorkCustomerOptionHandler(serverCtx), }, }..., ), @@ -2057,16 +2057,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { server.AddRoutes( []rest.Route{ { - // 查询产品品类列表 + // 查询产品详情 Method: http.MethodGet, - Path: "/product-categories", - Handler: mpcrmproduct.ListProductCategoriesHandler(serverCtx), + Path: "/products/:id", + Handler: mpcrmproduct.GetProductHandler(serverCtx), }, { - // 查询产品品类树形表 + // 产品列表 Method: http.MethodGet, - Path: "/product-category-tree", - Handler: mpcrmproduct.ListProductCategoryTreeHandler(serverCtx), + Path: "/products/page-list", + Handler: mpcrmproduct.ListProductsPageHandler(serverCtx), }, }, rest.WithPrefix("/api/v1/mp/product"), @@ -2075,16 +2075,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { server.AddRoutes( []rest.Route{ { - // 查询产品详情 + // 查询产品品类列表 Method: http.MethodGet, - Path: "/products/:id", - Handler: mpcrmproduct.GetProductHandler(serverCtx), + Path: "/product-categories", + Handler: mpcrmproduct.ListProductCategoriesHandler(serverCtx), }, { - // 产品列表 + // 查询产品品类树形表 Method: http.MethodGet, - Path: "/products/page-list", - Handler: mpcrmproduct.ListProductsPageHandler(serverCtx), + Path: "/product-category-tree", + Handler: mpcrmproduct.ListProductCategoryTreeHandler(serverCtx), }, }, rest.WithPrefix("/api/v1/mp/product"), @@ -2534,20 +2534,23 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { ) server.AddRoutes( - []rest.Route{ - { - // timeout api for provider demo - Method: http.MethodPost, - Path: "/echo-long-time", - Handler: openapiproviderbrainx.EchoLongTimeHandler(serverCtx), - }, - { - // hello world api for provider demo - Method: http.MethodGet, - Path: "/hello-world", - Handler: openapiproviderbrainx.HelloWorldHandler(serverCtx), - }, - }, + rest.WithMiddlewares( + []rest.Middleware{serverCtx.OpenAPIJWTAuth}, + []rest.Route{ + { + // timeout api for provider demo + Method: http.MethodPost, + Path: "/echo-long-time", + Handler: openapiproviderbrainx.EchoLongTimeHandler(serverCtx), + }, + { + // hello world api for provider demo + Method: http.MethodGet, + Path: "/hello-world", + Handler: openapiproviderbrainx.HelloWorldHandler(serverCtx), + }, + }..., + ), rest.WithPrefix("/openapi/v1/provider/brainx"), ) From 9c5e840cdb6c57e5011d6f6d36538d45d4f39436 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Sun, 6 Oct 2024 10:46:07 +0800 Subject: [PATCH 16/24] draft(mediaresrouce): add UploadVideoFromURL --- api/{openapi => }/provider/brainx/demo.api | 0 internal/uc/powerx/mediaresource.go | 83 +++++++++++++++++++++- 2 files changed, 81 insertions(+), 2 deletions(-) rename api/{openapi => }/provider/brainx/demo.api (100%) diff --git a/api/openapi/provider/brainx/demo.api b/api/provider/brainx/demo.api similarity index 100% rename from api/openapi/provider/brainx/demo.api rename to api/provider/brainx/demo.api diff --git a/internal/uc/powerx/mediaresource.go b/internal/uc/powerx/mediaresource.go index d477c5c0..94fe0e1e 100644 --- a/internal/uc/powerx/mediaresource.go +++ b/internal/uc/powerx/mediaresource.go @@ -25,6 +25,13 @@ import ( const DefaultStoragePath = "resource/static" +// 分片上传配置常量 +const ( + MultipartPartSize = 100 * 1024 * 1024 // 100MB + MultipartConcurrency = 5 + MultipartMaxRetries = 3 +) + // MediaResourceUseCase Use Case type MediaResourceUseCase struct { db *gorm.DB @@ -34,6 +41,7 @@ type MediaResourceUseCase struct { } const BucketMediaResourceProduct = "bucket.product" +const BucketMediaResourceVideo = "bucket.video" func NewMediaResourceUseCase(db *gorm.DB, conf *config.Config) *MediaResourceUseCase { // 使用Minio API SDK @@ -265,9 +273,9 @@ func (uc *MediaResourceUseCase) MakeOSSResourceByBase64String(ctx context.Contex } -func (m *MediaResourceUseCase) GetBase64DataFromMedia(ctx context.Context, media *media.MediaResource) (string, error) { +func (uc *MediaResourceUseCase) GetBase64DataFromMedia(ctx context.Context, media *media.MediaResource) (string, error) { // 从OSS中获取图片数据 - url, err := m.GetOSSResourceURL(media.BucketName, media.Filename) + url, err := uc.GetOSSResourceURL(media.BucketName, media.Filename) if err != nil { return "", err } @@ -382,3 +390,74 @@ func (uc *MediaResourceUseCase) GetCachedBase64DataFromMedia(ctx context.Context return data.(string), err } + +func (uc *MediaResourceUseCase) UploadVideoFromURL(ctx context.Context, mediaConfig *config.MediaResource, bucket string, videoURL string) error { + minioConfig := mediaConfig.OSS.Minio + client, err := minio.NewCore(minioConfig.Endpoint, &minio.Options{ + Creds: credentials.NewStaticV4(minioConfig.Credentials.AccessKey, minioConfig.Credentials.SecretKey, ""), + Secure: minioConfig.UseSSL, + }) + + // 从视频 URL 下载视频文件 + resp, err := http.Get(videoURL) + if err != nil { + return errors.Wrap(err, "failed to download video from URL") + } + defer resp.Body.Close() + + // 检查响应状态 + if resp.StatusCode != http.StatusOK { + return errors.Errorf("failed to download video, status code: %d", resp.StatusCode) + } + + // 设置上传的对象名称 + objectName := "uploaded_video.mp4" // 根据需要设置对象名称 + + // 创建分片上传 + uploadID, err := client.NewMultipartUpload(ctx, bucket, objectName, minio.PutObjectOptions{ + ContentType: "video/mp4", // 根据实际视频类型设置 + }) + if err != nil { + return errors.Wrap(err, "failed to initiate multipart upload") + } + + // 定义分片大小,MinIO 的限制通常为 5MB + const partSize = 5 * 1024 * 1024 // 5MB + var partNumber int + var completeParts []minio.CompletePart // 存储每个分片的信息 + + // 循环读取分片并上传 + for { + buf := make([]byte, partSize) + n, err := resp.Body.Read(buf) + if err == io.EOF { + break // 到达文件结尾 + } + if err != nil { + return errors.Wrap(err, "failed to read from response body") + } + + // 上传分片 + partNumber++ + partReader := io.LimitReader(resp.Body, int64(n)) // 限制读取的字节数 + objectPart, err := client.PutObjectPart(ctx, bucket, objectName, uploadID, partNumber, partReader, int64(n), minio.PutObjectPartOptions{}) + if err != nil { + return errors.Wrap(err, "failed to upload part") + } + + // 将上传的分片信息添加到 completeParts 列表中 + completeParts = append(completeParts, minio.CompletePart{ + ETag: objectPart.ETag, // 使用 ObjectPart 中的 ETag + PartNumber: partNumber, // 使用分片编号 + }) + } + + // 完成分片上传 + _, err = client.CompleteMultipartUpload(ctx, bucket, objectName, uploadID, completeParts, minio.PutObjectOptions{}) + if err != nil { + return errors.Wrap(err, "failed to complete multipart upload") + } + + fmt.Println("Upload completed successfully") + return nil +} From b4bc5a82db5a262880cf0aa878bd640a0ff41dc6 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Tue, 8 Oct 2024 10:48:15 +0800 Subject: [PATCH 17/24] update --- internal/model/infoorganization/category.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/model/infoorganization/category.go b/internal/model/infoorganization/category.go index 41add634..6aa48fb3 100644 --- a/internal/model/infoorganization/category.go +++ b/internal/model/infoorganization/category.go @@ -24,6 +24,7 @@ type Category struct { model.ImageAbleInfo } +const TableNameCategory = "categories" const CategoryUniqueId = powermodel.UniqueId func (mdl *Category) GetCategoryIds(categories []*Category) []int64 { From d176f26ecea4860ad6eba7e58cf56bc78365cc4a Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Tue, 8 Oct 2024 17:58:17 +0800 Subject: [PATCH 18/24] feat(table): make tables name into table.go --- api/admin/scrm/customer/weworkcustomer.api | 2 +- .../scrm/qrcode/weworkcustomergroupqrcode.api | 2 +- api/web/scene/qrcode.api | 4 +- cmd/ctl/database/migrate/powerx.go | 37 +++++- cmd/ctl/database/seed/organization.go | 18 +-- cmd/ctl/powerxctl.go | 15 ++- cmd/server/powerx.go | 2 + etc/powerx-example.yaml | 4 + internal/config/database.go | 1 + .../admin/department/createdepartmentlogic.go | 3 +- .../admin/position/createpositionlogic.go | 3 +- .../admin/position/patchpositionlogic.go | 5 +- .../customer/listweworkcustomerpagelogic.go | 71 ++++++------ .../customer/syncweworkcustomeroptionlogic.go | 2 +- .../scrm/qrcode/listweworkqrcodepagelogic.go | 44 ++++--- .../qrcode/updateactiveqrcodelinklogic.go | 84 +++++++------- internal/logic/admin/user/createuserlogic.go | 5 +- internal/logic/admin/user/getuserlogic.go | 3 +- internal/logic/admin/user/listuserlogic.go | 7 +- .../logic/admin/user/resetpasswordlogic.go | 3 +- internal/logic/admin/user/updateuserlogic.go | 5 +- .../logic/admin/userinfo/getuserinfologic.go | 3 +- .../admin/userinfo/modifyuserpasswordlogic.go | 3 +- internal/logic/web/scene/detailqrcodelogic.go | 17 ++- internal/model/crm/customerdomain/contact.go | 13 +++ internal/model/crm/customerdomain/customer.go | 13 +++ internal/model/crm/customerdomain/lead.go | 13 +++ .../model/crm/customerdomain/registercode.go | 13 +++ internal/model/crm/market/media.go | 4 +- internal/model/crm/market/store.go | 6 +- internal/model/crm/operation/ticket.go | 9 +- internal/model/crm/product/artisan.go | 6 +- .../product/pivotproducttoproductcategory.go | 5 +- .../crm/product/pivotskutospecificoption.go | 5 +- .../model/crm/product/pivotstoretoartisan.go | 5 +- internal/model/crm/product/pricebook.go | 1 - internal/model/crm/product/pricebookentry.go | 1 - internal/model/crm/product/priceconfig.go | 2 - internal/model/crm/product/product.go | 21 ++-- internal/model/crm/product/sku.go | 1 - .../crm/trade/pivotproducttopromotion.go | 1 - internal/model/datadictionary.go | 2 - internal/model/infoorganization/category.go | 1 - .../infoorganization/pivotcategorytobject.go | 5 +- .../infoorganization/pivotlabeltobject.go | 5 +- .../model/infoorganization/pivottagtobject.go | 5 +- .../model/media/pivotMediaResourceToObject.go | 5 +- .../model/{powermodel => }/operationlog.go | 16 +-- .../department.go | 2 +- .../position.go | 2 +- .../{origanzation => organization}/user.go | 2 +- .../user_test.go | 2 +- internal/model/scene/activeqrcode.go | 20 ++-- internal/model/scrm/app/weworkappgroup.go | 2 +- .../model/scrm/customer/weworkcustomer.go | 35 +++--- .../customer/weworkcustomerExternalFollow.go | 40 +++---- .../scrm/organization/weworkdepartment.go | 2 +- .../model/scrm/organization/weworkuser.go | 2 +- internal/model/scrm/resource/department.go | 65 +++++------ internal/model/scrm/tag/weworkgroup.go | 31 +++-- internal/model/scrm/tag/weworktag.go | 2 +- internal/model/tables.go | 107 ++++++++++++++++++ internal/model/tag/pivotobjecttotag.go | 5 +- internal/model/wechat/wework.go | 37 +++--- internal/types/types.go | 6 +- internal/uc/powerx/authorizationadmin.go | 10 +- internal/uc/powerx/organization.go | 96 ++++++++-------- internal/uc/powerx/scrm/scene/interface.go | 4 +- internal/uc/powerx/scrm/scene/qrcodescene.go | 8 +- internal/uc/powerx/scrm/scene/scene.go | 6 +- internal/uc/powerx/scrm/wechat/interface.go | 10 +- internal/uc/powerx/scrm/wechat/wechat.go | 8 +- .../scrm/wechat/wechatqrcodecustomergroup.go | 16 +-- .../uc/powerx/scrm/wechat/weworkcustomer.go | 20 ++-- internal/uc/powerx/scrm/wechat/weworkuser.go | 8 +- swagger/qrcode.json | 6 +- 76 files changed, 600 insertions(+), 455 deletions(-) rename internal/model/{powermodel => }/operationlog.go (90%) rename internal/model/{origanzation => organization}/department.go (98%) rename internal/model/{origanzation => organization}/position.go (95%) rename internal/model/{origanzation => organization}/user.go (99%) rename internal/model/{origanzation => organization}/user_test.go (94%) create mode 100644 internal/model/tables.go diff --git a/api/admin/scrm/customer/weworkcustomer.api b/api/admin/scrm/customer/weworkcustomer.api index fd8bdfcd..b43bd305 100644 --- a/api/admin/scrm/customer/weworkcustomer.api +++ b/api/admin/scrm/customer/weworkcustomer.api @@ -105,7 +105,7 @@ type ( UserId string `json:"userId"` Remark string `json:"remark"` Description string `json:"description"` - Createtime int `json:"createtime"` + CreatedTime int `json:"createtime"` Tags []WechatCustomersFollowUserWithTags `json:"tags"` TagIds []string `json:"tagIds"` WechatChannels WechatCustomersFollowUserWithWechatChannels `json:"wechatChannels"` diff --git a/api/admin/scrm/qrcode/weworkcustomergroupqrcode.api b/api/admin/scrm/qrcode/weworkcustomergroupqrcode.api index a83c30a3..73450d10 100644 --- a/api/admin/scrm/qrcode/weworkcustomergroupqrcode.api +++ b/api/admin/scrm/qrcode/weworkcustomergroupqrcode.api @@ -92,6 +92,6 @@ type ( ActionRequest { Qid string `path:"qid"`// 唯一标识 - SceneQrcodeLink string `json:"sceneQrcodeLink,optional"` + SceneQRCodeLink string `json:"sceneQrcodeLink,optional"` } ) diff --git a/api/web/scene/qrcode.api b/api/web/scene/qrcode.api index eecbdba0..6950c098 100644 --- a/api/web/scene/qrcode.api +++ b/api/web/scene/qrcode.api @@ -16,7 +16,7 @@ info( service PowerX { @doc "获取场景落地页详情" @handler DetailQrcode - get /qrcode/detail/:qid(SceneRequest) returns (SceneQrcodeActiveReply) + get /qrcode/detail/:qid(SceneRequest) returns (SceneQRCodeActiveReply) } @@ -27,7 +27,7 @@ type ( Status string `json:"status"` } - SceneQrcodeActiveReply { + SceneQRCodeActiveReply { QId string `json:"qid"` // 唯一码 Name string `json:"name"` // 活码名称 diff --git a/cmd/ctl/database/migrate/powerx.go b/cmd/ctl/database/migrate/powerx.go index d2c856a5..3fa5fe2b 100644 --- a/cmd/ctl/database/migrate/powerx.go +++ b/cmd/ctl/database/migrate/powerx.go @@ -12,15 +12,16 @@ import ( "PowerX/internal/model/crm/trade" infoorganizatoin "PowerX/internal/model/infoorganization" "PowerX/internal/model/media" - "PowerX/internal/model/origanzation" + "PowerX/internal/model/organization" "PowerX/internal/model/permission" "PowerX/internal/model/scene" "PowerX/internal/model/scrm/app" "PowerX/internal/model/scrm/customer" - "PowerX/internal/model/scrm/organization" + organization2 "PowerX/internal/model/scrm/organization" "PowerX/internal/model/scrm/resource" "PowerX/internal/model/scrm/tag" "PowerX/internal/model/wechat" + "fmt" "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/gorm" @@ -48,10 +49,34 @@ func NewPowerMigrator(conf *config.Config) (*PowerMigrator, error) { }, err } +func (m *PowerMigrator) InitSchema(schema string) error { + // 检查 schema 是否存在 + var exists bool + query := `SELECT EXISTS (SELECT 1 FROM information_schema.schemata WHERE schema_name = ?);` + err := m.db.Raw(query, schema).Scan(&exists).Error + if err != nil { + return fmt.Errorf("failed to check schema existence: %w", err) + } + + // 如果 schema 不存在,创建它 + if !exists { + createSchemaQuery := fmt.Sprintf("CREATE SCHEMA %s;", schema) + err := m.db.Exec(createSchemaQuery).Error + if err != nil { + return fmt.Errorf("failed to create schema: %w", err) + } + fmt.Printf("Schema %s created successfully.\n", schema) + } else { + fmt.Printf("Schema %s already exists.\n", schema) + } + + return nil +} + func (m *PowerMigrator) AutoMigrate() { _ = m.db.AutoMigrate(&model.DataDictionaryType{}, &model.DataDictionaryItem{}, &model.PivotDataDictionaryToObject{}) - _ = m.db.AutoMigrate(&origanzation.Department{}, &origanzation.User{}, &origanzation.Position{}) + _ = m.db.AutoMigrate(&organization.Department{}, &organization.User{}, &organization.Position{}) _ = m.db.AutoMigrate(&permission.UserCasbinPolicy{}, permission.AdminRole{}, permission.AdminRoleMenuName{}, permission.AdminAPI{}) // info organization @@ -100,9 +125,9 @@ func (m *PowerMigrator) AutoMigrate() { migrate.AutoMigrateCustom(m.db) // wechat organization - _ = m.db.AutoMigrate(&organization.WeWorkUser{}, &organization.WeWorkDepartment{}) + _ = m.db.AutoMigrate(&organization2.WeWorkUser{}, &organization2.WeWorkDepartment{}) // wechat customer - _ = m.db.AutoMigrate(&customer.WeWorkExternalContacts{}, &customer.WeWorkExternalContactFollow{}) + _ = m.db.AutoMigrate(&customer.WeWorkExternalContact{}, &customer.WeWorkExternalContactFollow{}) // wechat resource _ = m.db.AutoMigrate(&resource.WeWorkResource{}) // wechat app @@ -110,5 +135,5 @@ func (m *PowerMigrator) AutoMigrate() { // wechat tag _ = m.db.AutoMigrate(&tag.WeWorkTag{}, &tag.WeWorkTagGroup{}) // qrcode - _ = m.db.AutoMigrate(&scene.SceneQrcode{}) + _ = m.db.AutoMigrate(&scene.SceneQRCode{}) } diff --git a/cmd/ctl/database/seed/organization.go b/cmd/ctl/database/seed/organization.go index 5aa51724..e880544a 100644 --- a/cmd/ctl/database/seed/organization.go +++ b/cmd/ctl/database/seed/organization.go @@ -1,7 +1,7 @@ package seed import ( - "PowerX/internal/model/origanzation" + "PowerX/internal/model/organization" "PowerX/internal/uc/powerx" "context" "github.com/pkg/errors" @@ -10,12 +10,12 @@ import ( func CreateOrganization(db *gorm.DB) (err error) { var count int64 - if err = db.Model(&origanzation.Department{}).Count(&count).Error; err != nil { + if err = db.Model(&organization.Department{}).Count(&count).Error; err != nil { panic(errors.Wrap(err, "init root dep failed")) } if count == 0 { dep := DefaultDepartment() - if err := db.Model(&origanzation.Department{}).Create(&dep).Error; err != nil { + if err := db.Model(&organization.Department{}).Create(&dep).Error; err != nil { panic(errors.Wrap(err, "init root dep failed")) } } @@ -23,8 +23,8 @@ func CreateOrganization(db *gorm.DB) (err error) { return err } -func DefaultDepartment() *origanzation.Department { - return &origanzation.Department{ +func DefaultDepartment() *organization.Department { + return &organization.Department{ Name: "组织架构", PId: 0, Desc: "根节点, 别删除", @@ -37,8 +37,8 @@ func CreateDefaultDepartments(db *gorm.DB) error { departments := DefaultDepartments() ucOrg := powerx.NewOrganizationUseCase(db) for _, department := range departments { - existDep := &origanzation.Department{} - res := db.Model(&origanzation.Department{}).Where(origanzation.Department{Name: department.Name}).First(existDep) + existDep := &organization.Department{} + res := db.Model(&organization.Department{}).Where(organization.Department{Name: department.Name}).First(existDep) //fmt.Dump(existDep, res.Error) if errors.Is(res.Error, gorm.ErrRecordNotFound) { _ = ucOrg.CreateDepartment(context.Background(), department) @@ -47,8 +47,8 @@ func CreateDefaultDepartments(db *gorm.DB) error { return nil } -func DefaultDepartments() (departments []*origanzation.Department) { - departments = []*origanzation.Department{ +func DefaultDepartments() (departments []*organization.Department) { + departments = []*organization.Department{ { Name: "产品部门", PId: 1, diff --git a/cmd/ctl/powerxctl.go b/cmd/ctl/powerxctl.go index bf3341d4..8904732a 100644 --- a/cmd/ctl/powerxctl.go +++ b/cmd/ctl/powerxctl.go @@ -5,6 +5,7 @@ import ( "PowerX/cmd/ctl/database/seed" "PowerX/cmd/ctl/gen" "PowerX/internal/config" + "PowerX/internal/model" "PowerX/internal/uc" "fmt" "github.com/urfave/cli/v2" @@ -93,10 +94,22 @@ func ActionMigrate(cCtx *cli.Context) error { var c config.Config conf.MustLoad(configFile, &c) c.EtcDir = filepath.Dir(configFile) + model.PowerXSchema = c.PowerXDatabase.Schema // migrate tables - m, _ := migrate.NewPowerMigrator(&c) + m, err := migrate.NewPowerMigrator(&c) + if err != nil { + panic(err) + } + // create schema if not exists + err = m.InitSchema(model.PowerXSchema) + if err != nil { + panic(err) + } + // migrate tables m.AutoMigrate() + + // init admin authorization powerx, _ := uc.NewPowerXUseCase(&c) powerx.AdminAuthorization.Init() diff --git a/cmd/server/powerx.go b/cmd/server/powerx.go index 0eed8db3..5657ef2d 100644 --- a/cmd/server/powerx.go +++ b/cmd/server/powerx.go @@ -2,6 +2,7 @@ package main import ( "PowerX/internal/middleware/recovery" + "PowerX/internal/model" "PowerX/pkg/pluginx" "PowerX/pkg/zerox" "context" @@ -35,6 +36,7 @@ func main() { // 设置配置文件目录 c.EtcDir = filepath.Dir(*configFile) + model.PowerXSchema = c.PowerXDatabase.Schema // ---------- 设置 Gin 框架为发布模式 ---------- gin.SetMode(gin.ReleaseMode) diff --git a/etc/powerx-example.yaml b/etc/powerx-example.yaml index fe4efa23..3a91b339 100644 --- a/etc/powerx-example.yaml +++ b/etc/powerx-example.yaml @@ -55,6 +55,10 @@ PowerXDatabase: # 数据库连接信息 DSN: host=localhost user=powerx password=powerxpw dbname=powerx port=5432 sslmode=disable TimeZone=UTC + + # Schema + Schema: public + # 数据库是否初始化定制的种子数据 SeedCommerceData: false SeedDepartment: true diff --git a/internal/config/database.go b/internal/config/database.go index 00e17696..2250cbea 100644 --- a/internal/config/database.go +++ b/internal/config/database.go @@ -3,6 +3,7 @@ package config type Database struct { Driver string DSN string + Schema string SeedCommerceData bool SeedDepartment bool } diff --git a/internal/logic/admin/department/createdepartmentlogic.go b/internal/logic/admin/department/createdepartmentlogic.go index c4d04b85..c301aaea 100644 --- a/internal/logic/admin/department/createdepartmentlogic.go +++ b/internal/logic/admin/department/createdepartmentlogic.go @@ -1,7 +1,6 @@ package department import ( - "PowerX/internal/model/origanzation" "PowerX/internal/svc" "PowerX/internal/types" "context" @@ -24,7 +23,7 @@ func NewCreateDepartmentLogic(ctx context.Context, svcCtx *svc.ServiceContext) * } func (l *CreateDepartmentLogic) CreateDepartment(req *types.CreateDepartmentRequest) (resp *types.CreateDepartmentReply, err error) { - dep := origanzation.Department{ + dep := organization.Department{ Name: req.DepName, PId: req.PId, LeaderId: req.LeaderId, diff --git a/internal/logic/admin/position/createpositionlogic.go b/internal/logic/admin/position/createpositionlogic.go index f4114657..6de8eade 100644 --- a/internal/logic/admin/position/createpositionlogic.go +++ b/internal/logic/admin/position/createpositionlogic.go @@ -1,7 +1,6 @@ package position import ( - "PowerX/internal/model/origanzation" "PowerX/internal/model/permission" "context" @@ -32,7 +31,7 @@ func (l *CreatePositionLogic) CreatePosition(req *types.CreatePositionRequest) ( RoleCode: code, }) } - position := origanzation.Position{ + position := organization.Position{ Name: req.Name, Desc: req.Desc, Roles: roles, diff --git a/internal/logic/admin/position/patchpositionlogic.go b/internal/logic/admin/position/patchpositionlogic.go index 43c2c004..7474fb26 100644 --- a/internal/logic/admin/position/patchpositionlogic.go +++ b/internal/logic/admin/position/patchpositionlogic.go @@ -2,7 +2,6 @@ package position import ( "PowerX/internal/model/option" - "PowerX/internal/model/origanzation" "PowerX/internal/model/permission" "PowerX/pkg/slicex" "context" @@ -28,7 +27,7 @@ func NewPatchPositionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Pat } func (l *PatchPositionLogic) PatchPosition(req *types.PatchPositionRequest) (resp *types.PatchPositionReply, err error) { - patch := &origanzation.Position{ + patch := &organization.Position{ Name: req.Name, Desc: req.Desc, Level: req.Level, @@ -54,7 +53,7 @@ func (l *PatchPositionLogic) PatchPosition(req *types.PatchPositionRequest) (res PositionIDs: []int64{req.Id}, }) // pluck user id - userIDs := slicex.SlicePluck(page.List, func(item *origanzation.User) int64 { + userIDs := slicex.SlicePluck(page.List, func(item *organization.User) int64 { return item.Id }) diff --git a/internal/logic/admin/scrm/customer/listweworkcustomerpagelogic.go b/internal/logic/admin/scrm/customer/listweworkcustomerpagelogic.go index c5456ef9..3cfa05aa 100644 --- a/internal/logic/admin/scrm/customer/listweworkcustomerpagelogic.go +++ b/internal/logic/admin/scrm/customer/listweworkcustomerpagelogic.go @@ -27,14 +27,13 @@ func NewListWeWorkCustomerPageLogic(ctx context.Context, svcCtx *svc.ServiceCont } } -// // ListWeWorkCustomerPage -// @Description: 客户列表 -// @receiver customer -// @param opt -// @return resp -// @return err // +// @Description: 客户列表 +// @receiver customer +// @param opt +// @return resp +// @return err func (customer *ListWeWorkCustomerPageLogic) ListWeWorkCustomerPage(opt *types.WeWorkCustomersRequest) (resp *types.WechatListCustomersReply, err error) { data, err := customer.svcCtx.PowerX.SCRM.Wechat.FindManyWeWorkCustomerPage(customer.ctx, customer.OPT(opt), opt.Sync) @@ -47,13 +46,12 @@ func (customer *ListWeWorkCustomerPageLogic) ListWeWorkCustomerPage(opt *types.W } -// // OPT -// @Description: -// @receiver customer -// @param opt -// @return *types.PageOption[wechat.FindManyWechatCustomerOption] // +// @Description: +// @receiver customer +// @param opt +// @return *types.PageOption[wechat.FindManyWechatCustomerOption] func (customer *ListWeWorkCustomerPageLogic) OPT(opt *types.WeWorkCustomersRequest) *types.PageOption[wechat.FindManyWechatCustomerOption] { option := types.PageOption[wechat.FindManyWechatCustomerOption]{ @@ -72,14 +70,13 @@ func (customer *ListWeWorkCustomerPageLogic) OPT(opt *types.WeWorkCustomersReque } -// // DTO -// @Description: -// @receiver customer -// @param data -// @return resp // -func (customer *ListWeWorkCustomerPageLogic) DTO(data []*customer.WeWorkExternalContacts) (resp []*types.WechatCustomer) { +// @Description: +// @receiver customer +// @param data +// @return resp +func (customer *ListWeWorkCustomerPageLogic) DTO(data []*customer.WeWorkExternalContact) (resp []*types.WechatCustomer) { if data != nil { for _, obj := range data { @@ -90,14 +87,13 @@ func (customer *ListWeWorkCustomerPageLogic) DTO(data []*customer.WeWorkExternal } -// // dto -// @Description: -// @receiver customer -// @param contact -// @return *types.WechatCustomer // -func (customer *ListWeWorkCustomerPageLogic) dto(contact *customer.WeWorkExternalContacts) *types.WechatCustomer { +// @Description: +// @receiver customer +// @param contact +// @return *types.WechatCustomer +func (customer *ListWeWorkCustomerPageLogic) dto(contact *customer.WeWorkExternalContact) *types.WechatCustomer { return &types.WechatCustomer{ ExternalContact: types.WechatCustomersWithExternalContactExternalProfile{ @@ -119,13 +115,12 @@ func (customer *ListWeWorkCustomerPageLogic) dto(contact *customer.WeWorkExterna } } -// // externalContactExternalProfileWithExternalProfile -// @Description: -// @receiver customer -// @param attr -// @return data // +// @Description: +// @receiver customer +// @param attr +// @return data func (customer *ListWeWorkCustomerPageLogic) externalContactExternalProfileWithExternalProfile(attr string) (data types.ExternalContactExternalProfileWithExternalProfile) { if attr != `` { _ = json.Unmarshal([]byte(attr), &data) @@ -133,13 +128,12 @@ func (customer *ListWeWorkCustomerPageLogic) externalContactExternalProfileWithE return data } -// // wechatCustomersWithFollowUser -// @Description: -// @receiver customer -// @param follow -// @return *types.WechatCustomersWithFollowUser // +// @Description: +// @receiver customer +// @param follow +// @return *types.WechatCustomersWithFollowUser func (customer *ListWeWorkCustomerPageLogic) wechatCustomersWithFollowUser(follow *customer.WeWorkExternalContactFollow) *types.WechatCustomersWithFollowUser { if follow == nil { @@ -154,7 +148,7 @@ func (customer *ListWeWorkCustomerPageLogic) wechatCustomersWithFollowUser(follo UserId: follow.UserId, Remark: follow.Remark, Description: follow.Description, - Createtime: follow.Createtime, + CreatedTime: follow.CreatedTime, Tags: tags, TagIds: strings.Split(follow.TagIds, `,`), WechatChannels: customer.WechatCustomersFollowUserWithWechatChannels(follow.WechatChannels), @@ -166,13 +160,12 @@ func (customer *ListWeWorkCustomerPageLogic) wechatCustomersWithFollowUser(follo } } -// // WechatCustomersFollowUserWithWechatChannels -// @Description: -// @receiver customer -// @param channels -// @return channel // +// @Description: +// @receiver customer +// @param channels +// @return channel func (customer *ListWeWorkCustomerPageLogic) WechatCustomersFollowUserWithWechatChannels(channels string) (channel types.WechatCustomersFollowUserWithWechatChannels) { if channels == `` { diff --git a/internal/logic/admin/scrm/customer/syncweworkcustomeroptionlogic.go b/internal/logic/admin/scrm/customer/syncweworkcustomeroptionlogic.go index 1f0bc767..0b3f58a4 100644 --- a/internal/logic/admin/scrm/customer/syncweworkcustomeroptionlogic.go +++ b/internal/logic/admin/scrm/customer/syncweworkcustomeroptionlogic.go @@ -108,7 +108,7 @@ func (cMsg *SyncWeWorkCustomerOptionLogic) follow(follow *models.FollowUser) *ty UserId: follow.UserID, Remark: follow.Remark, Description: follow.Description, - Createtime: follow.CreateTime, + CreatedTime: follow.CreateTime, Tags: nil, WechatChannels: cMsg.followWechatChannels(follow.WechatChannels), RemarkCorpName: follow.RemarkCorpName, diff --git a/internal/logic/admin/scrm/qrcode/listweworkqrcodepagelogic.go b/internal/logic/admin/scrm/qrcode/listweworkqrcodepagelogic.go index f6b71f9e..0c961421 100644 --- a/internal/logic/admin/scrm/qrcode/listweworkqrcodepagelogic.go +++ b/internal/logic/admin/scrm/qrcode/listweworkqrcodepagelogic.go @@ -26,14 +26,13 @@ func NewListWeWorkQrcodePageLogic(ctx context.Context, svcCtx *svc.ServiceContex } } -// // ListWeWorkQrcodePage -// @Description: 群活码列表 -// @receiver qrcode -// @param req -// @return resp -// @return err // +// @Description: 群活码列表 +// @receiver qrcode +// @param req +// @return resp +// @return err func (qrcode *ListWeWorkQrcodePageLogic) ListWeWorkQrcodePage(opt *types.ListWeWorkGroupQrcodeActiveReqeust) (resp *types.ListWeWorkQrcodeActiveReply, err error) { reply, err := qrcode.svcCtx.PowerX.SCRM.Wechat.FindWeWorkCustomerGroupQrcodePage(qrcode.OPT(opt)) @@ -46,13 +45,10 @@ func (qrcode *ListWeWorkQrcodePageLogic) ListWeWorkQrcodePage(opt *types.ListWeW }, err } -// -// -// @Description: -// @receiver qrcode -// @param opt -// @return *types.PageOption[types.ListWeWorkGroupQrcodeActiveReqeust] -// +// @Description: +// @receiver qrcode +// @param opt +// @return *types.PageOption[types.ListWeWorkGroupQrcodeActiveReqeust] func (qrcode *ListWeWorkQrcodePageLogic) OPT(opt *types.ListWeWorkGroupQrcodeActiveReqeust) *types.PageOption[types.ListWeWorkGroupQrcodeActiveReqeust] { option := types.PageOption[types.ListWeWorkGroupQrcodeActiveReqeust]{ @@ -76,14 +72,13 @@ func (qrcode *ListWeWorkQrcodePageLogic) OPT(opt *types.ListWeWorkGroupQrcodeAct } -// // DTO -// @Description: -// @receiver qrcode -// @param data -// @return reply // -func (qrcode *ListWeWorkQrcodePageLogic) DTO(data *types.Page[*scene.SceneQrcode]) (reply []*types.WeWorkQrcodeActive) { +// @Description: +// @receiver qrcode +// @param data +// @return reply +func (qrcode *ListWeWorkQrcodePageLogic) DTO(data *types.Page[*scene.SceneQRCode]) (reply []*types.WeWorkQrcodeActive) { if data.List != nil { for _, obj := range data.List { @@ -94,14 +89,13 @@ func (qrcode *ListWeWorkQrcodePageLogic) DTO(data *types.Page[*scene.SceneQrcode return reply } -// // dto -// @Description: -// @receiver qrcode -// @param obj -// @return *types.WeWorkQrcodeActive // -func (qrcode *ListWeWorkQrcodePageLogic) dto(obj *scene.SceneQrcode) *types.WeWorkQrcodeActive { +// @Description: +// @receiver qrcode +// @param obj +// @return *types.WeWorkQrcodeActive +func (qrcode *ListWeWorkQrcodePageLogic) dto(obj *scene.SceneQRCode) *types.WeWorkQrcodeActive { return &types.WeWorkQrcodeActive{ QId: obj.QId, diff --git a/internal/logic/admin/scrm/qrcode/updateactiveqrcodelinklogic.go b/internal/logic/admin/scrm/qrcode/updateactiveqrcodelinklogic.go index e79539fd..8b511062 100644 --- a/internal/logic/admin/scrm/qrcode/updateactiveqrcodelinklogic.go +++ b/internal/logic/admin/scrm/qrcode/updateactiveqrcodelinklogic.go @@ -1,69 +1,67 @@ package qrcode import ( - "PowerX/internal/types/errorx" - "context" - "fmt" + "PowerX/internal/types/errorx" + "context" + "fmt" - "PowerX/internal/svc" - "PowerX/internal/types" + "PowerX/internal/svc" + "PowerX/internal/types" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logx" ) type UpdateActiveQrcodeLinkLogic struct { - logx.Logger - ctx context.Context - svcCtx *svc.ServiceContext + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext } func NewUpdateActiveQrcodeLinkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateActiveQrcodeLinkLogic { - return &UpdateActiveQrcodeLinkLogic{ - Logger: logx.WithContext(ctx), - ctx: ctx, - svcCtx: svcCtx, - } + return &UpdateActiveQrcodeLinkLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } } -// // UpdateActiveQrcodeLink -// @Description: -// @receiver qrcode -// @param opt -// @return resp -// @return err // +// @Description: +// @receiver qrcode +// @param opt +// @return resp +// @return err func (qrcode *UpdateActiveQrcodeLinkLogic) UpdateActiveQrcodeLink(opt *types.ActionRequest) (resp *types.ActionWeWorkGroupQrcodeActiveReply, err error) { - err = qrcode.OPT(opt) - if err != nil { - return nil, err - } - err = qrcode.svcCtx.PowerX.SCRM.Wechat.UpdateSceneQrcodeLink(opt.Qid, opt.SceneQrcodeLink) - if err != nil { - return nil, errorx.ErrBadRequest - } + err = qrcode.OPT(opt) + if err != nil { + return nil, err + } + err = qrcode.svcCtx.PowerX.SCRM.Wechat.UpdateSceneQRCodeLink(opt.Qid, opt.SceneQRCodeLink) + if err != nil { + return nil, errorx.ErrBadRequest + } - return &types.ActionWeWorkGroupQrcodeActiveReply{ - Status: `success`, - }, err + return &types.ActionWeWorkGroupQrcodeActiveReply{ + Status: `success`, + }, err } -// // OPT -// @Description: -// @receiver qrcode -// @param opt -// @return error // +// @Description: +// @receiver qrcode +// @param opt +// @return error func (qrcode *UpdateActiveQrcodeLinkLogic) OPT(opt *types.ActionRequest) error { - if opt.Qid == `` { - return fmt.Errorf(`Qid error`) - } - if opt.SceneQrcodeLink == `` { - return fmt.Errorf(`SceneQrcodeLink error`) - } - return nil + if opt.Qid == `` { + return fmt.Errorf(`Qid error`) + } + if opt.SceneQRCodeLink == `` { + return fmt.Errorf(`SceneQRCodeLink error`) + } + return nil } diff --git a/internal/logic/admin/user/createuserlogic.go b/internal/logic/admin/user/createuserlogic.go index 4c4f9a97..afaed787 100644 --- a/internal/logic/admin/user/createuserlogic.go +++ b/internal/logic/admin/user/createuserlogic.go @@ -1,7 +1,6 @@ package user import ( - "PowerX/internal/model/origanzation" "context" "github.com/pkg/errors" @@ -26,7 +25,7 @@ func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Create } func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (resp *types.CreateUserReply, err error) { - user := origanzation.User{ + user := organization.User{ Account: req.Account, Name: req.Name, NickName: req.NickName, @@ -39,7 +38,7 @@ func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (resp *types. ExternalEmail: req.ExternalEmail, Avatar: req.Avatar, Password: "123456", - Status: origanzation.UserStatusEnabled, + Status: organization.UserStatusEnabled, } if err = user.HashPassword(); err != nil { panic(errors.Wrap(err, "create user hash password failed")) diff --git a/internal/logic/admin/user/getuserlogic.go b/internal/logic/admin/user/getuserlogic.go index 4e6c4eed..300f2424 100644 --- a/internal/logic/admin/user/getuserlogic.go +++ b/internal/logic/admin/user/getuserlogic.go @@ -1,7 +1,6 @@ package user import ( - "PowerX/internal/model/origanzation" "PowerX/internal/model/permission" "PowerX/pkg/slicex" "context" @@ -57,7 +56,7 @@ func (l *GetUserLogic) GetUser(req *types.GetUserRequest) (resp *types.GetUserRe Department: dep, Roles: roles, JobTitle: user.JobTitle, - IsEnabled: user.Status == origanzation.UserStatusEnabled, + IsEnabled: user.Status == organization.UserStatusEnabled, CreatedAt: user.CreatedAt.Format(time.RFC3339), } if user.Position != nil { diff --git a/internal/logic/admin/user/listuserlogic.go b/internal/logic/admin/user/listuserlogic.go index d0eed4a5..be718196 100644 --- a/internal/logic/admin/user/listuserlogic.go +++ b/internal/logic/admin/user/listuserlogic.go @@ -2,7 +2,6 @@ package user import ( "PowerX/internal/model/option" - "PowerX/internal/model/origanzation" "PowerX/internal/model/permission" "PowerX/pkg/slicex" "context" @@ -53,9 +52,9 @@ func (l *ListUsersLogic) ListUser(req *types.ListUsersRequest) (resp *types.List } if req.IsEnabled != nil { if *req.IsEnabled { - opt.Statuses = append(opt.Statuses, origanzation.UserStatusEnabled) + opt.Statuses = append(opt.Statuses, organization.UserStatusEnabled) } else { - opt.Statuses = append(opt.Statuses, origanzation.UserStatusDisabled) + opt.Statuses = append(opt.Statuses, organization.UserStatusDisabled) } } @@ -86,7 +85,7 @@ func (l *ListUsersLogic) ListUser(req *types.ListUsersRequest) (resp *types.List Department: dep, Roles: roles, JobTitle: user.JobTitle, - IsEnabled: user.Status == origanzation.UserStatusEnabled, + IsEnabled: user.Status == organization.UserStatusEnabled, CreatedAt: user.CreatedAt.Format(time.RFC3339), } if user.Position != nil { diff --git a/internal/logic/admin/user/resetpasswordlogic.go b/internal/logic/admin/user/resetpasswordlogic.go index ba41334c..ab0cc27e 100644 --- a/internal/logic/admin/user/resetpasswordlogic.go +++ b/internal/logic/admin/user/resetpasswordlogic.go @@ -1,7 +1,6 @@ package user import ( - "PowerX/internal/model/origanzation" "PowerX/internal/types" "context" "github.com/pkg/errors" @@ -27,7 +26,7 @@ func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Res } func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordRequest) (resp *types.ResetPasswordReply, err error) { - user := origanzation.User{ + user := organization.User{ Model: model.Model{ Id: req.UserId, }, diff --git a/internal/logic/admin/user/updateuserlogic.go b/internal/logic/admin/user/updateuserlogic.go index 286f6d85..68dbbc1e 100644 --- a/internal/logic/admin/user/updateuserlogic.go +++ b/internal/logic/admin/user/updateuserlogic.go @@ -1,7 +1,6 @@ package user import ( - "PowerX/internal/model/origanzation" "PowerX/internal/types" "context" "github.com/pkg/errors" @@ -28,7 +27,7 @@ func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Update } func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (resp *types.UpdateUserReply, err error) { - user := origanzation.User{ + user := organization.User{ Model: model.Model{ Id: req.Id, }, @@ -86,7 +85,7 @@ func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (resp *types. Roles: roles, PositionId: user.PositionID, JobTitle: user.JobTitle, - IsEnabled: user.Status == origanzation.UserStatusEnabled, + IsEnabled: user.Status == organization.UserStatusEnabled, CreatedAt: user.CreatedAt.Format(time.RFC3339), }, }, nil diff --git a/internal/logic/admin/userinfo/getuserinfologic.go b/internal/logic/admin/userinfo/getuserinfologic.go index 67c5373c..34051d34 100644 --- a/internal/logic/admin/userinfo/getuserinfologic.go +++ b/internal/logic/admin/userinfo/getuserinfologic.go @@ -1,7 +1,6 @@ package userinfo import ( - "PowerX/internal/model/origanzation" "context" "github.com/pkg/errors" "time" @@ -61,7 +60,7 @@ func (l *GetUserInfoLogic) GetUserInfo() (resp *types.GetUserInfoReply, err erro if user.Department != nil { resp.DepName = user.Department.Name } - if user.Status == origanzation.UserStatusEnabled { + if user.Status == organization.UserStatusEnabled { resp.IsEnabled = true } return diff --git a/internal/logic/admin/userinfo/modifyuserpasswordlogic.go b/internal/logic/admin/userinfo/modifyuserpasswordlogic.go index 0674aedd..cda91adc 100644 --- a/internal/logic/admin/userinfo/modifyuserpasswordlogic.go +++ b/internal/logic/admin/userinfo/modifyuserpasswordlogic.go @@ -1,7 +1,6 @@ package userinfo import ( - "PowerX/internal/model/origanzation" "context" "github.com/pkg/errors" @@ -31,7 +30,7 @@ func (l *ModifyUserPasswordLogic) ModifyUserPassword(req *types.ModifyPasswordRe panic(errors.Wrap(err, "get user metadata failed")) } - err = l.svcCtx.PowerX.Organization.PatchUserByUserId(l.ctx, &origanzation.User{Password: req.Password}, cred.UID) + err = l.svcCtx.PowerX.Organization.PatchUserByUserId(l.ctx, &organization.User{Password: req.Password}, cred.UID) if err != nil { return err } diff --git a/internal/logic/web/scene/detailqrcodelogic.go b/internal/logic/web/scene/detailqrcodelogic.go index 6e50a1d5..b918540e 100644 --- a/internal/logic/web/scene/detailqrcodelogic.go +++ b/internal/logic/web/scene/detailqrcodelogic.go @@ -25,23 +25,22 @@ func NewDetailQrcodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Deta } } -// // DetailQrcode -// @Description: -// @receiver qrcode -// @param opt -// @return resp -// @return err // -func (qrcode *DetailQrcodeLogic) DetailQrcode(opt *types.SceneRequest) (resp *types.SceneQrcodeActiveReply, err error) { +// @Description: +// @receiver qrcode +// @param opt +// @return resp +// @return err +func (qrcode *DetailQrcodeLogic) DetailQrcode(opt *types.SceneRequest) (resp *types.SceneQRCodeActiveReply, err error) { if opt.Qid == `` { return nil, fmt.Errorf(`Qid error`) } - detail := qrcode.svcCtx.PowerX.Scene.Scene.FindOneSceneQrcodeDetail(opt.Qid) + detail := qrcode.svcCtx.PowerX.Scene.Scene.FindOneSceneQRCodeDetail(opt.Qid) go qrcode.svcCtx.PowerX.Scene.Scene.IncreaseSceneCpaNumber(opt.Qid) - return &types.SceneQrcodeActiveReply{ + return &types.SceneQRCodeActiveReply{ QId: detail.QId, Name: detail.Name, Desc: detail.Desc, diff --git a/internal/model/crm/customerdomain/contact.go b/internal/model/crm/customerdomain/contact.go index 2c75d20c..a83ea3cf 100644 --- a/internal/model/crm/customerdomain/contact.go +++ b/internal/model/crm/customerdomain/contact.go @@ -1,6 +1,7 @@ package customerdomain import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) @@ -14,3 +15,15 @@ type Contact struct { Status int8 Active bool } + +func (mdl *Contact) TableName() string { + return model.PowerXSchema + "." + model.TableNameContact +} + +func (mdl *Contact) GetTableName(needFull bool) string { + tableName := model.TableNameContact + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/customerdomain/customer.go b/internal/model/crm/customerdomain/customer.go index d3c456e9..e6ba1fc2 100644 --- a/internal/model/crm/customerdomain/customer.go +++ b/internal/model/crm/customerdomain/customer.go @@ -1,6 +1,7 @@ package customerdomain import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) @@ -34,3 +35,15 @@ const TypeCustomerType = "_customer_type" const CustomerPersonal = "_personal" const CustomerCompany = "_company" + +func (mdl *Customer) TableName() string { + return model.PowerXSchema + "." + model.TableNameCustomer +} + +func (mdl *Customer) GetTableName(needFull bool) string { + tableName := model.TableNameCustomer + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/customerdomain/lead.go b/internal/model/crm/customerdomain/lead.go index 982168f1..a23765f2 100644 --- a/internal/model/crm/customerdomain/lead.go +++ b/internal/model/crm/customerdomain/lead.go @@ -1,6 +1,7 @@ package customerdomain import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) @@ -20,3 +21,15 @@ type Lead struct { } const LeadUniqueId = "mobile" + +func (mdl *Lead) TableName() string { + return model.PowerXSchema + "." + model.TableNameLead +} + +func (mdl *Lead) GetTableName(needFull bool) string { + tableName := model.TableNameLead + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/customerdomain/registercode.go b/internal/model/crm/customerdomain/registercode.go index 26075870..5eaa70a4 100644 --- a/internal/model/crm/customerdomain/registercode.go +++ b/internal/model/crm/customerdomain/registercode.go @@ -1,6 +1,7 @@ package customerdomain import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "time" ) @@ -14,3 +15,15 @@ type RegisterCode struct { } const RegisterCodeUniqueId = "code" + +func (mdl *RegisterCode) TableName() string { + return model.PowerXSchema + "." + model.TableNameRegisterCode +} + +func (mdl *RegisterCode) GetTableName(needFull bool) string { + tableName := model.TableNameRegisterCode + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/market/media.go b/internal/model/crm/market/media.go index 58d48ed2..40621f6a 100644 --- a/internal/model/crm/market/media.go +++ b/internal/model/crm/market/media.go @@ -1,6 +1,7 @@ package market import ( + "PowerX/internal/model" "PowerX/internal/model/media" "PowerX/internal/model/powermodel" "gorm.io/gorm" @@ -21,7 +22,6 @@ type Media struct { ViewedCount int `gorm:"comment:浏览次数" json:"viewedCount"` } -const TableNameMedia = "media" const MediaUniqueId = powermodel.UniqueId const TypeMediaType = "_media_type" @@ -40,7 +40,7 @@ const ( func (mdl *Media) ClearPivotDetailImages(db *gorm.DB) error { conditions := &map[string]interface{}{} - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameMedia + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameMedia (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id return powermodel.ClearMorphPivots(db, &media.PivotMediaResourceToObject{}, false, false, conditions) diff --git a/internal/model/crm/market/store.go b/internal/model/crm/market/store.go index b4da9f8d..931814fa 100644 --- a/internal/model/crm/market/store.go +++ b/internal/model/crm/market/store.go @@ -1,6 +1,7 @@ package market import ( + "PowerX/internal/model" "PowerX/internal/model/crm/product" "PowerX/internal/model/media" "PowerX/internal/model/powermodel" @@ -28,7 +29,6 @@ type Store struct { EndWork time.Time `gorm:"comment:结束工作时间" json:"endWork"` } -const TableNameStore = "stores" const StoreUniqueId = powermodel.UniqueId func (mdl *Store) LoadArtisans(db *gorm.DB, conditions *map[string]interface{}, withClauseAssociations bool) error { @@ -54,7 +54,7 @@ func (mdl *Store) LoadPivotDetailImages(db *gorm.DB, conditions *map[string]inte conditions = &map[string]interface{}{} } - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameStore + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameStore (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id err := powermodel.SelectMorphPivots(db, &media.PivotMediaResourceToObject{}, false, false, conditions). @@ -66,7 +66,7 @@ func (mdl *Store) LoadPivotDetailImages(db *gorm.DB, conditions *map[string]inte func (mdl *Store) ClearPivotDetailImages(db *gorm.DB) error { conditions := &map[string]interface{}{} - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameStore + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameStore (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id return powermodel.ClearMorphPivots(db, &media.PivotMediaResourceToObject{}, false, false, conditions) } diff --git a/internal/model/crm/operation/ticket.go b/internal/model/crm/operation/ticket.go index e9548a16..1584d64e 100644 --- a/internal/model/crm/operation/ticket.go +++ b/internal/model/crm/operation/ticket.go @@ -1,6 +1,7 @@ package operation import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) @@ -15,14 +16,16 @@ type TicketRecord struct { IsUsed bool `gorm:"comment:是否使用" json:"isUsed"` } +func (mdl *TicketRecord) TableName() string { + return model.TableNameTicketRecord +} + func (mdl *TicketRecord) GetTableName(needFull bool) string { - tableName := TableNameTicketRecord + tableName := model.TableNameTicketRecord if needFull { tableName = "public." + tableName } return tableName } -const TableNameTicketRecord = "ticket_record" - const TicketRecordUniqueId = powermodel.UniqueId diff --git a/internal/model/crm/product/artisan.go b/internal/model/crm/product/artisan.go index 884bf79b..74eef572 100644 --- a/internal/model/crm/product/artisan.go +++ b/internal/model/crm/product/artisan.go @@ -1,6 +1,7 @@ package product import ( + "PowerX/internal/model" "PowerX/internal/model/media" "PowerX/internal/model/powermodel" "gorm.io/gorm" @@ -33,7 +34,6 @@ type Artisan struct { Address string `gorm:"comment:工作地址" json:"address"` } -const TableNameArtisan = "artisans" const ArtisanUniqueId = powermodel.UniqueId // artisan level dd type @@ -50,7 +50,7 @@ func (mdl *Artisan) LoadPivotDetailImages(db *gorm.DB, conditions *map[string]in conditions = &map[string]interface{}{} } - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameArtisan + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameArtisan (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id err := powermodel.SelectMorphPivots(db, &media.PivotMediaResourceToObject{}, false, false, conditions). @@ -62,7 +62,7 @@ func (mdl *Artisan) LoadPivotDetailImages(db *gorm.DB, conditions *map[string]in func (mdl *Artisan) ClearPivotDetailImages(db *gorm.DB) error { conditions := &map[string]interface{}{} - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameArtisan + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameArtisan (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id return powermodel.ClearMorphPivots(db, &media.PivotMediaResourceToObject{}, false, false, conditions) } diff --git a/internal/model/crm/product/pivotproducttoproductcategory.go b/internal/model/crm/product/pivotproducttoproductcategory.go index 0d237112..7c42f2f2 100644 --- a/internal/model/crm/product/pivotproducttoproductcategory.go +++ b/internal/model/crm/product/pivotproducttoproductcategory.go @@ -1,12 +1,13 @@ package product import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) // Table Name func (mdl *PivotProductToProductCategory) TableName() string { - return TableNamePivotProductToProductCategory + return model.TableNamePivotProductToProductCategory } // 数据表结构 @@ -17,8 +18,6 @@ type PivotProductToProductCategory struct { ProductCategoryId int64 `gorm:"column:product_category_id; not null;index:idx_product_category_id" json:"productCategoryId"` } -const TableNamePivotProductToProductCategory = "pivot_product_to_product_category" - const PivotProductToCategoryForeignKey = "product_id" const PivotProductToCategoryJoinKey = "product_category_id" diff --git a/internal/model/crm/product/pivotskutospecificoption.go b/internal/model/crm/product/pivotskutospecificoption.go index d801fdb9..d9c3eaac 100644 --- a/internal/model/crm/product/pivotskutospecificoption.go +++ b/internal/model/crm/product/pivotskutospecificoption.go @@ -1,6 +1,7 @@ package product import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/pkg/securityx" "fmt" @@ -9,7 +10,7 @@ import ( // Table Name func (mdl *PivotSkuToSpecificOption) TableName() string { - return TableNamePivotSkuToSpecificOption + return model.TableNamePivotSkuToSpecificOption } // 数据表结构 @@ -24,8 +25,6 @@ type PivotSkuToSpecificOption struct { IsActivated bool `gorm:"comment:是否被激活; column:is_activated;" json:"isActivated,optional"` } -const TableNamePivotSkuToSpecificOption = "pivot_sku_to_specific_options" - const PivotPivotSkuToSpecificOptionsUniqueId = "index_unique_id" func (mdl *PivotSkuToSpecificOption) GetPivotComposedUniqueID() object.NullString { diff --git a/internal/model/crm/product/pivotstoretoartisan.go b/internal/model/crm/product/pivotstoretoartisan.go index 01ea4270..e0e4372f 100644 --- a/internal/model/crm/product/pivotstoretoartisan.go +++ b/internal/model/crm/product/pivotstoretoartisan.go @@ -1,12 +1,13 @@ package product import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) // Table Name func (mdl *PivotStoreToArtisan) TableName() string { - return TableNamePivotStoreToArtisan + return model.TableNamePivotStoreToArtisan } // 数据表结构 @@ -17,8 +18,6 @@ type PivotStoreToArtisan struct { ArtisanId int64 `gorm:"column:artisan_id; not null;index:idx_artisan_id" json:"artisanId"` } -const TableNamePivotStoreToArtisan = "pivot_store_to_artisan" - const PivotStoreToArtisanForeignKey = "store_id" const PivotStoreToArtisanJoinKey = "artisan_id" diff --git a/internal/model/crm/product/pricebook.go b/internal/model/crm/product/pricebook.go index f2a4c413..76bc1245 100644 --- a/internal/model/crm/product/pricebook.go +++ b/internal/model/crm/product/pricebook.go @@ -16,5 +16,4 @@ type PriceBook struct { StoreId int64 `gorm:"column:storeId; comment:门店Id" json:"storeId"` } -const TableNamePriceBook = "price_books" const PriceBookUniqueId = powermodel.UniqueId diff --git a/internal/model/crm/product/pricebookentry.go b/internal/model/crm/product/pricebookentry.go index 081e3931..566b6e52 100644 --- a/internal/model/crm/product/pricebookentry.go +++ b/internal/model/crm/product/pricebookentry.go @@ -27,7 +27,6 @@ type PriceBookEntry struct { IsActive bool `gorm:"comment:是否激活" json:"isActive"` } -const TableNamePriceBookEntry = "price_book_entries" const PriceBookEntryUniqueId = "index_unique_id" func (mdl *PriceBookEntry) GetComposedUniqueID() object.NullString { diff --git a/internal/model/crm/product/priceconfig.go b/internal/model/crm/product/priceconfig.go index ad96d63f..4aaed241 100644 --- a/internal/model/crm/product/priceconfig.go +++ b/internal/model/crm/product/priceconfig.go @@ -14,8 +14,6 @@ type PriceConfig struct { EndDate time.Time `gorm:"column:end_date; comment:活动场景结束时间" json:"endDate"` } -const TableNamePriceConfig = "price_configs" - const TypeListPrice = "List_Price" const TypeMember = "Member" const TypeMemberEarlyBird = "Member_Early_Bird" diff --git a/internal/model/crm/product/product.go b/internal/model/crm/product/product.go index 763395ee..d5921421 100644 --- a/internal/model/crm/product/product.go +++ b/internal/model/crm/product/product.go @@ -54,7 +54,6 @@ type Product struct { ProductAttribute } -const TableNameProduct = "products" const ProductUniqueId = powermodel.UniqueId // Data Dictionary @@ -69,7 +68,7 @@ const ProductPlanOnce = "_once" const ProductPlanPeriod = "_period" func (mdl *Product) GetTableName(needFull bool) string { - tableName := TableNameProduct + tableName := model.TableNameProduct if needFull { tableName = "public." + tableName } @@ -87,7 +86,7 @@ func (mdl *Product) LoadPivotSalesChannels(db *gorm.DB, conditions *map[string]i conditions = &map[string]interface{}{} } - (*conditions)[model.PivotDataDictionaryToObjectOwnerKey] = TableNameProduct + (*conditions)[model.PivotDataDictionaryToObjectOwnerKey] = model.TableNameProduct (*conditions)[model.PivotDataDictionaryToObjectForeignKey] = mdl.Id (*conditions)["data_dictionary_type"] = model.TypeSalesChannel @@ -101,7 +100,7 @@ func (mdl *Product) LoadPivotSalesChannels(db *gorm.DB, conditions *map[string]i func (mdl *Product) ClearPivotSalesChannels(db *gorm.DB) error { conditions := &map[string]interface{}{} - (*conditions)[model.PivotDataDictionaryToObjectOwnerKey] = TableNameProduct + (*conditions)[model.PivotDataDictionaryToObjectOwnerKey] = model.TableNameProduct (*conditions)[model.PivotDataDictionaryToObjectForeignKey] = mdl.Id (*conditions)["data_dictionary_type"] = model.TypeSalesChannel @@ -114,7 +113,7 @@ func (mdl *Product) LoadPromoteChannels(db *gorm.DB, conditions *map[string]inte conditions = &map[string]interface{}{} } - (*conditions)[model.PivotDataDictionaryToObjectOwnerKey] = TableNameProduct + (*conditions)[model.PivotDataDictionaryToObjectOwnerKey] = model.TableNameProduct (*conditions)[model.PivotDataDictionaryToObjectForeignKey] = mdl.Id (*conditions)["data_dictionary_type"] = model.TypePromoteChannel @@ -127,7 +126,7 @@ func (mdl *Product) LoadPromoteChannels(db *gorm.DB, conditions *map[string]inte func (mdl *Product) ClearPivotPromoteChannels(db *gorm.DB) error { conditions := &map[string]interface{}{} - (*conditions)[model.PivotDataDictionaryToObjectOwnerKey] = TableNameProduct + (*conditions)[model.PivotDataDictionaryToObjectOwnerKey] = model.TableNameProduct (*conditions)[model.PivotDataDictionaryToObjectForeignKey] = mdl.Id (*conditions)["data_dictionary_type"] = model.TypePromoteChannel @@ -141,7 +140,7 @@ func (mdl *Product) LoadProductCategories(db *gorm.DB, conditions *map[string]in if conditions == nil { conditions = &map[string]interface{}{} } - (*conditions)[TableNamePivotProductToProductCategory+".deleted_at"] = nil + (*conditions)[model.TableNamePivotProductToProductCategory+".deleted_at"] = nil err := powermodel.AssociationRelationship(db, conditions, mdl, "ProductCategories", false).Find(&mdl.ProductCategories) if err != nil { @@ -162,7 +161,7 @@ func (mdl *Product) LoadPivotCoverImages(db *gorm.DB, conditions *map[string]int conditions = &map[string]interface{}{} } - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameProduct + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameProduct (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id err := powermodel.SelectMorphPivots(db, &media.PivotMediaResourceToObject{}, false, false, conditions). @@ -175,7 +174,7 @@ func (mdl *Product) LoadPivotCoverImages(db *gorm.DB, conditions *map[string]int func (mdl *Product) ClearPivotCoverImages(db *gorm.DB) error { conditions := &map[string]interface{}{} - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameProduct + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameProduct (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id (*conditions)["media_usage"] = media.MediaUsageCover @@ -188,7 +187,7 @@ func (mdl *Product) LoadPivotDetailImages(db *gorm.DB, conditions *map[string]in conditions = &map[string]interface{}{} } - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameProduct + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameProduct (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id err := powermodel.SelectMorphPivots(db, &media.PivotMediaResourceToObject{}, false, false, conditions). @@ -201,7 +200,7 @@ func (mdl *Product) LoadPivotDetailImages(db *gorm.DB, conditions *map[string]in func (mdl *Product) ClearPivotDetailImages(db *gorm.DB) error { conditions := &map[string]interface{}{} - (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = TableNameProduct + (*conditions)[media.PivotMediaResourceToObjectOwnerKey] = model.TableNameProduct (*conditions)[media.PivotMediaResourceToObjectForeignKey] = mdl.Id (*conditions)["media_usage"] = media.MediaUsageDetail diff --git a/internal/model/crm/product/sku.go b/internal/model/crm/product/sku.go index 5cd01b00..eb95c12b 100644 --- a/internal/model/crm/product/sku.go +++ b/internal/model/crm/product/sku.go @@ -22,7 +22,6 @@ type SKU struct { OptionIds datatypes.JSON `gorm:"comment:规格Ids" json:"OptionIds"` } -const TableNameSKU = "sku" const SkuUniqueId = "index_unique_id" func (mdl *SKU) GetComposedUniqueID() object.NullString { diff --git a/internal/model/crm/trade/pivotproducttopromotion.go b/internal/model/crm/trade/pivotproducttopromotion.go index a7a11bf4..f3e15917 100644 --- a/internal/model/crm/trade/pivotproducttopromotion.go +++ b/internal/model/crm/trade/pivotproducttopromotion.go @@ -21,7 +21,6 @@ type PivotOrderToInventoryLog struct { type ActionType int const ( - ActionCreate ActionType = 1 // 创建 ActionUpdate ActionType = 2 // 更新 ActionDelete ActionType = 3 // 删除 ActionRollback ActionType = 4 // 回滚 diff --git a/internal/model/datadictionary.go b/internal/model/datadictionary.go index a042986c..8deb7bff 100644 --- a/internal/model/datadictionary.go +++ b/internal/model/datadictionary.go @@ -84,8 +84,6 @@ type PivotDataDictionaryToObject struct { DataDictionaryKey string `gorm:"column:data_dictionary_key; not null;index:idx_dd_key;comment:数据字典数据项key" json:"dataDictionaryKey"` } -const TableNamePivotDataDictionaryToObject = "pivot_data_dictionary_to_object" - const PivotDataDictionaryToObjectOwnerKey = "object_type" const PivotDataDictionaryToObjectForeignKey = "object_id" diff --git a/internal/model/infoorganization/category.go b/internal/model/infoorganization/category.go index 6aa48fb3..41add634 100644 --- a/internal/model/infoorganization/category.go +++ b/internal/model/infoorganization/category.go @@ -24,7 +24,6 @@ type Category struct { model.ImageAbleInfo } -const TableNameCategory = "categories" const CategoryUniqueId = powermodel.UniqueId func (mdl *Category) GetCategoryIds(categories []*Category) []int64 { diff --git a/internal/model/infoorganization/pivotcategorytobject.go b/internal/model/infoorganization/pivotcategorytobject.go index 5605f7c3..74e48bca 100644 --- a/internal/model/infoorganization/pivotcategorytobject.go +++ b/internal/model/infoorganization/pivotcategorytobject.go @@ -1,6 +1,7 @@ package infoorganizatoin import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/internal/types" "PowerX/pkg/securityx" @@ -10,7 +11,7 @@ import ( // Table Name func (mdl *PivotCategoryToObject) TableName() string { - return TableNamePivotCategoryToObject + return model.TableNamePivotCategoryToObject } // Pivot表 @@ -29,8 +30,6 @@ type PivotCategoryToObject struct { Sort int `gorm:"comment:排序,越大约靠前"` } -const TableNamePivotCategoryToObject = "pivot_category_to_object" - const PivotCategoryToObjectOwnerKey = "object_type" const PivotCategoryToObjectForeignKey = "object_id" const PivotCategoryToObjectJoinKey = "category_id" diff --git a/internal/model/infoorganization/pivotlabeltobject.go b/internal/model/infoorganization/pivotlabeltobject.go index c483aa5f..9bbf6f79 100644 --- a/internal/model/infoorganization/pivotlabeltobject.go +++ b/internal/model/infoorganization/pivotlabeltobject.go @@ -1,6 +1,7 @@ package infoorganizatoin import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/internal/types" "PowerX/pkg/securityx" @@ -10,7 +11,7 @@ import ( // Table Name func (mdl *PivotLabelToObject) TableName() string { - return TableNamePivotLabelToObject + return model.TableNamePivotLabelToObject } // Pivot表 @@ -27,8 +28,6 @@ type PivotLabelToObject struct { Sort int `gorm:"comment:排序,越大约靠前"` } -const TableNamePivotLabelToObject = "pivot_label_to_object" - const PivotLabelToObjectOwnerKey = "object_type" const PivotLabelToObjectForeignKey = "object_id" const PivotLabelToObjectJoinKey = "label_id" diff --git a/internal/model/infoorganization/pivottagtobject.go b/internal/model/infoorganization/pivottagtobject.go index 5189637d..872eb7ca 100644 --- a/internal/model/infoorganization/pivottagtobject.go +++ b/internal/model/infoorganization/pivottagtobject.go @@ -1,6 +1,7 @@ package infoorganizatoin import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/internal/types" "PowerX/pkg/securityx" @@ -10,7 +11,7 @@ import ( // Table Name func (mdl *PivotTagToObject) TableName() string { - return TableNamePivotTagToObject + return model.TableNamePivotTagToObject } // Pivot表 @@ -27,8 +28,6 @@ type PivotTagToObject struct { Sort int `gorm:"comment:排序,越大约靠前"` } -const TableNamePivotTagToObject = "pivot_tag_to_object" - const PivotTagToObjectOwnerKey = "object_type" const PivotTagToObjectForeignKey = "object_id" const PivotTagToObjectJoinKey = "tag_id" diff --git a/internal/model/media/pivotMediaResourceToObject.go b/internal/model/media/pivotMediaResourceToObject.go index 6887ea37..7ddb6567 100644 --- a/internal/model/media/pivotMediaResourceToObject.go +++ b/internal/model/media/pivotMediaResourceToObject.go @@ -1,6 +1,7 @@ package media import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/internal/types" "PowerX/pkg/securityx" @@ -10,7 +11,7 @@ import ( // Table Name func (mdl *PivotMediaResourceToObject) TableName() string { - return TableNamePivotMediaResourceToObject + return model.TableNamePivotMediaResourceToObject } // Pivot表 @@ -31,8 +32,6 @@ type PivotMediaResourceToObject struct { MediaUsage string `gorm:"column:media_usage; comment:自定义用途" json:"mediaUsage"` } -const TableNamePivotMediaResourceToObject = "pivot_media_resource_to_object" - const PivotMediaResourceToObjectOwnerKey = "object_type" const PivotMediaResourceToObjectForeignKey = "object_id" const PivotMediaResourceToObjectJoinKey = "media_id" diff --git a/internal/model/powermodel/operationlog.go b/internal/model/operationlog.go similarity index 90% rename from internal/model/powermodel/operationlog.go rename to internal/model/operationlog.go index b2b6b651..f2e4be9e 100644 --- a/internal/model/powermodel/operationlog.go +++ b/internal/model/operationlog.go @@ -1,6 +1,7 @@ -package powermodel +package model import ( + "PowerX/internal/model/powermodel" "github.com/ArtisanCloud/PowerLibs/v3/object" "gorm.io/gorm" ) @@ -20,7 +21,7 @@ func (mdl *PowerOperationLog) TableName() string { // PowerOperationLog 数据表结构 type PowerOperationLog struct { - *PowerModel + *powermodel.PowerModel OperatorName *string `gorm:"column:operatorName" json:"operatorName"` OperatorTable *string `gorm:"column:operatorTable" json:"operatorTable"` @@ -34,8 +35,7 @@ type PowerOperationLog struct { Result *int8 `gorm:"column:result" json:"result"` } -const TableNameOperationLog = "power_operation_log" -const OperationLogUniqueId = UniqueId +const OperationLogUniqueId = powermodel.UniqueId func NewPowerOperationLog(mapObject *object.Collection) *PowerOperationLog { @@ -44,7 +44,7 @@ func NewPowerOperationLog(mapObject *object.Collection) *PowerOperationLog { } return &PowerOperationLog{ - PowerModel: NewPowerModel(), + PowerModel: powermodel.NewPowerModel(), OperatorName: mapObject.GetStringPointer("operatorName", ""), OperatorTable: mapObject.GetStringPointer("operatorTable", ""), OperatorId: mapObject.GetInt64Pointer("operatorId", 0), @@ -68,9 +68,9 @@ func (mdl *PowerOperationLog) GetTableName(needFull bool) string { } func (mdl *PowerOperationLog) SaveOps(db *gorm.DB, - operatorName string, operator ModelInterface, + operatorName string, operator powermodel.ModelInterface, module int16, operate string, event int8, - objectName string, object ModelInterface, + objectName string, object powermodel.ModelInterface, result int8, ) error { @@ -88,7 +88,7 @@ func (mdl *PowerOperationLog) SaveOps(db *gorm.DB, objectID := object.GetID() ops := &PowerOperationLog{ - PowerModel: NewPowerModel(), + PowerModel: powermodel.NewPowerModel(), OperatorName: &operatorName, OperatorTable: &operatorTable, OperatorId: &operatorID, diff --git a/internal/model/origanzation/department.go b/internal/model/organization/department.go similarity index 98% rename from internal/model/origanzation/department.go rename to internal/model/organization/department.go index c22643f9..06ed72fd 100644 --- a/internal/model/origanzation/department.go +++ b/internal/model/organization/department.go @@ -1,4 +1,4 @@ -package origanzation +package organization import ( "PowerX/internal/model" diff --git a/internal/model/origanzation/position.go b/internal/model/organization/position.go similarity index 95% rename from internal/model/origanzation/position.go rename to internal/model/organization/position.go index c4912ece..2d29e1c9 100644 --- a/internal/model/origanzation/position.go +++ b/internal/model/organization/position.go @@ -1,4 +1,4 @@ -package origanzation +package organization import ( "PowerX/internal/model" diff --git a/internal/model/origanzation/user.go b/internal/model/organization/user.go similarity index 99% rename from internal/model/origanzation/user.go rename to internal/model/organization/user.go index bb6f0747..ce3be753 100644 --- a/internal/model/origanzation/user.go +++ b/internal/model/organization/user.go @@ -1,4 +1,4 @@ -package origanzation +package organization import ( "PowerX/internal/model" diff --git a/internal/model/origanzation/user_test.go b/internal/model/organization/user_test.go similarity index 94% rename from internal/model/origanzation/user_test.go rename to internal/model/organization/user_test.go index d3cbdd09..9f9adb63 100644 --- a/internal/model/origanzation/user_test.go +++ b/internal/model/organization/user_test.go @@ -1,4 +1,4 @@ -package origanzation +package organization import ( fmt "PowerX/pkg/printx" diff --git a/internal/model/scene/activeqrcode.go b/internal/model/scene/activeqrcode.go index 186ed5ec..c1a40939 100644 --- a/internal/model/scene/activeqrcode.go +++ b/internal/model/scene/activeqrcode.go @@ -6,7 +6,7 @@ import ( "gorm.io/gorm/clause" ) -type SceneQrcode struct { +type SceneQRCode struct { model.Model QId string `gorm:"comment:唯一标识;unique;column:qid" json:"qid"` Name string `gorm:"comment:活码名称;column:name" json:"name"` @@ -31,8 +31,8 @@ type SceneQrcode struct { // @Description: // @receiver e // @return string -func (e SceneQrcode) TableName() string { - return `scene_qrcodes` +func (e SceneQRCode) TableName() string { + return model.TableNameSceneQRCode } // Query @@ -42,7 +42,7 @@ func (e SceneQrcode) TableName() string { // @param db // @return groups // @return err -func (e *SceneQrcode) Query(db *gorm.DB) (qrcode []*SceneQrcode) { +func (e *SceneQRCode) Query(db *gorm.DB) (qrcode []*SceneQRCode) { err := db.Model(e).Find(&qrcode).Error if err != nil { @@ -59,7 +59,7 @@ func (e *SceneQrcode) Query(db *gorm.DB) (qrcode []*SceneQrcode) { // @param db // @param group // @return []*WeWorkAppGroup -func (e *SceneQrcode) Action(db *gorm.DB, qrcode []*SceneQrcode) { +func (e *SceneQRCode) Action(db *gorm.DB, qrcode []*SceneQRCode) { err := db.Table(e.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "qid"}}, UpdateAll: true}).Create(&qrcode).Error if err != nil { @@ -75,7 +75,7 @@ func (e *SceneQrcode) Action(db *gorm.DB, qrcode []*SceneQrcode) { // @param db // @param qid // @param value -func (e *SceneQrcode) UpdateColumn(db *gorm.DB, qid string, value map[string]interface{}) { +func (e *SceneQRCode) UpdateColumn(db *gorm.DB, qid string, value map[string]interface{}) { err := db.Table(e.TableName()).Where(`qid = ?`, qid).UpdateColumns(&value).Error if err != nil { @@ -91,7 +91,7 @@ func (e *SceneQrcode) UpdateColumn(db *gorm.DB, qid string, value map[string]int // @param db // @param qid // @return qrcode -func (e *SceneQrcode) FindByQid(db *gorm.DB, qid string) (qrcode *SceneQrcode) { +func (e *SceneQRCode) FindByQid(db *gorm.DB, qid string) (qrcode *SceneQRCode) { err := db.Table(e.TableName()). //Debug(). @@ -102,14 +102,14 @@ func (e *SceneQrcode) FindByQid(db *gorm.DB, qid string) (qrcode *SceneQrcode) { return qrcode } -// FindEnableSceneQrcodeByQid +// FindEnableSceneQRCodeByQid // // @Description: // @receiver e // @param db // @param qid // @return qrcode -func (e *SceneQrcode) FindEnableSceneQrcodeByQid(db *gorm.DB, qid string) (qrcode *SceneQrcode) { +func (e *SceneQRCode) FindEnableSceneQRCodeByQid(db *gorm.DB, qid string) (qrcode *SceneQRCode) { err := db.Table(e.TableName()). //Debug(). @@ -126,7 +126,7 @@ func (e *SceneQrcode) FindEnableSceneQrcodeByQid(db *gorm.DB, qid string) (qrcod // @receiver e // @param db // @param qid -func (e *SceneQrcode) IncreaseCpa(db *gorm.DB, qid string) { +func (e *SceneQRCode) IncreaseCpa(db *gorm.DB, qid string) { err := db.Table(e.TableName()).Where(`qid = ?`, qid).Update(`cpa`, gorm.Expr(`cpa + ?`, 1)).Error if err != nil { diff --git a/internal/model/scrm/app/weworkappgroup.go b/internal/model/scrm/app/weworkappgroup.go index 47ecda07..0639063d 100644 --- a/internal/model/scrm/app/weworkappgroup.go +++ b/internal/model/scrm/app/weworkappgroup.go @@ -21,7 +21,7 @@ type WeWorkAppGroup struct { // @receiver e // @return string func (e WeWorkAppGroup) TableName() string { - return `we_work_app_groups` + return model.WeWorkAppGroup } type ( diff --git a/internal/model/scrm/customer/weworkcustomer.go b/internal/model/scrm/customer/weworkcustomer.go index dffe5229..c9e483bc 100644 --- a/internal/model/scrm/customer/weworkcustomer.go +++ b/internal/model/scrm/customer/weworkcustomer.go @@ -6,7 +6,7 @@ import ( "gorm.io/gorm/clause" ) -type WeWorkExternalContacts struct { +type WeWorkExternalContact struct { model.Model WeWorkExternalContactFollow WeWorkExternalContactFollow `gorm:"foreignKey:ExternalUserId;references:external_user_id" json:"WeWorkExternalContactFollow"` ExternalUserId string `gorm:"comment:客户ID;unique;not null;" json:"externalUserId"` @@ -29,24 +29,22 @@ type WeWorkExternalContacts struct { Active bool `gorm:"active" json:"active"` } -// // Table -// @Description: -// @receiver e -// @return string // -func (e WeWorkExternalContacts) TableName() string { - return `we_work_external_contacts` +// @Description: +// @receiver e +// @return string +func (e WeWorkExternalContact) TableName() string { + return model.TableNameWeWorkExternalContact } -// // Query -// @Description: -// @receiver e -// @param db -// @return contacts // -func (e WeWorkExternalContacts) Query(db *gorm.DB) (contacts []*WeWorkExternalContacts) { +// @Description: +// @receiver e +// @param db +// @return contacts +func (e WeWorkExternalContact) Query(db *gorm.DB) (contacts []*WeWorkExternalContact) { err := db.Model(e).Find(&contacts).Error if err != nil { @@ -56,14 +54,13 @@ func (e WeWorkExternalContacts) Query(db *gorm.DB) (contacts []*WeWorkExternalCo } -// // Action -// @Description: -// @receiver e -// @param db -// @param contacts // -func (e *WeWorkExternalContacts) Action(db *gorm.DB, contacts []*WeWorkExternalContacts) { +// @Description: +// @receiver e +// @param db +// @param contacts +func (e *WeWorkExternalContact) Action(db *gorm.DB, contacts []*WeWorkExternalContact) { err := db.Table(e.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "external_user_id"}}, UpdateAll: true}).CreateInBatches(&contacts, 100).Error if err != nil { diff --git a/internal/model/scrm/customer/weworkcustomerExternalFollow.go b/internal/model/scrm/customer/weworkcustomerExternalFollow.go index 3b2e24d9..7e654f26 100644 --- a/internal/model/scrm/customer/weworkcustomerExternalFollow.go +++ b/internal/model/scrm/customer/weworkcustomerExternalFollow.go @@ -13,7 +13,7 @@ type WeWorkExternalContactFollow struct { UserId string `gorm:"comment:员工ID;column:user_id" json:"user_id"` Remark string `gorm:"comment:备注;column:remark" json:"remark"` Description string `gorm:"comment:描述;column:description" json:"description"` - Createtime int `gorm:"comment:创建时间;column:create_time" json:"create_time"` + CreatedTime int `gorm:"comment:创建时间;column:create_time" json:"create_time"` Tags string `gorm:"comment:TAG;column:tags" json:"tags"` TagIds string `gorm:"comment:企业标签;column:tag_ids" json:"tag_ids"` WechatChannels string `gorm:"comment:Channels;column:wechat_channels" json:"wechat_channels"` @@ -24,23 +24,21 @@ type WeWorkExternalContactFollow struct { State string `gorm:"comment:State;column:state" json:"state"` } -// // Table -// @Description: -// @receiver e -// @return string // +// @Description: +// @receiver e +// @return string func (e WeWorkExternalContactFollow) TableName() string { - return `we_work_external_contact_follows` + return model.TableNameWeWorkExternalContactFollow } -// // Query -// @Description: -// @receiver e -// @param db -// @return follows // +// @Description: +// @receiver e +// @param db +// @return follows func (e WeWorkExternalContactFollow) Query(db *gorm.DB) (follows []*WeWorkExternalContactFollow) { err := db.Model(e).Find(&follows).Error @@ -51,13 +49,12 @@ func (e WeWorkExternalContactFollow) Query(db *gorm.DB) (follows []*WeWorkExtern } -// // Action -// @Description: -// @receiver e -// @param db -// @param contacts // +// @Description: +// @receiver e +// @param db +// @param contacts func (e *WeWorkExternalContactFollow) Action(db *gorm.DB, contacts []*WeWorkExternalContactFollow) { err := db.Table(e.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "external_user_id"}}, UpdateAll: true}).CreateInBatches(&contacts, 100).Error @@ -67,14 +64,13 @@ func (e *WeWorkExternalContactFollow) Action(db *gorm.DB, contacts []*WeWorkExte } -// // FindFollowByExternalUserId -// @Description: -// @receiver e -// @param db -// @param externalUserIds -// @return follows // +// @Description: +// @receiver e +// @param db +// @param externalUserIds +// @return follows func (e WeWorkExternalContactFollow) FindFollowByExternalUserId(db *gorm.DB, externalUserId string) (follow *WeWorkExternalContactFollow) { err := db.Model(e).Where(`external_user_id = ?`, externalUserId).Find(&follow).Error diff --git a/internal/model/scrm/organization/weworkdepartment.go b/internal/model/scrm/organization/weworkdepartment.go index f688010b..c6152584 100644 --- a/internal/model/scrm/organization/weworkdepartment.go +++ b/internal/model/scrm/organization/weworkdepartment.go @@ -24,7 +24,7 @@ type WeWorkDepartment struct { // @receiver e // @return string func (e WeWorkDepartment) TableName() string { - return `we_work_departments` + return model.TableNameWeWorkDepartment } // Query diff --git a/internal/model/scrm/organization/weworkuser.go b/internal/model/scrm/organization/weworkuser.go index 02cec8c0..c49aebab 100644 --- a/internal/model/scrm/organization/weworkuser.go +++ b/internal/model/scrm/organization/weworkuser.go @@ -35,7 +35,7 @@ type WeWorkUser struct { // @receiver e // @return string func (e WeWorkUser) TableName() string { - return `we_work_users` + return model.TableNameWeWorkUser } type ( diff --git a/internal/model/scrm/resource/department.go b/internal/model/scrm/resource/department.go index e3073dec..6c615079 100644 --- a/internal/model/scrm/resource/department.go +++ b/internal/model/scrm/resource/department.go @@ -1,60 +1,57 @@ package resource import ( - "PowerX/internal/model" - "gorm.io/gorm" - "gorm.io/gorm/clause" + "PowerX/internal/model" + "gorm.io/gorm" + "gorm.io/gorm/clause" ) type WeWorkResource struct { - model.Model - Url string `gorm:"comment:微信地址;column:url" json:"url"` - FileName string `gorm:"unique;comment:文件名;column:file_name" json:"file_name"` - Remark string `gorm:"comment:备注;column:remark" json:"remark"` - BucketName string `gorm:"comment:桶;column:bucket_name" json:"bucket_name"` - Size int `gorm:"comment:大小;column:size" json:"size"` - ResourceType string `gorm:"comment:资源类型:image,voice,file, video, other;column:resource_type" json:"resource_type"` + model.Model + Url string `gorm:"comment:微信地址;column:url" json:"url"` + FileName string `gorm:"unique;comment:文件名;column:file_name" json:"file_name"` + Remark string `gorm:"comment:备注;column:remark" json:"remark"` + BucketName string `gorm:"comment:桶;column:bucket_name" json:"bucket_name"` + Size int `gorm:"comment:大小;column:size" json:"size"` + ResourceType string `gorm:"comment:资源类型:image,voice,file, video, other;column:resource_type" json:"resource_type"` } -// // TableName -// @Description: -// @receiver e -// @return string // +// @Description: +// @receiver e +// @return string func (e WeWorkResource) TableName() string { - return `we_work_resources` + return model.TableNameWeWorkResource } -// // Query -// @Description: -// @receiver e -// @param db -// @return departments // +// @Description: +// @receiver e +// @param db +// @return departments func (e WeWorkResource) Query(db *gorm.DB) (resources []*WeWorkResource) { - err := db.Model(e).Find(&resources).Error - if err != nil { - panic(err) - } - return resources + err := db.Model(e).Find(&resources).Error + if err != nil { + panic(err) + } + return resources } -// // Action -// @Description: -// @receiver e -// @param db -// @param contacts // +// @Description: +// @receiver e +// @param db +// @param contacts func (e *WeWorkResource) Action(db *gorm.DB, resources []*WeWorkResource) { - err := db.Table(e.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "file_name"}}, UpdateAll: true}).CreateInBatches(&resources, 100).Error - if err != nil { - panic(err) - } + err := db.Table(e.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "file_name"}}, UpdateAll: true}).CreateInBatches(&resources, 100).Error + if err != nil { + panic(err) + } } diff --git a/internal/model/scrm/tag/weworkgroup.go b/internal/model/scrm/tag/weworkgroup.go index e8b6d69d..6b39ab3e 100644 --- a/internal/model/scrm/tag/weworkgroup.go +++ b/internal/model/scrm/tag/weworkgroup.go @@ -16,24 +16,22 @@ type WeWorkTagGroup struct { IsDelete bool `gorm:"comment:是否删除;column:is_delete" json:"is_delete"` } -// // Table -// @Description: -// @receiver e -// @return string // +// @Description: +// @receiver e +// @return string func (e WeWorkTagGroup) TableName() string { - return `we_work_tag_groups` + return model.TableNameWeWorkTagGroup } -// // Query -// @Description: -// @receiver this -// @param db -// @return groups -// @return err // +// @Description: +// @receiver this +// @param db +// @return groups +// @return err func (e *WeWorkTagGroup) Query(db *gorm.DB) (groups []*WeWorkTagGroup) { err := db.Model(e).Where(`is_delete = ?`, false).Preload(`WeWorkGroupTags`).Order(`sort ASC`).Find(&groups).Error @@ -44,14 +42,13 @@ func (e *WeWorkTagGroup) Query(db *gorm.DB) (groups []*WeWorkTagGroup) { } -// // Action -// @Description: -// @receiver this -// @param db -// @param group -// @return []*WeWorkAppGroup // +// @Description: +// @receiver this +// @param db +// @param group +// @return []*WeWorkAppGroup func (e *WeWorkTagGroup) Action(db *gorm.DB, groups []*WeWorkTagGroup) { err := db.Table(e.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "group_id"}}, UpdateAll: true}).Create(&groups).Error diff --git a/internal/model/scrm/tag/weworktag.go b/internal/model/scrm/tag/weworktag.go index 30f9b337..72902a76 100644 --- a/internal/model/scrm/tag/weworktag.go +++ b/internal/model/scrm/tag/weworktag.go @@ -26,7 +26,7 @@ type WeWorkTag struct { // @receiver e // @return string func (e WeWorkTag) TableName() string { - return `we_work_tags` + return model.TableNameWeWorkTag } // Query diff --git a/internal/model/tables.go b/internal/model/tables.go new file mode 100644 index 00000000..2f93e519 --- /dev/null +++ b/internal/model/tables.go @@ -0,0 +1,107 @@ +package model + +var PowerXSchema = "public" + +// crm customer domain + +const TableNameContact = "contacts" +const TableNameCustomer = "customers" +const TableNameLead = "leads" +const TableNameRegisterCode = "register_codes" + +// crm market +const TableNameMedia = "media" +const TableNameMGM = "mgm_rules" +const TableNamePromotionRule = "promotion_rules" +const TableNameStore = "stores" + +// operation +const TableNameMembership = "memberships" +const TableNameTicketRecord = "ticket_record" + +// product +const TableNameArtisan = "artisans" +const TableNamePivotProductToProductCategory = "pivot_product_to_product_category" +const TableNamePivotSkuToSpecificOption = "pivot_sku_to_specific_options" +const TableNamePivotStoreToArtisan = "pivot_store_to_artisan" +const TableNamePriceBook = "price_books" +const TableNamePriceBookEntry = "price_book_entries" +const TableNamePriceConfig = "price_configs" +const TableNameProduct = "products" +const TableNameProductCategory = "product_categories" +const TableNameProductSpecific = "product_specifics" +const TableNameProductStatistics = "product_statistics" +const TableNameSKU = "sku" + +// trade +const TableNameBillingAddress = "billing_addresses" +const TableNameBillingCart = "carts" +const TableNameBillingCartItem = "cart_items" +const TableNameDeliveryAddress = "delivery_addresses" +const TableNameInventory = "inventories" +const TableNameLogistics = "logistics" +const TableNameOrder = "orders" +const TableNamePayment = "payments" +const TableNamePivotProductToPromotion = "pivot_product_to_promotion" +const TableNamePivotOrderToInventoryLog = "pivot_order_to_inventory_log" +const TableNameRefundOrder = "refund_orders" +const TableNameRefundOrderItem = "refund_order_items" +const TableNameShippingAddress = "shipping_addresses" +const TableNameTokenExchangeRatio = "token_exchange_ratios" +const TableNameTokenExchangeRecord = "token_exchange_records" +const TableNameTokenReservation = "token_reservations" +const TableNameTokenTransaction = "token_transactions" +const TableNameWarehouse = "warehouse" + +// info organization +const TableNameCategory = "categories" +const TableNameLabel = "labels" +const TableNamePivotCategoryToObject = "pivot_category_to_object" +const TableNamePivotLabelToObject = "pivot_label_to_object" +const TableNamePivotTagToObject = "pivot_tag_to_object" + +// media +const TableNameMediaResource = "media_resources" +const TableNamePivotMediaResourceToObject = "pivot_media_resource_to_object" + +// organization +const TableNameDepartment = "departments" +const TableNamePosition = "positions" +const TableNameUser = "users" + +// power model +const TableNameOperationLog = "power_operation_logs" + +// scene +const TableNameSceneQRCode = "scene_qr_codes" + +const TableNamePivotDataDictionaryToObject = "pivot_data_dictionary_to_object" + +// tag +const TableNamePivotObjectToTag = "pivot_object_to_tag" +const TableNameTag = "tags" + +// scrm app +const WeWorkAppGroup = "wework_app_groups" + +// scrm customer +const TableNameWeWorkExternalContact = "we_work_external_contacts" +const TableNameWeWorkExternalContactFollow = "we_work_external_contact_follows" + +// scrm organization +const TableNameWeWorkDepartment = "we_work_departments" +const TableNameWeWorkUser = "we_work_users" + +// scrm resource +const TableNameWeWorkResource = "we_work_resources" + +// scrm tag +const TableNameWeWorkTagGroup = "we_work_tag_groups" +const TableNameWeWorkTag = "we_work_tags" + +// wechat +const TableNameWechatMPCustomer = "wechat_mp_customers" +const TableNameWechatOACustomer = "wechat_oa_customers" + +// custom +const TableNameArtisanSpecific = "artisan_specifics" diff --git a/internal/model/tag/pivotobjecttotag.go b/internal/model/tag/pivotobjecttotag.go index 0a653e63..a31c9d6e 100644 --- a/internal/model/tag/pivotobjecttotag.go +++ b/internal/model/tag/pivotobjecttotag.go @@ -1,6 +1,7 @@ package tag import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/pkg/securityx" "fmt" @@ -9,7 +10,7 @@ import ( // Table Name func (mdl *PivotObjectToTag) TableName() string { - return TableNamePivotObjectToTag + return model.TableNamePivotObjectToTag } // 数据表结构 @@ -23,8 +24,6 @@ type PivotObjectToTag struct { TagId int64 `gorm:"column:tag_id; not null;index:idx_tag_id" json:"tagId"` } -const TableNamePivotObjectToTag = "pivot_object_to_tag" - const PivotObjectToTagForeignOwnerKey = "object_type" const PivotObjectToTagForeignKey = "object_id" const PivotObjectToTagJoinKey = "tag_id" diff --git a/internal/model/wechat/wework.go b/internal/model/wechat/wework.go index 25798987..dde1d790 100644 --- a/internal/model/wechat/wework.go +++ b/internal/model/wechat/wework.go @@ -1,25 +1,20 @@ package wechat -import ( - "PowerX/internal/model" - "github.com/ArtisanCloud/PowerLibs/v3/object" -) - type WeWorkExternalContact struct { - model.Model - CorpId object.NullString `gorm:"index:idx_corp_id;column:corp_id" json:"corpId"` - AppId object.NullString `gorm:"index:idx_app_id;column:app_id" json:"appId"` - ExternalUserId object.NullString `gorm:"index:idx_external_user_id;column:external_user_id;not null;" json:"externalUserId"` - OpenId object.NullString `gorm:"index:idx_customer_open_id;column:open_id;" json:"openId"` - UnionId object.NullString `gorm:"index:idx_union_id;column:union_id" json:"unionId"` - - Name string `gorm:"column:name" json:"name"` - Mobile string `gorm:"column:mobile" json:"mobile"` - Position string `gorm:"column:position" json:"position"` - Avatar string `gorm:"column:avatar" json:"avatar"` - CorpName string `gorm:"column:corp_name" json:"corpName"` - CorpFullName string `gorm:"column:corp_full_name" json:"corpFullName"` - ExternalProfile string `gorm:"column:external_profile" json:"externalProfile"` - Gender int `gorm:"column:gender" json:"gender"` - WXType int8 `gorm:"column:wx_type" json:"wxType"` + //model.Model + //CorpId object.NullString `gorm:"index:idx_corp_id;column:corp_id" json:"corpId"` + //AppId object.NullString `gorm:"index:idx_app_id;column:app_id" json:"appId"` + //ExternalUserId object.NullString `gorm:"index:idx_external_user_id;column:external_user_id;not null;" json:"externalUserId"` + //OpenId object.NullString `gorm:"index:idx_customer_open_id;column:open_id;" json:"openId"` + //UnionId object.NullString `gorm:"index:idx_union_id;column:union_id" json:"unionId"` + // + //Name string `gorm:"column:name" json:"name"` + //Mobile string `gorm:"column:mobile" json:"mobile"` + //Position string `gorm:"column:position" json:"position"` + //Avatar string `gorm:"column:avatar" json:"avatar"` + //CorpName string `gorm:"column:corp_name" json:"corpName"` + //CorpFullName string `gorm:"column:corp_full_name" json:"corpFullName"` + //ExternalProfile string `gorm:"column:external_profile" json:"externalProfile"` + //Gender int `gorm:"column:gender" json:"gender"` + //WXType int8 `gorm:"column:wx_type" json:"wxType"` } diff --git a/internal/types/types.go b/internal/types/types.go index fe1c0125..ec23d536 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -23,7 +23,7 @@ type ActionQrcodeActiveReply struct { type ActionRequest struct { Qid string `path:"qid"` // 唯一标识 - SceneQrcodeLink string `json:"sceneQrcodeLink,optional"` + SceneQRCodeLink string `json:"sceneQrcodeLink,optional"` } type ActionTagGroup struct { @@ -3103,7 +3103,7 @@ type SKU struct { OptionsIds []int64 `json:"optionsIds,optional"` } -type SceneQrcodeActiveReply struct { +type SceneQRCodeActiveReply struct { QId string `json:"qid"` // 唯一码 Name string `json:"name"` // 活码名称 Desc string `json:"desc"` // 描述 @@ -3647,7 +3647,7 @@ type WechatCustomersWithFollowUser struct { UserId string `json:"userId"` Remark string `json:"remark"` Description string `json:"description"` - Createtime int `json:"createtime"` + CreatedTime int `json:"createtime"` Tags []WechatCustomersFollowUserWithTags `json:"tags"` TagIds []string `json:"tagIds"` WechatChannels WechatCustomersFollowUserWithWechatChannels `json:"wechatChannels"` diff --git a/internal/uc/powerx/authorizationadmin.go b/internal/uc/powerx/authorizationadmin.go index d8ec9fac..561f8bf5 100644 --- a/internal/uc/powerx/authorizationadmin.go +++ b/internal/uc/powerx/authorizationadmin.go @@ -2,7 +2,7 @@ package powerx import ( "PowerX/internal/config" - "PowerX/internal/model/origanzation" + "PowerX/internal/model/organization" "PowerX/internal/model/permission" "PowerX/internal/types/errorx" "PowerX/pkg/mapx" @@ -144,7 +144,7 @@ func (uc *AdminPermsUseCase) Init() { } // 初始化用户 - if err := uc.db.Model(&origanzation.User{}).Count(&count).Error; err != nil { + if err := uc.db.Model(&organization.User{}).Count(&count).Error; err != nil { panic(errors.Wrap(err, "init role failed")) } if count == 0 { @@ -161,16 +161,16 @@ func (uc *AdminPermsUseCase) Init() { if rooName == "" { rooName = "超级管理员" } - root := origanzation.User{ + root := organization.User{ UUID: uuid.New().String(), Account: rooAccount, Password: rooPass, Name: rooName, - Status: origanzation.UserStatusEnabled, + Status: organization.UserStatusEnabled, IsReserved: true, } root.HashPassword() - if err := uc.db.Model(&origanzation.User{}).Create(&root).Error; err != nil { + if err := uc.db.Model(&organization.User{}).Create(&root).Error; err != nil { panic(errors.Wrap(err, "init root failed")) } } diff --git a/internal/uc/powerx/organization.go b/internal/uc/powerx/organization.go index cab52800..216aacbf 100644 --- a/internal/uc/powerx/organization.go +++ b/internal/uc/powerx/organization.go @@ -3,7 +3,7 @@ package powerx import ( "PowerX/internal/model" "PowerX/internal/model/option" - "PowerX/internal/model/origanzation" + "PowerX/internal/model/organization" "PowerX/internal/model/permission" "PowerX/internal/model/powermodel" "PowerX/internal/types" @@ -28,10 +28,10 @@ func NewOrganizationUseCase(db *gorm.DB) *OrganizationUseCase { } func (uc *OrganizationUseCase) VerifyPassword(hashedPwd string, pwd string) bool { - return origanzation.VerifyPassword(hashedPwd, pwd) + return organization.VerifyPassword(hashedPwd, pwd) } -func (uc *OrganizationUseCase) CreateUser(ctx context.Context, user *origanzation.User) (err error) { +func (uc *OrganizationUseCase) CreateUser(ctx context.Context, user *organization.User) (err error) { if err := uc.db.WithContext(ctx).Create(&user).Error; err != nil { // todo use errors.Is() when gorm update ErrDuplicatedKey if strings.Contains(err.Error(), "duplicate key value violates unique constraint") { @@ -43,15 +43,15 @@ func (uc *OrganizationUseCase) CreateUser(ctx context.Context, user *origanzatio } func (uc *OrganizationUseCase) FindAccountsByIds(ctx context.Context, userIds []int64) (accounts []string) { - err := uc.db.WithContext(ctx).Model(&origanzation.User{}).Where("id in ?", userIds).Pluck("account", &accounts).Error + err := uc.db.WithContext(ctx).Model(&organization.User{}).Where("id in ?", userIds).Pluck("account", &accounts).Error if err != nil { panic(errors.Wrap(err, "find accounts by ids failed")) } return accounts } -func (uc *OrganizationUseCase) PatchUserByUserId(ctx context.Context, user *origanzation.User, userId int64) error { - result := uc.db.WithContext(ctx).Model(&origanzation.User{}).Where(user.Id).Updates(&user) +func (uc *OrganizationUseCase) PatchUserByUserId(ctx context.Context, user *organization.User, userId int64) error { + result := uc.db.WithContext(ctx).Model(&organization.User{}).Where(user.Id).Updates(&user) if result.Error != nil { panic(result.Error) } @@ -95,10 +95,10 @@ func buildFindManyUsersQueryNoPage(query *gorm.DB, opt *option.FindManyUsersOpti return query } -func (uc *OrganizationUseCase) FindManyUsersPage(ctx context.Context, opt *option.FindManyUsersOption) types.Page[*origanzation.User] { - var users []*origanzation.User +func (uc *OrganizationUseCase) FindManyUsersPage(ctx context.Context, opt *option.FindManyUsersOption) types.Page[*organization.User] { + var users []*organization.User var count int64 - query := uc.db.WithContext(ctx).Model(&origanzation.User{}) + query := uc.db.WithContext(ctx).Model(&organization.User{}) query = buildFindManyUsersQueryNoPage(query, opt) if err := query.Count(&count).Error; err != nil { @@ -119,7 +119,7 @@ func (uc *OrganizationUseCase) FindManyUsersPage(ctx context.Context, opt *optio if err := query.Find(&users).Error; err != nil { panic(errors.Wrap(err, "find users failed")) } - return types.Page[*origanzation.User]{ + return types.Page[*organization.User]{ List: users, PageIndex: opt.PageIndex, PageSize: opt.PageSize, @@ -127,12 +127,12 @@ func (uc *OrganizationUseCase) FindManyUsersPage(ctx context.Context, opt *optio } } -func (uc *OrganizationUseCase) FindOneUserByLoginOption(ctx context.Context, opt *option.UserLoginOption) (user *origanzation.User, err error) { +func (uc *OrganizationUseCase) FindOneUserByLoginOption(ctx context.Context, opt *option.UserLoginOption) (user *organization.User, err error) { if *opt == (option.UserLoginOption{}) { panic(errors.New("option empty")) } - var queryUser origanzation.User + var queryUser organization.User if opt.Account != "" { queryUser.Account = opt.Account } @@ -143,7 +143,7 @@ func (uc *OrganizationUseCase) FindOneUserByLoginOption(ctx context.Context, opt queryUser.MobilePhone = opt.PhoneNumber } - if err = uc.db.WithContext(ctx).Model(&origanzation.User{}).Where(&queryUser).First(&user).Error; err != nil { + if err = uc.db.WithContext(ctx).Model(&organization.User{}).Where(&queryUser).First(&user).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, errorx.WithCause(errorx.ErrBadRequest, "用户不存在, 请检查登录信息") } @@ -152,7 +152,7 @@ func (uc *OrganizationUseCase) FindOneUserByLoginOption(ctx context.Context, opt return } -func (uc *OrganizationUseCase) FindOneUserById(ctx context.Context, id int64) (user *origanzation.User, err error) { +func (uc *OrganizationUseCase) FindOneUserById(ctx context.Context, id int64) (user *organization.User, err error) { if err = uc.db.WithContext(ctx).Where(id).Preload("Department").Preload("Position").First(&user).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, errorx.WithCause(errorx.ErrBadRequest, "用户不存在") @@ -162,8 +162,8 @@ func (uc *OrganizationUseCase) FindOneUserById(ctx context.Context, id int64) (u return } -func (uc *OrganizationUseCase) UpdateUserById(ctx context.Context, user *origanzation.User, userId int64) error { - whereCase := origanzation.User{ +func (uc *OrganizationUseCase) UpdateUserById(ctx context.Context, user *organization.User, userId int64) error { + whereCase := organization.User{ Model: model.Model{ Id: userId, }, @@ -181,7 +181,7 @@ func (uc *OrganizationUseCase) UpdateUserById(ctx context.Context, user *origanz } func (uc *OrganizationUseCase) DeleteUserById(ctx context.Context, id int64) error { - result := uc.db.WithContext(ctx).Where(origanzation.User{IsReserved: false}, "is_reserved").Delete(&origanzation.User{}, id) + result := uc.db.WithContext(ctx).Where(organization.User{IsReserved: false}, "is_reserved").Delete(&organization.User{}, id) err := result.Error if err != nil { panic(errors.Wrap(err, "delete user failed")) @@ -194,7 +194,7 @@ func (uc *OrganizationUseCase) DeleteUserById(ctx context.Context, id int64) err // FindUserPositionRoleCodes 获取员工的职位的角色代码 func (uc *OrganizationUseCase) FindUserPositionRoleCodes(ctx context.Context, userId int64) (roleCodes []string, err error) { - var user origanzation.User + var user organization.User if err = uc.db.WithContext(ctx).Preload("Position.Roles").First(&user, userId).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, errorx.WithCause(errorx.ErrBadRequest, "用户不存在") @@ -207,8 +207,8 @@ func (uc *OrganizationUseCase) FindUserPositionRoleCodes(ctx context.Context, us return } -func (uc *OrganizationUseCase) FindOneDepartment(ctx context.Context, id int64) (department *origanzation.Department, err error) { - department = &origanzation.Department{} +func (uc *OrganizationUseCase) FindOneDepartment(ctx context.Context, id int64) (department *organization.Department, err error) { + department = &organization.Department{} if err := uc.db.WithContext(ctx).Preload("Leader").First(department, id).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, errorx.WithCause(errorx.ErrBadRequest, "部门未找到") @@ -218,13 +218,13 @@ func (uc *OrganizationUseCase) FindOneDepartment(ctx context.Context, id int64) return department, nil } -func (uc *OrganizationUseCase) CreateDepartment(ctx context.Context, dep *origanzation.Department) error { +func (uc *OrganizationUseCase) CreateDepartment(ctx context.Context, dep *organization.Department) error { if dep.PId == 0 { return errorx.WithCause(errorx.ErrBadRequest, "必须指定父部门Id") } db := uc.db.WithContext(ctx) // 查询父节点 - var pDep *origanzation.Department + var pDep *organization.Department if err := db.Preload("Ancestors").Where(dep.PId).First(&pDep).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return errorx.WithCause(errorx.ErrBadRequest, "父部门不存在") @@ -242,10 +242,10 @@ func (uc *OrganizationUseCase) CreateDepartment(ctx context.Context, dep *origan return nil } -func (uc *OrganizationUseCase) FindManyDepartmentsPage(ctx context.Context, opt *types.PageOption[option.FindManyDepartmentsOption]) *types.Page[*origanzation.Department] { - var deps []*origanzation.Department +func (uc *OrganizationUseCase) FindManyDepartmentsPage(ctx context.Context, opt *types.PageOption[option.FindManyDepartmentsOption]) *types.Page[*organization.Department] { + var deps []*organization.Department var count int64 - query := uc.db.WithContext(ctx).Model(origanzation.Department{}) + query := uc.db.WithContext(ctx).Model(organization.Department{}) if len(opt.Option.DepIds) > 0 { query.Where(opt.Option.DepIds) @@ -264,7 +264,7 @@ func (uc *OrganizationUseCase) FindManyDepartmentsPage(ctx context.Context, opt if err := query.Find(&deps).Error; err != nil { panic(errors.Wrap(err, "query deps failed")) } - return &types.Page[*origanzation.Department]{ + return &types.Page[*organization.Department]{ List: deps, PageIndex: opt.PageIndex, PageSize: opt.PageSize, @@ -272,9 +272,9 @@ func (uc *OrganizationUseCase) FindManyDepartmentsPage(ctx context.Context, opt } } -func (uc *OrganizationUseCase) FindManyDepartmentsByRootId(ctx context.Context, rootId int64) (departments []*origanzation.Department, err error) { - departments = []*origanzation.Department{} - if err := uc.db.WithContext(ctx).Model(origanzation.Department{}).Preload("Leader").Preload("Ancestors"). +func (uc *OrganizationUseCase) FindManyDepartmentsByRootId(ctx context.Context, rootId int64) (departments []*organization.Department, err error) { + departments = []*organization.Department{} + if err := uc.db.WithContext(ctx).Model(organization.Department{}).Preload("Leader").Preload("Ancestors"). Joins("LEFT JOIN department_ancestors ON departments.id = department_ancestors.department_id"). Where("department_ancestors.ancestor_id = ?", rootId).Or("departments.id = ?", rootId). Find(&departments).Error; err != nil { @@ -286,7 +286,7 @@ func (uc *OrganizationUseCase) FindManyDepartmentsByRootId(ctx context.Context, return } -func (uc *OrganizationUseCase) FindAllDepartments(ctx context.Context) (departments []*origanzation.Department) { +func (uc *OrganizationUseCase) FindAllDepartments(ctx context.Context) (departments []*organization.Department) { if err := uc.db.WithContext(ctx).Preload("Leader").Find(&departments).Error; err != nil { panic(err) } @@ -294,14 +294,14 @@ func (uc *OrganizationUseCase) FindAllDepartments(ctx context.Context) (departme } func (uc *OrganizationUseCase) CountUserInDepartmentByIds(ctx context.Context, depIds []int64) (count int64) { - if err := uc.db.WithContext(ctx).Model(origanzation.User{}).Where("department_id in ?", depIds).Count(&count).Error; err != nil { + if err := uc.db.WithContext(ctx).Model(organization.User{}).Where("department_id in ?", depIds).Count(&count).Error; err != nil { panic(err) } return count } -func (uc *OrganizationUseCase) PatchDepartmentById(ctx context.Context, id int64, dep *origanzation.Department) error { - result := uc.db.WithContext(ctx).Model(origanzation.Department{}).Where(origanzation.Department{IsReserved: false}, "is_reserved"). +func (uc *OrganizationUseCase) PatchDepartmentById(ctx context.Context, id int64, dep *organization.Department) error { + result := uc.db.WithContext(ctx).Model(organization.Department{}).Where(organization.Department{IsReserved: false}, "is_reserved"). Where("id = ?", id).Updates(&dep) if result.Error != nil { panic(result.Error) @@ -314,12 +314,12 @@ func (uc *OrganizationUseCase) PatchDepartmentById(ctx context.Context, id int64 func (uc *OrganizationUseCase) DeleteDepartmentById(ctx context.Context, id int64) error { db := uc.db.WithContext(ctx) - queryWhere := db.Model(origanzation.Department{}). + queryWhere := db.Model(organization.Department{}). Joins("LEFT JOIN department_ancestors ON departments.id = department_ancestors.department_id"). Where("department_ancestors.ancestor_id = ?", id).Or("departments.id = ?", id). Select("id") - result := db.Model(origanzation.Department{}).Where(origanzation.Department{IsReserved: false}, "is_reserved"). - Where("id in (?)", queryWhere).Delete(&origanzation.Department{}) + result := db.Model(organization.Department{}).Where(organization.Department{IsReserved: false}, "is_reserved"). + Where("id in (?)", queryWhere).Delete(&organization.Department{}) if result.Error != nil { panic(result.Error) } @@ -330,7 +330,7 @@ func (uc *OrganizationUseCase) DeleteDepartmentById(ctx context.Context, id int6 } // CreatePosition 创建职位 -func (uc *OrganizationUseCase) CreatePosition(ctx context.Context, position *origanzation.Position) error { +func (uc *OrganizationUseCase) CreatePosition(ctx context.Context, position *organization.Position) error { if err := uc.db.WithContext(ctx).Create(&position).Error; err != nil { panic(err) } @@ -338,8 +338,8 @@ func (uc *OrganizationUseCase) CreatePosition(ctx context.Context, position *ori } // EditPosition 编辑职位 -func (uc *OrganizationUseCase) EditPosition(ctx context.Context, position *origanzation.Position) error { - result := uc.db.WithContext(ctx).Model(&origanzation.Position{}).Where("id = ?", position.Id).Updates(&position) +func (uc *OrganizationUseCase) EditPosition(ctx context.Context, position *organization.Position) error { + result := uc.db.WithContext(ctx).Model(&organization.Position{}).Where("id = ?", position.Id).Updates(&position) if result.Error != nil { panic(result.Error) } @@ -350,8 +350,8 @@ func (uc *OrganizationUseCase) EditPosition(ctx context.Context, position *origa } // FindOnePositionByID 查询职位列表 -func (uc *OrganizationUseCase) FindOnePositionByID(ctx context.Context, id int64) (position *origanzation.Position, err error) { - position = &origanzation.Position{} +func (uc *OrganizationUseCase) FindOnePositionByID(ctx context.Context, id int64) (position *organization.Position, err error) { + position = &organization.Position{} if err := uc.db.WithContext(ctx).Preload("Roles").First(position, id).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, errorx.WithCause(errorx.ErrBadRequest, "职位未找到") @@ -362,9 +362,9 @@ func (uc *OrganizationUseCase) FindOnePositionByID(ctx context.Context, id int64 } // FindManyPositions 查询职位列表 -func (uc *OrganizationUseCase) FindManyPositions(ctx context.Context, opt *option.FindManyPositionsOption) (positions []*origanzation.Position, err error) { - positions = []*origanzation.Position{} - query := uc.db.WithContext(ctx).Model(&origanzation.Position{}).Preload("Roles") +func (uc *OrganizationUseCase) FindManyPositions(ctx context.Context, opt *option.FindManyPositionsOption) (positions []*organization.Position, err error) { + positions = []*organization.Position{} + query := uc.db.WithContext(ctx).Model(&organization.Position{}).Preload("Roles") if opt.LikeName != "" { query = query.Where("name like ?", fmt.Sprintf("%%%s%%", opt.LikeName)) @@ -378,7 +378,7 @@ func (uc *OrganizationUseCase) FindManyPositions(ctx context.Context, opt *optio // DeletePosition 删除职位 func (uc *OrganizationUseCase) DeletePosition(ctx context.Context, id int64) error { - result := uc.db.WithContext(ctx).Where("id = ?", id).Delete(&origanzation.Position{}) + result := uc.db.WithContext(ctx).Where("id = ?", id).Delete(&organization.Position{}) if result.Error != nil { panic(result.Error) } @@ -389,7 +389,7 @@ func (uc *OrganizationUseCase) DeletePosition(ctx context.Context, id int64) err } // PatchPosition 编辑职位 -func (uc *OrganizationUseCase) PatchPosition(ctx context.Context, id int64, position *origanzation.Position) error { +func (uc *OrganizationUseCase) PatchPosition(ctx context.Context, id int64, position *organization.Position) error { position.Id = id result := uc.db.WithContext(ctx).Where("id = ?", id).Updates(&position) uc.db.Model(&position).Association("Roles").Replace(position.Roles) @@ -401,8 +401,8 @@ func (uc *OrganizationUseCase) PatchPosition(ctx context.Context, id int64, posi // GetPositionOptionMap 获取职位Option {label: Name, value: Id} func (uc *OrganizationUseCase) GetPositionOptionMap(ctx context.Context, search string) ([]map[string]any, error) { - var positions []*origanzation.Position - query := uc.db.WithContext(ctx).Model(&origanzation.Position{}) + var positions []*organization.Position + query := uc.db.WithContext(ctx).Model(&organization.Position{}) if search != "" { query = query.Where("name like ?", fmt.Sprintf("%%%s%%", search)) } diff --git a/internal/uc/powerx/scrm/scene/interface.go b/internal/uc/powerx/scrm/scene/interface.go index b39eabba..b0729f20 100644 --- a/internal/uc/powerx/scrm/scene/interface.go +++ b/internal/uc/powerx/scrm/scene/interface.go @@ -14,12 +14,12 @@ type IsceneInterface interface { // @Description: type iQrcodeInterface interface { // - // FindOneSceneQrcodeDetail + // FindOneSceneQRCodeDetail // @Description: 场景码详情 // @param qid // @return *qrcode.QrcodeActive // - FindOneSceneQrcodeDetail(qid string) *scene.SceneQrcode + FindOneSceneQRCodeDetail(qid string) *scene.SceneQRCode // // IncreaseSceneCpaNumber // @Description: CPA+1 diff --git a/internal/uc/powerx/scrm/scene/qrcodescene.go b/internal/uc/powerx/scrm/scene/qrcodescene.go index 70894e1d..35b1f86b 100644 --- a/internal/uc/powerx/scrm/scene/qrcodescene.go +++ b/internal/uc/powerx/scrm/scene/qrcodescene.go @@ -4,15 +4,15 @@ import ( "PowerX/internal/model/scene" ) -// FindOneSceneQrcodeDetail +// FindOneSceneQRCodeDetail // // @Description: // @receiver this // @param qid // @return *qrcode.QrcodeActive -func (this *sceneUseCase) FindOneSceneQrcodeDetail(qid string) *scene.SceneQrcode { +func (this *sceneUseCase) FindOneSceneQRCodeDetail(qid string) *scene.SceneQRCode { - qrcode := this.modelSceneQrcode.qrcode.FindEnableSceneQrcodeByQid(this.db, qid) + qrcode := this.modelSceneQRCode.qrcode.FindEnableSceneQRCodeByQid(this.db, qid) return qrcode @@ -25,5 +25,5 @@ func (this *sceneUseCase) FindOneSceneQrcodeDetail(qid string) *scene.SceneQrcod // @param qid func (this *sceneUseCase) IncreaseSceneCpaNumber(qid string) { - this.modelSceneQrcode.qrcode.IncreaseCpa(this.db, qid) + this.modelSceneQRCode.qrcode.IncreaseCpa(this.db, qid) } diff --git a/internal/uc/powerx/scrm/scene/scene.go b/internal/uc/powerx/scrm/scene/scene.go index 8b944b14..78374643 100644 --- a/internal/uc/powerx/scrm/scene/scene.go +++ b/internal/uc/powerx/scrm/scene/scene.go @@ -13,11 +13,11 @@ type sceneUseCase struct { db *gorm.DB kv *redis.Redis ctx context.Context - modelSceneQrcode + modelSceneQRCode } type ( - modelSceneQrcode struct { - qrcode scene.SceneQrcode + modelSceneQRCode struct { + qrcode scene.SceneQRCode } ) diff --git a/internal/uc/powerx/scrm/wechat/interface.go b/internal/uc/powerx/scrm/wechat/interface.go index e6ad5147..4f63c17c 100644 --- a/internal/uc/powerx/scrm/wechat/interface.go +++ b/internal/uc/powerx/scrm/wechat/interface.go @@ -141,10 +141,10 @@ type iWeWorkCustomerInterface interface { // @param ctx // @param opt // @param sync - // @return *types.Page[*customer.WeWorkExternalContacts] + // @return *types.Page[*customer.WeWorkExternalContact] // @return error // - FindManyWeWorkCustomerPage(ctx context.Context, opt *types.PageOption[FindManyWechatCustomerOption], sync int) (*types.Page[*customer.WeWorkExternalContacts], error) + FindManyWeWorkCustomerPage(ctx context.Context, opt *types.PageOption[FindManyWechatCustomerOption], sync int) (*types.Page[*customer.WeWorkExternalContact], error) // // PushWoWorkCustomerTemplateRequest @@ -292,7 +292,7 @@ type iQrcodeInterface interface { // @return reply // @return err // - FindWeWorkCustomerGroupQrcodePage(opt *types.PageOption[types.ListWeWorkGroupQrcodeActiveReqeust]) (reply *types.Page[*scene.SceneQrcode], err error) + FindWeWorkCustomerGroupQrcodePage(opt *types.PageOption[types.ListWeWorkGroupQrcodeActiveReqeust]) (reply *types.Page[*scene.SceneQRCode], err error) // // ActionCustomerGroupQrcode @@ -304,13 +304,13 @@ type iQrcodeInterface interface { ActionCustomerGroupQrcode(qid string, action int) error // - // UpdateSceneQrcodeLink + // UpdateSceneQRCodeLink // @Description: 更新场景码 // @param qid // @param link // @return error // - UpdateSceneQrcodeLink(qid string, link string) error + UpdateSceneQRCodeLink(qid string, link string) error } // iTagInterface diff --git a/internal/uc/powerx/scrm/wechat/wechat.go b/internal/uc/powerx/scrm/wechat/wechat.go index 1eff5726..1022c0a1 100644 --- a/internal/uc/powerx/scrm/wechat/wechat.go +++ b/internal/uc/powerx/scrm/wechat/wechat.go @@ -1,7 +1,7 @@ package wechat import ( - "PowerX/internal/model/origanzation" + organization2 "PowerX/internal/model/organization" "PowerX/internal/model/scene" "PowerX/internal/model/scrm/app" "PowerX/internal/model/scrm/customer" @@ -95,8 +95,8 @@ type ( help struct{} hash power.HashMap modelOrganization struct { - user origanzation.User - department origanzation.Department + user organization2.User + department organization2.Department } modelWeworkApp struct { group app.WeWorkAppGroup @@ -109,7 +109,7 @@ type ( resource resource.WeWorkResource } modelWeworkQrcode struct { - qrcode scene.SceneQrcode + qrcode scene.SceneQRCode } modelWeworkTag struct { tag tag.WeWorkTag diff --git a/internal/uc/powerx/scrm/wechat/wechatqrcodecustomergroup.go b/internal/uc/powerx/scrm/wechat/wechatqrcodecustomergroup.go index 4211d0e6..af555d09 100644 --- a/internal/uc/powerx/scrm/wechat/wechatqrcodecustomergroup.go +++ b/internal/uc/powerx/scrm/wechat/wechatqrcodecustomergroup.go @@ -15,7 +15,7 @@ import ( // @return error func (this wechatUseCase) CreateWeWorkCustomerGroupQrcodeRequest(opt *types.QrcodeActiveRequest) (err error) { - this.qrcode.Action(this.db, []*scene.SceneQrcode{ + this.qrcode.Action(this.db, []*scene.SceneQRCode{ { QId: opt.Qid, Name: opt.Name, @@ -53,7 +53,7 @@ func (this wechatUseCase) UpdateWeWorkCustomerGroupQrcodeRequest(opt *types.Qrco qrcode.SceneLink = opt.SceneLink qrcode.SafeThresholdValue = opt.SafeThresholdValue qrcode.ExpiryDate = opt.ExpiryDate - this.qrcode.Action(this.db, []*scene.SceneQrcode{qrcode}) + this.qrcode.Action(this.db, []*scene.SceneQRCode{qrcode}) } @@ -67,11 +67,11 @@ func (this wechatUseCase) UpdateWeWorkCustomerGroupQrcodeRequest(opt *types.Qrco // @param opt // @return reply // @return error -func (this *wechatUseCase) FindWeWorkCustomerGroupQrcodePage(option *types.PageOption[types.ListWeWorkGroupQrcodeActiveReqeust]) (reply *types.Page[*scene.SceneQrcode], err error) { +func (this *wechatUseCase) FindWeWorkCustomerGroupQrcodePage(option *types.PageOption[types.ListWeWorkGroupQrcodeActiveReqeust]) (reply *types.Page[*scene.SceneQRCode], err error) { - var code []*scene.SceneQrcode + var code []*scene.SceneQRCode var count int64 - query := this.db.WithContext(this.ctx).Model(scene.SceneQrcode{}).Where(`state < 3`) + query := this.db.WithContext(this.ctx).Model(scene.SceneQRCode{}).Where(`state < 3`) if v := option.Option.Name; v != `` { query.Where("name like ?", "%"+v+"%") @@ -93,7 +93,7 @@ func (this *wechatUseCase) FindWeWorkCustomerGroupQrcodePage(option *types.PageO } _ = query.Find(&code).Error - return &types.Page[*scene.SceneQrcode]{ + return &types.Page[*scene.SceneQRCode]{ List: code, PageIndex: option.PageIndex, PageSize: option.PageSize, @@ -118,14 +118,14 @@ func (this *wechatUseCase) ActionCustomerGroupQrcode(qid string, action int) err return nil } -// UpdateSceneQrcodeLink +// UpdateSceneQRCodeLink // // @Description: // @receiver this // @param qid // @param link // @return error -func (this *wechatUseCase) UpdateSceneQrcodeLink(qid string, link string) error { +func (this *wechatUseCase) UpdateSceneQRCodeLink(qid string, link string) error { column := make(map[string]interface{}) column[`active_qrcode_link`] = link diff --git a/internal/uc/powerx/scrm/wechat/weworkcustomer.go b/internal/uc/powerx/scrm/wechat/weworkcustomer.go index 8f964dd2..47d0c5ec 100644 --- a/internal/uc/powerx/scrm/wechat/weworkcustomer.go +++ b/internal/uc/powerx/scrm/wechat/weworkcustomer.go @@ -23,17 +23,17 @@ import ( // @param ctx // @param opt // @param sync -// @return *types.Page[*customer.WeWorkExternalContacts] +// @return *types.Page[*customer.WeWorkExternalContact] // @return error -func (this wechatUseCase) FindManyWeWorkCustomerPage(ctx context.Context, opt *types.PageOption[FindManyWechatCustomerOption], sync int) (*types.Page[*customer.WeWorkExternalContacts], error) { +func (this wechatUseCase) FindManyWeWorkCustomerPage(ctx context.Context, opt *types.PageOption[FindManyWechatCustomerOption], sync int) (*types.Page[*customer.WeWorkExternalContact], error) { if sync > 0 { this.pullSyncWeWorkCustomerRequest(opt.Option.UserId) } - var customers []*customer.WeWorkExternalContacts + var customers []*customer.WeWorkExternalContact var count int64 - query := this.db.WithContext(ctx).Table(new(customer.WeWorkExternalContacts).TableName() + ` AS a`). + query := this.db.WithContext(ctx).Table(new(customer.WeWorkExternalContact).TableName() + ` AS a`). Joins(fmt.Sprintf(`LEFT JOIN %s AS b ON a.external_user_id=b.external_user_id`, new(customer.WeWorkExternalContactFollow).TableName())) if opt.PageIndex == 0 { @@ -53,7 +53,7 @@ func (this wechatUseCase) FindManyWeWorkCustomerPage(ctx context.Context, opt *t err := query.Preload(`WeWorkExternalContactFollow`).Find(&customers).Error - return &types.Page[*customer.WeWorkExternalContacts]{ + return &types.Page[*customer.WeWorkExternalContact]{ List: customers, PageIndex: opt.PageIndex, PageSize: opt.PageSize, @@ -114,7 +114,7 @@ func (this wechatUseCase) PullListWeWorkCustomerRequest(userID ...string) ([]*re err = this.help.error(`scrm.pull.wework.customer.list.error`, info.ResponseWork) } - contacts := []customer.WeWorkExternalContacts{} + contacts := []customer.WeWorkExternalContact{} follows := []customer.WeWorkExternalContactFollow{} for _, val := range info.ExternalContactList { @@ -140,9 +140,9 @@ func (this wechatUseCase) PullListWeWorkCustomerRequest(userID ...string) ([]*re // // @Description: // @param contact -// @return *customer.WeWorkExternalContacts -func transferExternalContactToModel(contact *models.ExternalContact, userID string) customer.WeWorkExternalContacts { - return customer.WeWorkExternalContacts{ +// @return *customer.WeWorkExternalContact +func transferExternalContactToModel(contact *models.ExternalContact, userID string) customer.WeWorkExternalContact { + return customer.WeWorkExternalContact{ ExternalUserId: contact.ExternalUserID, AppId: ``, @@ -179,7 +179,7 @@ func transferExternalContactFollowToModel(follow *models.FollowUser, externalUse UserId: follow.UserID, Remark: follow.Remark, Description: follow.Description, - Createtime: follow.CreateTime, + CreatedTime: follow.CreateTime, Tags: string(tags), TagIds: strings.Join(follow.TagIDs, `,`), WechatChannels: string(remarkMobiles), diff --git a/internal/uc/powerx/scrm/wechat/weworkuser.go b/internal/uc/powerx/scrm/wechat/weworkuser.go index dbeb15d7..31921b43 100644 --- a/internal/uc/powerx/scrm/wechat/weworkuser.go +++ b/internal/uc/powerx/scrm/wechat/weworkuser.go @@ -1,7 +1,7 @@ package wechat import ( - "PowerX/internal/model/origanzation" + organization2 "PowerX/internal/model/organization" "PowerX/internal/model/powermodel" "PowerX/internal/model/scrm/organization" "PowerX/internal/types" @@ -288,12 +288,12 @@ func (this *wechatUseCase) getWechatUserIDs(ctx context.Context) (ids []string, // @receiver this // @param fromUser // @return toUser -func (this *wechatUseCase) userFromWeWorkSyncToLocal(fromUser []*organization.WeWorkUser) (toUser []*origanzation.User) { +func (this *wechatUseCase) userFromWeWorkSyncToLocal(fromUser []*organization.WeWorkUser) (toUser []*organization2.User) { if fromUser != nil { - password, _ := origanzation.HashPassword(`123456`) + password, _ := organization2.HashPassword(`123456`) for _, user := range fromUser { - toUser = append(toUser, &origanzation.User{ + toUser = append(toUser, &organization2.User{ Account: user.WeWorkUserId, Name: user.Name, NickName: user.Name, diff --git a/swagger/qrcode.json b/swagger/qrcode.json index 8ac9f02d..9030f164 100644 --- a/swagger/qrcode.json +++ b/swagger/qrcode.json @@ -24,7 +24,7 @@ "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/SceneQrcodeActiveReply" + "$ref": "#/definitions/SceneQRCodeActiveReply" } } }, @@ -56,7 +56,7 @@ "status" ] }, - "SceneQrcodeActiveReply": { + "SceneQRCodeActiveReply": { "type": "object", "properties": { "qid": { @@ -121,7 +121,7 @@ "description": " 活码打开次数" } }, - "title": "SceneQrcodeActiveReply", + "title": "SceneQRCodeActiveReply", "required": [ "qid", "name", From 033c8090c90fe3770cefdd772a5a70153ceadf23 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Tue, 8 Oct 2024 23:57:46 +0800 Subject: [PATCH 19/24] feat(migrate): change migrate schema with config schema --- cmd/ctl/database/migrate/powerx.go | 6 +- cmd/ctl/powerxctl.go | 1 + internal/model/crm/market/media.go | 12 ++++ internal/model/crm/market/mgm.go | 61 +++++++++++++++++++ internal/model/crm/market/promotion.go | 17 +++++- internal/model/crm/market/store.go | 14 ++++- internal/model/crm/operation/membership.go | 13 ++++ internal/model/crm/operation/ticket.go | 4 +- internal/model/crm/product/artisan.go | 12 +++- .../product/pivotproducttoproductcategory.go | 17 ++++-- .../crm/product/pivotskutospecificoption.go | 17 ++++-- .../model/crm/product/pivotstoretoartisan.go | 17 ++++-- internal/model/crm/product/pricebook.go | 13 ++++ internal/model/crm/product/pricebookentry.go | 13 ++++ internal/model/crm/product/priceconfig.go | 13 ++++ internal/model/crm/product/product.go | 26 ++++---- internal/model/crm/product/productcategory.go | 12 ++++ internal/model/crm/product/productspecific.go | 29 ++++++++- .../model/crm/product/productstatistics.go | 17 +++++- internal/model/crm/product/sku.go | 13 ++++ internal/model/crm/trade/billingaddress.go | 17 +++++- internal/model/crm/trade/cart.go | 25 ++++++++ internal/model/crm/trade/deliveryaddress.go | 17 +++++- internal/model/crm/trade/inventory.go | 17 +++++- internal/model/crm/trade/logistics.go | 13 ++++ internal/model/crm/trade/order.go | 38 ++++++++++++ internal/model/crm/trade/payment.go | 25 ++++++++ .../crm/trade/pivotordertonventorylog.go | 13 ++++ .../crm/trade/pivotproducttopromotion.go | 13 ++++ internal/model/crm/trade/refund.go | 25 ++++++++ internal/model/crm/trade/shippingaddress.go | 17 +++++- internal/model/crm/trade/token.go | 61 +++++++++++++++++++ internal/model/crm/trade/warehouse.go | 17 +++++- internal/model/custom/artisanspecific.go | 13 ++++ internal/model/datadictionary.go | 37 ++++++++++- internal/model/infoorganization/category.go | 12 ++++ internal/model/infoorganization/label.go | 12 ++++ .../infoorganization/pivotcategorytobject.go | 17 ++++-- .../infoorganization/pivotlabeltobject.go | 17 ++++-- .../model/infoorganization/pivottagtobject.go | 17 ++++-- internal/model/infoorganization/tag.go | 12 ++++ internal/model/media/mediaresource.go | 13 ++++ .../model/media/pivotMediaResourceToObject.go | 17 ++++-- internal/model/operationlog.go | 26 ++++---- internal/model/organization/department.go | 20 ++++-- internal/model/organization/position.go | 16 ++++- internal/model/organization/user.go | 29 ++++++--- internal/model/scene/activeqrcode.go | 20 +++--- internal/model/scrm/app/weworkappgroup.go | 20 +++--- .../model/scrm/customer/weworkcustomer.go | 29 +++++---- .../customer/weworkcustomerExternalFollow.go | 20 +++--- .../scrm/organization/weworkdepartment.go | 21 ++++--- .../model/scrm/organization/weworkuser.go | 20 +++--- internal/model/scrm/resource/department.go | 21 ++++--- internal/model/scrm/tag/weworkgroup.go | 21 ++++--- internal/model/scrm/tag/weworktag.go | 21 ++++--- internal/model/tables.go | 27 ++++++-- internal/model/tag/pivotobjecttotag.go | 17 ++++-- internal/model/tag/tag.go | 11 ++++ internal/model/wechat/miniprogram.go | 16 ++++- internal/model/wechat/offiaccount.go | 16 ++++- internal/uc/powerx/organization.go | 3 +- internal/uc/powerx/scrm/wechat/weworktag.go | 6 +- 63 files changed, 984 insertions(+), 188 deletions(-) diff --git a/cmd/ctl/database/migrate/powerx.go b/cmd/ctl/database/migrate/powerx.go index 3fa5fe2b..eaa8c94e 100644 --- a/cmd/ctl/database/migrate/powerx.go +++ b/cmd/ctl/database/migrate/powerx.go @@ -88,7 +88,7 @@ func (m *PowerMigrator) AutoMigrate() { &customerdomain.Lead{}, &customerdomain.Contact{}, customerdomain.RegisterCode{}, &customerdomain.Customer{}, &operation.Membership{}, ) - _ = m.db.AutoMigrate(&wechat.WechatOACustomer{}, &wechat.WechatMPCustomer{}, &wechat.WeWorkExternalContact{}) + _ = m.db.AutoMigrate(&wechat.WechatOACustomer{}, &wechat.WechatMPCustomer{}) _ = m.db.AutoMigrate( &product.PivotProductToProductCategory{}, ) @@ -96,8 +96,8 @@ func (m *PowerMigrator) AutoMigrate() { _ = m.db.AutoMigrate(&product.Product{}, &product.ProductCategory{}) _ = m.db.AutoMigrate(&product.ProductSpecific{}, &product.SpecificOption{}, &product.ProductStatistics{}) _ = m.db.AutoMigrate(&product.SKU{}, &product.PivotSkuToSpecificOption{}) - _ = m.db.AutoMigrate(&product.PriceBook{}, &product.PriceBookEntry{}, &product.PriceConfig{}) - _ = m.db.AutoMigrate(&market.Store{}, &product.Artisan{}, &product.PivotStoreToArtisan{}) + _ = m.db.AutoMigrate(&product.PriceBookEntry{}, &product.PriceBook{}, &product.PriceConfig{}) + _ = m.db.AutoMigrate(&product.PivotStoreToArtisan{}, &market.Store{}, &product.Artisan{}) // market _ = m.db.AutoMigrate(&market.Media{}) diff --git a/cmd/ctl/powerxctl.go b/cmd/ctl/powerxctl.go index 8904732a..bc64abbb 100644 --- a/cmd/ctl/powerxctl.go +++ b/cmd/ctl/powerxctl.go @@ -125,6 +125,7 @@ func ActionSeed(cCtx *cli.Context) error { var c config.Config conf.MustLoad(configFile, &c) c.EtcDir = filepath.Dir(configFile) + model.PowerXSchema = c.PowerXDatabase.Schema // seed tables s, _ := seed.NewPowerSeeder(&c) diff --git a/internal/model/crm/market/media.go b/internal/model/crm/market/media.go index 40621f6a..ffcec6e2 100644 --- a/internal/model/crm/market/media.go +++ b/internal/model/crm/market/media.go @@ -24,6 +24,18 @@ type Media struct { const MediaUniqueId = powermodel.UniqueId +func (mdl *Media) TableName() string { + return model.PowerXSchema + "." + model.TableNameMedia +} + +func (mdl *Media) GetTableName(needFull bool) string { + tableName := model.TableNameMedia + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const TypeMediaType = "_media_type" const ( diff --git a/internal/model/crm/market/mgm.go b/internal/model/crm/market/mgm.go index 6832be48..d2b3258c 100644 --- a/internal/model/crm/market/mgm.go +++ b/internal/model/crm/market/mgm.go @@ -1,6 +1,7 @@ package market import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) @@ -16,6 +17,18 @@ type MGMRule struct { const MGMRuleUniqueId = powermodel.UniqueId +func (mdl *MGMRule) TableName() string { + return model.PowerXSchema + "." + model.TableNameMGMRule +} + +func (mdl *MGMRule) GetTableName(needFull bool) string { + tableName := model.TableNameMGMRule + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const ( TypeMGMScene = "_mgm_scene" @@ -43,6 +56,18 @@ type CustomerChannel struct { Code string `gorm:"comment:渠道码" json:"code"` } +func (mdl *CustomerChannel) TableName() string { + return model.PowerXSchema + "." + model.TableNameCustomerChannel +} + +func (mdl *CustomerChannel) GetTableName(needFull bool) string { + tableName := model.TableNameCustomerChannel + if needFull { + tableName = mdl.TableName() + } + return tableName +} + // InviteRecord 表示会员邀请记录 type InviteRecord struct { powermodel.PowerModel @@ -53,6 +78,18 @@ type InviteRecord struct { MgmSceneId int `gorm:"comment:MGM场景ID" json:"mgmSceneId"` } +func (mdl *InviteRecord) TableName() string { + return model.PowerXSchema + "." + model.TableNameInviteRecord +} + +func (mdl *InviteRecord) GetTableName(needFull bool) string { + tableName := model.TableNameInviteRecord + if needFull { + tableName = mdl.TableName() + } + return tableName +} + // CommissionRecord 表示分佣记录 type CommissionRecord struct { powermodel.PowerModel @@ -64,6 +101,18 @@ type CommissionRecord struct { OperationId int64 `gorm:"comment:操作对象ID" json:"operationId"` } +func (mdl *CommissionRecord) TableName() string { + return model.PowerXSchema + "." + model.TableNameCommissionRecord +} + +func (mdl *CommissionRecord) GetTableName(needFull bool) string { + tableName := model.TableNameCommissionRecord + if needFull { + tableName = mdl.TableName() + } + return tableName +} + // RewardRecord 表示奖励记录 type RewardRecord struct { powermodel.PowerModel @@ -73,3 +122,15 @@ type RewardRecord struct { OperationType string `gorm:"comment:操作对象类型" json:"operationType"` OperationId int64 `gorm:"comment:操作对象ID" json:"operationId"` } + +func (mdl *RewardRecord) TableName() string { + return model.PowerXSchema + "." + model.TableNameRewardRecord +} + +func (mdl *RewardRecord) GetTableName(needFull bool) string { + tableName := model.TableNameRewardRecord + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/market/promotion.go b/internal/model/crm/market/promotion.go index 1923024b..b72d5dbc 100644 --- a/internal/model/crm/market/promotion.go +++ b/internal/model/crm/market/promotion.go @@ -1,6 +1,9 @@ package market -import "PowerX/internal/model/powermodel" +import ( + "PowerX/internal/model" + "PowerX/internal/model/powermodel" +) type PromotionRule struct { powermodel.PowerModel @@ -8,3 +11,15 @@ type PromotionRule struct { MinPurchase float64 `gorm:"comment:起订购买量" json:"minPurchase"` BonusAmount float64 `gorm:"comment:额外赠送" json:"bonusAmount"` } + +func (mdl *PromotionRule) TableName() string { + return model.PowerXSchema + "." + model.TableNamePromotionRule +} + +func (mdl *PromotionRule) GetTableName(needFull bool) string { + tableName := model.TableNamePromotionRule + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/market/store.go b/internal/model/crm/market/store.go index 931814fa..59e1e239 100644 --- a/internal/model/crm/market/store.go +++ b/internal/model/crm/market/store.go @@ -12,7 +12,7 @@ import ( type Store struct { powermodel.PowerModel - Artisans []*product.Artisan `gorm:"many2many:public.pivot_store_to_artisan;foreignKey:Id;joinForeignKey:StoreId;References:Id;JoinReferences:ArtisanId" json:"priceBooks"` + Artisans []*product.Artisan `gorm:"many2many:pivot_store_to_artisan;foreignKey:Id;joinForeignKey:StoreId;References:Id;JoinReferences:ArtisanId" json:"priceBooks"` PivotDetailImages []*media.PivotMediaResourceToObject `gorm:"polymorphic:Object;polymorphicValue:stores" json:"pivotDetailImages"` CoverImage *media.MediaResource `gorm:"foreignKey:CoverImageId;references:Id" json:"coverImage"` @@ -31,6 +31,18 @@ type Store struct { const StoreUniqueId = powermodel.UniqueId +func (mdl *Store) TableName() string { + return model.PowerXSchema + "." + model.TableNameStore +} + +func (mdl *Store) GetTableName(needFull bool) string { + tableName := model.TableNameStore + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *Store) LoadArtisans(db *gorm.DB, conditions *map[string]interface{}, withClauseAssociations bool) error { mdl.Artisans = []*product.Artisan{} diff --git a/internal/model/crm/operation/membership.go b/internal/model/crm/operation/membership.go index 1ace41cb..26a2830d 100644 --- a/internal/model/crm/operation/membership.go +++ b/internal/model/crm/operation/membership.go @@ -1,6 +1,7 @@ package operation import ( + "PowerX/internal/model" "PowerX/internal/model/crm/customerdomain" "PowerX/internal/model/powermodel" "time" @@ -30,6 +31,18 @@ type Membership struct { const MembershipUniqueId = powermodel.UniqueId +func (mdl *Membership) TableName() string { + return model.PowerXSchema + "." + model.TableNameMembership +} + +func (mdl *Membership) GetTableName(needFull bool) string { + tableName := model.TableNameMembership + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const TypeMembershipType = "_membership_type" const TypeMembershipStatus = "_membership_status" diff --git a/internal/model/crm/operation/ticket.go b/internal/model/crm/operation/ticket.go index 1584d64e..721d7781 100644 --- a/internal/model/crm/operation/ticket.go +++ b/internal/model/crm/operation/ticket.go @@ -17,13 +17,13 @@ type TicketRecord struct { } func (mdl *TicketRecord) TableName() string { - return model.TableNameTicketRecord + return model.PowerXSchema + "." + model.TableNameTicketRecord } func (mdl *TicketRecord) GetTableName(needFull bool) string { tableName := model.TableNameTicketRecord if needFull { - tableName = "public." + tableName + tableName = mdl.TableName() } return tableName } diff --git a/internal/model/crm/product/artisan.go b/internal/model/crm/product/artisan.go index 74eef572..5f6ee67d 100644 --- a/internal/model/crm/product/artisan.go +++ b/internal/model/crm/product/artisan.go @@ -36,7 +36,17 @@ type Artisan struct { const ArtisanUniqueId = powermodel.UniqueId -// artisan level dd type +func (mdl *Artisan) TableName() string { + return model.PowerXSchema + "." + model.TableNameArtisan +} + +func (mdl *Artisan) GetTableName(needFull bool) string { + tableName := model.TableNameArtisan + if needFull { + tableName = mdl.TableName() + } + return tableName +} // artisan level dd type const ArtisanLevelType = "_artisan_level" // artisan level dd items diff --git a/internal/model/crm/product/pivotproducttoproductcategory.go b/internal/model/crm/product/pivotproducttoproductcategory.go index 7c42f2f2..40f822ba 100644 --- a/internal/model/crm/product/pivotproducttoproductcategory.go +++ b/internal/model/crm/product/pivotproducttoproductcategory.go @@ -5,11 +5,6 @@ import ( "PowerX/internal/model/powermodel" ) -// Table Name -func (mdl *PivotProductToProductCategory) TableName() string { - return model.TableNamePivotProductToProductCategory -} - // 数据表结构 type PivotProductToProductCategory struct { powermodel.PowerPivot @@ -18,6 +13,18 @@ type PivotProductToProductCategory struct { ProductCategoryId int64 `gorm:"column:product_category_id; not null;index:idx_product_category_id" json:"productCategoryId"` } +func (mdl *PivotProductToProductCategory) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotProductToProductCategory +} + +func (mdl *PivotProductToProductCategory) GetTableName(needFull bool) string { + tableName := model.TableNamePivotProductToProductCategory + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const PivotProductToCategoryForeignKey = "product_id" const PivotProductToCategoryJoinKey = "product_category_id" diff --git a/internal/model/crm/product/pivotskutospecificoption.go b/internal/model/crm/product/pivotskutospecificoption.go index d9c3eaac..f308f77c 100644 --- a/internal/model/crm/product/pivotskutospecificoption.go +++ b/internal/model/crm/product/pivotskutospecificoption.go @@ -8,11 +8,6 @@ import ( "github.com/ArtisanCloud/PowerLibs/v3/object" ) -// Table Name -func (mdl *PivotSkuToSpecificOption) TableName() string { - return model.TableNamePivotSkuToSpecificOption -} - // 数据表结构 type PivotSkuToSpecificOption struct { powermodel.PowerPivot @@ -27,6 +22,18 @@ type PivotSkuToSpecificOption struct { const PivotPivotSkuToSpecificOptionsUniqueId = "index_unique_id" +func (mdl *PivotSkuToSpecificOption) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotSkuToSpecificOption +} + +func (mdl *PivotSkuToSpecificOption) GetTableName(needFull bool) string { + tableName := model.TableNamePivotSkuToSpecificOption + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *PivotSkuToSpecificOption) GetPivotComposedUniqueID() object.NullString { if mdl.ProductId > 0 && mdl.SkuId > 0 && mdl.SpecificId > 0 && mdl.SpecificOptionId > 0 { strUniqueID := fmt.Sprintf("%d-%d-%d-%d-%d", mdl.ProductId, mdl.SkuId, mdl.SpecificId, mdl.SpecificOptionId, mdl.DeletedAt.Time.Unix()) diff --git a/internal/model/crm/product/pivotstoretoartisan.go b/internal/model/crm/product/pivotstoretoartisan.go index e0e4372f..8cb4b054 100644 --- a/internal/model/crm/product/pivotstoretoartisan.go +++ b/internal/model/crm/product/pivotstoretoartisan.go @@ -5,11 +5,6 @@ import ( "PowerX/internal/model/powermodel" ) -// Table Name -func (mdl *PivotStoreToArtisan) TableName() string { - return model.TableNamePivotStoreToArtisan -} - // 数据表结构 type PivotStoreToArtisan struct { powermodel.PowerPivot @@ -18,6 +13,18 @@ type PivotStoreToArtisan struct { ArtisanId int64 `gorm:"column:artisan_id; not null;index:idx_artisan_id" json:"artisanId"` } +func (mdl *PivotStoreToArtisan) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotStoreToArtisan +} + +func (mdl *PivotStoreToArtisan) GetTableName(needFull bool) string { + tableName := model.TableNamePivotStoreToArtisan + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const PivotStoreToArtisanForeignKey = "store_id" const PivotStoreToArtisanJoinKey = "artisan_id" diff --git a/internal/model/crm/product/pricebook.go b/internal/model/crm/product/pricebook.go index 76bc1245..ef0fe5c6 100644 --- a/internal/model/crm/product/pricebook.go +++ b/internal/model/crm/product/pricebook.go @@ -1,6 +1,7 @@ package product import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) @@ -17,3 +18,15 @@ type PriceBook struct { } const PriceBookUniqueId = powermodel.UniqueId + +func (mdl *PriceBook) TableName() string { + return model.PowerXSchema + "." + model.TableNamePriceBook +} + +func (mdl *PriceBook) GetTableName(needFull bool) string { + tableName := model.TableNamePriceBook + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/product/pricebookentry.go b/internal/model/crm/product/pricebookentry.go index 566b6e52..8dcb6a0b 100644 --- a/internal/model/crm/product/pricebookentry.go +++ b/internal/model/crm/product/pricebookentry.go @@ -1,6 +1,7 @@ package product import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/pkg/securityx" "fmt" @@ -29,6 +30,18 @@ type PriceBookEntry struct { const PriceBookEntryUniqueId = "index_unique_id" +func (mdl *PriceBookEntry) TableName() string { + return model.PowerXSchema + "." + model.TableNamePriceBookEntry +} + +func (mdl *PriceBookEntry) GetTableName(needFull bool) string { + tableName := model.TableNamePriceBookEntry + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *PriceBookEntry) GetComposedUniqueID() object.NullString { if mdl.PriceBookId > 0 && mdl.ProductId > 0 { strUniqueID := fmt.Sprintf("%d-%d-%d-%d", mdl.PriceBookId, mdl.ProductId, mdl.SkuId, mdl.DeletedAt.Time.Unix()) diff --git a/internal/model/crm/product/priceconfig.go b/internal/model/crm/product/priceconfig.go index 4aaed241..d06c8ab0 100644 --- a/internal/model/crm/product/priceconfig.go +++ b/internal/model/crm/product/priceconfig.go @@ -1,6 +1,7 @@ package product import ( + "PowerX/internal/model" "time" ) @@ -14,6 +15,18 @@ type PriceConfig struct { EndDate time.Time `gorm:"column:end_date; comment:活动场景结束时间" json:"endDate"` } +func (mdl *PriceConfig) TableName() string { + return model.PowerXSchema + "." + model.TableNamePriceConfig +} + +func (mdl *PriceConfig) GetTableName(needFull bool) string { + tableName := model.TableNamePriceConfig + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const TypeListPrice = "List_Price" const TypeMember = "Member" const TypeMemberEarlyBird = "Member_Early_Bird" diff --git a/internal/model/crm/product/product.go b/internal/model/crm/product/product.go index d5921421..6967427a 100644 --- a/internal/model/crm/product/product.go +++ b/internal/model/crm/product/product.go @@ -22,17 +22,17 @@ type ProductAttribute struct { type Product struct { SKUs []*SKU `gorm:"foreignKey:ProductId;references:Id" json:"skus"` ProductSpecifics []*ProductSpecific `gorm:"foreignKey:ProductId;references:Id" json:"productSpecifics"` - ProductCategories []*ProductCategory `gorm:"many2many:public.pivot_product_to_product_category;foreignKey:Id;joinForeignKey:ProductId;References:Id;JoinReferences:ProductCategoryId" json:"productCategories"` + ProductCategories []*ProductCategory `gorm:"many2many:pivot_product_to_product_category;foreignKey:Id;joinForeignKey:ProductId;References:Id;JoinReferences:ProductCategoryId" json:"productCategories"` PivotCoverImages []*media.PivotMediaResourceToObject `gorm:"polymorphic:Object;polymorphicValue:products" json:"pivotCoverImages"` PivotDetailImages []*media.PivotMediaResourceToObject `gorm:"polymorphic:Object;polymorphicValue:products" json:"pivotDetailImages"` - PriceBooks []*PriceBook `gorm:"many2many:public.price_book_entries;foreignKey:Id;joinForeignKey:Id;References:Id;JoinReferences:PriceBookId" json:"priceBooks"` + PriceBooks []*PriceBook `gorm:"many2many:price_book_entries;foreignKey:Id;joinForeignKey:Id;References:Id;JoinReferences:PriceBookId" json:"priceBooks"` PriceBookEntries []*PriceBookEntry `gorm:"foreignKey:ProductId;references:Id" json:"priceBookEntries"` PivotSalesChannels []*model.PivotDataDictionaryToObject `gorm:"polymorphic:Object;polymorphicValue:products" json:"pivotSalesChannels"` PivotPromoteChannels []*model.PivotDataDictionaryToObject `gorm:"polymorphic:Object;polymorphicValue:products" json:"pivotPromoteChannels"` ProductCategoryIds []int64 `gorm:"-"` SalesChannelsItemIds []int64 `gorm:"-"` PromoteChannelsItemIds []int64 `gorm:"-"` - //Coupons []*Coupon `gorm:"many2many:public.r_product_to_coupon;foreignKey:Id;joinForeignKey:ProductId;References:Id;JoinReferences:CouponId" json:"coupons"` + //Coupons []*Coupon `gorm:"many2many:r_product_to_coupon;foreignKey:Id;joinForeignKey:ProductId;References:Id;JoinReferences:CouponId" json:"coupons"` powermodel.PowerModel @@ -56,6 +56,18 @@ type Product struct { const ProductUniqueId = powermodel.UniqueId +func (mdl *Product) TableName() string { + return model.PowerXSchema + "." + model.TableNameProduct +} + +func (mdl *Product) GetTableName(needFull bool) string { + tableName := model.TableNameProduct + if needFull { + tableName = mdl.TableName() + } + return tableName +} + // Data Dictionary const TypeProductType = "_product_type" const TypeProductPlan = "_product_plan" @@ -67,14 +79,6 @@ const ProductTypeService = "_service" const ProductPlanOnce = "_once" const ProductPlanPeriod = "_period" -func (mdl *Product) GetTableName(needFull bool) string { - tableName := model.TableNameProduct - if needFull { - tableName = "public." + tableName - } - return tableName -} - func (mdl *Product) GetForeignReferValue() int64 { return mdl.Id } diff --git a/internal/model/crm/product/productcategory.go b/internal/model/crm/product/productcategory.go index 370a04b3..71f09623 100644 --- a/internal/model/crm/product/productcategory.go +++ b/internal/model/crm/product/productcategory.go @@ -26,6 +26,18 @@ type ProductCategory struct { const ProductCategoryUniqueId = powermodel.UniqueId +func (mdl *ProductCategory) TableName() string { + return model.PowerXSchema + "." + model.TableNameProductCategory +} + +func (mdl *ProductCategory) GetTableName(needFull bool) string { + tableName := model.TableNameProductCategory + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *ProductCategory) GetCategoryIds(categories []*ProductCategory) []int64 { uniqueIds := make(map[int64]bool) arrayIds := []int64{} diff --git a/internal/model/crm/product/productspecific.go b/internal/model/crm/product/productspecific.go index 4fc2499c..f0d4a0e5 100644 --- a/internal/model/crm/product/productspecific.go +++ b/internal/model/crm/product/productspecific.go @@ -1,6 +1,9 @@ package product -import "PowerX/internal/model/powermodel" +import ( + "PowerX/internal/model" + "PowerX/internal/model/powermodel" +) type ProductSpecific struct { Options []*SpecificOption `gorm:"foreignKey:ProductSpecificId" json:"options"` @@ -11,6 +14,18 @@ type ProductSpecific struct { Name string `gorm:"comment:规格名称;" json:"name"` } +func (mdl *ProductSpecific) TableName() string { + return model.PowerXSchema + "." + model.TableNameProductSpecific +} + +func (mdl *ProductSpecific) GetTableName(needFull bool) string { + tableName := model.TableNameProductSpecific + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type SpecificOption struct { powermodel.PowerModel @@ -21,3 +36,15 @@ type SpecificOption struct { const ProductSpecificUniqueId = powermodel.UniqueId const SpecificOptionUniqueId = powermodel.UniqueId + +func (mdl *SpecificOption) TableName() string { + return model.PowerXSchema + "." + model.TableNameSpecificOption +} + +func (mdl *SpecificOption) GetTableName(needFull bool) string { + tableName := model.TableNameSpecificOption + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/product/productstatistics.go b/internal/model/crm/product/productstatistics.go index 5e618e93..8f3fcd24 100644 --- a/internal/model/crm/product/productstatistics.go +++ b/internal/model/crm/product/productstatistics.go @@ -1,6 +1,9 @@ package product -import "PowerX/internal/model/powermodel" +import ( + "PowerX/internal/model" + "PowerX/internal/model/powermodel" +) type ProductStatistics struct { powermodel.PowerModel @@ -15,3 +18,15 @@ type ProductStatistics struct { } const ProductStatisticsUniqueId = "product_id" + +func (mdl *ProductStatistics) TableName() string { + return model.PowerXSchema + "." + model.TableNameProductStatistics +} + +func (mdl *ProductStatistics) GetTableName(needFull bool) string { + tableName := model.TableNameProductStatistics + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/product/sku.go b/internal/model/crm/product/sku.go index eb95c12b..85eca595 100644 --- a/internal/model/crm/product/sku.go +++ b/internal/model/crm/product/sku.go @@ -1,6 +1,7 @@ package product import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/pkg/securityx" "fmt" @@ -24,6 +25,18 @@ type SKU struct { const SkuUniqueId = "index_unique_id" +func (mdl *SKU) TableName() string { + return model.PowerXSchema + "." + model.TableNameSKU +} + +func (mdl *SKU) GetTableName(needFull bool) string { + tableName := model.TableNameSKU + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *SKU) GetComposedUniqueID() object.NullString { if len(mdl.OptionIds) > 0 && mdl.ProductId > 0 { strUniqueID := fmt.Sprintf("%d-%s-%d", mdl.ProductId, mdl.OptionIds.String(), mdl.DeletedAt.Time.Unix()) diff --git a/internal/model/crm/trade/billingaddress.go b/internal/model/crm/trade/billingaddress.go index 29a72fa9..4fcd0866 100644 --- a/internal/model/crm/trade/billingaddress.go +++ b/internal/model/crm/trade/billingaddress.go @@ -1,6 +1,9 @@ package trade -import "PowerX/internal/model/powermodel" +import ( + "PowerX/internal/model" + "PowerX/internal/model/powermodel" +) // 订单开票地址 type BillingAddress struct { @@ -19,3 +22,15 @@ type BillingAddress struct { Country string `gorm:"comment:国家" json:"country"` PhoneNumber string `gorm:"comment:联系电话" json:"phoneNumber"` } + +func (mdl *BillingAddress) TableName() string { + return model.PowerXSchema + "." + model.TableNameBillingAddress +} + +func (mdl *BillingAddress) GetTableName(needFull bool) string { + tableName := model.TableNameBillingAddress + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/trade/cart.go b/internal/model/crm/trade/cart.go index d0eca245..d505ef5f 100644 --- a/internal/model/crm/trade/cart.go +++ b/internal/model/crm/trade/cart.go @@ -1,6 +1,7 @@ package trade import ( + "PowerX/internal/model" "PowerX/internal/model/crm/product" "PowerX/internal/model/powermodel" ) @@ -15,6 +16,18 @@ type Cart struct { const CartUniqueId = powermodel.UniqueId +func (mdl *Cart) TableName() string { + return model.PowerXSchema + "." + model.TableNameCart +} + +func (mdl *Cart) GetTableName(needFull bool) string { + tableName := model.TableNameCart + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type CartItem struct { *powermodel.PowerModel @@ -34,6 +47,18 @@ type CartItem struct { ImageURL string `gorm:"comment:商品图片URL" json:"imageUrl"` } +func (mdl *CartItem) TableName() string { + return model.PowerXSchema + "." + model.TableNameCartItem +} + +func (mdl *CartItem) GetTableName(needFull bool) string { + tableName := model.TableNameCartItem + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type CartStatus string const ( diff --git a/internal/model/crm/trade/deliveryaddress.go b/internal/model/crm/trade/deliveryaddress.go index 4e6bbd8a..a5b92508 100644 --- a/internal/model/crm/trade/deliveryaddress.go +++ b/internal/model/crm/trade/deliveryaddress.go @@ -1,6 +1,9 @@ package trade -import "PowerX/internal/model/powermodel" +import ( + "PowerX/internal/model" + "PowerX/internal/model/powermodel" +) // 订单发货地址 type DeliveryAddress struct { @@ -19,3 +22,15 @@ type DeliveryAddress struct { Country string `gorm:"comment:国家" json:"country"` PhoneNumber string `gorm:"comment:联系电话" json:"phoneNumber"` } + +func (mdl *DeliveryAddress) TableName() string { + return model.PowerXSchema + "." + model.TableNameDeliveryAddress +} + +func (mdl *DeliveryAddress) GetTableName(needFull bool) string { + tableName := model.TableNameDeliveryAddress + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/trade/inventory.go b/internal/model/crm/trade/inventory.go index ee62460d..c9106138 100644 --- a/internal/model/crm/trade/inventory.go +++ b/internal/model/crm/trade/inventory.go @@ -1,6 +1,9 @@ package trade -import "PowerX/internal/model/powermodel" +import ( + "PowerX/internal/model" + "PowerX/internal/model/powermodel" +) // 仓库 type Inventory struct { @@ -11,3 +14,15 @@ type Inventory struct { SkuID int64 `gorm:"comment:SkuId" json:"skuID"` Quantity int `gorm:"comment:库存数量" json:"quantity"` } + +func (mdl *Inventory) TableName() string { + return model.PowerXSchema + "." + model.TableNameInventory +} + +func (mdl *Inventory) GetTableName(needFull bool) string { + tableName := model.TableNameInventory + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/trade/logistics.go b/internal/model/crm/trade/logistics.go index 0430f1ad..38c84449 100644 --- a/internal/model/crm/trade/logistics.go +++ b/internal/model/crm/trade/logistics.go @@ -1,6 +1,7 @@ package trade import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "time" ) @@ -16,6 +17,18 @@ type Logistics struct { ActualDeliveryDate time.Time `gorm:"comment:实际送达时间" json:"actualDeliveryDate"` } +func (mdl *Logistics) TableName() string { + return model.PowerXSchema + "." + model.TableNameLogistics +} + +func (mdl *Logistics) GetTableName(needFull bool) string { + tableName := model.TableNameLogistics + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type LogisticsStatus string const ( diff --git a/internal/model/crm/trade/order.go b/internal/model/crm/trade/order.go index c06d6d72..c81ead36 100644 --- a/internal/model/crm/trade/order.go +++ b/internal/model/crm/trade/order.go @@ -1,6 +1,7 @@ package trade import ( + "PowerX/internal/model" "PowerX/internal/model/crm/customerdomain" "PowerX/internal/model/crm/product" "PowerX/internal/model/media" @@ -45,6 +46,19 @@ const TypeOrderType = "_order_type" const TypeOrderStatus = "_order_status" const OrderUniqueId = powermodel.UniqueId + +func (mdl *Order) TableName() string { + return model.PowerXSchema + "." + model.TableNameOrder +} + +func (mdl *Order) GetTableName(needFull bool) string { + tableName := model.TableNameOrder + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const ( OrderStatusPending = "_pending" // 待处理 OrderStatusToBePaid = "_to_be_paid" // 待付款 @@ -100,6 +114,18 @@ type OrderItem struct { Discount float64 `gorm:"type:decimal(10,2); comment:折扣" json:"discount"` } +func (mdl *OrderItem) TableName() string { + return model.PowerXSchema + "." + model.TableNameOrderItem +} + +func (mdl *OrderItem) GetTableName(needFull bool) string { + tableName := model.TableNameOrderItem + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type OrderStatusTransition struct { *powermodel.PowerModel @@ -112,6 +138,18 @@ type OrderStatusTransition struct { TransitionTime time.Time `gorm:"comment:状态转换时间" json:"transitionTime"` } +func (mdl *OrderStatusTransition) TableName() string { + return model.PowerXSchema + "." + model.TableNameOrderStatusTransition +} + +func (mdl *OrderStatusTransition) GetTableName(needFull bool) string { + tableName := model.TableNameOrderStatusTransition + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func GenerateOrderNumber() string { //return "SO" + carbon.Now().Format("YmdHis") + object.QuickRandom(4) diff --git a/internal/model/crm/trade/payment.go b/internal/model/crm/trade/payment.go index ee525989..3a8ce916 100644 --- a/internal/model/crm/trade/payment.go +++ b/internal/model/crm/trade/payment.go @@ -1,6 +1,7 @@ package trade import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "github.com/ArtisanCloud/PowerLibs/v3/object" "github.com/golang-module/carbon/v2" @@ -23,6 +24,18 @@ type Payment struct { Status int `gorm:"comment:支付单状态" json:"status"` } +func (mdl *Payment) TableName() string { + return model.PowerXSchema + "." + model.TableNamePayment +} + +func (mdl *Payment) GetTableName(needFull bool) string { + tableName := model.TableNamePayment + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const TypePaymentType = "_payment_type" const TypePaymentStatus = "_payment_status" @@ -62,6 +75,18 @@ type PaymentItem struct { const PaymentUniqueId = powermodel.UniqueId +func (mdl *PaymentItem) TableName() string { + return model.PowerXSchema + "." + model.TableNamePaymentItem +} + +func (mdl *PaymentItem) GetTableName(needFull bool) string { + tableName := model.TableNamePaymentItem + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func GeneratePaymentNumber() string { return "PO" + carbon.Now().Format("YmdHis") + object.QuickRandom(6) } diff --git a/internal/model/crm/trade/pivotordertonventorylog.go b/internal/model/crm/trade/pivotordertonventorylog.go index d3fed746..51e81eb4 100644 --- a/internal/model/crm/trade/pivotordertonventorylog.go +++ b/internal/model/crm/trade/pivotordertonventorylog.go @@ -1,6 +1,7 @@ package trade import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) @@ -10,3 +11,15 @@ type PivotProductToPromotion struct { PromotionRuleId int64 `gorm:"comment:促销规则d; not null;index:idx_promotion_rule_id" json:"promotionRuleId"` ProductId int64 `gorm:"comment:商品Id; not null;index:idx_product_id" json:"productId"` } + +func (mdl *PivotProductToPromotion) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotProductToPromotion +} + +func (mdl *PivotProductToPromotion) GetTableName(needFull bool) string { + tableName := model.TableNamePivotProductToPromotion + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/trade/pivotproducttopromotion.go b/internal/model/crm/trade/pivotproducttopromotion.go index f3e15917..b7261c0e 100644 --- a/internal/model/crm/trade/pivotproducttopromotion.go +++ b/internal/model/crm/trade/pivotproducttopromotion.go @@ -1,6 +1,7 @@ package trade import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "time" ) @@ -18,6 +19,18 @@ type PivotOrderToInventoryLog struct { StockQuantityAfter int `gorm:"comment:回滚后的库存数量" json:"stockQuantityAfter"` } +func (mdl *PivotOrderToInventoryLog) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotOrderToInventoryLog +} + +func (mdl *PivotOrderToInventoryLog) GetTableName(needFull bool) string { + tableName := model.TableNamePivotOrderToInventoryLog + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type ActionType int const ( diff --git a/internal/model/crm/trade/refund.go b/internal/model/crm/trade/refund.go index c814b00a..5c31d7ee 100644 --- a/internal/model/crm/trade/refund.go +++ b/internal/model/crm/trade/refund.go @@ -1,6 +1,7 @@ package trade import ( + "PowerX/internal/model" "PowerX/internal/model/crm/customerdomain" "PowerX/internal/model/powermodel" "time" @@ -24,6 +25,18 @@ type RefundOrder struct { RefundDate time.Time `gorm:"comment:退款日期" json:"refundDate"` } +func (mdl *RefundOrder) TableName() string { + return model.PowerXSchema + "." + model.TableNameRefundOrder +} + +func (mdl *RefundOrder) GetTableName(needFull bool) string { + tableName := model.TableNameRefundOrder + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type RefundStatus int const RefundOrderUniqueId = powermodel.UniqueId @@ -48,3 +61,15 @@ type RefundOrderItem struct { RefundAmount float64 `gorm:"type:decimal(10,2); comment:退款金额" json:"refundAmount"` RefundDate time.Time `gorm:"comment:退款日期" json:"refundDate"` } + +func (mdl *RefundOrderItem) TableName() string { + return model.PowerXSchema + "." + model.TableNameRefundOrderItem +} + +func (mdl *RefundOrderItem) GetTableName(needFull bool) string { + tableName := model.TableNameRefundOrderItem + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/crm/trade/shippingaddress.go b/internal/model/crm/trade/shippingaddress.go index f55ef41a..9da2e670 100644 --- a/internal/model/crm/trade/shippingaddress.go +++ b/internal/model/crm/trade/shippingaddress.go @@ -1,6 +1,9 @@ package trade -import "PowerX/internal/model/powermodel" +import ( + "PowerX/internal/model" + "PowerX/internal/model/powermodel" +) // 用户发货地址 type ShippingAddress struct { @@ -22,6 +25,18 @@ type ShippingAddress struct { const ShippingAddressUniqueId = powermodel.UniqueId +func (mdl *ShippingAddress) TableName() string { + return model.PowerXSchema + "." + model.TableNameShippingAddress +} + +func (mdl *ShippingAddress) GetTableName(needFull bool) string { + tableName := model.TableNameShippingAddress + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *ShippingAddress) MakeDeliveryAddress() *DeliveryAddress { return &DeliveryAddress{ CustomerId: mdl.CustomerId, diff --git a/internal/model/crm/trade/token.go b/internal/model/crm/trade/token.go index 6e1e4894..def1de6f 100644 --- a/internal/model/crm/trade/token.go +++ b/internal/model/crm/trade/token.go @@ -1,6 +1,7 @@ package trade import ( + "PowerX/internal/model" "PowerX/internal/model/crm/customerdomain" "PowerX/internal/model/powermodel" ) @@ -12,6 +13,18 @@ type TokenExchangeRatio struct { Ratio float64 `gorm:"comment:兑换比例" json:"ratio"` } +func (mdl *TokenExchangeRatio) TableName() string { + return model.PowerXSchema + "." + model.TableNameTokenExchangeRatio +} + +func (mdl *TokenExchangeRatio) GetTableName(needFull bool) string { + tableName := model.TableNameTokenExchangeRatio + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type TokenBalance struct { powermodel.PowerModel @@ -25,6 +38,18 @@ type TokenBalance struct { const TokenBalanceUniqueId = powermodel.UniqueId const TokenExchangeRecordId = powermodel.UniqueId +func (mdl *TokenBalance) TableName() string { + return model.PowerXSchema + "." + model.TableNameTokenBalance +} + +func (mdl *TokenBalance) GetTableName(needFull bool) string { + tableName := model.TableNameTokenBalance + if needFull { + tableName = mdl.TableName() + } + return tableName +} + type TokenExchangeRecord struct { powermodel.PowerModel @@ -38,6 +63,18 @@ type TokenExchangeRecord struct { ExchangeRate float64 `gorm:"comment:兑换比例" json:"exchangeRate"` } +func (mdl *TokenExchangeRecord) TableName() string { + return model.PowerXSchema + "." + model.TableNameTokenExchangeRecord +} + +func (mdl *TokenExchangeRecord) GetTableName(needFull bool) string { + tableName := model.TableNameTokenExchangeRecord + if needFull { + tableName = mdl.TableName() + } + return tableName +} + // TokenCategory 代表代币的种类 const TypeTokenCategory = "_token_category" @@ -62,6 +99,18 @@ type TokenReservation struct { IsConfirmed bool `gorm:"comment:是否已确认" json:"isConfirmed"` } +func (mdl *TokenReservation) TableName() string { + return model.PowerXSchema + "." + model.TableNameTokenReservation +} + +func (mdl *TokenReservation) GetTableName(needFull bool) string { + tableName := model.TableNameTokenReservation + if needFull { + tableName = mdl.TableName() + } + return tableName +} + // 定义交易记录对象 type TokenTransaction struct { powermodel.PowerModel @@ -73,6 +122,18 @@ type TokenTransaction struct { SourceID int64 `gorm:"column:source_id; not null;index:idx_src_id;comment:对象Id" json:"sourceId"` } +func (mdl *TokenTransaction) TableName() string { + return model.PowerXSchema + "." + model.TableNameTokenTransaction +} + +func (mdl *TokenTransaction) GetTableName(needFull bool) string { + tableName := model.TableNameTokenTransaction + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const TokenTransactionId = powermodel.UniqueId const TypeTokenTransactionType = "_token_transaction_type" diff --git a/internal/model/crm/trade/warehouse.go b/internal/model/crm/trade/warehouse.go index 41cd8d4b..4d9908be 100644 --- a/internal/model/crm/trade/warehouse.go +++ b/internal/model/crm/trade/warehouse.go @@ -1,6 +1,9 @@ package trade -import "PowerX/internal/model/powermodel" +import ( + "PowerX/internal/model" + "PowerX/internal/model/powermodel" +) // 仓库 type Warehouse struct { @@ -16,3 +19,15 @@ type Warehouse struct { ContactPhone string `gorm:"comment:联系电话" json:"contactPhone"` IsActive bool `gorm:"comment:是否活动" json:"isActive"` } + +func (mdl *Warehouse) TableName() string { + return model.PowerXSchema + "." + model.TableNameWarehouse +} + +func (mdl *Warehouse) GetTableName(needFull bool) string { + tableName := model.TableNameWarehouse + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/custom/artisanspecific.go b/internal/model/custom/artisanspecific.go index 8cc94a99..985ef58c 100644 --- a/internal/model/custom/artisanspecific.go +++ b/internal/model/custom/artisanspecific.go @@ -1,6 +1,7 @@ package custom import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" ) @@ -11,3 +12,15 @@ type ArtisanSpecific struct { } const ArtisanSpecificUniqueId = powermodel.UniqueId + +func (mdl *ArtisanSpecific) TableName() string { + return model.PowerXSchema + "." + model.TableNameArtisanSpecific +} + +func (mdl *ArtisanSpecific) GetTableName(needFull bool) string { + tableName := model.TableNameArtisanSpecific + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/datadictionary.go b/internal/model/datadictionary.go index 8deb7bff..90cd5690 100644 --- a/internal/model/datadictionary.go +++ b/internal/model/datadictionary.go @@ -53,6 +53,18 @@ type DataDictionaryItem struct { const DataDictionaryItemUniqueId = powermodel.UniqueId +func (mdl *DataDictionaryItem) TableName() string { + return PowerXSchema + "." + TableNameDataDictionaryItem +} + +func (mdl *DataDictionaryItem) GetTableName(needFull bool) string { + tableName := TableNameDataDictionaryItem + if needFull { + tableName = mdl.TableName() + } + return tableName +} + // 数据字典类型,聚合数据字典 type DataDictionaryType struct { powermodel.PowerModel @@ -66,9 +78,16 @@ type DataDictionaryType struct { const DataDictionaryTypeUniqueId = powermodel.UniqueId -// Table Name -func (mdl *PivotDataDictionaryToObject) TableName() string { - return TableNamePivotDataDictionaryToObject +func (mdl *DataDictionaryType) TableName() string { + return PowerXSchema + "." + TableNameDataDictionaryType +} + +func (mdl *DataDictionaryType) GetTableName(needFull bool) string { + tableName := TableNameDataDictionaryType + if needFull { + tableName = mdl.TableName() + } + return tableName } // 数据表结构 @@ -87,6 +106,18 @@ type PivotDataDictionaryToObject struct { const PivotDataDictionaryToObjectOwnerKey = "object_type" const PivotDataDictionaryToObjectForeignKey = "object_id" +func (mdl *PivotDataDictionaryToObject) TableName() string { + return PowerXSchema + "." + TableNamePivotDataDictionaryToObject +} + +func (mdl *PivotDataDictionaryToObject) GetTableName(needFull bool) string { + tableName := TableNamePivotDataDictionaryToObject + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *PivotDataDictionaryToObject) GetOwnerKey() string { // 因为是morphy类型,所以外键是Owner return PivotDataDictionaryToObjectOwnerKey diff --git a/internal/model/infoorganization/category.go b/internal/model/infoorganization/category.go index 41add634..3661b408 100644 --- a/internal/model/infoorganization/category.go +++ b/internal/model/infoorganization/category.go @@ -26,6 +26,18 @@ type Category struct { const CategoryUniqueId = powermodel.UniqueId +func (mdl *Category) TableName() string { + return model.PowerXSchema + "." + model.TableNameCategory +} + +func (mdl *Category) GetTableName(needFull bool) string { + tableName := model.TableNameCategory + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *Category) GetCategoryIds(categories []*Category) []int64 { uniqueIds := make(map[int64]bool) arrayIds := []int64{} diff --git a/internal/model/infoorganization/label.go b/internal/model/infoorganization/label.go index c0e323c2..0c72c777 100644 --- a/internal/model/infoorganization/label.go +++ b/internal/model/infoorganization/label.go @@ -26,6 +26,18 @@ type Label struct { const LabelUniqueId = powermodel.UniqueId +func (mdl *Label) TableName() string { + return model.PowerXSchema + "." + model.TableNameLabel +} + +func (mdl *Label) GetTableName(needFull bool) string { + tableName := model.TableNameLabel + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func GetLabelIds(categories []*Label) []int64 { uniqueIds := make(map[int64]bool) arrayIds := []int64{} diff --git a/internal/model/infoorganization/pivotcategorytobject.go b/internal/model/infoorganization/pivotcategorytobject.go index 74e48bca..c797f244 100644 --- a/internal/model/infoorganization/pivotcategorytobject.go +++ b/internal/model/infoorganization/pivotcategorytobject.go @@ -9,11 +9,6 @@ import ( "gorm.io/gorm" ) -// Table Name -func (mdl *PivotCategoryToObject) TableName() string { - return model.TableNamePivotCategoryToObject -} - // Pivot表 type PivotCategoryToObject struct { powermodel.PowerPivot @@ -34,6 +29,18 @@ const PivotCategoryToObjectOwnerKey = "object_type" const PivotCategoryToObjectForeignKey = "object_id" const PivotCategoryToObjectJoinKey = "category_id" +func (mdl *PivotCategoryToObject) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotCategoryToObject +} + +func (mdl *PivotCategoryToObject) GetTableName(needFull bool) string { + tableName := model.TableNamePivotCategoryToObject + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *PivotCategoryToObject) GetOwnerKey() string { // 因为是morphy类型,所以外键是Owner return PivotCategoryToObjectOwnerKey diff --git a/internal/model/infoorganization/pivotlabeltobject.go b/internal/model/infoorganization/pivotlabeltobject.go index 9bbf6f79..8135b06d 100644 --- a/internal/model/infoorganization/pivotlabeltobject.go +++ b/internal/model/infoorganization/pivotlabeltobject.go @@ -9,11 +9,6 @@ import ( "gorm.io/gorm" ) -// Table Name -func (mdl *PivotLabelToObject) TableName() string { - return model.TableNamePivotLabelToObject -} - // Pivot表 type PivotLabelToObject struct { powermodel.PowerPivot @@ -32,6 +27,18 @@ const PivotLabelToObjectOwnerKey = "object_type" const PivotLabelToObjectForeignKey = "object_id" const PivotLabelToObjectJoinKey = "label_id" +func (mdl *PivotLabelToObject) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotLabelToObject +} + +func (mdl *PivotLabelToObject) GetTableName(needFull bool) string { + tableName := model.TableNamePivotLabelToObject + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *PivotLabelToObject) GetOwnerKey() string { // 因为是morphy类型,所以外键是Owner return PivotLabelToObjectOwnerKey diff --git a/internal/model/infoorganization/pivottagtobject.go b/internal/model/infoorganization/pivottagtobject.go index 872eb7ca..4ddf68e7 100644 --- a/internal/model/infoorganization/pivottagtobject.go +++ b/internal/model/infoorganization/pivottagtobject.go @@ -9,11 +9,6 @@ import ( "gorm.io/gorm" ) -// Table Name -func (mdl *PivotTagToObject) TableName() string { - return model.TableNamePivotTagToObject -} - // Pivot表 type PivotTagToObject struct { powermodel.PowerPivot @@ -32,6 +27,18 @@ const PivotTagToObjectOwnerKey = "object_type" const PivotTagToObjectForeignKey = "object_id" const PivotTagToObjectJoinKey = "tag_id" +func (mdl *PivotTagToObject) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotTagToObject +} + +func (mdl *PivotTagToObject) GetTableName(needFull bool) string { + tableName := model.TableNamePivotTagToObject + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *PivotTagToObject) GetOwnerKey() string { // 因为是morphy类型,所以外键是Owner return PivotTagToObjectOwnerKey diff --git a/internal/model/infoorganization/tag.go b/internal/model/infoorganization/tag.go index 07f6b927..7a55fdc6 100644 --- a/internal/model/infoorganization/tag.go +++ b/internal/model/infoorganization/tag.go @@ -26,6 +26,18 @@ type Tag struct { const TagUniqueId = powermodel.UniqueId +func (mdl *Tag) TableName() string { + return model.PowerXSchema + "." + model.TableNameTag +} + +func (mdl *Tag) GetTableName(needFull bool) string { + tableName := model.TableNameTag + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func GetTagIds(categories []*Tag) []int64 { uniqueIds := make(map[int64]bool) arrayIds := []int64{} diff --git a/internal/model/media/mediaresource.go b/internal/model/media/mediaresource.go index bb4ab038..146422a5 100644 --- a/internal/model/media/mediaresource.go +++ b/internal/model/media/mediaresource.go @@ -1,6 +1,7 @@ package media import ( + "PowerX/internal/model" "PowerX/internal/model/powermodel" "PowerX/internal/types" ) @@ -23,6 +24,18 @@ type MediaResource struct { type MediaSet struct { } +func (mdl *MediaResource) TableName() string { + return model.PowerXSchema + "." + model.TableNameMediaResource +} + +func (mdl *MediaResource) GetTableName(needFull bool) string { + tableName := model.TableNameMediaResource + if needFull { + tableName = mdl.TableName() + } + return tableName +} + const MediaUsageCover = "_cover" const MediaUsageDetail = "_detail" diff --git a/internal/model/media/pivotMediaResourceToObject.go b/internal/model/media/pivotMediaResourceToObject.go index 7ddb6567..94f9c522 100644 --- a/internal/model/media/pivotMediaResourceToObject.go +++ b/internal/model/media/pivotMediaResourceToObject.go @@ -9,11 +9,6 @@ import ( "gorm.io/gorm" ) -// Table Name -func (mdl *PivotMediaResourceToObject) TableName() string { - return model.TableNamePivotMediaResourceToObject -} - // Pivot表 type PivotMediaResourceToObject struct { powermodel.PowerPivot @@ -36,6 +31,18 @@ const PivotMediaResourceToObjectOwnerKey = "object_type" const PivotMediaResourceToObjectForeignKey = "object_id" const PivotMediaResourceToObjectJoinKey = "media_id" +func (mdl *PivotMediaResourceToObject) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotMediaResourceToObject +} + +func (mdl *PivotMediaResourceToObject) GetTableName(needFull bool) string { + tableName := model.TableNamePivotMediaResourceToObject + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *PivotMediaResourceToObject) GetOwnerKey() string { // 因为是morphy类型,所以外键是Owner return PivotMediaResourceToObjectOwnerKey diff --git a/internal/model/operationlog.go b/internal/model/operationlog.go index f2e4be9e..48a3e8ec 100644 --- a/internal/model/operationlog.go +++ b/internal/model/operationlog.go @@ -14,11 +14,6 @@ const OperationResultSuccess = 1 const OperationResultFailed = 2 const OperationResultCancel = 3 -// TableName overrides the table name used by price_book to `profiles` -func (mdl *PowerOperationLog) TableName() string { - return mdl.GetTableName(true) -} - // PowerOperationLog 数据表结构 type PowerOperationLog struct { *powermodel.PowerModel @@ -37,6 +32,18 @@ type PowerOperationLog struct { const OperationLogUniqueId = powermodel.UniqueId +func (mdl *PowerOperationLog) TableName() string { + return PowerXSchema + "." + TableNamePowerOperationLog +} + +func (mdl *PowerOperationLog) GetTableName(needFull bool) string { + tableName := TableNamePowerOperationLog + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func NewPowerOperationLog(mapObject *object.Collection) *PowerOperationLog { if mapObject == nil { @@ -58,15 +65,6 @@ func NewPowerOperationLog(mapObject *object.Collection) *PowerOperationLog { } } -// 获取当前 Model 的数据库表名称 -func (mdl *PowerOperationLog) GetTableName(needFull bool) string { - tableName := TableNameOperationLog - if needFull { - tableName = "public.ac_" + tableName - } - return tableName -} - func (mdl *PowerOperationLog) SaveOps(db *gorm.DB, operatorName string, operator powermodel.ModelInterface, module int16, operate string, event int8, diff --git a/internal/model/organization/department.go b/internal/model/organization/department.go index 06ed72fd..eaff941c 100644 --- a/internal/model/organization/department.go +++ b/internal/model/organization/department.go @@ -2,12 +2,14 @@ package organization import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type Department struct { - model.Model + powermodel.PowerModel + PDep *Department `gorm:"foreignKey:PId"` Leader *User `gorm:"foreignKey:LeaderId"` Ancestors []*Department `gorm:"many2many:department_ancestors;"` @@ -23,13 +25,21 @@ type Department struct { IsWeWorkArchitecture bool `gorm:"comment:是否启用企微架构;column:is_we_work_architecture" json:"is_we_work_architecture"` } -func (e *Department) TableName() string { - return `departments` +func (mdl *Department) TableName() string { + return model.PowerXSchema + "." + model.TableNameDepartment +} + +func (mdl *Department) GetTableName(needFull bool) string { + tableName := model.TableNameDepartment + if needFull { + tableName = mdl.TableName() + } + return tableName } -func (e *Department) Action(db *gorm.DB, departments []*Department) { +func (mdl *Department) Action(db *gorm.DB, departments []*Department) { - err := db.Table(e.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "we_work_user_id"}}, UpdateAll: true}).CreateInBatches(&departments, 100).Error + err := db.Table(mdl.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "we_work_user_id"}}, UpdateAll: true}).CreateInBatches(&departments, 100).Error if err != nil { panic(err) } diff --git a/internal/model/organization/position.go b/internal/model/organization/position.go index 2d29e1c9..b23711e9 100644 --- a/internal/model/organization/position.go +++ b/internal/model/organization/position.go @@ -3,13 +3,27 @@ package organization import ( "PowerX/internal/model" "PowerX/internal/model/permission" + "PowerX/internal/model/powermodel" ) // Position 职位 type Position struct { - model.Model + powermodel.PowerModel + Name string `gorm:"comment:职位名称;column:name" json:"name"` Desc string `gorm:"comment:描述;column:desc" json:"desc"` Roles []*permission.AdminRole `gorm:"many2many:position_roles;foreignKey:Id;References:RoleCode" json:"roles"` Level string `gorm:"comment:职级;column:level" json:"level"` } + +func (mdl *Position) TableName() string { + return model.PowerXSchema + "." + model.TableNamePosition +} + +func (mdl *Position) GetTableName(needFull bool) string { + tableName := model.TableNamePosition + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/model/organization/user.go b/internal/model/organization/user.go index ce3be753..2a9773cd 100644 --- a/internal/model/organization/user.go +++ b/internal/model/organization/user.go @@ -2,6 +2,7 @@ package organization import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "github.com/pkg/errors" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" @@ -9,7 +10,7 @@ import ( ) type User struct { - model.Model + powermodel.PowerModel UUID string `json:"comment:唯一标识;column:uuid;unique;type:uuid" json:"uuid"` Account string `gorm:"comment:账户;column:account unique;type:varchar" json:"account"` @@ -34,9 +35,21 @@ type User struct { WeWorkUserId string `gorm:"comment:微信账户;column:we_work_user_id;type:varchar" json:"we_work_user_id"` } -func (e *User) HashPassword() (err error) { - if e.Password != "" { - e.Password, err = HashPassword(e.Password) +func (mdl *User) TableName() string { + return model.PowerXSchema + "." + model.TableNameCart +} + +func (mdl *User) GetTableName(needFull bool) string { + tableName := model.TableNameCart + if needFull { + tableName = mdl.TableName() + } + return tableName +} + +func (mdl *User) HashPassword() (err error) { + if mdl.Password != "" { + mdl.Password, err = HashPassword(mdl.Password) } return nil } @@ -69,13 +82,9 @@ func VerifyPassword(hashedPwd string, pwd string) bool { return err == nil } -func (e *User) TableName() string { - return `users` -} - -func (e *User) Action(db *gorm.DB, users []*User) { +func (mdl *User) Action(db *gorm.DB, users []*User) { - err := db.Table(e.TableName()). + err := db.Table(mdl.TableName()). //Debug(). Clauses( clause.OnConflict{Columns: []clause.Column{{Name: `we_work_user_id`}}, diff --git a/internal/model/scene/activeqrcode.go b/internal/model/scene/activeqrcode.go index c1a40939..a067c82a 100644 --- a/internal/model/scene/activeqrcode.go +++ b/internal/model/scene/activeqrcode.go @@ -2,12 +2,13 @@ package scene import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type SceneQRCode struct { - model.Model + powermodel.PowerModel QId string `gorm:"comment:唯一标识;unique;column:qid" json:"qid"` Name string `gorm:"comment:活码名称;column:name" json:"name"` Desc string `gorm:"comment:描述;column:desc" json:"desc"` @@ -26,13 +27,16 @@ type SceneQRCode struct { State int `gorm:"comment:状态1:启用 2:禁用 3:删除;column:state" json:"state"` } -// Table -// -// @Description: -// @receiver e -// @return string -func (e SceneQRCode) TableName() string { - return model.TableNameSceneQRCode +func (mdl *SceneQRCode) TableName() string { + return model.PowerXSchema + "." + model.TableNameSceneQRCode +} + +func (mdl *SceneQRCode) GetTableName(needFull bool) string { + tableName := model.TableNameSceneQRCode + if needFull { + tableName = mdl.TableName() + } + return tableName } // Query diff --git a/internal/model/scrm/app/weworkappgroup.go b/internal/model/scrm/app/weworkappgroup.go index 0639063d..645f3ca1 100644 --- a/internal/model/scrm/app/weworkappgroup.go +++ b/internal/model/scrm/app/weworkappgroup.go @@ -2,12 +2,13 @@ package app import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type WeWorkAppGroup struct { - model.Model + powermodel.PowerModel Name string `gorm:"comment:群名称;column:name" json:"name"` Owner string `gorm:"comment:群主;column:owner" json:"owner"` @@ -15,13 +16,16 @@ type WeWorkAppGroup struct { ChatID string `gorm:"comment:群ID;unique"` } -// Table -// -// @Description: -// @receiver e -// @return string -func (e WeWorkAppGroup) TableName() string { - return model.WeWorkAppGroup +func (mdl *WeWorkAppGroup) TableName() string { + return model.PowerXSchema + "." + model.TableNameWeWorkAppGroup +} + +func (mdl *WeWorkAppGroup) GetTableName(needFull bool) string { + tableName := model.TableNameWeWorkAppGroup + if needFull { + tableName = mdl.TableName() + } + return tableName } type ( diff --git a/internal/model/scrm/customer/weworkcustomer.go b/internal/model/scrm/customer/weworkcustomer.go index c9e483bc..27c6240e 100644 --- a/internal/model/scrm/customer/weworkcustomer.go +++ b/internal/model/scrm/customer/weworkcustomer.go @@ -2,12 +2,14 @@ package customer import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type WeWorkExternalContact struct { - model.Model + powermodel.PowerModel + WeWorkExternalContactFollow WeWorkExternalContactFollow `gorm:"foreignKey:ExternalUserId;references:external_user_id" json:"WeWorkExternalContactFollow"` ExternalUserId string `gorm:"comment:客户ID;unique;not null;" json:"externalUserId"` AppId string `gorm:"comment:应用ID;index:idx_app_id;column:app_id" json:"appId"` @@ -29,13 +31,16 @@ type WeWorkExternalContact struct { Active bool `gorm:"active" json:"active"` } -// Table -// -// @Description: -// @receiver e -// @return string -func (e WeWorkExternalContact) TableName() string { - return model.TableNameWeWorkExternalContact +func (mdl *WeWorkExternalContact) TableName() string { + return model.PowerXSchema + "." + model.TableNameWeWorkExternalContact +} + +func (mdl *WeWorkExternalContact) GetTableName(needFull bool) string { + tableName := model.TableNameWeWorkExternalContact + if needFull { + tableName = mdl.TableName() + } + return tableName } // Query @@ -44,9 +49,9 @@ func (e WeWorkExternalContact) TableName() string { // @receiver e // @param db // @return contacts -func (e WeWorkExternalContact) Query(db *gorm.DB) (contacts []*WeWorkExternalContact) { +func (mdl *WeWorkExternalContact) Query(db *gorm.DB) (contacts []*WeWorkExternalContact) { - err := db.Model(e).Find(&contacts).Error + err := db.Model(mdl).Find(&contacts).Error if err != nil { panic(err) } @@ -60,9 +65,9 @@ func (e WeWorkExternalContact) Query(db *gorm.DB) (contacts []*WeWorkExternalCon // @receiver e // @param db // @param contacts -func (e *WeWorkExternalContact) Action(db *gorm.DB, contacts []*WeWorkExternalContact) { +func (mdl *WeWorkExternalContact) Action(db *gorm.DB, contacts []*WeWorkExternalContact) { - err := db.Table(e.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "external_user_id"}}, UpdateAll: true}).CreateInBatches(&contacts, 100).Error + err := db.Table(mdl.TableName()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "external_user_id"}}, UpdateAll: true}).CreateInBatches(&contacts, 100).Error if err != nil { panic(err) } diff --git a/internal/model/scrm/customer/weworkcustomerExternalFollow.go b/internal/model/scrm/customer/weworkcustomerExternalFollow.go index 7e654f26..ed1b80fb 100644 --- a/internal/model/scrm/customer/weworkcustomerExternalFollow.go +++ b/internal/model/scrm/customer/weworkcustomerExternalFollow.go @@ -2,12 +2,13 @@ package customer import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type WeWorkExternalContactFollow struct { - model.Model + powermodel.PowerModel ExternalUserId string `gorm:"comment:客户ID;column:external_user_id;unique" json:"external_user_id"` UserId string `gorm:"comment:员工ID;column:user_id" json:"user_id"` @@ -24,13 +25,16 @@ type WeWorkExternalContactFollow struct { State string `gorm:"comment:State;column:state" json:"state"` } -// Table -// -// @Description: -// @receiver e -// @return string -func (e WeWorkExternalContactFollow) TableName() string { - return model.TableNameWeWorkExternalContactFollow +func (mdl *WeWorkExternalContactFollow) TableName() string { + return model.PowerXSchema + "." + model.TableNameWeWorkExternalContactFollow +} + +func (mdl *WeWorkExternalContactFollow) GetTableName(needFull bool) string { + tableName := model.TableNameWeWorkExternalContactFollow + if needFull { + tableName = mdl.TableName() + } + return tableName } // Query diff --git a/internal/model/scrm/organization/weworkdepartment.go b/internal/model/scrm/organization/weworkdepartment.go index c6152584..0361cf4b 100644 --- a/internal/model/scrm/organization/weworkdepartment.go +++ b/internal/model/scrm/organization/weworkdepartment.go @@ -2,12 +2,14 @@ package organization import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type WeWorkDepartment struct { - model.Model + powermodel.PowerModel + // Leader *WeWorkUser `gorm:"foreignKey:LeaderId"` WeWorkDepId int `gorm:"comment:部门ID;column:we_work_dep_id;unique" json:"we_work_dep_id"` Name string `gorm:"comment:部门名称;column:name" json:"name"` @@ -18,13 +20,16 @@ type WeWorkDepartment struct { RefDepartmentId int64 `gorm:"comment:-;column:ref_department_id" json:"ref_department_id"` } -// Table -// -// @Description: -// @receiver e -// @return string -func (e WeWorkDepartment) TableName() string { - return model.TableNameWeWorkDepartment +func (mdl *WeWorkDepartment) TableName() string { + return model.PowerXSchema + "." + model.TableNameWeWorkDepartment +} + +func (mdl *WeWorkDepartment) GetTableName(needFull bool) string { + tableName := model.TableNameWeWorkDepartment + if needFull { + tableName = mdl.TableName() + } + return tableName } // Query diff --git a/internal/model/scrm/organization/weworkuser.go b/internal/model/scrm/organization/weworkuser.go index c49aebab..e4b94465 100644 --- a/internal/model/scrm/organization/weworkuser.go +++ b/internal/model/scrm/organization/weworkuser.go @@ -2,12 +2,13 @@ package organization import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type WeWorkUser struct { - model.Model + powermodel.PowerModel WeWorkUserId string `gorm:"comment:员工ID;column:we_work_user_id;unique" json:"we_work_user_id"` Name string `gorm:"comment:员工名称;column:name" json:"name"` @@ -29,13 +30,16 @@ type WeWorkUser struct { RefUserId int64 `gorm:"comment:RefUserId;column:ref_user_id" json:"ref_user_id"` } -// Table -// -// @Description: -// @receiver e -// @return string -func (e WeWorkUser) TableName() string { - return model.TableNameWeWorkUser +func (mdl *WeWorkUser) TableName() string { + return model.PowerXSchema + "." + model.TableNameWeWorkUser +} + +func (mdl *WeWorkUser) GetTableName(needFull bool) string { + tableName := model.TableNameWeWorkUser + if needFull { + tableName = mdl.TableName() + } + return tableName } type ( diff --git a/internal/model/scrm/resource/department.go b/internal/model/scrm/resource/department.go index 6c615079..ba444d97 100644 --- a/internal/model/scrm/resource/department.go +++ b/internal/model/scrm/resource/department.go @@ -2,12 +2,14 @@ package resource import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type WeWorkResource struct { - model.Model + powermodel.PowerModel + Url string `gorm:"comment:微信地址;column:url" json:"url"` FileName string `gorm:"unique;comment:文件名;column:file_name" json:"file_name"` Remark string `gorm:"comment:备注;column:remark" json:"remark"` @@ -16,13 +18,16 @@ type WeWorkResource struct { ResourceType string `gorm:"comment:资源类型:image,voice,file, video, other;column:resource_type" json:"resource_type"` } -// TableName -// -// @Description: -// @receiver e -// @return string -func (e WeWorkResource) TableName() string { - return model.TableNameWeWorkResource +func (mdl *WeWorkResource) TableName() string { + return model.PowerXSchema + "." + model.TableNameWeWorkResource +} + +func (mdl *WeWorkResource) GetTableName(needFull bool) string { + tableName := model.TableNameWeWorkResource + if needFull { + tableName = mdl.TableName() + } + return tableName } // Query diff --git a/internal/model/scrm/tag/weworkgroup.go b/internal/model/scrm/tag/weworkgroup.go index 6b39ab3e..7275be24 100644 --- a/internal/model/scrm/tag/weworkgroup.go +++ b/internal/model/scrm/tag/weworkgroup.go @@ -2,12 +2,14 @@ package tag import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" ) type WeWorkTagGroup struct { - model.Model + powermodel.PowerModel + WeWorkGroupTags []*WeWorkTag `gorm:"foreignKey:GroupId;references:group_id" json:"WeWorkGroupTags"` AgentId int `gorm:"comment:应用ID;column:agent_id" json:"agent_id"` GroupId string `gorm:"comment:标签组ID;column:group_id;unique" json:"group_id"` @@ -16,13 +18,16 @@ type WeWorkTagGroup struct { IsDelete bool `gorm:"comment:是否删除;column:is_delete" json:"is_delete"` } -// Table -// -// @Description: -// @receiver e -// @return string -func (e WeWorkTagGroup) TableName() string { - return model.TableNameWeWorkTagGroup +func (mdl *WeWorkTagGroup) TableName() string { + return model.PowerXSchema + "." + model.TableNameWeWorkTagGroup +} + +func (mdl *WeWorkTagGroup) GetTableName(needFull bool) string { + tableName := model.TableNameWeWorkTagGroup + if needFull { + tableName = mdl.TableName() + } + return tableName } // Query diff --git a/internal/model/scrm/tag/weworktag.go b/internal/model/scrm/tag/weworktag.go index 72902a76..cc053049 100644 --- a/internal/model/scrm/tag/weworktag.go +++ b/internal/model/scrm/tag/weworktag.go @@ -2,13 +2,15 @@ package tag import ( "PowerX/internal/model" + "PowerX/internal/model/powermodel" "gorm.io/gorm" "gorm.io/gorm/clause" "time" ) type WeWorkTag struct { - model.Model + powermodel.PowerModel + WeWorkGroup *WeWorkTagGroup `gorm:"foreignKey:GroupId;references:group_id" json:"WeWorkGroup"` // IsSelf int `gorm:"comment:是否自建:1:平台创建:其他:微信创建;column:is_self" json:"is_self"` @@ -20,13 +22,16 @@ type WeWorkTag struct { IsDelete bool `gorm:"comment:是否删除;column:is_delete" json:"is_delete"` } -// Table -// -// @Description: -// @receiver e -// @return string -func (e WeWorkTag) TableName() string { - return model.TableNameWeWorkTag +func (mdl *WeWorkTag) TableName() string { + return model.PowerXSchema + "." + model.TableNameWeWorkTag +} + +func (mdl *WeWorkTag) GetTableName(needFull bool) string { + tableName := model.TableNameWeWorkTag + if needFull { + tableName = mdl.TableName() + } + return tableName } // Query diff --git a/internal/model/tables.go b/internal/model/tables.go index 2f93e519..890cb90d 100644 --- a/internal/model/tables.go +++ b/internal/model/tables.go @@ -11,7 +11,11 @@ const TableNameRegisterCode = "register_codes" // crm market const TableNameMedia = "media" -const TableNameMGM = "mgm_rules" +const TableNameMGMRule = "mgm_rules" +const TableNameCustomerChannel = "customer_channels" +const TableNameInviteRecord = "invite_records" +const TableNameCommissionRecord = "commission_records" +const TableNameRewardRecord = "reward_records" const TableNamePromotionRule = "promotion_rules" const TableNameStore = "stores" @@ -30,24 +34,29 @@ const TableNamePriceConfig = "price_configs" const TableNameProduct = "products" const TableNameProductCategory = "product_categories" const TableNameProductSpecific = "product_specifics" +const TableNameSpecificOption = "product_options" const TableNameProductStatistics = "product_statistics" const TableNameSKU = "sku" // trade const TableNameBillingAddress = "billing_addresses" -const TableNameBillingCart = "carts" -const TableNameBillingCartItem = "cart_items" +const TableNameCart = "carts" +const TableNameCartItem = "cart_items" const TableNameDeliveryAddress = "delivery_addresses" const TableNameInventory = "inventories" const TableNameLogistics = "logistics" const TableNameOrder = "orders" +const TableNameOrderItem = "order_items" +const TableNameOrderStatusTransition = "order_status_transitions" const TableNamePayment = "payments" +const TableNamePaymentItem = "payment_items" const TableNamePivotProductToPromotion = "pivot_product_to_promotion" const TableNamePivotOrderToInventoryLog = "pivot_order_to_inventory_log" const TableNameRefundOrder = "refund_orders" const TableNameRefundOrderItem = "refund_order_items" const TableNameShippingAddress = "shipping_addresses" const TableNameTokenExchangeRatio = "token_exchange_ratios" +const TableNameTokenBalance = "token_balances" const TableNameTokenExchangeRecord = "token_exchange_records" const TableNameTokenReservation = "token_reservations" const TableNameTokenTransaction = "token_transactions" @@ -75,14 +84,12 @@ const TableNameOperationLog = "power_operation_logs" // scene const TableNameSceneQRCode = "scene_qr_codes" -const TableNamePivotDataDictionaryToObject = "pivot_data_dictionary_to_object" - // tag const TableNamePivotObjectToTag = "pivot_object_to_tag" const TableNameTag = "tags" // scrm app -const WeWorkAppGroup = "wework_app_groups" +const TableNameWeWorkAppGroup = "wework_app_groups" // scrm customer const TableNameWeWorkExternalContact = "we_work_external_contacts" @@ -103,5 +110,13 @@ const TableNameWeWorkTag = "we_work_tags" const TableNameWechatMPCustomer = "wechat_mp_customers" const TableNameWechatOACustomer = "wechat_oa_customers" +// data dictionary +const TableNameDataDictionaryItem = "data_dictionary_items" +const TableNameDataDictionaryType = "data_dictionary_types" +const TableNamePivotDataDictionaryToObject = "pivot_data_dictionary_to_object" + +// operation log +const TableNamePowerOperationLog = "power_operation_logs" + // custom const TableNameArtisanSpecific = "artisan_specifics" diff --git a/internal/model/tag/pivotobjecttotag.go b/internal/model/tag/pivotobjecttotag.go index a31c9d6e..ccf5334d 100644 --- a/internal/model/tag/pivotobjecttotag.go +++ b/internal/model/tag/pivotobjecttotag.go @@ -8,11 +8,6 @@ import ( "gorm.io/gorm" ) -// Table Name -func (mdl *PivotObjectToTag) TableName() string { - return model.TableNamePivotObjectToTag -} - // 数据表结构 type PivotObjectToTag struct { powermodel.PowerPivot @@ -28,6 +23,18 @@ const PivotObjectToTagForeignOwnerKey = "object_type" const PivotObjectToTagForeignKey = "object_id" const PivotObjectToTagJoinKey = "tag_id" +func (mdl *PivotObjectToTag) TableName() string { + return model.PowerXSchema + "." + model.TableNamePivotObjectToTag +} + +func (mdl *PivotObjectToTag) GetTableName(needFull bool) string { + tableName := model.TableNamePivotObjectToTag + if needFull { + tableName = mdl.TableName() + } + return tableName +} + func (mdl *PivotObjectToTag) GetOwnerKey() string { // 因为是morphy类型,所以外键是Owner return PivotObjectToTagForeignOwnerKey diff --git a/internal/model/tag/tag.go b/internal/model/tag/tag.go index d6d27b55..c8793897 100644 --- a/internal/model/tag/tag.go +++ b/internal/model/tag/tag.go @@ -26,6 +26,17 @@ type Tag struct { const TagUniqueId = powermodel.UniqueId +func (mdl *Tag) TableName() string { + return model.PowerXSchema + "." + model.TableNameTag +} + +func (mdl *Tag) GetTableName(needFull bool) string { + tableName := model.TableNameTag + if needFull { + tableName = mdl.TableName() + } + return tableName +} func GetTagIds(tags []*Tag) []int64 { uniqueIds := make(map[int64]bool) arrayIds := []int64{} diff --git a/internal/model/wechat/miniprogram.go b/internal/model/wechat/miniprogram.go index d776ec88..24f1ccce 100644 --- a/internal/model/wechat/miniprogram.go +++ b/internal/model/wechat/miniprogram.go @@ -3,15 +3,17 @@ package wechat import ( "PowerX/internal/model" customerdomain2 "PowerX/internal/model/crm/customerdomain" + "PowerX/internal/model/powermodel" "fmt" "github.com/ArtisanCloud/PowerLibs/v3/security" ) // 小程序客户信息 type WechatMPCustomer struct { + powermodel.PowerModel + Customer *customerdomain2.Customer `gorm:"foreignKey:OpenId;references:OpenIdInMiniProgram" json:"customer"` - model.Model UniqueID string `gorm:"unique" json:"uniqueId"` SessionKey string `json:"-"` OpenId string `json:"openId"` @@ -34,6 +36,18 @@ type WechatMPCustomer struct { const WechatMpCustomerUniqueId = "unique_id" +func (mdl *WechatMPCustomer) TableName() string { + return model.PowerXSchema + "." + model.TableNameWechatMPCustomer +} + +func (mdl *WechatMPCustomer) GetTableName(needFull bool) string { + tableName := model.TableNameWechatMPCustomer + if needFull { + tableName = mdl.TableName() + } + return tableName +} + // 小程序获取手机号 // https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html type MPPhoneInfo struct { diff --git a/internal/model/wechat/offiaccount.go b/internal/model/wechat/offiaccount.go index f87974e6..173050a2 100644 --- a/internal/model/wechat/offiaccount.go +++ b/internal/model/wechat/offiaccount.go @@ -3,6 +3,7 @@ package wechat import ( "PowerX/internal/model" customerdomain2 "PowerX/internal/model/crm/customerdomain" + "PowerX/internal/model/powermodel" "gorm.io/datatypes" ) @@ -10,9 +11,10 @@ import ( // 公众号的客户信息 // https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionId.html#UinonId type WechatOACustomer struct { + powermodel.PowerModel + Customer *customerdomain2.Customer `gorm:"foreignKey:OpenId;references:OpenIdInWeChatOfficialAccount" json:"customer"` - model.Model Subscribe int `json:"subscribe"` SessionKey string `json:"-"` OpenId string `json:"openId"` @@ -26,3 +28,15 @@ type WechatOACustomer struct { QrScene int `json:"qrScene"` QrSceneStr string `json:"qrSceneStr"` } + +func (mdl *WechatOACustomer) TableName() string { + return model.PowerXSchema + "." + model.TableNameWechatOACustomer +} + +func (mdl *WechatOACustomer) GetTableName(needFull bool) string { + tableName := model.TableNameWechatOACustomer + if needFull { + tableName = mdl.TableName() + } + return tableName +} diff --git a/internal/uc/powerx/organization.go b/internal/uc/powerx/organization.go index 216aacbf..a82850b7 100644 --- a/internal/uc/powerx/organization.go +++ b/internal/uc/powerx/organization.go @@ -1,7 +1,6 @@ package powerx import ( - "PowerX/internal/model" "PowerX/internal/model/option" "PowerX/internal/model/organization" "PowerX/internal/model/permission" @@ -164,7 +163,7 @@ func (uc *OrganizationUseCase) FindOneUserById(ctx context.Context, id int64) (u func (uc *OrganizationUseCase) UpdateUserById(ctx context.Context, user *organization.User, userId int64) error { whereCase := organization.User{ - Model: model.Model{ + PowerModel: powermodel.PowerModel{ Id: userId, }, IsReserved: false, diff --git a/internal/uc/powerx/scrm/wechat/weworktag.go b/internal/uc/powerx/scrm/wechat/weworktag.go index 8ee9fdec..3f6a1cf6 100644 --- a/internal/uc/powerx/scrm/wechat/weworktag.go +++ b/internal/uc/powerx/scrm/wechat/weworktag.go @@ -1,7 +1,7 @@ package wechat import ( - "PowerX/internal/model" + "PowerX/internal/model/powermodel" "PowerX/internal/model/scrm/customer" "PowerX/internal/model/scrm/tag" "PowerX/internal/types" @@ -170,7 +170,7 @@ func (this wechatUseCase) transferWeWorkToModel(data []*response.CorpTagGroup, a if data != nil { for _, val := range data { groups = append(groups, &tag.WeWorkTagGroup{ - Model: model.Model{ + PowerModel: powermodel.PowerModel{ CreatedAt: time.Unix(int64(val.CreateTime), 0), }, //AgentId: int(*agentId), @@ -182,7 +182,7 @@ func (this wechatUseCase) transferWeWorkToModel(data []*response.CorpTagGroup, a if val.Tags != nil { for _, value := range val.Tags { tags = append(tags, &tag.WeWorkTag{ - Model: model.Model{ + PowerModel: powermodel.PowerModel{ CreatedAt: time.Unix(int64(value.CreateTime), 0), }, Type: 1, From 1e74ef6c4a1399996469eef45ba7dd9f6e8029ec Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 9 Oct 2024 00:02:33 +0800 Subject: [PATCH 20/24] feat(migrate): change migrate schema with config schema --- internal/model/crm/customerdomain/customer.go | 3 ++- internal/model/organization/user.go | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/internal/model/crm/customerdomain/customer.go b/internal/model/crm/customerdomain/customer.go index e6ba1fc2..c4b8da58 100644 --- a/internal/model/crm/customerdomain/customer.go +++ b/internal/model/crm/customerdomain/customer.go @@ -37,7 +37,8 @@ const CustomerPersonal = "_personal" const CustomerCompany = "_company" func (mdl *Customer) TableName() string { - return model.PowerXSchema + "." + model.TableNameCustomer + //return model.PowerXSchema + "." + model.TableNameCustomer + return "public." + model.TableNameCustomer } func (mdl *Customer) GetTableName(needFull bool) string { diff --git a/internal/model/organization/user.go b/internal/model/organization/user.go index 2a9773cd..a2f272e1 100644 --- a/internal/model/organization/user.go +++ b/internal/model/organization/user.go @@ -36,11 +36,12 @@ type User struct { } func (mdl *User) TableName() string { - return model.PowerXSchema + "." + model.TableNameCart + //return model.PowerXSchema + "." + model.TableNameUser + return "public." + model.TableNameUser } func (mdl *User) GetTableName(needFull bool) string { - tableName := model.TableNameCart + tableName := model.TableNameUser if needFull { tableName = mdl.TableName() } From 8a7241d9602b1a408ea1cde6820fbe75c43d4bb7 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 9 Oct 2024 00:05:06 +0800 Subject: [PATCH 21/24] feat(migrate): change migrate schema with config schema --- etc/powerx-example.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/powerx-example.yaml b/etc/powerx-example.yaml index 3a91b339..4166a604 100644 --- a/etc/powerx-example.yaml +++ b/etc/powerx-example.yaml @@ -54,7 +54,7 @@ PowerXDatabase: # Driver: mysql # 可以连接,但是我们未基于mysql来开发应用。 # 数据库连接信息 - DSN: host=localhost user=powerx password=powerxpw dbname=powerx port=5432 sslmode=disable TimeZone=UTC + DSN: host=localhost user=powerx password=powerxpw dbname=powerx port=5432 sslmode=disable TimeZone=UTC SearchPath=public # Schema Schema: public From ac3d672fff0909f65827bc0388533f1ce03aaf85 Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 9 Oct 2024 00:12:41 +0800 Subject: [PATCH 22/24] feat(migrate): change migrate schema with config schema --- etc/powerx-example.yaml | 2 +- internal/logic/admin/department/createdepartmentlogic.go | 1 + internal/logic/admin/position/createpositionlogic.go | 1 + internal/logic/admin/position/patchpositionlogic.go | 1 + internal/logic/admin/user/createuserlogic.go | 1 + internal/logic/admin/user/getuserlogic.go | 1 + internal/logic/admin/user/listuserlogic.go | 1 + internal/logic/admin/user/resetpasswordlogic.go | 5 +++-- internal/logic/admin/user/updateuserlogic.go | 5 +++-- internal/logic/admin/userinfo/getuserinfologic.go | 1 + internal/logic/admin/userinfo/modifyuserpasswordlogic.go | 1 + 11 files changed, 15 insertions(+), 5 deletions(-) diff --git a/etc/powerx-example.yaml b/etc/powerx-example.yaml index 4166a604..8ca61825 100644 --- a/etc/powerx-example.yaml +++ b/etc/powerx-example.yaml @@ -54,7 +54,7 @@ PowerXDatabase: # Driver: mysql # 可以连接,但是我们未基于mysql来开发应用。 # 数据库连接信息 - DSN: host=localhost user=powerx password=powerxpw dbname=powerx port=5432 sslmode=disable TimeZone=UTC SearchPath=public + DSN: host=localhost user=powerx password=powerxpw dbname=powerx port=5432 sslmode=disable TimeZone=UTC search_path=public # Schema Schema: public diff --git a/internal/logic/admin/department/createdepartmentlogic.go b/internal/logic/admin/department/createdepartmentlogic.go index c301aaea..ce4c37b1 100644 --- a/internal/logic/admin/department/createdepartmentlogic.go +++ b/internal/logic/admin/department/createdepartmentlogic.go @@ -1,6 +1,7 @@ package department import ( + "PowerX/internal/model/organization" "PowerX/internal/svc" "PowerX/internal/types" "context" diff --git a/internal/logic/admin/position/createpositionlogic.go b/internal/logic/admin/position/createpositionlogic.go index 6de8eade..c619b574 100644 --- a/internal/logic/admin/position/createpositionlogic.go +++ b/internal/logic/admin/position/createpositionlogic.go @@ -1,6 +1,7 @@ package position import ( + "PowerX/internal/model/organization" "PowerX/internal/model/permission" "context" diff --git a/internal/logic/admin/position/patchpositionlogic.go b/internal/logic/admin/position/patchpositionlogic.go index 7474fb26..a4971d39 100644 --- a/internal/logic/admin/position/patchpositionlogic.go +++ b/internal/logic/admin/position/patchpositionlogic.go @@ -2,6 +2,7 @@ package position import ( "PowerX/internal/model/option" + "PowerX/internal/model/organization" "PowerX/internal/model/permission" "PowerX/pkg/slicex" "context" diff --git a/internal/logic/admin/user/createuserlogic.go b/internal/logic/admin/user/createuserlogic.go index afaed787..fc605d60 100644 --- a/internal/logic/admin/user/createuserlogic.go +++ b/internal/logic/admin/user/createuserlogic.go @@ -1,6 +1,7 @@ package user import ( + "PowerX/internal/model/organization" "context" "github.com/pkg/errors" diff --git a/internal/logic/admin/user/getuserlogic.go b/internal/logic/admin/user/getuserlogic.go index 300f2424..1ab77661 100644 --- a/internal/logic/admin/user/getuserlogic.go +++ b/internal/logic/admin/user/getuserlogic.go @@ -1,6 +1,7 @@ package user import ( + "PowerX/internal/model/organization" "PowerX/internal/model/permission" "PowerX/pkg/slicex" "context" diff --git a/internal/logic/admin/user/listuserlogic.go b/internal/logic/admin/user/listuserlogic.go index be718196..9836912c 100644 --- a/internal/logic/admin/user/listuserlogic.go +++ b/internal/logic/admin/user/listuserlogic.go @@ -2,6 +2,7 @@ package user import ( "PowerX/internal/model/option" + "PowerX/internal/model/organization" "PowerX/internal/model/permission" "PowerX/pkg/slicex" "context" diff --git a/internal/logic/admin/user/resetpasswordlogic.go b/internal/logic/admin/user/resetpasswordlogic.go index ab0cc27e..f479caf4 100644 --- a/internal/logic/admin/user/resetpasswordlogic.go +++ b/internal/logic/admin/user/resetpasswordlogic.go @@ -1,11 +1,12 @@ package user import ( + "PowerX/internal/model/organization" + "PowerX/internal/model/powermodel" "PowerX/internal/types" "context" "github.com/pkg/errors" - "PowerX/internal/model" "PowerX/internal/svc" "github.com/zeromicro/go-zero/core/logx" @@ -27,7 +28,7 @@ func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Res func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordRequest) (resp *types.ResetPasswordReply, err error) { user := organization.User{ - Model: model.Model{ + PowerModel: powermodel.PowerModel{ Id: req.UserId, }, Password: "123456", diff --git a/internal/logic/admin/user/updateuserlogic.go b/internal/logic/admin/user/updateuserlogic.go index 68dbbc1e..cd4c4f15 100644 --- a/internal/logic/admin/user/updateuserlogic.go +++ b/internal/logic/admin/user/updateuserlogic.go @@ -1,12 +1,13 @@ package user import ( + "PowerX/internal/model/organization" + "PowerX/internal/model/powermodel" "PowerX/internal/types" "context" "github.com/pkg/errors" "time" - "PowerX/internal/model" "PowerX/internal/svc" "github.com/zeromicro/go-zero/core/logx" @@ -28,7 +29,7 @@ func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Update func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (resp *types.UpdateUserReply, err error) { user := organization.User{ - Model: model.Model{ + PowerModel: powermodel.PowerModel{ Id: req.Id, }, Name: req.Name, diff --git a/internal/logic/admin/userinfo/getuserinfologic.go b/internal/logic/admin/userinfo/getuserinfologic.go index 34051d34..75659e1d 100644 --- a/internal/logic/admin/userinfo/getuserinfologic.go +++ b/internal/logic/admin/userinfo/getuserinfologic.go @@ -1,6 +1,7 @@ package userinfo import ( + "PowerX/internal/model/organization" "context" "github.com/pkg/errors" "time" diff --git a/internal/logic/admin/userinfo/modifyuserpasswordlogic.go b/internal/logic/admin/userinfo/modifyuserpasswordlogic.go index cda91adc..8e1ee720 100644 --- a/internal/logic/admin/userinfo/modifyuserpasswordlogic.go +++ b/internal/logic/admin/userinfo/modifyuserpasswordlogic.go @@ -1,6 +1,7 @@ package userinfo import ( + "PowerX/internal/model/organization" "context" "github.com/pkg/errors" From 153a0be0c2770abe0c670bf45429e5c9bed3559f Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 9 Oct 2024 12:04:59 +0800 Subject: [PATCH 23/24] refact(model): seperate model with differentschema --- api/admin/department.api | 2 +- api/admin/user.api | 16 +- api/openapi/provider/brainx/demo.api | 40 +++++ cmd/ctl/database/seed/mediaresource.go | 9 + internal/handler/routes.go | 168 +++++++++--------- .../customer/createcustomerlogic.go | 2 +- .../customer/putcustomerlogic.go | 2 +- .../admin/department/createdepartmentlogic.go | 2 +- internal/logic/admin/user/deleteuserlogic.go | 4 +- internal/logic/admin/user/getuserlogic.go | 2 +- .../logic/admin/user/resetpasswordlogic.go | 11 +- internal/logic/admin/user/updateuserlogic.go | 11 +- ...egistercustomerbyphoneininvitecodelogic.go | 2 +- ...istercustomerbyphoneinregistercodelogic.go | 2 +- .../auth/registercustomerbyphonelogic.go | 2 +- internal/model/media/mediaresource.go | 4 +- internal/model/organization/department.go | 4 +- internal/model/organization/user.go | 3 +- internal/model/powermodel/pivot.go | 7 +- internal/model/powermodel/powermodel.go | 22 ++- internal/types/types.go | 14 +- internal/uc/powerx/authorizationadmin.go | 5 +- .../uc/powerx/crm/customerdomain/customer.go | 2 +- internal/uc/powerx/organization.go | 32 +++- pkg/securityx/security.go | 5 +- 25 files changed, 236 insertions(+), 137 deletions(-) create mode 100644 api/openapi/provider/brainx/demo.api diff --git a/api/admin/department.api b/api/admin/department.api index f5ce585f..7e781804 100644 --- a/api/admin/department.api +++ b/api/admin/department.api @@ -56,7 +56,7 @@ type ( type ( CreateDepartmentRequest { DepName string `json:"depName"` - LeaderId int64 `json:"leaderId"` + LeaderUuid string `json:"leaderUuid"` PId int64 `json:"pId"` Desc string `json:"desc,optional"` PhoneNumber string `json:"phoneNumber,optional"` diff --git a/api/admin/user.api b/api/admin/user.api index 03188ba0..e34d27f1 100644 --- a/api/admin/user.api +++ b/api/admin/user.api @@ -21,7 +21,7 @@ service PowerX { @doc "查询员工" @handler GetUser - get /users/:id (GetUserRequest) returns (GetUserReply) + get /users/:uuid (GetUserRequest) returns (GetUserReply) @doc "List员工" @handler ListUsers @@ -33,11 +33,11 @@ service PowerX { @doc "编辑员工信息" @handler UpdateUser - patch /users/:id (UpdateUserRequest) returns (UpdateUserReply) + patch /users/:uuid (UpdateUserRequest) returns (UpdateUserReply) @doc "删除员工" @handler DeleteUser - delete /users/:id (DeleteUserRequest) returns (DeleteUserReply) + delete /users/:uuid (DeleteUserRequest) returns (DeleteUserReply) @doc "重设密码" @handler ResetPassword @@ -46,7 +46,7 @@ service PowerX { type ( GetUserRequest { - Id int64 `path:"id"` + Uuid string `path:"uuid"` } GetUserReply { @@ -136,7 +136,7 @@ type ( type ( UpdateUserRequest { - Id int64 `path:"id"` + Uuid string `path:"uuid"` Name string `json:"name,optional"` NickName string `json:"nickName,optional"` Desc string `json:"desc,optional"` @@ -159,17 +159,17 @@ type ( type ( DeleteUserRequest { - Id int64 `path:"id"` + Uuid string `path:"uuid"` } DeleteUserReply { - Id int64 `json:"id"` + Uuid string `json:"uuid"` } ) type ( ResetPasswordRequest { - UserId int64 `json:"userId"` + UserUuid string `json:"userUuid"` } ResetPasswordReply { diff --git a/api/openapi/provider/brainx/demo.api b/api/openapi/provider/brainx/demo.api new file mode 100644 index 00000000..5a0613a9 --- /dev/null +++ b/api/openapi/provider/brainx/demo.api @@ -0,0 +1,40 @@ +syntax = "v1" + +info( + title: "Provider Demo Open API of BrainX" + desc: "This is a api of Open API in Artisan Cloud" + author: "Matrix-X" + email: "matrix-x@artisan-cloud.com" + version: "v1" +) + +@server( + group: openapi/provider/brainx + prefix: /openapi/v1/provider/brainx + middleware: OpenAPIJWTAuth +) + +service PowerX { + @doc "hello world api for provider demo" + @handler HelloWorld + get /hello-world returns (HelloWorldResponse) + + @doc "timeout api for provider demo" + @handler EchoLongTime + post /echo-long-time (EchoLongTimeRequest) returns (EchoLongTimeResponse) +} + + + +type ( + HelloWorldResponse { + Message string `json:"message"` + } + + EchoLongTimeRequest { + Timeout int `json:"timeout"` + } + EchoLongTimeResponse { + Message string `json:"message"` + } +) \ No newline at end of file diff --git a/cmd/ctl/database/seed/mediaresource.go b/cmd/ctl/database/seed/mediaresource.go index d1323baf..7643399c 100644 --- a/cmd/ctl/database/seed/mediaresource.go +++ b/cmd/ctl/database/seed/mediaresource.go @@ -3,8 +3,10 @@ package seed import ( "PowerX/internal/config" "PowerX/internal/model/media" + "PowerX/internal/model/powermodel" "PowerX/internal/uc/powerx" "PowerX/pkg/httpx" + "PowerX/pkg/securityx" "PowerX/pkg/slicex" "fmt" "github.com/pkg/errors" @@ -37,6 +39,7 @@ func DefaultMediaResource(db *gorm.DB, conf *config.Config) (data []*media.Media path := path2.Join(powerx.DefaultStoragePath, "shop") coverImage := ProductCoverImage(ucMediaResource.LocalStorageUrl, path) detailImages := ProductDetailImages(ucMediaResource.LocalStorageUrl, path) + //fmt2.Dump(coverImage, detailImages) data = slicex.Concatenate(data, coverImage, detailImages) return data @@ -46,6 +49,9 @@ func ProductCoverImage(url string, name string) []*media.MediaResource { imageUrl, _ := httpx.AppendURIs(url, fmt.Sprintf("%s/0.png", name)) return []*media.MediaResource{ { + PowerUUIDModel: powermodel.PowerUUIDModel{ + UUID: securityx.GenerateUUID(), + }, Url: imageUrl, IsLocalStored: true, }, @@ -58,6 +64,9 @@ func ProductDetailImages(url string, path string) []*media.MediaResource { imageUrl, _ := httpx.AppendURIs(url, path, fmt.Sprintf("%d.png", i+1)) urls = append(urls, &media.MediaResource{ + PowerUUIDModel: powermodel.PowerUUIDModel{ + UUID: securityx.GenerateUUID(), + }, Url: imageUrl, IsLocalStored: true, }) diff --git a/internal/handler/routes.go b/internal/handler/routes.go index 29118615..4e6af409 100644 --- a/internal/handler/routes.go +++ b/internal/handler/routes.go @@ -1415,21 +1415,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/admin/position"), ) - server.AddRoutes( - rest.WithMiddlewares( - []rest.Middleware{serverCtx.UserJWTAuth}, - []rest.Route{ - { - // App发送图文信息 - Method: http.MethodPost, - Path: "/message/articles", - Handler: adminscrmapp.SendWeWorkAppArticleMessageHandler(serverCtx), - }, - }..., - ), - rest.WithPrefix("/api/v1/admin/scrm/app/wechat"), - ) - server.AddRoutes( rest.WithMiddlewares( []rest.Middleware{serverCtx.UserJWTAuth}, @@ -1457,6 +1442,21 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/admin/scrm/app/wechat"), ) + server.AddRoutes( + rest.WithMiddlewares( + []rest.Middleware{serverCtx.UserJWTAuth}, + []rest.Route{ + { + // App发送图文信息 + Method: http.MethodPost, + Path: "/message/articles", + Handler: adminscrmapp.SendWeWorkAppArticleMessageHandler(serverCtx), + }, + }..., + ), + rest.WithPrefix("/api/v1/admin/scrm/app/wechat"), + ) + server.AddRoutes( rest.WithMiddlewares( []rest.Middleware{serverCtx.UserJWTAuth}, @@ -1543,16 +1543,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 客户群列表/limit + // 所有客户列表/page Method: http.MethodPost, - Path: "/group/list", - Handler: adminscrmcustomer.ListWeWorkCustomerGroupLimitHandler(serverCtx), + Path: "/page", + Handler: adminscrmcustomer.ListWeWorkCustomerPageHandler(serverCtx), }, { - // 客户群发信息 + // 批量同步客户信息(根据员工ID同步/节流) Method: http.MethodPost, - Path: "/group/message/template", - Handler: adminscrmcustomer.SendWeWorkCustomerGroupMessageHandler(serverCtx), + Path: "/sync", + Handler: adminscrmcustomer.SyncWeWorkCustomerOptionHandler(serverCtx), }, }..., ), @@ -1564,16 +1564,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 所有客户列表/page + // 客户群列表/limit Method: http.MethodPost, - Path: "/page", - Handler: adminscrmcustomer.ListWeWorkCustomerPageHandler(serverCtx), + Path: "/group/list", + Handler: adminscrmcustomer.ListWeWorkCustomerGroupLimitHandler(serverCtx), }, { - // 批量同步客户信息(根据员工ID同步/节流) + // 客户群发信息 Method: http.MethodPost, - Path: "/sync", - Handler: adminscrmcustomer.SyncWeWorkCustomerOptionHandler(serverCtx), + Path: "/group/message/template", + Handler: adminscrmcustomer.SendWeWorkCustomerGroupMessageHandler(serverCtx), }, }..., ), @@ -1585,16 +1585,10 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 同步组织架构/department&user - Method: http.MethodGet, - Path: "/sync", - Handler: adminscrmorganization.SyncWeWorkUserHandler(serverCtx), - }, - { - // 员工列表/page + // 部门列表/page Method: http.MethodPost, - Path: "/user/page", - Handler: adminscrmorganization.ListWeWorkUserPageHandler(serverCtx), + Path: "/partment/page", + Handler: adminscrmorganization.ListWeWorkDepartMentPageHandler(serverCtx), }, }..., ), @@ -1606,10 +1600,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Middleware{serverCtx.UserJWTAuth}, []rest.Route{ { - // 部门列表/page + // 同步组织架构/department&user + Method: http.MethodGet, + Path: "/sync", + Handler: adminscrmorganization.SyncWeWorkUserHandler(serverCtx), + }, + { + // 员工列表/page Method: http.MethodPost, - Path: "/partment/page", - Handler: adminscrmorganization.ListWeWorkDepartMentPageHandler(serverCtx), + Path: "/user/page", + Handler: adminscrmorganization.ListWeWorkUserPageHandler(serverCtx), }, }..., ), @@ -1821,19 +1821,19 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { { // 查询员工 Method: http.MethodGet, - Path: "/users/:id", + Path: "/users/:uuid", Handler: adminuser.GetUserHandler(serverCtx), }, { // 编辑员工信息 Method: http.MethodPatch, - Path: "/users/:id", + Path: "/users/:uuid", Handler: adminuser.UpdateUserHandler(serverCtx), }, { // 删除员工 Method: http.MethodDelete, - Path: "/users/:id", + Path: "/users/:uuid", Handler: adminuser.DeleteUserHandler(serverCtx), }, { @@ -2057,16 +2057,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { server.AddRoutes( []rest.Route{ { - // 查询产品详情 + // 查询产品品类列表 Method: http.MethodGet, - Path: "/products/:id", - Handler: mpcrmproduct.GetProductHandler(serverCtx), + Path: "/product-categories", + Handler: mpcrmproduct.ListProductCategoriesHandler(serverCtx), }, { - // 产品列表 + // 查询产品品类树形表 Method: http.MethodGet, - Path: "/products/page-list", - Handler: mpcrmproduct.ListProductsPageHandler(serverCtx), + Path: "/product-category-tree", + Handler: mpcrmproduct.ListProductCategoryTreeHandler(serverCtx), }, }, rest.WithPrefix("/api/v1/mp/product"), @@ -2075,16 +2075,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { server.AddRoutes( []rest.Route{ { - // 查询产品品类列表 + // 查询产品详情 Method: http.MethodGet, - Path: "/product-categories", - Handler: mpcrmproduct.ListProductCategoriesHandler(serverCtx), + Path: "/products/:id", + Handler: mpcrmproduct.GetProductHandler(serverCtx), }, { - // 查询产品品类树形表 + // 产品列表 Method: http.MethodGet, - Path: "/product-category-tree", - Handler: mpcrmproduct.ListProductCategoryTreeHandler(serverCtx), + Path: "/products/page-list", + Handler: mpcrmproduct.ListProductsPageHandler(serverCtx), }, }, rest.WithPrefix("/api/v1/mp/product"), @@ -2395,6 +2395,36 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/mp/trade/token"), ) + server.AddRoutes( + []rest.Route{ + { + // 获取字典项列表 + Method: http.MethodGet, + Path: "/items", + Handler: mpdictionary.ListDictionaryItemsHandler(serverCtx), + }, + { + // 获取字典项 + Method: http.MethodGet, + Path: "/items/:type/:key", + Handler: mpdictionary.GetDictionaryItemHandler(serverCtx), + }, + { + // 获取字典类型 + Method: http.MethodGet, + Path: "/types/:type", + Handler: mpdictionary.GetDictionaryTypeHandler(serverCtx), + }, + { + // 获取字典类型列表 + Method: http.MethodGet, + Path: "/types/page-list", + Handler: mpdictionary.ListDictionaryPageTypesHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1/mp/dictionary"), + ) + server.AddRoutes( rest.WithMiddlewares( []rest.Middleware{serverCtx.WebCustomerJWTAuth}, @@ -2428,36 +2458,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { rest.WithPrefix("/api/v1/web/dictionary"), ) - server.AddRoutes( - []rest.Route{ - { - // 获取字典项列表 - Method: http.MethodGet, - Path: "/items", - Handler: mpdictionary.ListDictionaryItemsHandler(serverCtx), - }, - { - // 获取字典项 - Method: http.MethodGet, - Path: "/items/:type/:key", - Handler: mpdictionary.GetDictionaryItemHandler(serverCtx), - }, - { - // 获取字典类型 - Method: http.MethodGet, - Path: "/types/:type", - Handler: mpdictionary.GetDictionaryTypeHandler(serverCtx), - }, - { - // 获取字典类型列表 - Method: http.MethodGet, - Path: "/types/page-list", - Handler: mpdictionary.ListDictionaryPageTypesHandler(serverCtx), - }, - }, - rest.WithPrefix("/api/v1/mp/dictionary"), - ) - server.AddRoutes( []rest.Route{ { diff --git a/internal/logic/admin/crm/customerdomain/customer/createcustomerlogic.go b/internal/logic/admin/crm/customerdomain/customer/createcustomerlogic.go index aece7050..a2f95005 100644 --- a/internal/logic/admin/crm/customerdomain/customer/createcustomerlogic.go +++ b/internal/logic/admin/crm/customerdomain/customer/createcustomerlogic.go @@ -29,7 +29,7 @@ func (l *CreateCustomerLogic) CreateCustomer(req *types.CreateCustomerRequest) ( Name: req.Name, Mobile: req.Mobile, Email: req.Email, - Uuid: securityx.GenerateUUID(), + Uuid: securityx.GenerateUUIDString(), InviterId: req.InviterId, Source: req.Source, Type: req.Type, diff --git a/internal/logic/admin/crm/customerdomain/customer/putcustomerlogic.go b/internal/logic/admin/crm/customerdomain/customer/putcustomerlogic.go index a735a588..150c9b12 100644 --- a/internal/logic/admin/crm/customerdomain/customer/putcustomerlogic.go +++ b/internal/logic/admin/crm/customerdomain/customer/putcustomerlogic.go @@ -32,7 +32,7 @@ func (l *PutCustomerLogic) PutCustomer(req *types.PutCustomerRequest) (resp *typ } // 如果当前数据库的用户已经有了UUID if cCustomer.Uuid == "" { - mdlCustomer.Uuid = securityx.GenerateUUID() + mdlCustomer.Uuid = securityx.GenerateUUIDString() mdlCustomer.InviteCode = securityx.GenerateInviteCode(mdlCustomer.Uuid) } diff --git a/internal/logic/admin/department/createdepartmentlogic.go b/internal/logic/admin/department/createdepartmentlogic.go index ce4c37b1..84e26f6f 100644 --- a/internal/logic/admin/department/createdepartmentlogic.go +++ b/internal/logic/admin/department/createdepartmentlogic.go @@ -27,7 +27,7 @@ func (l *CreateDepartmentLogic) CreateDepartment(req *types.CreateDepartmentRequ dep := organization.Department{ Name: req.DepName, PId: req.PId, - LeaderId: req.LeaderId, + LeaderUuid: req.LeaderUuid, Desc: req.Desc, PhoneNumber: req.PhoneNumber, Email: req.Email, diff --git a/internal/logic/admin/user/deleteuserlogic.go b/internal/logic/admin/user/deleteuserlogic.go index 492a544f..b9947ba9 100644 --- a/internal/logic/admin/user/deleteuserlogic.go +++ b/internal/logic/admin/user/deleteuserlogic.go @@ -24,11 +24,11 @@ func NewDeleteUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Delete } func (l *DeleteUserLogic) DeleteUser(req *types.DeleteUserRequest) (resp *types.DeleteUserReply, err error) { - err = l.svcCtx.PowerX.Organization.DeleteUserById(l.ctx, req.Id) + err = l.svcCtx.PowerX.Organization.DeleteUserByUuid(l.ctx, req.Uuid) if err != nil { return nil, err } return &types.DeleteUserReply{ - Id: req.Id, + Uuid: req.Uuid, }, nil } diff --git a/internal/logic/admin/user/getuserlogic.go b/internal/logic/admin/user/getuserlogic.go index 1ab77661..dd369fb2 100644 --- a/internal/logic/admin/user/getuserlogic.go +++ b/internal/logic/admin/user/getuserlogic.go @@ -28,7 +28,7 @@ func NewGetUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserLo } func (l *GetUserLogic) GetUser(req *types.GetUserRequest) (resp *types.GetUserReply, err error) { - user, err := l.svcCtx.PowerX.Organization.FindOneUserById(l.ctx, req.Id) + user, err := l.svcCtx.PowerX.Organization.FindOneUserByUuid(l.ctx, req.Uuid) if err != nil { return nil, err } diff --git a/internal/logic/admin/user/resetpasswordlogic.go b/internal/logic/admin/user/resetpasswordlogic.go index f479caf4..4532f1c1 100644 --- a/internal/logic/admin/user/resetpasswordlogic.go +++ b/internal/logic/admin/user/resetpasswordlogic.go @@ -5,6 +5,7 @@ import ( "PowerX/internal/model/powermodel" "PowerX/internal/types" "context" + "github.com/google/uuid" "github.com/pkg/errors" "PowerX/internal/svc" @@ -27,9 +28,13 @@ func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Res } func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordRequest) (resp *types.ResetPasswordReply, err error) { + userUuid, err := uuid.Parse(req.UserUuid) + if err != nil { + return nil, err + } user := organization.User{ - PowerModel: powermodel.PowerModel{ - Id: req.UserId, + PowerUUIDModel: powermodel.PowerUUIDModel{ + UUID: userUuid, }, Password: "123456", } @@ -39,7 +44,7 @@ func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordRequest) (res panic(errors.Wrap(err, "create user hash password failed")) } - if err := l.svcCtx.PowerX.Organization.UpdateUserById(l.ctx, &user, req.UserId); err != nil { + if err := l.svcCtx.PowerX.Organization.UpdateUserByUuid(l.ctx, &user, req.UserUuid); err != nil { return nil, err } diff --git a/internal/logic/admin/user/updateuserlogic.go b/internal/logic/admin/user/updateuserlogic.go index cd4c4f15..690271dc 100644 --- a/internal/logic/admin/user/updateuserlogic.go +++ b/internal/logic/admin/user/updateuserlogic.go @@ -5,6 +5,7 @@ import ( "PowerX/internal/model/powermodel" "PowerX/internal/types" "context" + "github.com/google/uuid" "github.com/pkg/errors" "time" @@ -28,9 +29,13 @@ func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Update } func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (resp *types.UpdateUserReply, err error) { + userUuid, err := uuid.Parse(req.Uuid) + if err != nil { + return nil, err + } user := organization.User{ - PowerModel: powermodel.PowerModel{ - Id: req.Id, + PowerUUIDModel: powermodel.PowerUUIDModel{ + UUID: userUuid, }, Name: req.Name, NickName: req.NickName, @@ -51,7 +56,7 @@ func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (resp *types. panic(errors.Wrap(err, "create user hash password failed")) } - if err := l.svcCtx.PowerX.Organization.UpdateUserById(l.ctx, &user, req.Id); err != nil { + if err := l.svcCtx.PowerX.Organization.UpdateUserByUuid(l.ctx, &user, req.Uuid); err != nil { return nil, err } diff --git a/internal/logic/web/customer/auth/registercustomerbyphoneininvitecodelogic.go b/internal/logic/web/customer/auth/registercustomerbyphoneininvitecodelogic.go index 6688af2d..9c4bb0d9 100644 --- a/internal/logic/web/customer/auth/registercustomerbyphoneininvitecodelogic.go +++ b/internal/logic/web/customer/auth/registercustomerbyphoneininvitecodelogic.go @@ -48,7 +48,7 @@ func (l *RegisterCustomerByPhoneInInviteCodeLogic) RegisterCustomerByPhoneInInvi customerTypeId := l.svcCtx.PowerX.DataDictionary.GetCachedDDId(l.ctx, customerdomain.TypeCustomerType, customerdomain.CustomerPersonal) // upsert 客户 - uuid := securityx.GenerateUUID() + uuid := securityx.GenerateUUIDString() inviteCode := securityx.GenerateInviteCode(uuid) customer := &customerdomain.Customer{ Mobile: req.Phone, diff --git a/internal/logic/web/customer/auth/registercustomerbyphoneinregistercodelogic.go b/internal/logic/web/customer/auth/registercustomerbyphoneinregistercodelogic.go index 80f01339..1ad44313 100644 --- a/internal/logic/web/customer/auth/registercustomerbyphoneinregistercodelogic.go +++ b/internal/logic/web/customer/auth/registercustomerbyphoneinregistercodelogic.go @@ -55,7 +55,7 @@ func (l *RegisterCustomerByPhoneInRegisterCodeLogic) RegisterCustomerByPhoneInRe customerTypeId := l.svcCtx.PowerX.DataDictionary.GetCachedDDId(l.ctx, customerdomain.TypeCustomerType, customerdomain.CustomerPersonal) // upsert 客户 - uuid := securityx.GenerateUUID() + uuid := securityx.GenerateUUIDString() inviteCode := securityx.GenerateInviteCode(uuid) customer := &customerdomain.Customer{ Mobile: req.Phone, diff --git a/internal/logic/web/customer/auth/registercustomerbyphonelogic.go b/internal/logic/web/customer/auth/registercustomerbyphonelogic.go index 2e932a3e..474da18f 100644 --- a/internal/logic/web/customer/auth/registercustomerbyphonelogic.go +++ b/internal/logic/web/customer/auth/registercustomerbyphonelogic.go @@ -42,7 +42,7 @@ func (l *RegisterCustomerByPhoneLogic) RegisterCustomerByPhone(req *types.Custom customerTypeId := l.svcCtx.PowerX.DataDictionary.GetCachedDDId(l.ctx, customerdomain.TypeCustomerType, customerdomain.CustomerPersonal) // upsert 客户 - uuid := securityx.GenerateUUID() + uuid := securityx.GenerateUUIDString() inviteCode := securityx.GenerateInviteCode(uuid) customer := &customerdomain.Customer{ Mobile: req.Phone, diff --git a/internal/model/media/mediaresource.go b/internal/model/media/mediaresource.go index 146422a5..4c1763f0 100644 --- a/internal/model/media/mediaresource.go +++ b/internal/model/media/mediaresource.go @@ -7,7 +7,7 @@ import ( ) type MediaResource struct { - powermodel.PowerModel + powermodel.PowerUUIDModel CustomerId int64 `gorm:"comment:客户Id; index" json:"customerId"` Filename string `gorm:"comment:名称" json:"filename"` @@ -25,7 +25,7 @@ type MediaSet struct { } func (mdl *MediaResource) TableName() string { - return model.PowerXSchema + "." + model.TableNameMediaResource + return "public." + model.TableNameMediaResource } func (mdl *MediaResource) GetTableName(needFull bool) string { diff --git a/internal/model/organization/department.go b/internal/model/organization/department.go index eaff941c..fd264e82 100644 --- a/internal/model/organization/department.go +++ b/internal/model/organization/department.go @@ -11,11 +11,11 @@ type Department struct { powermodel.PowerModel PDep *Department `gorm:"foreignKey:PId"` - Leader *User `gorm:"foreignKey:LeaderId"` + Leader *User `gorm:"foreignKey:LeaderUuid"` Ancestors []*Department `gorm:"many2many:department_ancestors;"` Name string `gorm:"comment:部门名称;column:name" json:"name"` PId int64 `gorm:"comment:部门名ID;column:pid" json:"pid"` - LeaderId int64 `gorm:"comment:领导ID;column:leader_id" json:"leader_id"` + LeaderUuid *string `gorm:"comment:领导ID;column:leader_id;type:uuid;default:null" json:"leader_id"` Desc string `gorm:"comment:描述;column:desc" json:"desc"` PhoneNumber string `gorm:"comment:部门电话;column:phone_number" json:"phone_number"` Email string `gorm:"comment:部门邮箱;column:email" json:"email"` diff --git a/internal/model/organization/user.go b/internal/model/organization/user.go index a2f272e1..965ebeda 100644 --- a/internal/model/organization/user.go +++ b/internal/model/organization/user.go @@ -10,9 +10,8 @@ import ( ) type User struct { - powermodel.PowerModel + powermodel.PowerUUIDModel - UUID string `json:"comment:唯一标识;column:uuid;unique;type:uuid" json:"uuid"` Account string `gorm:"comment:账户;column:account unique;type:varchar" json:"account"` Name string `gorm:"comment:名称;column:name;type:varchar" json:"name"` NickName string `gorm:"comment:别称;column:nick_name;type:varchar" json:"nick_name"` diff --git a/internal/model/powermodel/pivot.go b/internal/model/powermodel/pivot.go index d44b89e5..10187f40 100644 --- a/internal/model/powermodel/pivot.go +++ b/internal/model/powermodel/pivot.go @@ -4,6 +4,7 @@ import ( fmt2 "PowerX/pkg/printx" "errors" "fmt" + "github.com/google/uuid" "gorm.io/gorm" "gorm.io/gorm/clause" "time" @@ -47,7 +48,11 @@ func (mdl *PowerPivot) GetID() int64 { return mdl.Id } -func (mdl *PowerPivot) GetUUID() string { +func (mdl *PowerPivot) GetUUID() *uuid.UUID { + return nil +} + +func (mdl *PowerPivot) GetUUIDString() string { return "" } diff --git a/internal/model/powermodel/powermodel.go b/internal/model/powermodel/powermodel.go index 220ed8f4..b26f49cb 100644 --- a/internal/model/powermodel/powermodel.go +++ b/internal/model/powermodel/powermodel.go @@ -4,6 +4,7 @@ import ( "PowerX/pkg/securityx" "database/sql" "github.com/ArtisanCloud/PowerLibs/v3/object" + "github.com/google/uuid" "gorm.io/gorm" "gorm.io/gorm/clause" "gorm.io/gorm/schema" @@ -21,7 +22,8 @@ type ModelInterface interface { GetTableName(needFull bool) string GetPowerModel() ModelInterface GetID() int64 - GetUUID() string + GetUUID() *uuid.UUID + GetUUIDString() string GetPrimaryKey() string GetForeignRefer() string GetForeignReferValue() int64 @@ -37,7 +39,7 @@ type PowerModel struct { type PowerUUIDModel struct { Id int64 `gorm:"autoIncrement:true;unique; column:id; ->;<-:create" json:"-"` - UUID string `gorm:"primaryKey;autoIncrement:false;unique; column:uuid; ->;<-:create " json:"uuid" sql:"index"` + UUID uuid.UUID `gorm:"type:uuid;primaryKey;autoIncrement:false;unique; column:uuid; ->;<-:create " json:"uuid" sql:"index"` CreatedAt time.Time `gorm:"column:created_at; ->;<-:create " json:"createdAt"` UpdatedAt time.Time `gorm:"column:updated_at" json:"updatedAt"` DeletedAt gorm.DeletedAt `gorm:"index"` @@ -83,8 +85,12 @@ func (mdl *PowerUUIDModel) GetPowerModel() ModelInterface { return mdl } -func (mdl *PowerUUIDModel) GetUUID() string { - return mdl.UUID +func (mdl *PowerUUIDModel) GetUUID() *uuid.UUID { + return &mdl.UUID +} + +func (mdl *PowerUUIDModel) GetUUIDString() string { + return mdl.UUID.String() } func (mdl *PowerUUIDModel) GetPrimaryKey() string { @@ -113,7 +119,11 @@ func (mdl *PowerModel) GetPowerModel() ModelInterface { func (mdl *PowerModel) GetID() int64 { return mdl.Id } -func (mdl *PowerModel) GetUUID() string { +func (mdl *PowerModel) GetUUID() *uuid.UUID { + return nil +} + +func (mdl *PowerModel) GetUUIDString() string { return "" } @@ -344,7 +354,7 @@ func IsPowerModelLoaded(mdl ModelInterface) bool { return false } - if mdl.GetUUID() == "" { + if mdl.GetUUID() == nil { return false } diff --git a/internal/types/types.go b/internal/types/types.go index ec23d536..259eeed6 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -464,7 +464,7 @@ type CreateDepartmentReply struct { type CreateDepartmentRequest struct { DepName string `json:"depName"` - LeaderId int64 `json:"leaderId"` + LeaderUuid string `json:"leaderUuid"` PId int64 `json:"pId"` Desc string `json:"desc,optional"` PhoneNumber string `json:"phoneNumber,optional"` @@ -1063,11 +1063,11 @@ type DeleteTagRequest struct { } type DeleteUserReply struct { - Id int64 `json:"id"` + Uuid string `json:"uuid"` } type DeleteUserRequest struct { - Id int64 `path:"id"` + Uuid string `path:"uuid"` } type DeliveryAddress struct { @@ -1639,7 +1639,7 @@ type GetUserReply struct { } type GetUserRequest struct { - Id int64 `path:"id"` + Uuid string `path:"uuid"` } type GetVersionResponse struct { @@ -3062,7 +3062,7 @@ type ResetPasswordReply struct { } type ResetPasswordRequest struct { - UserId int64 `json:"userId"` + UserUuid string `json:"userUuid"` } type Resource struct { @@ -3426,7 +3426,7 @@ type UpdateUserReply struct { } type UpdateUserRequest struct { - Id int64 `path:"id"` + Uuid string `path:"uuid"` Name string `json:"name,optional"` NickName string `json:"nickName,optional"` Desc string `json:"desc,optional"` @@ -3647,7 +3647,7 @@ type WechatCustomersWithFollowUser struct { UserId string `json:"userId"` Remark string `json:"remark"` Description string `json:"description"` - CreatedTime int `json:"createtime"` + CreatedTime int `json:"createtime"` Tags []WechatCustomersFollowUserWithTags `json:"tags"` TagIds []string `json:"tagIds"` WechatChannels WechatCustomersFollowUserWithWechatChannels `json:"wechatChannels"` diff --git a/internal/uc/powerx/authorizationadmin.go b/internal/uc/powerx/authorizationadmin.go index 561f8bf5..91b586e8 100644 --- a/internal/uc/powerx/authorizationadmin.go +++ b/internal/uc/powerx/authorizationadmin.go @@ -4,6 +4,7 @@ import ( "PowerX/internal/config" "PowerX/internal/model/organization" "PowerX/internal/model/permission" + "PowerX/internal/model/powermodel" "PowerX/internal/types/errorx" "PowerX/pkg/mapx" "PowerX/pkg/slicex" @@ -162,7 +163,9 @@ func (uc *AdminPermsUseCase) Init() { rooName = "超级管理员" } root := organization.User{ - UUID: uuid.New().String(), + PowerUUIDModel: powermodel.PowerUUIDModel{ + UUID: uuid.New(), + }, Account: rooAccount, Password: rooPass, Name: rooName, diff --git a/internal/uc/powerx/crm/customerdomain/customer.go b/internal/uc/powerx/crm/customerdomain/customer.go index fcb7d357..9b9b7104 100644 --- a/internal/uc/powerx/crm/customerdomain/customer.go +++ b/internal/uc/powerx/crm/customerdomain/customer.go @@ -127,7 +127,7 @@ func (uc *CustomerUseCase) UpsertCustomer(ctx context.Context, customer *custome } // 如果是新增用户,那么需要给一个唯一识别号 if customer.Uuid == "" { - customer.Uuid = securityx.GenerateUUID() + customer.Uuid = securityx.GenerateUUIDString() err = powermodel.UpsertModelsOnUniqueID(tx, &customerdomain.Customer{}, customerdomain.CustomerUniqueId, customer, []string{"uuid"}, false) if err != nil { return err diff --git a/internal/uc/powerx/organization.go b/internal/uc/powerx/organization.go index a82850b7..9b4bb878 100644 --- a/internal/uc/powerx/organization.go +++ b/internal/uc/powerx/organization.go @@ -10,6 +10,7 @@ import ( "PowerX/pkg/slicex" "context" "fmt" + "github.com/google/uuid" "github.com/pkg/errors" "gorm.io/gorm" "gorm.io/gorm/clause" @@ -161,10 +162,27 @@ func (uc *OrganizationUseCase) FindOneUserById(ctx context.Context, id int64) (u return } -func (uc *OrganizationUseCase) UpdateUserById(ctx context.Context, user *organization.User, userId int64) error { +func (uc *OrganizationUseCase) FindOneUserByUuid(ctx context.Context, userUUid string) (user *organization.User, err error) { + if err = uc.db.WithContext(ctx). + Where("uuid = ?", userUUid). + Preload("Department"). + Preload("Position").First(&user).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, errorx.WithCause(errorx.ErrBadRequest, "用户不存在") + } + panic(err) + } + return +} + +func (uc *OrganizationUseCase) UpdateUserByUuid(ctx context.Context, user *organization.User, strUuid string) error { + userUuid, err := uuid.Parse(strUuid) + if err != nil { + return err + } whereCase := organization.User{ - PowerModel: powermodel.PowerModel{ - Id: userId, + PowerUUIDModel: powermodel.PowerUUIDModel{ + UUID: userUuid, }, IsReserved: false, } @@ -172,15 +190,17 @@ func (uc *OrganizationUseCase) UpdateUserById(ctx context.Context, user *organiz if result.RowsAffected == 0 { return errorx.WithCause(errorx.ErrBadRequest, "更新失败, 用户保留或不存在") } - err := result.Error + err = result.Error if err != nil { panic(errors.Wrap(err, "delete user failed")) } return nil } -func (uc *OrganizationUseCase) DeleteUserById(ctx context.Context, id int64) error { - result := uc.db.WithContext(ctx).Where(organization.User{IsReserved: false}, "is_reserved").Delete(&organization.User{}, id) +func (uc *OrganizationUseCase) DeleteUserByUuid(ctx context.Context, strUuid string) error { + result := uc.db.WithContext(ctx). + Where("uuid = ? AND is_reserved = ?", strUuid, false). + Delete(&organization.User{}) err := result.Error if err != nil { panic(errors.Wrap(err, "delete user failed")) diff --git a/pkg/securityx/security.go b/pkg/securityx/security.go index 7f5304b9..f4e10474 100644 --- a/pkg/securityx/security.go +++ b/pkg/securityx/security.go @@ -100,7 +100,10 @@ func CheckPassword(hashedPassword string, encodedPassword string) (isPasswordVal return true } -func GenerateUUID() string { +func GenerateUUID() uuid.UUID { + return uuid.New() +} +func GenerateUUIDString() string { return uuid.New().String() } From a57a94f5da644a133c52a027127d3a2a46dcfcdf Mon Sep 17 00:00:00 2001 From: Matrix-X Date: Wed, 9 Oct 2024 12:10:28 +0800 Subject: [PATCH 24/24] refact(model): seperate model with different schema --- internal/logic/admin/department/createdepartmentlogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/logic/admin/department/createdepartmentlogic.go b/internal/logic/admin/department/createdepartmentlogic.go index 84e26f6f..e1311785 100644 --- a/internal/logic/admin/department/createdepartmentlogic.go +++ b/internal/logic/admin/department/createdepartmentlogic.go @@ -27,7 +27,7 @@ func (l *CreateDepartmentLogic) CreateDepartment(req *types.CreateDepartmentRequ dep := organization.Department{ Name: req.DepName, PId: req.PId, - LeaderUuid: req.LeaderUuid, + LeaderUuid: &req.LeaderUuid, Desc: req.Desc, PhoneNumber: req.PhoneNumber, Email: req.Email,