order_payment.go 8.7 KB
package service

import (
	"fmt"
	"github.com/linmadan/egglib-go/core/application"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/order_payment/command"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/order_payment/query"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/utils"
	"time"

	//"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/order_payment/query"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)

// 客户价值服务
type OrderPaymentService struct {
}

func NewOrderPaymentService(options map[string]interface{}) *OrderPaymentService {
	newOrderPaymentService := &OrderPaymentService{}
	return newOrderPaymentService
}

// 创建订单支付数据
func (OrderPaymentService *OrderPaymentService) CreateOrderPayment(command *command.CreateOrderPaymentCommand) (data interface{}, err error) {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		OrderDao, _           = factory.CreateOrderDao(map[string]interface{}{"transactionContext": transactionContext})
		OrderPaymentDao, _    = factory.CreateOrderPaymentDao(map[string]interface{}{"transactionContext": transactionContext})
	)
	if err = command.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, err.Error())
	}
	if err = transactionContext.StartTransaction(); err != nil {
		return nil, err
	}
	defer func() {
		if err == nil {
			err = transactionContext.CommitTransaction()
		}
		if err != nil {
			transactionContext.RollbackTransaction()
		}
	}()
	//检查订单是否存在

	var OrderPaymentRepository domain.OrderPaymentRepository
	if OrderPaymentRepository, err = factory.CreateOrderPaymentRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	orderBase, e := OrderDao.GetOrderBaseInfo(command.OrderId)
	if e != nil {
		err = e
		return
	}
	var excludeIdList []int
	var bonusStatus int = domain.BonusPaid //分红状态
	excludeIdList = append(excludeIdList, 0)
	for i := range command.DivdendPaymentItem {
		paymentItem := command.DivdendPaymentItem[i]
		dm := &domain.OrderPayment{
			OrderId:  command.OrderId,
			CreateAt: time.Now(),
			UpdateAt: time.Now(),
		}
		if bonusStatus == domain.BonusPaid && paymentItem.StateOfPayment == domain.BonusWaitPay {
			bonusStatus = domain.BonusWaitPay
		}
		if paymentItem.PaymentId > 0 {
			//检查货款 已存在 / 未存在
			if findDm, e := OrderPaymentRepository.FindOne(domain.OrderPaymentFindOneQuery{OrderId: command.OrderId, PaymentId: paymentItem.PaymentId}); e == nil {
				//状态更金额一样的时候 不做更新
				if findDm.BonusStatus == paymentItem.StateOfPayment && findDm.PaymentAmount == paymentItem.PaymentForGoods {
					excludeIdList = append(excludeIdList, paymentItem.PaymentId)
					continue
				}
				dm = findDm
			}
		}
		dm.PartnerId = orderBase["PartnerId"].(int64)
		bonusPercent := orderBase["PartnerBonusPercent"].(float64)
		dm.BonusAmount = utils.Decimal(paymentItem.PaymentForGoods * (bonusPercent / 100.0))
		dm.PaymentAmount = paymentItem.PaymentForGoods
		dm.BonusStatus = paymentItem.StateOfPayment
		dm.UpdateAt = time.Now()
		if data, err = OrderPaymentRepository.Save(dm); err != nil {
			return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
		}
		excludeIdList = append(excludeIdList, int(dm.Id))
	}

	if err = OrderPaymentDao.Remove(command.OrderId, domain.BonusWaitPay, excludeIdList); err != nil {
		return
	}
	if err = OrderDao.Update(map[string]interface{}{"id": command.OrderId, "orderPaymentAmount": command.TotalPaymentAmount, "bonusStatus": bonusStatus}); err != nil {
		return
	}

	return
}

