sync_order.go 12.2 KB
package service

import (
	"fmt"
	"time"

	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/dao"

	"github.com/astaxie/beego/logs"

	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/syncOrder/command"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)

//从其他系统接收订单数据
const (
	BEST_SHOP_UNIONID string = "gh_18eb644002fb" //海鲜干货小程序原始id
)

type SyncOrderService struct {
}

func NewOrderInfoService(option map[string]interface{}) *SyncOrderService {
	newService := new(SyncOrderService)
	return newService
}

//SyncOrderFromBestshop 接收来源于xiangmi小程序的订单数据
func (s SyncOrderService) SyncOrderFromBestshop(cmd command.CreateOrderFromBestshop) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()

	//检查账号是否存在
	var (
		orderBestshopDao  *dao.OrderBestshopDao
		orderExist        bool
		partnerRepository domain.PartnerInfoRepository
		partnerData       *domain.PartnerInfo
	)
	if orderBestshopDao, err = factory.CreateOrderBestshopDao(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
	}
	orderExist, err = orderBestshopDao.OrderExist(cmd.OrderCode)
	if err != nil {
		return lib.ThrowError(lib.TRANSACTION_ERROR, "orderBestshopDao.OrderExist err:"+err.Error())
	}
	//数据检查
	if partnerRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	partnerData, err = partnerRepository.FindOne(domain.PartnerFindOneQuery{UserId: cmd.PartnerId})
	if err != nil {
		e := fmt.Sprintf("未找到指定的合伙人(id=%d)数据,%s", cmd.PartnerId, err)
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
	}
	if partnerData.CompanyId != cmd.CompanyId {
		e := fmt.Sprintf("合伙人(partnerId)的公司(companyId=%d)和传递的参数中的companyId 不一致", partnerData.CompanyId)
		logs.Warning(e)
	}
	err = transactionContext.CommitTransaction()
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if orderExist {
		err = s.UpdateOrderFromBestshop(cmd)
	} else {
		err = s.CreateOrderFromBestshop(cmd)
	}

	return err
}

func (s SyncOrderService) CreateOrderFromBestshop(cmd command.CreateOrderFromBestshop) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var (
		orderBestshopRepository     domain.OrderBestshopRepository
		orderGoodBestshopRepository domain.OrderGoodBestshopRepository
	)
	if orderBestshopRepository, err = factory.CreateOrderBestshopRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if orderGoodBestshopRepository, err = factory.CreateOrderGoodBestshopRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	order := domain.OrderBestShop{
		OrderCode:     cmd.OrderCode,
		OrderTime:     cmd.OrderTime,
		OrderState:    cmd.OrderState,
		OrderCount:    cmd.OrderCount,
		OrderAmount:   cmd.OrderAmount,
		CreateTime:    time.Now(),
		PartnerId:     cmd.PartnerId,
		BuyerName:     cmd.BuyerName,
		BuyerPhone:    cmd.BuyerPhone,
		BuyerAddress:  cmd.BuyerAddress,
		BuyerRemark:   cmd.BuyerRemark,
		BuyerId:       cmd.BuyerId,
		DeliveryState: cmd.DeliveryState,
		DeliveryTime:  cmd.DeliveryTime,
		IsCopy:        false,
		CompanyId:     cmd.CompanyId,
	}
	err = orderBestshopRepository.Add(&order)
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, "添加order_bestshop失败:"+err.Error())
	}
	goods := []domain.OrderGoodBestShop{}
	for i := range cmd.Goods {
		good := domain.OrderGoodBestShop{
			Id:      cmd.Goods[i].Id,
			OrderId: order.Id,
			Sn:      cmd.Goods[i].Sn,
			Bn:      cmd.Goods[i].Bn,
			Name:    cmd.Goods[i].Name,
			Price:   cmd.Goods[i].Price,
			Nums:    cmd.Goods[i].Nums,
			Amount:  cmd.Goods[i].Amount,
		}
		err = orderGoodBestshopRepository.Add(&good)
		if err != nil {
			return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, "添加order_good失败:"+err.Error())
		}
		goods = append(goods, good)
	}
	order.Goods = goods
	err = transactionContext.CommitTransaction()
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if cmd.PartnerId <= 0 {
		logs.Info("[SyncOrderFromBestshop] PartnerId<=0 ,不复制订单数据")
		return nil
	}
	err = s.copyOrderBestshopToOrderBase(&order)
	return err
}

