Merge branch 'feature/mhw-v1.01' of https://gitee.com/fusenpack/fusenapi into develop
This commit is contained in:
6
constants/min_purchase_box.go
Normal file
6
constants/min_purchase_box.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package constants
|
||||
|
||||
type Purchase int64
|
||||
|
||||
// 最低购买箱数
|
||||
const MIN_PURCHASE_QUANTITY Purchase = 3
|
||||
85
constants/orders.go
Normal file
85
constants/orders.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package constants
|
||||
|
||||
// 货币
|
||||
type Currency string
|
||||
|
||||
const (
|
||||
Usd Currency = "usd"
|
||||
)
|
||||
|
||||
// 金额单位
|
||||
type AmountUnit string
|
||||
|
||||
// 交易方式
|
||||
type PayMethods string
|
||||
|
||||
const (
|
||||
Card PayMethods = "CARD"
|
||||
Visa PayMethods = "VISA"
|
||||
)
|
||||
|
||||
// 支付状态
|
||||
type PayStatusCode int64
|
||||
|
||||
const (
|
||||
PayStatusUnpaid PayStatusCode = 10 //10,未支付
|
||||
PayStatusPaid PayStatusCode = 20 //20,已支付
|
||||
PayStatusRefunded PayStatusCode = 30 //30,已退款
|
||||
)
|
||||
|
||||
// 订单状态
|
||||
type OrderStatusCode int64
|
||||
|
||||
const (
|
||||
ORDERSTATUSUNPAIDDEPOSIT OrderStatusCode = 0 // 0,未支付定金
|
||||
ORDERSTATUSDIRECTMAILORDERED OrderStatusCode = 10100 // 10100,直邮单--已下单
|
||||
ORDERSTATUSDIRECTMAILCANCEL OrderStatusCode = 10101 // 10101,直邮单--已取消
|
||||
ORDERSTATUSDIRECTMAILSTARTPRODUCTION OrderStatusCode = 10200 // 10200,直邮单--开始生产
|
||||
ORDERSTATUSDIRECTMAILCOMPLETEPRODUCTION OrderStatusCode = 10300 // 10300,直邮单--生产完成
|
||||
ORDERSTATUSDIRECTMAILSHIPPED OrderStatusCode = 10400 // 10400,直邮单--已发货
|
||||
ORDERSTATUSDIRECTMAILARRIVED OrderStatusCode = 10500 // 10500,直邮单--已到达
|
||||
ORDERSTATUSCLOUDSTOREORDERED OrderStatusCode = 20100 // 20100,云仓单--已下单
|
||||
ORDERSTATUSCLOUDSTORECANCEL OrderStatusCode = 20101 // 20101,云仓单--已取消
|
||||
ORDERSTATUSCLOUDSTORESTARTPRODUCTION OrderStatusCode = 20200 // 20200,云仓单--开始生产
|
||||
ORDERSTATUSCLOUDSTOREOMPLETEPRODUCTION OrderStatusCode = 20300 // 20300,云仓单--生产完成
|
||||
ORDERSTATUSCLOUDSTOREARRIVEDWAREHOUSE OrderStatusCode = 20400 // 20400,云仓单--直达仓库
|
||||
)
|
||||
|
||||
// 订单状态名称
|
||||
var OrderStatusMessage map[OrderStatusCode]string
|
||||
|
||||
// 支付状态名称
|
||||
var PayStatusMessage map[PayStatusCode]string
|
||||
|
||||
// 订单状态--用户可见
|
||||
var OrderStatusUser []OrderStatusCode
|
||||
|
||||
func init() {
|
||||
// 订单状态名称
|
||||
PayStatusMessage = make(map[PayStatusCode]string)
|
||||
PayStatusMessage[PayStatusUnpaid] = "Paid"
|
||||
PayStatusMessage[PayStatusPaid] = "Unpaid"
|
||||
PayStatusMessage[PayStatusRefunded] = "Refunded"
|
||||
|
||||
// 订单状态名称
|
||||
OrderStatusMessage = make(map[OrderStatusCode]string)
|
||||
OrderStatusMessage[ORDERSTATUSUNPAIDDEPOSIT] = "未支付定金"
|
||||
|
||||
OrderStatusMessage[ORDERSTATUSDIRECTMAILORDERED] = "直邮单--已下单"
|
||||
OrderStatusMessage[ORDERSTATUSDIRECTMAILSTARTPRODUCTION] = "直邮单--开始生产"
|
||||
OrderStatusMessage[ORDERSTATUSDIRECTMAILCOMPLETEPRODUCTION] = "直邮单--生产完成"
|
||||
OrderStatusMessage[ORDERSTATUSDIRECTMAILSHIPPED] = "直邮单--已发货"
|
||||
OrderStatusMessage[ORDERSTATUSDIRECTMAILARRIVED] = "直邮单--已到达"
|
||||
|
||||
OrderStatusMessage[ORDERSTATUSCLOUDSTOREORDERED] = "云仓单--已下单"
|
||||
OrderStatusMessage[ORDERSTATUSCLOUDSTORESTARTPRODUCTION] = "云仓单--开始生产"
|
||||
OrderStatusMessage[ORDERSTATUSCLOUDSTOREOMPLETEPRODUCTION] = "云仓单--生产完成"
|
||||
OrderStatusMessage[ORDERSTATUSCLOUDSTOREARRIVEDWAREHOUSE] = "云仓单--直达仓库"
|
||||
|
||||
// 订单状态--用户可见
|
||||
OrderStatusUser = []OrderStatusCode{
|
||||
ORDERSTATUSUNPAIDDEPOSIT,
|
||||
ORDERSTATUSDIRECTMAILORDERED, ORDERSTATUSDIRECTMAILSTARTPRODUCTION, ORDERSTATUSDIRECTMAILCOMPLETEPRODUCTION, ORDERSTATUSDIRECTMAILSHIPPED, ORDERSTATUSDIRECTMAILARRIVED,
|
||||
ORDERSTATUSCLOUDSTOREORDERED, ORDERSTATUSCLOUDSTORESTARTPRODUCTION, ORDERSTATUSCLOUDSTOREOMPLETEPRODUCTION, ORDERSTATUSCLOUDSTOREARRIVEDWAREHOUSE,
|
||||
}
|
||||
}
|
||||
25
model/gmodel/fs_cloud_storage_gen.go
Normal file
25
model/gmodel/fs_cloud_storage_gen.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package gmodel
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// fs_cloud_storage 仓库的基本信息, 只做映射
|
||||
type FsCloudStorage struct {
|
||||
CloudStorageId *string `gorm:"unique_key;default:'';" json:"cloud_storage_id"` // 仓库id, 需要固定的命名规则, 能表达国外国内,区域等,简单明了
|
||||
Name *string `gorm:"default:'';" json:"name"` // 仓库的名字, 中文使用拼音,国外使用英文
|
||||
Address *string `gorm:"default:'';" json:"address"` // 仓库地址
|
||||
Contact *[]byte `gorm:"default:'';" json:"contact"` //
|
||||
Ownership *int64 `gorm:"default:0;" json:"ownership"` // 0为自有, 1为第三方, 后期可以自由定制
|
||||
Scope *[]byte `gorm:"default:'';" json:"scope"` //
|
||||
Capacity *[]byte `gorm:"default:'';" json:"capacity"` //
|
||||
Metadata *[]byte `gorm:"default:'';" json:"metadata"` //
|
||||
}
|
||||
type FsCloudStorageModel struct {
|
||||
db *gorm.DB
|
||||
name string
|
||||
}
|
||||
|
||||
func NewFsCloudStorageModel(db *gorm.DB) *FsCloudStorageModel {
|
||||
return &FsCloudStorageModel{db: db, name: "fs_cloud_storage"}
|
||||
}
|
||||
2
model/gmodel/fs_cloud_storage_logic.go
Normal file
2
model/gmodel/fs_cloud_storage_logic.go
Normal file
@@ -0,0 +1,2 @@
|
||||
package gmodel
|
||||
// TODO: 使用model的属性做你想做的
|
||||
@@ -1,8 +1,9 @@
|
||||
package gmodel
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// fs_order 订单表
|
||||
@@ -10,12 +11,13 @@ type FsOrder struct {
|
||||
Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单ID
|
||||
UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID
|
||||
DeliveryMethod *int64 `gorm:"index;default:0;" json:"delivery_method"` // 物流类型
|
||||
OrderNo *string `gorm:"index;default:'';" json:"order_no"` //
|
||||
OrderSn *string `gorm:"index;default:'';" json:"order_sn"` //
|
||||
OrderSource *string `gorm:"default:'';" json:"order_source"` //
|
||||
Status *int64 `gorm:"index;default:0;" json:"status"` // 订单状态
|
||||
Metadata *[]byte `gorm:"default:'';" json:"metadata"` //
|
||||
Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` //
|
||||
Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` //
|
||||
IsDel *int64 `gorm:"default:0;" json:"is_del"` // 是否删除:0=否,1=是
|
||||
}
|
||||
type FsOrderModel struct {
|
||||
db *gorm.DB
|
||||
|
||||
297
model/gmodel/fs_order_logic.go
Executable file → Normal file
297
model/gmodel/fs_order_logic.go
Executable file → Normal file
@@ -1,192 +1,189 @@
|
||||
package gmodel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fusenapi/constants"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"fusenapi/utils/handlers"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (o *FsOrderModel) FindOneBySn(ctx context.Context, userId int64, sn string) (resp *FsOrder, err error) {
|
||||
err = o.db.WithContext(ctx).Model(&FsOrder{}).Where(" `user_id` = ? and `sn` = ? ", userId, sn).Take(&resp).Error
|
||||
return resp, err
|
||||
// TODO: 使用model的属性做你想做的
|
||||
|
||||
type NewFsOrder struct {
|
||||
Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单ID
|
||||
UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID
|
||||
DeliveryMethod *int64 `gorm:"index;default:0;" json:"delivery_method"` // 物流类型
|
||||
OrderSn *string `gorm:"index;default:'';" json:"order_sn"` //
|
||||
OrderSource *string `gorm:"default:'';" json:"order_source"` //
|
||||
Status *int64 `gorm:"index;default:0;" json:"status"` // 订单状态
|
||||
Metadata *OrderDetail `gorm:"metadata,type:json" json:"metadata"` //
|
||||
Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` //
|
||||
Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` //
|
||||
IsDel *int64 `gorm:"default:0;" json:"is_del"` // 是否删除:0=否,1=是
|
||||
}
|
||||
|
||||
func (o *FsOrderModel) FindOne(ctx context.Context, userId int64, OrderId int64) (order *FsOrder, err error) {
|
||||
err = o.db.WithContext(ctx).Model(&FsOrder{}).Where("`user_id` = ? and `id` = ?", userId, OrderId).Take(&order).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
// 订单详情
|
||||
type OrderDetail struct {
|
||||
DeliveryAddress *OrderAddress `json:"delivery_address"` // 收货地址
|
||||
OrderAmount OrderAmount `json:"order_amount"` // 订单金额
|
||||
OrderInfo OrderInfo `json:"order_info"` // 订单信息
|
||||
OrderProduct []OrderProduct `json:"order_product"` // 订单商品
|
||||
}
|
||||
|
||||
func (o *FsOrderModel) Update(ctx context.Context, data *FsOrder) error {
|
||||
return o.db.WithContext(ctx).Model(&FsOrder{}).Where("`id` = ?", data.Id).Updates(&data).Error
|
||||
// 收货地址
|
||||
type OrderAddress struct {
|
||||
Address string `json:"address"` // 详细地址
|
||||
Mobile string `json:"mobile"` // 手机
|
||||
Name string `json:"name"` // 姓名
|
||||
}
|
||||
|
||||
func (o *FsOrderModel) RBUpdate(ctx context.Context, data *FsOrder) error {
|
||||
return o.db.WithContext(ctx).Where("`id` = ?", data.Id).Updates(&data).Error
|
||||
// 订单金额
|
||||
type OrderAmount struct {
|
||||
Deposit PayInfo `json:"deposit"` // 定金
|
||||
RemainingBalance PayInfo `json:"remaining_balance"` // 尾款
|
||||
Discount AmountInfo `json:"discount"` // 折扣
|
||||
ShippingFee AmountInfo `json:"shipping_fee"` // 邮费
|
||||
Tax AmountInfo `json:"tax"` // 税费
|
||||
Subtotal AmountInfo `json:"subtotal"` // 商品总金额
|
||||
Total AmountInfo `json:"total"` // 订单总金额
|
||||
}
|
||||
|
||||
func (o *FsOrderModel) Create(ctx context.Context, data *FsOrder) error {
|
||||
return o.db.WithContext(ctx).Model(&FsOrder{}).Create(&data).Error
|
||||
// 支付明细
|
||||
type PayInfo struct {
|
||||
Metadata map[string]interface{} `json:"metadata"` // 额外参数
|
||||
PayAmount AmountInfo `json:"pay_amount"` // 金额明细
|
||||
PayMethod string `json:"pay_method"` // 交易方式
|
||||
PayTime string `json:"pay_time"` // 支付时间
|
||||
Status PayStatus `json:"status"` // 当前状态
|
||||
StatusLink []PayStatus `json:"status_link"` // 状态链路
|
||||
TradeNo string `json:"trade_no"` // 支付交易号
|
||||
}
|
||||
|
||||
func (o *FsOrderModel) FindOneAndCreateServiceContact(ctx context.Context, userId int64, OrderId int64, cs *FsContactService) (order *FsOrder, err error) {
|
||||
err = o.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
err = tx.Model(&FsOrder{}).Select("id").Limit(1).Where("`user_id` = ? and `id` = ?", userId, OrderId).Take(&order).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctime := time.Now().UTC().Unix()
|
||||
cs.Ctime = &ctime
|
||||
if constants.ConcactService(*cs.Type) == constants.TYPE_DEFAULT {
|
||||
*cs.RelationId = 0
|
||||
}
|
||||
|
||||
return tx.Model(&FsContactService{}).Create(cs).Error
|
||||
})
|
||||
return order, err
|
||||
// 金额明细
|
||||
type AmountInfo struct {
|
||||
ExchangeRate string `json:"exchange_rate"` // 换算汇率
|
||||
Change constants.AmountUnit `json:"change,omitempty"` // 变动金额
|
||||
ChangeRemark string `json:"change_remark,omitempty"` // 变动备注状态编码
|
||||
Currency string `json:"currency"` // 货币
|
||||
Current constants.AmountUnit `json:"current"` // 当前金额
|
||||
Initiate constants.AmountUnit `json:"initiate"` // 初始金额
|
||||
Metadata map[string]interface{} `json:"metadata"` // 额外明细
|
||||
}
|
||||
|
||||
// 获取用户最近下单成功的订单
|
||||
func (o *FsOrderModel) FindLastSuccessOneOrder(ctx context.Context, userId int64, statusGt int64) (order *FsOrder, err error) {
|
||||
err = o.db.WithContext(ctx).Model(&FsOrder{}).Where("`user_id` = ? and `status` > ?", userId, statusGt).Order("id DESC").Take(&order).Error
|
||||
return order, err
|
||||
// 金额货币
|
||||
type AmountCurrency struct {
|
||||
CurrentAmount constants.AmountUnit `json:"current_amount"` // 当前金额
|
||||
CurrentCurrency string `json:"current_currency"` // 当前货币
|
||||
ExchangeRate string `json:"exchange_rate"` // 换算汇率
|
||||
OriginalAmount constants.AmountUnit `json:"original_amount"` // 原始金额
|
||||
OriginalCurrency string `json:"original_currency"` // 原始货币
|
||||
}
|
||||
|
||||
// 分页查询的订单
|
||||
func (o *FsOrderModel) FindPageListByPage(ctx context.Context, rowBuilder *gorm.DB, page *int64, pageSize *int64, filterMap map[string]string, orderBy string) ([]*FsOrderRel, error) {
|
||||
var resp []*FsOrderRel
|
||||
// 过滤
|
||||
if filterMap != nil {
|
||||
rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap))
|
||||
}
|
||||
|
||||
// 排序
|
||||
if orderBy != "" {
|
||||
var fieldsMap = make(map[string]struct{})
|
||||
s := reflect.TypeOf(&FsOrder{}).Elem() //通过反射获取type定义
|
||||
for i := 0; i < s.NumField(); i++ {
|
||||
fieldsMap[s.Field(i).Tag.Get("json")] = struct{}{}
|
||||
}
|
||||
rowBuilder = rowBuilder.Scopes(handlers.OrderCheck(orderBy, fieldsMap))
|
||||
}
|
||||
|
||||
// 分页
|
||||
rowBuilder = rowBuilder.Scopes(handlers.Paginate(page, pageSize))
|
||||
|
||||
// 结果
|
||||
result := rowBuilder.Debug().WithContext(ctx).Find(&resp)
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
} else {
|
||||
return resp, nil
|
||||
}
|
||||
// 支付状态
|
||||
type PayStatus struct {
|
||||
Metadata map[string]interface{} `json:"metadata"` // 额外参数
|
||||
StatusCode int64 `json:"status_code"` // 状态编码
|
||||
StatusTitle string `json:"status_title"` // 状态名称
|
||||
}
|
||||
|
||||
type FsOrderRel struct {
|
||||
FsOrder
|
||||
FsOrderDetails []FsOrderDetails `gorm:"foreignKey:order_id;references:id"`
|
||||
FsOrderAffiliateInfo FsOrderAffiliate `gorm:"foreignKey:order_id;references:id"`
|
||||
// 订单信息
|
||||
type OrderInfo struct {
|
||||
Ctime string `json:"ctime"` // 创建日期
|
||||
DeliveryMethod int64 `json:"delivery_method"` // 物流类型
|
||||
Metadata map[string]interface{} `json:"metadata"` // 额外参数
|
||||
OrderSn string `json:"order_sn"` // 订单编号
|
||||
Status OrderStatus `json:"status"` // 当前状态
|
||||
StatusLink []OrderStatus `json:"status_link"` // 状态链路
|
||||
Utime string `json:"utime"` // 更新时间
|
||||
}
|
||||
|
||||
type FsOrderDetails struct {
|
||||
FsOrderDetail
|
||||
FsOrderDetailTemplateInfo FsOrderDetailTemplateInfo `gorm:"foreignKey:id;references:order_detail_template_id"`
|
||||
FsProductInfo FsProduct `gorm:"foreignKey:id;references:product_id"`
|
||||
// 订单状态--用户
|
||||
type OrderStatus struct {
|
||||
Children []*OrderStatus `json:"children"` // 子状态,管理人员的处理状态, 用户不可见
|
||||
Ctime string `json:"ctime"` // 创建时间
|
||||
ExpectedTime string `json:"expected_time"` // 预计时间
|
||||
Metadata map[string]interface{} `json:"metadata"` // 额外参数
|
||||
StatusCode constants.OrderStatusCode `json:"status_code"` // 状态编码
|
||||
StatusTitle string `json:"status_title"` // 状态名称
|
||||
Utime string `json:"utime"` // 更新时间
|
||||
}
|
||||
|
||||
type FsOrderDetailTemplateInfo struct {
|
||||
FsOrderDetailTemplate
|
||||
FsProductDesignInfo FsProductDesignInfo `gorm:"foreignKey:id;references:design_id"` //获取设计数据
|
||||
FsProductSizeInfo FsProductSize `gorm:"foreignKey:id;references:size_id"`
|
||||
// 订单商品
|
||||
type OrderProduct struct {
|
||||
Amount AmountCurrency `json:"amount"` // 商品总价
|
||||
ExpectedDeliveryTime string `json:"expected_delivery_time"` // 预计到货时间
|
||||
Number int64 `json:"number"` // 商品数量
|
||||
ProductID string `json:"product_id"` // 商品ID
|
||||
ProductLogo string `json:"product_logo"` // 商品logo
|
||||
ProductLogoResource *Resource `json:"product_logo_resource"` // 商品封面--资源详情
|
||||
ProductName string `json:"product_name"` // 商品名称
|
||||
ProductPrice AmountCurrency `json:"product_price"` // 商品单价
|
||||
ProductSnapshot map[string]interface{} `json:"product_snapshot"` // 商品快照
|
||||
ShoppingCartSnapshot *ShoppingCartSnapshot `json:"shopping_cart_snapshot"` // 购物车快照
|
||||
Unit string `json:"unit"` // 商品单位
|
||||
}
|
||||
|
||||
type FsProductDesignInfo struct {
|
||||
FsProductDesign
|
||||
OptionData FsProduct `gorm:"foreignKey:id;references:optional_id"` //获取配件信息
|
||||
TemplateData FsProductTemplateV2 `gorm:"foreignKey:id;references:template_id"` //获取模板信息
|
||||
// 资源详情
|
||||
type Resource struct {
|
||||
Metadata map[string]interface{} `json:"metadata"` // 资源额外
|
||||
ResourceID string `json:"resource_id"` // 资源ID
|
||||
ResourceType string `json:"resource_type"` // 资源类型
|
||||
ResourceURL string `json:"resource_url"` // 资源地址
|
||||
}
|
||||
|
||||
func (m *FsOrderModel) RowSelectBuilder(selectData []string) *gorm.DB {
|
||||
var rowBuilder = m.db.Table(m.name)
|
||||
|
||||
if selectData != nil {
|
||||
rowBuilder = rowBuilder.Select(selectData)
|
||||
} else {
|
||||
rowBuilder = rowBuilder.Select("*")
|
||||
}
|
||||
return rowBuilder
|
||||
// 购物车
|
||||
type ShoppingCartSnapshot struct {
|
||||
Ctime string `json:"ctime"` // 创建时间
|
||||
FittingID int64 `json:"fitting_id"` // 配件id
|
||||
ID int64 `json:"id"` // 购物车ID
|
||||
IsHighlyCustomized int64 `json:"is_highly_customized"` // 是否高度定制 0非 1是(针对客人高度定制只能后台增加如购物车)
|
||||
ModelID int64 `json:"model_id"` // 模型id
|
||||
ProductID int64 `json:"product_id"` // 产品id
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` // 购买数量
|
||||
SizeID int64 `json:"size_id"` // 尺寸id
|
||||
Snapshot Snapshot `json:"snapshot"` // 购物车快照数据
|
||||
TemplateID int64 `json:"template_id"` // 模板id
|
||||
UserID int64 `json:"user_id"` // 用户id
|
||||
Utime string `json:"utime"` // 更新时间
|
||||
}
|
||||
|
||||
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
|
||||
// 购物车快照
|
||||
type Snapshot struct {
|
||||
CombineImage string `json:"combine_image"` // 刀版图地址
|
||||
FittingInfo FittingInfo `json:"fitting_info"`
|
||||
Logo string `json:"logo"` // logo地址
|
||||
ModelInfo ModelInfo `json:"model_info"`
|
||||
RenderImage string `json:"render_image"` // 模板数据
|
||||
SizeInfo SizeInfo `json:"size_info"`
|
||||
TemplateInfo TemplateInfo `json:"template_info"`
|
||||
UserDiyInformation UserDiyInformation `json:"user_diy_information"`
|
||||
}
|
||||
|
||||
func (m *FsOrderModel) FindCount(ctx context.Context, countBuilder *gorm.DB, filterMap map[string]string) (int64, error) {
|
||||
var count int64
|
||||
|
||||
// 过滤
|
||||
if filterMap != nil {
|
||||
countBuilder = countBuilder.Scopes(handlers.FilterData(filterMap))
|
||||
}
|
||||
|
||||
result := countBuilder.WithContext(ctx).Limit(1).Count(&count)
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
} else {
|
||||
return count, nil
|
||||
}
|
||||
// 配件信息
|
||||
type FittingInfo struct {
|
||||
FittingJSON string `json:"fitting_json"`
|
||||
}
|
||||
|
||||
func (m *FsOrderModel) FindOneByQuery(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string) (*FsOrderRel, error) {
|
||||
var resp FsOrderRel
|
||||
|
||||
if filterMap != nil {
|
||||
rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap))
|
||||
}
|
||||
|
||||
result := rowBuilder.WithContext(ctx).Limit(1).Find(&resp)
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
} else {
|
||||
return &resp, nil
|
||||
}
|
||||
// 模型数据
|
||||
type ModelInfo struct {
|
||||
ModelJSON string `json:"model_json"`
|
||||
}
|
||||
|
||||
// 事务
|
||||
func (m *FsOrderModel) Trans(ctx context.Context, fn func(ctx context.Context, connGorm *gorm.DB) error) error {
|
||||
tx := m.db.Table(m.name).WithContext(ctx).Begin()
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
if err := tx.Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := fn(ctx, tx); err != nil {
|
||||
tx.Rollback()
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit().Error
|
||||
// 尺寸信息
|
||||
type SizeInfo struct {
|
||||
CM string `json:"cm"`
|
||||
Inch string `json:"inch"`
|
||||
}
|
||||
|
||||
func (m *FsOrderModel) TableName() string {
|
||||
return m.name
|
||||
// 模板数据
|
||||
type TemplateInfo struct {
|
||||
TemplateJSON string `json:"template_json"`
|
||||
TemplateTag string `json:"template_tag"`
|
||||
}
|
||||
|
||||
// DIY数据
|
||||
type UserDiyInformation struct {
|
||||
Address string `json:"address"` // 地址
|
||||
Phone string `json:"phone"` // 电话
|
||||
Qrcode string `json:"qrcode"` // 二维码
|
||||
Slogan string `json:"slogan"` // slogan
|
||||
Website string `json:"website"` // 网站
|
||||
}
|
||||
|
||||
192
model/gmodel/fs_order_logic_1.go
Executable file
192
model/gmodel/fs_order_logic_1.go
Executable file
@@ -0,0 +1,192 @@
|
||||
package gmodel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fusenapi/constants"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"fusenapi/utils/handlers"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (o *FsOrderModel) FindOneBySn(ctx context.Context, userId int64, sn string) (resp *FsOrder, err error) {
|
||||
err = o.db.WithContext(ctx).Model(&FsOrder{}).Where(" `user_id` = ? and `sn` = ? ", userId, sn).Take(&resp).Error
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (o *FsOrderModel) FindOne(ctx context.Context, userId int64, OrderId int64) (order *FsOrder, err error) {
|
||||
err = o.db.WithContext(ctx).Model(&FsOrder{}).Where("`user_id` = ? and `id` = ?", userId, OrderId).Take(&order).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func (o *FsOrderModel) FindOneAndCreateServiceContact(ctx context.Context, userId int64, OrderId int64, cs *FsContactService) (order *FsOrder, err error) {
|
||||
err = o.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
err = tx.Model(&FsOrder{}).Select("id").Limit(1).Where("`user_id` = ? and `id` = ?", userId, OrderId).Take(&order).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctime := time.Now().UTC().Unix()
|
||||
cs.Ctime = &ctime
|
||||
if constants.ConcactService(*cs.Type) == constants.TYPE_DEFAULT {
|
||||
*cs.RelationId = 0
|
||||
}
|
||||
|
||||
return tx.Model(&FsContactService{}).Create(cs).Error
|
||||
})
|
||||
return order, err
|
||||
}
|
||||
|
||||
// 获取用户最近下单成功的订单
|
||||
func (o *FsOrderModel) FindLastSuccessOneOrder(ctx context.Context, userId int64, statusGt int64) (order *FsOrder, err error) {
|
||||
err = o.db.WithContext(ctx).Model(&FsOrder{}).Where("`user_id` = ? and `status` > ?", userId, statusGt).Order("id DESC").Take(&order).Error
|
||||
return order, err
|
||||
}
|
||||
|
||||
// 分页查询的订单
|
||||
func (o *FsOrderModel) FindPageListByPage(ctx context.Context, rowBuilder *gorm.DB, page *int64, pageSize *int64, filterMap map[string]string, orderBy string) ([]*FsOrderRel, error) {
|
||||
var resp []*FsOrderRel
|
||||
// 过滤
|
||||
if filterMap != nil {
|
||||
rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap))
|
||||
}
|
||||
|
||||
// 排序
|
||||
if orderBy != "" {
|
||||
var fieldsMap = make(map[string]struct{})
|
||||
s := reflect.TypeOf(&FsOrder{}).Elem() //通过反射获取type定义
|
||||
for i := 0; i < s.NumField(); i++ {
|
||||
fieldsMap[s.Field(i).Tag.Get("json")] = struct{}{}
|
||||
}
|
||||
rowBuilder = rowBuilder.Scopes(handlers.OrderCheck(orderBy, fieldsMap))
|
||||
}
|
||||
|
||||
// 分页
|
||||
rowBuilder = rowBuilder.Scopes(handlers.Paginate(page, pageSize))
|
||||
|
||||
// 结果
|
||||
result := rowBuilder.Debug().WithContext(ctx).Find(&resp)
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
} else {
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
type FsOrderRel struct {
|
||||
FsOrder
|
||||
FsOrderDetails []FsOrderDetails `gorm:"foreignKey:order_id;references:id"`
|
||||
FsOrderAffiliateInfo FsOrderAffiliate `gorm:"foreignKey:order_id;references:id"`
|
||||
}
|
||||
|
||||
type FsOrderDetails struct {
|
||||
FsOrderDetail
|
||||
FsOrderDetailTemplateInfo FsOrderDetailTemplateInfo `gorm:"foreignKey:id;references:order_detail_template_id"`
|
||||
FsProductInfo FsProduct `gorm:"foreignKey:id;references:product_id"`
|
||||
}
|
||||
|
||||
type FsOrderDetailTemplateInfo struct {
|
||||
FsOrderDetailTemplate
|
||||
FsProductDesignInfo FsProductDesignInfo `gorm:"foreignKey:id;references:design_id"` //获取设计数据
|
||||
FsProductSizeInfo FsProductSize `gorm:"foreignKey:id;references:size_id"`
|
||||
}
|
||||
|
||||
type FsProductDesignInfo struct {
|
||||
FsProductDesign
|
||||
OptionData FsProduct `gorm:"foreignKey:id;references:optional_id"` //获取配件信息
|
||||
TemplateData FsProductTemplateV2 `gorm:"foreignKey:id;references:template_id"` //获取模板信息
|
||||
}
|
||||
|
||||
func (m *FsOrderModel) RowSelectBuilder(selectData []string) *gorm.DB {
|
||||
var rowBuilder = m.db.Table(m.name)
|
||||
|
||||
if selectData != nil {
|
||||
rowBuilder = rowBuilder.Select(selectData)
|
||||
} else {
|
||||
rowBuilder = rowBuilder.Select("*")
|
||||
}
|
||||
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
|
||||
|
||||
// 过滤
|
||||
if filterMap != nil {
|
||||
countBuilder = countBuilder.Scopes(handlers.FilterData(filterMap))
|
||||
}
|
||||
|
||||
result := countBuilder.WithContext(ctx).Limit(1).Count(&count)
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
} else {
|
||||
return count, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (m *FsOrderModel) FindOneByQuery(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string) (*FsOrderRel, error) {
|
||||
var resp FsOrderRel
|
||||
|
||||
if filterMap != nil {
|
||||
rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap))
|
||||
}
|
||||
|
||||
result := rowBuilder.WithContext(ctx).Limit(1).Find(&resp)
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
} else {
|
||||
return &resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 事务
|
||||
func (m *FsOrderModel) Trans(ctx context.Context, fn func(ctx context.Context, connGorm *gorm.DB) error) error {
|
||||
tx := m.db.Table(m.name).WithContext(ctx).Begin()
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
if err := tx.Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := fn(ctx, tx); err != nil {
|
||||
tx.Rollback()
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit().Error
|
||||
}
|
||||
|
||||
func (m *FsOrderModel) TableName() string {
|
||||
return m.name
|
||||
}
|
||||
35
model/gmodel/fs_orders_trade_gen.go
Normal file
35
model/gmodel/fs_orders_trade_gen.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package gmodel
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fs_orders_trade 订单交易记录表
|
||||
type FsOrdersTrade struct {
|
||||
Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单交易ID
|
||||
UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID
|
||||
OrderNo *string `gorm:"default:'';" json:"order_no"` //
|
||||
OrderSource *string `gorm:"default:'';" json:"order_source"` //
|
||||
TradeNo *string `gorm:"index;default:'';" json:"trade_no"` //
|
||||
PayAmount *int64 `gorm:"default:0;" json:"pay_amount"` // 支付金额 (分)
|
||||
PayStatus *int64 `gorm:"default:0;" json:"pay_status"` // 支付状态:1=未成功,2=已成功
|
||||
PaymentMethod *int64 `gorm:"default:0;" json:"payment_method"` // 支付方式:1=stripe,2=paypal
|
||||
PayStage *int64 `gorm:"default:0;" json:"pay_stage"` // 支付阶段:1=首付,2=尾款
|
||||
RefundStatus *int64 `gorm:"default:0;" json:"refund_status"` // 退款状态:1=未退款,2=已退款
|
||||
CardNo *string `gorm:"default:'';" json:"card_no"` //
|
||||
CardBrand *string `gorm:"default:'';" json:"card_brand"` //
|
||||
Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` //
|
||||
Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` //
|
||||
Country *string `gorm:"default:'';" json:"country"` //
|
||||
Currency *string `gorm:"default:'';" json:"currency"` //
|
||||
Metadata *[]byte `gorm:"default:'';" json:"metadata"` //
|
||||
}
|
||||
type FsOrdersTradeModel struct {
|
||||
db *gorm.DB
|
||||
name string
|
||||
}
|
||||
|
||||
func NewFsOrdersTradeModel(db *gorm.DB) *FsOrdersTradeModel {
|
||||
return &FsOrdersTradeModel{db: db, name: "fs_orders_trade"}
|
||||
}
|
||||
2
model/gmodel/fs_orders_trade_logic.go
Normal file
2
model/gmodel/fs_orders_trade_logic.go
Normal file
@@ -0,0 +1,2 @@
|
||||
package gmodel
|
||||
// TODO: 使用model的属性做你想做的
|
||||
@@ -18,12 +18,15 @@ func (p *FsProductModel) FindOneBySn(ctx context.Context, sn string, fields ...s
|
||||
err = db.Take(&resp).Error
|
||||
return resp, err
|
||||
}
|
||||
func (p *FsProductModel) GetProductListByIds(ctx context.Context, productIds []int64, sort string) (resp []FsProduct, err error) {
|
||||
func (p *FsProductModel) GetProductListByIds(ctx context.Context, productIds []int64, sort string, fields ...string) (resp []FsProduct, err error) {
|
||||
if len(productIds) == 0 {
|
||||
return
|
||||
}
|
||||
db := p.db.Model(&FsProduct{}).WithContext(ctx).
|
||||
Where("`id` in (?) and `is_del` =? and `is_shelf` = ? and `status` =?", productIds, 0, 1, 1)
|
||||
if len(fields) > 0 {
|
||||
db = db.Select(fields[0])
|
||||
}
|
||||
switch sort {
|
||||
case "sort-asc":
|
||||
db = db.Order("`sort` ASC")
|
||||
|
||||
@@ -23,11 +23,11 @@ func (p *FsProductPriceModel) GetSimplePriceListByProductIds(ctx context.Context
|
||||
}
|
||||
return
|
||||
}
|
||||
func (p *FsProductPriceModel) GetPriceListBySizeIds(ctx context.Context, sizeIds []int64) (resp []FsProductPrice, err error) {
|
||||
if len(sizeIds) == 0 {
|
||||
func (p *FsProductPriceModel) GetPriceListByProductIdsSizeIds(ctx context.Context, productIds, sizeIds []int64) (resp []FsProductPrice, err error) {
|
||||
if len(sizeIds) == 0 || len(productIds) == 0 {
|
||||
return
|
||||
}
|
||||
err = p.db.WithContext(ctx).Model(&FsProductPrice{}).Where("`size_id` in (?) and `status` = ? ", sizeIds, 1).Find(&resp).Error
|
||||
err = p.db.WithContext(ctx).Model(&FsProductPrice{}).Where("`size_id` in (?) and `product_id` in (?) and `status` = ? ", sizeIds, productIds, 1).Find(&resp).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -71,6 +71,11 @@ func (p *FsProductPriceModel) GetPriceListByProductIds(ctx context.Context, prod
|
||||
}
|
||||
return
|
||||
}
|
||||
func (p *FsProductPriceModel) FindOneBySizeId(ctx context.Context, sizeId int64) (resp *FsProductPrice, err error) {
|
||||
err = p.db.WithContext(ctx).Model(&FsProductPrice{}).
|
||||
Where("`size_id` = ? and `status` = ?", sizeId, 1).Take(&resp).Error
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// 产品价格
|
||||
type ProductPrice struct {
|
||||
|
||||
@@ -1,2 +1,102 @@
|
||||
package gmodel
|
||||
// TODO: 使用model的属性做你想做的
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type RelaFsShoppingCart struct {
|
||||
FsShoppingCart
|
||||
ShoppingCartProduct *FsProduct `json:"shopping_cart_product" gorm:"foreignkey:product_id;references:id"`
|
||||
ShoppingCartProductPriceList []*FsProductPrice `json:"shopping_cart_product_price_list" gorm:"foreignkey:product_id;references:product_id"`
|
||||
ShoppingCartProductModel3dList []*FsProductModel3d `json:"shopping_cart_product_model3d_list" gorm:"foreignkey:product_id;references:product_id"`
|
||||
}
|
||||
|
||||
// 获取单个
|
||||
func (s *FsShoppingCartModel) FindOne(ctx context.Context, id int64, fields ...string) (resp *FsShoppingCart, err error) {
|
||||
db := s.db.WithContext(ctx).Where("id = ?", id)
|
||||
if len(fields) > 0 {
|
||||
db = db.Select(fields[0])
|
||||
}
|
||||
err = db.Take(&resp).Error
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// 获取用户购物车指定item
|
||||
func (s *FsShoppingCartModel) FineOneUserCart(ctx context.Context, id, userId int64, fields ...string) (resp *FsShoppingCart, err error) {
|
||||
db := s.db.WithContext(ctx).Where("user_id = ? and id = ?", userId, id)
|
||||
if len(fields) > 0 {
|
||||
db = db.Select(fields[0])
|
||||
}
|
||||
err = db.Take(&resp).Error
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// 创建
|
||||
func (s *FsShoppingCartModel) Create(ctx context.Context, data *FsShoppingCart) error {
|
||||
return s.db.WithContext(ctx).Model(&FsShoppingCart{}).Create(&data).Error
|
||||
}
|
||||
|
||||
// 删除
|
||||
func (s *FsShoppingCartModel) Delete(ctx context.Context, id, userId int64) error {
|
||||
return s.db.WithContext(ctx).Model(&FsShoppingCart{}).Where("user_id = ? and id = ?", userId, id).Delete(&FsShoppingCart{}).Error
|
||||
}
|
||||
|
||||
// 更新
|
||||
func (s *FsShoppingCartModel) Update(ctx context.Context, id, userId int64, data *FsShoppingCart) error {
|
||||
return s.db.WithContext(ctx).Model(&FsShoppingCart{}).Where("user_id = ? and id = ?", userId, id).Updates(&data).Error
|
||||
}
|
||||
|
||||
// 获取用户购物车数量
|
||||
func (s *FsShoppingCartModel) CountUserCart(ctx context.Context, userId int64) (total int64, err error) {
|
||||
err = s.db.WithContext(ctx).Model(&FsShoppingCart{}).Where("user_id = ?", userId).Limit(1).Count(&total).Error
|
||||
return total, err
|
||||
}
|
||||
|
||||
// 获取多个
|
||||
func (s *FsShoppingCartModel) GetAllByIds(ctx context.Context, ids []int64, sort string, fields ...string) (resp []FsShoppingCart, err error) {
|
||||
if len(ids) == 0 {
|
||||
return
|
||||
}
|
||||
db := s.db.WithContext(ctx).Model(&FsShoppingCart{}).Where("id in (?)", ids)
|
||||
if len(fields) > 0 {
|
||||
db = db.Select(fields[0])
|
||||
}
|
||||
if sort != "" {
|
||||
db = db.Order(sort)
|
||||
}
|
||||
err = db.Find(&resp).Error
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// 获取用户所有的购物车
|
||||
type GetAllCartsByParamReq struct {
|
||||
Ids []int64 //id集合
|
||||
UserId int64 //用户id
|
||||
Fields string //筛选的字段
|
||||
Sort string //排序
|
||||
Page int //当前页
|
||||
Limit int //每页数量
|
||||
}
|
||||
|
||||
func (s *FsShoppingCartModel) GetAllCartsByParam(ctx context.Context, req GetAllCartsByParamReq) (resp []FsShoppingCart, total int64, err error) {
|
||||
db := s.db.WithContext(ctx).Model(&FsShoppingCart{})
|
||||
if req.UserId > 0 {
|
||||
db = db.Where("user_id = ?", req.UserId)
|
||||
}
|
||||
if len(req.Ids) > 0 {
|
||||
db = db.Where("id in (?)", req.Ids)
|
||||
}
|
||||
if req.Fields != "" {
|
||||
db = db.Select(req.Fields)
|
||||
}
|
||||
if req.Sort != "" {
|
||||
db = db.Order(req.Sort)
|
||||
}
|
||||
//查询数量
|
||||
if err = db.Limit(1).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
offset := (req.Page - 1) * req.Limit
|
||||
err = db.Offset(offset).Limit(req.Limit).Find(&resp).Error
|
||||
return resp, total, err
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ type AllModelsGen struct {
|
||||
CasbinRule *CasbinRuleModel // casbin_rule
|
||||
FsAddress *FsAddressModel // fs_address 用户地址表
|
||||
FsAdminApi *FsAdminApiModel // fs_admin_api 后台--接口表
|
||||
FsAdminAuthRole *FsAdminAuthRoleModel // fs_admin_auth_role 后台--角色表
|
||||
FsAdminDepartment *FsAdminDepartmentModel // fs_admin_department 后台--部门表
|
||||
FsAdminMenu *FsAdminMenuModel // fs_admin_menu 后台--菜单表
|
||||
FsAdminRole *FsAdminRoleModel // fs_admin_role 后台--角色表
|
||||
@@ -23,20 +22,15 @@ type AllModelsGen struct {
|
||||
FsCardGroup *FsCardGroupModel // fs_card_group 卡号分组表
|
||||
FsCart *FsCartModel // fs_cart 购物车
|
||||
FsChangeCode *FsChangeCodeModel // fs_change_code 忘记密码code表
|
||||
FsCloud *FsCloudModel // fs_cloud 云仓表
|
||||
FsCloudDeliverEveryTmpOld *FsCloudDeliverEveryTmpOldModel // fs_cloud_deliver_every_tmp_old
|
||||
FsCloudDeliverTmpOld *FsCloudDeliverTmpOldModel // fs_cloud_deliver_tmp_old
|
||||
FsCloudOld *FsCloudOldModel // fs_cloud_old 云仓表
|
||||
FsCloudPickUp *FsCloudPickUpModel // fs_cloud_pick_up 云仓提货单
|
||||
FsCloudPickUpDetail *FsCloudPickUpDetailModel // fs_cloud_pick_up_detail 云仓提货单-详情
|
||||
FsCloudPickUpDetailOld *FsCloudPickUpDetailOldModel // fs_cloud_pick_up_detail_old 云仓提货单-详情
|
||||
FsCloudPickUpOld *FsCloudPickUpOldModel // fs_cloud_pick_up_old 云仓提货单
|
||||
FsCloudReceive *FsCloudReceiveModel // fs_cloud_receive 云仓接收工厂总单
|
||||
FsCloudReceiveEveryOld *FsCloudReceiveEveryOldModel // fs_cloud_receive_every_old
|
||||
FsCloudReceiveOld *FsCloudReceiveOldModel // fs_cloud_receive_old 云仓接收工厂总单
|
||||
FsCloudRenderLog *FsCloudRenderLogModel // fs_cloud_render_log 云渲染日志表
|
||||
FsCloudRenderLogOld *FsCloudRenderLogOldModel // fs_cloud_render_log_old 云渲染日志表
|
||||
FsCloudUserApplyBack *FsCloudUserApplyBackModel // fs_cloud_user_apply_back 该表废弃
|
||||
FsCloudStorage *FsCloudStorageModel // fs_cloud_storage 仓库的基本信息, 只做映射
|
||||
FsCloudUserApplyBackOld *FsCloudUserApplyBackOldModel // fs_cloud_user_apply_back_old 该表废弃
|
||||
FsContact *FsContactModel // fs_contact 该表暂未使用
|
||||
FsContactService *FsContactServiceModel // fs_contact_service
|
||||
@@ -62,14 +56,10 @@ type AllModelsGen struct {
|
||||
FsMerchantCategory *FsMerchantCategoryModel // fs_merchant_category 商户类型表
|
||||
FsMigration *FsMigrationModel // fs_migration 版本库
|
||||
FsOrder *FsOrderModel // fs_order 订单表
|
||||
FsOrderAffiliate *FsOrderAffiliateModel // fs_order_affiliate 订单附属表-流程控制时间等
|
||||
FsOrderAffiliateOld *FsOrderAffiliateOldModel // fs_order_affiliate_old 订单附属表-流程控制时间等
|
||||
FsOrderDetail *FsOrderDetailModel // fs_order_detail 订单详细表
|
||||
FsOrderDetailOld *FsOrderDetailOldModel // fs_order_detail_old 订单详细表
|
||||
FsOrderDetailTemplate *FsOrderDetailTemplateModel // fs_order_detail_template 订单模板详细表
|
||||
FsOrderDetailTemplateOld *FsOrderDetailTemplateOldModel // fs_order_detail_template_old 订单模板详细表
|
||||
FsOrderOld *FsOrderOldModel // fs_order_old
|
||||
FsOrderRemark *FsOrderRemarkModel // fs_order_remark 订单备注表
|
||||
FsOrderRemarkOld *FsOrderRemarkOldModel // fs_order_remark_old 订单备注表
|
||||
FsOrderTrade *FsOrderTradeModel // fs_order_trade 订单交易表
|
||||
FsOrderTradeEvent *FsOrderTradeEventModel // fs_order_trade_event 订单交易事件表
|
||||
@@ -127,7 +117,6 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen {
|
||||
CasbinRule: NewCasbinRuleModel(gdb),
|
||||
FsAddress: NewFsAddressModel(gdb),
|
||||
FsAdminApi: NewFsAdminApiModel(gdb),
|
||||
FsAdminAuthRole: NewFsAdminAuthRoleModel(gdb),
|
||||
FsAdminDepartment: NewFsAdminDepartmentModel(gdb),
|
||||
FsAdminMenu: NewFsAdminMenuModel(gdb),
|
||||
FsAdminRole: NewFsAdminRoleModel(gdb),
|
||||
@@ -143,20 +132,15 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen {
|
||||
FsCardGroup: NewFsCardGroupModel(gdb),
|
||||
FsCart: NewFsCartModel(gdb),
|
||||
FsChangeCode: NewFsChangeCodeModel(gdb),
|
||||
FsCloud: NewFsCloudModel(gdb),
|
||||
FsCloudDeliverEveryTmpOld: NewFsCloudDeliverEveryTmpOldModel(gdb),
|
||||
FsCloudDeliverTmpOld: NewFsCloudDeliverTmpOldModel(gdb),
|
||||
FsCloudOld: NewFsCloudOldModel(gdb),
|
||||
FsCloudPickUp: NewFsCloudPickUpModel(gdb),
|
||||
FsCloudPickUpDetail: NewFsCloudPickUpDetailModel(gdb),
|
||||
FsCloudPickUpDetailOld: NewFsCloudPickUpDetailOldModel(gdb),
|
||||
FsCloudPickUpOld: NewFsCloudPickUpOldModel(gdb),
|
||||
FsCloudReceive: NewFsCloudReceiveModel(gdb),
|
||||
FsCloudReceiveEveryOld: NewFsCloudReceiveEveryOldModel(gdb),
|
||||
FsCloudReceiveOld: NewFsCloudReceiveOldModel(gdb),
|
||||
FsCloudRenderLog: NewFsCloudRenderLogModel(gdb),
|
||||
FsCloudRenderLogOld: NewFsCloudRenderLogOldModel(gdb),
|
||||
FsCloudUserApplyBack: NewFsCloudUserApplyBackModel(gdb),
|
||||
FsCloudStorage: NewFsCloudStorageModel(gdb),
|
||||
FsCloudUserApplyBackOld: NewFsCloudUserApplyBackOldModel(gdb),
|
||||
FsContact: NewFsContactModel(gdb),
|
||||
FsContactService: NewFsContactServiceModel(gdb),
|
||||
@@ -182,14 +166,10 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen {
|
||||
FsMerchantCategory: NewFsMerchantCategoryModel(gdb),
|
||||
FsMigration: NewFsMigrationModel(gdb),
|
||||
FsOrder: NewFsOrderModel(gdb),
|
||||
FsOrderAffiliate: NewFsOrderAffiliateModel(gdb),
|
||||
FsOrderAffiliateOld: NewFsOrderAffiliateOldModel(gdb),
|
||||
FsOrderDetail: NewFsOrderDetailModel(gdb),
|
||||
FsOrderDetailOld: NewFsOrderDetailOldModel(gdb),
|
||||
FsOrderDetailTemplate: NewFsOrderDetailTemplateModel(gdb),
|
||||
FsOrderDetailTemplateOld: NewFsOrderDetailTemplateOldModel(gdb),
|
||||
FsOrderOld: NewFsOrderOldModel(gdb),
|
||||
FsOrderRemark: NewFsOrderRemarkModel(gdb),
|
||||
FsOrderRemarkOld: NewFsOrderRemarkOldModel(gdb),
|
||||
FsOrderTrade: NewFsOrderTradeModel(gdb),
|
||||
FsOrderTradeEvent: NewFsOrderTradeEventModel(gdb),
|
||||
|
||||
@@ -31,7 +31,7 @@ func NewGetCanteenDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *
|
||||
// 获取餐厅详情
|
||||
func (l *GetCanteenDetailLogic) GetCanteenDetail(req *types.GetCanteenDetailReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first")
|
||||
}
|
||||
//获取餐厅类型数据
|
||||
canteenTypeModel := gmodel.NewFsCanteenTypeModel(l.svcCtx.MysqlConn)
|
||||
|
||||
@@ -32,7 +32,7 @@ func NewSaveCanteenTypeProductLogic(ctx context.Context, svcCtx *svc.ServiceCont
|
||||
// 保存餐厅类型的关联产品
|
||||
func (l *SaveCanteenTypeProductLogic) SaveCanteenTypeProduct(req *types.SaveCanteenTypeProductReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first")
|
||||
}
|
||||
if len(req.ProductList) == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "product list can`t be empty")
|
||||
|
||||
@@ -29,7 +29,7 @@ func NewGetQrCodeSetListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *
|
||||
// 获取二维码配置列表
|
||||
func (l *GetQrCodeSetListLogic) GetQrCodeSetList(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first")
|
||||
}
|
||||
qrCodeModel := gmodel.NewFsQrcodeSetModel(l.svcCtx.MysqlConn)
|
||||
qrCodeList, err := qrCodeModel.GetAll(l.ctx)
|
||||
|
||||
@@ -29,7 +29,7 @@ func NewGetStandardLogoListLogic(ctx context.Context, svcCtx *svc2.ServiceContex
|
||||
// 获取标准logo列表
|
||||
func (l *GetStandardLogoListLogic) GetStandardLogoList(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first")
|
||||
}
|
||||
standardLogoModel := gmodel.NewFsStandardLogoModel(l.svcCtx.MysqlConn)
|
||||
logoList, err := standardLogoModel.GetAll(l.ctx)
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/collect"
|
||||
|
||||
"context"
|
||||
|
||||
@@ -12,7 +10,6 @@ import (
|
||||
"fusenapi/server/home-user-auth/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserContactServiceLogic struct {
|
||||
@@ -33,36 +30,36 @@ func (l *UserContactServiceLogic) UserContactService(req *types.RequestContactSe
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
|
||||
if !userinfo.IsUser() {
|
||||
return resp.SetStatus(basic.CodeUnAuth)
|
||||
}
|
||||
// if !userinfo.IsUser() {
|
||||
// return resp.SetStatus(basic.CodeUnAuth)
|
||||
// }
|
||||
|
||||
cs := gmodel.FsContactService{
|
||||
UserId: &userinfo.UserId,
|
||||
}
|
||||
collect.LoadJsonTag(&cs, &req)
|
||||
// cs := gmodel.FsContactService{
|
||||
// UserId: &userinfo.UserId,
|
||||
// }
|
||||
// collect.LoadJsonTag(&cs, &req)
|
||||
|
||||
switch req.Type {
|
||||
case "order":
|
||||
_, err := l.svcCtx.AllModels.FsOrder.FindOneAndCreateServiceContact(l.ctx, userinfo.UserId, req.RelationID, &cs)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return resp.SetStatus(basic.CodeOrderNotFoundErr)
|
||||
}
|
||||
return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
}
|
||||
case "cloud":
|
||||
_, err := l.svcCtx.AllModels.FsCloudPickUp.GetCloudPickUpByIDAndUserID(l.ctx, userinfo.UserId, req.RelationID, &cs)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return resp.SetStatus(basic.CodeCloudOrderNotFoundErr)
|
||||
}
|
||||
return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
}
|
||||
return
|
||||
default:
|
||||
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "type is unknown")
|
||||
}
|
||||
// switch req.Type {
|
||||
// case "order":
|
||||
// _, err := l.svcCtx.AllModels.FsOrder.FindOneAndCreateServiceContact(l.ctx, userinfo.UserId, req.RelationID, &cs)
|
||||
// if err != nil {
|
||||
// if err == gorm.ErrRecordNotFound {
|
||||
// return resp.SetStatus(basic.CodeOrderNotFoundErr)
|
||||
// }
|
||||
// return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
// }
|
||||
// case "cloud":
|
||||
// _, err := l.svcCtx.AllModels.FsCloudPickUp.GetCloudPickUpByIDAndUserID(l.ctx, userinfo.UserId, req.RelationID, &cs)
|
||||
// if err != nil {
|
||||
// if err == gorm.ErrRecordNotFound {
|
||||
// return resp.SetStatus(basic.CodeCloudOrderNotFoundErr)
|
||||
// }
|
||||
// return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
// }
|
||||
// return
|
||||
// default:
|
||||
// return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "type is unknown")
|
||||
// }
|
||||
|
||||
return resp.SetStatus(basic.CodeOK, cs)
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
|
||||
@@ -1,23 +1,15 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
"fusenapi/server/home-user-auth/internal/svc"
|
||||
"fusenapi/server/home-user-auth/internal/types"
|
||||
|
||||
"github.com/stripe/stripe-go/v74"
|
||||
"github.com/stripe/stripe-go/v74/client"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserOderDeleteLogic struct {
|
||||
@@ -38,109 +30,109 @@ func (l *UserOderDeleteLogic) UserOderDelete(req *types.RequestOrderId, userinfo
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
|
||||
if !userinfo.IsUser() {
|
||||
return resp.SetStatus(basic.CodeUnAuth) // 如果不是用户信息, 返回未授权错误
|
||||
}
|
||||
// if !userinfo.IsUser() {
|
||||
// return resp.SetStatus(basic.CodeUnAuth) // 如果不是用户信息, 返回未授权错误
|
||||
// }
|
||||
|
||||
//订单id
|
||||
orderId := req.OrderId
|
||||
if orderId < 1 {
|
||||
return resp.SetStatus(basic.CodeRequestParamsErr)
|
||||
}
|
||||
// //订单id
|
||||
// orderId := req.OrderId
|
||||
// if orderId < 1 {
|
||||
// return resp.SetStatus(basic.CodeRequestParamsErr)
|
||||
// }
|
||||
|
||||
m := l.svcCtx.AllModels.FsOrder
|
||||
order, err := m.FindOne(l.ctx, userinfo.UserId, orderId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatus(basic.CodeOrderNotFoundErr)
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
}
|
||||
// m := l.svcCtx.AllModels.FsOrder
|
||||
// order, err := m.FindOne(l.ctx, userinfo.UserId, orderId)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatus(basic.CodeOrderNotFoundErr)
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
// }
|
||||
|
||||
if auth.CheckValueRange[constants.Order](
|
||||
constants.Order(*order.Status),
|
||||
constants.STATUS_NEW_NOT_PAY,
|
||||
constants.STATUS_NEW_PAY_COMPLETED,
|
||||
constants.STATUS_NEW_PART_PAY,
|
||||
) {
|
||||
return resp.SetStatus(basic.CodeOrderNotCancelledErr)
|
||||
}
|
||||
// if auth.CheckValueRange[constants.Order](
|
||||
// constants.Order(*order.Status),
|
||||
// constants.STATUS_NEW_NOT_PAY,
|
||||
// constants.STATUS_NEW_PAY_COMPLETED,
|
||||
// constants.STATUS_NEW_PART_PAY,
|
||||
// ) {
|
||||
// return resp.SetStatus(basic.CodeOrderNotCancelledErr)
|
||||
// }
|
||||
|
||||
if *order.IsPayCompleted == 1 &&
|
||||
time.Now().After(time.Unix(*order.Ctime, 0).Add(48*time.Hour)) {
|
||||
return resp.SetStatus(basic.CodeOrderNotCancelledErr)
|
||||
}
|
||||
// if *order.IsPayCompleted == 1 &&
|
||||
// time.Now().After(time.Unix(*order.Ctime, 0).Add(48*time.Hour)) {
|
||||
// return resp.SetStatus(basic.CodeOrderNotCancelledErr)
|
||||
// }
|
||||
|
||||
uOrder := &gmodel.FsOrder{
|
||||
Id: orderId,
|
||||
}
|
||||
// uOrder := &gmodel.FsOrder{
|
||||
// Id: orderId,
|
||||
// }
|
||||
|
||||
var (
|
||||
isCancel int64 = 1
|
||||
ustatus int64 = int64(constants.STATUS_NEW_CANCEL)
|
||||
)
|
||||
// 修改取消状态和取消原因
|
||||
uOrder.Status = &ustatus
|
||||
uOrder.IsCancel = &isCancel
|
||||
uOrder.RefundReasonId = &req.RefundReasonId
|
||||
uOrder.RefundReason = &req.RefundReason
|
||||
// var (
|
||||
// isCancel int64 = 1
|
||||
// ustatus int64 = int64(constants.STATUS_NEW_CANCEL)
|
||||
// )
|
||||
// // 修改取消状态和取消原因
|
||||
// uOrder.Status = &ustatus
|
||||
// uOrder.IsCancel = &isCancel
|
||||
// uOrder.RefundReasonId = &req.RefundReasonId
|
||||
// uOrder.RefundReason = &req.RefundReason
|
||||
|
||||
err = m.Update(l.ctx, uOrder)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatus(basic.CodeDbUpdateErr)
|
||||
}
|
||||
// err = m.Update(l.ctx, uOrder)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatus(basic.CodeDbUpdateErr)
|
||||
// }
|
||||
|
||||
var (
|
||||
IsRefund int64 = 0
|
||||
CreatedAt = time.Now().UTC().Unix()
|
||||
)
|
||||
// var (
|
||||
// IsRefund int64 = 0
|
||||
// CreatedAt = time.Now().UTC().Unix()
|
||||
// )
|
||||
|
||||
refund := &gmodel.FsRefundReason{
|
||||
IsRefund: &IsRefund,
|
||||
RefundReasonId: &req.RefundReasonId,
|
||||
RefundReason: &req.RefundReason,
|
||||
OrderId: &order.Id,
|
||||
CreatedAt: &CreatedAt,
|
||||
}
|
||||
// refund := &gmodel.FsRefundReason{
|
||||
// IsRefund: &IsRefund,
|
||||
// RefundReasonId: &req.RefundReasonId,
|
||||
// RefundReason: &req.RefundReason,
|
||||
// OrderId: &order.Id,
|
||||
// CreatedAt: &CreatedAt,
|
||||
// }
|
||||
|
||||
mFsRefundReason := gmodel.NewFsRefundReasonModel(l.svcCtx.MysqlConn)
|
||||
err = mFsRefundReason.Create(l.ctx, refund)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
}
|
||||
// mFsRefundReason := gmodel.NewFsRefundReasonModel(l.svcCtx.MysqlConn)
|
||||
// err = mFsRefundReason.Create(l.ctx, refund)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
// }
|
||||
|
||||
// 退款
|
||||
// 调用第三方接口发起退款
|
||||
// // 退款
|
||||
// // 调用第三方接口发起退款
|
||||
|
||||
config := &stripe.BackendConfig{
|
||||
MaxNetworkRetries: stripe.Int64(0), // Zero retries
|
||||
}
|
||||
// config := &stripe.BackendConfig{
|
||||
// MaxNetworkRetries: stripe.Int64(0), // Zero retries
|
||||
// }
|
||||
|
||||
sc := &client.API{}
|
||||
sc.Init(l.svcCtx.Config.Stripe.SK, &stripe.Backends{
|
||||
API: stripe.GetBackendWithConfig(stripe.APIBackend, config),
|
||||
Uploads: stripe.GetBackendWithConfig(stripe.UploadsBackend, config),
|
||||
})
|
||||
// ['order_number' => $order->sn, 'is_refund' => 0, 'pay_status' => 1]
|
||||
payM := l.svcCtx.AllModels.FsPay
|
||||
// sc := &client.API{}
|
||||
// sc.Init(l.svcCtx.Config.Stripe.SK, &stripe.Backends{
|
||||
// API: stripe.GetBackendWithConfig(stripe.APIBackend, config),
|
||||
// Uploads: stripe.GetBackendWithConfig(stripe.UploadsBackend, config),
|
||||
// })
|
||||
// // ['order_number' => $order->sn, 'is_refund' => 0, 'pay_status' => 1]
|
||||
// payM := l.svcCtx.AllModels.FsPay
|
||||
|
||||
// 查询支付信息
|
||||
pays, err := payM.GetOrderPayList(l.ctx, *order.Sn, 1, 0)
|
||||
for _, pay := range pays {
|
||||
sc.Refunds.New(&stripe.RefundParams{
|
||||
PaymentIntent: pay.TradeNo,
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatus(basic.CodeApiErr)
|
||||
}
|
||||
}
|
||||
// // 查询支付信息
|
||||
// pays, err := payM.GetOrderPayList(l.ctx, *order.Sn, 1, 0)
|
||||
// for _, pay := range pays {
|
||||
// sc.Refunds.New(&stripe.RefundParams{
|
||||
// PaymentIntent: pay.TradeNo,
|
||||
// })
|
||||
// }
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatus(basic.CodeApiErr)
|
||||
// }
|
||||
// }
|
||||
|
||||
return resp.SetStatus(basic.CodePayCancelOk, uOrder)
|
||||
return resp.SetStatus(basic.CodePayCancelOk)
|
||||
|
||||
// return ResponseError(500, "Cancellation failure")
|
||||
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/handlers"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
@@ -15,7 +10,6 @@ import (
|
||||
"fusenapi/server/home-user-auth/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserOrderCancelLogic struct {
|
||||
@@ -36,93 +30,93 @@ func (l *UserOrderCancelLogic) UserOrderCancel(req *types.UserOrderCancelReq, us
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
|
||||
if userinfo == nil || userinfo.UserId == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
// if userinfo == nil || userinfo.UserId == 0 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
|
||||
//查询订单信息
|
||||
orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the order is not exists")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatus(basic.CodeServiceErr, "failed to get order info")
|
||||
}
|
||||
// //查询订单信息
|
||||
// orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
// orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the order is not exists")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatus(basic.CodeServiceErr, "failed to get order info")
|
||||
// }
|
||||
|
||||
// 判断订单状态
|
||||
var notCancelStatusMap = make(map[int64]struct{}, 3)
|
||||
notCancelStatusMap[int64(constants.STATUS_NEW_NOT_PAY)] = struct{}{}
|
||||
notCancelStatusMap[int64(constants.STATUS_NEW_PART_PAY)] = struct{}{}
|
||||
notCancelStatusMap[int64(constants.STATUS_NEW_PAY_COMPLETED)] = struct{}{}
|
||||
_, ok := notCancelStatusMap[int64(*orderInfo.Status)]
|
||||
if !ok {
|
||||
return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "the order status not cancle")
|
||||
}
|
||||
// // 判断订单状态
|
||||
// var notCancelStatusMap = make(map[int64]struct{}, 3)
|
||||
// notCancelStatusMap[int64(constants.STATUS_NEW_NOT_PAY)] = struct{}{}
|
||||
// notCancelStatusMap[int64(constants.STATUS_NEW_PART_PAY)] = struct{}{}
|
||||
// notCancelStatusMap[int64(constants.STATUS_NEW_PAY_COMPLETED)] = struct{}{}
|
||||
// _, ok := notCancelStatusMap[int64(*orderInfo.Status)]
|
||||
// if !ok {
|
||||
// return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "the order status not cancle")
|
||||
// }
|
||||
|
||||
var cancelTime int64 = time.Now().UTC().Unix() - (*orderInfo.Ctime + int64(constants.CANCLE_ORDER_EXPIRE))
|
||||
// 第一次支付成功后48小时后不能进行取消操作
|
||||
if *orderInfo.IsPayCompleted == 1 && cancelTime > 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "The current order cannot be cancelled")
|
||||
}
|
||||
// var cancelTime int64 = time.Now().UTC().Unix() - (*orderInfo.Ctime + int64(constants.CANCLE_ORDER_EXPIRE))
|
||||
// // 第一次支付成功后48小时后不能进行取消操作
|
||||
// if *orderInfo.IsPayCompleted == 1 && cancelTime > 0 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "The current order cannot be cancelled")
|
||||
// }
|
||||
|
||||
// 修改订单--取消状态和取消原因
|
||||
*orderInfo.Status = int64(constants.STATUS_NEW_CANCEL)
|
||||
*orderInfo.IsCancel = 1
|
||||
orderInfo.RefundReasonId = &req.RefundReasonId
|
||||
orderInfo.RefundReason = &req.RefundReason
|
||||
// // 修改订单--取消状态和取消原因
|
||||
// *orderInfo.Status = int64(constants.STATUS_NEW_CANCEL)
|
||||
// *orderInfo.IsCancel = 1
|
||||
// orderInfo.RefundReasonId = &req.RefundReasonId
|
||||
// orderInfo.RefundReason = &req.RefundReason
|
||||
|
||||
var nowTime = time.Now().UTC().Unix()
|
||||
var payList []handlers.PayInfo
|
||||
// 事务处理
|
||||
ctx := l.ctx
|
||||
err = l.svcCtx.MysqlConn.Transaction(func(tx *gorm.DB) error {
|
||||
// 修改订单信息
|
||||
orderModelTS := gmodel.NewFsOrderModel(tx)
|
||||
err = orderModelTS.RBUpdate(ctx, orderInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 新增退款记录
|
||||
var isRefund int64 = 0
|
||||
refundReasonModelTS := gmodel.NewFsRefundReasonModel(tx)
|
||||
refundReasonModelTS.RBCreateOrUpdate(ctx, &gmodel.FsRefundReason{
|
||||
IsRefund: &isRefund,
|
||||
RefundReasonId: &req.RefundReasonId,
|
||||
RefundReason: &req.RefundReason,
|
||||
OrderId: &orderInfo.Id,
|
||||
CreatedAt: &nowTime,
|
||||
})
|
||||
// 退款申请
|
||||
// 退款申请--查询支付信息
|
||||
fsPayModelTS := gmodel.NewFsPayModel(tx)
|
||||
rbFsPay := fsPayModelTS.RowSelectBuilder(nil).Where("order_number = ?", orderInfo.Sn).Where("pay_status =?", constants.PAYSTATUS_SUCCESS).Where("is_refund =?", 0)
|
||||
payInfoList, err := fsPayModelTS.FindAll(ctx, rbFsPay, nil, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, payInfo := range payInfoList {
|
||||
var key string
|
||||
if *payInfo.PaymentMethod == int64(constants.PAYMETHOD_STRIPE) {
|
||||
key = l.svcCtx.Config.PayConfig.Stripe.Key
|
||||
}
|
||||
payList = append(payList, handlers.PayInfo{
|
||||
TradeNo: *payInfo.TradeNo,
|
||||
PaymentMethod: *payInfo.PaymentMethod,
|
||||
Key: key,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// 退款申请--调取第三方接口发起退款
|
||||
handlers.PayRefundHandler(&handlers.PayRefundHandlerReq{
|
||||
PayInfoList: payList,
|
||||
})
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeOrderCancelledNotOk, "the order cancle failed")
|
||||
}
|
||||
// var nowTime = time.Now().UTC().Unix()
|
||||
// var payList []handlers.PayInfo
|
||||
// // 事务处理
|
||||
// ctx := l.ctx
|
||||
// err = l.svcCtx.MysqlConn.Transaction(func(tx *gorm.DB) error {
|
||||
// // 修改订单信息
|
||||
// orderModelTS := gmodel.NewFsOrderModel(tx)
|
||||
// err = orderModelTS.RBUpdate(ctx, orderInfo)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// // 新增退款记录
|
||||
// var isRefund int64 = 0
|
||||
// refundReasonModelTS := gmodel.NewFsRefundReasonModel(tx)
|
||||
// refundReasonModelTS.RBCreateOrUpdate(ctx, &gmodel.FsRefundReason{
|
||||
// IsRefund: &isRefund,
|
||||
// RefundReasonId: &req.RefundReasonId,
|
||||
// RefundReason: &req.RefundReason,
|
||||
// OrderId: &orderInfo.Id,
|
||||
// CreatedAt: &nowTime,
|
||||
// })
|
||||
// // 退款申请
|
||||
// // 退款申请--查询支付信息
|
||||
// fsPayModelTS := gmodel.NewFsPayModel(tx)
|
||||
// rbFsPay := fsPayModelTS.RowSelectBuilder(nil).Where("order_number = ?", orderInfo.Sn).Where("pay_status =?", constants.PAYSTATUS_SUCCESS).Where("is_refund =?", 0)
|
||||
// payInfoList, err := fsPayModelTS.FindAll(ctx, rbFsPay, nil, "")
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// for _, payInfo := range payInfoList {
|
||||
// var key string
|
||||
// if *payInfo.PaymentMethod == int64(constants.PAYMETHOD_STRIPE) {
|
||||
// key = l.svcCtx.Config.PayConfig.Stripe.Key
|
||||
// }
|
||||
// payList = append(payList, handlers.PayInfo{
|
||||
// TradeNo: *payInfo.TradeNo,
|
||||
// PaymentMethod: *payInfo.PaymentMethod,
|
||||
// Key: key,
|
||||
// })
|
||||
// }
|
||||
// return nil
|
||||
// })
|
||||
// // 退款申请--调取第三方接口发起退款
|
||||
// handlers.PayRefundHandler(&handlers.PayRefundHandlerReq{
|
||||
// PayInfoList: payList,
|
||||
// })
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeOrderCancelledNotOk, "the order cancle failed")
|
||||
// }
|
||||
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
@@ -13,7 +10,6 @@ import (
|
||||
"fusenapi/server/home-user-auth/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserOrderDeleteLogic struct {
|
||||
@@ -43,36 +39,36 @@ func (l *UserOrderDeleteLogic) UserOrderDelete(req *types.UserOrderDeleteReq, us
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
|
||||
if userinfo == nil || userinfo.UserId == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
// if userinfo == nil || userinfo.UserId == 0 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
|
||||
orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID)
|
||||
// orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
// orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
|
||||
}
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
|
||||
// }
|
||||
|
||||
updateStatusMap := make(map[constants.Order]struct{}, 4)
|
||||
updateStatusMap[constants.STATUS_NEW_COMPLETED] = struct{}{}
|
||||
updateStatusMap[constants.STATUS_NEW_CANCEL] = struct{}{}
|
||||
updateStatusMap[constants.STATUS_NEW_REFUNDED] = struct{}{}
|
||||
updateStatusMap[constants.STATUS_NEW_CLOSE] = struct{}{}
|
||||
if _, ok := updateStatusMap[constants.Order(*orderInfo.Status)]; !ok {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
*orderInfo.Status = int64(constants.STATUS_NEW_DELETE)
|
||||
*orderInfo.IsDeleted = 1
|
||||
err = orderModel.Update(l.ctx, orderInfo)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "fail to delete")
|
||||
}
|
||||
// updateStatusMap := make(map[constants.Order]struct{}, 4)
|
||||
// updateStatusMap[constants.STATUS_NEW_COMPLETED] = struct{}{}
|
||||
// updateStatusMap[constants.STATUS_NEW_CANCEL] = struct{}{}
|
||||
// updateStatusMap[constants.STATUS_NEW_REFUNDED] = struct{}{}
|
||||
// updateStatusMap[constants.STATUS_NEW_CLOSE] = struct{}{}
|
||||
// if _, ok := updateStatusMap[constants.Order(*orderInfo.Status)]; !ok {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
// *orderInfo.Status = int64(constants.STATUS_NEW_DELETE)
|
||||
// *orderInfo.IsDeleted = 1
|
||||
// err = orderModel.Update(l.ctx, orderInfo)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "fail to delete")
|
||||
// }
|
||||
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
|
||||
@@ -1,20 +1,8 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/configs"
|
||||
"fusenapi/utils/image"
|
||||
"strings"
|
||||
|
||||
"fusenapi/utils/format"
|
||||
"fusenapi/utils/order"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
@@ -22,7 +10,6 @@ import (
|
||||
"fusenapi/server/home-user-auth/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserOrderListLogic struct {
|
||||
@@ -43,263 +30,264 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
|
||||
size := req.Size
|
||||
// size := req.Size
|
||||
|
||||
if size > 0 {
|
||||
size = int64(image.GetCurrentSize(uint32(size)))
|
||||
}
|
||||
// if size > 0 {
|
||||
// size = int64(image.GetCurrentSize(uint32(size)))
|
||||
// }
|
||||
|
||||
orderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn)
|
||||
orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn)
|
||||
fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn)
|
||||
orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
rowBuilder := orderModel.RowSelectBuilder(nil)
|
||||
if userinfo == nil || userinfo.UserId == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
// orderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn)
|
||||
// orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn)
|
||||
// fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn)
|
||||
// orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
// rowBuilder := orderModel.RowSelectBuilder(nil)
|
||||
// if userinfo == nil || userinfo.UserId == 0 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
|
||||
// 查询条件
|
||||
var page = req.Page
|
||||
var pageSize = req.PageSize
|
||||
var listRes []*gmodel.FsOrderRel
|
||||
rowBuilder = rowBuilder.Where("user_id =?", userinfo.UserId).Where("status <> ?", constants.STATUS_NEW_NOT_PAY).Where("status <>?", constants.STATUS_NEW_DELETE)
|
||||
// // 查询条件
|
||||
// var page = req.Page
|
||||
// var pageSize = req.PageSize
|
||||
// var listRes []*gmodel.FsOrderRel
|
||||
// rowBuilder = rowBuilder.Where("user_id =?", userinfo.UserId).Where("status <> ?", constants.STATUS_NEW_NOT_PAY).Where("status <>?", constants.STATUS_NEW_DELETE)
|
||||
|
||||
// 根据时间来查询不同范围的订单
|
||||
switch req.Time {
|
||||
case 1:
|
||||
rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -1, 0).Unix())
|
||||
case 2:
|
||||
rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -3, 0).Unix())
|
||||
case 3:
|
||||
rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -6, 0).Unix())
|
||||
case 4:
|
||||
rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(-1, 0, 0).Unix())
|
||||
default:
|
||||
}
|
||||
// // 根据时间来查询不同范围的订单
|
||||
// switch req.Time {
|
||||
// case 1:
|
||||
// rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -1, 0).Unix())
|
||||
// case 2:
|
||||
// rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -3, 0).Unix())
|
||||
// case 3:
|
||||
// rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -6, 0).Unix())
|
||||
// case 4:
|
||||
// rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(-1, 0, 0).Unix())
|
||||
// default:
|
||||
// }
|
||||
|
||||
//按照订单状态查询不同的订单
|
||||
if req.Status != -1 {
|
||||
switch req.Status {
|
||||
case 1:
|
||||
rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_PART_PAY, constants.STATUS_NEW_PAY_COMPLETED, constants.STATUS_NEW_SURE})
|
||||
case 2:
|
||||
rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_PRODUTING, constants.STATUS_NEW_PRODUT_COMPLETED})
|
||||
case 3:
|
||||
rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_DELIVER, constants.STATUS_NEW_UPS})
|
||||
case 4:
|
||||
rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_ARRIVAL)
|
||||
case 5:
|
||||
rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_ADDRESS)
|
||||
case 7:
|
||||
rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_CANCEL, constants.STATUS_NEW_REFUNDED, constants.STATUS_NEW_REFUNDING})
|
||||
case 8:
|
||||
rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_CLOUD)
|
||||
}
|
||||
}
|
||||
// //按照订单状态查询不同的订单
|
||||
// if req.Status != -1 {
|
||||
// switch req.Status {
|
||||
// case 1:
|
||||
// rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_PART_PAY, constants.STATUS_NEW_PAY_COMPLETED, constants.STATUS_NEW_SURE})
|
||||
// case 2:
|
||||
// rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_PRODUTING, constants.STATUS_NEW_PRODUT_COMPLETED})
|
||||
// case 3:
|
||||
// rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_DELIVER, constants.STATUS_NEW_UPS})
|
||||
// case 4:
|
||||
// rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_ARRIVAL)
|
||||
// case 5:
|
||||
// rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_ADDRESS)
|
||||
// case 7:
|
||||
// rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_CANCEL, constants.STATUS_NEW_REFUNDED, constants.STATUS_NEW_REFUNDING})
|
||||
// case 8:
|
||||
// rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_CLOUD)
|
||||
// }
|
||||
// }
|
||||
|
||||
// 查询总数
|
||||
total, err := orderModel.FindCount(l.ctx, rowBuilder, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
|
||||
}
|
||||
// // 查询总数
|
||||
// total, err := orderModel.FindCount(l.ctx, rowBuilder, nil)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
|
||||
// }
|
||||
|
||||
// 查询数据
|
||||
if total > 0 {
|
||||
rowBuilder = rowBuilder.Preload("FsOrderAffiliateInfo").Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
return dbPreload.Table(orderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
return dbPreload.Table(fsProductDesignModel.TableName()).Preload("OptionData").Preload("TemplateData")
|
||||
}).Preload("FsProductSizeInfo")
|
||||
}).Preload("FsProductInfo")
|
||||
})
|
||||
listRes, err = orderModel.FindPageListByPage(l.ctx, rowBuilder, &page, &pageSize, nil, "")
|
||||
}
|
||||
// // 查询数据
|
||||
// if total > 0 {
|
||||
// rowBuilder = rowBuilder.Preload("FsOrderAffiliateInfo").Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
// return dbPreload.Table(orderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
// return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
// return dbPreload.Table(fsProductDesignModel.TableName()).Preload("OptionData").Preload("TemplateData")
|
||||
// }).Preload("FsProductSizeInfo")
|
||||
// }).Preload("FsProductInfo")
|
||||
// })
|
||||
// listRes, err = orderModel.FindPageListByPage(l.ctx, rowBuilder, &page, &pageSize, nil, "")
|
||||
// }
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
|
||||
}
|
||||
listResLen := len(listRes)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
|
||||
// }
|
||||
// listResLen := len(listRes)
|
||||
|
||||
var respList []types.Items
|
||||
if listResLen > 0 {
|
||||
// 获取订单时间配置
|
||||
orderTimeConfig, err := configs.GetOrderTimeConfig(l.ctx, l.svcCtx.MysqlConn)
|
||||
if err != nil {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get config time info")
|
||||
}
|
||||
// var respList []types.Items
|
||||
// if listResLen > 0 {
|
||||
// // 获取订单时间配置
|
||||
// orderTimeConfig, err := configs.GetOrderTimeConfig(l.ctx, l.svcCtx.MysqlConn)
|
||||
// if err != nil {
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get config time info")
|
||||
// }
|
||||
|
||||
// 数据处理
|
||||
for _, item := range listRes {
|
||||
var pbData types.Items
|
||||
pbData.ID = item.Id
|
||||
pbData.Sn = *item.Sn
|
||||
pbData.UserID = *item.UserId
|
||||
pbData.TotalAmount = *item.TotalAmount
|
||||
pbData.Ctime = format.TimeIntToFormat(*item.Ctime)
|
||||
pbData.Status = *item.Status
|
||||
pbData.DeliveryMethod = *item.DeliveryMethod
|
||||
pbData.TsTime = format.TimeToFormat(*item.TsTime)
|
||||
pbData.IsPayCompleted = *item.IsPayCompleted
|
||||
pbData.DeliverSn = *item.DeliverSn
|
||||
// // 数据处理
|
||||
// for _, item := range listRes {
|
||||
// var pbData types.Items
|
||||
// pbData.ID = item.Id
|
||||
// pbData.Sn = *item.Sn
|
||||
// pbData.UserID = *item.UserId
|
||||
// pbData.TotalAmount = *item.TotalAmount
|
||||
// pbData.Ctime = format.TimeIntToFormat(*item.Ctime)
|
||||
// pbData.Status = *item.Status
|
||||
// pbData.DeliveryMethod = *item.DeliveryMethod
|
||||
// pbData.TsTime = format.TimeToFormat(*item.TsTime)
|
||||
// pbData.IsPayCompleted = *item.IsPayCompleted
|
||||
// pbData.DeliverSn = *item.DeliverSn
|
||||
|
||||
var pcsBox int64
|
||||
var pcs int64
|
||||
var productList []types.Product
|
||||
// var pcsBox int64
|
||||
// var pcs int64
|
||||
// var productList []types.Product
|
||||
|
||||
var surplusAt int64
|
||||
// var surplusAt int64
|
||||
|
||||
//如果是部分支付状态,那么取消订单倒计时2天
|
||||
if *item.Status == int64(constants.STATUS_NEW_PART_PAY) {
|
||||
surplusAt = (*item.Ctime + int64(constants.CANCLE_ORDER_EXPIRE)) - time.Now().UTC().Unix()
|
||||
if surplusAt < 0 {
|
||||
surplusAt = 0
|
||||
}
|
||||
}
|
||||
// //如果是部分支付状态,那么取消订单倒计时2天
|
||||
// if *item.Status == int64(constants.STATUS_NEW_PART_PAY) {
|
||||
// surplusAt = (*item.Ctime + int64(constants.CANCLE_ORDER_EXPIRE)) - time.Now().UTC().Unix()
|
||||
// if surplusAt < 0 {
|
||||
// surplusAt = 0
|
||||
// }
|
||||
// }
|
||||
|
||||
fsOrderAffiliateInfo := item.FsOrderAffiliateInfo
|
||||
// fsOrderAffiliateInfo := item.FsOrderAffiliateInfo
|
||||
|
||||
var sureTime int64
|
||||
var productTime int64
|
||||
var ProductEndtime int64
|
||||
var deliverTime int64
|
||||
var upsDeliverTime int64
|
||||
var upsTime int64
|
||||
var arrivalTime int64
|
||||
var recevieTime int64
|
||||
if fsOrderAffiliateInfo.Id > 0 {
|
||||
sureTime = *fsOrderAffiliateInfo.SureTime
|
||||
productTime = *fsOrderAffiliateInfo.ProductTime
|
||||
ProductEndtime = *fsOrderAffiliateInfo.ProductEndtime
|
||||
deliverTime = *fsOrderAffiliateInfo.DeliverTime
|
||||
upsDeliverTime = *fsOrderAffiliateInfo.UpsDeliverTime
|
||||
upsTime = *fsOrderAffiliateInfo.UpsTime
|
||||
arrivalTime = *fsOrderAffiliateInfo.ArrivalTime
|
||||
recevieTime = *fsOrderAffiliateInfo.RecevieTime
|
||||
}
|
||||
// var sureTime int64
|
||||
// var productTime int64
|
||||
// var ProductEndtime int64
|
||||
// var deliverTime int64
|
||||
// var upsDeliverTime int64
|
||||
// var upsTime int64
|
||||
// var arrivalTime int64
|
||||
// var recevieTime int64
|
||||
// if fsOrderAffiliateInfo.Id > 0 {
|
||||
// sureTime = *fsOrderAffiliateInfo.SureTime
|
||||
// productTime = *fsOrderAffiliateInfo.ProductTime
|
||||
// ProductEndtime = *fsOrderAffiliateInfo.ProductEndtime
|
||||
// deliverTime = *fsOrderAffiliateInfo.DeliverTime
|
||||
// upsDeliverTime = *fsOrderAffiliateInfo.UpsDeliverTime
|
||||
// upsTime = *fsOrderAffiliateInfo.UpsTime
|
||||
// arrivalTime = *fsOrderAffiliateInfo.ArrivalTime
|
||||
// recevieTime = *fsOrderAffiliateInfo.RecevieTime
|
||||
// }
|
||||
|
||||
var getOrderStatusAndLogisticsReq = order.GetOrderStatusAndLogisticsReq{
|
||||
OrderStatus: constants.Order(*item.Status),
|
||||
DeliveryMethod: constants.DeliveryMethod(*item.DeliveryMethod),
|
||||
IsPayCompleted: *item.IsAllProductCompleted,
|
||||
OrderCtime: *item.Ctime,
|
||||
// var getOrderStatusAndLogisticsReq = order.GetOrderStatusAndLogisticsReq{
|
||||
// OrderStatus: constants.Order(*item.Status),
|
||||
// DeliveryMethod: constants.DeliveryMethod(*item.DeliveryMethod),
|
||||
// IsPayCompleted: *item.IsAllProductCompleted,
|
||||
// OrderCtime: *item.Ctime,
|
||||
|
||||
SureTime: sureTime,
|
||||
ProductTime: productTime,
|
||||
ProductEndtime: ProductEndtime,
|
||||
DeliverTime: deliverTime,
|
||||
UpsDeliverTime: upsDeliverTime,
|
||||
UpsTime: upsTime,
|
||||
ArrivalTime: arrivalTime,
|
||||
RecevieTime: recevieTime,
|
||||
// SureTime: sureTime,
|
||||
// ProductTime: productTime,
|
||||
// ProductEndtime: ProductEndtime,
|
||||
// DeliverTime: deliverTime,
|
||||
// UpsDeliverTime: upsDeliverTime,
|
||||
// UpsTime: upsTime,
|
||||
// ArrivalTime: arrivalTime,
|
||||
// RecevieTime: recevieTime,
|
||||
|
||||
WebSetTimeInfo: orderTimeConfig,
|
||||
}
|
||||
// WebSetTimeInfo: orderTimeConfig,
|
||||
// }
|
||||
|
||||
statusAndLogisticsRes := order.GetOrderStatusAndLogistics(getOrderStatusAndLogisticsReq)
|
||||
// statusAndLogisticsRes := order.GetOrderStatusAndLogistics(getOrderStatusAndLogisticsReq)
|
||||
|
||||
// 流程控制
|
||||
var statusTime []types.StatusTime
|
||||
for _, itemTimes := range statusAndLogisticsRes.Times {
|
||||
statusTime = append(statusTime, types.StatusTime{
|
||||
Key: itemTimes.Key,
|
||||
Time: itemTimes.Time,
|
||||
})
|
||||
}
|
||||
pbData.StatusTimes = statusTime
|
||||
pbData.LogisticsStatus = int64(statusAndLogisticsRes.LogisticsStatus)
|
||||
pbData.Status = int64(statusAndLogisticsRes.OrderStatus)
|
||||
// // 流程控制
|
||||
// var statusTime []types.StatusTime
|
||||
// for _, itemTimes := range statusAndLogisticsRes.Times {
|
||||
// statusTime = append(statusTime, types.StatusTime{
|
||||
// Key: itemTimes.Key,
|
||||
// Time: itemTimes.Time,
|
||||
// })
|
||||
// }
|
||||
// pbData.StatusTimes = statusTime
|
||||
// pbData.LogisticsStatus = int64(statusAndLogisticsRes.LogisticsStatus)
|
||||
// pbData.Status = int64(statusAndLogisticsRes.OrderStatus)
|
||||
|
||||
var isStopMax int64
|
||||
if len(item.FsOrderDetails) > 0 {
|
||||
for _, fsOrderDetailItem := range item.FsOrderDetails {
|
||||
// var isStopMax int64
|
||||
// if len(item.FsOrderDetails) > 0 {
|
||||
// for _, fsOrderDetailItem := range item.FsOrderDetails {
|
||||
|
||||
fsOrderDetailBuyNum := *fsOrderDetailItem.FsOrderDetail.BuyNum
|
||||
fsOrderDetailEachBoxNum := *fsOrderDetailItem.FsOrderDetailTemplateInfo.EachBoxNum
|
||||
pcs = pcs + fsOrderDetailBuyNum
|
||||
pcsBoxNum := fsOrderDetailBuyNum / fsOrderDetailEachBoxNum
|
||||
var csBoxNumF int64
|
||||
if (fsOrderDetailBuyNum % fsOrderDetailEachBoxNum) > 0 {
|
||||
csBoxNumF = 1
|
||||
}
|
||||
pcsBox = pcsBox + pcsBoxNum + csBoxNumF
|
||||
// fsOrderDetailBuyNum := *fsOrderDetailItem.FsOrderDetail.BuyNum
|
||||
// fsOrderDetailEachBoxNum := *fsOrderDetailItem.FsOrderDetailTemplateInfo.EachBoxNum
|
||||
// pcs = pcs + fsOrderDetailBuyNum
|
||||
// pcsBoxNum := fsOrderDetailBuyNum / fsOrderDetailEachBoxNum
|
||||
// var csBoxNumF int64
|
||||
// if (fsOrderDetailBuyNum % fsOrderDetailEachBoxNum) > 0 {
|
||||
// csBoxNumF = 1
|
||||
// }
|
||||
// pcsBox = pcsBox + pcsBoxNum + csBoxNumF
|
||||
|
||||
productCover := *fsOrderDetailItem.Cover
|
||||
// 尺寸
|
||||
if size >= 200 {
|
||||
coverArr := strings.Split(*fsOrderDetailItem.Cover, ".")
|
||||
if len(coverArr) < 2 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "cover split slice item count is less than 2")
|
||||
}
|
||||
productCover = fmt.Sprintf("%s_%d.%s", coverArr[0], req.Size, coverArr[1])
|
||||
}
|
||||
// productCover := *fsOrderDetailItem.Cover
|
||||
// // 尺寸
|
||||
// if size >= 200 {
|
||||
// coverArr := strings.Split(*fsOrderDetailItem.Cover, ".")
|
||||
// if len(coverArr) < 2 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "cover split slice item count is less than 2")
|
||||
// }
|
||||
// productCover = fmt.Sprintf("%s_%d.%s", coverArr[0], req.Size, coverArr[1])
|
||||
// }
|
||||
|
||||
// 判断stop
|
||||
var isStop int64
|
||||
if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.OptionData.Id != 0 {
|
||||
// 尺寸或者模板下架
|
||||
if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 {
|
||||
isStop = 1
|
||||
} else {
|
||||
isStop = 3
|
||||
}
|
||||
} else {
|
||||
if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 {
|
||||
isStop = 1
|
||||
}
|
||||
}
|
||||
// // 判断stop
|
||||
// var isStop int64
|
||||
// if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.OptionData.Id != 0 {
|
||||
// // 尺寸或者模板下架
|
||||
// if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 {
|
||||
// isStop = 1
|
||||
// } else {
|
||||
// isStop = 3
|
||||
// }
|
||||
// } else {
|
||||
// if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 {
|
||||
// isStop = 1
|
||||
// }
|
||||
// }
|
||||
|
||||
// 判断产品是否下架
|
||||
if *fsOrderDetailItem.FsProductInfo.IsShelf == 0 || *fsOrderDetailItem.FsProductInfo.IsDel == 1 {
|
||||
isStop = 2
|
||||
}
|
||||
if isStop > isStopMax {
|
||||
isStopMax = isStop
|
||||
}
|
||||
// // 判断产品是否下架
|
||||
// if *fsOrderDetailItem.FsProductInfo.IsShelf == 0 || *fsOrderDetailItem.FsProductInfo.IsDel == 1 {
|
||||
// isStop = 2
|
||||
// }
|
||||
// if isStop > isStopMax {
|
||||
// isStopMax = isStop
|
||||
// }
|
||||
|
||||
productList = append(productList, types.Product{
|
||||
Cover: productCover,
|
||||
Fitting: *fsOrderDetailItem.OptionalTitle,
|
||||
OptionPrice: *fsOrderDetailItem.OptionPrice,
|
||||
OrderDetailTemplateId: *fsOrderDetailItem.OrderDetailTemplateId,
|
||||
OrderId: *fsOrderDetailItem.OrderId,
|
||||
Pcs: fsOrderDetailBuyNum,
|
||||
PcsBox: pcsBox,
|
||||
Price: *fsOrderDetailItem.FsOrderDetail.Amount,
|
||||
ProductId: *fsOrderDetailItem.OptionPrice,
|
||||
Title: *fsOrderDetailItem.FsProductInfo.Title,
|
||||
Size: *fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductSizeInfo.Capacity,
|
||||
IsStop: isStop,
|
||||
})
|
||||
}
|
||||
pbData.ProductList = productList
|
||||
}
|
||||
// productList = append(productList, types.Product{
|
||||
// Cover: productCover,
|
||||
// Fitting: *fsOrderDetailItem.OptionalTitle,
|
||||
// OptionPrice: *fsOrderDetailItem.OptionPrice,
|
||||
// OrderDetailTemplateId: *fsOrderDetailItem.OrderDetailTemplateId,
|
||||
// OrderId: *fsOrderDetailItem.OrderId,
|
||||
// Pcs: fsOrderDetailBuyNum,
|
||||
// PcsBox: pcsBox,
|
||||
// Price: *fsOrderDetailItem.FsOrderDetail.Amount,
|
||||
// ProductId: *fsOrderDetailItem.OptionPrice,
|
||||
// Title: *fsOrderDetailItem.FsProductInfo.Title,
|
||||
// Size: *fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductSizeInfo.Capacity,
|
||||
// IsStop: isStop,
|
||||
// })
|
||||
// }
|
||||
// pbData.ProductList = productList
|
||||
// }
|
||||
|
||||
pbData.IsStop = isStopMax
|
||||
pbData.PcsBox = pcsBox
|
||||
pbData.Pcs = pcs
|
||||
pbData.SurplusAt = surplusAt
|
||||
pbData.Deposit = *item.TotalAmount / 2
|
||||
pbData.Remaining = pbData.Deposit
|
||||
respList = append(respList, pbData)
|
||||
}
|
||||
// pbData.IsStop = isStopMax
|
||||
// pbData.PcsBox = pcsBox
|
||||
// pbData.Pcs = pcs
|
||||
// pbData.SurplusAt = surplusAt
|
||||
// pbData.Deposit = *item.TotalAmount / 2
|
||||
// pbData.Remaining = pbData.Deposit
|
||||
// respList = append(respList, pbData)
|
||||
// }
|
||||
|
||||
}
|
||||
// }
|
||||
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success", types.UserOrderListRsp{
|
||||
Items: respList,
|
||||
Meta: types.Meta{
|
||||
TotalCount: total,
|
||||
PageCount: int64(math.Ceil(float64(total) / float64(pageSize))),
|
||||
CurrentPage: int(page),
|
||||
PerPage: int(pageSize),
|
||||
},
|
||||
})
|
||||
// return resp.SetStatusWithMessage(basic.CodeOK, "success", types.UserOrderListRsp{
|
||||
// Items: respList,
|
||||
// Meta: types.Meta{
|
||||
// TotalCount: total,
|
||||
// PageCount: int64(math.Ceil(float64(total) / float64(pageSize))),
|
||||
// CurrentPage: int(page),
|
||||
// PerPage: int(pageSize),
|
||||
// },
|
||||
// })
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success")
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ func NewGetMapLibraryListLogic(ctx context.Context, svcCtx *svc.ServiceContext)
|
||||
|
||||
func (l *GetMapLibraryListLogic) GetMapLibraryList(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first")
|
||||
}
|
||||
mapLibraryModel := gmodel.NewFsMapLibraryModel(l.svcCtx.MysqlConn)
|
||||
mapLibraryList, err := mapLibraryModel.GetAllEnabledList(l.ctx)
|
||||
|
||||
@@ -46,7 +46,7 @@ func (l *SaveMapLibraryLogic) BeforeLogic(w http.ResponseWriter, r *http.Request
|
||||
|
||||
func (l *SaveMapLibraryLogic) SaveMapLibrary(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first")
|
||||
}
|
||||
|
||||
if len(l.bodyData) == 0 {
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/pay"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
@@ -15,7 +10,6 @@ import (
|
||||
"fusenapi/server/pay/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrderPaymentIntentLogic struct {
|
||||
@@ -45,143 +39,143 @@ func (l *OrderPaymentIntentLogic) OrderPaymentIntent(req *types.OrderPaymentInte
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
|
||||
if userinfo == nil || userinfo.UserId == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
// if userinfo == nil || userinfo.UserId == 0 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
|
||||
// 查询订单数据
|
||||
orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn)
|
||||
// // 查询订单数据
|
||||
// orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
// orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
|
||||
}
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
|
||||
// }
|
||||
|
||||
// 校验订单状态
|
||||
if *orderInfo.IsCancel == 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "order cancelled")
|
||||
}
|
||||
// // 校验订单状态
|
||||
// if *orderInfo.IsCancel == 1 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "order cancelled")
|
||||
// }
|
||||
|
||||
// 校验地址信息
|
||||
addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn)
|
||||
_, err = addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId)
|
||||
// // 校验地址信息
|
||||
// addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn)
|
||||
// _, err = addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "address not found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info")
|
||||
}
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "address not found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info")
|
||||
// }
|
||||
|
||||
// 校验订单支付信息
|
||||
if *orderInfo.IsPayCompleted == 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "order is pay completed")
|
||||
}
|
||||
// // 校验订单支付信息
|
||||
// if *orderInfo.IsPayCompleted == 1 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "order is pay completed")
|
||||
// }
|
||||
|
||||
// 判断订单状态以及该支付金额
|
||||
var nowAt int64 = time.Now().UTC().Unix()
|
||||
var payAmount int64
|
||||
if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) {
|
||||
payAmount = *orderInfo.TotalAmount / 2
|
||||
*orderInfo.DeliveryMethod = req.DeliveryMethod
|
||||
*orderInfo.AddressId = req.AddressId
|
||||
*orderInfo.PayMethod = req.PayMethod
|
||||
} else {
|
||||
payAmount = *orderInfo.TotalAmount - *orderInfo.TotalAmount/2
|
||||
}
|
||||
// // 判断订单状态以及该支付金额
|
||||
// var nowAt int64 = time.Now().UTC().Unix()
|
||||
// var payAmount int64
|
||||
// if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) {
|
||||
// payAmount = *orderInfo.TotalAmount / 2
|
||||
// *orderInfo.DeliveryMethod = req.DeliveryMethod
|
||||
// *orderInfo.AddressId = req.AddressId
|
||||
// *orderInfo.PayMethod = req.PayMethod
|
||||
// } else {
|
||||
// payAmount = *orderInfo.TotalAmount - *orderInfo.TotalAmount/2
|
||||
// }
|
||||
|
||||
payConfig := &pay.Config{}
|
||||
var generatePrepaymentReq = &pay.GeneratePrepaymentReq{
|
||||
OrderSn: req.Sn,
|
||||
ProductName: "支付标题",
|
||||
Amount: payAmount,
|
||||
Currency: "eur",
|
||||
Quantity: 1,
|
||||
ProductDescription: "支付描述",
|
||||
}
|
||||
// payConfig := &pay.Config{}
|
||||
// var generatePrepaymentReq = &pay.GeneratePrepaymentReq{
|
||||
// OrderSn: req.Sn,
|
||||
// ProductName: "支付标题",
|
||||
// Amount: payAmount,
|
||||
// Currency: "eur",
|
||||
// Quantity: 1,
|
||||
// ProductDescription: "支付描述",
|
||||
// }
|
||||
|
||||
var resData types.OrderPaymentIntentRes
|
||||
// 事务处理
|
||||
ctx := l.ctx
|
||||
err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error {
|
||||
// 支付记录--处理 //支付记录改为一条订单多条,分首款尾款
|
||||
var payStatus int64 = 0
|
||||
var orderSource int64 = 1
|
||||
var payStage int64
|
||||
var fspay *gmodel.FsPay
|
||||
newFsPayModel := gmodel.NewFsPayModel(connGorm)
|
||||
if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) {
|
||||
fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 1)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payStage = 1
|
||||
} else {
|
||||
fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 2)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payStage = 2
|
||||
}
|
||||
// var resData types.OrderPaymentIntentRes
|
||||
// // 事务处理
|
||||
// ctx := l.ctx
|
||||
// err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error {
|
||||
// // 支付记录--处理 //支付记录改为一条订单多条,分首款尾款
|
||||
// var payStatus int64 = 0
|
||||
// var orderSource int64 = 1
|
||||
// var payStage int64
|
||||
// var fspay *gmodel.FsPay
|
||||
// newFsPayModel := gmodel.NewFsPayModel(connGorm)
|
||||
// if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) {
|
||||
// fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 1)
|
||||
// if err != nil {
|
||||
// if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
// payStage = 1
|
||||
// } else {
|
||||
// fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 2)
|
||||
// if err != nil {
|
||||
// if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
// payStage = 2
|
||||
// }
|
||||
|
||||
// 支付预付--生成
|
||||
if constants.PayMethod(req.PayMethod) == constants.PAYMETHOD_STRIPE {
|
||||
payConfig.Stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key
|
||||
generatePrepaymentReq.SuccessURL = l.svcCtx.Config.PayConfig.Stripe.SuccessURL
|
||||
generatePrepaymentReq.CancelURL = l.svcCtx.Config.PayConfig.Stripe.CancelURL
|
||||
}
|
||||
payDriver := pay.NewPayDriver(req.PayMethod, payConfig)
|
||||
prepaymentRes, err := payDriver.GeneratePrepayment(generatePrepaymentReq)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// // 支付预付--生成
|
||||
// if constants.PayMethod(req.PayMethod) == constants.PAYMETHOD_STRIPE {
|
||||
// payConfig.Stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key
|
||||
// generatePrepaymentReq.SuccessURL = l.svcCtx.Config.PayConfig.Stripe.SuccessURL
|
||||
// generatePrepaymentReq.CancelURL = l.svcCtx.Config.PayConfig.Stripe.CancelURL
|
||||
// }
|
||||
// payDriver := pay.NewPayDriver(req.PayMethod, payConfig)
|
||||
// prepaymentRes, err := payDriver.GeneratePrepayment(generatePrepaymentReq)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
// 订单信息--修改
|
||||
err = gmodel.NewFsOrderModel(connGorm).RBUpdate(ctx, orderInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// // 订单信息--修改
|
||||
// err = gmodel.NewFsOrderModel(connGorm).RBUpdate(ctx, orderInfo)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
if fspay == nil {
|
||||
fspay = &gmodel.FsPay{
|
||||
UserId: orderInfo.UserId,
|
||||
OrderNumber: orderInfo.Sn,
|
||||
CreatedAt: &nowAt,
|
||||
}
|
||||
} else {
|
||||
fspay.UpdatedAt = &nowAt
|
||||
}
|
||||
fspay.PayAmount = &payAmount
|
||||
fspay.PayStage = &payStage
|
||||
//fspay.TradeNo = &prepaymentRes.TradeNo
|
||||
fspay.PaymentMethod = &req.PayMethod
|
||||
fspay.OrderSource = &orderSource
|
||||
fspay.PayStatus = &payStatus
|
||||
// if fspay == nil {
|
||||
// fspay = &gmodel.FsPay{
|
||||
// UserId: orderInfo.UserId,
|
||||
// OrderNumber: orderInfo.Sn,
|
||||
// CreatedAt: &nowAt,
|
||||
// }
|
||||
// } else {
|
||||
// fspay.UpdatedAt = &nowAt
|
||||
// }
|
||||
// fspay.PayAmount = &payAmount
|
||||
// fspay.PayStage = &payStage
|
||||
// //fspay.TradeNo = &prepaymentRes.TradeNo
|
||||
// fspay.PaymentMethod = &req.PayMethod
|
||||
// fspay.OrderSource = &orderSource
|
||||
// fspay.PayStatus = &payStatus
|
||||
|
||||
_, err = newFsPayModel.RBCreateOrUpdate(ctx, fspay)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// _, err = newFsPayModel.RBCreateOrUpdate(ctx, fspay)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
resData.RedirectUrl = prepaymentRes.URL
|
||||
resData.ClientSecret = prepaymentRes.ClientSecret
|
||||
// resData.RedirectUrl = prepaymentRes.URL
|
||||
// resData.ClientSecret = prepaymentRes.ClientSecret
|
||||
|
||||
return nil
|
||||
})
|
||||
// return nil
|
||||
// })
|
||||
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to make payment")
|
||||
}
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to make payment")
|
||||
// }
|
||||
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success", resData)
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success")
|
||||
}
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
@@ -15,9 +11,7 @@ import (
|
||||
"fusenapi/server/pay/internal/types"
|
||||
|
||||
"github.com/stripe/stripe-go/v74"
|
||||
"github.com/stripe/stripe-go/v74/webhook"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type StripeWebhookLogic struct {
|
||||
@@ -48,97 +42,97 @@ func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
|
||||
stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key
|
||||
event := stripe.Event{}
|
||||
// stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key
|
||||
// event := stripe.Event{}
|
||||
|
||||
if err := json.Unmarshal(req.Payload, &event); err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail")
|
||||
}
|
||||
// if err := json.Unmarshal(req.Payload, &event); err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail")
|
||||
// }
|
||||
|
||||
endpointSecret := l.svcCtx.Config.PayConfig.Stripe.EndpointSecret
|
||||
signatureHeader := req.StripeSignature
|
||||
event, err := webhook.ConstructEvent(req.Payload, signatureHeader, endpointSecret)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "Webhook signature verification failed")
|
||||
}
|
||||
// endpointSecret := l.svcCtx.Config.PayConfig.Stripe.EndpointSecret
|
||||
// signatureHeader := req.StripeSignature
|
||||
// event, err := webhook.ConstructEvent(req.Payload, signatureHeader, endpointSecret)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "Webhook signature verification failed")
|
||||
// }
|
||||
|
||||
// 新增支付回调事件日志
|
||||
var payMethod = int64(constants.PAYMETHOD_STRIPE)
|
||||
var nowTime = time.Now().UTC().Unix()
|
||||
var eventData = string(event.Data.Raw)
|
||||
var fsPayEvent = &gmodel.FsPayEvent{
|
||||
PayMethod: &payMethod,
|
||||
EventId: &event.ID,
|
||||
EventType: &event.Type,
|
||||
EventData: &eventData,
|
||||
EventCreated: &event.Created,
|
||||
Ip: &req.RemoteAddr,
|
||||
CreatedAt: &nowTime,
|
||||
}
|
||||
l.HandlePayEventCreate(fsPayEvent)
|
||||
// // 新增支付回调事件日志
|
||||
// var payMethod = int64(constants.PAYMETHOD_STRIPE)
|
||||
// var nowTime = time.Now().UTC().Unix()
|
||||
// var eventData = string(event.Data.Raw)
|
||||
// var fsPayEvent = &gmodel.FsPayEvent{
|
||||
// PayMethod: &payMethod,
|
||||
// EventId: &event.ID,
|
||||
// EventType: &event.Type,
|
||||
// EventData: &eventData,
|
||||
// EventCreated: &event.Created,
|
||||
// Ip: &req.RemoteAddr,
|
||||
// CreatedAt: &nowTime,
|
||||
// }
|
||||
// l.HandlePayEventCreate(fsPayEvent)
|
||||
|
||||
// Unmarshal the event data into an appropriate struct depending on its Type
|
||||
switch event.Type {
|
||||
case "charge.succeeded":
|
||||
// var charge stripe.Charge
|
||||
// err := json.Unmarshal(event.Data.Raw, &charge)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.succeeded")
|
||||
// }
|
||||
// // Unmarshal the event data into an appropriate struct depending on its Type
|
||||
// switch event.Type {
|
||||
// case "charge.succeeded":
|
||||
// // var charge stripe.Charge
|
||||
// // err := json.Unmarshal(event.Data.Raw, &charge)
|
||||
// // if err != nil {
|
||||
// // logx.Error(err)
|
||||
// // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.succeeded")
|
||||
// // }
|
||||
|
||||
case "checkout.session.completed":
|
||||
// checkout checkout.session.completed 处理逻辑
|
||||
// var session stripe.CheckoutSession
|
||||
// err := json.Unmarshal(event.Data.Raw, &session)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded")
|
||||
// }
|
||||
// fmt.Println("checkout.session.completed")
|
||||
// err = l.handlePaymentSessionCompleted(session.ID, session.PaymentIntent.ID)
|
||||
// if err != nil {
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "checkout.session.completed fail")
|
||||
// }
|
||||
case "payment_intent.succeeded":
|
||||
var paymentIntent stripe.PaymentIntent
|
||||
err := json.Unmarshal(event.Data.Raw, &paymentIntent)
|
||||
if err != nil {
|
||||
logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type payment_intent.succeeded")
|
||||
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded")
|
||||
}
|
||||
err = l.HandlePaymentIntentSucceeded(&paymentIntent)
|
||||
if err != nil {
|
||||
logx.Errorf("err:%+v,desc:%s", err, "pay notify handle payment_intent.succeeded")
|
||||
return resp.SetStatusWithMessage(basic.CodePaybackNotOk, "pay notify handle payment_intent.succeeded")
|
||||
}
|
||||
case "payment_method.attached":
|
||||
var paymentMethod stripe.PaymentMethod
|
||||
err := json.Unmarshal(event.Data.Raw, &paymentMethod)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_method.attached")
|
||||
}
|
||||
case "charge.refunded":
|
||||
var chargeRefunded stripe.Charge
|
||||
err := json.Unmarshal(event.Data.Raw, &chargeRefunded)
|
||||
if err != nil {
|
||||
logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type charge.refunded")
|
||||
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.refunded")
|
||||
}
|
||||
err = l.HandleChargeRefunded(&chargeRefunded)
|
||||
if err != nil {
|
||||
logx.Errorf("err:%+v,desc:%s", err, "pay notify handle charge.refunded")
|
||||
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify handle charge.refunded")
|
||||
}
|
||||
// case "checkout.session.completed":
|
||||
// // checkout checkout.session.completed 处理逻辑
|
||||
// // var session stripe.CheckoutSession
|
||||
// // err := json.Unmarshal(event.Data.Raw, &session)
|
||||
// // if err != nil {
|
||||
// // logx.Error(err)
|
||||
// // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded")
|
||||
// // }
|
||||
// // fmt.Println("checkout.session.completed")
|
||||
// // err = l.handlePaymentSessionCompleted(session.ID, session.PaymentIntent.ID)
|
||||
// // if err != nil {
|
||||
// // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "checkout.session.completed fail")
|
||||
// // }
|
||||
// case "payment_intent.succeeded":
|
||||
// var paymentIntent stripe.PaymentIntent
|
||||
// err := json.Unmarshal(event.Data.Raw, &paymentIntent)
|
||||
// if err != nil {
|
||||
// logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type payment_intent.succeeded")
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded")
|
||||
// }
|
||||
// err = l.HandlePaymentIntentSucceeded(&paymentIntent)
|
||||
// if err != nil {
|
||||
// logx.Errorf("err:%+v,desc:%s", err, "pay notify handle payment_intent.succeeded")
|
||||
// return resp.SetStatusWithMessage(basic.CodePaybackNotOk, "pay notify handle payment_intent.succeeded")
|
||||
// }
|
||||
// case "payment_method.attached":
|
||||
// var paymentMethod stripe.PaymentMethod
|
||||
// err := json.Unmarshal(event.Data.Raw, &paymentMethod)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_method.attached")
|
||||
// }
|
||||
// case "charge.refunded":
|
||||
// var chargeRefunded stripe.Charge
|
||||
// err := json.Unmarshal(event.Data.Raw, &chargeRefunded)
|
||||
// if err != nil {
|
||||
// logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type charge.refunded")
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.refunded")
|
||||
// }
|
||||
// err = l.HandleChargeRefunded(&chargeRefunded)
|
||||
// if err != nil {
|
||||
// logx.Errorf("err:%+v,desc:%s", err, "pay notify handle charge.refunded")
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify handle charge.refunded")
|
||||
// }
|
||||
|
||||
// ... handle other event types
|
||||
default:
|
||||
logx.Error("Unhandled event")
|
||||
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type Unhandled")
|
||||
}
|
||||
// // ... handle other event types
|
||||
// default:
|
||||
// logx.Error("Unhandled event")
|
||||
// return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type Unhandled")
|
||||
// }
|
||||
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
@@ -151,62 +145,62 @@ func (l *StripeWebhookLogic) HandlePayEventCreate(fsPayEvent *gmodel.FsPayEvent)
|
||||
|
||||
// 退款成功
|
||||
func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge) (err error) {
|
||||
// 退款成功
|
||||
if chargeRefunded.Status == "succeeded" {
|
||||
ctx := l.ctx
|
||||
err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error {
|
||||
// 查询支付记录
|
||||
payModelT := gmodel.NewFsPayModel(connGorm)
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
// 更新支付记录
|
||||
*payInfo.IsRefund = 1
|
||||
_, err = payModelT.RBCreateOrUpdate(ctx, payInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 获取是否还有未退款的数据
|
||||
payModelTRSB2 := payModelTRSB.Where("order_number = ?", payInfo.OrderNumber).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0)
|
||||
count, err := payModelT.FindCount(l.ctx, payModelTRSB2, nil)
|
||||
if count == 0 {
|
||||
// 退款完成更新订单状态
|
||||
orderModelT := gmodel.NewFsOrderModel(connGorm)
|
||||
orderModelTRSB := orderModelT.BuilderTrans(nil).Where("sn =?", payInfo.OrderNumber)
|
||||
orderInfoRel, err := orderModelT.FindOneByQuery(ctx, orderModelTRSB, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var isRefunded int64 = 1
|
||||
var isRefunding int64 = 1
|
||||
var orderStatus int64 = int64(constants.STATUS_NEW_REFUNDED)
|
||||
var orderInfo = &gmodel.FsOrder{}
|
||||
orderInfo.Id = orderInfoRel.Id
|
||||
orderInfo.IsRefunded = &isRefunded
|
||||
orderInfo.IsRefunding = &isRefunding
|
||||
orderInfo.Status = &orderStatus
|
||||
orderModelT.Update(ctx, orderInfo)
|
||||
// // 退款成功
|
||||
// if chargeRefunded.Status == "succeeded" {
|
||||
// ctx := l.ctx
|
||||
// err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error {
|
||||
// // 查询支付记录
|
||||
// payModelT := gmodel.NewFsPayModel(connGorm)
|
||||
// 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 {
|
||||
// return err
|
||||
// }
|
||||
// // 更新支付记录
|
||||
// *payInfo.IsRefund = 1
|
||||
// _, err = payModelT.RBCreateOrUpdate(ctx, payInfo)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// // 获取是否还有未退款的数据
|
||||
// payModelTRSB2 := payModelTRSB.Where("order_number = ?", payInfo.OrderNumber).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0)
|
||||
// count, err := payModelT.FindCount(l.ctx, payModelTRSB2, nil)
|
||||
// if count == 0 {
|
||||
// // 退款完成更新订单状态
|
||||
// orderModelT := gmodel.NewFsOrderModel(connGorm)
|
||||
// orderModelTRSB := orderModelT.BuilderTrans(nil).Where("sn =?", payInfo.OrderNumber)
|
||||
// orderInfoRel, err := orderModelT.FindOneByQuery(ctx, orderModelTRSB, nil)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// var isRefunded int64 = 1
|
||||
// var isRefunding int64 = 1
|
||||
// var orderStatus int64 = int64(constants.STATUS_NEW_REFUNDED)
|
||||
// var orderInfo = &gmodel.FsOrder{}
|
||||
// orderInfo.Id = orderInfoRel.Id
|
||||
// orderInfo.IsRefunded = &isRefunded
|
||||
// orderInfo.IsRefunding = &isRefunding
|
||||
// orderInfo.Status = &orderStatus
|
||||
// orderModelT.Update(ctx, orderInfo)
|
||||
|
||||
// 记录退款原因
|
||||
refundReasonModelT := gmodel.NewFsRefundReasonModel(connGorm)
|
||||
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.RBCreateOrUpdate(ctx, refundReasonInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
// // 记录退款原因
|
||||
// refundReasonModelT := gmodel.NewFsRefundReasonModel(connGorm)
|
||||
// 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.RBCreateOrUpdate(ctx, refundReasonInfo)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
// return err
|
||||
// })
|
||||
// }
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -234,160 +228,160 @@ func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge)
|
||||
|
||||
// 付款成功
|
||||
func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.PaymentIntent) error {
|
||||
orderSn, ok := paymentIntent.Metadata["order_sn"]
|
||||
if !ok || orderSn == "" {
|
||||
return errors.New("order_sn not found")
|
||||
}
|
||||
// orderSn, ok := paymentIntent.Metadata["order_sn"]
|
||||
// if !ok || orderSn == "" {
|
||||
// return errors.New("order_sn not found")
|
||||
// }
|
||||
|
||||
// 查询支付记录
|
||||
payModel := gmodel.NewFsPayModel(l.svcCtx.MysqlConn)
|
||||
rsbPay := payModel.RowSelectBuilder(nil)
|
||||
rsbPay = rsbPay.Where("order_number = ?", orderSn).Where("pay_status = ?", constants.PAYSTATUS_UNSUCCESS)
|
||||
payInfo, err := payModel.FindOneByQuery(l.ctx, rsbPay, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// // 查询支付记录
|
||||
// payModel := gmodel.NewFsPayModel(l.svcCtx.MysqlConn)
|
||||
// rsbPay := payModel.RowSelectBuilder(nil)
|
||||
// rsbPay = rsbPay.Where("order_number = ?", orderSn).Where("pay_status = ?", constants.PAYSTATUS_UNSUCCESS)
|
||||
// payInfo, err := payModel.FindOneByQuery(l.ctx, rsbPay, nil)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
//订单信息
|
||||
orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn)
|
||||
orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
fsOrderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn)
|
||||
fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn)
|
||||
// //订单信息
|
||||
// orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn)
|
||||
// orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
|
||||
// fsOrderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn)
|
||||
// fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn)
|
||||
|
||||
rsbOrder := orderModel.RowSelectBuilder(nil)
|
||||
rsbOrder = rsbOrder.Where("sn =?", orderSn).Preload("FsOrderDetails")
|
||||
rsbOrder = rsbOrder.Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
return dbPreload.Table(fsOrderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
return dbPreload.Table(fsProductDesignModel.TableName())
|
||||
})
|
||||
})
|
||||
})
|
||||
fsOrderRelInfo, err := orderModel.FindOneByQuery(l.ctx, rsbOrder, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// rsbOrder := orderModel.RowSelectBuilder(nil)
|
||||
// rsbOrder = rsbOrder.Where("sn =?", orderSn).Preload("FsOrderDetails")
|
||||
// rsbOrder = rsbOrder.Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
// return dbPreload.Table(fsOrderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
// return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB {
|
||||
// return dbPreload.Table(fsProductDesignModel.TableName())
|
||||
// })
|
||||
// })
|
||||
// })
|
||||
// fsOrderRelInfo, err := orderModel.FindOneByQuery(l.ctx, rsbOrder, nil)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
var designIds []int64
|
||||
var cartIds []int64
|
||||
if len(fsOrderRelInfo.FsOrderDetails) > 0 {
|
||||
for _, fsOrderDetail := range fsOrderRelInfo.FsOrderDetails {
|
||||
if fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 {
|
||||
designIds = append(designIds, fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id)
|
||||
}
|
||||
cartIds = append(cartIds, *fsOrderDetail.CartId)
|
||||
}
|
||||
}
|
||||
// var designIds []int64
|
||||
// var cartIds []int64
|
||||
// if len(fsOrderRelInfo.FsOrderDetails) > 0 {
|
||||
// for _, fsOrderDetail := range fsOrderRelInfo.FsOrderDetails {
|
||||
// if fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 {
|
||||
// designIds = append(designIds, fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id)
|
||||
// }
|
||||
// cartIds = append(cartIds, *fsOrderDetail.CartId)
|
||||
// }
|
||||
// }
|
||||
|
||||
var nowTime int64 = time.Now().UTC().Unix()
|
||||
// var nowTime int64 = time.Now().UTC().Unix()
|
||||
|
||||
// 支付成功
|
||||
if paymentIntent.Status == "succeeded" {
|
||||
var card string
|
||||
var brand string
|
||||
if paymentIntent.LatestCharge.PaymentMethodDetails != nil {
|
||||
if paymentIntent.LatestCharge.PaymentMethodDetails.Card != nil {
|
||||
if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 != "" {
|
||||
card = paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4
|
||||
}
|
||||
if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand != "" {
|
||||
brand = string(paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand)
|
||||
}
|
||||
}
|
||||
}
|
||||
// // 支付成功
|
||||
// if paymentIntent.Status == "succeeded" {
|
||||
// var card string
|
||||
// var brand string
|
||||
// if paymentIntent.LatestCharge.PaymentMethodDetails != nil {
|
||||
// if paymentIntent.LatestCharge.PaymentMethodDetails.Card != nil {
|
||||
// if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 != "" {
|
||||
// card = paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4
|
||||
// }
|
||||
// if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand != "" {
|
||||
// brand = string(paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
ctx := l.ctx
|
||||
err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error {
|
||||
// 更新支付信息
|
||||
payModelT := gmodel.NewFsPayModel(connGorm)
|
||||
*payInfo.PayStatus = 1
|
||||
*payInfo.PayTime = nowTime
|
||||
*payInfo.CardNo = card
|
||||
*payInfo.Brand = brand
|
||||
*payInfo.TradeNo = paymentIntent.ID
|
||||
_, err = payModelT.RBCreateOrUpdate(ctx, payInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// ctx := l.ctx
|
||||
// err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error {
|
||||
// // 更新支付信息
|
||||
// payModelT := gmodel.NewFsPayModel(connGorm)
|
||||
// *payInfo.PayStatus = 1
|
||||
// *payInfo.PayTime = nowTime
|
||||
// *payInfo.CardNo = card
|
||||
// *payInfo.Brand = brand
|
||||
// *payInfo.TradeNo = paymentIntent.ID
|
||||
// _, 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.RBUpdateByIds(productDesignModelTRSB, designIds, &gmodel.FsProductDesign{IsPay: &isPay})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// // 更新设计数据
|
||||
// productDesignModelT := gmodel.NewFsProductDesignModel(connGorm)
|
||||
// productDesignModelTRSB := productDesignModelT.BuilderTrans(ctx, nil)
|
||||
// var isPay int64 = 1
|
||||
// err = productDesignModelT.RBUpdateByIds(productDesignModelTRSB, designIds, &gmodel.FsProductDesign{IsPay: &isPay})
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
var orderInfo = &gmodel.FsOrder{}
|
||||
var orderStatus int64
|
||||
var orderIsPartPay int64
|
||||
var orderPayedAmount int64
|
||||
var orderIsPayCompleted int64
|
||||
// 支付记录是首款
|
||||
if *payInfo.PayStage == int64(constants.PAYSTAGE_DEPOSIT) {
|
||||
orderStatus = int64(constants.STATUS_NEW_PART_PAY)
|
||||
orderIsPartPay = 1
|
||||
orderInfo.IsPartPay = &orderIsPartPay
|
||||
orderPayedAmount = paymentIntent.Amount
|
||||
// var orderInfo = &gmodel.FsOrder{}
|
||||
// var orderStatus int64
|
||||
// var orderIsPartPay int64
|
||||
// var orderPayedAmount int64
|
||||
// var orderIsPayCompleted int64
|
||||
// // 支付记录是首款
|
||||
// if *payInfo.PayStage == int64(constants.PAYSTAGE_DEPOSIT) {
|
||||
// orderStatus = int64(constants.STATUS_NEW_PART_PAY)
|
||||
// orderIsPartPay = 1
|
||||
// orderInfo.IsPartPay = &orderIsPartPay
|
||||
// orderPayedAmount = paymentIntent.Amount
|
||||
|
||||
// 删除购物车
|
||||
cartModelT := gmodel.NewFsCartModel(connGorm)
|
||||
cartModelTRSB := cartModelT.BuilderTrans(ctx, nil)
|
||||
err = cartModelT.RBDeleteCartsByIds(cartModelTRSB, cartIds)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// // 删除购物车
|
||||
// cartModelT := gmodel.NewFsCartModel(connGorm)
|
||||
// cartModelTRSB := cartModelT.BuilderTrans(ctx, nil)
|
||||
// err = cartModelT.RBDeleteCartsByIds(cartModelTRSB, cartIds)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
|
||||
// 支付记录是尾款
|
||||
if *payInfo.PayStage == int64(constants.PAYSTAGE_REMAINING) {
|
||||
if *fsOrderRelInfo.Status < int64(constants.STATUS_NEW_PAY_COMPLETED) {
|
||||
orderStatus = int64(constants.STATUS_NEW_PAY_COMPLETED)
|
||||
}
|
||||
orderIsPayCompleted = 1
|
||||
orderInfo.IsPayCompleted = &orderIsPayCompleted
|
||||
orderPayedAmount = *fsOrderRelInfo.PayedAmount + paymentIntent.Amount
|
||||
}
|
||||
// // 支付记录是尾款
|
||||
// if *payInfo.PayStage == int64(constants.PAYSTAGE_REMAINING) {
|
||||
// if *fsOrderRelInfo.Status < int64(constants.STATUS_NEW_PAY_COMPLETED) {
|
||||
// orderStatus = int64(constants.STATUS_NEW_PAY_COMPLETED)
|
||||
// }
|
||||
// orderIsPayCompleted = 1
|
||||
// orderInfo.IsPayCompleted = &orderIsPayCompleted
|
||||
// orderPayedAmount = *fsOrderRelInfo.PayedAmount + paymentIntent.Amount
|
||||
// }
|
||||
|
||||
// 更新订单信息
|
||||
orderInfo.Id = fsOrderRelInfo.Id
|
||||
orderInfo.Status = &orderStatus
|
||||
orderInfo.Ptime = &nowTime
|
||||
orderInfo.PayedAmount = &orderPayedAmount
|
||||
orderModelT := gmodel.NewFsOrderModel(connGorm)
|
||||
err = orderModelT.RBUpdate(ctx, orderInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// // 更新订单信息
|
||||
// orderInfo.Id = fsOrderRelInfo.Id
|
||||
// orderInfo.Status = &orderStatus
|
||||
// orderInfo.Ptime = &nowTime
|
||||
// orderInfo.PayedAmount = &orderPayedAmount
|
||||
// orderModelT := gmodel.NewFsOrderModel(connGorm)
|
||||
// err = orderModelT.RBUpdate(ctx, orderInfo)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// return err
|
||||
// })
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
//千人千面的处理
|
||||
// $renderServer = (new RenderService());
|
||||
// $renderServer->thousandsFacesV2($order->id);
|
||||
// //清除用户最新的设计
|
||||
// $cache = \Yii::$app->cache;
|
||||
// $cache->delete(CacheConfigHelper::LAST_DESIGN . $order->user_id);
|
||||
// //缓存最新订单编号
|
||||
// $cache->set(CacheConfigHelper::USER_ORDERNO . $order->user_id, $order->sn);
|
||||
// //千人千面的处理
|
||||
// // $renderServer = (new RenderService());
|
||||
// // $renderServer->thousandsFacesV2($order->id);
|
||||
// // //清除用户最新的设计
|
||||
// // $cache = \Yii::$app->cache;
|
||||
// // $cache->delete(CacheConfigHelper::LAST_DESIGN . $order->user_id);
|
||||
// // //缓存最新订单编号
|
||||
// // $cache->set(CacheConfigHelper::USER_ORDERNO . $order->user_id, $order->sn);
|
||||
|
||||
// //查询用户邮箱信息
|
||||
// $user = \api\models\User::find()->where(['id' => $order->user_id])->one();
|
||||
// $redisData = [
|
||||
// 'key' => 'receipt_download',
|
||||
// 'param' => [
|
||||
// 'email' => $user->email,
|
||||
// 'order_id' => $order->id,
|
||||
// 'pay_id' => $pay->id,
|
||||
// 'type' => 1,//付款成功为1
|
||||
// ]
|
||||
// ];
|
||||
// Email::timely($redisData);
|
||||
}
|
||||
// // //查询用户邮箱信息
|
||||
// // $user = \api\models\User::find()->where(['id' => $order->user_id])->one();
|
||||
// // $redisData = [
|
||||
// // 'key' => 'receipt_download',
|
||||
// // 'param' => [
|
||||
// // 'email' => $user->email,
|
||||
// // 'order_id' => $order->id,
|
||||
// // 'pay_id' => $pay->id,
|
||||
// // 'type' => 1,//付款成功为1
|
||||
// // ]
|
||||
// // ];
|
||||
// // Email::timely($redisData);
|
||||
// }
|
||||
|
||||
// 订单记录
|
||||
return nil
|
||||
|
||||
@@ -2,11 +2,10 @@ package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"fusenapi/server/product/internal/svc"
|
||||
@@ -31,7 +30,7 @@ func NewGetLastProductDesignLogic(ctx context.Context, svcCtx *svc.ServiceContex
|
||||
|
||||
func (l *GetLastProductDesignLogic) GetLastProductDesign(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if !userinfo.IsUser() {
|
||||
return resp.SetStatusAddMessage(basic.CodeUnAuth, "please login")
|
||||
return resp.SetStatusAddMessage(basic.CodeUnAuth, "please sign in")
|
||||
}
|
||||
//获取用户信息
|
||||
user, err := l.svcCtx.AllModels.FsUser.FindUserById(l.ctx, userinfo.UserId)
|
||||
@@ -47,64 +46,64 @@ func (l *GetLastProductDesignLogic) GetLastProductDesign(req *types.Request, use
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success:IsOpenRender switch is closed")
|
||||
}
|
||||
//查询用户最近下单成功的数据
|
||||
orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, user.Id, int64(constants.STATUS_NEW_NOT_PAY))
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "none of order is found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusAddMessage(basic.CodeDbSqlErr, "failed to get your last order")
|
||||
}
|
||||
// orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, user.Id, int64(constants.STATUS_NEW_NOT_PAY))
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "none of order is found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusAddMessage(basic.CodeDbSqlErr, "failed to get your last order")
|
||||
// }
|
||||
//获取该订单相关设计信息
|
||||
orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order detail is not found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusAddMessage(basic.CodeDbSqlErr, "failed to get order detail")
|
||||
}
|
||||
//获取设计模板详情,便于获得design_id
|
||||
orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order detail template is not found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get order detail template")
|
||||
}
|
||||
// orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order detail is not found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusAddMessage(basic.CodeDbSqlErr, "failed to get order detail")
|
||||
// }
|
||||
// //获取设计模板详情,便于获得design_id
|
||||
// orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order detail template is not found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get order detail template")
|
||||
// }
|
||||
//最后一次设计不存在,则不返回该设计相关数据
|
||||
if *orderDetailTemplate.DesignId <= 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success:last design id is not set")
|
||||
}
|
||||
// if *orderDetailTemplate.DesignId <= 0 {
|
||||
// return resp.SetStatusWithMessage(basic.CodeOK, "success:last design id is not set")
|
||||
// }
|
||||
//获取设计数据
|
||||
productDesign, err := l.svcCtx.AllModels.FsProductDesign.FindOne(l.ctx, *orderDetailTemplate.DesignId, user.Id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "product design is not found")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product design")
|
||||
}
|
||||
var info interface{}
|
||||
if productDesign.Info != nil && *productDesign.Info != "" {
|
||||
if err := json.Unmarshal([]byte(*productDesign.Info), &info); err != nil {
|
||||
logx.Error(err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
var logoColor interface{}
|
||||
if productDesign.LogoColor != nil && *productDesign.LogoColor != "" {
|
||||
if err := json.Unmarshal([]byte(*productDesign.LogoColor), &logoColor); err != nil {
|
||||
logx.Error(err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// productDesign, err := l.svcCtx.AllModels.FsProductDesign.FindOne(l.ctx, *orderDetailTemplate.DesignId, user.Id)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "product design is not found")
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product design")
|
||||
// }
|
||||
// var info interface{}
|
||||
// if productDesign.Info != nil && *productDesign.Info != "" {
|
||||
// if err := json.Unmarshal([]byte(*productDesign.Info), &info); err != nil {
|
||||
// logx.Error(err)
|
||||
// return nil
|
||||
// }
|
||||
// }
|
||||
// var logoColor interface{}
|
||||
// if productDesign.LogoColor != nil && *productDesign.LogoColor != "" {
|
||||
// if err := json.Unmarshal([]byte(*productDesign.LogoColor), &logoColor); err != nil {
|
||||
// logx.Error(err)
|
||||
// return nil
|
||||
// }
|
||||
// }
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetLastProductDesignRsp{
|
||||
Id: productDesign.Id,
|
||||
OptionalId: *productDesign.OptionalId,
|
||||
SizeId: *productDesign.SizeId,
|
||||
LogoColor: logoColor,
|
||||
Info: info,
|
||||
Id: 1,
|
||||
OptionalId: 1,
|
||||
SizeId: 1,
|
||||
LogoColor: 1,
|
||||
Info: nil,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,10 +8,11 @@ import (
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/format"
|
||||
"fusenapi/utils/step_price"
|
||||
"gorm.io/gorm"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"context"
|
||||
|
||||
"fusenapi/server/product/internal/svc"
|
||||
|
||||
@@ -31,7 +31,7 @@ func NewGetProductDesignLogic(ctx context.Context, svcCtx *svc.ServiceContext) *
|
||||
|
||||
func (l *GetProductDesignLogic) GetProductDesign(req *types.GetProductDesignReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in first")
|
||||
}
|
||||
if req.Sn == "" {
|
||||
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param sn is required")
|
||||
|
||||
@@ -14,10 +14,11 @@ import (
|
||||
"fusenapi/utils/format"
|
||||
"fusenapi/utils/image"
|
||||
"fusenapi/utils/step_price"
|
||||
"gorm.io/gorm"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"fusenapi/server/product/internal/svc"
|
||||
"fusenapi/server/product/internal/types"
|
||||
|
||||
@@ -460,66 +461,66 @@ func (l *GetProductInfoLogic) getRenderDesign(clientNo string) interface{} {
|
||||
// 获取用户最新设计
|
||||
func (l *GetProductInfoLogic) getLastDesign(userInfo gmodel.FsUser) interface{} {
|
||||
//查询用户最近下单成功的数据
|
||||
orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, userInfo.Id, int64(constants.STATUS_NEW_NOT_PAY))
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
logx.Error(err)
|
||||
return nil
|
||||
}
|
||||
// orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, userInfo.Id, int64(constants.STATUS_NEW_NOT_PAY))
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return nil
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return nil
|
||||
// }
|
||||
//获取该订单相关设计信息
|
||||
orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
logx.Error(err)
|
||||
return nil
|
||||
}
|
||||
//获取设计模板详情,便于获得design_id
|
||||
orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
logx.Error(err)
|
||||
return nil
|
||||
}
|
||||
// orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return nil
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return nil
|
||||
// }
|
||||
// //获取设计模板详情,便于获得design_id
|
||||
// orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return nil
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return nil
|
||||
// }
|
||||
//若没打开了个性化渲染按钮或者最后一次设计不存在,则不返回该设计相关数据
|
||||
if *userInfo.IsOpenRender != 1 || *orderDetailTemplate.DesignId <= 0 {
|
||||
return nil
|
||||
}
|
||||
//获取设计数据
|
||||
productDesign, err := l.svcCtx.AllModels.FsProductDesign.FindOne(l.ctx, *orderDetailTemplate.DesignId, userInfo.Id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
logx.Error(err)
|
||||
return nil
|
||||
}
|
||||
var info interface{}
|
||||
if productDesign.Info != nil && *productDesign.Info != "" {
|
||||
if err := json.Unmarshal([]byte(*productDesign.Info), &info); err != nil {
|
||||
logx.Error(err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
var logoColor interface{}
|
||||
if productDesign.LogoColor != nil && *productDesign.LogoColor != "" {
|
||||
if err := json.Unmarshal([]byte(*productDesign.LogoColor), &logoColor); err != nil {
|
||||
logx.Error(err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// if *userInfo.IsOpenRender != 1 || *orderDetailTemplate.DesignId <= 0 {
|
||||
// return nil
|
||||
// }
|
||||
// //获取设计数据
|
||||
// productDesign, err := l.svcCtx.AllModels.FsProductDesign.FindOne(l.ctx, *orderDetailTemplate.DesignId, userInfo.Id)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return nil
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return nil
|
||||
// }
|
||||
// var info interface{}
|
||||
// if productDesign.Info != nil && *productDesign.Info != "" {
|
||||
// if err := json.Unmarshal([]byte(*productDesign.Info), &info); err != nil {
|
||||
// logx.Error(err)
|
||||
// return nil
|
||||
// }
|
||||
// }
|
||||
// var logoColor interface{}
|
||||
// if productDesign.LogoColor != nil && *productDesign.LogoColor != "" {
|
||||
// if err := json.Unmarshal([]byte(*productDesign.LogoColor), &logoColor); err != nil {
|
||||
// logx.Error(err)
|
||||
// return nil
|
||||
// }
|
||||
// }
|
||||
return map[string]interface{}{
|
||||
"id": productDesign.Id,
|
||||
"info": info,
|
||||
"logo_color": logoColor,
|
||||
"material_id": *productDesign.MaterialId,
|
||||
"optional_id": *productDesign.OptionalId,
|
||||
"size_id": *productDesign.SizeId,
|
||||
"id": 1,
|
||||
"info": 1,
|
||||
"logo_color": 1,
|
||||
"material_id": 1,
|
||||
"optional_id": 1,
|
||||
"size_id": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,14 +2,14 @@ package logic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/color_list"
|
||||
"gorm.io/gorm"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"context"
|
||||
|
||||
"fusenapi/server/product/internal/svc"
|
||||
@@ -126,28 +126,28 @@ func (l *GetRenderSettingByPidLogic) checkRenderDesign(clientNo string) (bool, e
|
||||
// 查询是否存在最新设计
|
||||
func (l *GetRenderSettingByPidLogic) checkLastDesignExists(userId int64) (bool, error) {
|
||||
//查询用户最近下单成功的数据
|
||||
orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, userId, int64(constants.STATUS_NEW_NOT_PAY))
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
// orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, userId, int64(constants.STATUS_NEW_NOT_PAY))
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return false, nil
|
||||
// }
|
||||
// return false, err
|
||||
// }
|
||||
//获取该订单相关设计信息
|
||||
orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
//获取设计模板详情,便于获得design_id
|
||||
orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return *orderDetailTemplate.DesignId > 0, nil
|
||||
// orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return false, nil
|
||||
// }
|
||||
// return false, err
|
||||
// }
|
||||
// //获取设计模板详情,便于获得design_id
|
||||
// orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId)
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// return false, nil
|
||||
// }
|
||||
// return false, err
|
||||
// }
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ func NewGetSizeByProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *
|
||||
// 获取分类下的产品以及尺寸
|
||||
func (l *GetSizeByProductLogic) GetSizeByProduct(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in first")
|
||||
}
|
||||
//获取所有网站目录
|
||||
tagsModel := gmodel.NewFsTagsModel(l.svcCtx.MysqlConn)
|
||||
@@ -74,14 +74,14 @@ func (l *GetSizeByProductLogic) GetSizeByProduct(req *types.Request, userinfo *a
|
||||
}
|
||||
//获取价格列表
|
||||
productPriceModel := gmodel.NewFsProductPriceModel(l.svcCtx.MysqlConn)
|
||||
productPriceList, err := productPriceModel.GetPriceListBySizeIds(l.ctx, sizeIds)
|
||||
productPriceList, err := productPriceModel.GetPriceListByProductIdsSizeIds(l.ctx, productIds, sizeIds)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product proce list")
|
||||
}
|
||||
mapProductPrice := make(map[int64]gmodel.FsProductPrice)
|
||||
mapProductPrice := make(map[string]gmodel.FsProductPrice)
|
||||
for _, v := range productPriceList {
|
||||
mapProductPrice[*v.SizeId] = v
|
||||
mapProductPrice[fmt.Sprintf("%d_%d", *v.ProductId, *v.SizeId)] = v
|
||||
}
|
||||
//组装返回
|
||||
list := make([]types.GetSizeByProductRsp, 0, len(tagsList))
|
||||
@@ -103,7 +103,7 @@ func (l *GetSizeByProductLogic) GetSizeByProduct(req *types.Request, userinfo *a
|
||||
}
|
||||
|
||||
// 第一层子层
|
||||
func (l *GetSizeByProductLogic) GetFirstChildrenList(tag gmodel.FsTags, productList []gmodel.FsProduct, productSizeList []gmodel.FsProductSize, mapProductPrice map[int64]gmodel.FsProductPrice) (childrenList []types.Children, err error) {
|
||||
func (l *GetSizeByProductLogic) GetFirstChildrenList(tag gmodel.FsTags, productList []gmodel.FsProduct, productSizeList []gmodel.FsProductSize, mapProductPrice map[string]gmodel.FsProductPrice) (childrenList []types.Children, err error) {
|
||||
childrenList = make([]types.Children, 0, len(productList))
|
||||
for _, product := range productList {
|
||||
if *product.Type != tag.Id {
|
||||
@@ -126,14 +126,14 @@ func (l *GetSizeByProductLogic) GetFirstChildrenList(tag gmodel.FsTags, productL
|
||||
}
|
||||
|
||||
// 第2层子层
|
||||
func (l *GetSizeByProductLogic) GetSecondChildrenList(product gmodel.FsProduct, productSizeList []gmodel.FsProductSize, mapProductPrice map[int64]gmodel.FsProductPrice) (childrenObjList []types.ChildrenObj, err error) {
|
||||
func (l *GetSizeByProductLogic) GetSecondChildrenList(product gmodel.FsProduct, productSizeList []gmodel.FsProductSize, mapProductPrice map[string]gmodel.FsProductPrice) (childrenObjList []types.ChildrenObj, err error) {
|
||||
childrenObjList = make([]types.ChildrenObj, 0, len(productSizeList))
|
||||
for _, productSize := range productSizeList {
|
||||
if product.Id != *productSize.ProductId {
|
||||
continue
|
||||
}
|
||||
priceList := make([]types.PriceObj, 0, len(productSizeList))
|
||||
price, ok := mapProductPrice[productSize.Id]
|
||||
price, ok := mapProductPrice[fmt.Sprintf("%d_%d", *productSize.ProductId, productSize.Id)]
|
||||
//无对应尺寸价格
|
||||
if !ok {
|
||||
priceList = []types.PriceObj{
|
||||
|
||||
@@ -30,7 +30,7 @@ func NewGetSuccessRecommandLogic(ctx context.Context, svcCtx *svc.ServiceContext
|
||||
// 获取推荐的产品列表
|
||||
func (l *GetSuccessRecommandLogic) GetSuccessRecommand(req *types.GetSuccessRecommandReq, userInfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userInfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in first")
|
||||
}
|
||||
//获取用户信息
|
||||
userModel := gmodel.NewFsUserModel(l.svcCtx.MysqlConn)
|
||||
|
||||
@@ -47,7 +47,7 @@ func NewSaveDesignLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveDe
|
||||
|
||||
func (l *SaveDesignLogic) SaveDesign(req *types.SaveDesignReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in first")
|
||||
}
|
||||
//查询是否是加密的(不太合理)
|
||||
encryptWebsetting, err := l.svcCtx.AllModels.FsWebSet.FindValueByKey(l.ctx, "is_encrypt")
|
||||
|
||||
12
server/shopping-cart/etc/shopping-cart.yaml
Normal file
12
server/shopping-cart/etc/shopping-cart.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
Name: shopping-cart
|
||||
Host: 0.0.0.0
|
||||
Port: 9918
|
||||
Timeout: 15000 #服务超时时间(毫秒)
|
||||
SourceMysql: fsreaderwriter:XErSYmLELKMnf3Dh@tcp(fusen.cdmigcvz3rle.us-east-2.rds.amazonaws.com:3306)/fusen
|
||||
SourceRabbitMq: amqp://rabbit001:rabbit001129@110.41.19.98:5672
|
||||
Log:
|
||||
Stat: false
|
||||
Auth:
|
||||
AccessSecret: fusen2023
|
||||
AccessExpire: 2592000
|
||||
RefreshAfter: 1592000
|
||||
13
server/shopping-cart/internal/config/config.go
Normal file
13
server/shopping-cart/internal/config/config.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
"github.com/zeromicro/go-zero/rest"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
rest.RestConf
|
||||
SourceMysql string
|
||||
Auth types.Auth
|
||||
SourceRabbitMq string
|
||||
}
|
||||
35
server/shopping-cart/internal/handler/addtocarthandler.go
Normal file
35
server/shopping-cart/internal/handler/addtocarthandler.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/logic"
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
)
|
||||
|
||||
func AddToCartHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var req types.AddToCartReq
|
||||
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 创建一个业务逻辑层实例
|
||||
l := logic.NewAddToCartLogic(r.Context(), svcCtx)
|
||||
|
||||
rl := reflect.ValueOf(l)
|
||||
basic.BeforeLogic(w, r, rl)
|
||||
|
||||
resp := l.AddToCart(&req, userinfo)
|
||||
|
||||
if !basic.AfterLogic(w, r, rl, resp) {
|
||||
basic.NormalAfterLogic(w, r, resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/logic"
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
)
|
||||
|
||||
func CalculateCartPriceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var req types.CalculateCartPriceReq
|
||||
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 创建一个业务逻辑层实例
|
||||
l := logic.NewCalculateCartPriceLogic(r.Context(), svcCtx)
|
||||
|
||||
rl := reflect.ValueOf(l)
|
||||
basic.BeforeLogic(w, r, rl)
|
||||
|
||||
resp := l.CalculateCartPrice(&req, userinfo)
|
||||
|
||||
if !basic.AfterLogic(w, r, rl, resp) {
|
||||
basic.NormalAfterLogic(w, r, resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
35
server/shopping-cart/internal/handler/deletecarthandler.go
Normal file
35
server/shopping-cart/internal/handler/deletecarthandler.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/logic"
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
)
|
||||
|
||||
func DeleteCartHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var req types.DeleteCartReq
|
||||
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 创建一个业务逻辑层实例
|
||||
l := logic.NewDeleteCartLogic(r.Context(), svcCtx)
|
||||
|
||||
rl := reflect.ValueOf(l)
|
||||
basic.BeforeLogic(w, r, rl)
|
||||
|
||||
resp := l.DeleteCart(&req, userinfo)
|
||||
|
||||
if !basic.AfterLogic(w, r, rl, resp) {
|
||||
basic.NormalAfterLogic(w, r, resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
35
server/shopping-cart/internal/handler/getcartshandler.go
Normal file
35
server/shopping-cart/internal/handler/getcartshandler.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/logic"
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
)
|
||||
|
||||
func GetCartsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var req types.GetCartsReq
|
||||
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 创建一个业务逻辑层实例
|
||||
l := logic.NewGetCartsLogic(r.Context(), svcCtx)
|
||||
|
||||
rl := reflect.ValueOf(l)
|
||||
basic.BeforeLogic(w, r, rl)
|
||||
|
||||
resp := l.GetCarts(&req, userinfo)
|
||||
|
||||
if !basic.AfterLogic(w, r, rl, resp) {
|
||||
basic.NormalAfterLogic(w, r, resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/logic"
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
)
|
||||
|
||||
func ModifyCartPurchaseQuantityHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var req types.ModifyCartPurchaseQuantityReq
|
||||
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 创建一个业务逻辑层实例
|
||||
l := logic.NewModifyCartPurchaseQuantityLogic(r.Context(), svcCtx)
|
||||
|
||||
rl := reflect.ValueOf(l)
|
||||
basic.BeforeLogic(w, r, rl)
|
||||
|
||||
resp := l.ModifyCartPurchaseQuantity(&req, userinfo)
|
||||
|
||||
if !basic.AfterLogic(w, r, rl, resp) {
|
||||
basic.NormalAfterLogic(w, r, resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
42
server/shopping-cart/internal/handler/routes.go
Normal file
42
server/shopping-cart/internal/handler/routes.go
Normal file
@@ -0,0 +1,42 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
|
||||
"github.com/zeromicro/go-zero/rest"
|
||||
)
|
||||
|
||||
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
|
||||
server.AddRoutes(
|
||||
[]rest.Route{
|
||||
{
|
||||
Method: http.MethodPost,
|
||||
Path: "/api/shopping-cart/add",
|
||||
Handler: AddToCartHandler(serverCtx),
|
||||
},
|
||||
{
|
||||
Method: http.MethodPost,
|
||||
Path: "/api/shopping-cart/delete",
|
||||
Handler: DeleteCartHandler(serverCtx),
|
||||
},
|
||||
{
|
||||
Method: http.MethodPost,
|
||||
Path: "/api/shopping-cart/modify",
|
||||
Handler: ModifyCartPurchaseQuantityHandler(serverCtx),
|
||||
},
|
||||
{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/shopping-cart/get_carts",
|
||||
Handler: GetCartsHandler(serverCtx),
|
||||
},
|
||||
{
|
||||
Method: http.MethodPost,
|
||||
Path: "/api/shopping-cart/calculate_cart_price",
|
||||
Handler: CalculateCartPriceHandler(serverCtx),
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
217
server/shopping-cart/internal/logic/addtocartlogic.go
Normal file
217
server/shopping-cart/internal/logic/addtocartlogic.go
Normal file
@@ -0,0 +1,217 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/shopping_cart"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type AddToCartLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewAddToCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddToCartLogic {
|
||||
return &AddToCartLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
// 处理进入前逻辑w,r
|
||||
// func (l *AddToCartLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
|
||||
// }
|
||||
|
||||
func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if !userinfo.IsUser() {
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in")
|
||||
}
|
||||
//校验参数
|
||||
if err := l.AddToCartParamVerify(req); err != nil {
|
||||
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, err.Error())
|
||||
}
|
||||
//查询该用户购物车数量
|
||||
cartCount, err := l.svcCtx.AllModels.FsShoppingCart.CountUserCart(l.ctx, userinfo.UserId)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get the count of your shopping cart")
|
||||
}
|
||||
if cartCount >= 100 {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "sorry,the count of your carts can`t greater than 100")
|
||||
}
|
||||
//获取产品是否存在
|
||||
productInfo, err := l.svcCtx.AllModels.FsProduct.FindOne(l.ctx, req.ProductId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the product is not exists")
|
||||
}
|
||||
logx.Error("获取产品信息错误:", err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product info")
|
||||
}
|
||||
var (
|
||||
templateJson string //模板表的记录中的json设计信息
|
||||
templateTag string //模板表的模板标签
|
||||
fittingJson string //配件的json设计信息
|
||||
fittingName string //配件名
|
||||
)
|
||||
//有模板
|
||||
if req.TemplateId > 0 {
|
||||
templateInfo, err := l.svcCtx.AllModels.FsProductTemplateV2.FindOne(l.ctx, req.TemplateId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the template is not exists")
|
||||
}
|
||||
logx.Error("获取模板信息错误:", err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template info")
|
||||
}
|
||||
if *templateInfo.IsDel == 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template is deleted")
|
||||
}
|
||||
if *templateInfo.Status != 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template`s status is unNormal")
|
||||
}
|
||||
if templateInfo.TemplateInfo == nil || *templateInfo.TemplateInfo == "" {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template`s design info is empty")
|
||||
}
|
||||
templateJson = *templateInfo.TemplateInfo
|
||||
templateTag = *templateInfo.TemplateTag
|
||||
}
|
||||
//有配件
|
||||
if req.FittingId > 0 {
|
||||
fittingInfo, err := l.svcCtx.AllModels.FsProductModel3d.FindOne(l.ctx, req.FittingId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the fitting is not exists")
|
||||
}
|
||||
logx.Error("获取配件信息错误:", err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get fitting info")
|
||||
}
|
||||
if *fittingInfo.Status != 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "the fitting`s status is unNormal")
|
||||
}
|
||||
if fittingInfo.ModelInfo == nil || *fittingInfo.ModelInfo == "" {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "the fitting`s design info is empty")
|
||||
}
|
||||
fittingJson = *fittingInfo.ModelInfo
|
||||
fittingName = *fittingInfo.Title
|
||||
}
|
||||
//获取尺寸信息
|
||||
sizeInfo, err := l.svcCtx.AllModels.FsProductSize.FindOne(l.ctx, req.SizeId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the size is not exists")
|
||||
}
|
||||
logx.Error("获取尺寸信息错误:", err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get size info")
|
||||
}
|
||||
//状态
|
||||
if *sizeInfo.Status != 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "size info status is not normal")
|
||||
}
|
||||
//获取模型信息
|
||||
modelInfo, err := l.svcCtx.AllModels.FsProductModel3d.GetOneBySizeIdTag(l.ctx, sizeInfo.Id, constants.TAG_MODEL)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the template`s model is not exists")
|
||||
}
|
||||
logx.Error("获取模型信息错误:", err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template`s model info")
|
||||
}
|
||||
if *modelInfo.Status != 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "the model` status is unNormal")
|
||||
}
|
||||
//如果模型是配件则返回
|
||||
if *modelInfo.Tag != 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "the model your post is not a model but fitting")
|
||||
}
|
||||
if modelInfo.ModelInfo == nil || *modelInfo.ModelInfo == "" {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "the model`s design info is empty")
|
||||
}
|
||||
var sizeKeyInfo shopping_cart.SizeInfo
|
||||
if err = json.Unmarshal([]byte(*sizeInfo.Title), &sizeKeyInfo); err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse size info`s title ")
|
||||
}
|
||||
sizeKeyInfo.Capacity = *sizeInfo.Capacity
|
||||
//快照数据
|
||||
snapshot := shopping_cart.CartSnapshot{
|
||||
Logo: req.Logo,
|
||||
CombineImage: req.CombineImage,
|
||||
RenderImage: req.RenderImage,
|
||||
TemplateInfo: shopping_cart.TemplateInfo{
|
||||
TemplateJson: templateJson,
|
||||
TemplateTag: templateTag,
|
||||
},
|
||||
ModelInfo: shopping_cart.ModelInfo{
|
||||
ModelJson: *modelInfo.ModelInfo,
|
||||
},
|
||||
FittingInfo: shopping_cart.FittingInfo{
|
||||
FittingJson: fittingJson,
|
||||
FittingName: fittingName,
|
||||
},
|
||||
SizeInfo: sizeKeyInfo,
|
||||
ProductInfo: shopping_cart.ProductInfo{
|
||||
ProductName: *productInfo.Title,
|
||||
ProductSn: *productInfo.Sn,
|
||||
},
|
||||
UserDiyInformation: shopping_cart.UserDiyInformation{
|
||||
Phone: req.DiyInfo.Phone,
|
||||
Address: req.DiyInfo.Address,
|
||||
Website: req.DiyInfo.Website,
|
||||
Qrcode: req.DiyInfo.Qrcode,
|
||||
Slogan: req.DiyInfo.Slogan,
|
||||
},
|
||||
}
|
||||
snapshotJsonBytes, _ := json.Marshal(snapshot)
|
||||
snapshotJsonStr := string(snapshotJsonBytes)
|
||||
now := time.Now().UTC()
|
||||
err = l.svcCtx.AllModels.FsShoppingCart.Create(l.ctx, &gmodel.FsShoppingCart{
|
||||
UserId: &userinfo.UserId,
|
||||
ProductId: &req.ProductId,
|
||||
TemplateId: &req.TemplateId,
|
||||
ModelId: &modelInfo.Id,
|
||||
SizeId: &req.SizeId,
|
||||
FittingId: &req.FittingId,
|
||||
PurchaseQuantity: &req.PurchaseQuantity,
|
||||
Snapshot: &snapshotJsonStr,
|
||||
Ctime: &now,
|
||||
Utime: &now,
|
||||
})
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to add to cart ")
|
||||
}
|
||||
return resp.SetStatus(basic.CodeOK, "success")
|
||||
}
|
||||
|
||||
// 参数校验
|
||||
func (l *AddToCartLogic) AddToCartParamVerify(req *types.AddToCartReq) error {
|
||||
if req.ProductId <= 0 {
|
||||
return errors.New("product_id is required")
|
||||
}
|
||||
if req.SizeId <= 0 {
|
||||
return errors.New("product size is required")
|
||||
}
|
||||
if req.PurchaseQuantity <= 0 {
|
||||
return errors.New("purchase quantity can not less than 0 or equal 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
|
||||
// func (l *AddToCartLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
|
||||
// // httpx.OkJsonCtx(r.Context(), w, resp)
|
||||
// }
|
||||
@@ -0,0 +1,86 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type CalculateCartPriceLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewCalculateCartPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CalculateCartPriceLogic {
|
||||
return &CalculateCartPriceLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
// 处理进入前逻辑w,r
|
||||
// func (l *CalculateCartPriceLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
|
||||
// }
|
||||
|
||||
func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPriceReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if !userinfo.IsUser() {
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in")
|
||||
}
|
||||
if len(req.CalculateList) == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success", types.CalculateCartPriceRsp{CalculateResultList: []types.CalculateResultItem{}})
|
||||
}
|
||||
cartIds := make([]int64, 0, len(req.CalculateList))
|
||||
for _, v := range req.CalculateList {
|
||||
cartIds = append(cartIds, v.CartId)
|
||||
}
|
||||
//获取购物车列表
|
||||
carts, _, err := l.svcCtx.AllModels.FsShoppingCart.GetAllCartsByParam(l.ctx, gmodel.GetAllCartsByParamReq{
|
||||
Ids: cartIds,
|
||||
Fields: "id,size_id,product_id",
|
||||
UserId: userinfo.UserId,
|
||||
Page: 1,
|
||||
Limit: len(cartIds),
|
||||
})
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get cart list")
|
||||
}
|
||||
sizeIds := make([]int64, 0, len(carts))
|
||||
productIds := make([]int64, 0, len(carts))
|
||||
fittingIds := make([]int64, 0, len(carts))
|
||||
for _, v := range carts {
|
||||
sizeIds = append(sizeIds, *v.SizeId)
|
||||
productIds = append(productIds, *v.ProductId)
|
||||
if *v.FittingId > 0 {
|
||||
fittingIds = append(fittingIds, *v.FittingId)
|
||||
}
|
||||
}
|
||||
//根据sizeid获取价格列表
|
||||
priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListByProductIdsSizeIds(l.ctx, productIds, sizeIds)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get price list")
|
||||
}
|
||||
mapPrice := make(map[string]int)
|
||||
for k, v := range priceList {
|
||||
mapPrice[fmt.Sprintf("%d_%d", *v.ProductId, *v.SizeId)] = k
|
||||
}
|
||||
//获取配件列表
|
||||
// todo 下周写
|
||||
/*fittingList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIdsTag()*/
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
|
||||
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
|
||||
// func (l *CalculateCartPriceLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
|
||||
// // httpx.OkJsonCtx(r.Context(), w, resp)
|
||||
// }
|
||||
48
server/shopping-cart/internal/logic/deletecartlogic.go
Normal file
48
server/shopping-cart/internal/logic/deletecartlogic.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"context"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type DeleteCartLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewDeleteCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteCartLogic {
|
||||
return &DeleteCartLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
// 处理进入前逻辑w,r
|
||||
// func (l *DeleteCartLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
|
||||
// }
|
||||
|
||||
func (l *DeleteCartLogic) DeleteCart(req *types.DeleteCartReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if !userinfo.IsUser() {
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in")
|
||||
}
|
||||
//删除购物车
|
||||
if err := l.svcCtx.AllModels.FsShoppingCart.Delete(l.ctx, userinfo.UserId, req.Id); err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to delete shopping cart")
|
||||
}
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
|
||||
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
|
||||
// func (l *DeleteCartLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
|
||||
// // httpx.OkJsonCtx(r.Context(), w, resp)
|
||||
// }
|
||||
268
server/shopping-cart/internal/logic/getcartslogic.go
Normal file
268
server/shopping-cart/internal/logic/getcartslogic.go
Normal file
@@ -0,0 +1,268 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/format"
|
||||
"fusenapi/utils/shopping_cart"
|
||||
"fusenapi/utils/step_price"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type GetCartsLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCartsLogic {
|
||||
return &GetCartsLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
// 处理进入前逻辑w,r
|
||||
// func (l *GetCartsLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
|
||||
// }
|
||||
|
||||
func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if req.CurrentPage <= 0 {
|
||||
req.CurrentPage = constants.DEFAULT_PAGE
|
||||
}
|
||||
limit := 10
|
||||
//获取用户购物车列表
|
||||
carts, total, err := l.svcCtx.AllModels.FsShoppingCart.GetAllCartsByParam(l.ctx, gmodel.GetAllCartsByParamReq{
|
||||
UserId: userinfo.UserId,
|
||||
Sort: "id DESC",
|
||||
Page: req.CurrentPage,
|
||||
Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to get your shopping carts")
|
||||
}
|
||||
if len(carts) == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetCartsRsp{
|
||||
Meta: types.Meta{
|
||||
TotalCount: total,
|
||||
PageCount: int64(math.Ceil(float64(total) / float64(limit))),
|
||||
CurrentPage: req.CurrentPage,
|
||||
PerPage: limit,
|
||||
},
|
||||
CartList: nil,
|
||||
})
|
||||
}
|
||||
var (
|
||||
mapSize = make(map[int64]gmodel.FsProductSize)
|
||||
mapModel = make(map[int64]gmodel.FsProductModel3d)
|
||||
mapTemplate = make(map[int64]gmodel.FsProductTemplateV2)
|
||||
mapSizePrice = make(map[string]gmodel.FsProductPrice)
|
||||
mapProduct = make(map[int64]struct{})
|
||||
)
|
||||
//获取相关信息
|
||||
err = l.GetRelationInfo(GetRelationInfoReq{
|
||||
Carts: carts,
|
||||
MapSize: mapSize,
|
||||
MapModel: mapModel,
|
||||
MapTemplate: mapTemplate,
|
||||
MapSizePrice: mapSizePrice,
|
||||
MapProduct: mapProduct,
|
||||
})
|
||||
if err != nil {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, err.Error())
|
||||
}
|
||||
//定义map收集变更信息
|
||||
mapCartChange := make(map[int64]string)
|
||||
mapSnapshot := make(map[int64]shopping_cart.CartSnapshot)
|
||||
//校验购物车数据是否变更
|
||||
err = shopping_cart.VerifyShoppingCartSnapshotDataChange(shopping_cart.VerifyShoppingCartSnapshotDataChangeReq{
|
||||
Carts: carts,
|
||||
MapSize: mapSize,
|
||||
MapModel: mapModel,
|
||||
MapTemplate: mapTemplate,
|
||||
MapCartChange: mapCartChange,
|
||||
MapSnapshot: mapSnapshot,
|
||||
MapProduct: mapProduct,
|
||||
})
|
||||
if err != nil {
|
||||
logx.Error("VerifyShoppingCartSnapshotDataChange err:", err.Error())
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "system err:failed to check shopping cart change data")
|
||||
}
|
||||
|
||||
list := make([]types.CartItem, 0, len(carts))
|
||||
for _, cart := range carts {
|
||||
snapShot := mapSnapshot[cart.Id]
|
||||
sizePrice, ok := mapSizePrice[fmt.Sprintf("%d_%d", *cart.ProductId, *cart.SizeId)]
|
||||
if !ok {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("the size`s price info is not exists:%d", *cart.SizeId))
|
||||
}
|
||||
//阶梯数量切片
|
||||
stepNum, err := format.StrSlicToIntSlice(strings.Split(*sizePrice.StepNum, ","))
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step number:%d", *cart.SizeId))
|
||||
}
|
||||
lenStepNum := len(stepNum)
|
||||
//阶梯价格切片
|
||||
stepPrice, err := format.StrSlicToIntSlice(strings.Split(*sizePrice.StepPrice, ","))
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step price:%d", *cart.SizeId))
|
||||
}
|
||||
lenStepPrice := len(stepPrice)
|
||||
if lenStepPrice == 0 || lenStepNum == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("step price or step number is not set:%d ", *cart.SizeId))
|
||||
}
|
||||
//购买箱数
|
||||
boxQuantity := int(math.Ceil(float64(*cart.PurchaseQuantity) / float64(*sizePrice.EachBoxNum)))
|
||||
//获取阶梯数量
|
||||
stepQuantityList := make([]int64, 0, 20)
|
||||
tmpMinBuyNum := *sizePrice.MinBuyNum
|
||||
for tmpMinBuyNum < (int64(stepNum[lenStepNum-1]) + 5) {
|
||||
//阶梯数
|
||||
tmpQuantity := tmpMinBuyNum * (*sizePrice.EachBoxNum)
|
||||
stepQuantityList = append(stepQuantityList, tmpQuantity)
|
||||
tmpMinBuyNum++
|
||||
}
|
||||
//根据数量获取阶梯价格中对应的价格
|
||||
itemPrice := step_price.GetCentStepPrice(boxQuantity, stepNum, stepPrice)
|
||||
//如果有配件,单价也要加入配件价格
|
||||
if *cart.FittingId > 0 {
|
||||
if curFittingInfo, ok := mapModel[*cart.FittingId]; ok {
|
||||
itemPrice += *curFittingInfo.Price
|
||||
}
|
||||
}
|
||||
totalPrice := itemPrice * (*cart.PurchaseQuantity)
|
||||
item := types.CartItem{
|
||||
ProductId: *cart.ProductId,
|
||||
SizeInfo: types.SizeInfo{
|
||||
SizeId: *cart.SizeId,
|
||||
Capacity: snapShot.SizeInfo.Capacity,
|
||||
Title: types.SizeTitle{
|
||||
Cm: snapShot.SizeInfo.Cm,
|
||||
Inch: snapShot.SizeInfo.Inch,
|
||||
},
|
||||
},
|
||||
FittingInfo: types.FittingInfo{
|
||||
FittingId: *cart.FittingId,
|
||||
FittingName: snapShot.FittingInfo.FittingName,
|
||||
},
|
||||
ItemPrice: fmt.Sprintf("%.3f", format.CentitoDollar(itemPrice)),
|
||||
TotalPrice: fmt.Sprintf("%.3f", format.CentitoDollar(totalPrice)),
|
||||
DiyInformation: types.DiyInformation{
|
||||
Phone: snapShot.UserDiyInformation.Phone,
|
||||
Address: snapShot.UserDiyInformation.Address,
|
||||
Website: snapShot.UserDiyInformation.Website,
|
||||
Qrcode: snapShot.UserDiyInformation.Qrcode,
|
||||
Slogan: snapShot.UserDiyInformation.Slogan,
|
||||
},
|
||||
PurchaseQuantity: *cart.PurchaseQuantity,
|
||||
StepNum: stepQuantityList,
|
||||
IsInvalid: false,
|
||||
InvalidDescription: "",
|
||||
}
|
||||
//是否有失效的
|
||||
if description, ok := mapCartChange[cart.Id]; ok {
|
||||
item.IsInvalid = true
|
||||
item.InvalidDescription = description
|
||||
}
|
||||
list = append(list, item)
|
||||
}
|
||||
return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetCartsRsp{
|
||||
Meta: types.Meta{
|
||||
TotalCount: total,
|
||||
PageCount: int64(math.Ceil(float64(total) / float64(limit))),
|
||||
CurrentPage: req.CurrentPage,
|
||||
PerPage: limit,
|
||||
},
|
||||
CartList: list,
|
||||
})
|
||||
}
|
||||
|
||||
// 获取相关信息
|
||||
type GetRelationInfoReq struct {
|
||||
Carts []gmodel.FsShoppingCart
|
||||
MapSize map[int64]gmodel.FsProductSize
|
||||
MapModel map[int64]gmodel.FsProductModel3d
|
||||
MapTemplate map[int64]gmodel.FsProductTemplateV2
|
||||
MapSizePrice map[string]gmodel.FsProductPrice
|
||||
MapProduct map[int64]struct{}
|
||||
}
|
||||
|
||||
func (l *GetCartsLogic) GetRelationInfo(req GetRelationInfoReq) error {
|
||||
lenCarts := len(req.Carts)
|
||||
templateIds := make([]int64, 0, lenCarts)
|
||||
modelIds := make([]int64, 0, lenCarts) //模型 + 配件
|
||||
sizeIds := make([]int64, 0, lenCarts)
|
||||
productIds := make([]int64, 0, lenCarts)
|
||||
for index := range req.Carts {
|
||||
templateIds = append(templateIds, *req.Carts[index].TemplateId)
|
||||
modelIds = append(modelIds, *req.Carts[index].ModelId, *req.Carts[index].FittingId)
|
||||
sizeIds = append(sizeIds, *req.Carts[index].SizeId)
|
||||
productIds = append(productIds, *req.Carts[index].ProductId)
|
||||
}
|
||||
//获取产品集合
|
||||
productList, err := l.svcCtx.AllModels.FsProduct.GetProductListByIds(l.ctx, productIds, "", "id")
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return errors.New("failed to get product list")
|
||||
}
|
||||
for _, v := range productList {
|
||||
req.MapProduct[v.Id] = struct{}{}
|
||||
}
|
||||
//获取尺寸列表
|
||||
sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByIds(l.ctx, sizeIds, "")
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return errors.New("failed to get size list")
|
||||
}
|
||||
for _, v := range sizeList {
|
||||
req.MapSize[v.Id] = v
|
||||
}
|
||||
//获取模型和配件信息
|
||||
modelList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIds(l.ctx, modelIds, "")
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return errors.New("failed to get model list")
|
||||
}
|
||||
for _, v := range modelList {
|
||||
req.MapModel[v.Id] = v
|
||||
}
|
||||
//获取模板列表
|
||||
templateList, err := l.svcCtx.AllModels.FsProductTemplateV2.FindAllByIds(l.ctx, templateIds)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return errors.New("failed to get template list")
|
||||
}
|
||||
for _, v := range templateList {
|
||||
req.MapTemplate[v.Id] = v
|
||||
}
|
||||
//根据sizeid获取价格列表
|
||||
priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListByProductIdsSizeIds(l.ctx, productIds, sizeIds)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return errors.New("failed to get cart`s product price list")
|
||||
}
|
||||
for _, v := range priceList {
|
||||
req.MapSizePrice[fmt.Sprintf("%d_%d", *v.ProductId, *v.SizeId)] = v
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
|
||||
// func (l *GetCartsLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
|
||||
// // httpx.OkJsonCtx(r.Context(), w, resp)
|
||||
// }
|
||||
@@ -0,0 +1,69 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"context"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
"fusenapi/server/shopping-cart/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type ModifyCartPurchaseQuantityLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewModifyCartPurchaseQuantityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ModifyCartPurchaseQuantityLogic {
|
||||
return &ModifyCartPurchaseQuantityLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
// 处理进入前逻辑w,r
|
||||
// func (l *ModifyCartPurchaseQuantityLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
|
||||
// }
|
||||
|
||||
func (l *ModifyCartPurchaseQuantityLogic) ModifyCartPurchaseQuantity(req *types.ModifyCartPurchaseQuantityReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if !userinfo.IsUser() {
|
||||
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in")
|
||||
}
|
||||
if req.Id <= 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "cart id is required")
|
||||
}
|
||||
if req.PurchaseQuantity <= 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "purchase quantity can not less than 0 or equal to 0")
|
||||
}
|
||||
//查询购物车
|
||||
_, err := l.svcCtx.AllModels.FsShoppingCart.FineOneUserCart(l.ctx, req.Id, userinfo.UserId, "id")
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the shopping cart is not exists")
|
||||
}
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to get shopping cart info ")
|
||||
}
|
||||
//修改数量
|
||||
err = l.svcCtx.AllModels.FsShoppingCart.Update(l.ctx, req.Id, userinfo.UserId, &gmodel.FsShoppingCart{
|
||||
PurchaseQuantity: &req.PurchaseQuantity,
|
||||
})
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to modify cart purchase quantity")
|
||||
}
|
||||
return resp.SetStatus(basic.CodeOK, "success")
|
||||
}
|
||||
|
||||
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
|
||||
// func (l *ModifyCartPurchaseQuantityLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
|
||||
// // httpx.OkJsonCtx(r.Context(), w, resp)
|
||||
// }
|
||||
26
server/shopping-cart/internal/svc/servicecontext.go
Normal file
26
server/shopping-cart/internal/svc/servicecontext.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"fusenapi/initalize"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/server/shopping-cart/internal/config"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ServiceContext struct {
|
||||
Config config.Config
|
||||
MysqlConn *gorm.DB
|
||||
AllModels *gmodel.AllModelsGen
|
||||
RabbitMq *initalize.RabbitMqHandle
|
||||
}
|
||||
|
||||
func NewServiceContext(c config.Config) *ServiceContext {
|
||||
conn := initalize.InitMysql(c.SourceMysql)
|
||||
|
||||
return &ServiceContext{
|
||||
Config: c,
|
||||
MysqlConn: conn,
|
||||
AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)),
|
||||
RabbitMq: initalize.InitRabbitMq(c.SourceRabbitMq, nil),
|
||||
}
|
||||
}
|
||||
169
server/shopping-cart/internal/types/types.go
Normal file
169
server/shopping-cart/internal/types/types.go
Normal file
@@ -0,0 +1,169 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
package types
|
||||
|
||||
import (
|
||||
"fusenapi/utils/basic"
|
||||
)
|
||||
|
||||
type AddToCartReq struct {
|
||||
ProductId int64 `json:"product_id"` //产品id
|
||||
TemplateId int64 `json:"template_id,optional"` //模板id(不可定制的不传)
|
||||
SizeId int64 `json:"size_id"` //尺寸id
|
||||
FittingId int64 `json:"fitting_id,optional"` //配件id(没有可以不传)
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量
|
||||
Logo string `json:"logo,optional"` //logo地址(没有可以不传)
|
||||
CombineImage string `json:"combine_image,optional"` //合图地址 (没有可以不传)
|
||||
RenderImage string `json:"render_image,optional"` //渲染结果图 (没有可以不传)
|
||||
DiyInfo DiyInfo `json:"diy_info,optional"` //用户diy数据(可选)
|
||||
}
|
||||
|
||||
type DiyInfo struct {
|
||||
Phone string `json:"phone,optional"` //电话(可选)
|
||||
Address string `json:"address,optional"` //地址 (可选)
|
||||
Website string `json:"website,optional"` //网站 (可选)
|
||||
Qrcode string `json:"qrcode,optional"` //二维码 (可选)
|
||||
Slogan string `json:"slogan,optional"` //slogan (可选)
|
||||
}
|
||||
|
||||
type DeleteCartReq struct {
|
||||
Id int64 `json:"id"` //购物车id
|
||||
}
|
||||
|
||||
type ModifyCartPurchaseQuantityReq struct {
|
||||
Id int64 `json:"id"` //购物车id
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` //数量
|
||||
}
|
||||
|
||||
type GetCartsReq struct {
|
||||
CurrentPage int `form:"current_page"` //当前页
|
||||
}
|
||||
|
||||
type GetCartsRsp struct {
|
||||
Meta Meta `json:"meta"` //分页信息
|
||||
CartList []CartItem `json:"cart_list"`
|
||||
}
|
||||
|
||||
type CartItem struct {
|
||||
ProductId int64 `json:"product_id"` //产品id
|
||||
SizeInfo SizeInfo `json:"size_info"` //尺寸信息
|
||||
FittingInfo FittingInfo `json:"fitting_info"` //配件信息
|
||||
ItemPrice string `json:"item_price"` //单价
|
||||
TotalPrice string `json:"total_price"` //单价X数量=总价
|
||||
DiyInformation DiyInformation `json:"diy_information"` //diy信息
|
||||
StepNum []int64 `json:"step_num"` //阶梯数量
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` //当前购买数量
|
||||
IsInvalid bool `json:"is_invalid"` //是否无效
|
||||
InvalidDescription string `json:"invalid_description"` //无效原因
|
||||
}
|
||||
|
||||
type SizeInfo struct {
|
||||
SizeId int64 `json:"size_id"` //尺寸id
|
||||
Capacity string `json:"capacity"` //尺寸名称
|
||||
Title SizeTitle `json:"title"`
|
||||
}
|
||||
|
||||
type FittingInfo struct {
|
||||
FittingId int64 `json:"fitting_id"` //配件id
|
||||
FittingName string `json:"fitting_name"` //配件名称
|
||||
}
|
||||
|
||||
type SizeTitle struct {
|
||||
Cm string `json:"cm"`
|
||||
Inch string `json:"inch"`
|
||||
}
|
||||
|
||||
type DiyInformation struct {
|
||||
Phone string `json:"phone"`
|
||||
Address string `json:"address"`
|
||||
Website string `json:"website"`
|
||||
Qrcode string `json:"qrcode"`
|
||||
Slogan string `json:"slogan"`
|
||||
}
|
||||
|
||||
type CalculateCartPriceReq struct {
|
||||
CalculateList []CalculateItem `json:"calculate_list"`
|
||||
}
|
||||
|
||||
type CalculateItem struct {
|
||||
CartId int64 `json:"cart_id"` //购物车id
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` //数量
|
||||
}
|
||||
|
||||
type CalculateCartPriceRsp struct {
|
||||
CalculateResultList []CalculateResultItem `json:"calculate_result_list"`
|
||||
}
|
||||
|
||||
type CalculateResultItem struct {
|
||||
CartId int64 `json:"cart_id"` //购物车id
|
||||
ItemPrice string `json:"item_price"` //单价
|
||||
TotalPrice string `json:"total_price"` //总价
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"msg"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
AccessSecret string `json:"accessSecret"`
|
||||
AccessExpire int64 `json:"accessExpire"`
|
||||
RefreshAfter int64 `json:"refreshAfter"`
|
||||
}
|
||||
|
||||
type File struct {
|
||||
Filename string `fsfile:"filename"`
|
||||
Header map[string][]string `fsfile:"header"`
|
||||
Size int64 `fsfile:"size"`
|
||||
Data []byte `fsfile:"data"`
|
||||
}
|
||||
|
||||
type Meta struct {
|
||||
TotalCount int64 `json:"total_count"`
|
||||
PageCount int64 `json:"page_count"`
|
||||
CurrentPage int `json:"current_page"`
|
||||
PerPage int `json:"per_page"`
|
||||
}
|
||||
|
||||
// Set 设置Response的Code和Message值
|
||||
func (resp *Response) Set(Code int, Message string) *Response {
|
||||
return &Response{
|
||||
Code: Code,
|
||||
Message: Message,
|
||||
}
|
||||
}
|
||||
|
||||
// Set 设置整个Response
|
||||
func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response {
|
||||
return &Response{
|
||||
Code: Code,
|
||||
Message: Message,
|
||||
Data: Data,
|
||||
}
|
||||
}
|
||||
|
||||
// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数
|
||||
func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response {
|
||||
newResp := &Response{
|
||||
Code: sr.Code,
|
||||
}
|
||||
if len(data) == 1 {
|
||||
newResp.Data = data[0]
|
||||
}
|
||||
return newResp
|
||||
}
|
||||
|
||||
// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数
|
||||
func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response {
|
||||
newResp := &Response{
|
||||
Code: sr.Code,
|
||||
Message: msg,
|
||||
}
|
||||
if len(data) == 1 {
|
||||
newResp.Data = data[0]
|
||||
}
|
||||
return newResp
|
||||
}
|
||||
36
server/shopping-cart/shopping-cart.go
Normal file
36
server/shopping-cart/shopping-cart.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"fusenapi/utils/auth"
|
||||
|
||||
"fusenapi/server/shopping-cart/internal/config"
|
||||
"fusenapi/server/shopping-cart/internal/handler"
|
||||
"fusenapi/server/shopping-cart/internal/svc"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/conf"
|
||||
"github.com/zeromicro/go-zero/rest"
|
||||
)
|
||||
|
||||
var configFile = flag.String("f", "etc/shopping-cart.yaml", "the config file")
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
var c config.Config
|
||||
conf.MustLoad(*configFile, &c)
|
||||
c.Timeout = int64(time.Second * 15)
|
||||
server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) {
|
||||
}))
|
||||
defer server.Stop()
|
||||
|
||||
ctx := svc.NewServiceContext(c)
|
||||
handler.RegisterHandlers(server, ctx)
|
||||
|
||||
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
|
||||
server.Start()
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func NewUploadQrcodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Uplo
|
||||
|
||||
func (l *UploadQrcodeLogic) UploadQrcode(req *types.UploadQrcodeReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if userinfo.GetIdType() != auth.IDTYPE_User {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first")
|
||||
}
|
||||
if req.Url == "" {
|
||||
resp.SetStatus(basic.CodeApiErr, "param url is empty")
|
||||
|
||||
@@ -33,11 +33,10 @@ type File {
|
||||
Data []byte `fsfile:"data"`
|
||||
}
|
||||
|
||||
|
||||
// 统一分页
|
||||
type Meta struct {
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
PageCount int64 `json:"pageCount"`
|
||||
CurrentPage int `json:"currentPage"`
|
||||
PerPage int `json:"perPage"`
|
||||
TotalCount int64 `json:"total_count"`
|
||||
PageCount int64 `json:"page_count"`
|
||||
CurrentPage int `json:"current_page"`
|
||||
PerPage int `json:"per_page"`
|
||||
}
|
||||
42
server_api/order.api
Normal file
42
server_api/order.api
Normal file
@@ -0,0 +1,42 @@
|
||||
syntax = "v1"
|
||||
|
||||
info (
|
||||
title: "订单模块"
|
||||
desc: "订单相关"
|
||||
author: ""
|
||||
email: ""
|
||||
)
|
||||
|
||||
import "basic.api"
|
||||
|
||||
service order {
|
||||
|
||||
@handler CreateOrderHandler
|
||||
post /api/order/create(CreateOrderReq) returns (response);
|
||||
|
||||
@handler CreatePrePaymentHandler
|
||||
post /api/order/create-prepayment(CreatePrePaymentReq) returns (response);
|
||||
|
||||
@handler OrderListHandler
|
||||
post /api/order/list(OrderListReq) returns (response);
|
||||
|
||||
}
|
||||
|
||||
type CreateOrderReq struct {
|
||||
CartIds []int64 `json:"cart_ids"`
|
||||
DeliveryMethod string `json:"delivery_method,options=[1,2]"`
|
||||
}
|
||||
|
||||
type CreatePrePaymentReq struct {
|
||||
OrderSn string `json:"order_sn"`
|
||||
DeliveryMethod int `json:"delivery_method"`
|
||||
DeliveryAddres struct {
|
||||
Address string `json:"address,optional"`
|
||||
Name string `json:"name,optional"`
|
||||
Mobile string `json:"mobile,optional"`
|
||||
} `json:"delivery_addres,optional"`
|
||||
}
|
||||
|
||||
type OrderListReq struct {
|
||||
|
||||
}
|
||||
113
server_api/shopping-cart.api
Normal file
113
server_api/shopping-cart.api
Normal file
@@ -0,0 +1,113 @@
|
||||
syntax = "v1"
|
||||
|
||||
info (
|
||||
title: "shopping-cart"// TODO: add title
|
||||
desc: "购物车服务"// TODO: add description
|
||||
author: ""
|
||||
email: ""
|
||||
)
|
||||
|
||||
import "basic.api"
|
||||
service shopping-cart {
|
||||
//加入购物车
|
||||
@handler AddToCartHandler
|
||||
post /api/shopping-cart/add(AddToCartReq) returns (response);
|
||||
//删除购物车
|
||||
@handler DeleteCartHandler
|
||||
post /api/shopping-cart/delete(DeleteCartReq) returns (response);
|
||||
//修改购物车购买数量
|
||||
@handler ModifyCartPurchaseQuantityHandler
|
||||
post /api/shopping-cart/modify(ModifyCartPurchaseQuantityReq) returns (response);
|
||||
//获取购物车列表
|
||||
@handler GetCartsHandler
|
||||
get /api/shopping-cart/get_carts(GetCartsReq) returns (response);
|
||||
//计算购物车价格
|
||||
@handler CalculateCartPriceHandler
|
||||
post /api/shopping-cart/calculate_cart_price(CalculateCartPriceReq) returns (response);
|
||||
}
|
||||
|
||||
//加入购物车
|
||||
type AddToCartReq {
|
||||
ProductId int64 `json:"product_id"` //产品id
|
||||
TemplateId int64 `json:"template_id,optional"` //模板id(不可定制的不传)
|
||||
SizeId int64 `json:"size_id"` //尺寸id
|
||||
FittingId int64 `json:"fitting_id,optional"` //配件id(没有可以不传)
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量
|
||||
Logo string `json:"logo,optional"` //logo地址(没有可以不传)
|
||||
CombineImage string `json:"combine_image,optional"` //合图地址 (没有可以不传)
|
||||
RenderImage string `json:"render_image,optional"` //渲染结果图 (没有可以不传)
|
||||
DiyInfo DiyInfo `json:"diy_info,optional"` //用户diy数据(可选)
|
||||
}
|
||||
type DiyInfo {
|
||||
Phone string `json:"phone,optional"` //电话(可选)
|
||||
Address string `json:"address,optional"` //地址 (可选)
|
||||
Website string `json:"website,optional"` //网站 (可选)
|
||||
Qrcode string `json:"qrcode,optional"` //二维码 (可选)
|
||||
Slogan string `json:"slogan,optional"` //slogan (可选)
|
||||
}
|
||||
//删除购物车
|
||||
type DeleteCartReq {
|
||||
Id int64 `json:"id"` //购物车id
|
||||
}
|
||||
//修改购物车购买数量
|
||||
type ModifyCartPurchaseQuantityReq {
|
||||
Id int64 `json:"id"` //购物车id
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` //数量
|
||||
}
|
||||
//获取购物车列表
|
||||
type GetCartsReq {
|
||||
CurrentPage int `form:"current_page"` //当前页
|
||||
}
|
||||
type GetCartsRsp {
|
||||
Meta Meta `json:"meta"` //分页信息
|
||||
CartList []CartItem `json:"cart_list"`
|
||||
}
|
||||
type CartItem {
|
||||
ProductId int64 `json:"product_id"` //产品id
|
||||
SizeInfo SizeInfo `json:"size_info"` //尺寸信息
|
||||
FittingInfo FittingInfo `json:"fitting_info"` //配件信息
|
||||
ItemPrice string `json:"item_price"` //单价
|
||||
TotalPrice string `json:"total_price"` //单价X数量=总价
|
||||
DiyInformation DiyInformation `json:"diy_information"` //diy信息
|
||||
StepNum []int64 `json:"step_num"` //阶梯数量
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` //当前购买数量
|
||||
IsInvalid bool `json:"is_invalid"` //是否无效
|
||||
InvalidDescription string `json:"invalid_description"` //无效原因
|
||||
}
|
||||
type SizeInfo {
|
||||
SizeId int64 `json:"size_id"` //尺寸id
|
||||
Capacity string `json:"capacity"` //尺寸名称
|
||||
Title SizeTitle `json:"title"`
|
||||
}
|
||||
type FittingInfo {
|
||||
FittingId int64 `json:"fitting_id"` //配件id
|
||||
FittingName string `json:"fitting_name"` //配件名称
|
||||
}
|
||||
type SizeTitle {
|
||||
Cm string `json:"cm"`
|
||||
Inch string `json:"inch"`
|
||||
}
|
||||
type DiyInformation {
|
||||
Phone string `json:"phone"`
|
||||
Address string `json:"address"`
|
||||
Website string `json:"website"`
|
||||
Qrcode string `json:"qrcode"`
|
||||
Slogan string `json:"slogan"`
|
||||
}
|
||||
|
||||
//计算购物车价格
|
||||
type CalculateCartPriceReq {
|
||||
CalculateList []CalculateItem `json:"calculate_list"`
|
||||
}
|
||||
type CalculateItem {
|
||||
CartId int64 `json:"cart_id"` //购物车id
|
||||
PurchaseQuantity int64 `json:"purchase_quantity"` //数量
|
||||
}
|
||||
type CalculateCartPriceRsp {
|
||||
CalculateResultList []CalculateResultItem `json:"calculate_result_list"`
|
||||
}
|
||||
type CalculateResultItem {
|
||||
CartId int64 `json:"cart_id"` //购物车id
|
||||
ItemPrice string `json:"item_price"` //单价
|
||||
TotalPrice string `json:"total_price"` //总价
|
||||
}
|
||||
173
service/repositories/order.go
Normal file
173
service/repositories/order.go
Normal file
@@ -0,0 +1,173 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/basic"
|
||||
"fusenapi/utils/shopping_cart"
|
||||
"fusenapi/utils/step_price"
|
||||
"math"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func NewOrder(gormDB *gorm.DB, bLMServiceUrl *string, awsSession *session.Session) Order {
|
||||
return &defaultOrder{
|
||||
MysqlConn: gormDB,
|
||||
}
|
||||
}
|
||||
|
||||
type (
|
||||
defaultOrder struct {
|
||||
MysqlConn *gorm.DB
|
||||
}
|
||||
Order interface {
|
||||
// 下单
|
||||
// 预支付
|
||||
// 列表
|
||||
// 详情
|
||||
}
|
||||
|
||||
/* 下单 */
|
||||
CreateReq struct {
|
||||
CurrentCurrency string `json:"current_currency"` // 当前货币
|
||||
ExchangeRate string `json:"exchange_rate"` // 换算汇率
|
||||
OriginalCurrency string `json:"original_currency"` // 原始货币
|
||||
UserId int64 `json:"user_id"`
|
||||
CartIds []int64 `json:"cart_ids"`
|
||||
DeliveryMethod string `json:"delivery_method"`
|
||||
}
|
||||
CreateRes struct {
|
||||
ErrorCode basic.StatusResponse
|
||||
OrderSn string
|
||||
}
|
||||
/* 下单 */
|
||||
)
|
||||
|
||||
// 下单
|
||||
func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRes, err error) {
|
||||
var errorCode basic.StatusResponse
|
||||
err = d.MysqlConn.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// 查询购物车
|
||||
var shoppingCartList []*gmodel.RelaFsShoppingCart
|
||||
resShoppingCartFind := tx.Preload("ShoppingCartProduct").Preload("ShoppingCartProductPriceList").Preload("ShoppingCartProductModel3dList").
|
||||
Where("id IN ?", in.CartIds).
|
||||
Where("user_id = ?", in.UserId).
|
||||
Find(&shoppingCartList)
|
||||
err = resShoppingCartFind.Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
shoppingCartListLen := len(shoppingCartList)
|
||||
if shoppingCartListLen == 0 {
|
||||
errorCode = *basic.CodeErrOrderCreatShoppingCartEmpty
|
||||
return errors.New(errorCode.Message)
|
||||
}
|
||||
if shoppingCartListLen != len(in.CartIds) {
|
||||
errorCode = *basic.CodeErrOrderCreatShoppingCartNotMatched
|
||||
return errors.New(errorCode.Message)
|
||||
}
|
||||
|
||||
var orderProductList []*gmodel.OrderProduct
|
||||
|
||||
for _, shoppingCart := range shoppingCartList {
|
||||
// 购物车快照
|
||||
var shoppingCartSnapshot shopping_cart.CartSnapshot
|
||||
// 购物车商品价格
|
||||
var shoppingCartProductPrice *gmodel.FsProductPrice
|
||||
// 购物车商品模型
|
||||
var shoppingCartProductModel3d *gmodel.FsProductModel3d
|
||||
if shoppingCart.Snapshot != nil {
|
||||
json.Unmarshal([]byte(*shoppingCart.Snapshot), &shoppingCartSnapshot)
|
||||
}
|
||||
// 商品异常
|
||||
if shoppingCart.ShoppingCartProduct == nil || (shoppingCart.ShoppingCartProduct != nil && *shoppingCart.ShoppingCartProduct.IsShelf == 0) {
|
||||
errorCode = *basic.CodeErrOrderCreatProductAbsent
|
||||
errorCode.Message = "create order failed, product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent"
|
||||
return errors.New(errorCode.Message)
|
||||
}
|
||||
// 商品价格异常
|
||||
if len(shoppingCart.ShoppingCartProductPriceList) == 0 {
|
||||
errorCode = *basic.CodeErrOrderCreatProductPriceAbsent
|
||||
errorCode.Message = "create order failed, price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent"
|
||||
return errors.New(errorCode.Message)
|
||||
} else {
|
||||
var isProductPrice bool
|
||||
for _, shoppingCartProductPriceInfo := range shoppingCart.ShoppingCartProductPriceList {
|
||||
if shoppingCart.SizeId == shoppingCartProductPriceInfo.SizeId {
|
||||
shoppingCartProductPrice = shoppingCartProductPriceInfo
|
||||
isProductPrice = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isProductPrice {
|
||||
errorCode = *basic.CodeErrOrderCreatProductPriceAbsent
|
||||
errorCode.Message = "create order failed, price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent"
|
||||
return errors.New(errorCode.Message)
|
||||
}
|
||||
shoppingCart.ShoppingCartProductPriceList = []*gmodel.FsProductPrice{shoppingCartProductPrice}
|
||||
}
|
||||
|
||||
// 商品模型异常
|
||||
if len(shoppingCart.ShoppingCartProductModel3dList) == 0 {
|
||||
errorCode = *basic.CodeErrOrderCreatProductAccessoryAbsent
|
||||
errorCode.Message = "create order failed, accessoryof product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent"
|
||||
return errors.New(errorCode.Message)
|
||||
} else {
|
||||
var isProductModel bool
|
||||
for _, shoppingCartProductModel3dInfo := range shoppingCart.ShoppingCartProductModel3dList {
|
||||
if shoppingCart.SizeId == shoppingCartProductModel3dInfo.SizeId {
|
||||
shoppingCartProductModel3d = shoppingCartProductModel3dInfo
|
||||
isProductModel = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isProductModel {
|
||||
errorCode = *basic.CodeErrOrderCreatProductAccessoryAbsent
|
||||
errorCode.Message = "create order failed, accessory of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent"
|
||||
return errors.New(errorCode.Message)
|
||||
}
|
||||
shoppingCart.ShoppingCartProductModel3dList = []*gmodel.FsProductModel3d{shoppingCartProductModel3d}
|
||||
}
|
||||
|
||||
var purchaseQuantity float64 = float64(*shoppingCart.PurchaseQuantity)
|
||||
var eachBoxNum float64 = float64(*shoppingCartProductPrice.EachBoxNum)
|
||||
var boxNum float64 = math.Ceil(purchaseQuantity / eachBoxNum)
|
||||
var stepNum []int
|
||||
var stepPrice []int
|
||||
if *shoppingCartProductPrice.StepNum == "" {
|
||||
errorCode = *basic.CodeErrOrderCreatProductPriceAbsent
|
||||
errorCode.Message = "create order failed, step num of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is failed"
|
||||
return errors.New(errorCode.Message)
|
||||
} else {
|
||||
json.Unmarshal([]byte(*shoppingCartProductPrice.StepNum), &stepNum)
|
||||
}
|
||||
if *shoppingCartProductPrice.StepPrice == "" {
|
||||
errorCode = *basic.CodeErrOrderCreatProductPriceAbsent
|
||||
errorCode.Message = "create order failed, step price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is failed"
|
||||
return errors.New(errorCode.Message)
|
||||
} else {
|
||||
json.Unmarshal([]byte(*shoppingCartProductPrice.StepPrice), &stepPrice)
|
||||
}
|
||||
// 商品单价
|
||||
productPrice := step_price.GetCentStepPrice(int(boxNum), stepNum, stepPrice)
|
||||
|
||||
// 商品总价
|
||||
productTotalPrice := productPrice * *shoppingCart.PurchaseQuantity
|
||||
|
||||
// 存储订单商品
|
||||
orderProductList = append(orderProductList, &gmodel.OrderProduct{})
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
return &CreateRes{
|
||||
ErrorCode: errorCode,
|
||||
}, nil
|
||||
}
|
||||
@@ -99,6 +99,13 @@ var (
|
||||
|
||||
CodeLogoCombineErr = &StatusResponse{5115, "logo combine fail"} // 合图失败
|
||||
CodeLogoCombineNoFoundErr = &StatusResponse{5116, "template record not found"} // 模版不存在
|
||||
|
||||
CodeErrOrder = &StatusResponse{5300, "ocreate order failed"} // 订单错误
|
||||
CodeErrOrderCreatShoppingCartEmpty = &StatusResponse{5301, "ocreate order failed, shopping cart is empty"} // 订单创建失败,购物车为空
|
||||
CodeErrOrderCreatShoppingCartNotMatched = &StatusResponse{5302, "ocreate order failed, shopping cart not matched"} // 订单创建失败,购物车不相符
|
||||
CodeErrOrderCreatProductAbsent = &StatusResponse{5303, "ocreate order failed, product is absent"} // 订单创建失败,商品不存在
|
||||
CodeErrOrderCreatProductPriceAbsent = &StatusResponse{5304, "ocreate order failed, price of product is absent"} // 订单创建失败,商品价格不存在
|
||||
CodeErrOrderCreatProductAccessoryAbsent = &StatusResponse{5305, "ocreate order failed, accessory of product is absent"} // 订单创建失败,商品配件不存在
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
|
||||
@@ -2,13 +2,7 @@ package configs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fusenapi/constants"
|
||||
"fusenapi/model/gmodel"
|
||||
"strconv"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -27,49 +21,49 @@ type WebSetTimeInfoData struct {
|
||||
}
|
||||
|
||||
func GetOrderTimeConfig(ctx context.Context, db *gorm.DB) (res WebSetTimeInfo, err error) {
|
||||
resData, err := gmodel.NewFsWebSetModel(db).FindValueByKey(ctx, string(constants.WEBSET_TIME_INFO))
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
res.ProductDay = int64(constants.ORDER_PRODUCT_DAY)
|
||||
res.FactoryDeliverDay = int64(constants.ORDER_FACTORY_DELIVER_DAY)
|
||||
res.DeliverUpsDay = int64(constants.ORDER_DELIVER_UPS_DAY)
|
||||
res.UpsTransDay = int64(constants.ORDER_UPS_TRANS_DAY)
|
||||
return res, nil
|
||||
}
|
||||
logx.Error(err)
|
||||
return res, err
|
||||
} else {
|
||||
var timeInfo WebSetTimeInfoData
|
||||
err = json.Unmarshal([]byte(*resData.Value), &timeInfo)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return res, err
|
||||
}
|
||||
productDay, err := strconv.Atoi(timeInfo.ProductDay)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return res, err
|
||||
}
|
||||
factoryDeliverDay, err := strconv.Atoi(timeInfo.FactoryDeliverDay)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return res, err
|
||||
}
|
||||
deliverUpsDay, err := strconv.Atoi(timeInfo.DeliverUpsDay)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return res, err
|
||||
}
|
||||
upsTransDay, err := strconv.Atoi(timeInfo.UpsTransDay)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return res, err
|
||||
}
|
||||
res.ProductDay = int64(productDay)
|
||||
res.FactoryDeliverDay = int64(factoryDeliverDay)
|
||||
res.DeliverUpsDay = int64(deliverUpsDay)
|
||||
res.UpsTransDay = int64(upsTransDay)
|
||||
}
|
||||
// resData, err := gmodel.NewFsWebSetModel(db).FindValueByKey(ctx, string(constants.WEBSET_TIME_INFO))
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// res.ProductDay = int64(constants.ORDER_PRODUCT_DAY)
|
||||
// res.FactoryDeliverDay = int64(constants.ORDER_FACTORY_DELIVER_DAY)
|
||||
// res.DeliverUpsDay = int64(constants.ORDER_DELIVER_UPS_DAY)
|
||||
// res.UpsTransDay = int64(constants.ORDER_UPS_TRANS_DAY)
|
||||
// return res, nil
|
||||
// }
|
||||
// logx.Error(err)
|
||||
// return res, err
|
||||
// } else {
|
||||
// var timeInfo WebSetTimeInfoData
|
||||
// err = json.Unmarshal([]byte(*resData.Value), &timeInfo)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return res, err
|
||||
// }
|
||||
// productDay, err := strconv.Atoi(timeInfo.ProductDay)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return res, err
|
||||
// }
|
||||
// factoryDeliverDay, err := strconv.Atoi(timeInfo.FactoryDeliverDay)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return res, err
|
||||
// }
|
||||
// deliverUpsDay, err := strconv.Atoi(timeInfo.DeliverUpsDay)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return res, err
|
||||
// }
|
||||
// upsTransDay, err := strconv.Atoi(timeInfo.UpsTransDay)
|
||||
// if err != nil {
|
||||
// logx.Error(err)
|
||||
// return res, err
|
||||
// }
|
||||
// res.ProductDay = int64(productDay)
|
||||
// res.FactoryDeliverDay = int64(factoryDeliverDay)
|
||||
// res.DeliverUpsDay = int64(deliverUpsDay)
|
||||
// res.UpsTransDay = int64(upsTransDay)
|
||||
// }
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// 美分转美元
|
||||
func CentoDollar(price int64) float64 {
|
||||
str := fmt.Sprintf("%.2f", float64(price)/float64(100))
|
||||
// 厘转美元
|
||||
func CentitoDollar(price int64) float64 {
|
||||
str := fmt.Sprintf("%.3f", float64(price)/float64(1000))
|
||||
dollar, _ := strconv.ParseFloat(str, 64)
|
||||
return dollar
|
||||
}
|
||||
|
||||
19
utils/order/order.go
Normal file
19
utils/order/order.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package order
|
||||
|
||||
type AmountCurrency struct {
|
||||
ExchangeRate float64 `json:"exchange_rate"` // 换算汇率
|
||||
CurrentAmount float64 `json:"current_amount"` // 当前金额
|
||||
OriginalAmount float64 `json:"original_amount"` // 原始金额
|
||||
CurrentCurrency string `json:"current_currency"` // 当前货币
|
||||
OriginalCurrency string `json:"original_currency"` // 原始货币
|
||||
}
|
||||
|
||||
// 汇率换算
|
||||
func GetAmountCurrency(req *AmountCurrency) error {
|
||||
if req.CurrentCurrency == req.OriginalCurrency {
|
||||
req.CurrentAmount = req.OriginalAmount
|
||||
} else {
|
||||
req.CurrentAmount = req.OriginalAmount * req.ExchangeRate
|
||||
}
|
||||
return nil
|
||||
}
|
||||
41
utils/shopping_cart/shopping_cart_snapshot.go
Normal file
41
utils/shopping_cart/shopping_cart_snapshot.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package shopping_cart
|
||||
|
||||
// 购物车快照数据结构
|
||||
type CartSnapshot struct {
|
||||
Logo string `json:"logo"` //logo地址
|
||||
CombineImage string `json:"combine_image"` //刀版图地址
|
||||
RenderImage string `json:"render_image"` //渲染结果图
|
||||
TemplateInfo TemplateInfo `json:"template_info"` //模板数据
|
||||
ModelInfo ModelInfo `json:"model_info"` //模型的数据
|
||||
FittingInfo FittingInfo `json:"fitting_info"` //配件信息
|
||||
SizeInfo SizeInfo `json:"size_info"` //尺寸基本信息
|
||||
ProductInfo ProductInfo `json:"product_info"` //产品基本信息(只记录不要使用)
|
||||
UserDiyInformation UserDiyInformation `json:"user_diy_information"` //用户diy数据
|
||||
}
|
||||
type ProductInfo struct {
|
||||
ProductName string `json:"product_name"`
|
||||
ProductSn string `json:"product_sn"`
|
||||
}
|
||||
type ModelInfo struct {
|
||||
ModelJson string `json:"model_json"` //模型设计json数据
|
||||
}
|
||||
type FittingInfo struct {
|
||||
FittingJson string `json:"fitting_json"` //配件设计json数据
|
||||
FittingName string `json:"fitting_name"` //配件名称
|
||||
}
|
||||
type TemplateInfo struct {
|
||||
TemplateJson string `json:"template_json"` //模板设计json数据
|
||||
TemplateTag string `json:"template_tag"` //模板标签
|
||||
}
|
||||
type SizeInfo struct {
|
||||
Inch string `json:"inch"`
|
||||
Cm string `json:"cm"`
|
||||
Capacity string `json:"capacity"`
|
||||
}
|
||||
type UserDiyInformation struct {
|
||||
Phone string `json:"phone"` //电话
|
||||
Address string `json:"address"` //地址
|
||||
Website string `json:"website"` //网站
|
||||
Qrcode string `json:"qrcode"` //二维码
|
||||
Slogan string `json:"slogan"` //slogan
|
||||
}
|
||||
102
utils/shopping_cart/verify_shopping_cart_channged.go
Normal file
102
utils/shopping_cart/verify_shopping_cart_channged.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package shopping_cart
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/hash"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 校验购物车快照数据跟目前是否一致
|
||||
type VerifyShoppingCartSnapshotDataChangeReq struct {
|
||||
Carts []gmodel.FsShoppingCart
|
||||
MapSize map[int64]gmodel.FsProductSize
|
||||
MapModel map[int64]gmodel.FsProductModel3d //模型跟配件都在
|
||||
MapTemplate map[int64]gmodel.FsProductTemplateV2
|
||||
MapCartChange map[int64]string
|
||||
MapSnapshot map[int64]CartSnapshot
|
||||
MapProduct map[int64]struct{}
|
||||
}
|
||||
|
||||
func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChangeReq) error {
|
||||
for _, cartInfo := range req.Carts {
|
||||
descrptionBuilder := strings.Builder{}
|
||||
//产品下架/删除
|
||||
if _, ok := req.MapProduct[*cartInfo.ProductId]; !ok {
|
||||
descrptionBuilder.WriteString("<p>the product is off shelf or deleted </p>")
|
||||
}
|
||||
var snapShotParseInfo CartSnapshot
|
||||
if err := json.Unmarshal([]byte(*cartInfo.Snapshot), &snapShotParseInfo); err != nil {
|
||||
return err
|
||||
}
|
||||
req.MapSnapshot[cartInfo.Id] = snapShotParseInfo
|
||||
//快照中模板设计json数据哈希值
|
||||
snapshotTemplateJsonHash := hash.JsonHashKey(snapShotParseInfo.TemplateInfo.TemplateJson)
|
||||
//快照中模型设计json数据哈希值
|
||||
snapshotModelJsonHash := hash.JsonHashKey(snapShotParseInfo.ModelInfo.ModelJson)
|
||||
//快照中配件设计json数据哈希值
|
||||
snapshotFittingJsonHash := hash.JsonHashKey(snapShotParseInfo.FittingInfo.FittingJson)
|
||||
//有模板验证模板相关
|
||||
if *cartInfo.TemplateId > 0 {
|
||||
if curTemplateInfo, ok := req.MapTemplate[*cartInfo.TemplateId]; !ok {
|
||||
descrptionBuilder.WriteString("<p>the template is lose</p>")
|
||||
} else {
|
||||
//当前模板设计json数据哈希值
|
||||
curTemplateJsonHash := hash.JsonHashKey(*curTemplateInfo.TemplateInfo)
|
||||
//模板设计信息改变了
|
||||
if snapshotTemplateJsonHash != curTemplateJsonHash {
|
||||
descrptionBuilder.WriteString("<p>the template design info has changed</p>")
|
||||
}
|
||||
//模板标签改变了
|
||||
if snapShotParseInfo.TemplateInfo.TemplateTag != *curTemplateInfo.TemplateTag {
|
||||
descrptionBuilder.WriteString("<p>the template`s template tag has changed</p>")
|
||||
}
|
||||
}
|
||||
}
|
||||
//有模型验证模型相关
|
||||
if *cartInfo.ModelId > 0 {
|
||||
if curModelInfo, ok := req.MapModel[*cartInfo.ModelId]; !ok { //不存在
|
||||
descrptionBuilder.WriteString("<p>the model is lose</p>")
|
||||
} else {
|
||||
//当前模型设计json数据哈希值
|
||||
curModelJsonHash := hash.JsonHashKey(*curModelInfo.ModelInfo)
|
||||
if snapshotModelJsonHash != curModelJsonHash {
|
||||
descrptionBuilder.WriteString("<p>the model design info has changed</p>")
|
||||
}
|
||||
}
|
||||
}
|
||||
//有配件验证配件相关
|
||||
if *cartInfo.FittingId > 0 {
|
||||
if curFittingInfo, ok := req.MapModel[*cartInfo.FittingId]; !ok { //不存在
|
||||
descrptionBuilder.WriteString("<p>the fitting is lose</p>")
|
||||
} else {
|
||||
//当前配件设计json数据哈希值
|
||||
curFittingJsonHash := hash.JsonHashKey(*curFittingInfo.ModelInfo)
|
||||
if snapshotFittingJsonHash != curFittingJsonHash {
|
||||
descrptionBuilder.WriteString("<p>the fitting design info has changed</p>")
|
||||
}
|
||||
}
|
||||
}
|
||||
//验证尺寸相关
|
||||
if *cartInfo.SizeId > 0 {
|
||||
curSize, ok := req.MapSize[*cartInfo.SizeId]
|
||||
if !ok {
|
||||
descrptionBuilder.WriteString("<p>the size is lose</p>")
|
||||
} else {
|
||||
var curSizeTitle SizeInfo
|
||||
if err := json.Unmarshal([]byte(*curSize.Title), &curSizeTitle); err != nil {
|
||||
return err
|
||||
}
|
||||
if snapShotParseInfo.SizeInfo.Inch != curSizeTitle.Inch || snapShotParseInfo.SizeInfo.Cm != curSizeTitle.Cm {
|
||||
descrptionBuilder.WriteString("<p>the size design info has changed</p>")
|
||||
}
|
||||
}
|
||||
}
|
||||
//收集错误
|
||||
descrption := descrptionBuilder.String()
|
||||
if descrption != "" {
|
||||
req.MapCartChange[cartInfo.Id] = descrption
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -3,20 +3,20 @@ package step_price
|
||||
// 返回美元
|
||||
func GetStepPrice(minBuyNum int, stepNum []int, stepPrice []int) float64 {
|
||||
if minBuyNum > stepNum[len(stepNum)-1] {
|
||||
return float64(stepPrice[len(stepPrice)-1]) / float64(100)
|
||||
return float64(stepPrice[len(stepPrice)-1]) / float64(1000)
|
||||
}
|
||||
for k, v := range stepNum {
|
||||
if minBuyNum <= v {
|
||||
if k <= (len(stepPrice) - 1) {
|
||||
return float64(stepPrice[k]) / float64(100)
|
||||
return float64(stepPrice[k]) / float64(1000)
|
||||
}
|
||||
return float64(stepPrice[len(stepPrice)-1]) / float64(100)
|
||||
return float64(stepPrice[len(stepPrice)-1]) / float64(1000)
|
||||
}
|
||||
}
|
||||
return float64(stepPrice[len(stepPrice)-1]) / float64(100)
|
||||
return float64(stepPrice[len(stepPrice)-1]) / float64(1000)
|
||||
}
|
||||
|
||||
// 返回美分
|
||||
// 返回厘
|
||||
func GetCentStepPrice(minBuyNum int, stepNum []int, stepPrice []int) int64 {
|
||||
if minBuyNum > stepNum[len(stepNum)-1] {
|
||||
return int64(stepPrice[len(stepPrice)-1])
|
||||
|
||||
Reference in New Issue
Block a user