pg_order_base_dao.go 10.4 KB
package dao

import (
	"fmt"

	"github.com/go-pg/pg/v10/orm"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
)

type OrderBaseDao struct {
	transactionContext *transaction.TransactionContext
}

func NewOrderBaseDao(transactionContext *transaction.TransactionContext) (*OrderBaseDao, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &OrderBaseDao{
			transactionContext: transactionContext,
		}, nil
	}
}

//OrderCodeExist 检查order_code是否重复
//
func (dao OrderBaseDao) OrderCodeExist(code string, partnerCategory int64, partnerId int64) (bool, error) {
	tx := dao.transactionContext.GetDB()
	m := &models.OrderBase{}
	query := tx.Model(m).
		Where("order_code=?", code).
		Where("partner_id=?", partnerId).
		Where(`partner_category @>'{"id":?}'`, partnerCategory)
	ok, err := query.Exists()
	return ok, err
}

func (dao OrderBaseDao) DeliveryCodeExist(code string, companyId int64, notId ...int64) (bool, error) {
	tx := dao.transactionContext.GetDB()
	m := &models.OrderBase{}
	query := tx.Model(m).Where("delivery_code=?", code).Where("company_id=?", companyId)
	if len(notId) > 0 {
		query = query.WhereIn("id not in(?)", notId)
	}
	ok, err := query.Exists()
	return ok, err
}

//OrderBonusListByCondition 根据条件获取订单分红列表
//@param orderType 订单类型
//@param partnerOrCode 合伙人姓名或订单号或发货单号
//@param companyId 公司id
//@param partnerCategory 合伙人类型
//@param createTime 创建时间
func (dao OrderBaseDao) OrderBonusListByCondition(companyId int64, orderType int, partnerOrCode string,
	partnerCategory int, createTime [2]string, limit, offset int) ([]models.OrderBase, int, error) {
	tx := dao.transactionContext.GetDB()
	var orders []models.OrderBase
	query := tx.Model(&orders).Where("order_base.company_id=?", companyId)
	if orderType > 0 {
		query = query.Where("order_base.order_type=?", orderType)
	} else {
		query = query.Where("order_base.order_type<>?", domain.OrderIntention)
	}
	if partnerCategory > 0 {
		query = query.Where(`order_base.partner_category@>'{"id":?}'`, partnerCategory)
	}

	if len(createTime[0]) > 0 {
		query = query.Where(`order_base.create_time>=?`, createTime[0])
	}

	if len(createTime[1]) > 0 {
		query = query.Where(`order_base.create_time<=?`, createTime[1])
	}

	if len(partnerOrCode) > 0 {
		query = query.Join("LEFT JOIN partner_info as p ON order_base.partner_id=p.id").
			WhereGroup(func(q *orm.Query) (*orm.Query, error) {
				q = q.WhereOr("order_base.order_code like ? ", "%"+partnerOrCode+"%").
					WhereOr("order_base.delivery_code like ? ", "%"+partnerOrCode+"%").
					WhereOr("p.partner_name like ? ", "%"+partnerOrCode+"%")
				return q, nil
			})
	}
	query = query.Order("order_base.update_time DESC").
		Offset(offset).
		Limit(limit)

	cnt, err := query.SelectAndCount()
	return orders, cnt, err
}

//CustomOrderBonusForExcel 导出分红列表所用的结构
type CustomOrderBonusForExcel struct {
	OrderId             int64
	OrderType           int
	OrderCode           string
	BonusStatus         int
	DeliveryCode        string
	UpdateTime          string
	CreateTime          string
	PartnerBonus        float64
	PartnerBonusHas     float64
	PartnerBonusNot     float64
	PartnerBonusExpense float64
	HasBonusPercent     int
	PartnerName         string
}