// 返回订单支付列表
func (OrderPaymentService *OrderPaymentService) ListOrderPayment(listOrderPaymentQuery *query.GetOrderPaymentQuery) ([]*domain.OrderPayment, error) {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		OrderDao, _           = factory.CreateOrderDao(map[string]interface{}{"transactionContext": transactionContext})
		OrderPayments         []*domain.OrderPayment
		err                   error
	)
	if err = listOrderPaymentQuery.ValidateQuery(); err != nil {
		return nil, lib.ThrowError(lib.ARG_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var OrderPaymentRepository domain.OrderPaymentRepository
	if OrderPaymentRepository, err = factory.CreateOrderPaymentRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	queryOption := domain.OrderPaymentQuery{
		OrderId: listOrderPaymentQuery.OrderId,
	}
	_, e := OrderDao.GetOrderBaseInfo(listOrderPaymentQuery.OrderId)
	if e != nil {
		return nil, e
	}
	if OrderPayments, err = OrderPaymentRepository.Find(queryOption); err != nil {
		return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err = transactionContext.CommitTransaction(); err != nil {
		return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
	}
	return OrderPayments, nil
}

// 返回分红管理列表
func (OrderPaymentService *OrderPaymentService) ListDividendOrders(listOrderPaymentQuery *query.ListDividendOrdersQuery) (int, interface{}, error) {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		//OrderPayments         []*domain.OrderPayment
		count       int
		err         error
		OrderDao, _ = factory.CreateOrderDao(map[string]interface{}{"transactionContext": transactionContext})
		orders      []*models.Order
	)
	if err = listOrderPaymentQuery.ValidateQuery(); err != nil {
		return 0, nil, lib.ThrowError(lib.ARG_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return 0, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	if count, orders, err = OrderDao.GetDividendOrders(map[string]interface{}{
		"orderCode": listOrderPaymentQuery.SearchText,
		"partnerId": listOrderPaymentQuery.PartnerId,
		"orderType": 1,
		"offset":    (listOrderPaymentQuery.PageNumber - 1) * listOrderPaymentQuery.PageSize,
		"limit":     listOrderPaymentQuery.PageSize,
	}); err != nil {
		return 0, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}

	type DividendOrderItem struct {
		OrderId              string  `json:"id"`                   //订单编号
		OrderNumber          string  `json:"orderNumber"`          //订单号
		OrderState           int     `json:"orderState"`           //订单状态
		StateOfPayment       int     `json:"stateOfPayment"`       //支付状态
		CreateTime           string  `json:"createTime"`           //订单创建时间
		PartnerName          string  `json:"partnerName"`          //合伙人姓名
		DividendProportion   float64 `json:"dividendProportion"`   //分红比例
		DividendsReceivable  float64 `json:"dividendsReceivable"`  //应收分红
		DividendSpending     float64 `json:"dividendSpending"`     //分红支出
		ReceiveDividends     float64 `json:"receiveDividends"`     //实收分红
		CommissionProportion float64 `json:"commissionProportion"` //业务员抽成比例
	}
	var list = make([]DividendOrderItem, 0)
	for i := range orders {
		order := orders[i]
		item := DividendOrderItem{
			OrderId:              fmt.Sprintf("%v", order.Id),
			OrderNumber:          order.OrderCode,
			OrderState:           order.OrderStatus,
			StateOfPayment:       order.BonusStatus,
			CreateTime:           order.CreateAt.Local().Format("2006-01-02 15:04:05"),
			PartnerName:          order.PartnerInfo.PartnerName,
			DividendProportion:   order.PartnerBonusPercent,
			DividendsReceivable:  utils.Decimal(order.OrderActualAmount * (order.PartnerBonusPercent / 100.0)),
			DividendSpending:     0,
			ReceiveDividends:     utils.Decimal(order.OrderPaymentAmount * (order.PartnerBonusPercent / 100.0)),
			CommissionProportion: order.SalesmanBonusPercent,
		}
		//if order.BonusStatus == domain.BonusPaid {
		//	item.StateOfPayment = "已支付分红"
		//} else {
		//	item.StateOfPayment = "等待支付分红"
		//}
		if order.OrderActualAmount < order.OrderAmount {
			item.DividendSpending = utils.Decimal((order.OrderAmount - order.OrderActualAmount) * (order.PartnerBonusPercent / 100.0))
		}
		list = append(list, item)
	}

	if err = transactionContext.CommitTransaction(); err != nil {
		return 0, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
	}
	return count, list, nil
}