Commit 8d731b5d authored by fodorpatrik2000's avatar fodorpatrik2000 👻
Browse files

separate model from db queries

parent be61bc93
Pipeline #9096 failed
package db
import (
"encoding/json"
"fmt"
"git.sch.bme.hu/disappointment-industries/becskasszasch/helpers"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"gitlab.com/MikeTTh/env"
"io/ioutil"
"strings"
"time"
)
const TopupID = "topup"
type Spend struct {
ID string `pg:"id,pk,default:gen_random_uuid()"`
SchAcc string `pg:"user_schacc"`
ProdID string `pg:"product_id"`
Amount int64 `pg:"amount,default:1"`
Date time.Time `pg:"date,default:now()"`
Notes string `pg:"notes"`
User *User `pg:"rel:has-one,join_fk:user_schacc"`
Product *Product `pg:"rel:has-one,join_fk:product_id"`
}
type Product struct {
ID string `pg:"id,pk"`
Name string `pg:"name"`
IconURI string `pg:"icon_uri"`
Price int64 `pg:"price,use_zero"`
Buyable bool `pg:"buyable,use_zero"`
}
type User struct {
SchAcc string `pg:"schacc,pk"`
Name string `pg:"name"`
Money int64 `pg:"money,use_zero"`
IsAdmin bool `pg:"is_admin,default:false"`
Spends []*Spend `pg:"rel:has-many,join_fk:user_schacc"`
}
type Session struct {
Id string `pg:"id,pk,default:gen_random_uuid()"`
SchAcc string `pg:"user_schacc"`
DarkTheme bool `pg:"dark_theme,default:true"`
User *User `pg:"rel:has-one,join_fk:user_schacc"`
}
type Payout struct {
Id string `pg:"id,pk,default:gen_random_uuid()"`
ProdGroupID string `pg:"product_group_id"`
Amount int64 `pg:"amount"`
Date time.Time `pg:"date,default:now()"`
ProductGroup *ProductGroup `pg:"rel:has-one,join_fk:product_group_id"`
}
type ProductGroup struct {
Id string `pg:"id,pk,default:gen_random_uuid()"`
Name string `pg:"name"`
}
type ProductCategories struct {
Id string `pg:"id,pk,default:gen_random_uuid()"`
ProdID string `pg:"product_id"`
ProdGroupID string `pg:"product_group_id"`
Product *Product `pg:"rel:has-one,join_fk:product_id"`
ProductGroup *ProductGroup `pg:"rel:has-one,join_fk:product_group_id"`
}
var db = pg.Connect(&pg.Options{
Addr: func() string {
host := env.String("POSTGRES", "localhost")
if !strings.Contains(host, ":") {
host += ":5432"
}
return host
}(),
User: env.String("POSTGRES_USER", "postgres"),
Password: env.String("POSTGRES_PASS", "postgres"),
Database: env.String("POSTGRES_DB", "postgres"),
})
var spendsNow = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "becskasszasch",
Name: "products_bought",
Help: "Products bought",
}, []string{"product"})
func init() {
models := []interface{}{
(*Product)(nil),
(*User)(nil),
(*Spend)(nil),
(*Session)(nil),
(*ProductGroup)(nil),
(*ProductCategories)(nil),
(*Payout)(nil),
}
for _, model := range models {
err := db.Model(model).CreateTable(&orm.CreateTableOptions{
IfNotExists: true,
FKConstraints: true,
})
if err != nil {
panic(err)
}
}
// TODO: Auto-migrate: https://github.com/go-pg/pg/issues/728#issuecomment-433345074
// Auto-create products
b, e := ioutil.ReadFile("db/products.json")
if e == nil {
var prods []*Product
e = json.Unmarshal(b, &prods)
for _, p := range prods {
_, e := db.Model(p).Insert()
if e != nil && !strings.Contains(e.Error(), "ERROR #23505") {
helpers.Logger.Println(e)
}
}
}
// Auto-create topup
top := &Product{
ID: TopupID,
Name: "Feltöltés",
IconURI: "/static/images/kszkoin.svg",
Buyable: false,
Price: -1,
}
_, e = db.Model(top).Insert()
if e != nil {
_, e := db.Model(top).WherePK().Update()
if e != nil {
panic(e)
}
}
prod, err := GetProducts()
if err != nil {
// TODO
}
for _, p := range prod {
s, _ := GetSpends(p.ID)
var a float64
if s != nil {
for _, u := range s {
a += float64(u.Amount)
}
}
spendsNow.With(prometheus.Labels{"product": p.Name}).Add(a)
}
//GetSpendsBetween(time.Date(2021,7,19, 0, 0, 0, 0, time.Local), time.Date(2021,8,18, 0, 0, 0, 0, time.Local))
}
func StoreUserAndGiveCookie(SchAcc, Name string) (string, error) {
u := &User{
SchAcc: SchAcc,
......@@ -287,6 +131,94 @@ func GetSpendsBetween(from, to string) (map[string]*int64, map[string]*Product,
return m, products, nil
}
func GetMoney() (map[string]*int64, map[string]*ProductGroup, error) {
var res []*Spend
e := db.Model(&res).Relation("Product").Relation("Product.ProductGroup").Select()
if e != nil {
return nil, nil, e
}
m := make(map[string]*int64)
products := make(map[string]*ProductGroup)
for _, sp := range res {
val, ok := m[sp.Product.ProductGroup.Name]
if !ok {
val = new(int64)
m[sp.Product.ProductGroup.Name] = val
}
*val += sp.Amount * sp.Product.Price
if _, ok := products[sp.Product.ProductGroup.Name]; !ok {
products[sp.Product.ProductGroup.Name] = sp.Product.ProductGroup
}
}
/* for p := range products {
fmt.Print(p + ":")
fmt.Print(*m[p])
fmt.Println()
}*/
return m, products, nil
}
func GetPayouts() (map[string]*int64, error) {
var res []*Payout
e := db.Model(&res).Relation("ProductGroup").Select()
if e != nil {
return nil, e
}
m := make(map[string]*int64)
for _, pay := range res {
val, ok := m[pay.ProductGroup.Name]
if !ok {
val = new(int64)
m[pay.ProductGroup.Name] = val
}
*val += pay.Price
}
return m, nil
}
func GetBalance() (map[string]*int64, map[string]*ProductGroup, error) {
allMoney, groupList, err := GetMoney()
if err != nil {
return nil, nil, err
}
allPayout, e := GetPayouts()
if e != nil {
return nil, nil, e
}
m := make(map[string]*int64)
fmt.Println("-------------------------------")
for g := range groupList {
m[g] = new(int64)
if allPayout[g] != nil {
*m[g] = *allMoney[g] - *allPayout[g]
} else {
*m[g] = *allMoney[g]
}
fmt.Print(g + ":")
fmt.Print(*m[g])
fmt.Println()
}
return m, groupList, err
}
func GetSpends(typ string) ([]*Spend, error) {
var spends []*Spend
......@@ -315,6 +247,18 @@ func (p *Product) Save() error {
return update(p)
}
func (p *Payout) Save() error {
return update(p)
}
func (p *ProductGroup) Save() error {
return update(p)
}
/*func (p *ProductCategories) Save() error {
return update(p)
}*/
func (p *Product) Load() error {
e := db.Model(p).WherePK().First()
......@@ -350,3 +294,8 @@ func (sp *Spend) Delete() error {
_, e := db.Model(sp).WherePK().Delete()
return e
}
func (p *Payout) Delete() error {
_, e := db.Model(p).WherePK().Delete()
return e
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment