feat: update

This commit is contained in:
Rogee
2025-05-23 20:07:34 +08:00
parent 9b38699764
commit 57cb0a750b
53 changed files with 741 additions and 982 deletions

View File

@@ -0,0 +1,24 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"quyun/database/fields"
"time"
)
type Medias struct {
ID int64 `sql:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
Name string `json:"name"`
MimeType string `json:"mime_type"`
Size int64 `json:"size"`
Path string `json:"path"`
Metas fields.Json[fields.MediaMetas] `json:"metas"`
Hash string `json:"hash"`
}

270
backend/app/model/medias.go Normal file
View File

@@ -0,0 +1,270 @@
package model
import (
"context"
"time"
"quyun/app/requests"
"quyun/database/fields"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Medias) log() *log.Entry {
return log.WithField("model", "MediasModel")
}
func (m *Medias) BuildConditionWithKey(key *string) BoolExpression {
tbl := table.Medias
cond := Bool(true)
if key == nil || *key == "" {
return cond
}
cond = cond.AND(
tbl.Name.LIKE(String("%" + *key + "%")),
)
return cond
}
// countByCond
func (m *Medias) countByCondition(ctx context.Context, expr BoolExpression) (int64, error) {
var cnt struct {
Cnt int64
}
tbl := table.Medias
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting media items: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
func (m *Medias) List(ctx context.Context, pagination *requests.Pagination, expr BoolExpression) (*requests.Pager, error) {
pagination.Format()
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(expr).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log().Infof("sql: %s", stmt.DebugSql())
var medias []Medias
err := stmt.QueryContext(ctx, db, &medias)
if err != nil {
m.log().Errorf("error querying media items: %v", err)
return nil, err
}
count, err := m.countByCondition(ctx, expr)
if err != nil {
m.log().Errorf("error getting media count: %v", err)
return nil, err
}
return &requests.Pager{
Items: medias,
Total: count,
Pagination: *pagination,
}, nil
}
func (m *Medias) BatchCreate(ctx context.Context, models []*Medias) error {
stmt := table.Medias.INSERT(table.Medias.MutableColumns).MODELS(models)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error creating media item: %v", err)
return err
}
m.log().Infof("media item created successfully")
return nil
}
func (m *Medias) Create(ctx context.Context, medias *Medias) error {
medias.CreatedAt = time.Now()
stmt := table.Medias.INSERT(table.Medias.MutableColumns).MODEL(medias).RETURNING(table.Medias.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, medias); err != nil {
m.log().Errorf("error creating media item: %v", err)
return err
}
m.log().Infof("media item created successfully")
return nil
}
// GetByIds
func (m *Medias) GetByIds(ctx context.Context, ids []int64) ([]*Medias, error) {
if len(ids) == 0 {
return nil, nil
}
condIds := lo.Map(ids, func(id int64, _ int) Expression {
return Int64(id)
})
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(tbl.ID.IN(condIds...))
m.log().Infof("sql: %s", stmt.DebugSql())
var medias []Medias
err := stmt.QueryContext(ctx, db, &medias)
if err != nil {
m.log().Errorf("error querying media items: %v", err)
return nil, err
}
return lo.Map(medias, func(media Medias, _ int) *Medias {
return &media
}), nil
}
// GetByHash
func (m *Medias) GetByHash(ctx context.Context, hash string) (*Medias, error) {
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(tbl.Hash.EQ(String(hash)))
m.log().Infof("sql: %s", stmt.DebugSql())
var media Medias
err := stmt.QueryContext(ctx, db, &media)
if err != nil {
m.log().Errorf("error querying media item by hash: %v", err)
return nil, err
}
return &media, nil
}
// Update
func (m *Medias) Update(ctx context.Context, hash string, model *Medias) error {
tbl := table.Medias
stmt := tbl.
UPDATE(tbl.MutableColumns.Except(tbl.CreatedAt)).
MODEL(model).
WHERE(table.Medias.Hash.EQ(String(hash)))
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().WithField("hash", hash).Errorf("error updating media item: %v", err)
return err
}
m.log().Infof("media item updated successfully")
return nil
}
// GetByID
func (m *Medias) GetByID(ctx context.Context, id int64) (*Medias, error) {
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(tbl.ID.EQ(Int64(id)))
m.log().Infof("sql: %s", stmt.DebugSql())
var media Medias
if err := stmt.QueryContext(ctx, db, &media); err != nil {
m.log().Errorf("error querying media item by ID: %v", err)
return nil, err
}
return &media, nil
}
// Delete
func (m *Medias) Delete(ctx context.Context, id int64) error {
tbl := table.Medias
stmt := tbl.
DELETE().
WHERE(tbl.ID.EQ(Int64(id)))
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error deleting media item: %v", err)
return err
}
m.log().Infof("media item deleted successfully")
return nil
}
// UpdateMetas
func (m *Medias) UpdateMetas(ctx context.Context, id int64, metas fields.MediaMetas) error {
meta := fields.ToJson(metas)
tbl := table.Medias
stmt := tbl.
UPDATE(tbl.Metas).
SET(meta).
WHERE(tbl.ID.EQ(Int64(id)))
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating media metas: %v", err)
return err
}
m.log().Infof("media (%d) metas updated successfully", id)
return nil
}
// GetRelationMedias
func (m *Medias) GetRelations(ctx context.Context, hash string) ([]*Medias, error) {
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
RawBool("metas->>'parent_hash' = ?", RawArgs{"?": hash}),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var medias []Medias
if err := stmt.QueryContext(ctx, db, &medias); err != nil {
m.log().Errorf("error querying media items: %v", err)
return nil, err
}
return lo.Map(medias, func(media Medias, _ int) *Medias {
return &media
}), nil
}
// Count
func (m *Medias) Count(ctx context.Context) (int64, error) {
tbl := table.Medias
stmt := tbl.SELECT(COUNT(tbl.ID).AS("count"))
m.log().Infof("sql: %s", stmt.DebugSql())
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting media items: %v", err)
return 0, err
}
return count.Count, nil
}

View File

@@ -0,0 +1,226 @@
package model
import (
"context"
"fmt"
"math"
"math/rand"
"testing"
"time"
"quyun/app/requests"
"quyun/app/service/testx"
"quyun/database"
"quyun/database/table"
. "github.com/smartystreets/goconvey/convey"
"go.ipao.vip/atom/contracts"
// . "github.com/go-jet/jet/v2/postgres"
"github.com/stretchr/testify/suite"
"go.uber.org/dig"
)
type MediasInjectParams struct {
dig.In
Initials []contracts.Initial `group:"initials"`
}
type MediasTestSuite struct {
suite.Suite
MediasInjectParams
}
func Test_Medias(t *testing.T) {
providers := testx.Default().With(Provide)
testx.Serve(providers, t, func(params MediasInjectParams) {
suite.Run(t, &MediasTestSuite{
MediasInjectParams: params,
})
})
}
func (s *MediasTestSuite) Test_Demo() {
Convey("Test_Demo", s.T(), func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
})
}
func (s *MediasTestSuite) Test_countByCondition() {
Convey("countByCondition", s.T(), func() {
Convey("no cond", func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
cnt, err := MediasModel.countByCondition(context.Background(), nil)
Convey("should not return an error", func() {
So(err, ShouldBeNil)
})
Convey("should return a count of zero", func() {
So(cnt, ShouldEqual, 0)
})
})
})
}
func (s *MediasTestSuite) Test_BatchCreate() {
Convey("Create", s.T(), func() {
Convey("valid media", func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
models := []*Medias{
{
Name: "test 01",
CreatedAt: time.Now(),
MimeType: "video/mp4",
Size: rand.Int63n(math.MaxInt64), // Random size
Path: "path/to/media.mp4",
},
{
Name: "test 02",
CreatedAt: time.Now(),
MimeType: "audio/mp3",
Size: rand.Int63n(math.MaxInt64), // Random size
Path: "path/to/media.mp3",
},
{
Name: "test 03",
CreatedAt: time.Now(),
MimeType: "application/pdf",
Size: rand.Int63n(math.MaxInt64), // Random size
Path: "path/to/media.pdf",
},
{
Name: "test 04",
CreatedAt: time.Now(),
MimeType: "image/jpeg",
Size: rand.Int63n(math.MaxInt64), // Random size
Path: "path/to/media.jpeg",
},
{
Name: "test 05",
CreatedAt: time.Now(),
MimeType: "application/zip",
Size: rand.Int63n(math.MaxInt64), // Random size
Path: "path/to/media.zip",
},
}
count := 10
for i := 0; i < count; i++ {
err := MediasModel.BatchCreate(context.Background(), models)
Convey("Create should not return an error: "+fmt.Sprintf("%d", i), func() {
So(err, ShouldBeNil)
})
}
})
})
}
func (s *MediasTestSuite) Test_Create() {
Convey("Create", s.T(), func() {
Convey("valid media", func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
model := &Medias{
Name: "test",
CreatedAt: time.Now(),
MimeType: "application/pdf",
Size: 100,
Path: "path/to/media.pdf",
}
err := MediasModel.Create(context.Background(), model)
Convey("Create should not return an error", func() {
So(err, ShouldBeNil)
})
cnt, err := MediasModel.countByCondition(context.Background(), nil)
Convey("Count should not return an error", func() {
So(err, ShouldBeNil)
})
Convey("should return a count of one", func() {
So(cnt, ShouldEqual, 1)
})
Convey("should create the media successfully", func() {
So(model.ID, ShouldNotBeEmpty)
})
})
})
}
func (s *MediasTestSuite) Test_Page() {
Convey("Create", s.T(), func() {
Convey("Insert Items", func() {
database.Truncate(context.Background(), db, table.Medias.TableName())
for i := 0; i < 20; i++ {
model := &Medias{
Name: fmt.Sprintf("test-%d", i),
CreatedAt: time.Now(),
MimeType: "application/pdf",
Size: 100,
Path: "path/to/media.pdf",
}
err := MediasModel.Create(context.Background(), model)
So(err, ShouldBeNil)
}
cnt, err := MediasModel.countByCondition(context.Background(), nil)
So(err, ShouldBeNil)
So(cnt, ShouldEqual, 20)
})
Convey("Page", func() {
Convey("page 1", func() {
pager, err := MediasModel.List(context.Background(), &requests.Pagination{Page: 1, Limit: 10}, nil)
So(err, ShouldBeNil)
So(pager.Total, ShouldEqual, 20)
So(pager.Items, ShouldHaveLength, 10)
})
Convey("page 2", func() {
pager, err := MediasModel.List(context.Background(), &requests.Pagination{Page: 2, Limit: 10}, nil)
So(err, ShouldBeNil)
So(pager.Total, ShouldEqual, 20)
So(pager.Items, ShouldHaveLength, 10)
})
Convey("page 3", func() {
pager, err := MediasModel.List(context.Background(), &requests.Pagination{Page: 3, Limit: 10}, nil)
So(err, ShouldBeNil)
So(pager.Total, ShouldEqual, 20)
So(pager.Items, ShouldBeEmpty)
})
})
})
}
func (s *MediasTestSuite) Test_CreateGetID() {
Convey("Create", s.T(), func() {
model := &Medias{
Name: fmt.Sprintf("test-%d", 1),
CreatedAt: time.Now(),
MimeType: "application/pdf",
Size: 100,
Path: "path/to/media.pdf",
}
err := MediasModel.Create(context.Background(), model)
So(err, ShouldBeNil)
So(model.ID, ShouldNotBeEmpty)
s.T().Logf("model id :%d", model.ID)
})
}
func (s *MediasTestSuite) Test_GetRelations() {
Convey("GetByHash", s.T(), func() {
hash := "ce4cd071128cef282cf315dda75bdab4"
media, err := MediasModel.GetRelations(context.Background(), hash)
So(err, ShouldBeNil)
So(media, ShouldNotBeNil)
s.T().Logf("media: %+v", media)
})
}

View File

@@ -0,0 +1,19 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"time"
)
type Migrations struct {
ID int32 `sql:"primary_key" json:"id"`
VersionID int64 `json:"version_id"`
IsApplied bool `json:"is_applied"`
Tstamp time.Time `json:"tstamp"`
}

View File

@@ -0,0 +1,31 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"quyun/database/fields"
"time"
)
type Orders struct {
ID int64 `sql:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
OrderNo string `json:"order_no"`
SubOrderNo string `json:"sub_order_no"`
TransactionID string `json:"transaction_id"`
RefundTransactionID string `json:"refund_transaction_id"`
Price int64 `json:"price"`
Discount int16 `json:"discount"`
Currency string `json:"currency"`
PaymentMethod string `json:"payment_method"`
PostID int64 `json:"post_id"`
UserID int64 `json:"user_id"`
Status fields.OrderStatus `json:"status"`
Meta fields.Json[fields.OrderMeta] `json:"meta"`
}