//copyOrderBestshopToOrderBase 复制数据
func (s SyncOrderService) copyOrderBestshopToOrderBase(orderBestshop *domain.OrderBestShop) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var (
		orderBaseRepository     domain.OrderBaseRepository
		orderGoodRepository     domain.OrderGoodRepository
		orderBestshopRepository domain.OrderBestshopRepository
		partnerRepository       domain.PartnerInfoRepository
		companyRepository       domain.CompanyRepository
	)
	if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if partnerRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if companyRepository, err = factory.CreateCompanyRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if orderBestshopRepository, err = factory.CreateOrderBestshopRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	var (
		partnerData  *domain.PartnerInfo
		companyData  domain.Company
		canCopyOrder bool
	)
	partnerData, err = partnerRepository.FindOne(domain.PartnerFindOneQuery{UserId: orderBestshop.PartnerId})
	if err != nil {
		e := fmt.Sprintf("未找到指定的合伙人(id=%d)数据,%s", orderBestshop.PartnerId, err)
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
	}
	companyData, err = companyRepository.FindOne(domain.CompanyFindOneOptions{
		Id: partnerData.CompanyId,
	})
	if err != nil {
		e := fmt.Sprintf("未找到指定的合伙人的公司(partner_id=%d,company_id=%d)数据,%s", orderBestshop.PartnerId, partnerData.CompanyId, err)
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
	}
	for _, v := range companyData.Applets {
		if v.Id == BEST_SHOP_UNIONID {
			canCopyOrder = true
		}
	}
	if !canCopyOrder {
		logs.Warning("公司未设置xiangmi小程序原始id; order_bestshop.id=%d", orderBestshop.Id)
		return nil
	}
	var (
		orderbase  domain.OrderBase
		ordergoods []domain.OrderGood
	)
	//TODO 添加orderBase
	orderBestshop.CopyToOrderBase(&orderbase)
	orderbase.CompanyId = companyData.Id
	for i := range orderBestshop.Goods {
		good := domain.NewOrderGood()
		orderBestshop.Goods[i].CopyToOrderGood(&good)
		good.CompanyId = partnerData.CompanyId
		good.Compute()
		good.CurrentBonusStatus.WartPayPartnerBonus(&good)
		ordergoods = append(ordergoods, good)
	}
	orderbase.Goods = ordergoods
	orderbase.PartnerId = partnerData.Partner.Id
	orderbase.CompanyId = partnerData.CompanyId
	orderbase.Compute()
	err = orderBaseRepository.Save(&orderbase)
	if err != nil {
		e := fmt.Sprintf("添加order_base数据失败%s", err)
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
	}
	for i := range ordergoods {
		ordergoods[i].OrderId = orderbase.Id
	}
	// 添加goods
	err = orderGoodRepository.Save(ordergoods)
	if err != nil {
		e := fmt.Sprintf("添加order_good数据失败%s", err)
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
	}
	// 更新isCopy
	orderBestshop.IsCopy = true
	err = orderBestshopRepository.Edit(orderBestshop)
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	err = transactionContext.CommitTransaction()
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	return nil
}

func (s SyncOrderService) UpdateOrderFromBestshop(cmd command.CreateOrderFromBestshop) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var (
		orderBestshopRepository     domain.OrderBestshopRepository
		orderGoodBestshopRepository domain.OrderGoodBestshopRepository
	)
	if orderBestshopRepository, err = factory.CreateOrderBestshopRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if orderGoodBestshopRepository, err = factory.CreateOrderGoodBestshopRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	var (
		orderData  *domain.OrderBestShop
		orderGoods []domain.OrderGoodBestShop
	)
	orderData, err = orderBestshopRepository.FindOne(domain.OrderBestshopFindOneQuery{
		OrderCode: cmd.OrderCode,
	})
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, "获取orderBestshop(order_code=%s)数据失败,err=%s", cmd.OrderCode, err.Error())
	}

	orderData.OrderCode = cmd.OrderCode
	orderData.OrderTime = cmd.OrderTime
	orderData.OrderState = cmd.OrderState
	orderData.OrderCount = cmd.OrderCount
	orderData.OrderAmount = cmd.OrderAmount
	orderData.PartnerId = cmd.PartnerId
	orderData.BuyerName = cmd.BuyerName
	orderData.BuyerPhone = cmd.BuyerPhone
	orderData.BuyerAddress = cmd.BuyerAddress
	orderData.BuyerRemark = cmd.BuyerRemark
	orderData.BuyerId = cmd.BuyerId
	orderData.DeliveryState = cmd.DeliveryState
	orderData.DeliveryTime = cmd.DeliveryTime
	orderData.CompanyId = cmd.CompanyId
	err = orderBestshopRepository.Edit(orderData)
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, "编辑order_bestshop失败:"+err.Error())
	}
	orderGoods, err = orderGoodBestshopRepository.Find(domain.OrderGoodBestshopFindQuery{
		OrderId: orderData.Id,
	})
	if err != nil {
		e := fmt.Sprintf("获取orderGoodBestshop(order_id=%d)数据失败,err=%s", orderData.Id, err.Error())
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
	}

	for i := range orderGoods {
		var updated bool
		for ii := range cmd.Goods {
			if cmd.Goods[ii].Id != orderGoods[i].Id {
				continue
			}
			orderGoods[i].Sn = cmd.Goods[ii].Sn
			orderGoods[i].Bn = cmd.Goods[ii].Bn
			orderGoods[i].Name = cmd.Goods[ii].Name
			orderGoods[i].Price = cmd.Goods[ii].Price
			orderGoods[i].Nums = cmd.Goods[ii].Nums
			orderGoods[i].Amount = cmd.Goods[ii].Amount
			updated = true
		}
		if updated {
			err = orderGoodBestshopRepository.Edit(&orderGoods[i])
			if err != nil {
				logs.Error("更新order_good_bestshop失败:" + err.Error())
			}
		}
	}
	err = transactionContext.CommitTransaction()
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	return nil
}