Merge branch 'develop' of https://gitee.com/fusenpack/fusenapi into feature/auth

This commit is contained in:
eson 2023-08-14 14:12:33 +08:00
commit 187cb48a41
39 changed files with 581 additions and 287 deletions

View File

@ -8,6 +8,12 @@ const (
WEBSOCKET_UNAUTH = "WEBSOCKET_UNAUTH"
//ws连接成功
WEBSOCKET_CONNECT_SUCCESS = "WEBSOCKET_CONNECT_SUCCESS"
//请求恢复为上次连接的标识
WEBSOCKET_REQUEST_RESUME_LAST_CONNECT = "WEBSOCKET_REQUEST_RESUME_LAST_CONNECT"
//请求恢复为上次连接的标识错误
WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR = "WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR"
//请求恢复为上次连接的标识成功
WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_SUCCESS = "WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_SUCCESS"
//渲染前数据组装
WEBSOCKET_RENDER_IMAGE_ASSEMBLE = "WEBSOCKET_RENDER_IMAGE_ASSEMBLE"
//图片渲染

View File

@ -4,6 +4,7 @@ package gmodel
import (
"context"
"gorm.io/gorm"
)
type FindOneCartByParamsReq struct {
@ -94,3 +95,22 @@ func (c *FsCartModel) DeleteCartsByIds(ctx context.Context, ids []int64) ( err e
}
return c.db.Table(c.name).WithContext(ctx).Model(&FsCart{}).Where("`id` in (?)", ids).Update("status", 0).Error
}
func (c *FsCartModel) RBDeleteCartsByIds(rowBuilder *gorm.DB,ids []int64) ( err error) {
if len(ids) == 0 {
return
}
return rowBuilder.Where("`id` in (?)", ids).Update("status", 0).Error
}
func (c *FsCartModel) BuilderTrans(ctx context.Context,selectData []string) *gorm.DB {
var rowBuilder = c.db.WithContext(ctx)
if selectData != nil {
rowBuilder = rowBuilder.Select(selectData)
} else {
rowBuilder = rowBuilder.Select("*")
}
return rowBuilder
}

View File

@ -0,0 +1,25 @@
package gmodel
import (
"gorm.io/gorm"
)
// fs_merchant_category 商户类型表
type FsMerchantCategory struct {
Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // Id
ZnName *string `gorm:"default:'';" json:"zn_name"` // 中文名
EnName *string `gorm:"default:'';" json:"en_name"` // 英文名
Icon *string `gorm:"default:'';" json:"icon"` // 图标
RecommendProduct *string `gorm:"default:'';" json:"recommend_product"` // 推荐商品
Sort *int64 `gorm:"default:128;" json:"sort"` // 排序
Status *int64 `gorm:"default:0;" json:"status"` // 状态
Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间
}
type FsMerchantCategoryModel struct {
db *gorm.DB
name string
}
func NewFsMerchantCategoryModel(db *gorm.DB) *FsMerchantCategoryModel {
return &FsMerchantCategoryModel{db: db, name: "fs_merchant_category"}
}

View File

@ -0,0 +1,13 @@
package gmodel
import "context"
// TODO: 使用model的属性做你想做的
func (m *FsMerchantCategoryModel) FindOne(ctx context.Context, id int64) (resp *FsMerchantCategory, err error) {
err = m.db.WithContext(ctx).Model(&FsMerchantCategory{}).Where("id = ? and status = ?", id, 1).Take(&resp).Error
return resp, err
}
func (m *FsMerchantCategoryModel) FindRandOne(ctx context.Context) (resp *FsMerchantCategory, err error) {
err = m.db.WithContext(ctx).Model(&FsMerchantCategory{}).Where("status = ?", 1).Order("RAND()").Take(&resp).Error
return resp, err
}

View File

@ -26,6 +26,10 @@ func (dt *FsOrderDetailTemplateModel) FindOne(ctx context.Context, id int64) (re
return resp, err
}
func (dt *FsOrderDetailTemplateModel) RBCreate(ctx context.Context, data *FsOrderDetailTemplate) error {
return dt.db.WithContext(ctx).Create(&data).Error
}
func (m *FsOrderDetailTemplateModel) TableName() string {
return m.name
}

View File

@ -28,6 +28,10 @@ func (o *FsOrderModel) Update(ctx context.Context, data *FsOrder) error {
return o.db.WithContext(ctx).Model(&FsOrder{}).Where("`id` = ?", data.Id).Updates(&data).Error
}
func (o *FsOrderModel) RBUpdate(ctx context.Context, data *FsOrder) error {
return o.db.WithContext(ctx).Where("`id` = ?", data.Id).Updates(&data).Error
}
func (o *FsOrderModel) Create(ctx context.Context, data *FsOrder) error {
return o.db.WithContext(ctx).Model(&FsOrder{}).Create(&data).Error
}
@ -120,6 +124,17 @@ func (m *FsOrderModel) RowSelectBuilder(selectData []string) *gorm.DB {
return rowBuilder
}
func (m *FsOrderModel) BuilderTrans(selectData []string) *gorm.DB {
var rowBuilder = m.db
if selectData != nil {
rowBuilder = rowBuilder.Select(selectData)
} else {
rowBuilder = rowBuilder.Select("*")
}
return rowBuilder
}
func (m *FsOrderModel) FindCount(ctx context.Context, countBuilder *gorm.DB, filterMap map[string]string) (int64, error) {
var count int64

View File

@ -29,6 +29,14 @@ func (p *FsPayModel) GetListByOrderNumberStage(ctx context.Context, sn string, s
return resp, nil
}
func (p *FsPayModel) RBGetListByOrderNumberStage(ctx context.Context, sn string, stage int64) (resp *FsPay, err error) {
err = p.db.WithContext(ctx).Where("`order_number` = ? ", sn).Where("`pay_stage` = ? ", stage).Take(&resp).Error
if err != nil {
return nil, err
}
return resp, nil
}
func (p *FsPayModel) CreateOrUpdate(ctx context.Context, req *FsPay) (resp *FsPay, err error) {
rowBuilder := p.db.Table(p.name).WithContext(ctx)
if req.Id > 0 {
@ -39,6 +47,16 @@ func (p *FsPayModel) CreateOrUpdate(ctx context.Context, req *FsPay) (resp *FsPa
return req, err
}
func (p *FsPayModel) RBCreateOrUpdate(ctx context.Context, req *FsPay) (resp *FsPay, err error) {
rowBuilder := p.db.WithContext(ctx)
if req.Id > 0 {
err = rowBuilder.Save(req).Error
} else {
err = rowBuilder.Create(req).Error
}
return req, err
}
func (m *FsPayModel) RowSelectBuilder(selectData []string) *gorm.DB {
var rowBuilder = m.db.Table(m.name)
@ -50,6 +68,17 @@ func (m *FsPayModel) RowSelectBuilder(selectData []string) *gorm.DB {
return rowBuilder
}
func (m *FsPayModel) BuilderTrans(selectData []string) *gorm.DB {
var rowBuilder = m.db
if selectData != nil {
rowBuilder = rowBuilder.Select(selectData)
} else {
rowBuilder = rowBuilder.Select("*")
}
return rowBuilder
}
func (m *FsPayModel) FindCount(ctx context.Context, countBuilder *gorm.DB, filterMap map[string]string) (int64, error) {
var count int64

View File

@ -2,6 +2,8 @@ package gmodel
import (
"context"
"gorm.io/gorm"
)
func (d *FsProductDesignModel) FindOneBySn(ctx context.Context, sn string, userId int64) (resp *FsProductDesign, err error) {
@ -39,6 +41,21 @@ func (d *FsProductDesignModel) UpdateByIds(ctx context.Context, ids []int64, dat
return d.db.Table(d.name).WithContext(ctx).Model(&FsProductDesign{}).Where("`id` in ?", ids).Updates(&data).Error
}
func (d *FsProductDesignModel) RBUpdateByIds(rowBuilder *gorm.DB, ids []int64, data *FsProductDesign) error {
return rowBuilder.Where("`id` in ?", ids).Updates(&data).Error
}
func (m *FsProductDesignModel) BuilderTrans(ctx context.Context, selectData []string) *gorm.DB {
var rowBuilder = m.db.WithContext(ctx)
if selectData != nil {
rowBuilder = rowBuilder.Select(selectData)
} else {
rowBuilder = rowBuilder.Select("*")
}
return rowBuilder
}
func (m *FsProductDesignModel) TableName() string {
return m.name
}

View File

@ -101,3 +101,14 @@ func (d *FsProductModel3dModel) FindOneJoinSize(ctx context.Context, productId i
Order("s.sort ASC").Take(&resp).Error
return resp, err
}
func (d *FsProductModel3dModel) GetOneBySizeIdTag(ctx context.Context, sizeId int64, tag int64, fields ...string) (resp *FsProductModel3d, err error) {
db := d.db.WithContext(ctx).Model(&FsProductModel3d{}).
Where("`size_id` = ? and `tag` = ? and `status` = ?", sizeId, tag, 1).
Order("sort DESC")
if len(fields) != 0 {
db = db.Select(fields[0])
}
err = db.Take(&resp).Error
return resp, err
}

View File

@ -1,21 +0,0 @@
package gmodel
import (
"gorm.io/gorm"
)
// fs_product_recommend 推荐商品表
type FsProductRecommend struct {
Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` //
ProductId *int64 `gorm:"default:0;" json:"product_id"` // 产品ID
Status *int64 `gorm:"default:1;" json:"status"` // 状态 1正常 0不正常
Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间
}
type FsProductRecommendModel struct {
db *gorm.DB
name string
}
func NewFsProductRecommendModel(db *gorm.DB) *FsProductRecommendModel {
return &FsProductRecommendModel{db: db, name: "fs_product_recommend"}
}

View File

@ -1,39 +0,0 @@
package gmodel
import (
"context"
"errors"
"gorm.io/gorm"
)
type GetRecommendProductListReq struct {
Ctx context.Context
Page int
Limit int
}
func (r *FsProductRecommendModel) GetRecommendProductList(req GetRecommendProductListReq) (resp []FsProduct, total int64, err error) {
db := r.db.WithContext(req.Ctx).
Table("fs_product_recommend as r").
Joins("inner join fs_product as p on r.product_id = p.id").
Where("r.status = ? ", 1).
Where("p.is_shelf = ? and p.is_del = ? and p.status = ?", 1, 0, 1)
if err = db.Limit(1).Count(&total).Error; err != nil {
return nil, 0, err
}
db = db.Select("p.*")
offset := (req.Page - 1) * req.Limit
err = db.Offset(offset).Limit(req.Limit).Find(&resp).Error
return resp, total, err
}
func (r *FsProductRecommendModel) CreateOrUpdate(ctx context.Context, productId int64, data *FsProductRecommend) error {
var info FsProductRecommend
err := r.db.WithContext(ctx).Model(&FsProductRecommend{}).Where("`product_id` = ?", productId).Take(&info).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
if info.Id == 0 {
return r.db.WithContext(ctx).Model(&FsProductRecommend{}).Create(data).Error
}
return r.db.WithContext(ctx).Model(&FsProductRecommend{}).Where("`product_id` = ?", productId).Updates(data).Error
}

View File

@ -9,20 +9,21 @@ type FsProductTemplateV2 struct {
Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` //
ProductId *int64 `gorm:"index;default:0;" json:"product_id"` // 产品ID
ModelId *int64 `gorm:"default:0;" json:"model_id"` // 模型ID
Title *string `gorm:"default:'';" json:"title"` // 模板sku,预留字段
Name *string `gorm:"default:'';" json:"name"` // 名称
CoverImg *string `gorm:"default:'';" json:"cover_img"` // 模板背景图
TemplateInfo *string `gorm:"default:'';" json:"template_info"` // 模板详情
MaterialImg *string `gorm:"default:'';" json:"material_img"` // 合成好的贴图
Title *string `gorm:"default:'';" json:"title"` //
Name *string `gorm:"default:'';" json:"name"` //
CoverImg *string `gorm:"default:'';" json:"cover_img"` //
TemplateInfo *string `gorm:"default:'';" json:"template_info"` //
MaterialImg *string `gorm:"default:'';" json:"material_img"` //
Sort *int64 `gorm:"default:0;" json:"sort"` // 排序
LogoWidth *int64 `gorm:"default:0;" json:"logo_width"` // logo图最大宽度
LogoHeight *int64 `gorm:"default:0;" json:"logo_height"` // logo图最大高度
IsPublic *int64 `gorm:"default:0;" json:"is_public"` // 是否可公用1:可以0不可以
Status *int64 `gorm:"default:0;" json:"status"` // 状态1正常 2异常
Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间
Tag *string `gorm:"default:'';" json:"tag"` // 标签(用户自填)
Tag *string `gorm:"default:'';" json:"tag"` //
IsDel *int64 `gorm:"default:0;" json:"is_del"` // 是否删除 1删除
GroupOptions *string `gorm:"default:'';" json:"group_options"` // 颜色分组
SwitchInfo *string `gorm:"default:'';" json:"switch_info"` //
GroupOptions *string `gorm:"default:'';" json:"group_options"` //
Version *int64 `gorm:"default:0;" json:"version"` //
}
type FsProductTemplateV2Model struct {

View File

@ -139,3 +139,14 @@ func (t *FsProductTemplateV2Model) FindAllByModelIdsTemplateTag(ctx context.Cont
err = db.Find(&resp).Error
return resp, err
}
// 获取产品在指定模板标签下的所有模板
func (t *FsProductTemplateV2Model) GetListByProductAndTemplateTag(ctx context.Context, templateTagId string, productId int64, fields ...string) (resp []FsProductTemplateV2, err error) {
db := t.db.WithContext(ctx).Model(&FsProductTemplateV2{}).
Where("tag = ? and product_id = ? and status = ? and is_del = ?", templateTagId, productId, 1, 0)
if len(fields) > 0 {
db = db.Select(fields[0])
}
err = db.Find(&resp).Error
return resp, err
}

View File

@ -36,6 +36,16 @@ func (m *FsRefundReasonModel) CreateOrUpdate(ctx context.Context, req *FsRefundR
return req, err
}
func (m *FsRefundReasonModel) RBCreateOrUpdate(ctx context.Context, req *FsRefundReason) (resp *FsRefundReason, err error) {
rowBuilder := m.db.WithContext(ctx)
if req.Id > 0 {
err = rowBuilder.Save(req).Error
} else {
err = rowBuilder.Create(req).Error
}
return req, err
}
func (m *FsRefundReasonModel) FindOneByQuery(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string) (*FsRefundReason, error) {
var resp FsRefundReason
@ -62,6 +72,16 @@ func (m *FsRefundReasonModel) RowSelectBuilder(selectData []string) *gorm.DB {
return rowBuilder
}
func (m *FsRefundReasonModel) BuilderTrans(selectData []string) *gorm.DB {
var rowBuilder = m.db
if selectData != nil {
rowBuilder = rowBuilder.Select(selectData)
} else {
rowBuilder = rowBuilder.Select("*")
}
return rowBuilder
}
func (m *FsRefundReasonModel) TableName() string {
return m.name
}

View File

@ -24,6 +24,16 @@ func (p *FsResourceModel) Update(ctx context.Context, req *FsResource) (resp *Fs
return req, err
}
func (p *FsResourceModel) BuilderCreate(ctx context.Context, rowBuilder *gorm.DB, req *FsResource) (resp *FsResource, err error) {
err = rowBuilder.WithContext(ctx).Create(req).Error
return req, err
}
func (p *FsResourceModel) BuilderUpdate(ctx context.Context, rowBuilder *gorm.DB, req *FsResource) (resp *FsResource, err error) {
err = rowBuilder.WithContext(ctx).Where("resource_id =?", req.ResourceId).Save(req).Error
return req, err
}
func (m *FsResourceModel) FindOneByQuery(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string) (*FsResource, error) {
var resp FsResource
@ -50,6 +60,17 @@ func (m *FsResourceModel) RowSelectBuilder(selectData []string) *gorm.DB {
return rowBuilder
}
func (m *FsResourceModel) BuilderTrans(selectData []string) *gorm.DB {
var rowBuilder = m.db
if selectData != nil {
rowBuilder = rowBuilder.Select(selectData)
} else {
rowBuilder = rowBuilder.Select("*")
}
return rowBuilder
}
// 事务
func (m *FsResourceModel) Trans(ctx context.Context, fn func(ctx context.Context, connGorm *gorm.DB) error) error {

View File

@ -45,6 +45,7 @@ type AllModelsGen struct {
FsLog *FsLogModel // fs_log 日志表
FsMapLibrary *FsMapLibraryModel // fs_map_library 贴图库
FsMenu *FsMenuModel // fs_menu 后台菜单
FsMerchantCategory *FsMerchantCategoryModel // fs_merchant_category 商户类型表
FsMigration *FsMigrationModel // fs_migration 版本库
FsOrder *FsOrderModel // fs_order
FsOrderAffiliate *FsOrderAffiliateModel // fs_order_affiliate 订单附属表-流程控制时间等
@ -61,7 +62,6 @@ type AllModelsGen struct {
FsProductModel3dLight *FsProductModel3dLightModel // fs_product_model3d_light 模型-灯光组表
FsProductOption *FsProductOptionModel // fs_product_option 产品选项表(已废弃)
FsProductPrice *FsProductPriceModel // fs_product_price 阶梯价格表
FsProductRecommend *FsProductRecommendModel // fs_product_recommend 推荐商品表
FsProductRenderDesign *FsProductRenderDesignModel // fs_product_render_design
FsProductScene *FsProductSceneModel // fs_product_scene 产品场景表
FsProductSize *FsProductSizeModel // fs_product_size 产品尺寸表
@ -139,6 +139,7 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen {
FsLog: NewFsLogModel(gdb),
FsMapLibrary: NewFsMapLibraryModel(gdb),
FsMenu: NewFsMenuModel(gdb),
FsMerchantCategory: NewFsMerchantCategoryModel(gdb),
FsMigration: NewFsMigrationModel(gdb),
FsOrder: NewFsOrderModel(gdb),
FsOrderAffiliate: NewFsOrderAffiliateModel(gdb),
@ -155,7 +156,6 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen {
FsProductModel3dLight: NewFsProductModel3dLightModel(gdb),
FsProductOption: NewFsProductOptionModel(gdb),
FsProductPrice: NewFsProductPriceModel(gdb),
FsProductRecommend: NewFsProductRecommendModel(gdb),
FsProductRenderDesign: NewFsProductRenderDesignModel(gdb),
FsProductScene: NewFsProductSceneModel(gdb),
FsProductSize: NewFsProductSizeModel(gdb),

View File

@ -80,14 +80,14 @@ func (l *UserOrderCancelLogic) UserOrderCancel(req *types.UserOrderCancelReq, us
err = l.svcCtx.MysqlConn.Transaction(func(tx *gorm.DB) error {
// 修改订单信息
orderModelTS := gmodel.NewFsOrderModel(tx)
err = orderModelTS.Update(ctx, orderInfo)
err = orderModelTS.RBUpdate(ctx, orderInfo)
if err != nil {
return err
}
// 新增退款记录
var isRefund int64 = 0
refundReasonModelTS := gmodel.NewFsRefundReasonModel(tx)
refundReasonModelTS.CreateOrUpdate(ctx, &gmodel.FsRefundReason{
refundReasonModelTS.RBCreateOrUpdate(ctx, &gmodel.FsRefundReason{
IsRefund: &isRefund,
RefundReasonId: &req.RefundReasonId,
RefundReason: &req.RefundReason,

View File

@ -116,7 +116,7 @@ func (l *OrderPaymentIntentLogic) OrderPaymentIntent(req *types.OrderPaymentInte
var fspay *gmodel.FsPay
newFsPayModel := gmodel.NewFsPayModel(connGorm)
if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) {
fspay, err = newFsPayModel.GetListByOrderNumberStage(ctx, *orderInfo.Sn, 1)
fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 1)
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return err
@ -124,7 +124,7 @@ func (l *OrderPaymentIntentLogic) OrderPaymentIntent(req *types.OrderPaymentInte
}
payStage = 1
} else {
fspay, err = newFsPayModel.GetListByOrderNumberStage(ctx, *orderInfo.Sn, 2)
fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 2)
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return err
@ -146,7 +146,7 @@ func (l *OrderPaymentIntentLogic) OrderPaymentIntent(req *types.OrderPaymentInte
}
// 订单信息--修改
err = gmodel.NewFsOrderModel(connGorm).Update(ctx, orderInfo)
err = gmodel.NewFsOrderModel(connGorm).RBUpdate(ctx, orderInfo)
if err != nil {
return err
}
@ -167,7 +167,7 @@ func (l *OrderPaymentIntentLogic) OrderPaymentIntent(req *types.OrderPaymentInte
fspay.OrderSource = &orderSource
fspay.PayStatus = &payStatus
_, err = newFsPayModel.CreateOrUpdate(ctx, fspay)
_, err = newFsPayModel.RBCreateOrUpdate(ctx, fspay)
if err != nil {
return err
}

View File

@ -157,7 +157,7 @@ func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge)
err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error {
// 查询支付记录
payModelT := gmodel.NewFsPayModel(connGorm)
payModelTRSB := payModelT.RowSelectBuilder(nil)
payModelTRSB := payModelT.BuilderTrans(nil)
payModelTRSB1 := payModelTRSB.Where("trade_no = ?", chargeRefunded.PaymentIntent.ID).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0)
payInfo, err := payModelT.FindOneByQuery(ctx, payModelTRSB1, nil)
if err != nil {
@ -165,7 +165,7 @@ func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge)
}
// 更新支付记录
*payInfo.IsRefund = 1
_, err = payModelT.CreateOrUpdate(ctx, payInfo)
_, err = payModelT.RBCreateOrUpdate(ctx, payInfo)
if err != nil {
return err
}
@ -175,7 +175,7 @@ func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge)
if count == 0 {
// 退款完成更新订单状态
orderModelT := gmodel.NewFsOrderModel(connGorm)
orderModelTRSB := orderModelT.RowSelectBuilder(nil).Where("sn =?", payInfo.OrderNumber)
orderModelTRSB := orderModelT.BuilderTrans(nil).Where("sn =?", payInfo.OrderNumber)
orderInfoRel, err := orderModelT.FindOneByQuery(ctx, orderModelTRSB, nil)
if err != nil {
return err
@ -192,13 +192,14 @@ func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge)
// 记录退款原因
refundReasonModelT := gmodel.NewFsRefundReasonModel(connGorm)
refundReasonModelTRSB := refundReasonModelT.RowSelectBuilder(nil).Where("order_id =?", orderInfoRel.Id)
refundReasonInfo, err := refundReasonModelT.FindOneByQuery(ctx, refundReasonModelTRSB, nil)
refundReasonModelTRSB := refundReasonModelT.BuilderTrans(nil)
refundReasonModelTRSB1 := refundReasonModelTRSB.Where("order_id =?", orderInfoRel.Id)
refundReasonInfo, err := refundReasonModelT.FindOneByQuery(ctx, refundReasonModelTRSB1, nil)
if err != nil {
return err
}
*refundReasonInfo.IsRefund = 1
_, err = refundReasonModelT.CreateOrUpdate(ctx, refundReasonInfo)
_, err = refundReasonModelT.RBCreateOrUpdate(ctx, refundReasonInfo)
if err != nil {
return err
}
@ -304,15 +305,16 @@ func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.
*payInfo.CardNo = card
*payInfo.Brand = brand
*payInfo.TradeNo = paymentIntent.ID
_, err = payModelT.CreateOrUpdate(ctx, payInfo)
_, err = payModelT.RBCreateOrUpdate(ctx, payInfo)
if err != nil {
return err
}
// 更新设计数据
productDesignModelT := gmodel.NewFsProductDesignModel(connGorm)
productDesignModelTRSB := productDesignModelT.BuilderTrans(ctx, nil)
var isPay int64 = 1
err = productDesignModelT.UpdateByIds(ctx, designIds, &gmodel.FsProductDesign{IsPay: &isPay})
err = productDesignModelT.RBUpdateByIds(productDesignModelTRSB, designIds, &gmodel.FsProductDesign{IsPay: &isPay})
if err != nil {
return err
}
@ -331,7 +333,8 @@ func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.
// 删除购物车
cartModelT := gmodel.NewFsCartModel(connGorm)
err = cartModelT.DeleteCartsByIds(ctx, cartIds)
cartModelTRSB := cartModelT.BuilderTrans(ctx, nil)
err = cartModelT.RBDeleteCartsByIds(cartModelTRSB, cartIds)
if err != nil {
return err
}
@ -353,7 +356,7 @@ func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.
orderInfo.Ptime = &nowTime
orderInfo.PayedAmount = &orderPayedAmount
orderModelT := gmodel.NewFsOrderModel(connGorm)
err = orderModelT.Update(ctx, orderInfo)
err = orderModelT.RBUpdate(ctx, orderInfo)
if err != nil {
return err
}

View File

@ -1,7 +1,7 @@
Name: product-template-tag
Host: 0.0.0.0
Port: 9916
ReplicaId: 10
Port: 9917
SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest
Auth:
AccessSecret: fusen2023

View File

@ -113,14 +113,27 @@ func (l *GetRecommandProductListLogic) GetRecommandProductList(req *types.GetRec
}
}
//获取用户信息(不用判断存在)
user, err := l.svcCtx.AllModels.FsUser.FindUserById(l.ctx, userinfo.UserId)
/*user, err := l.svcCtx.AllModels.FsUser.FindUserById(l.ctx, userinfo.UserId)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get user")
}*/
//获取产品标签相关属性
productTagPropList, err := l.svcCtx.AllModels.FsProductTagProp.GetTagPropByProductIdsWithProductTag(l.ctx, productIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product tag property")
}
mapTagProp := make(map[int64][]types.CoverDefaultItem)
for _, v := range productTagPropList {
mapTagProp[*v.ProductId] = append(mapTagProp[*v.ProductId], types.CoverDefaultItem{
Tag: v.Title,
Cover: *v.Cover,
})
}
list := make([]types.GetRecommandProductListRsp, 0, len(recommendProductList))
for _, v := range recommendProductList {
r := image.ThousandFaceImageFormatReq{
/*r := image.ThousandFaceImageFormatReq{
Size: int(req.Size),
IsThousandFace: 0,
Cover: *v.Cover,
@ -133,7 +146,7 @@ func (l *GetRecommandProductListLogic) GetRecommandProductList(req *types.GetRec
r.IsThousandFace = int(*user.IsThousandFace)
}
//千人前面处理
image.ThousandFaceImageFormat(&r)
image.ThousandFaceImageFormat(&r)*/
isRecommend := int64(0)
if _, ok := mapRecommend[v.Id]; ok {
isRecommend = 1
@ -142,18 +155,22 @@ func (l *GetRecommandProductListLogic) GetRecommandProductList(req *types.GetRec
if minVal, ok := mapProductMinPrice[v.Id]; ok {
minPrice = minVal
}
list = append(list, types.GetRecommandProductListRsp{
item := types.GetRecommandProductListRsp{
Id: v.Id,
Sn: *v.Sn,
Title: *v.Title,
TitleCn: *v.TitleCn,
Cover: r.Cover,
CoverImg: r.CoverImg,
CoverDefault: r.CoverDefault,
Cover: *productInfo.Cover,
CoverImg: *productInfo.CoverImg,
CoverDefault: []types.CoverDefaultItem{},
Intro: *v.Intro,
IsRecommend: isRecommend,
MinPrice: minPrice,
})
}
if _, ok := mapTagProp[productInfo.Id]; ok {
item.CoverDefault = mapTagProp[productInfo.Id]
}
list = append(list, item)
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", list)
}

View File

@ -366,12 +366,13 @@ func (l *GetTagProductListLogic) getTagProducts(req getTagProductsReq) (productL
MinPrice: minPrice,
HaveOptionalFitting: haveOptionalFitting,
Recommended: *productInfo.IsRecommend > 0,
Cover: *productInfo.Cover,
}
if _, ok = req.MapTagProp[productInfo.Id]; ok {
item.CoverDefault = req.MapTagProp[productInfo.Id]
}
//千人千面处理
r := image.ThousandFaceImageFormatReq{
/*r := image.ThousandFaceImageFormatReq{
Size: int(req.Size),
IsThousandFace: 0,
Cover: *productInfo.Cover,
@ -383,7 +384,7 @@ func (l *GetTagProductListLogic) getTagProducts(req getTagProductsReq) (productL
r.IsThousandFace = int(*req.User.IsThousandFace)
}
image.ThousandFaceImageFormat(&r)
item.Cover = r.Cover
item.Cover = r.Cover*/
//加入分类产品切片
productListRsp = append(productListRsp, item)
}

View File

@ -7,9 +7,7 @@ import (
"fusenapi/constants"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/image"
"gorm.io/gorm"
"strconv"
"strings"
"context"
@ -39,13 +37,10 @@ func (l *GetTemplateByPidLogic) GetTemplateByPid(req *types.GetTemplateByPidReq,
if req.Pid == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "err param:pid is empty")
}
if req.Size > 0 {
req.Size = image.GetCurrentSize(req.Size)
}
if req.ProductTemplateTagId <= 0 {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "err param:product_template_tag_id")
}
//获取产品信息(只获取id)
//获取产品信息(只获取id)
productInfo, err := l.svcCtx.AllModels.FsProduct.FindOneBySn(l.ctx, req.Pid, "id")
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@ -54,27 +49,32 @@ func (l *GetTemplateByPidLogic) GetTemplateByPid(req *types.GetTemplateByPidReq,
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product info")
}
//获取尺寸ids(只获取id)
sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByProductIds(l.ctx, []int64{productInfo.Id}, "id")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get size list")
//没有指定物料
sizeIds := make([]int64, 0, 10)
if req.ProductSizeId <= 0 {
//获取产品所有物料
sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByProductIds(l.ctx, []int64{productInfo.Id}, "id")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "failed to get product size list")
}
if len(sizeList) == 0 {
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "product size list is empty")
}
for _, v := range sizeList {
sizeIds = append(sizeIds, v.Id)
}
} else { //指定物料
sizeIds = append(sizeIds, req.ProductSizeId)
}
if len(sizeList) == 0 {
return resp.SetStatusWithMessage(basic.CodeOK, "success:size list is empty")
}
sizeIds := make([]int64, 0, len(sizeList))
for _, v := range sizeList {
sizeIds = append(sizeIds, v.Id)
}
//获取模型数据
modelList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllBySizeIdsTag(l.ctx, sizeIds, constants.TAG_MODEL, "id,size_id")
//根据尺寸id获取模型
modelList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllBySizeIdsTag(l.ctx, sizeIds, constants.TAG_MODEL)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get model list")
}
if len(modelList) == 0 {
return resp.SetStatusWithMessage(basic.CodeOK, "success:model list is empty")
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "model list is empty")
}
modelIds := make([]int64, 0, len(modelList))
mapModel := make(map[int64]int)
@ -82,71 +82,44 @@ func (l *GetTemplateByPidLogic) GetTemplateByPid(req *types.GetTemplateByPidReq,
modelIds = append(modelIds, v.Id)
mapModel[v.Id] = k
}
//获取模板数据
productTemplateList, err := l.svcCtx.AllModels.FsProductTemplateV2.FindAllByModelIdsTemplateTag(l.ctx, modelIds, fmt.Sprintf("%d", req.ProductTemplateTagId), "sort DESC")
//查询模型ids下对应tag标签的模板
templateList, err := l.svcCtx.AllModels.FsProductTemplateV2.FindAllByModelIdsTemplateTag(l.ctx, modelIds, fmt.Sprintf("%d", req.ProductTemplateTagId), "")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product templates")
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template list")
}
if len(productTemplateList) == 0 {
return resp.SetStatusWithMessage(basic.CodeOK, "success:product template list is empty")
}
tagIds := make([]int64, 0, len(productTemplateList))
for _, v := range productTemplateList {
if *v.Tag == "" {
rsp := make(map[string][]interface{})
for _, templateInfo := range templateList {
//没有设置模板据不要
if templateInfo.TemplateInfo == nil || *templateInfo.TemplateInfo == "" {
continue
}
tag, err := strconv.ParseInt(*v.Tag, 10, 64)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "template tag is not a number:"+*v.Tag)
}
tagIds = append(tagIds, tag)
}
//获取模板标签列表
templateTagList, err := l.svcCtx.AllModels.FsProductTemplateTags.GetListByIds(l.ctx, tagIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template tag list")
}
mapTemplateTag := make(map[string]int)
for k, v := range templateTagList {
mapTemplateTag[fmt.Sprintf("%d", v.Id)] = k
}
mapRsp := make(map[string][]interface{})
for _, v := range productTemplateList {
//过滤没有设置详细数据的模板
if v.TemplateInfo == nil || *v.TemplateInfo == "" {
continue
}
var templateInfo map[string]interface{}
if err = json.Unmarshal([]byte(*v.TemplateInfo), &templateInfo); err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse json:template info")
}
if templateInfo["cover"] != nil && templateInfo["cover"].(string) != "" {
cover := strings.Split(templateInfo["cover"].(string), ".")
if req.Size >= 200 && len(cover) >= 2 {
templateInfo["cover"] = fmt.Sprintf("%s_%d.%s", cover[0], req.Size, cover[1])
}
} else {
templateInfo["cover"] = ""
}
templateInfo["tag_name"] = ""
if tagIndex, ok := mapTemplateTag[*v.Tag]; ok {
templateInfo["tag_name"] = *templateTagList[tagIndex].Title
}
templateInfo["title"] = *v.Title
modelIndex, ok := mapModel[*v.ModelId]
modelIndex, ok := mapModel[*templateInfo.ModelId]
if !ok {
continue
}
key := fmt.Sprintf("_%d", *modelList[modelIndex].SizeId)
if _, ok = mapRsp[key]; ok {
mapRsp[key] = append(mapRsp[key], templateInfo)
} else {
mapRsp[key] = []interface{}{templateInfo}
//基础模板信息
var info map[string]map[string]interface{}
if err = json.Unmarshal([]byte(*templateInfo.TemplateInfo), &info); err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeJsonErr, fmt.Sprintf("failed to parse json product template info(may be old data):%d", templateInfo.Id))
}
//后台隐藏/显示信息
var switchInfo interface{}
if templateInfo.SwitchInfo != nil && *templateInfo.SwitchInfo != "" {
_ = json.Unmarshal([]byte(*templateInfo.SwitchInfo), &switchInfo)
}
modelInfo := modelList[modelIndex]
var material interface{}
if info["module_data"] != nil && info["module_data"]["material"] != nil {
material = info["module_data"]["material"]
}
mapKey := fmt.Sprintf("_%d", *modelInfo.SizeId)
rsp[mapKey] = append(rsp[mapKey], map[string]interface{}{
"id": templateInfo.Id,
"material": material,
"material_data": switchInfo,
})
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", mapRsp)
return resp.SetStatusWithMessage(basic.CodeOK, "success", rsp)
}

View File

@ -7,7 +7,6 @@ import (
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/format"
"fusenapi/utils/image"
"gorm.io/gorm"
"sort"
"strings"
@ -36,28 +35,51 @@ func NewHomePageRecommendProductListLogic(ctx context.Context, svcCtx *svc.Servi
func (l *HomePageRecommendProductListLogic) HomePageRecommendProductList(req *types.HomePageRecommendProductListReq, userinfo *auth.UserInfo) (resp *basic.Response) {
//查询用户信息(不用判断存在)
user, err := l.svcCtx.AllModels.FsUser.FindUserById(l.ctx, userinfo.UserId)
_, err := l.svcCtx.AllModels.FsUser.FindUserById(l.ctx, userinfo.UserId)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "get user info err")
}
var (
merchantInfo *gmodel.FsMerchantCategory
recommendProductList []gmodel.FsProduct //产品列表select 字段需要看查询的地方)
productOptionalPartList []gmodel.GetGroupPartListByProductIdsRsp //产品配件列表
mapProductHaveOptionFitting = make(map[int64]struct{})
productPriceList []gmodel.GetPriceListByProductIdsRsp //产品价格列表select 字段需要看查询的地方)
mapProductMinPrice = make(map[int64]int64) //产品最小价格map
productTemplatesV2 []gmodel.FsProductTemplateV2 //产品模板列表select 字段需要看查询的地方)
productSizeCountList []gmodel.CountProductSizeByStatusRsp //产品尺寸数量列表select 字段需要看查询的地方)
mapProductSizeCount = make(map[int64]int64) //产品尺寸数量map
mapProductTemplate = make(map[int64]struct{}) //产品模板map
mapProductHaveOptionFitting = make(map[int64]struct{}) //是否有配件map
productPriceList []gmodel.GetPriceListByProductIdsRsp //产品价格列表select 字段需要看查询的地方)
mapProductMinPrice = make(map[int64]int64) //产品最小价格map
productTemplatesV2 []gmodel.FsProductTemplateV2 //产品模板列表select 字段需要看查询的地方)
productSizeCountList []gmodel.CountProductSizeByStatusRsp //产品尺寸数量列表select 字段需要看查询的地方)
mapProductSizeCount = make(map[int64]int64) //产品尺寸数量map
mapProductTemplate = make(map[int64]struct{}) //产品模板map
)
//选了商家类型
if req.MerchantType > 0 {
merchantInfo, err = l.svcCtx.AllModels.FsMerchantCategory.FindOne(l.ctx, req.MerchantType)
} else {
//随机获取一个商家类型
merchantInfo, err = l.svcCtx.AllModels.FsMerchantCategory.FindRandOne(l.ctx)
}
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "none of merchant type found")
}
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get merchant type info")
}
if *merchantInfo.RecommendProduct == "" {
return resp.SetStatusWithMessage(basic.CodeOK, "success", []interface{}{})
}
recommendProductIds, err := format.StrSlicToInt64Slice(strings.Split(*merchantInfo.RecommendProduct, ","))
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to parse recommend product")
}
//获取列表推荐产品
recommendProductList, _, err = l.svcCtx.AllModels.FsProductRecommend.GetRecommendProductList(gmodel.GetRecommendProductListReq{
Ctx: l.ctx,
Page: 1,
Limit: 500, //设置最大500
})
recommendProductList, err = l.svcCtx.AllModels.FsProduct.GetProductListByIds(l.ctx, recommendProductIds, "sort-desc")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product list")
}
if len(recommendProductList) == 0 {
return resp.SetStatusWithMessage(basic.CodeOK, "success", []interface{}{})
}
@ -125,6 +147,19 @@ func (l *HomePageRecommendProductListLogic) HomePageRecommendProductList(req *ty
for _, v := range productSizeCountList {
mapProductSizeCount[v.ProductId] = v.Num
}
//获取产品标签相关属性
productTagPropList, err := l.svcCtx.AllModels.FsProductTagProp.GetTagPropByProductIdsWithProductTag(l.ctx, productIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product tag property")
}
mapTagProp := make(map[int64][]types.CoverDefaultItem)
for _, v := range productTagPropList {
mapTagProp[*v.ProductId] = append(mapTagProp[*v.ProductId], types.CoverDefaultItem{
Tag: v.Title,
Cover: *v.Cover,
})
}
//组装返回
listRsp := make([]types.HomePageRecommendProductListRsp, 0, len(recommendProductList))
for _, productInfo := range recommendProductList {
@ -147,12 +182,17 @@ func (l *HomePageRecommendProductListLogic) HomePageRecommendProductList(req *ty
Id: productInfo.Id,
Sn: *productInfo.Sn,
Title: *productInfo.Title,
Cover: *productInfo.Cover,
CoverDefault: []types.CoverDefaultItem{},
SizeNum: uint32(sizeNum),
MinPrice: minPrice,
HaveOptionalFitting: haveOptionalFitting,
}
if _, ok = mapTagProp[productInfo.Id]; ok {
item.CoverDefault = mapTagProp[productInfo.Id]
}
//千人千面处理
r := image.ThousandFaceImageFormatReq{
/*r := image.ThousandFaceImageFormatReq{
Size: int(req.Size),
IsThousandFace: 0,
Cover: *productInfo.Cover,
@ -166,7 +206,7 @@ func (l *HomePageRecommendProductListLogic) HomePageRecommendProductList(req *ty
}
image.ThousandFaceImageFormat(&r)
item.Cover = r.Cover
item.CoverDefault = r.CoverDefault
item.CoverDefault = r.CoverDefault*/
//加入分类产品切片
listRsp = append(listRsp, item)
}

View File

@ -234,16 +234,16 @@ type GetRecommandProductListReq struct {
}
type GetRecommandProductListRsp struct {
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
TitleCn string `json:"title_cn"`
Cover string `json:"cover"`
CoverImg string `json:"cover_img"`
CoverDefault string `json:"cover_default"`
Intro string `json:"intro"`
IsRecommend int64 `json:"is_recommend"`
MinPrice int64 `json:"min_price"`
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
TitleCn string `json:"title_cn"`
Cover string `json:"cover"`
CoverImg string `json:"cover_img"`
CoverDefault []CoverDefaultItem `json:"cover_default"`
Intro string `json:"intro"`
IsRecommend int64 `json:"is_recommend"`
MinPrice int64 `json:"min_price"`
}
type GetTagProductListReq struct {
@ -341,7 +341,7 @@ type GetSizeByPidRsp struct {
type GetTemplateByPidReq struct {
Pid string `form:"pid"`
Size uint32 `form:"size"`
ProductSizeId int64 `form:"product_size_id,optional"`
ProductTemplateTagId int64 `form:"product_template_tag_id"`
}
@ -390,18 +390,19 @@ type GetLastProductDesignRsp struct {
}
type HomePageRecommendProductListReq struct {
Size uint32 `form:"size"`
Size uint32 `form:"size"`
MerchantType int64 `form:"merchant_type"`
}
type HomePageRecommendProductListRsp struct {
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
Cover string `json:"cover"`
SizeNum uint32 `json:"size_num"`
MinPrice int64 `json:"min_price"`
CoverDefault string `json:"cover_default"`
HaveOptionalFitting bool `json:"have_optional_fitting"`
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
Cover string `json:"cover"`
SizeNum uint32 `json:"size_num"`
MinPrice int64 `json:"min_price"`
CoverDefault []CoverDefaultItem `json:"cover_default"`
HaveOptionalFitting bool `json:"have_optional_fitting"`
}
type Request struct {

View File

@ -18,13 +18,14 @@ import (
"gorm.io/gorm"
"io/ioutil"
"strconv"
"time"
)
// 这里请求的py接口返回数据
type pythonApiRsp struct {
Id string `json:"id"` //物料模板的id
LogoUrl string `json:"logo_url"` //logo地址
result string `json:"result"` //图片base64
Result string `json:"result"` //图片base64
}
// 消费渲染需要组装的数据
@ -32,6 +33,11 @@ type MqConsumerRenderAssemble struct {
}
func (m *MqConsumerRenderAssemble) Run(ctx context.Context, data []byte) error {
defer func() {
if err := recover(); err != nil {
logx.Error("MqConsumerRenderAssemble panic:", err)
}
}()
logx.Info("收到需要组装的消息:", string(data))
var parseInfo websocket_data.AssembleRenderData
if err := json.Unmarshal(data, &parseInfo); err != nil {
@ -177,10 +183,10 @@ func getCombineImage(ctx context.Context, svcCtx *svc.ServiceContext, parseInfo
//需要替换的参数
replaceData := map[string]interface{}{
"logo_url": parseInfo.RenderData.Logo,
"website": "",
"slogan": "",
"address": "",
"phone": "",
"website": parseInfo.RenderData.Website,
"slogan": parseInfo.RenderData.Slogan,
"address": parseInfo.RenderData.Address,
"phone": parseInfo.RenderData.Phone,
"colors": []string{},
"template_tagid": []string{"b1a"},
"is_crop": false,
@ -227,7 +233,7 @@ func getCombineImage(ctx context.Context, svcCtx *svc.ServiceContext, parseInfo
/*f, _ := os.Create("a.txt")
defer f.Close()
f.Write(postData)*/
httpRsp, err := curl.ApiCall(url, "POST", header, bytes.NewReader(postData), 20)
httpRsp, err := curl.ApiCall(url, "POST", header, bytes.NewReader(postData), time.Second*20)
if err != nil {
logx.Error("failed to combine logo:", err)
return "", err
@ -243,6 +249,7 @@ func getCombineImage(ctx context.Context, svcCtx *svc.ServiceContext, parseInfo
logx.Error("failed to parse python api rsp:", err)
return "", err
}
//fmt.Println("××××××××××××××××××××", pythonApiInfo)
//上传刀版图
var upload = file.Upload{
Ctx: ctx,
@ -251,7 +258,7 @@ func getCombineImage(ctx context.Context, svcCtx *svc.ServiceContext, parseInfo
}
uploadRes, err := upload.UploadFileByBase64(&file.UploadBaseReq{
FileHash: combineHash,
FileData: pythonApiInfo.result,
FileData: pythonApiInfo.Result,
UploadBucket: 1,
ApiType: 2,
UserId: parseInfo.RenderData.UserId,

View File

@ -17,4 +17,5 @@ AWS:
Token:
BLMService:
LogoCombine:
Url: "http://192.168.1.7:45678/LogoCombine"
#Url: "http://192.168.1.7:8999/LogoCombine"
Url: "http://18.119.109.254:8999/LogoCombine"

View File

@ -2,14 +2,16 @@ package logic
import (
"encoding/json"
"errors"
"fusenapi/model/gmodel"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/curl"
"fusenapi/utils/file"
"fusenapi/utils/hash"
"io"
"net/http"
"strings"
"time"
"context"
@ -17,6 +19,7 @@ import (
"fusenapi/server/resource/internal/types"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
)
type LogoCombineLogic struct {
@ -75,8 +78,10 @@ func (l *LogoCombineLogic) LogoCombine(req *types.LogoCombineReq, userinfo *auth
})
} else {
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeDbSqlErr, "LogoCombine error")
if !errors.Is(err, gorm.ErrRecordNotFound) {
logx.Error(err)
return resp.SetStatus(basic.CodeDbSqlErr, "LogoCombine error")
}
}
}
@ -123,7 +128,11 @@ func (l *LogoCombineLogic) LogoCombine(req *types.LogoCombineReq, userinfo *auth
postMap["param_data"] = combineParam
postMapB, _ := json.Marshal(postMap)
result, err := http.Post(l.svcCtx.Config.BLMService.LogoCombine.Url, "application/json", strings.NewReader(string(postMapB)))
//result, err := http.Post(l.svcCtx.Config.BLMService.LogoCombine.Url, "application/json", strings.NewReader(string(postMapB)))
var headerData = make(map[string]string, 1)
headerData["Content-Type"] = "application/json"
result, err := curl.ApiCall(l.svcCtx.Config.BLMService.LogoCombine.Url, "POST", headerData, strings.NewReader(string(postMapB)), time.Second*20)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileLogoCombineErr, "service post fail")
@ -134,8 +143,9 @@ func (l *LogoCombineLogic) LogoCombine(req *types.LogoCombineReq, userinfo *auth
logx.Error(err)
return resp.SetStatus(basic.CodeFileLogoCombineErr, "service read fail")
}
ress := string(b)
if string(b) == "Internal Server Error" {
if ress == "Internal Server Error" {
return resp.SetStatus(basic.CodeFileLogoCombineErr, "service read fail")
}

View File

@ -16,4 +16,5 @@ AWS:
Token:
BLMService:
ImageProcess:
Url: "http://192.168.1.7:45678/FeatureExtraction"
#Url: "http://192.168.1.7:45678/FeatureExtraction"
Url: "http://18.119.109.254:8999/FeatureExtraction"

View File

@ -21,7 +21,7 @@ func UploadLogoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
}
// 创建一个业务逻辑层实例
l := logic.NewUploadLogoLogic(r.Context(), svcCtx)
l := logic.NewUploadLogoLogic(r, svcCtx)
rl := reflect.ValueOf(l)
basic.BeforeLogic(w, r, rl)

View File

@ -66,8 +66,10 @@ func (l *UploadCallbackLogic) UploadCallback(req *types.UploadCallbackReq, useri
ctx := l.ctx
err := l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error {
resourceModelTS := gmodel.NewFsResourceModel(l.svcCtx.MysqlConn)
resourceInfo, err := resourceModelTS.FindOneById(ctx, req.ResourceId)
resourceModelTS := gmodel.NewFsResourceModel(connGorm)
transBuilder := resourceModelTS.BuilderTrans(nil)
transBuilderFind := transBuilder.Where("resource_id =?", req.ResourceId)
resourceInfo, err := resourceModelTS.FindOneByQuery(ctx, transBuilderFind, nil)
if err != nil {
return err
}
@ -84,9 +86,9 @@ func (l *UploadCallbackLogic) UploadCallback(req *types.UploadCallbackReq, useri
fsResource.BucketName = bucketName
fsResource.Version = &version
if resourceInfo.ResourceId == "" {
_, err = resourceModelTS.Create(ctx, fsResource)
_, err = resourceModelTS.BuilderCreate(ctx, transBuilder, fsResource)
} else {
_, err = resourceModelTS.Update(ctx, fsResource)
_, err = resourceModelTS.BuilderUpdate(ctx, transBuilder, fsResource)
}
return err
})

View File

@ -6,7 +6,10 @@ import (
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/curl"
"fusenapi/utils/file"
"fusenapi/utils/hash"
"io"
"net/http"
"strings"
"time"
@ -22,13 +25,15 @@ type UploadLogoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
r *http.Request
}
func NewUploadLogoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogoLogic {
func NewUploadLogoLogic(r *http.Request, svcCtx *svc.ServiceContext) *UploadLogoLogic {
return &UploadLogoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
Logger: logx.WithContext(r.Context()),
ctx: r.Context(),
svcCtx: svcCtx,
r: r,
}
}
@ -61,6 +66,43 @@ func (l *UploadLogoLogic) UploadLogo(req *types.UploadLogoReq, userinfo *auth.Us
userId = userinfo.UserId
}
//设置内存大小
l.r.ParseMultipartForm(32 << 20)
fileObject, _, err := l.r.FormFile("file")
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "file upload err,no files")
}
// 读取数据流
ioData, err := io.ReadAll(fileObject)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "file upload err,no files")
}
// 上传文件
var upload = file.Upload{
Ctx: l.ctx,
MysqlConn: l.svcCtx.MysqlConn,
AwsSession: l.svcCtx.AwsSession,
}
var resourceId string = hash.JsonHashKey(req.FileKey)
uploadRes, err := upload.UploadFileByByte(&file.UploadBaseReq{
FileHash: resourceId,
FileByte: ioData,
UploadBucket: 1,
ApiType: 2,
UserId: userId,
GuestId: guestId,
})
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "upload file failed")
}
var logoWidth int64
var logoHeight int64
// 查看sku是否存在
@ -82,17 +124,14 @@ func (l *UploadLogoLogic) UploadLogo(req *types.UploadLogoReq, userinfo *auth.Us
logoHeight = 200
}
var resultStr string
var err error
var postMap = make(map[string]interface{}, 1)
postMap["logo_url"] = req.ResourceUrl
postMap["logo_url"] = uploadRes.ResourceUrl
postMapB, _ := json.Marshal(postMap)
//result, err := http.Post(l.svcCtx.Config.BLMService.ImageProcess.Url, "application/json", strings.NewReader(string(postMapB)))
var headerData = make(map[string]string, 1)
headerData["Content-Type"] = "application/json"
result, err := curl.ApiCall(l.svcCtx.Config.BLMService.ImageProcess.Url, "POST", headerData, strings.NewReader(string(postMapB)), 20)
result, err := curl.ApiCall(l.svcCtx.Config.BLMService.ImageProcess.Url, "POST", headerData, strings.NewReader(string(postMapB)), time.Second*20)
if err != nil {
logx.Error(err)
@ -118,8 +157,8 @@ func (l *UploadLogoLogic) UploadLogo(req *types.UploadLogoReq, userinfo *auth.Us
Module: &module,
UserId: &userId,
GuestId: &guestId,
ResourceId: &req.ResourceId,
ResourceUrl: &req.ResourceUrl,
ResourceId: &uploadRes.ResourceId,
ResourceUrl: &uploadRes.ResourceUrl,
Metadata: &resultStr,
CreateAt: &nowTime,
})
@ -129,5 +168,12 @@ func (l *UploadLogoLogic) UploadLogo(req *types.UploadLogoReq, userinfo *auth.Us
return resp.SetStatus(basic.CodeFileUploadLogoErr, "service fail")
}
return resp.SetStatus(basic.CodeOK)
// 返回成功的响应和上传URL
return resp.SetStatus(basic.CodeOK, map[string]interface{}{
"upload_data": UploadUrl{
Status: 1,
ResourceId: uploadRes.ResourceId,
ResourceUrl: uploadRes.ResourceUrl,
},
})
}

View File

@ -16,11 +16,10 @@ type UploadFileBaseReq struct {
}
type UploadLogoReq struct {
ResourceId string `form:"resource_id"` // 资源ID
ResourceUrl string `form:"resource_url"` // 资源URL
IsRemoveBg int64 `form:"is_remove_bg,optional"` // 是否要去掉背景
Proportion int64 `form:"proportion,default=60"` // 贴图在模型面板上的比例
SkuId int64 `form:"sku_id,default=0"` // 模板ID
FileKey string `form:"file_key"` // 上传logo唯一标识信息
IsRemoveBg int64 `form:"is_remove_bg,optional"` // 是否要去掉背景
Proportion int64 `form:"proportion,default=60"` // 贴图在模型面板上的比例
SkuId int64 `form:"sku_id,default=0"` // 模板ID
}
type UploadFileBackendReq struct {

View File

@ -13,6 +13,7 @@ import (
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"context"
@ -62,6 +63,8 @@ var (
}
//websocket连接存储
mapConnPool = sync.Map{}
//公共互斥锁
publicMutex sync.Mutex
)
// 每个连接的连接基本属性
@ -72,7 +75,7 @@ type wsConnectItem struct {
allModels *gmodel.AllModelsGen
closeChan chan struct{} //ws连接关闭chan
isClose bool //是否已经关闭
uniqueId uint64 //ws连接唯一标识
uniqueId string //ws连接唯一标识
inChan chan []byte //接受消息缓冲通道
outChan chan []byte //发送回客户端的消息
mutex sync.Mutex //互斥锁
@ -96,7 +99,7 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp
)
isAuth, userInfo = l.checkAuth(svcCtx, r)
if !isAuth {
time.Sleep(time.Second * 4) //兼容下火狐
time.Sleep(time.Second * 2) //兼容下火狐
rsp := websocket_data.DataTransferData{
T: constants.WEBSOCKET_UNAUTH,
D: nil,
@ -111,8 +114,27 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp
//测试的目前写死 39
var userInfo auth.UserInfo
userInfo.UserId = 39
//设置连接
ws := l.setConnPool(conn, userInfo)
defer ws.close()
//循环读客户端信息
go ws.readLoop()
//循环把数据发送给客户端
go ws.writeLoop()
//推消息到云渲染
go ws.sendLoop()
//操作连接中渲染任务的增加/删除
go ws.operationRenderTask()
//心跳
ws.heartbeat()
}
// 设置连接
func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo auth.UserInfo) wsConnectItem {
publicMutex.Lock()
defer publicMutex.Unlock()
//生成连接唯一标识
uniqueId := websocketIdGenerator.Get()
uniqueId := l.getUniqueId()
ws := wsConnectItem{
conn: conn,
ctx: l.ctx,
@ -131,23 +153,22 @@ func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.Resp
}
//保存连接
mapConnPool.Store(uniqueId, ws)
defer ws.close()
go func() {
//把连接成功消息发回去
time.Sleep(time.Second * 4) //兼容下火狐
time.Sleep(time.Second * 2) //兼容下火狐
b := ws.respondDataFormat(constants.WEBSOCKET_CONNECT_SUCCESS, uniqueId)
_ = conn.WriteMessage(websocket.TextMessage, b)
}()
//循环读客户端信息
go ws.readLoop()
//循环把数据发送给客户端
go ws.writeLoop()
//推消息到云渲染
go ws.sendLoop()
//操作连接中渲染任务的增加/删除
go ws.operationRenderTask()
//心跳
ws.heartbeat()
return ws
}
// 获取唯一id
func (l *DataTransferLogic) getUniqueId() string {
uniqueId := uuid.New().String() + time.Now().Format("20060102150405")
if _, ok := mapConnPool.Load(uniqueId); ok {
uniqueId = l.getUniqueId()
}
return uniqueId
}
// 鉴权
@ -293,6 +314,9 @@ func (w *wsConnectItem) dealwithReciveData(data []byte) {
//图片渲染
case constants.WEBSOCKET_RENDER_IMAGE:
w.renderImage(d)
//刷新重连请求恢复上次连接的标识
case constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT:
w.resumeLateConnect(d)
default:
}

View File

@ -14,6 +14,11 @@ type MqConsumerRenderResult struct {
}
func (m *MqConsumerRenderResult) Run(ctx context.Context, data []byte) error {
defer func() {
if err := recover(); err != nil {
logx.Error("MqConsumerRenderResult panic:", err)
}
}()
logx.Info("接收到MqConsumerRenderResult数据:", string(data))
var parseInfo websocket_data.RenderImageNotify
if err := json.Unmarshal(data, &parseInfo); err != nil {

View File

@ -0,0 +1,27 @@
package logic
import "fusenapi/constants"
// 刷新重连请求恢复上次连接的标识
func (w *wsConnectItem) resumeLateConnect(data []byte) {
clientId := string(data)
//id长度不对
if len(clientId) != 50 {
rsp := w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR, "request id is invalid")
w.sendToOutChan(rsp)
return
}
publicMutex.Lock()
defer publicMutex.Unlock()
//存在是不能给他申请重新绑定
if _, ok := mapConnPool.Load(clientId); ok {
rsp := w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_ERR, "id has bound by other connect ")
w.sendToOutChan(rsp)
return
}
//重新绑定
w.uniqueId = clientId
rsp := w.respondDataFormat(constants.WEBSOCKET_REQUEST_RESUME_LAST_CONNECT_SUCCESS, clientId)
w.sendToOutChan(rsp)
return
}

View File

@ -50,7 +50,7 @@ service product {
//获取产品尺寸列表
@handler GetSizeByPidHandler
get /api/product/get_size_by_pid(GetSizeByPidReq) returns (response);
//获取产品模板列表
//获取产品模板
@handler GetTemplateByPidHandler
get /api/product/get_template_by_pid(GetTemplateByPidReq) returns (response);
//获取产品配件数据
@ -286,16 +286,16 @@ type GetRecommandProductListReq {
Sn string `form:"sn"`
}
type GetRecommandProductListRsp {
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
TitleCn string `json:"title_cn"`
Cover string `json:"cover"`
CoverImg string `json:"cover_img"`
CoverDefault string `json:"cover_default"`
Intro string `json:"intro"`
IsRecommend int64 `json:"is_recommend"`
MinPrice int64 `json:"min_price"`
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
TitleCn string `json:"title_cn"`
Cover string `json:"cover"`
CoverImg string `json:"cover_img"`
CoverDefault []CoverDefaultItem `json:"cover_default"`
Intro string `json:"intro"`
IsRecommend int64 `json:"is_recommend"`
MinPrice int64 `json:"min_price"`
}
//获取分类产品列表
type GetTagProductListReq {
@ -383,10 +383,10 @@ type GetSizeByPidRsp {
IsPopular bool `json:"is_popular"` //是否受欢迎
MinPrice float64 `json:"min_price"` //最小价格
}
//获取产品模板列表
//获取产品模板
type GetTemplateByPidReq {
Pid string `form:"pid"`
Size uint32 `form:"size"`
ProductSizeId int64 `form:"product_size_id,optional"`
ProductTemplateTagId int64 `form:"product_template_tag_id"`
}
//获取产品配件数据
@ -433,15 +433,16 @@ type GetLastProductDesignRsp {
}
//获取列表页推荐产品(返回是这个维度数组)
type HomePageRecommendProductListReq {
Size uint32 `form:"size"`
Size uint32 `form:"size"`
MerchantType int64 `form:"merchant_type"`
}
type HomePageRecommendProductListRsp {
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
Cover string `json:"cover"`
SizeNum uint32 `json:"size_num"`
MinPrice int64 `json:"min_price"`
CoverDefault string `json:"cover_default"`
HaveOptionalFitting bool `json:"have_optional_fitting"`
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
Cover string `json:"cover"`
SizeNum uint32 `json:"size_num"`
MinPrice int64 `json:"min_price"`
CoverDefault []CoverDefaultItem `json:"cover_default"`
HaveOptionalFitting bool `json:"have_optional_fitting"`
}

View File

@ -58,11 +58,10 @@ type (
type (
UploadLogoReq {
ResourceId string `form:"resource_id"` // 资源ID
ResourceUrl string `form:"resource_url"` // 资源URL
IsRemoveBg int64 `form:"is_remove_bg,optional"` // 是否要去掉背景
Proportion int64 `form:"proportion,default=60"` // 贴图在模型面板上的比例
SkuId int64 `form:"sku_id,default=0"` // 模板ID
FileKey string `form:"file_key"` // 上传logo唯一标识信息
IsRemoveBg int64 `form:"is_remove_bg,optional"` // 是否要去掉背景
Proportion int64 `form:"proportion,default=60"` // 贴图在模型面板上的比例
SkuId int64 `form:"sku_id,default=0"` // 模板ID
}
)

View File

@ -16,6 +16,10 @@ type RenderData struct {
ProductId int64 `json:"product_id"` //产品id
UserMaterialId int64 `json:"user_material_id"` //用户素材id
Logo string `json:"logo"` //log资源地址(websocket连接建立再赋值)
Website string `json:"website"` //网站
Slogan string `json:"slogan"` //slogan
Address string `json:"address"` //地址
Phone string `json:"phone"` //电话
UserId int64 `json:"user_id"` //用户id(websocket连接建立再赋值)
GuestId int64 `json:"guest_id"` //游客id(websocket连接建立再赋值)
}