//OrderBonusListForExcel 导出分红列表所用
//@param companyId 公司id
//@param orderType 订单类型
//@param partnerOrCode 合伙人姓名或订单号或发货单号
//@param partnerCategory 合伙人类型id
//@param createTime 订单的创建时间范围"[开始时间,结束时间]" 时间格式"2006-01-02 15:04:05+07"
//@return result 查询结果数据
func (dao OrderBaseDao) OrderBonusListForExcel(companyId int64, orderType int, partnerOrCode string,
	partnerCategory int) (result []CustomOrderBonusForExcel, err error) {
	//导出分红列表所用的sql
	sqlStr := `SELECT
		t1.ID AS order_id,
		t1.order_type,
		t1.order_code,
		t1.delivery_code,
		t1.bonus_status,
		to_char(t1.update_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS update_time,
		to_char(t1.create_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS create_time,
		(CASE 
		WHEN t1.use_partner_bonus>0 
		THEN
			t1.use_partner_bonus
		ELSE
			t1.plan_partner_bonus
		END) AS partner_bonus,
		t1.partner_bonus_has,
		t1.partner_bonus_not,
		t1.partner_bonus_expense,
		tt1.has_bonus_percent,
		t2.partner_name 
	FROM
		order_base AS t1
	LEFT JOIN partner_info AS t2 ON t1.partner_id = t2."id"
	LEFT JOIN ( 
		SELECT COUNT ( * ) AS has_bonus_percent, t3.order_id 
		FROM "order_good" AS t3 
		WHERE t3.partner_bonus_percent >= 0 
		GROUP BY t3.order_id 
	) AS tt1 ON t1."id" = tt1.order_id 
	WHERE 1=1 `
	sqlStr += ` AND t1.company_id = ? `
	param := []interface{}{companyId}
	if orderType > 0 {
		param = append(param, orderType)
		sqlStr += ` AND  t1.order_type=? `
	} else {
		param = append(param, domain.OrderIntention)
		sqlStr += ` AND t1.order_type<>? `
	}
	if len(partnerOrCode) > 0 {
		sqlStr += ` AND (t1.order_code like ? OR t1.delivery_code like ? OR t2.partner_name like ? )`
		likeParam := "%" + partnerOrCode + "%"
		param = append(param, likeParam, likeParam, likeParam)
	}
	if partnerCategory > 0 {
		sqlStr += ` AND t1.partner_category @>'{"id":?}'`
		param = append(param, partnerCategory)
	}
	sqlStr += ` ORDER BY t1.update_time DESC limit 10000 `
	tx := dao.transactionContext.GetDB()
	_, err = tx.Query(&result, sqlStr, param...)

	if err != nil {
		return result, err
	}
	return result, nil
}

//OrderListByCondition 获取实际订单列表
//@param companyId 公司id
//@param orderType 订单类型
//@param partnerOrCode 合伙人姓名或订单号或发货单号
//@param partnerCategory 合伙人类型id
//@param updateTime 订单更新时间范围"[开始时间,结束时间]",时间格式"2006-01-02 15:04:05+07"
//@param createTime 订单的创建时间范围"[开始时间,结束时间]" 时间格式"2006-01-02 15:04:05+07"
func (dao OrderBaseDao) OrderListByCondition(companyId int64, orderType int, partnerOrCode string,
	updateTime [2]string, createTime [2]string, partnerCategory int, limit, offset int) ([]models.OrderBase, int, error) {
	tx := dao.transactionContext.GetDB()
	var orders []models.OrderBase
	query := tx.Model(&orders).Where("order_base.company_id=?", companyId)
	if orderType > 0 {
		query = query.Where("order_base.order_type=?", orderType)
	} else {
		query = query.Where("order_base.order_type<>?", domain.OrderIntention)
	}
	if partnerCategory > 0 {
		query = query.Where(`order_base.partner_category@>'{"id":?}'`, partnerCategory)
	}
	if len(updateTime[0]) > 0 {
		query = query.Where(`order_base.update_time>=?`, updateTime[0])
	}
	if len(updateTime[1]) > 0 {
		query = query.Where(`order_base.update_time<=?`, updateTime[1])
	}
	if len(createTime[0]) > 0 {
		query = query.Where(`order_base.create_time>=?`, createTime[0])
	}
	if len(createTime[1]) > 0 {
		query = query.Where(`order_base.create_time<=?`, createTime[1])
	}

	if len(partnerOrCode) > 0 {
		query = query.Join("LEFT JOIN partner_info as p ON order_base.partner_id=p.id").
			WhereGroup(func(q *orm.Query) (*orm.Query, error) {
				q = q.WhereOr("order_base.order_code like ? ", "%"+partnerOrCode+"%").
					WhereOr("order_base.delivery_code like ? ", "%"+partnerOrCode+"%").
					WhereOr("p.partner_name like ? ", "%"+partnerOrCode+"%")
				return q, nil
			})
	}
	query = query.Order("order_base.create_time DESC").
		Offset(offset).
		Limit(limit)

	cnt, err := query.SelectAndCount()
	return orders, cnt, err

}

