瀏覽代碼

Merge branch 'yun-group-buy' of k.zhang/duoduo into yun-test

k.zhang 1 月之前
父節點
當前提交
d9357174c4

+ 83 - 10
apis/shanghu/active.pay.go

@@ -326,6 +326,11 @@ func GroupBuyCancel(c *gin.Context) {
 		return
 	}
 
+	if transInfo.AccountStatus == shanghu.ClientActivePayTransAccountStatusSettlePending {
+		app.Error(c, 500, errors.New("正在分账中"), "正在分账中")
+		return
+	}
+
 	//查看核销次数
 	//是否可以核销,默认不可以核销,只要有一个可以核销就为true
 	isCancel := false
@@ -345,8 +350,8 @@ func GroupBuyCancel(c *gin.Context) {
 			isCancel = true
 			for i := 0; i < projectInfo.CancelNum; i++ {
 				var activeCancelLogInfo shanghu.ActiveCancelLog
-				activeCancelLogInfo.ActiveConfigID = payTrans.ActiveConfigID
-				activeCancelLogInfo.ClientOpenID = payTrans.ClientOpenID
+				activeCancelLogInfo.ActiveConfigID = transInfo.ActiveConfigID
+				activeCancelLogInfo.ClientOpenID = transInfo.ClientOpenID
 				activeCancelLogInfo.MerchantOpenID = inData.OpenId
 				activeCancelLogInfo.GroupByProjectID = v.ID
 				activeCancelLogInfo.CreatedAt = time.Now()
@@ -364,7 +369,7 @@ func GroupBuyCancel(c *gin.Context) {
 	}
 
 	// 分账
-	if transInfo.AccountStatus != shanghu.ClientActivePayTransAccountStatusUnSettle && transInfo.AccountStatus != shanghu.ClientActivePayTransAccountStatusSettleFail {
+	if transInfo.AccountStatus == shanghu.ClientActivePayTransAccountStatusSettleSuccess {
 		//不需要分账
 		var activeCancel shanghu.ActiveCancelLog
 		err = activeCancel.TXActiveCancelLogCreate(activeCancelLogList)
@@ -373,20 +378,46 @@ func GroupBuyCancel(c *gin.Context) {
 			return
 		}
 	} else { // 需要分账
+		// 分账中
+		payTrans.ID = transInfo.ID
+		payTrans.AccountStatus = shanghu.ClientActivePayTransAccountStatusSettlePending
+		err = payTrans.UpdateAccountStatusByID()
+		if err != nil {
+			dataErr := make(map[string]interface{})
+			dataErr["account_status"] = shanghu.ClientActivePayTransAccountStatusSettleFail //分账失败
+			dataErr["account_err_log"] = "修改分账中失败:" + err.Error()                           //分账失败日志
+			dataErr["updated_at"] = time.Now()
+			_ = payTrans.UpdateById(dataErr)
+
+			app.Error(c, 500, err, err.Error())
+			return
+		}
+
 		//校验是否被分过,分过后不再分账
 		var merchantAccountLog shanghu.MerchantAccountLog
-		merchantAccountLog.PayTransId = payTrans.ID
+		merchantAccountLog.PayTransId = transInfo.ID
 		merchantAccountLog.TransType = shanghu.MerchantAccountLogTransTypeGroupBuy
 		num := merchantAccountLog.GetAccountLogNum()
 		if num > 0 { //交易已经分过账
+			dataErr := make(map[string]interface{})
+			dataErr["account_status"] = shanghu.ClientActivePayTransAccountStatusSettleFail //分账失败
+			dataErr["account_err_log"] = "交易已分过账"                                           //分账失败日志
+			dataErr["updated_at"] = time.Now()
+			_ = payTrans.UpdateById(dataErr)
 			app.Error(c, 500, errors.New("交易已分过账"), "交易已分过账")
 			return
 		}
 		//分账校验账号
 		var merchantAccount shanghu.MerchantAccount
-		merchantAccount.MerchantOpenID = payTrans.MerchantOpenID
+		merchantAccount.MerchantOpenID = transInfo.MerchantOpenID
 		merchantAccountInfo, err := merchantAccount.GetMerchantAccount()
 		if err != nil && err.Error() != "record not found" {
+			dataErr := make(map[string]interface{})
+			dataErr["account_status"] = shanghu.ClientActivePayTransAccountStatusSettleFail //分账失败
+			dataErr["account_err_log"] = "商家分账校验账号:" + err.Error()                          //分账失败日志
+			dataErr["updated_at"] = time.Now()
+			_ = payTrans.UpdateById(dataErr)
+
 			app.Error(c, 500, err, err.Error())
 			return
 		}
@@ -395,25 +426,46 @@ func GroupBuyCancel(c *gin.Context) {
 			merchantAccount.Version = 1
 			merchantAccount.CreatedAt = time.Now()
 			merchantAccount.UpdatedAt = time.Now()
-			_, err = merchantAccount.Create()
+			merchantAccount, err = merchantAccount.Create()
 			if err != nil {
+
+				dataErr := make(map[string]interface{})
+				dataErr["account_status"] = shanghu.ClientActivePayTransAccountStatusSettleFail //分账失败
+				dataErr["account_err_log"] = "创建新的商家账号:" + err.Error()                          //分账失败日志
+				dataErr["updated_at"] = time.Now()
+				_ = payTrans.UpdateById(dataErr)
+
 				app.Error(c, 500, err, err.Error())
 				return
 			}
 
 		}
-		if payTrans.InvitationCode != shanghu.YuanShiMa { //校验c端客户
+		var clientAccount shanghu.ActiveClientAccount
+		if transInfo.InvitationCode != shanghu.YuanShiMa { //校验c端客户
 			var activeUser shanghu.ActiveUser
-			var clientAccount shanghu.ActiveClientAccount
-			activeUser.Code = payTrans.InvitationCode
+			activeUser.Code = transInfo.InvitationCode
 			activeUserInfo, err := activeUser.GetUserInfoByCode()
 			if err != nil {
+
+				dataErr := make(map[string]interface{})
+				dataErr["account_status"] = shanghu.ClientActivePayTransAccountStatusSettleFail         //分账失败
+				dataErr["account_err_log"] = "根据Code获取c端客户信息:" + transInfo.InvitationCode + err.Error() //分账失败日志
+				dataErr["updated_at"] = time.Now()
+				_ = payTrans.UpdateById(dataErr)
+
 				app.Error(c, 500, err, err.Error())
 				return
 			}
 			clientAccount.ClientOpenID = activeUserInfo.OpenID
 			clientAccountInfo, err := clientAccount.GetMerchantAccount()
 			if err != nil && err.Error() != "record not found" {
+
+				dataErr := make(map[string]interface{})
+				dataErr["account_status"] = shanghu.ClientActivePayTransAccountStatusSettleFail //分账失败
+				dataErr["account_err_log"] = "获取c端客户账户:" + err.Error()                          //分账失败日志
+				dataErr["updated_at"] = time.Now()
+				_ = payTrans.UpdateById(dataErr)
+
 				app.Error(c, 500, err, err.Error())
 				return
 			}
@@ -423,8 +475,15 @@ func GroupBuyCancel(c *gin.Context) {
 				clientAccount.Version = 1
 				clientAccount.CreatedAt = time.Now()
 				clientAccount.UpdatedAt = time.Now()
-				_, err = clientAccount.Create()
+				clientAccount, err = clientAccount.Create()
 				if err != nil {
+
+					dataErr := make(map[string]interface{})
+					dataErr["account_status"] = shanghu.ClientActivePayTransAccountStatusSettleFail //分账失败
+					dataErr["account_err_log"] = "创建c端客户:" + err.Error()                            //分账失败日志
+					dataErr["updated_at"] = time.Now()
+					_ = payTrans.UpdateById(dataErr)
+
 					app.Error(c, 500, err, err.Error())
 					return
 				}
@@ -434,7 +493,21 @@ func GroupBuyCancel(c *gin.Context) {
 		}
 
 		//分账 根据merchant-openid + activeUserInfo.openid 进行分账
+		//商家分多少钱,客户分多少钱
+		err = merchantAccount.ActiveCancelSettle(activeCancelLogList, merchantAccount, clientAccount, transInfo)
+		if err != nil {
+
+			dataErr := make(map[string]interface{})
+			dataErr["account_status"] = shanghu.ClientActivePayTransAccountStatusSettleFail //分账失败
+			dataErr["account_err_log"] = "分账失败:" + err.Error()                              //分账失败日志
+			dataErr["updated_at"] = time.Now()
+			_ = payTrans.UpdateById(dataErr)
+
+			app.Error(c, 500, err, err.Error())
+			return
+		}
 
 	}
+	app.OK(c, nil, app.Success)
 
 }

+ 2 - 1
apis/shanghu/base.go

@@ -98,7 +98,8 @@ func InitShangHuRouter(engine *gin.RouterGroup) {
 		activeV1.POST("/active/group.buy/code", GroupBuyPayCode)            //拼团核销码
 		activeV1.POST("/active/group.buy/pay", GetGroupBuyPayList)          //购买拼团列表
 		//提现
-		activeV1.POST("/active/draw/count", ActiveDrawCount) //邀请客户数量统计
+		activeV1.POST("/active/draw/count", ActiveDrawCount)  //邀请客户数量统计
+		activeV1.POST("/client/user/info", GetActiveUserInfo) //client 用户信息
 
 	}
 }

+ 22 - 0
apis/shanghu/merchant.user.go

@@ -224,6 +224,28 @@ func ClientGetUserInfo(c *gin.Context) {
 
 }
 
+func GetActiveUserInfo(c *gin.Context) {
+	var inData models.GetUserInfoRequest
+	var sqlData shanghu.ActiveUser
+
+	err := c.ShouldBindJSON(&inData)
+	if err != nil {
+		app.Error(c, 400, err, err.Error())
+		return
+	}
+
+	//查询数据
+	sqlData.OpenID = inData.OpenId
+	userInfo, err := sqlData.GetUserInfo()
+	if err != nil {
+		app.Error(c, 500, err, err.Error())
+		return
+	}
+
+	app.OK(c, userInfo, app.Success)
+
+}
+
 func MerchantUserCode(c *gin.Context) {
 	var inData models.MerchantUserCodeRequest
 	var sqlData shanghu.MerchantUser

+ 26 - 18
models/shanghu/active.account.log.go

@@ -1,24 +1,32 @@
 package shanghu
 
-import "time"
+import (
+	"github.com/shopspring/decimal"
+	"time"
+)
 
-type ActiveAccountLog struct {
-	ID                int64     `gorm:"column:id;type:bigint(20);primary_key;AUTO_INCREMENT" json:"id"`           // 主键
-	ReviewAmountAfter string    `gorm:"column:review_amount_after;type:decimal(10,2)" json:"review_amount_after"` // 审核资金 交易后
-	ReviewAmountPre   string    `gorm:"column:review_amount_pre;type:decimal(10,2)" json:"review_amount_pre"`     // 审核资金 交易前
-	AmountPre         string    `gorm:"column:amount_pre;type:decimal(10,2)" json:"amount_pre"`                   // 交易前
-	AmountAfter       string    `gorm:"column:amount_after;type:decimal(10,2)" json:"amount_after"`               // 交易后
-	TransType         int       `gorm:"column:trans_type;type:int(11)" json:"trans_type"`                         // 交易类型  1-买卡入待审核 2-核销入账  3-提现
-	MerchantOpenID    string    `gorm:"column:merchant_open_id;type:varchar(255)" json:"merchant_open_id"`        // 商户openid
-	CreateBy          int64     `gorm:"column:create_by;type:bigint(20)" json:"create_by"`                        // 创建者
-	UpdateBy          int64     `gorm:"column:update_by;type:bigint(20)" json:"update_by"`                        // 更新者
-	CreatedAt         time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"`                     // 创建时间
-	UpdatedAt         time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"`                     // 最后更新时间
-	DeletedAt         time.Time `gorm:"column:deleted_at;type:datetime(3);default:null" json:"deleted_at"`        // 删除时间
-	Amount            string    `gorm:"column:amount;type:decimal(10,2)" json:"amount"`                           // 交易金额
-	PayTransID        int64     `gorm:"column:pay_trans_id;type:bigint(20)" json:"pay_trans_id"`                  // 交易id
+type ActiveClientAccountLog struct {
+	ID                int64           `gorm:"column:id;type:bigint(20);primary_key;AUTO_INCREMENT" json:"id"`           // 主键
+	ReviewAmountAfter decimal.Decimal `gorm:"column:review_amount_after;type:decimal(10,2)" json:"review_amount_after"` // 审核资金 交易后
+	ReviewAmountPre   decimal.Decimal `gorm:"column:review_amount_pre;type:decimal(10,2)" json:"review_amount_pre"`     // 审核资金 交易前
+	AmountPre         decimal.Decimal `gorm:"column:amount_pre;type:decimal(10,2)" json:"amount_pre"`                   // 交易前
+	AmountAfter       decimal.Decimal `gorm:"column:amount_after;type:decimal(10,2)" json:"amount_after"`               // 交易后
+	TransType         int             `gorm:"column:trans_type;type:int(11)" json:"trans_type"`                         // 交易类型 1-拼团核销入账  3-提现
+	ClientOpenID      string          `gorm:"column:client_open_id;type:varchar(255)" json:"client_open_id"`            // 客户openid
+	CreateBy          int64           `gorm:"column:create_by;type:bigint(20)" json:"create_by"`                        // 创建者
+	UpdateBy          int64           `gorm:"column:update_by;type:bigint(20)" json:"update_by"`                        // 更新者
+	CreatedAt         time.Time       `gorm:"column:created_at;type:datetime(3)" json:"created_at"`                     // 创建时间
+	UpdatedAt         time.Time       `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"`                     // 最后更新时间
+	DeletedAt         time.Time       `gorm:"column:deleted_at;type:datetime(3)" json:"deleted_at"`                     // 删除时间
+	Amount            decimal.Decimal `gorm:"column:amount;type:decimal(10,2)" json:"amount"`                           // 交易金额
+	PayTransID        int64           `gorm:"column:pay_trans_id;type:bigint(20)" json:"pay_trans_id"`                  // 交易id
 }
 
-func (m *ActiveAccountLog) TableName() string {
-	return "active_account_log"
+const (
+	ActiveClientAccountLogTransTypeGroupBuy = 1 //拼团入账
+	ActiveClientAccountLogTypeCashOut       = 2 //提现
+)
+
+func (m *ActiveClientAccountLog) TableName() string {
+	return "active_client_account_log"
 }

+ 11 - 10
models/shanghu/actvie.client.account.go

@@ -2,20 +2,21 @@ package shanghu
 
 import (
 	orm "duoduo/database"
+	"github.com/shopspring/decimal"
 	"time"
 )
 
 type ActiveClientAccount struct {
-	ID           int64     `gorm:"column:id;type:bigint(20);primary_key;AUTO_INCREMENT" json:"id"`    // 主键
-	ClientOpenID string    `gorm:"column:client_open_id;type:varchar(255)" json:"client_open_id"`     //
-	ReviewAmount string    `gorm:"column:review_amount;type:decimal(10,2)" json:"review_amount"`      // 待核销金额
-	Version      int       `gorm:"column:version;type:int(11)" json:"version"`                        // Version
-	Amount       string    `gorm:"column:amount;type:decimal(10,2)" json:"amount"`                    // 可提现金额
-	CreateBy     int64     `gorm:"column:create_by;type:bigint(20)" json:"create_by"`                 // 创建者
-	UpdateBy     int64     `gorm:"column:update_by;type:bigint(20)" json:"update_by"`                 // 更新者
-	CreatedAt    time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"`              // 创建时间
-	UpdatedAt    time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"`              // 最后更新时间
-	DeletedAt    time.Time `gorm:"column:deleted_at;type:datetime(3);default:null" json:"deleted_at"` // 删除时间
+	ID           int64           `gorm:"column:id;type:bigint(20);primary_key;AUTO_INCREMENT" json:"id"`    // 主键
+	ClientOpenID string          `gorm:"column:client_open_id;type:varchar(255)" json:"client_open_id"`     //
+	ReviewAmount decimal.Decimal `gorm:"column:review_amount;type:decimal(10,2)" json:"review_amount"`      // 待核销金额
+	Version      int             `gorm:"column:version;type:int(11)" json:"version"`                        // Version
+	Amount       decimal.Decimal `gorm:"column:amount;type:decimal(10,2)" json:"amount"`                    // 可提现金额
+	CreateBy     int64           `gorm:"column:create_by;type:bigint(20)" json:"create_by"`                 // 创建者
+	UpdateBy     int64           `gorm:"column:update_by;type:bigint(20)" json:"update_by"`                 // 更新者
+	CreatedAt    time.Time       `gorm:"column:created_at;type:datetime(3)" json:"created_at"`              // 创建时间
+	UpdatedAt    time.Time       `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"`              // 最后更新时间
+	DeletedAt    time.Time       `gorm:"column:deleted_at;type:datetime(3);default:null" json:"deleted_at"` // 删除时间
 }
 
 func (m *ActiveClientAccount) TableName() string {

+ 19 - 0
models/shanghu/client.active.pay.trans.go

@@ -192,3 +192,22 @@ func (m *ClientActivePayTrans) TXSettle(payInfo ClientActivePayTrans) error {
 	//商家加款 c端用户加款
 	return nil
 }
+
+func (m *ClientActivePayTrans) UpdateAccountStatusByID() error {
+
+	if err := orm.ShMysql.Table(m.TableName()).Model(&m).Where("id = ? ", m.ID).Updates(
+		map[string]interface{}{
+			"account_status": m.Status,
+			"updated_at":     time.Now()}).Error; err != nil {
+		return err
+	}
+	return nil
+}
+
+func (m *ClientActivePayTrans) UpdateById(data map[string]interface{}) error {
+	err := orm.ShMysql.Table(m.TableName()).Where("id = ?", m.ID).Updates(data).Error
+	if err != nil {
+		return err
+	}
+	return nil
+}

+ 114 - 0
models/shanghu/merchant.account.go

@@ -2,6 +2,7 @@ package shanghu
 
 import (
 	orm "duoduo/database"
+	"errors"
 	"github.com/shopspring/decimal"
 	"time"
 )
@@ -49,3 +50,116 @@ func (m *MerchantAccount) Create() (MerchantAccount, error) {
 
 	return doc, nil
 }
+
+// 拼团核销与分账
+func (m *MerchantAccount) ActiveCancelSettle(log []ActiveCancelLog, merchantAccount MerchantAccount, activeClientAccount ActiveClientAccount, payTrans ClientActivePayTrans) error {
+	var err error
+	var merchantAccountLog MerchantAccountLog
+	var clientAccountLog ActiveClientAccountLog
+
+	tx := orm.ShMysql.Begin()
+	defer func() {
+		if err != nil {
+			tx.Rollback()
+		} else {
+			tx.Commit()
+		}
+	}()
+
+	//核销日志
+	for i := 0; i < len(log); i++ {
+		err = tx.Table(log[i].TableName()).Create(&log[i]).Error
+		if err != nil {
+			return err
+		}
+	}
+
+	//分账
+	//商家加款
+	merchantAmountAdd := merchantAccount.Amount.Add(payTrans.MerchantAmount)
+	result := tx.Table("merchant_account").Model(&merchantAccount).Where("merchant_open_id = ? and version = ?", merchantAccount.MerchantOpenID, merchantAccount.Version).Updates(
+		map[string]interface{}{
+			"amount":     merchantAmountAdd,
+			"version":    merchantAccount.Version + 1,
+			"updated_at": time.Now()})
+
+	if result.Error != nil {
+		err = result.Error
+		return err
+	}
+	if result.RowsAffected <= 0 {
+		err = errors.New("rows is zero")
+		return err
+	}
+
+	merchantAccountLog.MerchantOpenID = merchantAccount.MerchantOpenID
+	merchantAccountLog.UpdatedAt = time.Now()
+	merchantAccountLog.AmountPre = merchantAccount.Amount
+	merchantAccountLog.AmountAfter = merchantAmountAdd
+	merchantAccountLog.ReviewAmountAfter = merchantAccount.ReviewAmount
+	merchantAccountLog.ReviewAmountPre = merchantAccount.ReviewAmount
+	merchantAccountLog.Amount = payTrans.MerchantAmount
+	merchantAccountLog.PayTransId = payTrans.ID
+	merchantAccountLog.TransType = MerchantAccountLogTransTypeGroupBuy
+	err = tx.Table("merchant_account_log").Create(&merchantAccountLog).Error
+	if err != nil {
+		return err
+	}
+
+	//err = tx.Table("merchant_account_log").Create(&merchantAccountLog).Error
+	//if err != nil {
+	//	return err
+	//}
+
+	// 客户加款
+	if activeClientAccount.ID > 0 {
+		clientAmountAdd := activeClientAccount.Amount.Add(payTrans.ClientAmount)
+		clientResult := tx.Table("active_client_account").Model(&activeClientAccount).Where("client_open_id = ? and version = ?", merchantAccount.MerchantOpenID, merchantAccount.Version).Updates(
+			map[string]interface{}{
+				"amount":     clientAmountAdd,
+				"version":    activeClientAccount.Version + 1,
+				"updated_at": time.Now()})
+
+		if clientResult.Error != nil {
+			err = clientResult.Error
+			return err
+		}
+		if clientResult.RowsAffected <= 0 {
+			err = errors.New("rows is zero")
+			return err
+		}
+
+		clientAccountLog.ClientOpenID = activeClientAccount.ClientOpenID
+		clientAccountLog.UpdatedAt = time.Now()
+		clientAccountLog.AmountPre = activeClientAccount.Amount
+		clientAccountLog.AmountAfter = clientAmountAdd
+		clientAccountLog.ReviewAmountAfter = activeClientAccount.ReviewAmount
+		clientAccountLog.ReviewAmountPre = activeClientAccount.ReviewAmount
+		clientAccountLog.Amount = payTrans.ClientAmount
+		clientAccountLog.PayTransID = payTrans.ID
+		clientAccountLog.TransType = ActiveClientAccountLogTransTypeGroupBuy
+		err = tx.Table("merchant_account_log").Create(&merchantAccountLog).Error
+		if err != nil {
+			return err
+		}
+
+	}
+	//更新状态
+	var activePay ClientActivePayTrans
+	resultPay := tx.Table("client_active_pay_trans").Model(&activePay).Where("id = ? ", payTrans.ID).Updates(
+		map[string]interface{}{
+			"account_status": ClientActivePayTransAccountStatusSettleSuccess,
+			"updated_at":     time.Now()})
+
+	if resultPay.Error != nil {
+		err = resultPay.Error
+		return err
+	}
+	if resultPay.RowsAffected <= 0 {
+		err = errors.New("pay rows is zero")
+		return err
+	}
+
+	return nil
+
+}