作者 yangfu

add order test case

... ... @@ -22,6 +22,14 @@ func CreateReceivingService(options map[string]interface{}) (service.ReceivingGo
return domainService.NewReceivingGoodsService(transactionContext)
}
func CreateCreateOrderService(options map[string]interface{}) (service.CreateOrderService, error) {
var transactionContext *pgTransaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pgTransaction.TransactionContext)
}
return domainService.NewCreateOrderService(transactionContext)
}
func CreateCancelOrderService(options map[string]interface{}) (service.CancelOrderService, error) {
var transactionContext *pgTransaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
... ...
... ... @@ -2,6 +2,7 @@ package command
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"github.com/beego/beego/v2/core/validation"
)
... ... @@ -31,6 +32,12 @@ type CreateOrderCommand struct {
OrderStatus int `json:"orderStatus"`
// 订单类型
OrderType int `json:"orderType"`
// 订单商品
OrderGoods []*domain.Good `json:"orderGoods"`
// 合伙人分红比例
PartnerBonusPercent float64 `json:"partnerBonusPercent"`
// 业务员抽成比例
SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
}
func (createOrderCommand *CreateOrderCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -12,7 +12,7 @@ type RemoveOrderCommand struct {
}
func (removeOrderCommand *RemoveOrderCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeOrderCommand *RemoveOrderCommand) ValidateCommand() error {
... ...
... ... @@ -12,11 +12,11 @@ type UpdateOrderCommand struct {
// 发货地址
BuyerName string `json:"buyerName"`
// 订单商品总数
OrderNum string `json:"orderNum"`
OrderNum int `json:"orderNum"`
// 订单总价
TotalPrice float64 `json:"totalPrice"`
// 收货地址
ShippingAddress string `json:"shippingAddress" valid:"omitempty"`
ShippingAddress string `json:"shippingAddress,omitempty"`
}
func (updateOrderCommand *UpdateOrderCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -12,7 +12,7 @@ type GetOrderQuery struct {
}
func (getOrderQuery *GetOrderQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getOrderQuery *GetOrderQuery) ValidateQuery() error {
... ...
... ... @@ -8,13 +8,13 @@ import (
type ListOrderQuery struct {
// 查询偏离量
Offset int `json:"offset" valid:"Required"`
Offset int `json:"offset"`
// 查询限制
Limit int `json:"limit" valid:"Required"`
}
func (listOrderQuery *ListOrderQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listOrderQuery *ListOrderQuery) ValidateQuery() error {
... ...
... ... @@ -9,6 +9,7 @@ import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/order/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"strconv"
"time"
)
// 订单基础服务
... ... @@ -54,21 +55,34 @@ func (orderService *OrderService) CreateOrder(createOrderCommand *command.Create
newOrder := &domain.Order{
OrderNo: createOrderCommand.OrderNo,
CompanyId: createOrderCommand.CompanyId,
PartnerId: createOrderCommand.PartnerId,
IsDisable: false,
OrderGoods: createOrderCommand.OrderGoods,
OrderDividend: &domain.Dividend{
PartnerBonusPercent: createOrderCommand.PartnerBonusPercent,
SalesmanBonusPercent: createOrderCommand.SalesmanBonusPercent,
},
Buyer: &domain.BuyerInfo{
BuyerName: createOrderCommand.BuyerName,
ContactInfo: createOrderCommand.ContactInfo,
ShippingAddress: createOrderCommand.ShippingAddress,
Remarks: createOrderCommand.Remarks,
},
TotalPrice: createOrderCommand.TotalPrice,
CreateAt: time.Now(),
OrderStatus: domain.ORDER_STATUS_UNSHIPPED,
OrderType: createOrderCommand.OrderType,
CurrentStatus: &domain.UnShippedStatus{},
}
var orderRepository domain.OrderRepository
if value, err := factory.CreateOrderRepository(map[string]interface{}{
createOrderService, err := factory.CreateCreateOrderService(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
})
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if order, err := orderRepository.Save(newOrder); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
order, err := createOrderService.Create(newOrder)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ...
package domain
const (
Dividend_Unpaid = iota + 1
Dividend_Payed
)
// 分红值对象
type Dividend struct {
// 计划分红
... ...
... ... @@ -188,15 +188,9 @@ func (status *UnShippedStatus) Update(order *Order, data map[string]interface{})
if remarks, ok := data["remarks"]; ok {
order.Remarks = remarks.(string)
}
if createAt, ok := data["createAt"]; ok {
order.CreateAt = createAt.(time.Time)
}
if updateAt, ok := data["updateAt"]; ok {
order.UpdateAt = updateAt.(time.Time)
}
if deleteAt, ok := data["deleteAt"]; ok {
order.DeleteAt = deleteAt.(time.Time)
}
order.UpdateAt = time.Now()
order.ComputeDividend()
return nil
}
... ... @@ -227,6 +221,11 @@ func (status *UnShippedStatus) Receive(order *Order) error {
return fmt.Errorf("待发货订单不能收货")
}
// 待收货订单不能关闭
func (status *UnShippedStatus) Close(order *Order) error {
return fmt.Errorf("待收货订单不能关闭")
}
// 待收货状态
type TransitStatus struct{}
... ... @@ -510,3 +509,70 @@ func (order *Order) Cancel() error {
func (order *Order) Close() error {
return order.CurrentStatus.Close(order)
}
func (order *Order) RefreshOrderDetail() {
}
func (order *Order) ComputeDividend() {
order.computeGoodsDividend()
order.computeOrderDividend()
}
func (order *Order) computeOrderDividend() {
var totalPlanBonus float64
// 调整后分红
var totalUseBonus float64
// 已收分红
var totalBonusHas float64
// 未收分红
var totalBonusNot float64
// 分红支出
var totalBonusExpense float64
for _, v := range order.OrderGoods {
totalPlanBonus += v.GoodDividend.PlanBonus
totalUseBonus += v.GoodDividend.UseBonus
totalBonusHas += v.GoodDividend.BonusHas
totalBonusNot += v.GoodDividend.BonusNot
totalBonusExpense += v.GoodDividend.BonusExpense
}
order.OrderDividend.PlanBonus = totalPlanBonus
order.OrderDividend.UseBonus = totalUseBonus
order.OrderDividend.BonusHas = totalBonusHas
order.OrderDividend.BonusNot = totalBonusNot
order.OrderDividend.BonusExpense = totalBonusExpense
}
func (order *Order) computeGoodsDividend() {
for i := range order.OrderGoods {
good := order.OrderGoods[i]
bonus := good.GoodTotalPrice * float64(good.GoodNum) * (order.OrderDividend.PartnerBonusPercent / 100)
if good.GoodDividend == nil {
good.GoodDividend = &Dividend{
PlanBonus: bonus,
UseBonus: -1,
BonusHas: 0,
BonusNot: bonus,
BonusExpense: 0,
BonusStatus: Dividend_Unpaid,
}
} else {
/* 计算预计分红、调整后分红 */
if bonus != good.GoodDividend.PlanBonus {
if order.OrderStatus == ORDER_STATUS_UNSHIPPED {
good.GoodDividend.PlanBonus = bonus
good.GoodDividend.BonusNot = bonus
} else {
expense := good.GoodDividend.PlanBonus - bonus
if expense <= 0 {
expense = 0
}
good.GoodDividend.UseBonus = bonus
good.GoodDividend.BonusNot = bonus
good.GoodDividend.BonusExpense = expense
}
}
/*计算未支付分红*/
if good.GoodDividend.BonusHas > 0 {
good.GoodDividend.BonusNot = good.GoodDividend.PlanBonus - good.GoodDividend.BonusHas
}
}
}
}
... ...
package service
import (
coreDomain "github.com/linmadan/egglib-go/core/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
)
type CreateOrderService interface {
coreDomain.DomainEventPublisher
Create(newOrder *domain.Order) (*domain.Order, error)
}
... ...
... ... @@ -141,10 +141,10 @@ func CheckPartnerUserType(dm *User) (*User, error) {
if dm.PartnerInfo.PartnerName == "" {
return nil, fmt.Errorf("合伙人姓名不能为空")
}
if len(dm.PartnerInfo.PartnerCategorys) == 0 {
if len(dm.PartnerInfo.PartnerCategories) == 0 {
return nil, fmt.Errorf("合伙人类别不能为空")
}
if len(dm.PartnerInfo.Salesmans) == 0 {
if len(dm.PartnerInfo.Salesmen) == 0 {
return nil, fmt.Errorf("合伙人查看合伙人账号不能为空")
}
return dm, nil
... ...
package domainService
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
coreDomain "github.com/linmadan/egglib-go/core/domain"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/repository"
)
type CreateOrderService struct {
coreDomain.BaseEventPublisher
transactionContext *pgTransaction.TransactionContext
}
func (service *CreateOrderService) Create(newOrder *domain.Order) (*domain.Order, error) {
var orderRepository domain.OrderRepository
if value, err := repository.NewOrderRepository(service.transactionContext); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
}
if err := newOrder.Update(nil); err != nil {
return nil, err
}
if order, err := orderRepository.Save(newOrder); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
return order, nil
}
return nil, nil
}
func NewCreateOrderService(transactionContext *pgTransaction.TransactionContext) (*CreateOrderService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &CreateOrderService{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -6,7 +6,7 @@ import (
)
type Order struct {
tableName string `pg:"orders,alias:order"`
tableName string `pg:"orders,alias:orders"`
// 订单id
OrderId int64 `pg:",pk"`
// 买家信息
... ...
... ... @@ -6,6 +6,15 @@ import (
)
func TransformToOrderDomainModelFromPgModels(orderModel *models.Order) (*domain.Order, error) {
var currentStatus domain.OrderStatus
switch orderModel.OrderStatus {
case domain.ORDER_STATUS_UNSHIPPED:
currentStatus = &domain.UnShippedStatus{}
case domain.ORDER_STATUS_SHIPPING:
currentStatus = &domain.TransitStatus{}
default:
currentStatus = &domain.UnShippedStatus{}
}
return &domain.Order{
OrderId: orderModel.OrderId,
Buyer: orderModel.Buyer,
... ... @@ -27,5 +36,6 @@ func TransformToOrderDomainModelFromPgModels(orderModel *models.Order) (*domain.
CreateAt: orderModel.CreateAt,
UpdateAt: orderModel.UpdateAt,
DeleteAt: orderModel.DeleteAt,
CurrentStatus: currentStatus,
}, nil
}
... ...
... ... @@ -72,7 +72,7 @@ func (repository *OrderRepository) Save(order *domain.Order) (*domain.Order, err
&order.OrderDetail,
&order.OrderDividend,
&order.OrderDividendStatus,
pg.Array(&order.OrderGoods),
&order.OrderGoods,
&order.OrderSource,
&order.OrderType,
&order.OrderStatus,
... ... @@ -94,7 +94,7 @@ func (repository *OrderRepository) Save(order *domain.Order) (*domain.Order, err
order.OrderDetail,
order.OrderDividend,
order.OrderDividendStatus,
pg.Array(order.OrderGoods),
order.OrderGoods,
order.OrderSource,
order.OrderType,
order.OrderStatus,
... ... @@ -120,7 +120,7 @@ func (repository *OrderRepository) Save(order *domain.Order) (*domain.Order, err
&order.OrderDetail,
&order.OrderDividend,
&order.OrderDividendStatus,
pg.Array(&order.OrderGoods),
&order.OrderGoods,
&order.OrderSource,
&order.OrderType,
&order.OrderStatus,
... ... @@ -132,7 +132,6 @@ func (repository *OrderRepository) Save(order *domain.Order) (*domain.Order, err
&order.DeleteAt,
),
fmt.Sprintf("UPDATE orders SET %s WHERE order_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
order.OrderId,
order.Buyer,
order.CompanyId,
order.PartnerId,
... ... @@ -142,7 +141,7 @@ func (repository *OrderRepository) Save(order *domain.Order) (*domain.Order, err
order.OrderDetail,
order.OrderDividend,
order.OrderDividendStatus,
pg.Array(order.OrderGoods),
order.OrderGoods,
order.OrderSource,
order.OrderType,
order.OrderStatus,
... ... @@ -172,7 +171,7 @@ func (repository *OrderRepository) FindOne(queryOptions map[string]interface{})
tx := repository.transactionContext.PgTx
orderModel := new(models.Order)
query := sqlbuilder.BuildQuery(tx.Model(orderModel), queryOptions)
query.SetWhereByQueryOption("order.order_id = ?", "orderId")
query.SetWhereByQueryOption("orders.order_id = ?", "orderId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
... ...
package order
import (
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
)
var _ = FDescribe("创建订单增删改查", func() {
var _ = Describe("创建订单增删改查", func() {
Describe("提交数据创建订单增删改查", func() {
Context("提交正确的新订单实体数据", func() {
It("返回订单实体数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
orderGoods := []map[string]interface{}{
{"goodNum": 10, "goodName": "banana", "goodTotalPrice": 3.5, "remarks": "单位:斤"},
{"goodNum": 20, "goodName": "apple", "goodTotalPrice": 5.5, "remarks": "单位:斤"},
}
body := map[string]interface{}{
"orderNo": "string",
"companyId": 1,
... ... @@ -23,6 +27,8 @@ var _ = FDescribe("创建订单增删改查", func() {
"orderNum": 10,
"totalPrice": 10,
"partnerId": "1213",
"partnerBonusPercent": 15,
"orderGoods": orderGoods,
}
httpExpect.POST("/orders/").
WithJSON(body).
... ...
... ... @@ -10,27 +10,21 @@ import (
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
)
var _ = FDescribe("返回订单增删改查", func() {
var _ = Describe("返回订单增删改查", func() {
var orderId int64
BeforeEach(func() {
// 新增合伙人测试数据
_, err1 := pG.DB.QueryOne(
pg.Scan(),
"",
"")
Expect(err1).NotTo(HaveOccurred())
// 新增订单测试数据
_, err2 := pG.DB.QueryOne(
pg.Scan(&orderId),
"INSERT INTO orders ( buyer, company_id, partner_id, delivery_code, is_disable, order_no, order_detail, order_dividend, order_dividend_status, order_goods, order_source, order_type, order_status, total_price, region_info, remarks, create_at, update_at, delete_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING order_id",
"testBuyer", 1, "testPartnerId", "testDeliveryCode", false, "testOrderNo", "testOrderDetail", "testOrderDividend", "testOrderDividendStatus", "testOrderGoods", "testOrderSource", "testOrderType", "testOrderStatus", "testTotalPrice", "testRegionInfo", "testRemarks", "testCreateAt", "testUpdateAt", "testDeleteAt")
"INSERT INTO orders (order_id) VALUES (?) RETURNING order_id",
1)
Expect(err2).NotTo(HaveOccurred())
})
Describe("根据orderId参数返回订单实体", func() {
Context("传入有效的orderId", func() {
It("返回订单实体数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/orders/{orderId}").
httpExpect.GET("/orders/1").
Expect().
Status(http.StatusOK).
JSON().
... ...
... ... @@ -13,19 +13,20 @@ import (
var _ = Describe("返回订单增删改查列表", func() {
var orderId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
// 新增订单测试数据
_, err2 := pG.DB.QueryOne(
pg.Scan(&orderId),
"INSERT INTO orders (order_id, buyer, company_id, partner_id, delivery_code, is_disable, order_no, order_detail, order_dividend, order_dividend_status, order_goods, order_source, order_type, order_status, total_price, region_info, remarks, create_at, update_at, delete_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING order_id",
"testOrderId", "testBuyer", "testCompanyId", "testPartnerId", "testDeliveryCode", "testIsDisable", "testOrderNo", "testOrderDetail", "testOrderDividend", "testOrderDividendStatus", "testOrderGoods", "testOrderSource", "testOrderType", "testOrderStatus", "testTotalPrice", "testRegionInfo", "testRemarks", "testCreateAt", "testUpdateAt", "testDeleteAt")
Expect(err).NotTo(HaveOccurred())
"INSERT INTO orders (order_id) VALUES (?) RETURNING order_id",
1)
Expect(err2).NotTo(HaveOccurred())
})
Describe("根据参数返回订单实体列表", func() {
Context("传入有效的参数", func() {
It("返回订单实体数据列表", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/orders/").
WithQuery("offset", "int").
WithQuery("limit", "int").
WithQuery("offset", 0).
WithQuery("limit", 10).
Expect().
Status(http.StatusOK).
JSON().
... ...
... ... @@ -13,24 +13,24 @@ import (
var _ = Describe("移除订单增删改查", func() {
var orderId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
// 新增订单测试数据
_, err2 := pG.DB.QueryOne(
pg.Scan(&orderId),
"INSERT INTO orders (order_id, buyer, company_id, partner_id, delivery_code, is_disable, order_no, order_detail, order_dividend, order_dividend_status, order_goods, order_source, order_type, order_status, total_price, region_info, remarks, create_at, update_at, delete_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING order_id",
"testOrderId", "testBuyer", "testCompanyId", "testPartnerId", "testDeliveryCode", "testIsDisable", "testOrderNo", "testOrderDetail", "testOrderDividend", "testOrderDividendStatus", "testOrderGoods", "testOrderSource", "testOrderType", "testOrderStatus", "testTotalPrice", "testRegionInfo", "testRemarks", "testCreateAt", "testUpdateAt", "testDeleteAt")
Expect(err).NotTo(HaveOccurred())
"INSERT INTO orders (order_id) VALUES (?) RETURNING order_id",
1)
Expect(err2).NotTo(HaveOccurred())
})
Describe("根据参数移除订单增删改查", func() {
Context("传入有效的orderId", func() {
It("返回被移除订单实体的数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.DELETE("/orders/{orderId}").
httpExpect.DELETE("/orders/1").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
ContainsKey("msg").ValueEqual("msg", "ok")
})
})
})
... ...
... ... @@ -13,18 +13,21 @@ import (
var _ = Describe("更新订单增删改查", func() {
var orderId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
// 新增订单测试数据
_, err2 := pG.DB.QueryOne(
pg.Scan(&orderId),
"INSERT INTO orders (order_id, buyer, company_id, partner_id, delivery_code, is_disable, order_no, order_detail, order_dividend, order_dividend_status, order_goods, order_source, order_type, order_status, total_price, region_info, remarks, create_at, update_at, delete_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING order_id",
"testOrderId", "testBuyer", "testCompanyId", "testPartnerId", "testDeliveryCode", "testIsDisable", "testOrderNo", "testOrderDetail", "testOrderDividend", "testOrderDividendStatus", "testOrderGoods", "testOrderSource", "testOrderType", "testOrderStatus", "testTotalPrice", "testRegionInfo", "testRemarks", "testCreateAt", "testUpdateAt", "testDeleteAt")
Expect(err).NotTo(HaveOccurred())
"INSERT INTO orders (order_id,company_id,partner_id,buyer,order_dividend,order_detail) VALUES (?,?,?,?,?,?) RETURNING order_id",
1, 1, 1, "{}", "{}", "{}")
Expect(err2).NotTo(HaveOccurred())
})
Describe("提交数据更新订单增删改查", func() {
Context("提交正确的订单实体数据", func() {
It("返回更新后的订单实体数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.PUT("/orders/{orderId}").
body := map[string]interface{}{
"shippingAddress": "fuzhou",
}
httpExpect.PUT("/orders/1").
WithJSON(body).
Expect().
Status(http.StatusOK).
... ...