//CustomOrderListForExcel 导出实际订单列表所用的结构
type CustomOrderListForExcel struct {
	OrderCode       string //订单编号
	DeliveryCode    string //发货编号
	UpdateTime      string //更新时间
	CreateTime      string //创建时间
	PlanOrderCount  int64  //货品总数
	UseOrderCount   int64  //货品总数调整
	RegionName      string //订单区域
	PlanOrderAmount int64  //订单金额
	UseOrderAmount  int64  //订单金额调整
	PartnerCategory string //合伙人类型
	BuyerName       string //买家
	PartnerName     string //合伙人
}

//OrderListForExcel 获取实际订单列表用于excel导出
//@param companyId 公司id
//@param orderType 订单类型
//@param partnerOrCode 合伙人姓名或订单号或发货单号
//@param partnerCategory 合伙人类型id
//@param updateTime 订单更新时间范围"[开始时间,结束时间]",时间格式"2006-01-02 15:04:05+07"
//@param createTime 订单的创建时间范围"[开始时间,结束时间]" 时间格式"2006-01-02 15:04:05+07"
func (dao OrderBaseDao) OrderListForExcel(companyId int64, partnerOrCode string,
	updateTime [2]string, createTime [2]string, partnerCategory int) (
	result []CustomOrderListForExcel, err error) {
	sqlstr := `
			SELECT t1.order_code,t1.delivery_code
			,to_char(t1.create_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS create_time
			,to_char(t1.update_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS update_time
			,t1.plan_order_count,t1.use_order_count,t1.plan_order_amount,t1.use_order_amount
			,t1.region_info->'regionName' AS region_name,t1.buyer->'buyerName' AS buyer_name
			,t1.partner_category->'name' AS partner_category
			,t2.partner_name
			FROM "order_base" AS t1
			LEFT JOIN partner_info as t2 ON t1.partner_id=t2.id
			WHERE 1=1 AND t1.order_type = 1 
			`
	params := []interface{}{companyId}
	if len(partnerOrCode) > 0 {
		like := "%" + partnerOrCode + "%"
		params = append(params, like, like, like)
		sqlstr += " AND (t1.order_code like ? OR t1.delivery_code like ? OR t2.partner_name like ? ) "
	}

	if partnerCategory > 0 {
		params = append(params, partnerCategory)
		sqlstr += ` AND t1.partner_category@>'{"id":?}' `
	}

	if len(updateTime[0]) > 0 {
		params = append(params, updateTime[0])
		sqlstr += ` AND t1.update_time>=? `
	}

	if len(updateTime[1]) > 0 {
		params = append(params, updateTime[1])
		sqlstr += ` AND t1.update_time<=? `
	}

	if len(createTime[0]) > 0 {
		params = append(params, createTime[0])
		sqlstr += ` AND t1.create_time>=? `
	}
	if len(createTime[1]) > 0 {
		params = append(params, createTime[1])
		sqlstr += ` AND t1.create_time<=? `
	}
	sqlstr += ` ORDER BY t1.create_time DESC limit 10000 `
	tx := dao.transactionContext.GetDB()
	_, err = tx.Query(&result, sqlstr, params...)
	if err != nil {
		return result, err
	}
	return result, nil
}