@fudanda/create-arcbase 2.20261024.1-beta.2 → 2.20261107.1-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.runtime/npm/index.json +18 -18
- package/.runtime/sdk.json +3 -3
- package/LICENSE +21 -21
- package/README.md +99 -91
- package/cli.mjs +42 -39
- package/package.json +58 -53
- package/src/assistant.mjs +76 -0
- package/src/delivery.mjs +20 -20
- package/src/enhance.mjs +103 -104
- package/src/evolve.mjs +66 -66
- package/src/fields.mjs +73 -73
- package/src/goa-contracts.mjs +331 -331
- package/src/goa.mjs +202 -202
- package/src/history.mjs +16 -16
- package/src/layout.mjs +1 -1
- package/src/module.mjs +439 -477
- package/src/packages.mjs +12 -4
- package/src/page-antd.mjs +98 -77
- package/src/page-webmcp.mjs +51 -0
- package/src/project.mjs +112 -105
- package/src/records.mjs +15 -15
- package/src/release-vite.mjs +1 -0
- package/src/release.mjs +455 -0
- package/src/templates.mjs +20 -20
- package/src/upgrade.mjs +415 -249
- package/templates/module/02-migrations.go.txt +10 -10
- package/templates/module/03-service.go.txt +52 -52
- package/templates/module/04-module.go.txt +12 -12
- package/templates/module/06-queries.ts.txt +15 -15
- package/templates/module/08-service_test.go.txt +9 -9
- package/templates/module/09-TransferPanel.tsx.txt +16 -0
- package/templates/module-runtime-test.go.txt +86 -86
- package/templates/module-transfer.go.txt +74 -74
- package/templates/project-v2/.agents/skills/arcbase/SKILL.md +32 -0
- package/templates/project-v2/.agents/skills/goa-service-designer/SKILL.md +31 -0
- package/templates/project-v2/AGENTS.md +38 -0
- package/templates/project-v2/DEVELOPMENT.md +115 -84
- package/templates/project-v2/README.md +76 -74
- package/templates/project-v2/RELEASE.md +88 -0
- package/templates/project-v2/TEAM-TRIAL.md +32 -32
- package/templates/project-v2/arcbase.release.json +23 -0
- package/templates/project-v2/cmd/server/main.go +62 -36
- package/templates/project-v2/cmd/server/modules.gen.go +6 -6
- package/templates/project-v2/eslint.config.mjs +9 -9
- package/templates/project-v2/internal/dashboard/dist/README.txt +1 -1
- package/templates/project-v2/internal/dashboard/embed.go +11 -11
- package/templates/project-v2/package.json +11 -4
- package/templates/project-v2/scripts/application-version.mjs +138 -0
- package/templates/project-v2/scripts/assets.mjs +13 -11
- package/templates/project-v2/scripts/build-backend.mjs +11 -9
- package/templates/project-v2/scripts/build.mjs +12 -0
- package/templates/project-v2/scripts/check-generated.mjs +79 -48
- package/templates/project-v2/scripts/config.mjs +55 -54
- package/templates/project-v2/scripts/dev-watch.mjs +78 -78
- package/templates/project-v2/scripts/dev.mjs +50 -49
- package/templates/project-v2/scripts/doctor.mjs +94 -94
- package/templates/project-v2/scripts/generate-contracts.mjs +88 -88
- package/templates/project-v2/scripts/go-build-identity/main.go +210 -0
- package/templates/project-v2/scripts/go.mjs +17 -15
- package/templates/project-v2/scripts/layout.mjs +10 -10
- package/templates/project-v2/scripts/lifecycle.mjs +245 -245
- package/templates/project-v2/scripts/openobserve-build.mjs +115 -0
- package/templates/project-v2/scripts/project-info.mjs +105 -0
- package/templates/project-v2/scripts/release-metadata.mjs +13 -0
- package/templates/project-v2/scripts/release-vite.mjs +23 -0
- package/templates/project-v2/scripts/release.mjs +3 -0
- package/templates/project-v2/scripts/run.mjs +11 -11
- package/templates/project-v2/scripts/sdk-integrity.mjs +39 -39
- package/templates/project-v2/scripts/setup.mjs +44 -44
- package/templates/project-v2/web/admin/index.html +5 -5
- package/templates/project-v2/web/admin/package.json +3 -2
- package/templates/project-v2/web/admin/src/brand.json +1 -1
- package/templates/project-v2/web/admin/src/extensions.gen.ts +6 -6
- package/templates/project-v2/web/admin/src/extensions.ts +1 -1
- package/templates/project-v2/web/admin/src/main.tsx +20 -14
- package/templates/project-v2/web/admin/tsconfig.json +17 -17
- package/templates/project-v2/web/admin/vite.config.ts +47 -27
- package/src/page.mjs +0 -66
- package/templates/module/07-Page.tsx.txt +0 -20
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
package module
|
|
2
|
-
import ( "context"; arcbase "github.com/fudanda/arcbase/backend/v2" )
|
|
3
|
-
var migrations = []arcbase.HostMigration{{Version:1, PostgreSQL:[]string{__ARCBASE_0__},SQLite:[]string{__ARCBASE_1__}}}
|
|
4
|
-
func (*Module) Migrate(ctx context.Context, store *arcbase.Store) error { return store.HostData().MigrateModule(ctx,"__ARCBASE_2__",migrations) }
|
|
5
|
-
func (*Module) Check(ctx context.Context, store *arcbase.Store) error { return store.HostData().RequireModuleVersion(ctx,"__ARCBASE_3__",1) }
|
|
6
|
-
func (*Module) Seed(ctx context.Context, store *arcbase.Store) error { return store.HostData().SeedMenus(ctx,"__ARCBASE_4__",[]arcbase.HostMenuSeed{
|
|
7
|
-
{Name:"host:__ARCBASE_5__:root",Title:__ARCBASE_6__,Type:"directory",Icon:__ARCBASE_7__,Sort:10000},
|
|
8
|
-
{Name:"host:__ARCBASE_8__:records",Title:__ARCBASE_9__,Permission:"__ARCBASE_10__",Path:"__ARCBASE_11__",Component:"host:__ARCBASE_12__:records",Type:"menu",ParentName:"host:__ARCBASE_13__:root",Icon:__ARCBASE_14__,KeepAlive:true},
|
|
9
|
-
__ARCBASE_15__
|
|
10
|
-
}) }
|
|
1
|
+
package module
|
|
2
|
+
import ( "context"; arcbase "github.com/fudanda/arcbase/backend/v2" )
|
|
3
|
+
var migrations = []arcbase.HostMigration{{Version:1, PostgreSQL:[]string{__ARCBASE_0__},SQLite:[]string{__ARCBASE_1__}}}
|
|
4
|
+
func (*Module) Migrate(ctx context.Context, store *arcbase.Store) error { return store.HostData().MigrateModule(ctx,"__ARCBASE_2__",migrations) }
|
|
5
|
+
func (*Module) Check(ctx context.Context, store *arcbase.Store) error { return store.HostData().RequireModuleVersion(ctx,"__ARCBASE_3__",1) }
|
|
6
|
+
func (*Module) Seed(ctx context.Context, store *arcbase.Store) error { return store.HostData().SeedMenus(ctx,"__ARCBASE_4__",[]arcbase.HostMenuSeed{
|
|
7
|
+
{Name:"host:__ARCBASE_5__:root",Title:__ARCBASE_6__,Type:"directory",Icon:__ARCBASE_7__,Sort:10000},
|
|
8
|
+
{Name:"host:__ARCBASE_8__:records",Title:__ARCBASE_9__,Permission:"__ARCBASE_10__",Path:"__ARCBASE_11__",Component:"host:__ARCBASE_12__:records",Type:"menu",ParentName:"host:__ARCBASE_13__:root",Icon:__ARCBASE_14__,KeepAlive:true},
|
|
9
|
+
__ARCBASE_15__
|
|
10
|
+
}) }
|
|
@@ -1,52 +1,52 @@
|
|
|
1
|
-
package module
|
|
2
|
-
import (
|
|
3
|
-
"context"; "encoding/json"; "errors"; "time"; "reflect"; "strings"
|
|
4
|
-
"entgo.io/ent"; "entgo.io/ent/dialect"; entsql "entgo.io/ent/dialect/sql"
|
|
5
|
-
arcbase "github.com/fudanda/arcbase/backend/v2"
|
|
6
|
-
entity "__ARCBASE_0__/internal/ent"
|
|
7
|
-
"golang.org/x/sync/errgroup"
|
|
8
|
-
)
|
|
9
|
-
var ErrNotFound=errors.New("record not found")
|
|
10
|
-
var ErrConflict=errors.New("record conflict")
|
|
11
|
-
func classify(err error)error{if entity.IsConstraintError(err){return errors.Join(ErrConflict,err)};return err}
|
|
12
|
-
type Service struct { services arcbase.HostServices; client *entity.Client }
|
|
13
|
-
func newService(services arcbase.HostServices)*Service { return &Service{services,entity.NewClient(entity.Driver(services.Data.Driver()))} }
|
|
14
|
-
func(s *Service) query(ctx context.Context,client *entity.Client)(*entity.__ARCBASE_1__Query,error){
|
|
15
|
-
actor,ok:=arcbase.CurrentActor(ctx);if !ok{return nil,arcbase.ErrUnauthenticated};q:=client.__ARCBASE_2__.Query();__ARCBASE_3__;return q,nil
|
|
16
|
-
}
|
|
17
|
-
func view(row *entity.__ARCBASE_4__)map[string]any{
|
|
18
|
-
// Ent JSON tags omit zero values; reflect exported fields to preserve false/0.
|
|
19
|
-
raw:=map[string]any{};value:=reflect.ValueOf(row).Elem();for index:=0;index<value.NumField();index++{field:=value.Type().Field(index);if field.PkgPath!=""{continue};key:=strings.Split(field.Tag.Get("json"),",")[0];if key!=""&&key!="-"{raw[key]=value.Field(index).Interface()}}
|
|
20
|
-
result:=map[string]any{"id":row.ID,"createdBy":row.CreatedBy,"updatedBy":row.UpdatedBy,"createdAt":row.CreatedAt.UTC().Format(time.RFC3339Nano),"updatedAt":row.UpdatedAt.UTC().Format(time.RFC3339Nano)}
|
|
21
|
-
__ARCBASE_5__
|
|
22
|
-
return result
|
|
23
|
-
}
|
|
24
|
-
func payload(input any)(map[string]any,error){bytes,err:=json.Marshal(input);if err!=nil{return nil,err};var values map[string]any;err=json.Unmarshal(bytes,&values);return values,err}
|
|
25
|
-
type mutable interface{SetField(string,ent.Value)error;ClearField(string)error}
|
|
26
|
-
func assign(mutation mutable,values map[string]any)error{
|
|
27
|
-
for _,field:=range []struct{JSON,SQL,Kind string}{__ARCBASE_6__}{
|
|
28
|
-
value,exists:=values[field.JSON];if !exists{continue};if value==nil{if err:=mutation.ClearField(field.SQL);err!=nil{return err};continue}
|
|
29
|
-
if field.Kind=="int"{value=int(value.(float64))};if err:=mutation.SetField(field.SQL,value);err!=nil{return err}
|
|
30
|
-
};return nil
|
|
31
|
-
}
|
|
32
|
-
func(s *Service) List(ctx context.Context,page,size int,keyword string)(map[string]any,error){
|
|
33
|
-
if err:=s.services.Authorize(ctx,"__ARCBASE_7__");err!=nil{return nil,err}
|
|
34
|
-
q,err:=s.query(ctx,s.client);if err!=nil{return nil,err};__ARCBASE_8__
|
|
35
|
-
var total int;var rows []*entity.__ARCBASE_9__;group,cancelCtx:=errgroup.WithContext(ctx)
|
|
36
|
-
group.Go(func()error{var err error;total,err=q.Clone().Count(cancelCtx);return err})
|
|
37
|
-
group.Go(func()error{var err error;rows,err=q.Clone().Order(entity.Desc("id")).Offset((page-1)*size).Limit(size).All(cancelCtx);return err})
|
|
38
|
-
if err=group.Wait();err!=nil{return nil,err};list:=make([]map[string]any,0,len(rows));for _,row:=range rows{list=append(list,view(row))};return map[string]any{"list":list,"total":total,"page":page,"pageSize":size},nil
|
|
39
|
-
}
|
|
40
|
-
func(s *Service) Detail(ctx context.Context,id int)(map[string]any,error){if err:=s.services.Authorize(ctx,"__ARCBASE_10__");err!=nil{return nil,err};q,err:=s.query(ctx,s.client);if err!=nil{return nil,err};row,err:=q.Where(func(selector *entsql.Selector){selector.Where(entsql.EQ(selector.C("id"),id))}).Only(ctx);if entity.IsNotFound(err){return nil,ErrNotFound};if err!=nil{return nil,err};return view(row),nil}
|
|
41
|
-
func(s *Service) Create(ctx context.Context,input any)(map[string]any,error){
|
|
42
|
-
if err:=s.services.Authorize(ctx,"__ARCBASE_11__");err!=nil{return nil,err};actor,ok:=arcbase.CurrentActor(ctx);if !ok{return nil,arcbase.ErrUnauthenticated};values,err:=payload(input);if err!=nil{return nil,err};var saved *entity.__ARCBASE_12__
|
|
43
|
-
err=s.services.Data.Write(ctx,"__ARCBASE_13__","create","__ARCBASE_14__",func(driver dialect.Driver)(int,error){client:=entity.NewClient(entity.Driver(driver));builder:=client.__ARCBASE_15__.Create().SetCreatedBy(actor.UserID).SetUpdatedBy(actor.UserID);if err:=assign(builder.Mutation(),values);err!=nil{return 0,err};var err error;saved,err=builder.Save(ctx);if err!=nil{return 0,err};return saved.ID,nil});if err!=nil{return nil,classify(err)};return view(saved),nil
|
|
44
|
-
}
|
|
45
|
-
func(s *Service) Update(ctx context.Context,id int,input any)(map[string]any,error){
|
|
46
|
-
if err:=s.services.Authorize(ctx,"__ARCBASE_16__");err!=nil{return nil,err};actor,ok:=arcbase.CurrentActor(ctx);if !ok{return nil,arcbase.ErrUnauthenticated};values,err:=payload(input);if err!=nil{return nil,err};var saved *entity.__ARCBASE_17__
|
|
47
|
-
err=s.services.Data.Write(ctx,"__ARCBASE_18__","update","__ARCBASE_19__",func(driver dialect.Driver)(int,error){client:=entity.NewClient(entity.Driver(driver));q,err:=s.query(ctx,client);if err!=nil{return 0,err};row,err:=q.Where(func(selector *entsql.Selector){selector.Where(entsql.EQ(selector.C("id"),id))}).Only(ctx);if entity.IsNotFound(err){return 0,ErrNotFound};if err!=nil{return 0,err};builder:=client.__ARCBASE_20__.UpdateOneID(row.ID).SetUpdatedBy(actor.UserID);if err=assign(builder.Mutation(),values);err!=nil{return 0,err};saved,err=builder.Save(ctx);return id,err});if err!=nil{return nil,classify(err)};return view(saved),nil
|
|
48
|
-
}
|
|
49
|
-
func(s *Service) Remove(ctx context.Context,id int)error{
|
|
50
|
-
if err:=s.services.Authorize(ctx,"__ARCBASE_21__");err!=nil{return err}
|
|
51
|
-
return s.services.Data.Write(ctx,"__ARCBASE_22__","remove","__ARCBASE_23__",func(driver dialect.Driver)(int,error){client:=entity.NewClient(entity.Driver(driver));q,err:=s.query(ctx,client);if err!=nil{return 0,err};row,err:=q.Where(func(selector *entsql.Selector){selector.Where(entsql.EQ(selector.C("id"),id))}).Only(ctx);if entity.IsNotFound(err){return 0,ErrNotFound};if err!=nil{return 0,err};return id,client.__ARCBASE_24__.DeleteOneID(row.ID).Exec(ctx)})
|
|
52
|
-
}
|
|
1
|
+
package module
|
|
2
|
+
import (
|
|
3
|
+
"context"; "encoding/json"; "errors"; "time"; "reflect"; "strings"
|
|
4
|
+
"entgo.io/ent"; "entgo.io/ent/dialect"; entsql "entgo.io/ent/dialect/sql"
|
|
5
|
+
arcbase "github.com/fudanda/arcbase/backend/v2"
|
|
6
|
+
entity "__ARCBASE_0__/internal/ent"
|
|
7
|
+
"golang.org/x/sync/errgroup"
|
|
8
|
+
)
|
|
9
|
+
var ErrNotFound=errors.New("record not found")
|
|
10
|
+
var ErrConflict=errors.New("record conflict")
|
|
11
|
+
func classify(err error)error{if entity.IsConstraintError(err){return errors.Join(ErrConflict,err)};return err}
|
|
12
|
+
type Service struct { services arcbase.HostServices; client *entity.Client }
|
|
13
|
+
func newService(services arcbase.HostServices)*Service { return &Service{services,entity.NewClient(entity.Driver(services.Data.Driver()))} }
|
|
14
|
+
func(s *Service) query(ctx context.Context,client *entity.Client)(*entity.__ARCBASE_1__Query,error){
|
|
15
|
+
actor,ok:=arcbase.CurrentActor(ctx);if !ok{return nil,arcbase.ErrUnauthenticated};q:=client.__ARCBASE_2__.Query();__ARCBASE_3__;return q,nil
|
|
16
|
+
}
|
|
17
|
+
func view(row *entity.__ARCBASE_4__)map[string]any{
|
|
18
|
+
// Ent JSON tags omit zero values; reflect exported fields to preserve false/0.
|
|
19
|
+
raw:=map[string]any{};value:=reflect.ValueOf(row).Elem();for index:=0;index<value.NumField();index++{field:=value.Type().Field(index);if field.PkgPath!=""{continue};key:=strings.Split(field.Tag.Get("json"),",")[0];if key!=""&&key!="-"{raw[key]=value.Field(index).Interface()}}
|
|
20
|
+
result:=map[string]any{"id":row.ID,"createdBy":row.CreatedBy,"updatedBy":row.UpdatedBy,"createdAt":row.CreatedAt.UTC().Format(time.RFC3339Nano),"updatedAt":row.UpdatedAt.UTC().Format(time.RFC3339Nano)}
|
|
21
|
+
__ARCBASE_5__
|
|
22
|
+
return result
|
|
23
|
+
}
|
|
24
|
+
func payload(input any)(map[string]any,error){bytes,err:=json.Marshal(input);if err!=nil{return nil,err};var values map[string]any;err=json.Unmarshal(bytes,&values);return values,err}
|
|
25
|
+
type mutable interface{SetField(string,ent.Value)error;ClearField(string)error}
|
|
26
|
+
func assign(mutation mutable,values map[string]any)error{
|
|
27
|
+
for _,field:=range []struct{JSON,SQL,Kind string}{__ARCBASE_6__}{
|
|
28
|
+
value,exists:=values[field.JSON];if !exists{continue};if value==nil{if err:=mutation.ClearField(field.SQL);err!=nil{return err};continue}
|
|
29
|
+
if field.Kind=="int"{value=int(value.(float64))};if err:=mutation.SetField(field.SQL,value);err!=nil{return err}
|
|
30
|
+
};return nil
|
|
31
|
+
}
|
|
32
|
+
func(s *Service) List(ctx context.Context,page,size int,keyword string)(map[string]any,error){
|
|
33
|
+
if err:=s.services.Authorize(ctx,"__ARCBASE_7__");err!=nil{return nil,err}
|
|
34
|
+
q,err:=s.query(ctx,s.client);if err!=nil{return nil,err};__ARCBASE_8__
|
|
35
|
+
var total int;var rows []*entity.__ARCBASE_9__;group,cancelCtx:=errgroup.WithContext(ctx)
|
|
36
|
+
group.Go(func()error{var err error;total,err=q.Clone().Count(cancelCtx);return err})
|
|
37
|
+
group.Go(func()error{var err error;rows,err=q.Clone().Order(entity.Desc("id")).Offset((page-1)*size).Limit(size).All(cancelCtx);return err})
|
|
38
|
+
if err=group.Wait();err!=nil{return nil,err};list:=make([]map[string]any,0,len(rows));for _,row:=range rows{list=append(list,view(row))};return map[string]any{"list":list,"total":total,"page":page,"pageSize":size},nil
|
|
39
|
+
}
|
|
40
|
+
func(s *Service) Detail(ctx context.Context,id int)(map[string]any,error){if err:=s.services.Authorize(ctx,"__ARCBASE_10__");err!=nil{return nil,err};q,err:=s.query(ctx,s.client);if err!=nil{return nil,err};row,err:=q.Where(func(selector *entsql.Selector){selector.Where(entsql.EQ(selector.C("id"),id))}).Only(ctx);if entity.IsNotFound(err){return nil,ErrNotFound};if err!=nil{return nil,err};return view(row),nil}
|
|
41
|
+
func(s *Service) Create(ctx context.Context,input any)(map[string]any,error){
|
|
42
|
+
if err:=s.services.Authorize(ctx,"__ARCBASE_11__");err!=nil{return nil,err};actor,ok:=arcbase.CurrentActor(ctx);if !ok{return nil,arcbase.ErrUnauthenticated};values,err:=payload(input);if err!=nil{return nil,err};var saved *entity.__ARCBASE_12__
|
|
43
|
+
err=s.services.Data.Write(ctx,"__ARCBASE_13__","create","__ARCBASE_14__",func(driver dialect.Driver)(int,error){client:=entity.NewClient(entity.Driver(driver));builder:=client.__ARCBASE_15__.Create().SetCreatedBy(actor.UserID).SetUpdatedBy(actor.UserID);if err:=assign(builder.Mutation(),values);err!=nil{return 0,err};var err error;saved,err=builder.Save(ctx);if err!=nil{return 0,err};return saved.ID,nil});if err!=nil{return nil,classify(err)};return view(saved),nil
|
|
44
|
+
}
|
|
45
|
+
func(s *Service) Update(ctx context.Context,id int,input any)(map[string]any,error){
|
|
46
|
+
if err:=s.services.Authorize(ctx,"__ARCBASE_16__");err!=nil{return nil,err};actor,ok:=arcbase.CurrentActor(ctx);if !ok{return nil,arcbase.ErrUnauthenticated};values,err:=payload(input);if err!=nil{return nil,err};var saved *entity.__ARCBASE_17__
|
|
47
|
+
err=s.services.Data.Write(ctx,"__ARCBASE_18__","update","__ARCBASE_19__",func(driver dialect.Driver)(int,error){client:=entity.NewClient(entity.Driver(driver));q,err:=s.query(ctx,client);if err!=nil{return 0,err};row,err:=q.Where(func(selector *entsql.Selector){selector.Where(entsql.EQ(selector.C("id"),id))}).Only(ctx);if entity.IsNotFound(err){return 0,ErrNotFound};if err!=nil{return 0,err};builder:=client.__ARCBASE_20__.UpdateOneID(row.ID).SetUpdatedBy(actor.UserID);if err=assign(builder.Mutation(),values);err!=nil{return 0,err};saved,err=builder.Save(ctx);return id,err});if err!=nil{return nil,classify(err)};return view(saved),nil
|
|
48
|
+
}
|
|
49
|
+
func(s *Service) Remove(ctx context.Context,id int)error{
|
|
50
|
+
if err:=s.services.Authorize(ctx,"__ARCBASE_21__");err!=nil{return err}
|
|
51
|
+
return s.services.Data.Write(ctx,"__ARCBASE_22__","remove","__ARCBASE_23__",func(driver dialect.Driver)(int,error){client:=entity.NewClient(entity.Driver(driver));q,err:=s.query(ctx,client);if err!=nil{return 0,err};row,err:=q.Where(func(selector *entsql.Selector){selector.Where(entsql.EQ(selector.C("id"),id))}).Only(ctx);if entity.IsNotFound(err){return 0,ErrNotFound};if err!=nil{return 0,err};return id,client.__ARCBASE_24__.DeleteOneID(row.ID).Exec(ctx)})
|
|
52
|
+
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
package module
|
|
2
|
-
import ( "context"; arcbase "github.com/fudanda/arcbase/backend/v2" )
|
|
3
|
-
type Module struct { services arcbase.HostServices; service *Service }
|
|
4
|
-
func(*Module)Name()string{return "__ARCBASE_0__"}
|
|
5
|
-
func(*Module)Dependencies()[]string{return []string{"authorization"}}
|
|
6
|
-
func(m *Module)BindServices(services arcbase.HostServices)error{m.services=services;return nil}
|
|
7
|
-
func(m *Module)Shutdown(context.Context)error{if m.service!=nil{return m.service.client.Close()};return nil}
|
|
8
|
-
func(*Module)Extension()arcbase.ExtensionDefinition{return arcbase.ExtensionDefinition{Pages:[]arcbase.ExtensionPage{{ID:"records",Path:"__ARCBASE_1__",Permission:"__ARCBASE_2__"}},Permissions:[]string{__ARCBASE_3__},Resources:[]arcbase.ExtensionResource{{Name:"__ARCBASE_4__",Permission:"__ARCBASE_5__"}}}}
|
|
9
|
-
func(m *Module)Initialize(ctx context.Context,reg *arcbase.Registrar)error{
|
|
10
|
-
if err:=m.services.Data.RequireModuleVersion(ctx,"__ARCBASE_6__",1);err!=nil{return err};m.service=newService(m.services)
|
|
11
|
-
return m.mountNative(reg)
|
|
12
|
-
}
|
|
1
|
+
package module
|
|
2
|
+
import ( "context"; arcbase "github.com/fudanda/arcbase/backend/v2" )
|
|
3
|
+
type Module struct { services arcbase.HostServices; service *Service }
|
|
4
|
+
func(*Module)Name()string{return "__ARCBASE_0__"}
|
|
5
|
+
func(*Module)Dependencies()[]string{return []string{"authorization"}}
|
|
6
|
+
func(m *Module)BindServices(services arcbase.HostServices)error{m.services=services;return nil}
|
|
7
|
+
func(m *Module)Shutdown(context.Context)error{if m.service!=nil{return m.service.client.Close()};return nil}
|
|
8
|
+
func(*Module)Extension()arcbase.ExtensionDefinition{return arcbase.ExtensionDefinition{Pages:[]arcbase.ExtensionPage{{ID:"records",Path:"__ARCBASE_1__",Permission:"__ARCBASE_2__"}},Permissions:[]string{__ARCBASE_3__},Resources:[]arcbase.ExtensionResource{{Name:"__ARCBASE_4__",Permission:"__ARCBASE_5__"}}}}
|
|
9
|
+
func(m *Module)Initialize(ctx context.Context,reg *arcbase.Registrar)error{
|
|
10
|
+
if err:=m.services.Data.RequireModuleVersion(ctx,"__ARCBASE_6__",1);err!=nil{return err};m.service=newService(m.services)
|
|
11
|
+
return m.mountNative(reg)
|
|
12
|
+
}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import type { GoaClient } from '@fudanda/client';
|
|
2
|
-
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
3
|
-
import type { GoaBodyOf } from '@fudanda/shared/core';
|
|
4
|
-
import { contractKey } from '@fudanda/react-core/lib/contract-query';
|
|
5
|
-
import { contract } from './contracts.ts';
|
|
6
|
-
const listKey=contractKey(contract.list);const lookupKey=contractKey(contract.lookup);
|
|
7
|
-
// Admin's single RealtimeBridge invalidates the generated extension query roots.
|
|
8
|
-
export function useRecords(client:GoaClient,page:number,pageSize:number,keyword:string){
|
|
9
|
-
return useQuery({queryKey:contractKey(contract.list,{query:{page,pageSize,keyword}}),queryFn:({signal})=>client.call(contract.list,{query:{page,pageSize,keyword}},{signal})});
|
|
10
|
-
}
|
|
11
|
-
export function useRecordMutations(client:GoaClient){const cache=useQueryClient();const refresh=()=>{void cache.invalidateQueries({queryKey:listKey});void cache.invalidateQueries({queryKey:lookupKey});};return {
|
|
12
|
-
create:useMutation({mutationFn:(body:GoaBodyOf<typeof contract.create>)=>client.call(contract.create,{body}),onSuccess:refresh}),
|
|
13
|
-
update:useMutation({mutationFn:({id,body}:{id:number;body:GoaBodyOf<typeof contract.update>})=>client.call(contract.update,{params:{id},body}),onSuccess:(_saved,input)=>{refresh();void cache.invalidateQueries({queryKey:contractKey(contract.detail,{params:{id:input.id}})});}}),
|
|
14
|
-
remove:useMutation({mutationFn:(id:number)=>client.call(contract.remove,{params:{id}}),onSuccess:(_saved,id)=>{refresh();cache.removeQueries({queryKey:contractKey(contract.detail,{params:{id}})});}}),
|
|
15
|
-
};}
|
|
1
|
+
import type { GoaClient } from '@fudanda/client';
|
|
2
|
+
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
3
|
+
import type { GoaBodyOf } from '@fudanda/shared/core';
|
|
4
|
+
import { contractKey } from '@fudanda/react-core/lib/contract-query';
|
|
5
|
+
import { contract } from './contracts.ts';
|
|
6
|
+
const listKey=contractKey(contract.list);const lookupKey=contractKey(contract.lookup);
|
|
7
|
+
// Admin's single RealtimeBridge invalidates the generated extension query roots.
|
|
8
|
+
export function useRecords(client:GoaClient,page:number,pageSize:number,keyword:string){
|
|
9
|
+
return useQuery({queryKey:contractKey(contract.list,{query:{page,pageSize,keyword}}),queryFn:({signal})=>client.call(contract.list,{query:{page,pageSize,keyword}},{signal})});
|
|
10
|
+
}
|
|
11
|
+
export function useRecordMutations(client:GoaClient){const cache=useQueryClient();const refresh=()=>{void cache.invalidateQueries({queryKey:listKey});void cache.invalidateQueries({queryKey:lookupKey});};return {
|
|
12
|
+
create:useMutation({retry:false,mutationFn:(body:GoaBodyOf<typeof contract.create>)=>client.call(contract.create,{body}),onSuccess:refresh}),
|
|
13
|
+
update:useMutation({retry:false,mutationFn:({id,body}:{id:number;body:GoaBodyOf<typeof contract.update>})=>client.call(contract.update,{params:{id},body}),onSuccess:(_saved,input)=>{refresh();void cache.invalidateQueries({queryKey:contractKey(contract.detail,{params:{id:input.id}})});}}),
|
|
14
|
+
remove:useMutation({retry:false,mutationFn:(id:number)=>client.call(contract.remove,{params:{id}}),onSuccess:(_saved,id)=>{refresh();cache.removeQueries({queryKey:contractKey(contract.detail,{params:{id}})});}}),
|
|
15
|
+
};}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
package module
|
|
2
|
-
import ("context";"path/filepath";"testing";arcbase "github.com/fudanda/arcbase/backend/v2")
|
|
3
|
-
func TestMigrationAndAuditTransaction(t *testing.T){
|
|
4
|
-
ctx:=context.Background();store,err:=arcbase.OpenStore(ctx,"sqlite:"+filepath.Join(t.TempDir(),"module.db"));if err!=nil{t.Fatal(err)};defer store.Close();if err=store.Migrate(ctx);err!=nil{t.Fatal(err)}
|
|
5
|
-
module:=&Module{};for i:=0;i<2;i++{if err=module.Migrate(ctx,store);err!=nil{t.Fatal(err)}}
|
|
6
|
-
if err=store.HostData().RequireModuleVersion(ctx,"__ARCBASE_0__",1);err!=nil{t.Fatal(err)}
|
|
7
|
-
changed:=append([]arcbase.HostMigration{},migrations...);changed[0].SQLite=append([]string{},migrations[0].SQLite...);changed[0].SQLite[0]+=" ";if err=store.HostData().MigrateModule(ctx,"__ARCBASE_1__",changed);err==nil{t.Fatal("changed published migration accepted")}
|
|
8
|
-
if err=store.HostData().Write(ctx,"__ARCBASE_2__","create","__ARCBASE_3__",nil);err!=arcbase.ErrUnauthenticated{t.Fatal("unauthenticated host write accepted")}
|
|
9
|
-
}
|
|
1
|
+
package module
|
|
2
|
+
import ("context";"path/filepath";"testing";arcbase "github.com/fudanda/arcbase/backend/v2")
|
|
3
|
+
func TestMigrationAndAuditTransaction(t *testing.T){
|
|
4
|
+
ctx:=context.Background();store,err:=arcbase.OpenStore(ctx,"sqlite:"+filepath.Join(t.TempDir(),"module.db"));if err!=nil{t.Fatal(err)};defer store.Close();if err=store.Migrate(ctx);err!=nil{t.Fatal(err)}
|
|
5
|
+
module:=&Module{};for i:=0;i<2;i++{if err=module.Migrate(ctx,store);err!=nil{t.Fatal(err)}}
|
|
6
|
+
if err=store.HostData().RequireModuleVersion(ctx,"__ARCBASE_0__",1);err!=nil{t.Fatal(err)}
|
|
7
|
+
changed:=append([]arcbase.HostMigration{},migrations...);changed[0].SQLite=append([]string{},migrations[0].SQLite...);changed[0].SQLite[0]+=" ";if err=store.HostData().MigrateModule(ctx,"__ARCBASE_1__",changed);err==nil{t.Fatal("changed published migration accepted")}
|
|
8
|
+
if err=store.HostData().Write(ctx,"__ARCBASE_2__","create","__ARCBASE_3__",nil);err!=arcbase.ErrUnauthenticated{t.Fatal("unauthenticated host write accepted")}
|
|
9
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {useState} from 'react';
|
|
2
|
+
import {Button,Modal,Select,Space,Table} from 'antd';
|
|
3
|
+
import {PermissionGuard} from '@fudanda/admin-antd/hooks';
|
|
4
|
+
import type {GoaClient} from '@fudanda/client';
|
|
5
|
+
import {useMutation,useQueryClient} from '@tanstack/react-query';
|
|
6
|
+
import {contractKey} from '@fudanda/admin-antd/core/lib/contract-query';
|
|
7
|
+
import {contract,type ImportResult} from './contracts.ts';
|
|
8
|
+
import {permissions} from './permissions.ts';
|
|
9
|
+
function save(blob:Blob,name:string){const url=URL.createObjectURL(blob);const link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
|
|
10
|
+
export function TransferPanel({client,keyword}:{client:GoaClient;keyword:string}){
|
|
11
|
+
const [open,setOpen]=useState(false);const [file,setFile]=useState<File|null>(null);const [duplicate,setDuplicate]=useState<'error'|'skip'>('error');const [result,setResult]=useState<ImportResult|null>(null);const [error,setError]=useState<Error|null>(null);const [downloading,setDownloading]=useState(false);const cache=useQueryClient();
|
|
12
|
+
const upload=useMutation({mutationFn:async(dryRun:boolean)=>{if(!file)throw new Error('请选择文件');if(file.size>5*1024*1024)throw new Error('文件不得超过 5 MiB');const format=file.name.toLowerCase().endsWith('.xlsx')?'xlsx':file.name.toLowerCase().endsWith('.csv')?'csv':null;if(!format)throw new Error('请选择 CSV 或 XLSX');return client.upload(contract.importRecords,{body:{file},query:{format,dryRun,duplicate}});},onSuccess:result=>{setResult(result);if(!result.dryRun){void cache.invalidateQueries({queryKey:contractKey(contract.list)});void cache.invalidateQueries({queryKey:contractKey(contract.lookup)});void cache.invalidateQueries({queryKey:contractKey(contract.detail)});}}});
|
|
13
|
+
async function download(template:boolean,format:'csv'|'xlsx'){try{setDownloading(true);setError(null);const op=template?contract.importTemplate:contract.exportRecords;const response=await client.download(op,{query:template?{format}:{format,keyword}});save(await response.blob(),(template?'import-template':'records')+'.'+format);}catch(error){setError(error instanceof Error?error:new Error('下载失败'));}finally{setDownloading(false);}}
|
|
14
|
+
return <><PermissionGuard permission={permissions.exportRecords}><Button disabled={downloading} loading={downloading} onClick={()=>void download(false,'csv')}>导出 CSV</Button><Button disabled={downloading} loading={downloading} onClick={()=>void download(false,'xlsx')}>导出 XLSX</Button></PermissionGuard><PermissionGuard permission={permissions.importRecords}><Button onClick={()=>{setOpen(true);setResult(null);setError(null);}}>导入</Button></PermissionGuard>{error&&<span role="alert">{error.message}</span>}
|
|
15
|
+
<Modal title="导入记录" open={open} footer={null} onCancel={()=>setOpen(false)}><Space wrap><Button disabled={downloading} loading={downloading} onClick={()=>void download(true,'xlsx')}>下载模板</Button><input aria-label="导入文件" type="file" accept=".csv,.xlsx" onChange={event=>{setFile(event.target.files?.[0]??null);setResult(null);}}/><Select aria-label="重复记录处理" value={duplicate} onChange={value=>{setDuplicate(value==='skip'?'skip':'error');setResult(null);}} options={[{value:'error',label:'重复时报错'},{value:'skip',label:'跳过重复记录'}]}/><Button disabled={!file} loading={upload.isPending} onClick={()=>{setError(null);upload.mutate(true);}}>预检</Button><Button type="primary" disabled={!file} loading={upload.isPending} onClick={()=>{setError(null);upload.mutate(false);}}>导入</Button></Space>{upload.error&&<div role="alert">{upload.error.message}</div>}{result&&<><p>{result.dryRun?'预检':'导入'}:成功 {result.success},失败 {result.failed},跳过 {result.skipped}</p><Table rowKey="row" dataSource={result.rows} columns={[{title:'行',dataIndex:'row',width:70},{title:'状态',dataIndex:'status',width:100},{title:'结果',dataIndex:'message'}]} pagination={{pageSize:20}}/></>}</Modal></>;
|
|
16
|
+
}
|
|
@@ -1,86 +1,86 @@
|
|
|
1
|
-
package module
|
|
2
|
-
|
|
3
|
-
import (
|
|
4
|
-
"bytes"
|
|
5
|
-
"context"
|
|
6
|
-
"crypto/rand"
|
|
7
|
-
"encoding/base64"
|
|
8
|
-
"encoding/json"
|
|
9
|
-
"fmt"
|
|
10
|
-
"net/http"
|
|
11
|
-
"net/http/cookiejar"
|
|
12
|
-
"net/http/httptest"
|
|
13
|
-
"net/url"
|
|
14
|
-
"os"
|
|
15
|
-
"path/filepath"
|
|
16
|
-
"regexp"
|
|
17
|
-
"strings"
|
|
18
|
-
"testing"
|
|
19
|
-
"time"
|
|
20
|
-
arcbase "github.com/fudanda/arcbase/backend/v2"
|
|
21
|
-
"github.com/fudanda/arcbase/backend/v2/ent/user"
|
|
22
|
-
"github.com/fudanda/arcbase/backend/v2/ent/userrole"
|
|
23
|
-
"github.com/fudanda/arcbase/backend/v2/ent/menu"
|
|
24
|
-
"github.com/fudanda/arcbase/backend/v2/ent/auditlog"
|
|
25
|
-
"github.com/fudanda/arcbase/backend/v2/ent/usermenu"
|
|
26
|
-
)
|
|
27
|
-
|
|
28
|
-
func TestGeneratedHTTPPermissionsScopeValidationAndAudit(t *testing.T) {
|
|
29
|
-
ctx:=context.Background();dsn:="sqlite:"+filepath.Join(t.TempDir(),"http.db")
|
|
30
|
-
if value:=os.Getenv("ARCBASE_TEST_DATABASE_URL");strings.HasPrefix(value,"postgres") {
|
|
31
|
-
admin,err:=arcbase.OpenStore(ctx,value);if err!=nil{t.Fatal(err)}
|
|
32
|
-
schema:=fmt.Sprintf("arcbase_generated_%d",time.Now().UnixNano());if _,err=admin.DB.ExecContext(ctx,"CREATE SCHEMA "+schema);err!=nil{t.Fatal(err)}
|
|
33
|
-
t.Cleanup(func(){admin.DB.ExecContext(context.Background(),"DROP SCHEMA "+schema+" CASCADE");admin.Close()})
|
|
34
|
-
parsed,_:=url.Parse(value);query:=parsed.Query();query.Set("search_path",schema);parsed.RawQuery=query.Encode();dsn=parsed.String()
|
|
35
|
-
}
|
|
36
|
-
store,err:=arcbase.OpenStore(ctx,dsn);if err!=nil{t.Fatal(err)};defer store.Close()
|
|
37
|
-
if err=store.Migrate(ctx);err!=nil{t.Fatal(err)};if err=store.Seed(ctx);err!=nil{t.Fatal(err)}
|
|
38
|
-
module:=&Module{};if err=module.Migrate(ctx,store);err!=nil{t.Fatal(err)};if err=module.Seed(ctx,store);err!=nil{t.Fatal(err)};if err=module.Seed(ctx,store);err!=nil{t.Fatal(err)}
|
|
39
|
-
password:="Aa1!"+rand.Text();for _,name:=range []string{"admin","owner","other"}{if err=store.InitAdmin(ctx,name,password);err!=nil{t.Fatal(err)}}
|
|
40
|
-
for _,name:=range []string{"owner","other"} {
|
|
41
|
-
account,err:=store.Client.User.Query().Where(user.UsernameEQ(name)).Only(ctx);if err!=nil{t.Fatal(err)}
|
|
42
|
-
if _,err=store.Client.UserRole.Delete().Where(userrole.UserIDEQ(account.ID)).Exec(ctx);err!=nil{t.Fatal(err)}
|
|
43
|
-
rows,err:=store.Client.Menu.Query().Where(menu.PermissionHasPrefix("host:__MODULE__:" )).All(ctx);if err!=nil{t.Fatal(err)}
|
|
44
|
-
for _,row:=range rows{if err=store.Client.UserMenu.Create().SetUserID(account.ID).SetMenuID(row.ID).Exec(ctx);err!=nil{t.Fatal(err)}}
|
|
45
|
-
}
|
|
46
|
-
framework,err:=arcbase.New(ctx,arcbase.Config{DSN:dsn,Modules:[]arcbase.Module{module}});if err!=nil{t.Fatal(err)}
|
|
47
|
-
server:=httptest.NewServer(framework.Handler());defer server.Close();defer framework.Shutdown(ctx)
|
|
48
|
-
call:=func(client *http.Client,method,path string,body any,csrf string)(int,map[string]any){
|
|
49
|
-
raw,_:=json.Marshal(body);r,_:=http.NewRequest(method,server.URL+path,bytes.NewReader(raw));r.Header.Set("Content-Type","application/json");r.Header.Set("Origin",server.URL);if csrf!=""{r.Header.Set("X-CSRF-Token",csrf)}
|
|
50
|
-
response,err:=client.Do(r);if err!=nil{t.Fatal(err)};defer response.Body.Close();payload:=map[string]any{};json.NewDecoder(response.Body).Decode(&payload);return response.StatusCode,payload
|
|
51
|
-
}
|
|
52
|
-
login:=func(name string)(*http.Client,string){jar,_:=cookiejar.New(nil);client:=&http.Client{Jar:jar};status,payload:=call(client,"GET","/api/v1/auth/captcha",nil,"");if status!=200{t.Fatal(status)}
|
|
53
|
-
enabled,ok:=payload["enabled"].(bool);if !ok{t.Fatal("captcha response omitted enabled")};body:=map[string]any{"username":name,"password":password}
|
|
54
|
-
if enabled{
|
|
55
|
-
image,ok:=payload["image"].(string);if !ok{t.Fatal("enabled captcha omitted image")};parts:=strings.SplitN(image,",",2);if len(parts)!=2||parts[0]!="data:image/svg+xml;base64"{t.Fatal("invalid captcha image")}
|
|
56
|
-
svg,err:=base64.StdEncoding.DecodeString(parts[1]);if err!=nil{t.Fatal("invalid captcha encoding")};answer:=regexp.MustCompile(`>([A-F0-9]{4,8})</text>`).FindSubmatch(svg);if len(answer)!=2{t.Fatal("enabled captcha has no answer")}
|
|
57
|
-
captchaID,ok:=payload["captchaId"].(string);if !ok||captchaID==""{t.Fatal("enabled captcha omitted ID")};body["captchaId"],body["captchaAnswer"]=captchaID,string(answer[1])
|
|
58
|
-
}else{_,hasImage:=payload["image"];_,hasID:=payload["captchaId"];if hasImage||hasID{t.Fatal("disabled captcha exposed challenge fields")}}
|
|
59
|
-
status,payload=call(client,"POST","/api/v1/auth/login",body,"");if status!=200{t.Fatal("login",status,payload["message"])}
|
|
60
|
-
outcome,ok:=payload["outcome"].(map[string]any);if !ok||outcome["type"]!="session"{t.Fatal("login did not establish a session")};value,ok:=outcome["value"].(map[string]any);if !ok{t.Fatal("session result is missing")};csrf,ok:=value["csrfToken"].(string);if !ok||csrf==""{t.Fatal("session CSRF token is missing")};return client,csrf
|
|
61
|
-
}
|
|
62
|
-
admin,adminCSRF:=login("admin");owner,csrf:=login("owner");other,otherCSRF:=login("other");base:="/api/v1/extensions/__MODULE__/records"
|
|
63
|
-
if status,_:=call(http.DefaultClient,"GET",base,nil,"");status!=401{t.Fatal("anonymous",status)}
|
|
64
|
-
if status,_:=call(owner,"POST",base,__INPUT__,"");status!=403{t.Fatal("CSRF",status)}
|
|
65
|
-
if status,_:=call(owner,"GET",base+"?page=0",nil,"");status!=400{t.Fatal("pagination",status)}
|
|
66
|
-
status,payload:=call(owner,"POST",base,__INPUT__,csrf);if status!=201{t.Fatal("create",status,payload["message"])}
|
|
67
|
-
for field,want:=range __INPUT__{if payload["data"].(map[string]any)[field]!=want{t.Fatal("field value changed in response",field,payload["data"].(map[string]any)[field],want)}}
|
|
68
|
-
id:=int(payload["data"].(map[string]any)["id"].(float64));detail:=fmt.Sprintf("%s/%d",base,id)
|
|
69
|
-
if status,payload=call(admin,"GET",detail,nil,"");status!=200{t.Fatal("super administrator read",status)}
|
|
70
|
-
__SCOPE_ASSERTIONS__
|
|
71
|
-
for _,body:=range []any{map[string]any{},map[string]any{"unknown":true},map[string]any{__REQUIRED_FIELD__:nil}} {if status,_=call(owner,"PUT",detail,body,csrf);status!=400{t.Fatal("patch validation",status)}}
|
|
72
|
-
if status,payload=call(owner,"PUT",detail,map[string]any{__PATCH_FIELD__:__PATCH_VALUE__},csrf);status!=200{t.Fatal("partial update",status,payload["message"])}
|
|
73
|
-
if status,payload=call(owner,"GET",detail,nil,"");status!=200||payload["data"].(map[string]any)[__UNCHANGED_FIELD__]!=__UNCHANGED_VALUE__{t.Fatal("omitted field changed",payload)}
|
|
74
|
-
__NULLABLE_ASSERTIONS__
|
|
75
|
-
__UNIQUE_ASSERTIONS__
|
|
76
|
-
count,err:=store.Client.AuditLog.Query().Where(auditlog.ModuleEQ("__MODULE__"),auditlog.OperationEQ("create")).Count(ctx);if err!=nil||count!=1{t.Fatal("transaction audit",count,err)}
|
|
77
|
-
account,err:=store.Client.User.Query().Where(user.UsernameEQ("owner")).Only(ctx);if err!=nil{t.Fatal(err)};button,err:=store.Client.Menu.Query().Where(menu.PermissionEQ("host:__MODULE__:remove")).Only(ctx);if err!=nil{t.Fatal(err)}
|
|
78
|
-
if _,err=store.Client.UserMenu.Delete().Where(usermenu.UserIDEQ(account.ID),usermenu.MenuIDEQ(button.ID)).Exec(ctx);err!=nil{t.Fatal(err)}
|
|
79
|
-
if status,_=call(owner,"DELETE",detail,nil,csrf);status!=403{t.Fatal("permission revocation",status)}
|
|
80
|
-
var before int;if err=store.DB.QueryRowContext(ctx,"SELECT count(*) FROM __TABLE__").Scan(&before);err!=nil{t.Fatal(err)}
|
|
81
|
-
// A failed mandatory audit must roll back the business write.
|
|
82
|
-
if _,err=store.DB.ExecContext(ctx,"DROP TABLE audit_logs");err!=nil{t.Fatal(err)}
|
|
83
|
-
if status,_=call(owner,"POST",base,__SECOND_INPUT__,csrf);status!=503{t.Fatal("audit failure",status)}
|
|
84
|
-
var after int;if err=store.DB.QueryRowContext(ctx,"SELECT count(*) FROM __TABLE__").Scan(&after);err!=nil||after!=before{t.Fatal("business write survived failed audit",before,after,err)}
|
|
85
|
-
_=adminCSRF;_=otherCSRF
|
|
86
|
-
}
|
|
1
|
+
package module
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"bytes"
|
|
5
|
+
"context"
|
|
6
|
+
"crypto/rand"
|
|
7
|
+
"encoding/base64"
|
|
8
|
+
"encoding/json"
|
|
9
|
+
"fmt"
|
|
10
|
+
"net/http"
|
|
11
|
+
"net/http/cookiejar"
|
|
12
|
+
"net/http/httptest"
|
|
13
|
+
"net/url"
|
|
14
|
+
"os"
|
|
15
|
+
"path/filepath"
|
|
16
|
+
"regexp"
|
|
17
|
+
"strings"
|
|
18
|
+
"testing"
|
|
19
|
+
"time"
|
|
20
|
+
arcbase "github.com/fudanda/arcbase/backend/v2"
|
|
21
|
+
"github.com/fudanda/arcbase/backend/v2/ent/user"
|
|
22
|
+
"github.com/fudanda/arcbase/backend/v2/ent/userrole"
|
|
23
|
+
"github.com/fudanda/arcbase/backend/v2/ent/menu"
|
|
24
|
+
"github.com/fudanda/arcbase/backend/v2/ent/auditlog"
|
|
25
|
+
"github.com/fudanda/arcbase/backend/v2/ent/usermenu"
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
func TestGeneratedHTTPPermissionsScopeValidationAndAudit(t *testing.T) {
|
|
29
|
+
ctx:=context.Background();dsn:="sqlite:"+filepath.Join(t.TempDir(),"http.db")
|
|
30
|
+
if value:=os.Getenv("ARCBASE_TEST_DATABASE_URL");strings.HasPrefix(value,"postgres") {
|
|
31
|
+
admin,err:=arcbase.OpenStore(ctx,value);if err!=nil{t.Fatal(err)}
|
|
32
|
+
schema:=fmt.Sprintf("arcbase_generated_%d",time.Now().UnixNano());if _,err=admin.DB.ExecContext(ctx,"CREATE SCHEMA "+schema);err!=nil{t.Fatal(err)}
|
|
33
|
+
t.Cleanup(func(){admin.DB.ExecContext(context.Background(),"DROP SCHEMA "+schema+" CASCADE");admin.Close()})
|
|
34
|
+
parsed,_:=url.Parse(value);query:=parsed.Query();query.Set("search_path",schema);parsed.RawQuery=query.Encode();dsn=parsed.String()
|
|
35
|
+
}
|
|
36
|
+
store,err:=arcbase.OpenStore(ctx,dsn);if err!=nil{t.Fatal(err)};defer store.Close()
|
|
37
|
+
if err=store.Migrate(ctx);err!=nil{t.Fatal(err)};if err=store.Seed(ctx);err!=nil{t.Fatal(err)}
|
|
38
|
+
module:=&Module{};if err=module.Migrate(ctx,store);err!=nil{t.Fatal(err)};if err=module.Seed(ctx,store);err!=nil{t.Fatal(err)};if err=module.Seed(ctx,store);err!=nil{t.Fatal(err)}
|
|
39
|
+
password:="Aa1!"+rand.Text();for _,name:=range []string{"admin","owner","other"}{if err=store.InitAdmin(ctx,name,password);err!=nil{t.Fatal(err)}}
|
|
40
|
+
for _,name:=range []string{"owner","other"} {
|
|
41
|
+
account,err:=store.Client.User.Query().Where(user.UsernameEQ(name)).Only(ctx);if err!=nil{t.Fatal(err)}
|
|
42
|
+
if _,err=store.Client.UserRole.Delete().Where(userrole.UserIDEQ(account.ID)).Exec(ctx);err!=nil{t.Fatal(err)}
|
|
43
|
+
rows,err:=store.Client.Menu.Query().Where(menu.PermissionHasPrefix("host:__MODULE__:" )).All(ctx);if err!=nil{t.Fatal(err)}
|
|
44
|
+
for _,row:=range rows{if err=store.Client.UserMenu.Create().SetUserID(account.ID).SetMenuID(row.ID).Exec(ctx);err!=nil{t.Fatal(err)}}
|
|
45
|
+
}
|
|
46
|
+
framework,err:=arcbase.New(ctx,arcbase.Config{DSN:dsn,Modules:[]arcbase.Module{module}});if err!=nil{t.Fatal(err)}
|
|
47
|
+
server:=httptest.NewServer(framework.Handler());defer server.Close();defer framework.Shutdown(ctx)
|
|
48
|
+
call:=func(client *http.Client,method,path string,body any,csrf string)(int,map[string]any){
|
|
49
|
+
raw,_:=json.Marshal(body);r,_:=http.NewRequest(method,server.URL+path,bytes.NewReader(raw));r.Header.Set("Content-Type","application/json");r.Header.Set("Origin",server.URL);if csrf!=""{r.Header.Set("X-CSRF-Token",csrf)}
|
|
50
|
+
response,err:=client.Do(r);if err!=nil{t.Fatal(err)};defer response.Body.Close();payload:=map[string]any{};json.NewDecoder(response.Body).Decode(&payload);return response.StatusCode,payload
|
|
51
|
+
}
|
|
52
|
+
login:=func(name string)(*http.Client,string){jar,_:=cookiejar.New(nil);client:=&http.Client{Jar:jar};status,payload:=call(client,"GET","/api/v1/auth/captcha",nil,"");if status!=200{t.Fatal(status)}
|
|
53
|
+
enabled,ok:=payload["enabled"].(bool);if !ok{t.Fatal("captcha response omitted enabled")};body:=map[string]any{"username":name,"password":password}
|
|
54
|
+
if enabled{
|
|
55
|
+
image,ok:=payload["image"].(string);if !ok{t.Fatal("enabled captcha omitted image")};parts:=strings.SplitN(image,",",2);if len(parts)!=2||parts[0]!="data:image/svg+xml;base64"{t.Fatal("invalid captcha image")}
|
|
56
|
+
svg,err:=base64.StdEncoding.DecodeString(parts[1]);if err!=nil{t.Fatal("invalid captcha encoding")};answer:=regexp.MustCompile(`>([A-F0-9]{4,8})</text>`).FindSubmatch(svg);if len(answer)!=2{t.Fatal("enabled captcha has no answer")}
|
|
57
|
+
captchaID,ok:=payload["captchaId"].(string);if !ok||captchaID==""{t.Fatal("enabled captcha omitted ID")};body["captchaId"],body["captchaAnswer"]=captchaID,string(answer[1])
|
|
58
|
+
}else{_,hasImage:=payload["image"];_,hasID:=payload["captchaId"];if hasImage||hasID{t.Fatal("disabled captcha exposed challenge fields")}}
|
|
59
|
+
status,payload=call(client,"POST","/api/v1/auth/login",body,"");if status!=200{t.Fatal("login",status,payload["message"])}
|
|
60
|
+
outcome,ok:=payload["outcome"].(map[string]any);if !ok||outcome["type"]!="session"{t.Fatal("login did not establish a session")};value,ok:=outcome["value"].(map[string]any);if !ok{t.Fatal("session result is missing")};csrf,ok:=value["csrfToken"].(string);if !ok||csrf==""{t.Fatal("session CSRF token is missing")};return client,csrf
|
|
61
|
+
}
|
|
62
|
+
admin,adminCSRF:=login("admin");owner,csrf:=login("owner");other,otherCSRF:=login("other");base:="/api/v1/extensions/__MODULE__/records"
|
|
63
|
+
if status,_:=call(http.DefaultClient,"GET",base,nil,"");status!=401{t.Fatal("anonymous",status)}
|
|
64
|
+
if status,_:=call(owner,"POST",base,__INPUT__,"");status!=403{t.Fatal("CSRF",status)}
|
|
65
|
+
if status,_:=call(owner,"GET",base+"?page=0",nil,"");status!=400{t.Fatal("pagination",status)}
|
|
66
|
+
status,payload:=call(owner,"POST",base,__INPUT__,csrf);if status!=201{t.Fatal("create",status,payload["message"])}
|
|
67
|
+
for field,want:=range __INPUT__{if payload["data"].(map[string]any)[field]!=want{t.Fatal("field value changed in response",field,payload["data"].(map[string]any)[field],want)}}
|
|
68
|
+
id:=int(payload["data"].(map[string]any)["id"].(float64));detail:=fmt.Sprintf("%s/%d",base,id)
|
|
69
|
+
if status,payload=call(admin,"GET",detail,nil,"");status!=200{t.Fatal("super administrator read",status)}
|
|
70
|
+
__SCOPE_ASSERTIONS__
|
|
71
|
+
for _,body:=range []any{map[string]any{},map[string]any{"unknown":true},map[string]any{__REQUIRED_FIELD__:nil}} {if status,_=call(owner,"PUT",detail,body,csrf);status!=400{t.Fatal("patch validation",status)}}
|
|
72
|
+
if status,payload=call(owner,"PUT",detail,map[string]any{__PATCH_FIELD__:__PATCH_VALUE__},csrf);status!=200{t.Fatal("partial update",status,payload["message"])}
|
|
73
|
+
if status,payload=call(owner,"GET",detail,nil,"");status!=200||payload["data"].(map[string]any)[__UNCHANGED_FIELD__]!=__UNCHANGED_VALUE__{t.Fatal("omitted field changed",payload)}
|
|
74
|
+
__NULLABLE_ASSERTIONS__
|
|
75
|
+
__UNIQUE_ASSERTIONS__
|
|
76
|
+
count,err:=store.Client.AuditLog.Query().Where(auditlog.ModuleEQ("__MODULE__"),auditlog.OperationEQ("create")).Count(ctx);if err!=nil||count!=1{t.Fatal("transaction audit",count,err)}
|
|
77
|
+
account,err:=store.Client.User.Query().Where(user.UsernameEQ("owner")).Only(ctx);if err!=nil{t.Fatal(err)};button,err:=store.Client.Menu.Query().Where(menu.PermissionEQ("host:__MODULE__:remove")).Only(ctx);if err!=nil{t.Fatal(err)}
|
|
78
|
+
if _,err=store.Client.UserMenu.Delete().Where(usermenu.UserIDEQ(account.ID),usermenu.MenuIDEQ(button.ID)).Exec(ctx);err!=nil{t.Fatal(err)}
|
|
79
|
+
if status,_=call(owner,"DELETE",detail,nil,csrf);status!=403{t.Fatal("permission revocation",status)}
|
|
80
|
+
var before int;if err=store.DB.QueryRowContext(ctx,"SELECT count(*) FROM __TABLE__").Scan(&before);err!=nil{t.Fatal(err)}
|
|
81
|
+
// A failed mandatory audit must roll back the business write.
|
|
82
|
+
if _,err=store.DB.ExecContext(ctx,"DROP TABLE audit_logs");err!=nil{t.Fatal(err)}
|
|
83
|
+
if status,_=call(owner,"POST",base,__SECOND_INPUT__,csrf);status!=503{t.Fatal("audit failure",status)}
|
|
84
|
+
var after int;if err=store.DB.QueryRowContext(ctx,"SELECT count(*) FROM __TABLE__").Scan(&after);err!=nil||after!=before{t.Fatal("business write survived failed audit",before,after,err)}
|
|
85
|
+
_=adminCSRF;_=otherCSRF
|
|
86
|
+
}
|
|
@@ -1,74 +1,74 @@
|
|
|
1
|
-
package module
|
|
2
|
-
|
|
3
|
-
import (
|
|
4
|
-
"bytes"
|
|
5
|
-
"context"
|
|
6
|
-
"encoding/csv"
|
|
7
|
-
"encoding/json"
|
|
8
|
-
"errors"
|
|
9
|
-
"fmt"
|
|
10
|
-
"io"
|
|
11
|
-
"strconv"
|
|
12
|
-
"strings"
|
|
13
|
-
"entgo.io/ent/dialect"
|
|
14
|
-
entsql "entgo.io/ent/dialect/sql"
|
|
15
|
-
arcbase "github.com/fudanda/arcbase/backend/v2"
|
|
16
|
-
entity "__GO_MODULE__/internal/ent"
|
|
17
|
-
"github.com/xuri/excelize/v2"
|
|
18
|
-
)
|
|
19
|
-
|
|
20
|
-
type transferField struct{Name,Type string;Required bool}
|
|
21
|
-
type importRow struct{Row int `json:"row"`;Status string `json:"status"`;Message string `json:"message"`}
|
|
22
|
-
type importResult struct{DryRun bool `json:"dryRun"`;Total int `json:"total"`;Success int `json:"success"`;Failed int `json:"failed"`;Skipped int `json:"skipped"`;Rows []importRow `json:"rows"`}
|
|
23
|
-
var errPrecheck=errors.New("precheck transaction rollback")
|
|
24
|
-
func transferFields()[]transferField{var fields []transferField;if err:=json.Unmarshal([]byte(__FIELDS_JSON__),&fields);err!=nil{panic("invalid generated transfer fields")};return fields}
|
|
25
|
-
func readSheet(raw []byte,format string)([][]string,error){
|
|
26
|
-
if len(raw)==0||len(raw)>5<<20{return nil,ErrInvalid}
|
|
27
|
-
result:=[][]string{}
|
|
28
|
-
if format=="csv"{reader:=csv.NewReader(bytes.NewReader(raw));reader.FieldsPerRecord=-1;for{row,err:=reader.Read();if err==io.EOF{break};if err!=nil{return nil,ErrInvalid};result=append(result,row);if len(result)>1001{return nil,ErrInvalid}}}else if format=="xlsx"{
|
|
29
|
-
book,err:=excelize.OpenReader(bytes.NewReader(raw),excelize.Options{UnzipSizeLimit:32<<20,UnzipXMLSizeLimit:8<<20,RawCellValue:true});if err!=nil{return nil,ErrInvalid};defer book.Close();sheets:=book.GetSheetList();if len(sheets)!=1{return nil,ErrInvalid};iterator,err:=book.Rows(sheets[0]);if err!=nil{return nil,ErrInvalid};defer iterator.Close();for iterator.Next(){row,err:=iterator.Columns(excelize.Options{RawCellValue:true});if err!=nil{return nil,ErrInvalid};result=append(result,row);if len(result)>1001{return nil,ErrInvalid}};if err=iterator.Error();err!=nil{return nil,ErrInvalid}
|
|
30
|
-
}else{return nil,ErrInvalid}
|
|
31
|
-
if len(result)<2||len(result[0])==0{return nil,ErrInvalid};result[0][0]=strings.TrimPrefix(result[0][0],"\ufeff");return result,nil
|
|
32
|
-
}
|
|
33
|
-
func rowInput(fields []transferField,headers,values []string)(map[string]any,error){
|
|
34
|
-
if len(values)>len(headers){return nil,ErrInvalid};result:=map[string]any{}
|
|
35
|
-
for index,field:=range fields{raw:="";if index<len(values){raw=values[index]};if raw==""{if field.Required{continue};result[field.Name]=nil;continue}
|
|
36
|
-
switch field.Type{case "int","reference":number,err:=strconv.ParseInt(raw,10,32);if err!=nil{return nil,ErrInvalid};result[field.Name]=float64(number);case "bool":value,err:=strconv.ParseBool(raw);if err!=nil{return nil,ErrInvalid};result[field.Name]=value;default:if field.Type=="string"&&len(raw)>1&&raw[0]=='\''&&strings.ContainsRune("=+-@\t\r",rune(raw[1])){raw=raw[1:]};result[field.Name]=raw}
|
|
37
|
-
};return result,nil
|
|
38
|
-
}
|
|
39
|
-
func(s *Service)precheckRow(ctx context.Context,values map[string]any)error{
|
|
40
|
-
if err:=s.services.Authorize(ctx,"host:__MODULE__:create");err!=nil{return err};actor,ok:=arcbase.CurrentActor(ctx);if !ok{return arcbase.ErrUnauthenticated}
|
|
41
|
-
err:=s.services.Data.Write(ctx,"__MODULE__","importRecords","__TABLE__",func(driver dialect.Driver)(int,error){client:=entity.NewClient(entity.Driver(driver));if err:=s.validateReferences(ctx,client,values);err!=nil{return 0,err};builder:=client.__ENTITY__.Create().SetCreatedBy(actor.UserID).SetUpdatedBy(actor.UserID);if err:=assign(builder.Mutation(),values);err!=nil{return 0,err};if _,err:=builder.Save(ctx);err!=nil{return 0,classify(err)};return 0,errPrecheck});if errors.Is(err,errPrecheck){return nil};return err
|
|
42
|
-
}
|
|
43
|
-
func(s *Service)Import(ctx context.Context,raw []byte,format string,dryRun bool,duplicate string)(importResult,error){
|
|
44
|
-
result:=importResult{DryRun:dryRun,Rows:[]importRow{}}
|
|
45
|
-
if err:=s.services.Authorize(ctx,"host:__MODULE__:importRecords");err!=nil{return result,err};if err:=s.services.Authorize(ctx,"host:__MODULE__:create");err!=nil{return result,err};if duplicate!="error"&&duplicate!="skip"{return result,ErrInvalid}
|
|
46
|
-
rows,err:=readSheet(raw,format);if err!=nil{return result,err};fields:=transferFields();if len(rows[0])!=len(fields){return result,ErrInvalid};for index,field:=range fields{if rows[0][index]!=field.Name{return result,ErrInvalid}}
|
|
47
|
-
// A precheck rolls each attempted write back, but still detects duplicates within the file.
|
|
48
|
-
uniqueSeen:=map[string]bool{};var uniqueNames []string;if err=json.Unmarshal([]byte(__UNIQUE_FIELDS_JSON__),&uniqueNames);err!=nil{return result,err}
|
|
49
|
-
result.Total=len(rows)-1
|
|
50
|
-
for index,rawValues:=range rows[1:]{
|
|
51
|
-
item:=importRow{Row:index+2,Status:"failed",Message:"Invalid record input"}
|
|
52
|
-
values,rowErr:=rowInput(fields,rows[0],rawValues);if rowErr==nil{values,rowErr=s.prepare(values,false)}
|
|
53
|
-
if rowErr==nil{rowErr=s.referencePermissions(ctx,values)}
|
|
54
|
-
keys:=[]string{};if rowErr==nil{for _,field:=range uniqueNames{if value:=values[field];value!=nil{encoded,_:=json.Marshal(value);key:=field+":"+string(encoded);keys=append(keys,key);if uniqueSeen[key]{rowErr=ErrConflict}}}}
|
|
55
|
-
if rowErr==nil{if dryRun{rowErr=s.precheckRow(ctx,values)}else{_,rowErr=s.Create(ctx,values)}}
|
|
56
|
-
switch{case rowErr==nil:item.Status="success";item.Message="Imported";if dryRun{item.Message="Ready to import"};result.Success++;for _,key:=range keys{uniqueSeen[key]=true}
|
|
57
|
-
case errors.Is(rowErr,ErrConflict):item.Message="Duplicate or conflicting record";if duplicate=="skip"{item.Status="skipped";result.Skipped++}else{result.Failed++}
|
|
58
|
-
case errors.Is(rowErr,arcbase.ErrForbidden):item.Message="Referenced record permission denied";result.Failed++
|
|
59
|
-
case errors.Is(rowErr,ErrInvalid):result.Failed++
|
|
60
|
-
default:return result,rowErr
|
|
61
|
-
};result.Rows=append(result.Rows,item)
|
|
62
|
-
};return result,nil
|
|
63
|
-
}
|
|
64
|
-
func(s *Service)exportRows(ctx context.Context,keyword string)([]map[string]any,error){
|
|
65
|
-
if err:=s.services.Authorize(ctx,"host:__MODULE__:exportRecords");err!=nil{return nil,err};if err:=s.services.Authorize(ctx,"host:__MODULE__:list");err!=nil{return nil,err}
|
|
66
|
-
query,err:=s.query(ctx,s.client);if err!=nil{return nil,err};__EXPORT_SEARCH__
|
|
67
|
-
// Bound synchronous exports and refuse truncation; callers receive an explicit error.
|
|
68
|
-
rows,err:=query.Order(entity.Desc("id")).Limit(10001).All(ctx);if err!=nil{return nil,err};if len(rows)>10000{return nil,ErrInvalid};result:=make([]map[string]any,0,len(rows));for _,row:=range rows{result=append(result,view(row))};return result,nil
|
|
69
|
-
}
|
|
70
|
-
func sheetBytes(format string,rows []map[string]any)([]byte,error){
|
|
71
|
-
fields:=transferFields();header:=make([]string,len(fields));for index,field:=range fields{header[index]=field.Name}
|
|
72
|
-
if format=="csv"{var output bytes.Buffer;writer:=csv.NewWriter(&output);if err:=writer.Write(header);err!=nil{return nil,err};for _,row:=range rows{values:=make([]string,len(fields));for index,field:=range fields{if row[field.Name]!=nil{values[index]=fmt.Sprint(row[field.Name]);if field.Type=="string"&&len(values[index])>0&&strings.ContainsRune("=+-@\t\r",rune(values[index][0])){values[index]="'"+values[index]}}};if err:=writer.Write(values);err!=nil{return nil,err}};writer.Flush();return output.Bytes(),writer.Error()}
|
|
73
|
-
if format!="xlsx"{return nil,ErrInvalid};book:=excelize.NewFile();defer book.Close();for index,name:=range header{cell,_:=excelize.CoordinatesToCellName(index+1,1);if err:=book.SetCellStr("Sheet1",cell,name);err!=nil{return nil,err}};for index,row:=range rows{for column,field:=range fields{cell,_:=excelize.CoordinatesToCellName(column+1,index+2);value:="";if row[field.Name]!=nil{value=fmt.Sprint(row[field.Name])};if err:=book.SetCellStr("Sheet1",cell,value);err!=nil{return nil,err}}};output,err:=book.WriteToBuffer();if err!=nil{return nil,err};return output.Bytes(),nil
|
|
74
|
-
}
|
|
1
|
+
package module
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"bytes"
|
|
5
|
+
"context"
|
|
6
|
+
"encoding/csv"
|
|
7
|
+
"encoding/json"
|
|
8
|
+
"errors"
|
|
9
|
+
"fmt"
|
|
10
|
+
"io"
|
|
11
|
+
"strconv"
|
|
12
|
+
"strings"
|
|
13
|
+
"entgo.io/ent/dialect"
|
|
14
|
+
entsql "entgo.io/ent/dialect/sql"
|
|
15
|
+
arcbase "github.com/fudanda/arcbase/backend/v2"
|
|
16
|
+
entity "__GO_MODULE__/internal/ent"
|
|
17
|
+
"github.com/xuri/excelize/v2"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
type transferField struct{Name,Type string;Required bool}
|
|
21
|
+
type importRow struct{Row int `json:"row"`;Status string `json:"status"`;Message string `json:"message"`}
|
|
22
|
+
type importResult struct{DryRun bool `json:"dryRun"`;Total int `json:"total"`;Success int `json:"success"`;Failed int `json:"failed"`;Skipped int `json:"skipped"`;Rows []importRow `json:"rows"`}
|
|
23
|
+
var errPrecheck=errors.New("precheck transaction rollback")
|
|
24
|
+
func transferFields()[]transferField{var fields []transferField;if err:=json.Unmarshal([]byte(__FIELDS_JSON__),&fields);err!=nil{panic("invalid generated transfer fields")};return fields}
|
|
25
|
+
func readSheet(raw []byte,format string)([][]string,error){
|
|
26
|
+
if len(raw)==0||len(raw)>5<<20{return nil,ErrInvalid}
|
|
27
|
+
result:=[][]string{}
|
|
28
|
+
if format=="csv"{reader:=csv.NewReader(bytes.NewReader(raw));reader.FieldsPerRecord=-1;for{row,err:=reader.Read();if err==io.EOF{break};if err!=nil{return nil,ErrInvalid};result=append(result,row);if len(result)>1001{return nil,ErrInvalid}}}else if format=="xlsx"{
|
|
29
|
+
book,err:=excelize.OpenReader(bytes.NewReader(raw),excelize.Options{UnzipSizeLimit:32<<20,UnzipXMLSizeLimit:8<<20,RawCellValue:true});if err!=nil{return nil,ErrInvalid};defer book.Close();sheets:=book.GetSheetList();if len(sheets)!=1{return nil,ErrInvalid};iterator,err:=book.Rows(sheets[0]);if err!=nil{return nil,ErrInvalid};defer iterator.Close();for iterator.Next(){row,err:=iterator.Columns(excelize.Options{RawCellValue:true});if err!=nil{return nil,ErrInvalid};result=append(result,row);if len(result)>1001{return nil,ErrInvalid}};if err=iterator.Error();err!=nil{return nil,ErrInvalid}
|
|
30
|
+
}else{return nil,ErrInvalid}
|
|
31
|
+
if len(result)<2||len(result[0])==0{return nil,ErrInvalid};result[0][0]=strings.TrimPrefix(result[0][0],"\ufeff");return result,nil
|
|
32
|
+
}
|
|
33
|
+
func rowInput(fields []transferField,headers,values []string)(map[string]any,error){
|
|
34
|
+
if len(values)>len(headers){return nil,ErrInvalid};result:=map[string]any{}
|
|
35
|
+
for index,field:=range fields{raw:="";if index<len(values){raw=values[index]};if raw==""{if field.Required{continue};result[field.Name]=nil;continue}
|
|
36
|
+
switch field.Type{case "int","reference":number,err:=strconv.ParseInt(raw,10,32);if err!=nil{return nil,ErrInvalid};result[field.Name]=float64(number);case "bool":value,err:=strconv.ParseBool(raw);if err!=nil{return nil,ErrInvalid};result[field.Name]=value;default:if field.Type=="string"&&len(raw)>1&&raw[0]=='\''&&strings.ContainsRune("=+-@\t\r",rune(raw[1])){raw=raw[1:]};result[field.Name]=raw}
|
|
37
|
+
};return result,nil
|
|
38
|
+
}
|
|
39
|
+
func(s *Service)precheckRow(ctx context.Context,values map[string]any)error{
|
|
40
|
+
if err:=s.services.Authorize(ctx,"host:__MODULE__:create");err!=nil{return err};actor,ok:=arcbase.CurrentActor(ctx);if !ok{return arcbase.ErrUnauthenticated}
|
|
41
|
+
err:=s.services.Data.Write(ctx,"__MODULE__","importRecords","__TABLE__",func(driver dialect.Driver)(int,error){client:=entity.NewClient(entity.Driver(driver));if err:=s.validateReferences(ctx,client,values);err!=nil{return 0,err};builder:=client.__ENTITY__.Create().SetCreatedBy(actor.UserID).SetUpdatedBy(actor.UserID);if err:=assign(builder.Mutation(),values);err!=nil{return 0,err};if _,err:=builder.Save(ctx);err!=nil{return 0,classify(err)};return 0,errPrecheck});if errors.Is(err,errPrecheck){return nil};return err
|
|
42
|
+
}
|
|
43
|
+
func(s *Service)Import(ctx context.Context,raw []byte,format string,dryRun bool,duplicate string)(importResult,error){
|
|
44
|
+
result:=importResult{DryRun:dryRun,Rows:[]importRow{}}
|
|
45
|
+
if err:=s.services.Authorize(ctx,"host:__MODULE__:importRecords");err!=nil{return result,err};if err:=s.services.Authorize(ctx,"host:__MODULE__:create");err!=nil{return result,err};if duplicate!="error"&&duplicate!="skip"{return result,ErrInvalid}
|
|
46
|
+
rows,err:=readSheet(raw,format);if err!=nil{return result,err};fields:=transferFields();if len(rows[0])!=len(fields){return result,ErrInvalid};for index,field:=range fields{if rows[0][index]!=field.Name{return result,ErrInvalid}}
|
|
47
|
+
// A precheck rolls each attempted write back, but still detects duplicates within the file.
|
|
48
|
+
uniqueSeen:=map[string]bool{};var uniqueNames []string;if err=json.Unmarshal([]byte(__UNIQUE_FIELDS_JSON__),&uniqueNames);err!=nil{return result,err}
|
|
49
|
+
result.Total=len(rows)-1
|
|
50
|
+
for index,rawValues:=range rows[1:]{
|
|
51
|
+
item:=importRow{Row:index+2,Status:"failed",Message:"Invalid record input"}
|
|
52
|
+
values,rowErr:=rowInput(fields,rows[0],rawValues);if rowErr==nil{values,rowErr=s.prepare(values,false)}
|
|
53
|
+
if rowErr==nil{rowErr=s.referencePermissions(ctx,values)}
|
|
54
|
+
keys:=[]string{};if rowErr==nil{for _,field:=range uniqueNames{if value:=values[field];value!=nil{encoded,_:=json.Marshal(value);key:=field+":"+string(encoded);keys=append(keys,key);if uniqueSeen[key]{rowErr=ErrConflict}}}}
|
|
55
|
+
if rowErr==nil{if dryRun{rowErr=s.precheckRow(ctx,values)}else{_,rowErr=s.Create(ctx,values)}}
|
|
56
|
+
switch{case rowErr==nil:item.Status="success";item.Message="Imported";if dryRun{item.Message="Ready to import"};result.Success++;for _,key:=range keys{uniqueSeen[key]=true}
|
|
57
|
+
case errors.Is(rowErr,ErrConflict):item.Message="Duplicate or conflicting record";if duplicate=="skip"{item.Status="skipped";result.Skipped++}else{result.Failed++}
|
|
58
|
+
case errors.Is(rowErr,arcbase.ErrForbidden):item.Message="Referenced record permission denied";result.Failed++
|
|
59
|
+
case errors.Is(rowErr,ErrInvalid):result.Failed++
|
|
60
|
+
default:return result,rowErr
|
|
61
|
+
};result.Rows=append(result.Rows,item)
|
|
62
|
+
};return result,nil
|
|
63
|
+
}
|
|
64
|
+
func(s *Service)exportRows(ctx context.Context,keyword string)([]map[string]any,error){
|
|
65
|
+
if err:=s.services.Authorize(ctx,"host:__MODULE__:exportRecords");err!=nil{return nil,err};if err:=s.services.Authorize(ctx,"host:__MODULE__:list");err!=nil{return nil,err}
|
|
66
|
+
query,err:=s.query(ctx,s.client);if err!=nil{return nil,err};__EXPORT_SEARCH__
|
|
67
|
+
// Bound synchronous exports and refuse truncation; callers receive an explicit error.
|
|
68
|
+
rows,err:=query.Order(entity.Desc("id")).Limit(10001).All(ctx);if err!=nil{return nil,err};if len(rows)>10000{return nil,ErrInvalid};result:=make([]map[string]any,0,len(rows));for _,row:=range rows{result=append(result,view(row))};return result,nil
|
|
69
|
+
}
|
|
70
|
+
func sheetBytes(format string,rows []map[string]any)([]byte,error){
|
|
71
|
+
fields:=transferFields();header:=make([]string,len(fields));for index,field:=range fields{header[index]=field.Name}
|
|
72
|
+
if format=="csv"{var output bytes.Buffer;writer:=csv.NewWriter(&output);if err:=writer.Write(header);err!=nil{return nil,err};for _,row:=range rows{values:=make([]string,len(fields));for index,field:=range fields{if row[field.Name]!=nil{values[index]=fmt.Sprint(row[field.Name]);if field.Type=="string"&&len(values[index])>0&&strings.ContainsRune("=+-@\t\r",rune(values[index][0])){values[index]="'"+values[index]}}};if err:=writer.Write(values);err!=nil{return nil,err}};writer.Flush();return output.Bytes(),writer.Error()}
|
|
73
|
+
if format!="xlsx"{return nil,ErrInvalid};book:=excelize.NewFile();defer book.Close();for index,name:=range header{cell,_:=excelize.CoordinatesToCellName(index+1,1);if err:=book.SetCellStr("Sheet1",cell,name);err!=nil{return nil,err}};for index,row:=range rows{for column,field:=range fields{cell,_:=excelize.CoordinatesToCellName(column+1,index+2);value:="";if row[field.Name]!=nil{value=fmt.Sprint(row[field.Name])};if err:=book.SetCellStr("Sheet1",cell,value);err!=nil{return nil,err}}};output,err:=book.WriteToBuffer();if err!=nil{return nil,err};return output.Bytes(),nil
|
|
74
|
+
}
|