326
backend/app/model/orders.go Normal file
View File

@@ -0,0 +1,326 @@
package model
import (
"context"
"fmt"
"time"
"quyun/app/requests"
"quyun/database/fields"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/pkg/errors"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Orders) log() *log.Entry {
return log.WithField("model", "OrdersModel")
}
// GetByID returns an order by ID
func (m *Orders) GetByID(ctx context.Context, id int64) (*Orders, error) {
tbl := table.Orders
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var order Orders
err := stmt.QueryContext(ctx, db, &order)
if err != nil {
m.log().Errorf("error querying order by ID: %v", err)
return nil, err
}
return &order, nil
}
// BuildConditionWithKey builds the WHERE clause for order queries
func (m *Orders) BuildConditionWithKey(orderNumber *string, userID *int64) BoolExpression {
tbl := table.Orders
cond := Bool(true)
if orderNumber != nil && *orderNumber != "" {
cond = cond.AND(
tbl.OrderNo.LIKE(String("%" + *orderNumber + "%")),
)
}
if userID != nil {
cond = cond.AND(
tbl.UserID.EQ(Int(*userID)),
)
}
return cond
}
// countByCondition counts orders matching the given condition
func (m *Orders) countByCondition(ctx context.Context, expr BoolExpression) (int64, error) {
var cnt struct {
Cnt int64
}
tbl := table.Orders
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting orders: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
// List returns a paginated list of orders
func (m *Orders) List(ctx context.Context, pagination *requests.Pagination, cond BoolExpression) (*requests.Pager, error) {
pagination.Format()
tbl := table.Orders
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(cond).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log().Infof("sql: %s", stmt.DebugSql())
var orders []Orders = make([]Orders, 0)
if err := stmt.QueryContext(ctx, db, &orders); err != nil {
m.log().Errorf("error querying orders: %v", err)
return nil, err
}
postsMap, err := PostsModel.GetPostsMapByIDs(ctx, lo.Map(orders, func(order Orders, _ int) int64 {
return order.PostID
}))
if err != nil {
m.log().Errorf("error getting posts map: %v", err)
return nil, err
}
userMap, err := UsersModel.GetUsersMapByIDs(ctx, lo.Map(orders, func(order Orders, _ int) int64 {
return order.UserID
}))
if err != nil {
m.log().Errorf("error getting users map: %v", err)
return nil, err
}
count, err := m.countByCondition(ctx, cond)
if err != nil {
m.log().Errorf("error getting order count: %v", err)
return nil, err
}
type orderItem struct {
Orders
PostTitle string `json:"post_title"`
Username string `json:"username"`
}
return &requests.Pager{
Items: lo.Map(orders, func(order Orders, _ int) *orderItem {
item := &orderItem{
Orders: order,
}
if post, ok := postsMap[order.PostID]; ok {
item.PostTitle = post.Title
}
if user, ok := userMap[order.UserID]; ok {
item.Username = user.Username
}
return item
}),
Total: count,
Pagination: *pagination,
}, nil
}
// Create creates a new order
func (o *Orders) Create(ctx context.Context, userId, postId int64) (*Orders, error) {
post, err := PostsModel.GetByID(ctx, postId)
if err != nil {
return nil, errors.Wrap(err, "failed to get post")
}
m := &Orders{}
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
m.Status = fields.OrderStatusPending
m.OrderNo = fmt.Sprintf("%s", time.Now().Format("20060102150405"))
m.SubOrderNo = m.OrderNo
m.UserID = userId
m.PostID = postId
m.Meta = fields.ToJson(fields.OrderMeta{})
m.Price = post.Price
m.Discount = post.Discount
tbl := table.Orders
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(m).RETURNING(tbl.AllColumns)
o.log().Infof("sql: %s", stmt.DebugSql())
var order Orders
if err := stmt.QueryContext(ctx, db, &order); err != nil {
o.log().Errorf("error creating order: %v", err)
return nil, err
}
return &order, nil
}
func (m *Orders) SetMeta(ctx context.Context, id int64, metaFunc func(fields.OrderMeta) fields.OrderMeta) error {
order, err := m.GetByID(ctx, id)
if err != nil {
return errors.Wrap(err, "failed to get order")
}
tbl := table.Orders
stmt := tbl.
UPDATE(tbl.Meta).
SET(fields.ToJson(metaFunc(order.Meta.Data))).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error set order meta: %v", err)
return err
}
return nil
}
// DeleteByID soft deletes an order by ID
func (m *Orders) SetStatus(ctx context.Context, orderNo string, status fields.OrderStatus) error {
tbl := table.Orders
stmt := tbl.
UPDATE(tbl.Status).
SET(status).
WHERE(
tbl.OrderNo.EQ(String(orderNo)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error set order status: %v", err)
return err
}
return nil
}
// Count
func (m *Orders) Count(ctx context.Context, cond BoolExpression) (int64, error) {
tbl := table.Orders
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var cnt struct {
Cnt int64
}
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting orders: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
// SumAmount
func (m *Orders) SumAmount(ctx context.Context) (int64, error) {
tbl := table.Orders
stmt := SELECT(SUM(tbl.Price).AS("cnt")).FROM(tbl).WHERE(
tbl.Status.EQ(Int(int64(fields.OrderStatusCompleted))),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var cnt struct {
Cnt int64
}
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error summing order amount: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
// GetByOrderNo
func (m *Orders) GetByOrderNo(ctx context.Context, orderNo string) (*Orders, error) {
tbl := table.Orders
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.OrderNo.EQ(String(orderNo)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var order Orders
err := stmt.QueryContext(ctx, db, &order)
if err != nil {
m.log().Errorf("error querying order by orderNo: %v", err)
return nil, err
}
return &order, nil
}
// SetTranscationID
func (m *Orders) SetTranscationID(ctx context.Context, id int64, transactionID string) error {
tbl := table.Orders
stmt := tbl.
UPDATE(tbl.TransactionID).
SET(String(transactionID)).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error set order transaction ID: %v", err)
return err
}
return nil
}
// Update
func (m *Orders) Update(ctx context.Context, order *Orders) error {
tbl := table.Orders
stmt := tbl.
UPDATE(
tbl.MutableColumns.Except(
tbl.OrderNo,
tbl.Price,
tbl.Discount,
tbl.SubOrderNo,
tbl.PostID,
tbl.UserID,
),
).
MODEL(order).
WHERE(
tbl.ID.EQ(Int64(order.ID)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating order: %v", err)
return err
}
return nil
}

View File

@@ -0,0 +1,43 @@
package model
import (
"context"
"testing"
"quyun/app/service/testx"
"quyun/database"
"quyun/database/table"
. "github.com/smartystreets/goconvey/convey"
"go.ipao.vip/atom/contracts"
// . "github.com/go-jet/jet/v2/postgres"
"github.com/stretchr/testify/suite"
"go.uber.org/dig"
)
type OrdersInjectParams struct {
dig.In
Initials []contracts.Initial `group:"initials"`
}
type OrdersTestSuite struct {
suite.Suite
OrdersInjectParams
}
func Test_Orders(t *testing.T) {
providers := testx.Default().With(Provide)
testx.Serve(providers, t, func(params OrdersInjectParams) {
suite.Run(t, &OrdersTestSuite{
OrdersInjectParams: params,
})
})
}
func (s *OrdersTestSuite) Test_Demo() {
Convey("Test_Demo", s.T(), func() {
database.Truncate(context.Background(), db, table.Orders.TableName())
})
}

View File

@@ -0,0 +1,31 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"quyun/database/fields"
"time"
)
type Posts struct {
ID int64 `sql:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
Status fields.PostStatus `json:"status"`
Title string `json:"title"`
HeadImages fields.Json[[]int64] `json:"head_images"`
Description string `json:"description"`
Content string `json:"content"`
Price int64 `json:"price"`
Discount int16 `json:"discount"`
Views int64 `json:"views"`
Likes int64 `json:"likes"`
Tags fields.Json[[]string] `json:"tags"`
Assets fields.Json[[]fields.MediaAsset] `json:"assets"`
}

400
backend/app/model/posts.go Normal file
View File

@@ -0,0 +1,400 @@
package model
import (
"context"
"errors"
"time"
"quyun/app/requests"
"quyun/database/conds"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/qrm"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Posts) log() *log.Entry {
return log.WithField("model", "PostsModel")
}
func (m *Posts) IncrViewCount(ctx context.Context, id int64) error {
tbl := table.Posts
stmt := tbl.UPDATE(tbl.Views).SET(tbl.Views.ADD(Int64(1))).WHERE(tbl.ID.EQ(Int64(id)))
m.log().Infof("sql: %s", stmt.DebugSql())
var post Posts
err := stmt.QueryContext(ctx, db, &post)
if err != nil {
m.log().Errorf("error updating post view count: %v", err)
return err
}
return nil
}
// GetByID
func (m *Posts) GetByID(ctx context.Context, id int64, cond ...conds.Cond) (*Posts, error) {
tbl := table.Posts
var combinedCond BoolExpression = tbl.ID.EQ(Int64(id))
for _, c := range cond {
combinedCond = c(combinedCond)
}
stmt := tbl.SELECT(tbl.AllColumns).WHERE(combinedCond)
m.log().Infof("sql: %s", stmt.DebugSql())
var post Posts
err := stmt.QueryContext(ctx, db, &post)
if err != nil {
m.log().Errorf("error getting post: %v", err)
return nil, err
}
return &post, nil
}
// Create
func (m *Posts) Create(ctx context.Context, post *Posts) error {
post.CreatedAt = time.Now()
post.UpdatedAt = time.Now()
tbl := table.Posts
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(post)
m.log().Infof("sql: %s", stmt.DebugSql())
_, err := stmt.ExecContext(ctx, db)
if err != nil {
m.log().Errorf("error creating post: %v", err)
return err
}
return nil
}
// Update
func (m *Posts) Update(ctx context.Context, id int64, posts *Posts) error {
posts.UpdatedAt = time.Now()
tbl := table.Posts
stmt := tbl.UPDATE(tbl.MutableColumns.Except(tbl.CreatedAt, tbl.DeletedAt)).MODEL(posts).WHERE(tbl.ID.EQ(Int64(id)))
m.log().Infof("sql: %s", stmt.DebugSql())
_, err := stmt.ExecContext(ctx, db)
if err != nil {
m.log().Errorf("error updating post: %v", err)
return err
}
return nil
}
// countByCond
func (m *Posts) countByCondition(ctx context.Context, expr BoolExpression) (int64, error) {
var cnt struct {
Cnt int64
}
tbl := table.Posts
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting post items: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
func (m *Posts) List(ctx context.Context, pagination *requests.Pagination, cond ...conds.Cond) (*requests.Pager, error) {
pagination.Format()
combinedCond := table.Posts.DeletedAt.IS_NULL()
for _, c := range cond {
combinedCond = c(combinedCond)
}
tbl := table.Posts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(combinedCond).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log().Infof("sql: %s", stmt.DebugSql())
var posts []Posts = make([]Posts, 0)
err := stmt.QueryContext(ctx, db, &posts)
if err != nil {
m.log().Errorf("error querying post items: %v", err)
return nil, err
}
count, err := m.countByCondition(ctx, combinedCond)
if err != nil {
m.log().Errorf("error getting post count: %v", err)
return nil, err
}
return &requests.Pager{
Items: posts,
Total: count,
Pagination: *pagination,
}, nil
}
func (m *Posts) IsUserBought(ctx context.Context, userId, postId int64) (bool, error) {
tbl := table.UserPosts
stmt := tbl.
SELECT(tbl.ID).
WHERE(
tbl.UserID.EQ(Int64(userId)).AND(
tbl.PostID.EQ(Int64(postId)),
),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var userPost UserPosts
err := stmt.QueryContext(ctx, db, &userPost)
if err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return false, nil
}
m.log().Errorf("error querying user post item: %v", err)
return false, err
}
return userPost.ID > 0, nil
}
func (m *Posts) Buy(ctx context.Context, userId, postId int64) error {
tbl := table.UserPosts
post, err := m.GetByID(ctx, postId)
if err != nil {
m.log().Errorf("error getting post by ID: %v", err)
return err
}
user, err := UsersModel.GetByID(ctx, userId)
if err != nil {
m.log().Errorf("error getting user by ID: %v", err)
return err
}
record := UserPosts{
UserID: user.ID,
PostID: post.ID,
Price: post.Price * int64(post.Discount) / 100,
}
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(record)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error buying post: %v", err)
return err
}
return nil
}
// DeleteByID soft delete item
func (m *Posts) DeleteByID(ctx context.Context, id int64) error {
tbl := table.Posts
stmt := tbl.
UPDATE(tbl.DeletedAt).
SET(TimestampT(time.Now())).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error deleting post: %v", err)
return err
}
return nil
}
// SendTo
func (m *Posts) SendTo(ctx context.Context, postId, userId int64) error {
// add record to user_posts
tbl := table.UserPosts
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(UserPosts{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
UserID: userId,
PostID: postId,
Price: -1,
})
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error sending post to user: %v", err)
return err
}
return nil
}
// PostBoughtStatistics 获取指定文件 ID 的购买次数
func (m *Posts) BoughtStatistics(ctx context.Context, postIds []int64) (map[int64]int64, error) {
tbl := table.UserPosts
// select count(user_id), post_id from user_posts up where post_id in (1, 2,3,4,5,6,7,8,9,10) group by post_id
stmt := tbl.
SELECT(
COUNT(tbl.UserID).AS("cnt"),
tbl.PostID.AS("post_id"),
).
WHERE(
tbl.PostID.IN(lo.Map(postIds, func(id int64, _ int) Expression { return Int64(id) })...),
).
GROUP_BY(
tbl.PostID,
)
m.log().Infof("sql: %s", stmt.DebugSql())
var result []struct {
Cnt int64
PostId int64
}
if err := stmt.QueryContext(ctx, db, &result); err != nil {
m.log().Errorf("error getting post bought statistics: %v", err)
return nil, err
}
// convert to map
resultMap := make(map[int64]int64)
for _, item := range result {
resultMap[item.PostId] = item.Cnt
}
return resultMap, nil
}
// Bought
func (m *Posts) Bought(ctx context.Context, userId int64, pagination *requests.Pagination) (*requests.Pager, error) {
pagination.Format()
// select up.price,up.created_at,p.* from user_posts up left join posts p on up.post_id = p.id where up.user_id =1
tbl := table.UserPosts
stmt := tbl.
SELECT(
tbl.Price.AS("price"),
tbl.CreatedAt.AS("bought_at"),
table.Posts.Title.AS("title"),
).
FROM(
tbl.INNER_JOIN(table.Posts, table.Posts.ID.EQ(tbl.PostID)),
).
WHERE(
tbl.UserID.EQ(Int64(userId)),
).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log().Infof("sql: %s", stmt.DebugSql())
var items []struct {
Title string `json:"title"`
Price int64 `json:"price"`
BoughtAt time.Time `json:"bought_at"`
}
if err := stmt.QueryContext(ctx, db, &items); err != nil {
m.log().Errorf("error getting bought posts: %v", err)
return nil, err
}
// convert to Posts
var cnt struct {
Cnt int64
}
stmtCnt := tbl.
SELECT(COUNT(tbl.ID).AS("cnt")).
WHERE(
tbl.UserID.EQ(Int64(userId)),
)
if err := stmtCnt.QueryContext(ctx, db, &cnt); err != nil {
m.log().Errorf("error getting bought posts count: %v", err)
return nil, err
}
return &requests.Pager{
Items: items,
Total: cnt.Cnt,
Pagination: *pagination,
}, nil
}
// GetPostsMapByIDs
func (m *Posts) GetPostsMapByIDs(ctx context.Context, ids []int64) (map[int64]Posts, error) {
if len(ids) == 0 {
return nil, nil
}
tbl := table.Posts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.IN(lo.Map(ids, func(id int64, _ int) Expression { return Int64(id) })...),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var posts []Posts = make([]Posts, 0)
err := stmt.QueryContext(ctx, db, &posts)
if err != nil {
m.log().Errorf("error querying posts: %v", err)
return nil, err
}
return lo.SliceToMap(posts, func(item Posts) (int64, Posts) {
return item.ID, item
}), nil
}
// GetMediaByIds
func (m *Posts) GetMediaByIds(ctx context.Context, ids []int64) ([]Medias, error) {
if len(ids) == 0 {
return nil, nil
}
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.IN(lo.Map(ids, func(id int64, _ int) Expression { return Int64(id) })...),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var medias []Medias
if err := stmt.QueryContext(ctx, db, &medias); err != nil {
m.log().Errorf("error querying media: %v", err)
return nil, err
}
return medias, nil
}
// Count
func (m *Posts) Count(ctx context.Context, cond BoolExpression) (int64, error) {
tbl := table.Posts
stmt := tbl.
SELECT(COUNT(tbl.ID).AS("count")).
WHERE(cond)
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting posts: %v", err)
return 0, err
}
return count.Count, nil
}

View File

@@ -0,0 +1,43 @@
package model
import (
"context"
"testing"
"quyun/app/service/testx"
"quyun/database"
"quyun/database/table"
. "github.com/smartystreets/goconvey/convey"
"go.ipao.vip/atom/contracts"
// . "github.com/go-jet/jet/v2/postgres"
"github.com/stretchr/testify/suite"
"go.uber.org/dig"
)
type PostsInjectParams struct {
dig.In
Initials []contracts.Initial `group:"initials"`
}
type PostsTestSuite struct {
suite.Suite
PostsInjectParams
}
func Test_Posts(t *testing.T) {
providers := testx.Default().With(Provide)
testx.Serve(providers, t, func(params PostsInjectParams) {
suite.Run(t, &PostsTestSuite{
PostsInjectParams: params,
})
})
}
func (s *PostsTestSuite) Test_Demo() {
Convey("Test_Demo", s.T(), func() {
database.Truncate(context.Background(), db, table.Posts.TableName())
})
}

View File

@@ -0,0 +1,76 @@
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
// Code generated by the atomctl ; DO NOT EDIT.
package model
import (
"context"
"database/sql"
"go.ipao.vip/atom"
"go.ipao.vip/atom/container"
"go.ipao.vip/atom/contracts"
"go.ipao.vip/atom/opt"
)
var db *sql.DB
var MediasModel *Medias
var OrdersModel *Orders
var PostsModel *Posts
var UsersModel *Users
func Transaction(ctx context.Context) (*sql.Tx, error) {
return db.Begin()
}
func DB() *sql.DB {
return db
}
func Provide(opts ...opt.Option) error {
if err := container.Container.Provide(func() (*Medias, error) {
obj := &Medias{}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func() (*Orders, error) {
obj := &Orders{}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func() (*Posts, error) {
obj := &Posts{}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func() (*Users, error) {
obj := &Users{}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func(
_db *sql.DB,
medias *Medias,
orders *Orders,
posts *Posts,
users *Users,
) (contracts.Initial, error) {
db = _db
MediasModel = medias
OrdersModel = orders
PostsModel = posts
UsersModel = users
return nil, nil
}, atom.GroupInitial); err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,21 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"time"
)
type UserPosts struct {
ID int64 `sql:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
UserID int64 `json:"user_id"`
PostID int64 `json:"post_id"`
Price int64 `json:"price"`
}

View File

@@ -0,0 +1,27 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"quyun/database/fields"
"time"
)
type Users struct {
ID int64 `sql:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
Status fields.UserStatus `json:"status"`
OpenID string `json:"open_id"`
Username string `json:"username"`
Avatar *string `json:"avatar"`
Metas fields.Json[fields.UserMetas] `json:"metas"`
AuthToken fields.Json[fields.UserAuthToken] `json:"auth_token"`
Balance int64 `json:"balance"`
}

505
backend/app/model/users.go Normal file
View File

@@ -0,0 +1,505 @@
package model
import (
"context"
"time"
"quyun/app/requests"
"quyun/database/conds"
"quyun/database/fields"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/qrm"
"github.com/pkg/errors"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Users) log() *log.Entry {
return log.WithField("model", "UsersModel")
}
// GetByID
func (m *Users) GetByID(ctx context.Context, id int64) (*Users, error) {
tbl := table.Users
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var user Users
err := stmt.QueryContext(ctx, db, &user)
if err != nil {
m.log().Errorf("error querying user by ID: %v", err)
return nil, err
}
return &user, nil
}
func (m *Users) Own(ctx context.Context, userID, postID int64) error {
tbl := table.UserPosts
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(&UserPosts{
UserID: userID,
PostID: postID,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error inserting user post: %v", err)
return err
}
m.log().Infof("user post inserted successfully: userID=%d, postID=%d", userID, postID)
return nil
}
// BuildConditionWithKey builds the WHERE clause for user queries
func (m *Users) BuildConditionWithKey(key *string) BoolExpression {
tbl := table.Users
cond := tbl.DeletedAt.IS_NULL()
if key == nil || *key == "" {
return cond
}
cond = cond.AND(
tbl.Username.LIKE(String("%" + *key + "%")),
)
return cond
}
// countByCondition counts users matching the given condition
func (m *Users) countByCondition(ctx context.Context, expr BoolExpression) (int64, error) {
var cnt struct {
Cnt int64
}
tbl := table.Users
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting users: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
// List returns a paginated list of users
func (m *Users) List(ctx context.Context, pagination *requests.Pagination, cond BoolExpression) (*requests.Pager, error) {
pagination.Format()
tbl := table.Users
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(cond).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log().Infof("sql: %s", stmt.DebugSql())
var users []Users = make([]Users, 0)
err := stmt.QueryContext(ctx, db, &users)
if err != nil {
m.log().Errorf("error querying users: %v", err)
return nil, err
}
count, err := m.countByCondition(ctx, cond)
if err != nil {
m.log().Errorf("error getting user count: %v", err)
return nil, err
}
return &requests.Pager{
Items: users,
Total: count,
Pagination: *pagination,
}, nil
}
// Create creates a new user
func (m *Users) Create(ctx context.Context, userModel *Users) (*Users, error) {
userModel.CreatedAt = time.Now()
userModel.UpdatedAt = time.Now()
tbl := table.Users
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(userModel).RETURNING(tbl.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
var createdUser Users
err := stmt.QueryContext(ctx, db, &createdUser)
if err != nil {
m.log().Errorf("error creating user: %v", err)
return nil, err
}
return &createdUser, nil
}
// Update updates an existing user
func (m *Users) Update(ctx context.Context, id int64, userModel *Users) (*Users, error) {
userModel.UpdatedAt = time.Now()
tbl := table.Users
stmt := tbl.
UPDATE(
tbl.MutableColumns.Except(
tbl.Balance,
tbl.CreatedAt,
tbl.DeletedAt,
),
).
MODEL(userModel).
WHERE(tbl.ID.EQ(Int64(id))).
RETURNING(tbl.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
var updatedUser Users
if err := stmt.QueryContext(ctx, db, &updatedUser); err != nil {
m.log().Errorf("error updating user: %v", err)
return nil, err
}
return &updatedUser, nil
}
// DeleteByID soft deletes a user by ID
func (m *Users) DeleteByID(ctx context.Context, id int64) error {
tbl := table.Users
stmt := tbl.
UPDATE(tbl.DeletedAt).
SET(TimestampT(time.Now())).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error deleting user: %v", err)
return err
}
return nil
}
// PostList returns a paginated list of posts for a user
func (m *Users) PostList(ctx context.Context, userId int64, pagination *requests.Pagination, conds ...conds.Cond) (*requests.Pager, error) {
pagination.Format()
tblUserPosts := table.UserPosts
combineConds := tblUserPosts.UserID.EQ(Int64(userId))
for _, c := range conds {
combineConds = c(combineConds)
}
tbl := table.Posts
stmt := SELECT(tbl.AllColumns).
FROM(tbl.
RIGHT_JOIN(
tblUserPosts,
tblUserPosts.PostID.EQ(tbl.ID),
),
).
WHERE(combineConds).
ORDER_BY(tblUserPosts.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log().Infof("sql: %s", stmt.DebugSql())
var posts []Posts
err := stmt.QueryContext(ctx, db, &posts)
if err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return &requests.Pager{
Items: nil,
Total: 0,
Pagination: *pagination,
}, nil
}
m.log().Errorf("error querying posts: %v", err)
return nil, err
}
// total count
var cnt struct {
Cnt int64
}
stmtCnt := tblUserPosts.SELECT(COUNT(tblUserPosts.ID).AS("cnt")).WHERE(tblUserPosts.UserID.EQ(Int64(userId)))
m.log().Infof("sql: %s", stmtCnt.DebugSql())
if err := stmtCnt.QueryContext(ctx, db, &cnt); err != nil {
m.log().Errorf("error counting users: %v", err)
return nil, err
}
return &requests.Pager{
Items: posts,
Total: cnt.Cnt,
Pagination: *pagination,
}, nil
}
// GetUserIDByOpenID
func (m *Users) GetUserByOpenID(ctx context.Context, openID string) (*Users, error) {
tbl := table.Users
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.OpenID.EQ(String(openID)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var user Users
if err := stmt.QueryContext(ctx, db, &user); err != nil {
m.log().Errorf("error querying user by OpenID: %v", err)
return nil, err
}
return &user, nil
}
// GetUserByOpenIDOrCreate
func (m *Users) GetUserByOpenIDOrCreate(ctx context.Context, openID string, userModel *Users) (*Users, error) {
user, err := m.GetUserByOpenID(ctx, openID)
if err != nil {
if errors.Is(err, qrm.ErrNoRows) {
user, err = m.Create(ctx, userModel)
if err != nil {
return nil, errors.Wrap(err, "failed to create user")
}
} else {
return nil, errors.Wrap(err, "failed to get user")
}
} else {
userModel.OpenID = user.OpenID
if !(user.Username == "" || user.Username == "-" || user.Username == "暂未设置昵称") {
userModel.Username = user.Username
userModel.Avatar = user.Avatar
}
user, err = m.Update(ctx, user.ID, userModel)
if err != nil {
return nil, errors.Wrap(err, "failed to update user")
}
}
return user, nil
}
// GetUsersMapByIDs
func (m *Users) GetUsersMapByIDs(ctx context.Context, ids []int64) (map[int64]Users, error) {
if len(ids) == 0 {
return nil, nil
}
tbl := table.Users
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.IN(lo.Map(ids, func(id int64, _ int) Expression { return Int64(id) })...),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var users []Users = make([]Users, 0)
err := stmt.QueryContext(ctx, db, &users)
if err != nil {
m.log().Errorf("error querying users: %v", err)
return nil, err
}
return lo.SliceToMap(users, func(item Users) (int64, Users) {
return item.ID, item
}), nil
}
func (m *Users) BatchCheckHasBought(ctx context.Context, userID int64, postIDs []int64) (map[int64]bool, error) {
tbl := table.UserPosts
stmt := tbl.SELECT(tbl.PostID.AS("post_id")).WHERE(
tbl.UserID.EQ(Int64(userID)).AND(
tbl.PostID.IN(lo.Map(postIDs, func(id int64, _ int) Expression { return Int64(id) })...),
),
)
var userPosts []struct {
PostID int64
}
if err := stmt.QueryContext(ctx, db, &userPosts); err != nil {
m.log().Errorf("error querying user posts: %v", err)
return nil, err
}
result := make(map[int64]bool)
for _, post := range userPosts {
result[post.PostID] = true
}
return result, nil
}
// HasBought
func (m *Users) HasBought(ctx context.Context, userID, postID int64) (bool, error) {
tbl := table.UserPosts
stmt := tbl.
SELECT(tbl.ID).
WHERE(
tbl.UserID.EQ(Int64(userID)).AND(
tbl.PostID.EQ(Int64(postID)),
),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var userPost UserPosts
if err := stmt.QueryContext(ctx, db, &userPost); err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return false, nil
}
m.log().Errorf("error querying user post: %v", err)
return false, err
}
return userPost.ID > 0, nil
}
// Count
func (m *Users) Count(ctx context.Context, cond BoolExpression) (int64, error) {
tbl := table.Users
stmt := tbl.
SELECT(COUNT(tbl.ID).AS("cnt")).
WHERE(cond)
m.log().Infof("sql: %s", stmt.DebugSql())
var cnt struct {
Cnt int64
}
if err := stmt.QueryContext(ctx, db, &cnt); err != nil {
m.log().Errorf("error counting users: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
// UpdateUsername
func (m *Users) UpdateUsername(ctx context.Context, id int64, username string) error {
tbl := table.Users
stmt := tbl.
UPDATE(tbl.Username).
SET(String(username)).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating username: %v", err)
return err
}
return nil
}
// UpdateUserToken
func (m *Users) UpdateUserToken(ctx context.Context, id int64, token fields.UserAuthToken) error {
tbl := table.Users
stmt := tbl.
UPDATE(tbl.AuthToken).
SET(fields.ToJson(token)).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating user token: %v", err)
return err
}
return nil
}
// BuyPosts
func (m *Users) BuyPosts(ctx context.Context, userID, postID, price int64) error {
tbl := table.UserPosts
stmt := tbl.
INSERT(tbl.MutableColumns).
MODEL(&UserPosts{
UserID: userID,
PostID: postID,
Price: price,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error inserting user post: %v", err)
return err
}
return nil
}
func (m *Users) RevokePosts(ctx context.Context, userID, postID int64) error {
tbl := table.UserPosts
stmt := tbl.
DELETE().
WHERE(
tbl.UserID.EQ(Int64(userID)).AND(
tbl.PostID.EQ(Int64(postID)),
),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error revoking user post: %v", err)
return err
}
return nil
}
// SetBalance
func (m *Users) SetBalance(ctx context.Context, id, balance int64) error {
tbl := table.Users
stmt := tbl.
UPDATE(tbl.Balance).
SET(Int64(balance)).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating user balance: %v", err)
return err
}
return nil
}
// AddBalance adds the given amount to the user's balance
func (m *Users) AddBalance(ctx context.Context, id, amount int64) error {
tbl := table.Users
stmt := tbl.
UPDATE(tbl.Balance).
SET(tbl.Balance.ADD(Int64(amount))).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating user balance: %v", err)
return err
}
return nil
}

View File

@@ -0,0 +1,43 @@
package model
import (
"context"
"testing"
"quyun/app/service/testx"
"quyun/database"
"quyun/database/table"
. "github.com/smartystreets/goconvey/convey"
"go.ipao.vip/atom/contracts"
// . "github.com/go-jet/jet/v2/postgres"
"github.com/stretchr/testify/suite"
"go.uber.org/dig"
)
type UsersInjectParams struct {
dig.In
Initials []contracts.Initial `group:"initials"`
}
type UsersTestSuite struct {
suite.Suite
UsersInjectParams
}
func Test_Users(t *testing.T) {
providers := testx.Default().With(Provide)
testx.Serve(providers, t, func(params UsersInjectParams) {
suite.Run(t, &UsersTestSuite{
UsersInjectParams: params,
})
})
}
func (s *UsersTestSuite) Test_Demo() {
Convey("Test_Demo", s.T(), func() {
database.Truncate(context.Background(), db, table.Users.TableName())
})
}