示例#1
0
func init() {
	mux := http.NewServeMux()
	db = utils.TestDB()
	models := []interface{}{&User{}, &CreditCard{}, &Address{}, &Language{}, &Profile{}, &Phone{}}
	for _, value := range models {
		db.DropTableIfExists(value)
		db.AutoMigrate(value)
	}

	Admin = admin.New(&qor.Config{DB: db})
	user := Admin.AddResource(&User{})
	user.Meta(&admin.Meta{Name: "Languages", Type: "select_many",
		Collection: func(resource interface{}, context *qor.Context) (results [][]string) {
			if languages := []Language{}; !context.GetDB().Find(&languages).RecordNotFound() {
				for _, language := range languages {
					results = append(results, []string{fmt.Sprint(language.ID), language.Name})
				}
			}
			return
		}})

	Admin.MountTo("/admin", mux)

	server = httptest.NewServer(mux)
}
示例#2
0
func main() {
	DB, _ := gorm.Open("sqlite3", "demo.db")
	DB.AutoMigrate(&User{}, &Product{})

	Admin := admin.New(&qor.Config{DB: &DB})
	Admin.AddResource(&User{}, &admin.Config{Menu: []string{"User Management"}})
	Admin.AddResource(&Product{}, &admin.Config{Menu: []string{"Product Management"}})

	mux := http.NewServeMux()
	Admin.MountTo("/admin", mux)
	http.ListenAndServe(":9000", mux)
}
示例#3
0
func AdminConfig() (mux *http.ServeMux) {
	DB, _ = gorm.Open("sqlite3", "demo.db")
	DB.AutoMigrate(&User{})

	Admin := admin.New(&qor.Config{DB: &DB})
	user := Admin.AddResource(&User{}, &admin.Config{Menu: []string{"User Management"}})
	user.Meta(&admin.Meta{Name: "Gender", Type: "select_one", Collection: []string{"自有设备", "消耗品", "客户设备"}})

	mux = http.NewServeMux()
	Admin.MountTo("/admin", mux)

	return
}
示例#4
0
func init() {
	Admin = admin.New(&qor.Config{DB: db.DB})
	Admin.SetAuth(Auth{})

	User = Admin.AddResource(
		&models.User{},
		&admin.Config{
			Name: "Users",
		},
	)
	User.IndexAttrs("ID", "Name")
	User.EditAttrs("Name")
}
示例#5
0
func main() {
	roles.Register("admin", func(req *http.Request, cu qor.CurrentUser) bool {
		return true
	})
	mux := http.NewServeMux()
	adm := admin.New(&qor.Config{DB: &db.DB})

	adm.SetAuth(&Auth{})
	page := adm.AddResource(&db.Page{}, &admin.Config{Menu: []string{"Cms"}})
	// adm.AddResource(&db.Product{}, &admin.Config{Menu: []string{"Cms"}})
	page.Meta(&admin.Meta{
		Name:     "Section1",
		Type:     "rich_editor",
		Resource: adm.AddResource(&admin.AssetManager{}, &admin.Config{Invisible: true}),
	})

	page.Meta(&admin.Meta{Name: "Url", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		url := resource.(*db.Page).Url
		url = fmt.Sprintf(`<a href="%s/page%s">%s</a>`, config.CmsHost, url, url)
		return template.HTML(url)
	}})

	page.NewAttrs("-ProductCodes")
	page.EditAttrs("-ProductCodes")
	page.IndexAttrs("-ProductCodes")
	I18nBackend := database.New(&db.DB)
	// config.I18n = i18n.New(I18nBackend)
	adm.AddResource(i18n.New(I18nBackend), &admin.Config{Menu: []string{"系统设置"}, Invisible: true})

	adm.MountTo("/admin", mux)
	// frontend routes
	router := gin.Default()
	router.LoadHTMLGlob("templates/*")
	bindPages(router)
	router.StaticFS("/system/", http.Dir("public/system"))
	// books
	pageRoutes := router.Group("/page")
	{
		// listing
		// pageRoutes.GET("", controllers.ListBooksHandler)
		// pageRoutes.GET("/", controllers.ListBooksHandler)
		pageRoutes.GET("/:url", controllers.ViewPageHandler)
	}
	mux.Handle("/", router)

	log.Println("Starting Server at 9000.")
	err := http.ListenAndServe(":9000", mux)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
示例#6
0
文件: init.go 项目: cncodog/mediom
func initAdmin() {
	Admin = admin.New(&qor.Config{DB: models.DB})
	Publish = publish.New(models.DB)
	sorting.RegisterCallbacks(models.DB)
	validations.RegisterCallbacks(models.DB)

	nodeSelectMeta := &admin.Meta{Name: "NodeId", Type: "select_one", Collection: nodeCollection}
	bodyMeta := &admin.Meta{Name: "Body", Type: "text"}

	Admin.AddResource(&admin.AssetManager{}, &admin.Config{Invisible: true})

	topic := Admin.AddResource(&models.Topic{})
	topic.SearchAttrs("Title")
	topic.NewAttrs("Title", "NodeId", "Body", "UserId")
	topic.EditAttrs("Title", "NodeId", "Body", "UserId")
	topic.IndexAttrs("Id", "UserId", "Title", "NodeId", "RepliesCount", "CreatedAt", "UpdatedAt")
	topic.Meta(bodyMeta)
	topic.Meta(nodeSelectMeta)

	reply := Admin.AddResource(&models.Reply{})
	reply.NewAttrs("TopicId", "UserId", "Body")
	reply.EditAttrs("Body")
	reply.IndexAttrs("Id", "Topic", "User", "Body", "CreatedAt", "UpdatedAt")
	reply.Meta(bodyMeta)

	user := Admin.AddResource(&models.User{})
	user.SearchAttrs("Login", "Email")
	user.EditAttrs("Login", "Email", "Location", "GitHub", "Twitter", "HomePage", "Tagline", "Description")
	user.IndexAttrs("Id", "Login", "Email", "Location", "CreatedAt", "UpdatedAt")

	node := Admin.AddResource(&models.Node{})
	node.IndexAttrs("Id", "NodeGroupId", "Name", "Summary", "Sort")
	node.NewAttrs("NodeGroupId", "Name", "Summary", "Sort")
	node.EditAttrs("NodeGroupId", "Name", "Summary", "Sort")
	node.Meta(&admin.Meta{Name: "NodeGroupId", Type: "select_one", Collection: nodeGroupCollection})

	nodeGroup := Admin.AddResource(&models.NodeGroup{})
	nodeGroup.IndexAttrs("Id", "Name", "Sort")
	nodeGroup.NewAttrs("Name", "Sort")
	nodeGroup.EditAttrs("Name", "Sort")

	notification := Admin.AddResource(&models.Notification{})
	notification.EditAttrs("Id")
	notification.IndexAttrs("Id", "UserId", "ActorId", "NotifyType", "Read", "NotifyableType", "NotifyableId", "CreatedAt", "UpdatedAt")

	mux = http.NewServeMux()
	mux.Handle("/system/", http.FileServer(http.Dir("public")))
	Admin.MountTo("/admin", mux)
}
示例#7
0
func init() {
	API = admin.New(&qor.Config{DB: db.DB})

	Product := API.AddResource(&models.Product{})

	ColorVariationMeta := Product.Meta(&admin.Meta{Name: "ColorVariations"})
	ColorVariation := ColorVariationMeta.Resource
	ColorVariation.IndexAttrs("ID", "Color", "Images", "SizeVariations")
	ColorVariation.ShowAttrs("Color", "Images", "SizeVariations")

	SizeVariationMeta := ColorVariation.Meta(&admin.Meta{Name: "SizeVariations"})
	SizeVariation := SizeVariationMeta.Resource
	SizeVariation.IndexAttrs("ID", "Size", "AvailableQuantity")
	SizeVariation.ShowAttrs("ID", "Size", "AvailableQuantity")

	API.AddResource(&models.Order{})
	API.AddResource(&models.User{})
}
示例#8
0
func init() {
	Admin = admin.New(&qor.Config{DB: db.Publish.DraftDB()})
	Admin.SetAuth(Auth{})

	assetManager := Admin.AddResource(&admin.AssetManager{}, &admin.Config{Invisible: true})

	product := Admin.AddResource(&models.Product{}, &admin.Config{Menu: []string{"Product Management"}})
	product.Meta(&admin.Meta{Name: "MadeCountry", Type: "select_one", Collection: Countries})
	product.Meta(&admin.Meta{Name: "Description", Type: "rich_editor", Resource: assetManager})

	for _, country := range Countries {
		var country = country
		product.Scope(&admin.Scope{Name: country, Group: "Made Country", Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
			return db.Where("made_country = ?", country)
		}})
	}

	product.IndexAttrs("-ColorVariations")

	Admin.AddResource(&models.Color{}, &admin.Config{Menu: []string{"Product Management"}})
	Admin.AddResource(&models.Size{}, &admin.Config{Menu: []string{"Product Management"}})
	Admin.AddResource(&models.Category{}, &admin.Config{Menu: []string{"Product Management"}})

	Admin.AddResource(&models.Order{}, &admin.Config{Menu: []string{"Order Management"}})

	store := Admin.AddResource(&models.Store{}, &admin.Config{Menu: []string{"Store Management"}})
	store.IndexAttrs("-Latitude", "-Longitude")
	store.AddValidator(func(record interface{}, metaValues *resource.MetaValues, context *qor.Context) error {
		if meta := metaValues.Get("Name"); meta != nil {
			if name := utils.ToString(meta.Value); strings.TrimSpace(name) == "" {
				return validations.NewError(record, "Name", "Name can't be blank")
			}
		}
		return nil
	})

	Admin.AddResource(config.Config.I18n, &admin.Config{Menu: []string{"Site Management"}})

	user := Admin.AddResource(&models.User{})
	user.IndexAttrs("ID", "Email", "Name", "Gender", "Role")

	Admin.AddResource(db.Publish)
}
示例#9
0
文件: main.go 项目: nilslice/qor
func AdminConfig() (mux *http.ServeMux) {
	Admin := admin.New(&qor.Config{DB: draftDB})
	Admin.SetAuth(&Auth{})

	Admin.AddResource(Publish)

	user := Admin.AddResource(&User{})
	user.Meta(&admin.Meta{Name: "Gender", Type: "select_one", Collection: []string{"Male", "Female"}})
	user.Meta(&admin.Meta{Name: "Languages", Type: "select_many"})
	user.Meta(&admin.Meta{Name: "Profile"})
	user.Meta(&admin.Meta{Name: "Note", Type: "rich_editor", Resource: Admin.NewResource(&admin.AssetManager{})})
	user.Meta(&admin.Meta{Name: "Avatar"})

	Admin.AddResource(&Product{}, &admin.Config{Menu: []string{"Product Management"}})

	Admin.AddMenu(&admin.Menu{Name: "Google", Link: "http://www.google.com", Ancestors: []string{"Outside", "Search Engine"}})

	mux = http.NewServeMux()
	Admin.MountTo("/admin", mux)

	return
}
示例#10
0
func init() {
	Admin = admin.New(&qor.Config{DB: db.Publish.DraftDB()})
	Admin.SetSiteName("Qor DEMO")
	Admin.SetAuth(Auth{})

	// Add Dashboard
	Admin.AddMenu(&admin.Menu{Name: "Dashboard", Link: "/admin"})

	// Add Asset Manager, for rich editor
	assetManager := Admin.AddResource(&admin.AssetManager{}, &admin.Config{Invisible: true})

	// Add Product
	product := Admin.AddResource(&models.Product{}, &admin.Config{Menu: []string{"Product Management"}})
	product.Meta(&admin.Meta{Name: "MadeCountry", Type: "select_one", Collection: Countries})
	product.Meta(&admin.Meta{Name: "Description", Type: "rich_editor", Resource: assetManager})
	sizeVariation := Admin.NewResource(&models.SizeVariation{}, &admin.Config{Invisible: true})
	sizeVariation.NewAttrs("-ColorVariation")
	sizeVariation.EditAttrs("-ColorVariation")
	colorVariation := Admin.NewResource(&models.ColorVariation{}, &admin.Config{Invisible: true})
	colorVariation.Meta(&admin.Meta{Name: "SizeVariations", Resource: sizeVariation})
	colorVariation.NewAttrs("-Product")
	colorVariation.EditAttrs("-Product")
	product.Meta(&admin.Meta{Name: "ColorVariations", Resource: colorVariation})
	product.SearchAttrs("Name", "Code", "Category.Name", "Brand.Name")

	for _, country := range Countries {
		var country = country
		product.Scope(&admin.Scope{Name: country, Group: "Made Country", Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
			return db.Where("made_country = ?", country)
		}})
	}

	product.IndexAttrs("-ColorVariations")

	Admin.AddResource(&models.Color{}, &admin.Config{Menu: []string{"Product Management"}})
	Admin.AddResource(&models.Size{}, &admin.Config{Menu: []string{"Product Management"}})
	Admin.AddResource(&models.Category{}, &admin.Config{Menu: []string{"Product Management"}})
	Admin.AddResource(&models.Collection{}, &admin.Config{Menu: []string{"Product Management"}})

	// Add Order
	orderItem := Admin.NewResource(&models.OrderItem{})
	orderItem.Meta(&admin.Meta{Name: "SizeVariation", Type: "select_one", Collection: sizeVariationCollection})

	order := Admin.AddResource(&models.Order{}, &admin.Config{Menu: []string{"Order Management"}})
	order.Meta(&admin.Meta{Name: "ShippingAddress", Type: "single_edit"})
	order.Meta(&admin.Meta{Name: "BillingAddress", Type: "single_edit"})
	order.Meta(&admin.Meta{Name: "OrderItems", Resource: orderItem})
	activity.RegisterActivityMeta(order)

	// define scopes for Order
	for _, state := range []string{"checkout", "cancelled", "paid", "paid_cancelled", "processing", "shipped", "returned"} {
		var state = state
		order.Scope(&admin.Scope{
			Name:  state,
			Label: strings.Title(strings.Replace(state, "_", " ", -1)),
			Group: "Order Status",
			Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB {
				return db.Where(models.Order{Transition: transition.Transition{State: state}})
			},
		})
	}
	order.IndexAttrs("-DiscountValue", "-OrderItems", "-AbandonedReason")
	order.NewAttrs("-DiscountValue", "-AbandonedReason")
	order.EditAttrs("-DiscountValue", "-AbandonedReason")
	order.ShowAttrs("-DiscountValue", "-AbandonedReason")
	order.SearchAttrs("User.Name", "User.Email", "ShippingAddress.ContactName", "ShippingAddress.Address1", "ShippingAddress.Address2")

	// Define another resource for same model
	abandonedOrder := Admin.AddResource(&models.Order{}, &admin.Config{Name: "Abandoned Order", Menu: []string{"Order Management"}})
	abandonedOrder.Meta(&admin.Meta{Name: "ShippingAddress", Type: "single_edit"})
	abandonedOrder.Meta(&admin.Meta{Name: "BillingAddress", Type: "single_edit"})

	// Define default scope for abandoned orders
	abandonedOrder.Scope(&admin.Scope{
		Default: true,
		Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB {
			return db.Where("abandoned_reason IS NOT NULL AND abandoned_reason <> ?", "")
		},
	})

	// Define scopes for abandoned orders
	for _, amount := range []int{5000, 10000, 20000} {
		var amount = amount
		abandonedOrder.Scope(&admin.Scope{
			Name:  fmt.Sprint(amount),
			Group: "Amount Greater Than",
			Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB {
				return db.Where("payment_amount > ?", amount)
			},
		})
	}

	abandonedOrder.IndexAttrs("-ShippingAddress", "-BillingAddress", "-DiscountValue", "-OrderItems")
	abandonedOrder.NewAttrs("-DiscountValue")
	abandonedOrder.EditAttrs("-DiscountValue")
	abandonedOrder.ShowAttrs("-DiscountValue")

	// Add Store
	store := Admin.AddResource(&models.Store{}, &admin.Config{Menu: []string{"Store Management"}})
	store.AddValidator(func(record interface{}, metaValues *resource.MetaValues, context *qor.Context) error {
		if meta := metaValues.Get("Name"); meta != nil {
			if name := utils.ToString(meta.Value); strings.TrimSpace(name) == "" {
				return validations.NewError(record, "Name", "Name can't be blank")
			}
		}
		return nil
	})

	// Add Translations
	Admin.AddResource(config.Config.I18n, &admin.Config{Menu: []string{"Site Management"}})

	// Add Setting
	Admin.AddResource(&models.Setting{}, &admin.Config{Singleton: true})

	// Add User
	user := Admin.AddResource(&models.User{})
	user.IndexAttrs("ID", "Email", "Name", "Gender", "Role")

	// Add Publish
	Admin.AddResource(db.Publish, &admin.Config{Singleton: true})

	// Add Seo
	Admin.AddResource(&models.Seo{}, &admin.Config{Name: "Meta Data", Singleton: true})

	// Add Search Center
	Admin.AddSearchResource(order, user, product)

	initFuncMap()
	initRouter()
}
示例#11
0
func init() {
	Admin = admin.New(&qor.Config{DB: db.Publish.DraftDB()})
	Admin.SetSiteName("Qor DEMO")
	Admin.SetAuth(Auth{})

	// Add Dashboard
	Admin.AddMenu(&admin.Menu{Name: "Dashboard", Link: "/admin"})

	// Add Asset Manager, for rich editor
	assetManager := Admin.AddResource(&media_library.AssetManager{}, &admin.Config{Invisible: true})

	// Add Product
	product := Admin.AddResource(&models.Product{}, &admin.Config{Menu: []string{"Product Management"}})
	product.Meta(&admin.Meta{Name: "MadeCountry", Type: "select_one", Collection: Countries})
	product.Meta(&admin.Meta{Name: "Description", Type: "rich_editor", Resource: assetManager})

	colorVariationMeta := product.Meta(&admin.Meta{Name: "ColorVariations"})
	colorVariation := colorVariationMeta.Resource
	colorVariation.NewAttrs("-Product")
	colorVariation.EditAttrs("-Product")

	sizeVariationMeta := colorVariation.Meta(&admin.Meta{Name: "SizeVariations"})
	sizeVariation := sizeVariationMeta.Resource
	sizeVariation.NewAttrs("-ColorVariation")
	sizeVariation.EditAttrs(
		&admin.Section{
			Rows: [][]string{
				{"Size", "AvailableQuantity"},
			},
		},
	)

	product.SearchAttrs("Name", "Code", "Category.Name", "Brand.Name")
	product.EditAttrs(
		&admin.Section{
			Title: "Basic Information",
			Rows: [][]string{
				{"Name"},
				{"Code", "Price"},
				{"Disabled"},
			}},
		&admin.Section{
			Title: "Organization",
			Rows: [][]string{
				{"Category", "Collections", "MadeCountry"},
			}},
		"Description",
		"ColorVariations",
	)

	for _, country := range Countries {
		var country = country
		product.Scope(&admin.Scope{Name: country, Group: "Made Country", Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
			return db.Where("made_country = ?", country)
		}})
	}

	product.IndexAttrs("-ColorVariations")
	product.Action(&admin.Action{
		Name: "disable",
		Handle: func(arg *admin.ActionArgument) error {
			for _, record := range arg.FindSelectedRecords() {
				arg.Context.DB.Model(record.(*models.Product)).Update("disabled", true)
			}
			return nil
		},
		Visibles: []string{"menu_item"},
	})
	product.Action(&admin.Action{
		Name: "enable",
		Handle: func(arg *admin.ActionArgument) error {
			for _, record := range arg.FindSelectedRecords() {
				arg.Context.DB.Model(record.(*models.Product)).Update("disabled", false)
			}
			return nil
		},
		Visibles: []string{"menu_item"},
	})

	Admin.AddResource(&models.Color{}, &admin.Config{Menu: []string{"Product Management"}})
	Admin.AddResource(&models.Size{}, &admin.Config{Menu: []string{"Product Management"}})
	Admin.AddResource(&models.Category{}, &admin.Config{Menu: []string{"Product Management"}})
	Admin.AddResource(&models.Collection{}, &admin.Config{Menu: []string{"Product Management"}})

	// Add Order
	order := Admin.AddResource(&models.Order{}, &admin.Config{Menu: []string{"Order Management"}})
	order.Meta(&admin.Meta{Name: "ShippingAddress", Type: "single_edit"})
	order.Meta(&admin.Meta{Name: "BillingAddress", Type: "single_edit"})
	order.Meta(&admin.Meta{Name: "ShippedAt", Type: "date"})

	orderItemMeta := order.Meta(&admin.Meta{Name: "OrderItems"})
	orderItemMeta.Resource.Meta(&admin.Meta{Name: "SizeVariation", Type: "select_one", Collection: sizeVariationCollection})

	// define scopes for Order
	for _, state := range []string{"checkout", "cancelled", "paid", "paid_cancelled", "processing", "shipped", "returned"} {
		var state = state
		order.Scope(&admin.Scope{
			Name:  state,
			Label: strings.Title(strings.Replace(state, "_", " ", -1)),
			Group: "Order Status",
			Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB {
				return db.Where(models.Order{Transition: transition.Transition{State: state}})
			},
		})
	}

	// define actions for Order
	type trackingNumberArgument struct {
		TrackingNumber string
	}

	order.Action(&admin.Action{
		Name: "Ship",
		Handle: func(argument *admin.ActionArgument) error {
			trackingNumberArgument := argument.Argument.(*trackingNumberArgument)
			for _, record := range argument.FindSelectedRecords() {
				argument.Context.GetDB().Model(record).UpdateColumn("tracking_number", trackingNumberArgument.TrackingNumber)
			}
			return nil
		},
		Resource: Admin.NewResource(&trackingNumberArgument{}),
		Visibles: []string{"menu_item"},
	})

	order.Action(&admin.Action{
		Name: "Cancel",
		Handle: func(argument *admin.ActionArgument) error {
			for _, order := range argument.FindSelectedRecords() {
				db := argument.Context.GetDB()
				if err := models.OrderState.Trigger("cancel", order.(*models.Order), db); err != nil {
					return err
				}
				db.Select("state").Save(order)
			}
			return nil
		},
		Visibles: []string{"menu_item"},
	})

	order.IndexAttrs("User", "PaymentAmount", "ShippedAt", "CancelledAt", "State", "ShippingAddress")
	order.NewAttrs("-DiscountValue", "-AbandonedReason", "-CancelledAt")
	order.EditAttrs("-DiscountValue", "-AbandonedReason", "-CancelledAt")
	order.SearchAttrs("User.Name", "User.Email", "ShippingAddress.ContactName", "ShippingAddress.Address1", "ShippingAddress.Address2")

	// Define another resource for same model
	abandonedOrder := Admin.AddResource(&models.Order{}, &admin.Config{Name: "Abandoned Order", Menu: []string{"Order Management"}})
	abandonedOrder.Meta(&admin.Meta{Name: "ShippingAddress", Type: "single_edit"})
	abandonedOrder.Meta(&admin.Meta{Name: "BillingAddress", Type: "single_edit"})

	// Define default scope for abandoned orders
	abandonedOrder.Scope(&admin.Scope{
		Default: true,
		Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB {
			return db.Where("abandoned_reason IS NOT NULL AND abandoned_reason <> ?", "")
		},
	})

	// Define scopes for abandoned orders
	for _, amount := range []int{5000, 10000, 20000} {
		var amount = amount
		abandonedOrder.Scope(&admin.Scope{
			Name:  fmt.Sprint(amount),
			Group: "Amount Greater Than",
			Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB {
				return db.Where("payment_amount > ?", amount)
			},
		})
	}

	abandonedOrder.IndexAttrs("-ShippingAddress", "-BillingAddress", "-DiscountValue", "-OrderItems")
	abandonedOrder.NewAttrs("-DiscountValue")
	abandonedOrder.EditAttrs("-DiscountValue")
	abandonedOrder.ShowAttrs("-DiscountValue")

	// Add Store
	store := Admin.AddResource(&models.Store{}, &admin.Config{Menu: []string{"Store Management"}})
	store.AddValidator(func(record interface{}, metaValues *resource.MetaValues, context *qor.Context) error {
		if meta := metaValues.Get("Name"); meta != nil {
			if name := utils.ToString(meta.Value); strings.TrimSpace(name) == "" {
				return validations.NewError(record, "Name", "Name can't be blank")
			}
		}
		return nil
	})

	// Add Translations
	Admin.AddResource(config.Config.I18n, &admin.Config{Menu: []string{"Site Management"}})

	// Add Setting
	Admin.AddResource(&models.Setting{}, &admin.Config{Singleton: true})

	// Add User
	user := Admin.AddResource(&models.User{})
	user.IndexAttrs("ID", "Email", "Name", "Gender", "Role")

	// Add Publish
	Admin.AddResource(db.Publish, &admin.Config{Singleton: true})

	// Add Worker
	Worker := getWorker()
	Admin.AddResource(Worker)
	exchange_actions.RegisterExchangeJobs(config.Config.I18n, Worker)

	initFuncMap()
	initRouter()
}
示例#12
0
func init() {
	// setting up QOR admin
	Admin = admin.New(&qor.Config{DB: Pub.DraftDB()})
	Admin.AddResource(Pub)
	Admin.SetAuth(&Auth{})

	I18n = i18n.New(database.New(StagingDB))
	Admin.AddResource(I18n)

	roles.Register("admin", func(req *http.Request, currentUser qor.CurrentUser) bool {
		if currentUser == nil {
			return false
		}

		if currentUser.(*User).Role == "admin" {
			return true
		}

		return false
	})

	roles.Register("user", func(req *http.Request, currentUser qor.CurrentUser) bool {
		if currentUser == nil {
			return false
		}

		if currentUser.(*User).Role == "user" {
			return true
		}

		return false
	})

	user := Admin.AddResource(&User{})

	user.Meta(&admin.Meta{
		Name:  "UserRole",
		Label: "Role",
		//Type:  "select_one",
		Collection: func(resource interface{}, context *qor.Context) (results [][]string) {
			return [][]string{
				{"admin", "admin"},
				{"user", "user"},
			}
		},
		Valuer: func(value interface{}, context *qor.Context) interface{} {
			if value == nil {
				return value
			}
			user := value.(*User)
			log.Println("user", user.Role)
			return user.Role
		},
	})

	user.IndexAttrs("ID", "Name", "Role")
	user.NewAttrs("Name", "UserRole")
	user.EditAttrs("Name", "UserRole")

	author := Admin.AddResource(&Author{})

	author.IndexAttrs("ID", "Name")
	author.SearchAttrs("ID", "Name")

	book := Admin.AddResource(&Book{})

	book.Meta(&admin.Meta{
		Name:  "FormattedDate",
		Label: "Release Date",
		Valuer: func(value interface{}, context *qor.Context) interface{} {
			book := value.(*Book)
			return book.ReleaseDate.Format("Jan 2, 2006")
		},
	})

	book.Meta(&admin.Meta{
		Name: "Synopsis",
		Type: "rich_editor",
	})

	// which fields should be displayed in the books list on admin
	book.IndexAttrs("ID", "Title", "Authors", "FormattedDate", "Price")
	// which fields should be editable in the book esit interface
	book.NewAttrs("Title", "Authors", "Synopsis", "ReleaseDate", "Price", "CoverImage")
	book.EditAttrs("Title", "Authors", "Synopsis", "ReleaseDate", "Price", "CoverImage")
	// which fields should be searched when using the item search on the list view
	book.SearchAttrs("ID", "Title")
}
示例#13
0
func main() {
	roles.Register("admin", func(req *http.Request, cu qor.CurrentUser) bool {
		return true
	})

	adm := admin.New(&qor.Config{DB: &db.DB})

	adm.SetAuth(&Auth{})

	noUpdatePermission := roles.Deny(roles.Update, "admin")

	reportItem := adm.AddResource(&db.ReportItem{}, &admin.Config{Menu: []string{"查询"},
		Permission: roles.Deny(roles.Update, "admin").Deny(roles.Delete, "admin").Deny(roles.Create, "admin"),
	})
	reportItem.IndexAttrs("WhoHasThemName", "ClientName", "DeviceName", "DeviceCode", "Count")
	reportItem.Scope(&admin.Scope{
		Default: true,
		Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
			return db.Where("count > 0").Order("updated_at DESC")
		},
	})

	reportItem.Scope(&admin.Scope{
		Name:  "employee-take-outs",
		Label: "Employee Take Outs",
		Group: "设备状态",
		Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
			return db.Where("who_has_them_type = ?", "Employee")
		},
	})
	reportItem.Scope(&admin.Scope{
		Name:  "to-check-company",
		Label: "To Check Company",
		Group: "设备状态",
		Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
			return db.Where("who_has_them_type = ?", "DeviceCheckCompany")
		},
	})
	reportItem.Scope(&admin.Scope{
		Name:  "in-warehouse",
		Label: "In Warehouse",
		Group: "设备状态",
		Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
			return db.Where("who_has_them_type = ?", "Warehouse")
		},
	})

	reportItem.Meta(&admin.Meta{
		Name: "WhoHasThemName",
		Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
			ri := resource.(*db.ReportItem)
			name := ri.WhoHasThemName
			color := "black"
			switch ri.WhoHasThemType {
			case "Employee":
				color = "red"
			case "DeviceCheckCompany":
				color = "blue"
			}

			if color != "black" {
				name = fmt.Sprintf(`<strong style="color:%s">%s</string>`, color, name)
			}

			return template.HTML(name)
		},
	})

	cdIn := adm.AddResource(&db.ClientDeviceIn{}, &admin.Config{
		Menu:       []string{"日常操作"},
		Permission: noUpdatePermission,
	})

	cdIn.Meta(&admin.Meta{Name: "WarehouseID", Type: "select_one", Collection: db.WarehouseCollection})
	cdIn.Meta(&admin.Meta{Name: "ByWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	// cdIn.Scope(&admin.Scope{
	// 	Default: true,
	// 	Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
	// 		return db.Preload("Device").Preload("Client")
	// 	},
	// })
	cdIn.IndexAttrs("ClientName", "DeviceName", "WarehouseName", "Quantity", "ByWhomName", "Date")
	cdIn.NewAttrs("ClientName", "DeviceName", "WarehouseID", "Quantity", "ByWhomID", "Date")
	cdIn.Meta(&admin.Meta{Name: "Date", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		date := resource.(*db.ClientDeviceIn).Date
		if date.IsZero() {
			date = time.Now()
		}
		return date
	}})

	cdOut := adm.AddResource(&db.ClientDeviceOut{}, &admin.Config{
		Menu:       []string{"日常操作"},
		Permission: noUpdatePermission,
	})

	cdOut.Meta(&admin.Meta{Name: "ReportItemID", Type: "select_one", Collection: db.CurrentClientDeviceCollection})
	cdOut.Meta(&admin.Meta{Name: "ByWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	cdOut.Meta(&admin.Meta{Name: "Date", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		date := resource.(*db.ClientDeviceOut).Date
		if date.IsZero() {
			date = time.Now()
		}
		return date
	}})

	// cdOut.Scope(&admin.Scope{
	// 	Default: true,
	// 	Handle: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
	// 		return db.Preload("Device").Preload("Client")
	// 	},
	// })
	cdOut.IndexAttrs("ClientName", "DeviceName", "Quantity", "WarehouseName", "ByWhomName", "Date")
	cdOut.NewAttrs("ReportItemID", "ByWhomID", "Date")

	deviceOut := adm.AddResource(&db.DeviceOut{}, &admin.Config{
		Menu:       []string{"日常操作"},
		Permission: noUpdatePermission,
	})

	deviceOut.IndexAttrs("ToWhomName", "FromWarehouseName", "DeviceName", "Quantity", "ByWhomName", "Date")
	deviceOut.NewAttrs("FromReportItemID", "Quantity", "ToWhomID", "ByWhomID", "Date")
	deviceOut.Meta(&admin.Meta{Name: "FromReportItemID", Type: "select_one", Collection: db.CurrentWarehouseDeviceCollection})
	deviceOut.Meta(&admin.Meta{Name: "ToWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	deviceOut.Meta(&admin.Meta{Name: "ByWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	deviceOut.Meta(&admin.Meta{Name: "Date", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		date := resource.(*db.DeviceOut).Date
		if date.IsZero() {
			date = time.Now()
		}
		return date
	}})

	deviceIn := adm.AddResource(&db.DeviceIn{}, &admin.Config{
		Menu:       []string{"日常操作"},
		Permission: noUpdatePermission,
	})
	deviceIn.IndexAttrs("FromWhomName", "ToWarehouseName", "DeviceName", "Quantity", "ByWhomName", "Date")
	deviceIn.NewAttrs("FromReportItemID", "Quantity", "ToWarehouseID", "ByWhomID", "Date")
	deviceIn.Meta(&admin.Meta{Name: "FromReportItemID", Type: "select_one", Collection: db.CurrentEmployeeDeviceCollection})
	deviceIn.Meta(&admin.Meta{Name: "ToWarehouseID", Type: "select_one", Collection: db.WarehouseCollection})
	deviceIn.Meta(&admin.Meta{Name: "ByWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	deviceIn.Meta(&admin.Meta{Name: "Date", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		date := resource.(*db.DeviceIn).Date
		if date.IsZero() {
			date = time.Now()
		}
		return date
	}})

	deviceCheckOut := adm.AddResource(&db.ClientDeviceCheckOut{}, &admin.Config{
		Menu:       []string{"日常操作"},
		Permission: noUpdatePermission,
	})
	deviceCheckOut.IndexAttrs("FromWarehouseName", "ToDeviceCheckCompanyName", "DeviceName", "ClientName", "Quantity", "ByWhomName", "Date")
	deviceCheckOut.NewAttrs("FromReportItemID", "Quantity", "ToDeviceCheckCompanyID", "ByWhomID", "Date")
	deviceCheckOut.Meta(&admin.Meta{Name: "FromReportItemID", Type: "select_one", Collection: db.CurrentClientDeviceCollection})
	deviceCheckOut.Meta(&admin.Meta{Name: "ToDeviceCheckCompanyID", Type: "select_one", Collection: db.DeviceCheckCompanyCollection})
	deviceCheckOut.Meta(&admin.Meta{Name: "ByWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	deviceCheckOut.Meta(&admin.Meta{Name: "Date", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		date := resource.(*db.ClientDeviceCheckOut).Date
		if date.IsZero() {
			date = time.Now()
		}
		return date
	}})

	deviceCheckIn := adm.AddResource(&db.ClientDeviceCheckIn{}, &admin.Config{
		Menu:       []string{"日常操作"},
		Permission: noUpdatePermission,
	})

	deviceCheckIn.IndexAttrs("FromDeviceCheckCompanyName", "ToWarehouseName", "DeviceName", "Quantity", "ByWhomName", "Date")
	deviceCheckIn.NewAttrs("FromReportItemID", "Quantity", "ToWarehouseID", "ByWhomID", "Date")
	deviceCheckIn.Meta(&admin.Meta{Name: "FromReportItemID", Type: "select_one", Collection: db.CurrentDeviceCheckCollection})
	deviceCheckIn.Meta(&admin.Meta{Name: "ToWarehouseID", Type: "select_one", Collection: db.WarehouseCollection})
	deviceCheckIn.Meta(&admin.Meta{Name: "ByWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	deviceCheckIn.Meta(&admin.Meta{Name: "Date", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		date := resource.(*db.ClientDeviceCheckIn).Date
		if date.IsZero() {
			date = time.Now()
		}
		return date
	}})

	consumableOut := adm.AddResource(&db.ConsumableOut{}, &admin.Config{
		Menu:       []string{"日常操作"},
		Permission: noUpdatePermission,
	})
	consumableOut.IndexAttrs("DeviceName", "Quantity", "ToWhomName", "WarehouseName", "ByWhomName", "Date")
	consumableOut.NewAttrs("ReportItemID", "Quantity", "ToWhomID", "ByWhomID", "Date")
	consumableOut.Meta(&admin.Meta{Name: "ReportItemID", Type: "select_one", Collection: db.CurrentConsumableCollection})
	consumableOut.Meta(&admin.Meta{Name: "ToWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	consumableOut.Meta(&admin.Meta{Name: "ByWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	consumableOut.Meta(&admin.Meta{Name: "Date", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		date := resource.(*db.ConsumableOut).Date
		if date.IsZero() {
			date = time.Now()
		}
		return date
	}})

	consumableIn := adm.AddResource(&db.ConsumableIn{}, &admin.Config{
		Menu:       []string{"日常操作"},
		Permission: noUpdatePermission,
	})

	consumableIn.IndexAttrs("DeviceName", "Quantity", "WarehouseName", "ByWhomName", "Date")
	consumableIn.NewAttrs("ReportItemID", "Quantity", "ToWhomID", "ByWhomID", "Date")
	consumableIn.Meta(&admin.Meta{Name: "ReportItemID", Type: "select_one", Collection: db.CurrentConsumableCollection})
	consumableIn.Meta(&admin.Meta{Name: "ByWhomID", Type: "select_one", Collection: db.EmployeeCollection})
	consumableIn.Meta(&admin.Meta{Name: "Date", Valuer: func(resource interface{}, ctx *qor.Context) interface{} {
		date := resource.(*db.ConsumableIn).Date
		if date.IsZero() {
			date = time.Now()
		}
		return date
	}})

	device := adm.AddResource(&db.Device{}, &admin.Config{Menu: []string{"数据维护"}})
	device.Meta(&admin.Meta{Name: "CategoryID", Type: "select_one", Collection: db.DeviceCategories})
	device.Meta(&admin.Meta{Name: "WarehouseID", Type: "select_one", Collection: db.WarehouseCollection})
	device.Meta(&admin.Meta{Name: "Note", Type: "rich_editor"})
	device.EditAttrs("Name", "Code", "TotalQuantity", "TypeSize", "UnitName", "MakerName", "MakeDate", "FromSource", "Note")
	device.NewAttrs("Name", "Code", "CategoryID", "TotalQuantity", "WarehouseID", "TypeSize", "UnitName", "MakerName", "MakeDate", "FromSource", "Note")
	device.IndexAttrs("Name", "Code", "CategoryName", "TypeSize", "MakerName", "TotalQuantity")

	employee := adm.AddResource(&db.Employee{}, &admin.Config{Menu: []string{"数据维护"}})
	employee.IndexAttrs("Name", "Title", "Mobile")

	warehouse := adm.AddResource(&db.Warehouse{}, &admin.Config{Menu: []string{"数据维护"}})
	warehouse.Meta(&admin.Meta{Name: "Name", Type: "string"})
	warehouse.Meta(&admin.Meta{Name: "Address", Type: "string"})
	warehouse.EditAttrs("Name", "Address")
	warehouse.NewAttrs(warehouse.EditAttrs())
	warehouse.IndexAttrs("Name", "Address")

	deviceCheckCompany := adm.AddResource(&db.DeviceCheckCompany{}, &admin.Config{Menu: []string{"数据维护"}})
	deviceCheckCompany.Meta(&admin.Meta{Name: "Name", Type: "string"})
	deviceCheckCompany.Meta(&admin.Meta{Name: "Address", Type: "string"})
	deviceCheckCompany.EditAttrs("Name", "Address")
	deviceCheckCompany.NewAttrs(warehouse.EditAttrs())
	deviceCheckCompany.IndexAttrs("Name", "Address")

	I18nBackend := database.New(&db.DB)
	// config.I18n = i18n.New(I18nBackend)
	adm.AddResource(i18n.New(I18nBackend), &admin.Config{Menu: []string{"系统设置"}, Invisible: true})

	adm.MountTo("/admin", http.DefaultServeMux)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/admin/report_items", 302)
	})

	log.Println("Starting Server at 9000.")
	err := http.ListenAndServe(":9000", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
示例#14
0
文件: main.go 项目: gitter-badger/qor
func main() {
	Admin := admin.New(&qor.Config{DB: Publish.DraftDB()})
	Admin.SetAuth(&Auth{})

	Admin.AddMenu(&admin.Menu{Name: "Dashboard", Link: "/admin"})

	creditcard := Admin.AddResource(&CreditCard{}, &admin.Config{Invisible: true})
	creditcard.Meta(&admin.Meta{Name: "issuer", Type: "select_one", Collection: []string{"VISA", "MasterCard", "UnionPay", "JCB", "American Express", "Diners Club"}})

	user := Admin.AddResource(&User{}, &admin.Config{Menu: []string{"Users Management"}})

	user.Scope(&admin.Scope{Name: "active", Group: "Status", Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB {
		return db.Where("state = ?", "Active")
	}})
	user.Scope(&admin.Scope{Name: "inactive", Group: "Status", Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB {
		return db.Where("state = ?", "Inactive")
	}})
	user.Scope(&admin.Scope{Name: "enabled", Handle: func(db *gorm.DB, context *qor.Context) *gorm.DB { return db }})

	user.Meta(&admin.Meta{Name: "CreditCard", Resource: creditcard})
	user.Meta(&admin.Meta{Name: "fullname", Alias: "name"})

	user.Meta(&admin.Meta{Name: "State", Type: "select_one", Collection: []string{"Active", "Inactive"}})
	user.Meta(&admin.Meta{Name: "Role", Type: "select_one"})

	user.Meta(&admin.Meta{Name: "Languages", Type: "select_many"})
	Asset := Admin.AddResource(&admin.AssetManager{})
	user.Meta(&admin.Meta{Name: "description", Type: "rich_editor", Resource: Asset})

	Admin.AddResource(&Language{}, &admin.Config{Name: "Locales", Menu: []string{"Products Management"}})

	product := Admin.AddResource(&Product{}, &admin.Config{Menu: []string{"Products Management"}})
	product.SearchAttrs("Name", "Description")
	product.Meta(&admin.Meta{Name: "Collection", Type: "select_one"})

	Admin.AddResource(&Collection{}, &admin.Config{Menu: []string{"Products Management"}})
	Admin.AddResource(&Order{}, &admin.Config{Menu: []string{"Orders Management"}})

	I18n := i18n.New(database.New(Publish.DraftDB()))
	Admin.AddResource(I18n)

	Admin.AddResource(Publish)

	mux := http.NewServeMux()
	Admin.MountTo("/admin", mux)
	mux.Handle("/system/", http.FileServer(http.Dir("public")))
	mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		var user User

		if request.Method == "POST" {
			request.ParseForm()
			if !DB.First(&user, "name = ?", request.Form.Get("username")).RecordNotFound() {
				cookie := http.Cookie{Name: "userid", Value: fmt.Sprintf("%v", user.ID), Expires: time.Now().AddDate(1, 0, 0)}
				http.SetCookie(writer, &cookie)
				writer.Write([]byte("<html><body>logged as `" + user.Name + "`, go <a href='/admin'>admin</a></body></html>"))
			} else {
				http.Redirect(writer, request, "/login?failed_to_login", 301)
			}
		} else if userid, err := request.Cookie("userid"); err == nil {
			if !DB.First(&user, "id = ?", userid.Value).RecordNotFound() {
				writer.Write([]byte("<html><body>already logged as `" + user.Name + "`, go <a href='/admin'>admin</a></body></html>"))
			} else {
				http.Redirect(writer, request, "/logout", http.StatusSeeOther)
			}
		} else {
			writer.Write([]byte(`<html><form action="/login" method="POST"><input name="username" value="" placeholder="username"><input type=submit value="Login"></form></html>`))
		}
	})

	mux.HandleFunc("/logout", func(writer http.ResponseWriter, request *http.Request) {
		cookie := http.Cookie{Name: "userid", MaxAge: -1}
		http.SetCookie(writer, &cookie)
		http.Redirect(writer, request, "/login?logged_out", http.StatusSeeOther)
	})

	fmt.Println("listening on :9000")
	http.ListenAndServe(":9000", mux)
}