作者 tangxvhui

Merge branch 'dev' into test

# Conflicts:
#	pkg/domain/order.go
正在显示 37 个修改的文件 包含 4103 行增加40 行删除

要显示太多修改。

为保证性能只显示 37 of 37+ 个文件。

... ... @@ -22,6 +22,6 @@
*.sum
/vendor
/*.exe~
/logs
... ...
... ... @@ -5,11 +5,12 @@ WORKDIR $APP_DIR/
COPY ./pkg pkg
COPY ./conf conf
COPY ./go.mod go.mod
COPY ./vendor vendor
COPY ./main.go main.go
RUN ["ln","-sf","/usr/share/zoneinfo/Asia/Shanghai","/etc/localtime"]
ENV GO111MODULE on
ENV GOPROXY https://goproxy.cn
RUN ["go","mod","tidy"]
RUN ["go","build"]
# RUN ["go","mod","tidy"]
RUN ["go","build","-mod=vendor"]
EXPOSE 8082
ENTRYPOINT ["./partnermg"]
\ No newline at end of file
... ...
... ... @@ -50,3 +50,21 @@ func CreateOrderRepository(options map[string]interface{}) (domain.OrderReposito
}
return repository.NewOrderRepository(transactionContext)
}
//CreateOrderBaseRepository 订单信息
func CreateOrderBaseRepository(options map[string]interface{}) (domain.OrderBaseRepository, error) {
var transactionContext *transaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*transaction.TransactionContext)
}
return repository.NewOrderBaseRepository(transactionContext)
}
//CreateOrderGoodRepository 订单信息
func CreateOrderGoodRepository(options map[string]interface{}) (domain.OrderGoodRepository, error) {
var transactionContext *transaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*transaction.TransactionContext)
}
return repository.NewOrderGoodRepository(transactionContext)
}
... ...
package query
//ListOrderQuery 获取用户列表
//GetOrderQuery 获取订单详情
type GetOrderQuery struct {
OrderId int64 `json:"orderId"`
}
... ...
package query
//ListOrderQuery 获取用户列表
//ListOrderQuery 获取订单列表
type ListOrderQuery struct {
//合伙人id
PartnerId int64 `json:"partnerId" `
... ...
package command
type CreateOrderCommand struct {
//订单类型
OrderType int `json:"orderType"`
//订单编号
OrderCode string `json:"orderCode"`
//交货编号
DeliveryCode string `json:"deliveryCode"`
//买家
BuyerName string `json:"buyerName"`
//订单区域信息
OrderRegion string `json:"orderRegion"`
//订单对应的合伙人
PartnerId int64 `json:"partnerId"`
//业务员抽成比例
SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
//货品
Goods []OrderGoodData `json:"goods"`
}
... ...
package command
//DisableOrderCommand 开启关闭订单
type DisableOrderCommand struct {
OrderId int64 `json:"orderId"`
IsDisable int `json:"isDisable"`
OrderType int `json:"orderType"`
}
... ...
package command
type OrderGoodData struct {
//货品id
Id int64 `json:"id"`
//货品名称 长度可能较长
GoodName string `json:"goodName"`
//预计的货品数量
PlanGoodNumber int `json:"planGoodNumber"`
//货品单价
Price float64 `json:"price"`
//合伙人分红比例
PartnerBonusPercent float64 `json:"partnerBonusPercent"`
//备注信息
Remark string `json:"remark"`
}
... ...
package command
import "time"
type OrderDeliveryCommand struct {
OrderId int64 `json:"orderId"`
DeliveryTime time.Time `json:"deliveryTime"`
DeliveryCode string `json:"deliveryCode"`
Goods []OrderGoodData `json:"goods"`
}
... ...
package command
//更新订单的商品数字并更新分红的数据
type UpdateGoodBouns struct {
Id int64 `json:"id"` //订单id
GoodBouns []GoodBouns `json:"goodBouns"`
}
//GoodBoun 商品数量调整
type GoodBouns struct {
GoodId int64 `json:"goodId"` //货品id
UseGoodNumber int `json:"useGoodNumber"` //货品数量调整的数值
Remark string `json:"remark"` //原因
BounsStatus int `json:"BounsStatus"`
}
... ...
package command
//UpdateOrderPurposeCommand 更新意向单
type UpdateOrderCommand struct {
Id int64 `json:"id"`
//订单编号
OrderCode string `json:"orderCode"`
//交货编号
DeliveryCode string `json:"deliveryCode"`
//买家
BuyerName string `json:"buyerName"`
//订单区域信息
OrderRegion string `json:"orderRegion"`
//订单对应的合伙人
PartnerId int64 `json:"partnerId"`
//业务员抽成比例
SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
//订单类型
OrderType int `json:"orderType"`
//货品
Goods []OrderGoodData `json:"goods"`
}
... ...
package query
//GetOrderQuery 获取订单详情
type GetOrderQuery struct {
OrderId int64 `json:"orderId"`
}
... ...
package query
//ListOrderQuery 获取用户列表
type ListOrderBaseQuery struct {
//合伙人id
PartnerId int64 `json:"partnerId" `
//订单编号
OrderCode string `json:"order_code"`
// 查询偏离量
Offset int `json:"offset" `
// 查询限制
Limit int `json:"limit"`
//订单类型
OrderType int `json:"orderType"`
//发货单号
DeliveryCode string `json:"deliveryCode"`
}
... ...
package service
import (
"fmt"
"time"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/command"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/query"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)
//OrderService 管理员相关服务
type OrderInfoService struct {
}
func NewOrderInfoService(option map[string]interface{}) *OrderInfoService {
newAdminUserService := new(OrderInfoService)
return newAdminUserService
}
// PageListOrderBase 获取订单列表
func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrderBaseQuery) ([]domain.OrderBase, int, error) {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, 0, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
var (
orderRepository domain.OrderBaseRepository
orders []domain.OrderBase
cnt int
)
if value, err := factory.CreateOrderBaseRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
}
query := domain.OrderBaseFindQuery{
PartnerId: listOrderQuery.PartnerId,
OrderCode: listOrderQuery.OrderCode,
Offset: listOrderQuery.Offset,
Limit: listOrderQuery.Limit,
OrderType: listOrderQuery.OrderType,
DeliveryCode: listOrderQuery.DeliveryCode,
}
orders, cnt, err = orderRepository.Find(query)
if err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
var PartnerInfoRepository domain.PartnerInfoRepository
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
for i := range orders {
var partnerData *domain.PartnerInfo
partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{
UserId: orders[i].PartnerId,
})
if err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
orders[i].PartnerInfo = partnerData.Partner
}
return orders, cnt, nil
}
//GetOrderDetail 获取订单详情
func (service OrderInfoService) GetOrderDetail(getOrderQuery query.GetOrderQuery) (*domain.OrderBase, error) {
//实际业务
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
var (
orderBaseRepository domain.OrderBaseRepository
PartnerInfoRepository domain.PartnerInfoRepository
orderGoodRepository domain.OrderGoodRepository
order *domain.OrderBase
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
if value, err := factory.CreateOrderBaseRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderBaseRepository = value
}
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
order, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
OrderId: getOrderQuery.OrderId,
})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("获取订单数据失败:%s", err))
}
var (
partnerData *domain.PartnerInfo
goods []domain.OrderGood
)
partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{UserId: order.PartnerId})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("检索合伙人数据失败:%s", err))
}
order.PartnerInfo = partnerData.Partner
goods, _, err = orderGoodRepository.Find(domain.OrderGoodFindQuery{
OrderId: order.Id,
})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("获取订单中的商品列表失败:%s", err))
}
order.Goods = goods
err = transactionContext.CommitTransaction()
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return order, nil
}
func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (*domain.OrderBase, error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
err error
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var PartnerInfoRepository domain.PartnerInfoRepository
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
var partnerData *domain.PartnerInfo
partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{UserId: cmd.PartnerId})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("检索合伙人数据失败"))
}
var (
orderBaseRepository domain.OrderBaseRepository
orderGoodRepository domain.OrderGoodRepository
)
if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
newOrder := &domain.OrderBase{
OrderType: cmd.OrderType, OrderCode: cmd.OrderCode,
DeliveryCode: cmd.DeliveryCode,
Buyer: &domain.Buyer{
BuyerName: cmd.BuyerName,
},
RegionInfo: &domain.RegionInfo{
RegionName: cmd.OrderRegion,
},
PartnerId: cmd.PartnerId,
PartnerInfo: partnerData.Partner,
SalesmanBonusPercent: cmd.SalesmanBonusPercent,
}
var orderGoods []domain.OrderGood
for _, good := range cmd.Goods {
m := domain.NewOrderGood()
m.OrderId = 0
m.GoodName = good.GoodName
m.PlanGoodNumber = good.PlanGoodNumber
m.Price = good.Price
m.PartnerBonusPercent = good.PartnerBonusPercent
m.Remark = good.Remark
err = m.Compute()
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的数值失败:%s", err))
}
err = m.CurrentBonusStatus.WartPayPartnerBonus(&m)
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
}
orderGoods = append(orderGoods, m)
}
newOrder.Goods = orderGoods
err = newOrder.Compute()
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
}
err = orderBaseRepository.Save(newOrder)
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
}
for i := range newOrder.Goods {
newOrder.Goods[i].OrderId = newOrder.Id
}
err = orderGoodRepository.Save(orderGoods)
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单中的商品数据失败:%s", err))
}
newOrder.Goods = orderGoods
err = transactionContext.CommitTransaction()
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return newOrder, nil
}
//DeleteOrder 删除订单
func (service OrderInfoService) DeleteOrder(orderId int64) 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 (
orderBaseRepository domain.OrderBaseRepository
orderGoodRepository domain.OrderGoodRepository
)
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())
}
err = orderBaseRepository.Remove(orderId)
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("删除订单数据失败:%s", err))
}
err = orderGoodRepository.Remove(orderId)
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("删除订单中商品数据失败:%s", err))
}
err = transactionContext.CommitTransaction()
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return nil
}
//UpdateOrderData 编辑订单
func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand) (*domain.OrderBase, error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
err error
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var PartnerInfoRepository domain.PartnerInfoRepository
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
var partnerData *domain.PartnerInfo
partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{UserId: cmd.PartnerId})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("检索合伙人数据失败"))
}
var (
orderBaseRepository domain.OrderBaseRepository
orderGoodRepository domain.OrderGoodRepository
oldOrderData *domain.OrderBase
oldOrderGoods []domain.OrderGood
newOrderGoods []domain.OrderGood
delGoods []int64
)
if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
//获取旧的订单
oldOrderData, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
OrderId: cmd.Id,
})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单:%s", err))
}
//判定要求的更新的订单类型
if oldOrderData.OrderType != cmd.OrderType {
return nil, lib.ThrowError(lib.BUSINESS_ERROR, fmt.Sprintf("操作失败,待更新的订单的类型已变更"))
}
//获取旧的订单中的商品
oldOrderGoods, _, err = orderGoodRepository.Find(domain.OrderGoodFindQuery{
OrderId: cmd.Id,
})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单中的商品列表失败:%s", err))
}
for _, good := range cmd.Goods {
m := domain.NewOrderGood()
m.OrderId = oldOrderData.Id
m.GoodName = good.GoodName
m.PlanGoodNumber = good.PlanGoodNumber
m.Price = good.Price
m.PartnerBonusPercent = good.PartnerBonusPercent
m.Remark = good.Remark
err = m.Compute()
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的数值失败:%s", err))
}
err = m.CurrentBonusStatus.WartPayPartnerBonus(&m)
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
}
newOrderGoods = append(newOrderGoods, m)
}
oldOrderData.OrderCode = cmd.OrderCode
oldOrderData.DeliveryCode = cmd.DeliveryCode
oldOrderData.Buyer.BuyerName = cmd.BuyerName
oldOrderData.RegionInfo.RegionName = cmd.OrderRegion
oldOrderData.PartnerId = cmd.PartnerId
oldOrderData.PartnerInfo = partnerData.Partner
oldOrderData.SalesmanBonusPercent = cmd.SalesmanBonusPercent
oldOrderData.Goods = newOrderGoods
err = oldOrderData.Compute()
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
}
err = orderBaseRepository.Save(oldOrderData)
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
}
err = orderGoodRepository.Save(newOrderGoods)
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单中的商品数据失败:%s", err))
}
oldOrderData.Goods = newOrderGoods
//删不需要的订单总不需要的商品
delGoods = service.deleteOldOrderGoods(newOrderGoods, oldOrderGoods)
err = orderGoodRepository.Remove(oldOrderData.Id, delGoods...)
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("删除订单中的商品数据失败:%s", err))
}
err = transactionContext.CommitTransaction()
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return oldOrderData, nil
}
//deleteOldOrderGoods 新旧商品列表对比
func (service OrderInfoService) deleteOldOrderGoods(newGoods []domain.OrderGood, oldGoods []domain.OrderGood) (goodIds []int64) {
for _, old := range oldGoods {
var hasIn bool
for _, new := range newGoods {
if old.Id == new.Id {
hasIn = true
break
}
}
if !hasIn {
goodIds = append(goodIds, old.Id)
}
}
return
}
//Delivery 发货
func (service OrderInfoService) Delivery(cmd command.OrderDeliveryCommand) 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 (
orderBaseRepository domain.OrderBaseRepository
orderGoodRepository domain.OrderGoodRepository
oldOrderData *domain.OrderBase
oldOrderGoods []domain.OrderGood
)
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())
}
//获取旧的订单
oldOrderData, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
OrderId: cmd.OrderId,
})
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单:%s", err))
}
//获取旧的订单中的商品
oldOrderGoods, _, err = orderGoodRepository.Find(domain.OrderGoodFindQuery{
OrderId: cmd.OrderId,
})
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单中的商品列表失败:%s", err))
}
for _, newGood := range cmd.Goods {
for i := range oldOrderGoods {
if newGood.Id != oldOrderGoods[i].Id {
continue
}
oldOrderGoods[i].GoodName = newGood.GoodName
oldOrderGoods[i].PlanGoodNumber = newGood.PlanGoodNumber
oldOrderGoods[i].Price = newGood.Price
oldOrderGoods[i].PartnerBonusPercent = newGood.PartnerBonusPercent
oldOrderGoods[i].Remark = newGood.Remark
err = oldOrderGoods[i].Compute()
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的数值失败:%s", err))
}
err = oldOrderGoods[i].CurrentBonusStatus.WartPayPartnerBonus(&oldOrderGoods[i])
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
}
}
}
oldOrderData.DeliveryCode = cmd.DeliveryCode
oldOrderData.DeliveryTime = time.Now()
oldOrderData.Goods = oldOrderGoods
//变更订单类型
oldOrderData.OrderType = domain.OrderReal
err = oldOrderData.Compute()
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
}
err = orderBaseRepository.Save(oldOrderData)
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
}
err = orderGoodRepository.Save(oldOrderGoods)
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单中的商品数据失败:%s", err))
}
err = transactionContext.CommitTransaction()
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return nil
}
//DisableOrEnable 开启关闭订单
func (service OrderInfoService) DisableOrEnable(cmd command.DisableOrderCommand) 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 (
orderBaseRepository domain.OrderBaseRepository
oldOrderData *domain.OrderBase
)
if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
//获取旧的订单
oldOrderData, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
OrderId: cmd.OrderId,
})
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单:%s", err))
}
if oldOrderData.OrderType != cmd.OrderType {
return lib.ThrowError(lib.BUSINESS_ERROR, fmt.Sprintf("操作失败,指定的订单的类型发生变更"))
}
oldOrderData.IsDisable = cmd.IsDisable
err = orderBaseRepository.Save(oldOrderData)
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
}
err = transactionContext.CommitTransaction()
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return nil
}
//UpdateGoodBouns 更新货品的分红相关的数值
func (service OrderInfoService) UpdateGoodBouns(cmd command.UpdateGoodBouns) 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 (
orderBaseRepository domain.OrderBaseRepository
orderGoodRepository domain.OrderGoodRepository
oldOrderData *domain.OrderBase
oldOrderGoods []domain.OrderGood
)
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())
}
//获取旧的订单
oldOrderData, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
OrderId: cmd.Id,
})
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单:%s", err))
}
if oldOrderData.OrderType != domain.OrderReal {
return lib.ThrowError(lib.BUSINESS_ERROR, fmt.Sprintf("指定的订单的订单类型发生变更"))
}
//获取旧的订单中的商品
oldOrderGoods, _, err = orderGoodRepository.Find(domain.OrderGoodFindQuery{
OrderId: cmd.Id,
})
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单中的商品列表失败:%s", err))
}
for _, newGood := range cmd.GoodBouns {
for i := range oldOrderGoods {
if newGood.GoodId != oldOrderGoods[i].Id {
continue
}
oldOrderGoods[i].UseGoodNumber = newGood.UseGoodNumber
oldOrderGoods[i].Remark = newGood.Remark
oldOrderGoods[i].BonusStatus = newGood.BounsStatus
err = oldOrderGoods[i].Compute()
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的数值失败:%s", err))
}
switch newGood.BounsStatus {
case domain.OrderGoodWaitPay:
err = oldOrderGoods[i].CurrentBonusStatus.WartPayPartnerBonus(&oldOrderGoods[i])
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
}
case domain.OrderGoodHasPay:
err = oldOrderGoods[i].CurrentBonusStatus.PayPartnerBonus(&oldOrderGoods[i])
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
}
default:
return lib.ThrowError(lib.ARG_ERROR, fmt.Sprintf("货品的支付状态错误"))
}
}
}
//变更订单类型
err = oldOrderData.Compute()
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
}
err = orderBaseRepository.Save(oldOrderData)
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
}
err = orderGoodRepository.Save(oldOrderGoods)
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单中的商品数据失败:%s", err))
}
err = transactionContext.CommitTransaction()
if err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return nil
}
... ...
... ... @@ -7,26 +7,11 @@ import (
)
const (
OrderStatusReserve int = iota + 1 //预定中
OrderStatusDeliverSome //部分发货
OrderStatusDeliverAll //全部发货
OrderStatusReserve = iota + 1 //预定中
OrderStatusDeliverSome //部分发货
OrderStatusDeliverAll //全部发货
)
const (
OrderReal int = iota + 1 //实发订单
OrderIntention //意向订单
)
//买家
type Buyer struct {
//买家姓名
BuyerName string `json:"buyerName"`
//联系方式
ContactInfo string `json:"contactInfo"`
//收获地址
ShippingAddress string `json:"shippingAddress"`
}
type Order struct {
Id int64 `json:"id"`
//订单类型
... ... @@ -157,15 +142,16 @@ type OrderFindOneQuery struct {
}
type OrderFindQuery struct {
PartnerId int64
OrderCode string
Offset int
Limit int
OrderType int
PartnerId int64
OrderCode string
DeliveryCode string
Offset int
Limit int
OrderType int
}
type OrderRepository interface {
Save(order Order) error
Save(order *Order) error
FindOne(qureyOptions OrderFindOneQuery) (*Order, error)
Find(queryOptions OrderFindQuery) ([]Order, error)
CountAll(queryOption OrderFindQuery) (int, error)
... ...
package domain
import (
"time"
"github.com/shopspring/decimal"
)
const (
OrderReal = iota + 1 //实发订单
OrderIntention //意向订单
)
const (
OrderDisableNot = iota //订单未关闭
OrderDisableYes //订单已关闭
)
//Buyer 买家
type Buyer struct {
//买家姓名
BuyerName string `json:"buyerName"`
//联系方式
ContactInfo string `json:"contactInfo"`
//收获地址
ShippingAddress string `json:"shippingAddress"`
}
//OrderBase 订单基础
type OrderBase struct {
//表id
Id int64 `json:"id"`
//订单类型
OrderType int `json:"orderType"`
//订单编号
OrderCode string `json:"orderCode"`
//交货编号
DeliveryCode string `json:"deliveryCode"`
//买家
Buyer *Buyer `json:"buyer"`
//订单区域信息
RegionInfo *RegionInfo `json:"regionInfo"`
//订单对应的合伙人
PartnerId int64 `json:"partnerId"`
PartnerInfo Partner `json:"partnerInfo"`
//业务员抽成比例
SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
//订单的创建时间
CreateTime time.Time `json:"createTime"`
//发货时间
DeliveryTime time.Time `json:"deliveryTime"`
//更新时间
UpdateTime time.Time `json:"updateTime"`
//货品
Goods []OrderGood `json:"goods"`
//核算订单相关数据
OrderCompute OrderCompute `json:"orderCompute"`
//是否关闭订单
IsDisable int `json:"isDisable"`
//分红支付状态
BonusStatus int `json:"bonusStatus"`
}
type OrderCompute struct {
//合伙人应收分红
PlanPartnerBonus float64 `json:"planPartnerBonus"`
//调整后的合伙人应收分红 (初始值=-1);
//业务判定时0是有效值,
//所以用空串表示无值,转换到数据库中为负值
UsePartnerBonus float64 `json:"usePartnerBonus"`
//合伙人已收分红
PartnerBonusHas float64 `json:"partnerBonusHas"`
//合伙人未收分红
PartnerBonusNot float64 `json:"partnerBonusNot"`
//合伙人分红支出
PartnerBonusExpense float64 `json:"partnerBonusExpense"`
//业务员抽成
SalesmanBonus float64 `json:"salesmanBonus"`
//预计的订单内货品总数
PlanOrderCount int `json:"planOrderCount"`
//预计的订单的总金额
PlanOrderAmount float64 `json:"planOrderAmount"`
//按需使用的订单内货品总数 (初始值=-1)
//业务判定时0是有效值,
//所以用空串表示无值,转换到数据库中为负值
UseOrderCount int `json:"useOrderCount"`
//按需使用的订单内货总金额 (初始值=-1)
//业务判定时0是有效值,
//所以用空串表示无值,转换到数据库中为负值
UseOrderAmount float64 `json:"useOrderAmount"`
}
//Compute 数据汇总核算
func (order *OrderBase) Compute() error {
planPartnerBonus := decimal.NewFromFloat(0)
planOrderAmount := decimal.NewFromFloat(0)
var (
planOrderCount int = 0
useOrderCount int = 0
HasUseOrderCount bool = false
)
usePartnerBonus := decimal.NewFromFloat(0)
var hasUsePartnerBonus bool = false
useOrderAmount := decimal.NewFromFloat(0)
var hasUseOrderAmount bool = false
partnerBonusHas := decimal.NewFromFloat(0)
partnerBonusNot := decimal.NewFromFloat(0)
partnerBonusExpense := decimal.NewFromFloat(0)
//初始订单的支付状态
order.BonusStatus = OrderGoodWaitPay
//统计所以货品的值
for i := range order.Goods {
if order.Goods[i].BonusStatus == OrderGoodHasPay {
//确定订单的支付状态
order.BonusStatus = OrderGoodHasPay
}
planPartnerBonus = planPartnerBonus.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PlanPartnerBonus))
planOrderAmount = planOrderAmount.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PlanAmount))
planOrderCount += order.Goods[i].PlanGoodNumber
goodUseAmount := decimal.NewFromFloat(order.Goods[i].GoodCompute.UseAmount)
if goodUseAmount.GreaterThanOrEqual(decimal.NewFromFloat(0)) {
//调整值非负值得情况
hasUseOrderAmount = true
useOrderAmount = useOrderAmount.Add(goodUseAmount)
} else {
useOrderAmount = useOrderAmount.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PlanAmount))
}
goodUsePartnerBonus := decimal.NewFromFloat(order.Goods[i].GoodCompute.UsePartnerBonus)
if goodUsePartnerBonus.GreaterThanOrEqual(decimal.NewFromFloat(0)) {
hasUsePartnerBonus = true
usePartnerBonus = usePartnerBonus.Add(goodUsePartnerBonus)
} else {
usePartnerBonus = usePartnerBonus.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PlanPartnerBonus))
}
if order.Goods[i].UseGoodNumber >= 0 {
HasUseOrderCount = true
useOrderCount += order.Goods[i].UseGoodNumber
} else {
useOrderCount += order.Goods[i].PlanGoodNumber
}
partnerBonusHas = partnerBonusHas.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PartnerBonusHas))
partnerBonusNot = partnerBonusNot.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PartnerBonusNot))
partnerBonusExpense = partnerBonusExpense.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PartnerBonusExpense))
}
//汇总赋值
order.OrderCompute.PartnerBonusExpense, _ = partnerBonusExpense.Round(2).Float64()
order.OrderCompute.PartnerBonusHas, _ = partnerBonusHas.Round(2).Float64()
order.OrderCompute.PartnerBonusNot, _ = partnerBonusNot.Round(2).Float64()
order.OrderCompute.PlanPartnerBonus, _ = planPartnerBonus.Round(2).Float64()
order.OrderCompute.PlanOrderAmount, _ = planOrderAmount.Round(2).Float64()
order.OrderCompute.PlanOrderCount = planOrderCount
if hasUsePartnerBonus {
order.OrderCompute.UsePartnerBonus, _ = usePartnerBonus.Round(2).Float64()
} else {
order.OrderCompute.UsePartnerBonus = -1
}
if hasUseOrderAmount {
order.OrderCompute.UseOrderAmount, _ = useOrderAmount.Round(2).Float64()
//计算业务员的抽成
order.OrderCompute.SalesmanBonus, _ = useOrderAmount.
Mul(decimal.NewFromFloat(order.SalesmanBonusPercent)).
Div(decimal.NewFromInt(100)).
Round(2).Float64()
} else {
order.OrderCompute.UseOrderAmount = -1
order.OrderCompute.SalesmanBonus, _ = planOrderAmount.
Mul(decimal.NewFromFloat(order.SalesmanBonusPercent)).
Div(decimal.NewFromInt(100)).
Round(2).Float64()
}
if HasUseOrderCount {
order.OrderCompute.UseOrderCount = useOrderCount
} else {
order.OrderCompute.UseOrderCount = -1
}
return nil
}
type OrderBaseFindOneQuery struct {
OrderId int64
}
type OrderBaseFindQuery struct {
PartnerId int64
OrderCode string
DeliveryCode string
Offset int
Limit int
OrderType int
}
type OrderBaseRepository interface {
Save(order *OrderBase) error
FindOne(qureyOptions OrderBaseFindOneQuery) (*OrderBase, error)
Find(queryOptions OrderBaseFindQuery) ([]OrderBase, int, error)
Remove(id int64) error
}
... ...
package domain
import (
"errors"
"github.com/shopspring/decimal"
)
//分红状态
type OrderGoodBonusStatus interface {
//状态变更为待支付
WartPayPartnerBonus(orderGood *OrderGood) error
//状态变更为已支付
PayPartnerBonus(orderGood *OrderGood) error
}
//货单的支付状态
const (
//待支付
OrderGoodWaitPay int = 1
//已支付
OrderGoodHasPay int = 2
)
//OrderGood 订单中的货品
type OrderGood struct {
//货品id
Id int64 `json:"id"`
//所属订单id
OrderId int64 `json:"orderId"`
//货品名称 长度可能较长
GoodName string `json:"goodName"`
//预计的货品数量
PlanGoodNumber int `json:"planGoodNumber"`
//调整后的货品数量
//业务判定时0是有效值,
//所以用空串表示无值,转换到数据库中为负值
UseGoodNumber int `json:"useGoodNumber"`
//货品单价
Price float64 `json:"price"`
//合伙人分红比例
PartnerBonusPercent float64 `json:"partnerBonusPercent"`
//分红支付状态
BonusStatus int `json:"bonusStatus"`
//备注信息
Remark string `json:"remark"`
//当前分红支付状态
CurrentBonusStatus OrderGoodBonusStatus `json:"-"`
///核算订单相关数据
GoodCompute GoodCompute `json:"goodCompute"`
}
type GoodCompute struct {
//预计的货品总额
PlanAmount float64 `json:"planAmount"`
//调整后的货品总额 (初始值=-1)
//业务判定时0是有效值,
//所以用空串表示无值,转换到数据库中为负值
UseAmount float64 `json:"useAmount"`
//预计的合伙人分红
PlanPartnerBonus float64 `json:"planPartnerBonus"`
//合伙人应收分红调整 (初始值=-1),
//业务判定时0是有效值,
//所以用空串表示无值,转换到数据库中为负值
UsePartnerBonus float64 `json:"usePartnerBonus"`
//合伙人已收分红
PartnerBonusHas float64 `json:"partnerBonusHas"`
//合伙人未收分红
PartnerBonusNot float64 `json:"partnerBonusNot"`
//合伙人分红支出
PartnerBonusExpense float64 `json:"partnerBonusExpense"`
}
//OrderGoodBonusWaitPay 货品分红待支付
type OrderGoodBonusWaitPay struct{}
var _ OrderGoodBonusStatus = (*OrderGoodBonusWaitPay)(nil)
//OrderGoodBonusHasPay 货品分红已支付
type OrderGoodBonusHasPay struct{}
var _ OrderGoodBonusStatus = (*OrderGoodBonusHasPay)(nil)
func (waitPay OrderGoodBonusWaitPay) WartPayPartnerBonus(good *OrderGood) error {
good.GoodCompute.PartnerBonusExpense = 0
good.GoodCompute.PartnerBonusHas = 0
//初始状态为待支付时 ,合伙人未收分红等于合伙人应收分红(或者调整的)
if good.UseGoodNumber < 0 {
//数量没有调整,未收等于预计应收分红
good.GoodCompute.PartnerBonusNot = good.GoodCompute.PlanPartnerBonus
} else {
//数量有调整,未收等于调整后的应收分红
good.GoodCompute.PartnerBonusNot = good.GoodCompute.UsePartnerBonus
}
good.CurrentBonusStatus = OrderGoodBonusWaitPay{}
return nil
}
func (waitPay OrderGoodBonusWaitPay) PayPartnerBonus(good *OrderGood) error {
//待支付状态转支付时
//合伙人已收收分红等于合伙人应收分红(或者调整的)
//计算已支付
if good.UseGoodNumber < 0 {
//数量没有调整,已收等于预计应收分红
good.GoodCompute.PartnerBonusHas = good.GoodCompute.PlanPartnerBonus
} else {
//数量有调整,已收等于调整后的应收分红
good.GoodCompute.PartnerBonusHas = good.GoodCompute.UsePartnerBonus
}
good.GoodCompute.PartnerBonusExpense = 0
good.GoodCompute.PartnerBonusNot = 0
good.CurrentBonusStatus = OrderGoodBonusHasPay{}
return nil
}
func (hasPay OrderGoodBonusHasPay) PayPartnerBonus(good *OrderGood) error {
//已支付的值保持不变
//未支付的值保持不变
//计算分红支出
//分红支出=应收分红(有出现调整,则取调整后的应收分红)和已收分红的差额
if good.UseGoodNumber >= 0 {
//有数量调整,分红支出等于 已支付分红-调整后的已收分红
good.GoodCompute.PartnerBonusExpense = good.GoodCompute.PartnerBonusHas - good.GoodCompute.UsePartnerBonus
}
good.CurrentBonusStatus = OrderGoodBonusHasPay{}
return nil
}
func (hasPay OrderGoodBonusHasPay) WartPayPartnerBonus(good *OrderGood) error {
return errors.New("已支付的货单不能将状态回退为待支付")
}
//NewOrderGood 初始值设定
func NewOrderGood() OrderGood {
return OrderGood{
UseGoodNumber: -1,
BonusStatus: OrderGoodWaitPay,
GoodCompute: GoodCompute{
UsePartnerBonus: -1,
UseAmount: -1,
},
CurrentBonusStatus: OrderGoodBonusWaitPay{},
}
}
//Compute 数据汇总核算
func (good *OrderGood) Compute() error {
//计算预计货品总值
//计算预计合伙人分红
price := decimal.NewFromFloat(good.Price)
planamount := price.Mul(decimal.NewFromInt(int64(good.PlanGoodNumber))) //price*planGoodNumber
//price*useGoodNumber
planPartnerBonus := planamount.Mul(decimal.NewFromFloat(good.PartnerBonusPercent)).Div(decimal.NewFromInt(100)) //price*planGoodNumber*PartnerBonusPercent
good.GoodCompute.PlanAmount, _ = planamount.Round(2).Float64()
good.GoodCompute.PlanPartnerBonus, _ = planPartnerBonus.Round(2).Float64()
if good.UseGoodNumber < 0 {
//没有出现数量调整
good.GoodCompute.UsePartnerBonus = -1
good.GoodCompute.UseAmount = -1
} else {
//计算调整后的货品总值
//计算调整后的合伙人分红
useamount := price.Mul(decimal.NewFromInt(int64(good.UseGoodNumber))) //price*useGoodNumber/price*useGoodNumber
usePartnerBonus := useamount.Mul(decimal.NewFromFloat(good.PartnerBonusPercent)).Div(decimal.NewFromInt(100)) //price*useGoodNumber*PartnerBonusPercent
good.GoodCompute.UsePartnerBonus, _ = usePartnerBonus.Round(2).Float64()
good.GoodCompute.UseAmount, _ = useamount.Round(2).Float64()
}
return nil
}
type OrderGoodFindQuery struct {
OrderId int64
Offset int
Limit int
}
type OrderGoodRepository interface {
Save(order []OrderGood) error
Find(queryOptions OrderGoodFindQuery) ([]OrderGood, int, error)
Remove(orderid int64, ids ...int64) error
}
... ...
package models
import (
"context"
"time"
"github.com/go-pg/pg/v10"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
)
//OrderBase 订单基础
type OrderBase struct {
tableName struct{} `pg:"order_base"`
//表id
Id int64 `pg:",pk"`
//订单类型
OrderType int
//订单编号
OrderCode string
//交货编号
DeliveryCode string
//买家
Buyer *domain.Buyer
//订单区域信息
RegionInfo *domain.RegionInfo
//订单对应的合伙人
PartnerId int64
//业务员抽成比例
SalesmanBonusPercent float64
//业务员抽成
SalesmanBonus float64
//预计的订单内货品总数
PlanOrderCount int
//预计的订单的总金额
PlanOrderAmount float64
//按需使用的订单内货品总数 (初始值=-1)
//业务判定时0是有效值,负值无效
UseOrderCount int
//按需使用的订单内货总金额 (初始值=-1)
//业务判定时0是有效值,负值无效
UseOrderAmount float64
//订单的创建时间
CreateTime time.Time
//发货时间
DeliveryTime time.Time
//更新时间
UpdateTime time.Time
//合伙人应收分红
PlanPartnerBonus float64
//调整后的合伙人应收分红 (初始值=-1);
//业务判定时0是有效值,负值无效
UsePartnerBonus float64
//合伙人已收分红
PartnerBonusHas float64
//合伙人未收分红
PartnerBonusNot float64
//合伙人分红支出
PartnerBonusExpense float64
//上一次查看时间 已读情况
LastViewTime time.Time
//是否关闭订单
IsDisable int `pg:",use_zero"`
//分红支付状态
BonusStatus int
}
var _ pg.BeforeUpdateHook = (*OrderBase)(nil)
func (order *OrderBase) BeforeUpdate(ctx context.Context) (context.Context, error) {
order.UpdateTime = time.Now()
return ctx, nil
}
var _ pg.BeforeInsertHook = (*OrderBase)(nil)
func (order *OrderBase) BeforeInsert(ctx context.Context) (context.Context, error) {
order.CreateTime = time.Now()
order.UpdateTime = time.Now()
return ctx, nil
}
... ...
package models
//OrderGood 订单中的货品
type OrderGood struct {
tableName struct{} `pg:"order_good"`
//货品id
Id int64
//所属订单id
OrderId int64
//货品名称 长度可能较长
GoodName string
//预计的货品数量
PlanGoodNumber int
//货品单价
Price float64
//预计的货品总额
PlanAmount float64
//调整后的货品数量(初始值=-1)
//业务判定时0是有效值,负值无效
UseGoodNumber int
//调整后的货品总额
UseAmount float64
//合伙人分红比例
PartnerBonusPercent float64
//预计的合伙人分红
PlanPartnerBonus float64
//合伙人应收分红调整 (初始值=-1)
////业务判定时0是有效值,负值无效
UsePartnerBonus float64
//合伙人已收分红
PartnerBonusHas float64
//合伙人未收分红
PartnerBonusNot float64
//合伙人分红支出
PartnerBonusExpense float64
//分红状态
BonusStatus int
//备注信息
Remark string
}
... ...
package repository
import (
"fmt"
"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 OrderBaseRepository struct {
transactionContext *transaction.TransactionContext
}
var (
_ domain.OrderBaseRepository = (*OrderBaseRepository)(nil)
)
func NewOrderBaseRepository(transactionContext *transaction.TransactionContext) (*OrderBaseRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
}
return &OrderBaseRepository{transactionContext: transactionContext}, nil
}
func (reponsitory OrderBaseRepository) transformPgModelToDomainModel(orderModel *models.OrderBase) (order domain.OrderBase, err error) {
order = domain.OrderBase{
Id: orderModel.Id, OrderType: orderModel.OrderType, OrderCode: orderModel.OrderCode,
DeliveryCode: orderModel.DeliveryCode, Buyer: orderModel.Buyer, RegionInfo: orderModel.RegionInfo,
PartnerId: orderModel.PartnerId, SalesmanBonusPercent: orderModel.SalesmanBonusPercent,
CreateTime: orderModel.CreateTime, DeliveryTime: orderModel.DeliveryTime, UpdateTime: orderModel.UpdateTime,
IsDisable: orderModel.IsDisable,
OrderCompute: domain.OrderCompute{
PlanPartnerBonus: orderModel.PlanPartnerBonus, UsePartnerBonus: orderModel.UsePartnerBonus,
PartnerBonusHas: orderModel.PartnerBonusHas, PartnerBonusNot: orderModel.PartnerBonusNot,
PartnerBonusExpense: orderModel.PartnerBonusExpense, SalesmanBonus: orderModel.SalesmanBonus,
PlanOrderCount: orderModel.PlanOrderCount, PlanOrderAmount: orderModel.PlanOrderAmount,
UseOrderCount: orderModel.UseOrderCount, UseOrderAmount: orderModel.UseOrderAmount,
},
PartnerInfo: domain.Partner{
Id: orderModel.PartnerId,
},
BonusStatus: orderModel.BonusStatus,
}
return order, nil
}
func (repository OrderBaseRepository) Save(orderInfo *domain.OrderBase) error {
var (
err error
tx = repository.transactionContext.PgTx
)
m := &models.OrderBase{
Id: orderInfo.Id, OrderType: orderInfo.OrderType, OrderCode: orderInfo.OrderCode,
DeliveryCode: orderInfo.DeliveryCode, Buyer: orderInfo.Buyer, RegionInfo: orderInfo.RegionInfo,
PartnerId: orderInfo.PartnerId, SalesmanBonusPercent: orderInfo.SalesmanBonusPercent,
SalesmanBonus: orderInfo.OrderCompute.SalesmanBonus, PlanOrderCount: orderInfo.OrderCompute.PlanOrderCount,
PlanOrderAmount: orderInfo.OrderCompute.PlanOrderAmount, UseOrderCount: orderInfo.OrderCompute.UseOrderCount,
UseOrderAmount: orderInfo.OrderCompute.UseOrderAmount, DeliveryTime: orderInfo.DeliveryTime,
PlanPartnerBonus: orderInfo.OrderCompute.PlanPartnerBonus, UsePartnerBonus: orderInfo.OrderCompute.UsePartnerBonus,
PartnerBonusHas: orderInfo.OrderCompute.PartnerBonusHas, PartnerBonusNot: orderInfo.OrderCompute.PartnerBonusNot,
PartnerBonusExpense: orderInfo.OrderCompute.PartnerBonusExpense, IsDisable: orderInfo.IsDisable,
CreateTime: orderInfo.CreateTime, BonusStatus: orderInfo.BonusStatus,
}
if m.Id == 0 {
_, err = tx.Model(m).
Returning("*").
Insert()
orderInfo.Id = m.Id
orderInfo.CreateTime = m.CreateTime
orderInfo.UpdateTime = m.UpdateTime
} else {
_, err = tx.Model(m).
WherePK().
Returning("*").
Update()
orderInfo.UpdateTime = m.UpdateTime
}
return err
}
func (repository OrderBaseRepository) Find(queryOption domain.OrderBaseFindQuery) ([]domain.OrderBase, int, error) {
db := repository.transactionContext.PgDd
orderModels := []models.OrderBase{}
query := db.Model(&orderModels)
if queryOption.PartnerId > 0 {
query = query.Where("partner_id=?", queryOption.PartnerId)
}
if len(queryOption.OrderCode) > 0 {
query = query.Where("order_code like ?", "%"+queryOption.OrderCode+"%")
}
if len(queryOption.DeliveryCode) > 0 {
query = query.Where("delivery_code like ?", "%"+queryOption.DeliveryCode+"%")
}
if queryOption.OrderType > 0 {
query = query.Where("order_type=?", queryOption.OrderType)
}
if queryOption.Offset > -1 {
query = query.Offset(queryOption.Offset)
}
if queryOption.Limit > 0 {
query = query.Limit(queryOption.Limit)
} else {
query = query.Limit(20)
}
var (
err error
ordersReturn = make([]domain.OrderBase, 0)
)
query = query.Order("order_base.id DESC")
count, err := query.SelectAndCount()
if err != nil {
return ordersReturn, 0, err
}
for i := range orderModels {
domainOrder, err := repository.transformPgModelToDomainModel(&orderModels[i])
if err != nil {
return ordersReturn, 0, err
}
ordersReturn = append(ordersReturn, domainOrder)
}
return ordersReturn, count, nil
}
func (repository OrderBaseRepository) FindOne(qureyOptions domain.OrderBaseFindOneQuery) (*domain.OrderBase, error) {
var (
err error
tx = repository.transactionContext.PgDd
)
m := new(models.OrderBase)
err = tx.Model(m).
Where("id=?", qureyOptions.OrderId).
First()
if err != nil {
return nil, err
}
result, err := repository.transformPgModelToDomainModel(m)
return &result, err
}
func (repository OrderBaseRepository) Remove(id int64) error {
var (
err error
tx = repository.transactionContext.PgTx
)
m := &models.OrderBase{
Id: id,
}
_, err = tx.Model(m).WherePK().Delete()
return err
}
... ...
package repository
import (
"fmt"
"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 OrderGoodRepository struct {
transactionContext *transaction.TransactionContext
}
var (
_ domain.OrderGoodRepository = (*OrderGoodRepository)(nil)
)
func NewOrderGoodRepository(transactionContext *transaction.TransactionContext) (*OrderGoodRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
}
return &OrderGoodRepository{transactionContext: transactionContext}, nil
}
func (reponsitory OrderGoodRepository) transformPgModelToDomainModel(orderModel *models.OrderGood) (order domain.OrderGood, err error) {
order = domain.OrderGood{
Id: orderModel.Id, OrderId: orderModel.OrderId, GoodName: orderModel.GoodName,
PlanGoodNumber: orderModel.PlanGoodNumber, UseGoodNumber: orderModel.UseGoodNumber,
Price: orderModel.Price, PartnerBonusPercent: orderModel.PartnerBonusPercent,
BonusStatus: orderModel.BonusStatus, Remark: orderModel.Remark,
GoodCompute: domain.GoodCompute{
PlanAmount: orderModel.PlanAmount,
UseAmount: orderModel.UseAmount,
PlanPartnerBonus: orderModel.PlanPartnerBonus,
UsePartnerBonus: orderModel.UsePartnerBonus,
PartnerBonusHas: orderModel.PartnerBonusHas,
PartnerBonusNot: orderModel.PartnerBonusNot,
PartnerBonusExpense: orderModel.PartnerBonusExpense,
},
}
switch orderModel.BonusStatus {
case domain.OrderGoodWaitPay:
order.CurrentBonusStatus = domain.OrderGoodBonusWaitPay{}
case domain.OrderGoodHasPay:
order.CurrentBonusStatus = domain.OrderGoodBonusHasPay{}
}
return order, nil
}
func (repository OrderGoodRepository) Save(data []domain.OrderGood) error {
var (
err error
tx = repository.transactionContext.PgTx
)
for k, v := range data {
m := &models.OrderGood{
Id: v.Id, OrderId: v.OrderId, GoodName: v.GoodName,
PlanGoodNumber: v.PlanGoodNumber, Price: v.Price,
PlanAmount: v.GoodCompute.PlanAmount, UseGoodNumber: v.UseGoodNumber,
UseAmount: v.GoodCompute.UseAmount, PartnerBonusPercent: v.PartnerBonusPercent,
PlanPartnerBonus: v.GoodCompute.PlanPartnerBonus, UsePartnerBonus: v.GoodCompute.UsePartnerBonus,
PartnerBonusHas: v.GoodCompute.PartnerBonusHas, PartnerBonusNot: v.GoodCompute.PartnerBonusNot,
PartnerBonusExpense: v.GoodCompute.PartnerBonusExpense, BonusStatus: v.BonusStatus,
Remark: v.Remark,
}
if v.Id == 0 {
_, err = tx.Model(m).
Returning("*").
Insert()
if err != nil {
return err
}
data[k].Id = m.Id
} else {
_, err = tx.Model(m).
WherePK().
Update()
if err != nil {
return err
}
}
}
return nil
}
func (repository OrderGoodRepository) Find(queryOption domain.OrderGoodFindQuery) ([]domain.OrderGood, int, error) {
db := repository.transactionContext.PgDd
goodModes := []models.OrderGood{}
query := db.Model(&goodModes)
if queryOption.OrderId > 0 {
query = query.Where("order_id=?", queryOption.OrderId)
}
if queryOption.Offset > -1 {
query = query.Offset(queryOption.Offset)
}
if queryOption.Limit > 0 {
query = query.Limit(queryOption.Limit)
} else {
query = query.Limit(50)
}
var (
err error
orderGoods = make([]domain.OrderGood, 0)
)
query = query.Order("order_good.id DESC")
count, err := query.SelectAndCount()
if err != nil {
return orderGoods, 0, err
}
for i := range goodModes {
domainOrderGood, err := repository.transformPgModelToDomainModel(&goodModes[i])
if err != nil {
return orderGoods, 0, err
}
orderGoods = append(orderGoods, domainOrderGood)
}
return orderGoods, count, nil
}
func (repository OrderGoodRepository) Remove(orderId int64, goodids ...int64) error {
var (
err error
tx = repository.transactionContext.PgTx
)
m := &models.OrderGood{}
query := tx.Model(m).Where("order_id=?", orderId)
if len(goodids) > 0 {
query = query.WhereIn("id in(?)", goodids)
}
_, err = query.Delete()
return err
}
... ...
package controllers
import (
"errors"
"fmt"
"strconv"
"github.com/astaxie/beego/logs"
orderCmd "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/command"
orderQuery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/query"
orderService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/service"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
)
//OrderDividendController 订单分红管理
type OrderDividendController struct {
BaseController
}
//Prepare 重写 BaseController 的Prepare方法
func (c *OrderDividendController) Prepare() {
c.BaseController.Prepare()
return
if ok := c.ValidJWTToken(); !ok {
return
}
if ok := c.ValidAdminPermission(domain.PERMISSION_DIVIDEND); !ok {
return
}
}
//PageListOrderDividend 获取实发订单分红列表
func (c *OrderDividendController) PageListOrderDividend() {
type Parameter struct {
SearchText string `json:"searchText"`
Partner int64 `json:"partner"`
PageSize int `json:"pageSize"`
PageNumber int `json:"pageNumber"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if param.PageNumber == 0 {
param.PageNumber = 1
}
if param.PageSize == 0 {
param.PageSize = 20
}
orderSrv := orderService.NewOrderInfoService(nil)
orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
PartnerId: param.Partner,
DeliveryCode: param.SearchText,
OrderType: domain.OrderReal,
Limit: param.PageSize,
Offset: (param.PageNumber - 1) * param.PageSize,
})
if err != nil {
c.ResponseError(err)
return
}
rsp := []map[string]interface{}{}
for i := range orderinfos {
orderinfo := orderinfos[i]
m := map[string]interface{}{
"updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
"id": orderinfo.Id,
"shipmentsId": orderinfo.DeliveryCode,
"partner": orderinfo.PartnerInfo.PartnerName,
"dividendsReceivable": orderinfo.OrderCompute.PlanPartnerBonus,
"dividendSpending": orderinfo.OrderCompute.PartnerBonusExpense,
"receiveDividends": orderinfo.OrderCompute.PartnerBonusHas,
"uncollectedDividends": orderinfo.OrderCompute.PartnerBonusNot,
"stateOfPayment": orderinfo.BonusStatus,
}
if orderinfo.OrderCompute.UsePartnerBonus >= 0 {
m["dividendsReceivable"] = orderinfo.OrderCompute.UsePartnerBonus
}
rsp = append(rsp, m)
}
c.ResponsePageList(rsp, cnt, param.PageNumber)
return
}
//OrderDividendDetail 订单的分红详情
func (c *OrderDividendController) OrderDividendDetail() {
type Parameter struct {
Id string `json:"id"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
orderid, _ := strconv.ParseInt(param.Id, 10, 64)
if orderid == 0 {
c.ResponseError(errors.New("参数错误"))
return
}
orderSrv := orderService.NewOrderInfoService(nil)
orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
OrderId: orderid,
})
if err != nil {
c.ResponseError(err)
return
}
if orderinfo.OrderType != domain.OrderReal {
c.ResponseError(errors.New("参数错误"))
return
}
allGoods := []map[string]interface{}{}
for _, v := range orderinfo.Goods {
detail := map[string]interface{}{
"productName": v.GoodName,
"orderNum": v.PlanGoodNumber,
"univalence": v.Price,
"partnerRatio": v.PartnerBonusPercent,
"orderPrice": v.GoodCompute.PlanAmount,
"partnerDividendsReceivable": v.GoodCompute.PlanPartnerBonus,
}
m := map[string]interface{}{
"detail": detail,
"quantityControl": "",
"id": v.Id,
"stateOfPayment": v.BonusStatus,
"remark": v.Remark,
"amountControl": "",
"partnerDividendControl": "",
"receivedDividends": v.GoodCompute.PartnerBonusHas,
"notReceivedDividend": v.GoodCompute.PartnerBonusNot,
"dividendSpending": v.GoodCompute.PartnerBonusExpense,
}
if v.GoodCompute.UseAmount >= 0 {
m["amountControl"] = fmt.Sprint(v.GoodCompute.UseAmount)
}
if v.UseGoodNumber >= 0 {
m["quantityControl"] = fmt.Sprint(v.UseGoodNumber)
}
if v.GoodCompute.UsePartnerBonus >= 0 {
m["partnerDividendControl"] = fmt.Sprint(v.GoodCompute.UsePartnerBonus)
}
allGoods = append(allGoods, m)
}
orderData := map[string]interface{}{
"buyer": orderinfo.Buyer.BuyerName,
"shipmentsId": orderinfo.DeliveryCode,
"orderDist": orderinfo.RegionInfo.RegionName,
"partner": orderinfo.PartnerInfo.PartnerName,
"id": orderinfo.Id,
"orderId": orderinfo.OrderCode,
}
dividendCount := map[string]interface{}{
"orderNum": orderinfo.OrderCompute.PlanOrderCount,
"orderAmountAdjustment": orderinfo.OrderCompute.PlanOrderAmount,
"orderNumControl": "",
"orderAmountAdjustmentControl": "",
"partnerDividends": orderinfo.OrderCompute.PlanPartnerBonus,
"partnerDividendsControl": "",
"receivedDividends": orderinfo.OrderCompute.PartnerBonusHas,
"notReceivedDividend": orderinfo.OrderCompute.PartnerBonusNot,
"dividendSpending": orderinfo.OrderCompute.PartnerBonusExpense,
"commissionProportion": orderinfo.SalesmanBonusPercent,
"expectedCommission": orderinfo.OrderCompute.SalesmanBonus,
}
if orderinfo.OrderCompute.UseOrderAmount >= 0 {
dividendCount["orderAmountAdjustmentControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
}
if orderinfo.OrderCompute.UsePartnerBonus >= 0 {
dividendCount["partnerDividendsControl"] = fmt.Sprint(orderinfo.OrderCompute.UsePartnerBonus)
}
if orderinfo.OrderCompute.UseOrderCount >= 0 {
dividendCount["orderNumControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
}
rsp := map[string]interface{}{
"order": orderData,
"product": allGoods,
"dividendCount": dividendCount,
"operationTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:06"),
}
if orderinfo.OrderCompute.UseOrderAmount >= 0 {
rsp["orderNumCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
}
if orderinfo.OrderCompute.UseOrderCount >= 0 {
rsp["orderAmountAdjustmentCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
}
c.ResponseData(rsp)
return
}
type postOrderDividend struct {
Id int64 `json:"id"`
DividendPayments []postDividendPayment `json:"dividendPayment"`
}
type postDividendPayment struct {
QuantityControl string `json:"quantityControl"`
StateOfPayment int `json:"stateOfPayment"`
ProductId int64 `json:"productId"`
Remark string `json:"remark"`
}
func (c *OrderDividendController) EditOrderDividend() {
var (
param postOrderDividend
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if param.Id == 0 {
c.ResponseError(errors.New("参数错误"))
return
}
goodbouns := []orderCmd.GoodBouns{}
for _, v := range param.DividendPayments {
if v.ProductId == 0 {
c.ResponseError(errors.New("参数错误"))
return
}
if !(v.StateOfPayment == domain.OrderGoodWaitPay || v.StateOfPayment == domain.OrderGoodHasPay) {
c.ResponseError(errors.New("参数错误"))
return
}
g := orderCmd.GoodBouns{
GoodId: v.ProductId,
Remark: v.Remark,
BounsStatus: v.StateOfPayment,
}
if len(v.QuantityControl) == 0 {
g.UseGoodNumber = -1
} else {
num, err := strconv.Atoi(v.QuantityControl)
if err != nil {
c.ResponseError(errors.New("参数错误"))
return
}
g.UseGoodNumber = num
}
goodbouns = append(goodbouns, g)
}
cmd := orderCmd.UpdateGoodBouns{
Id: param.Id,
GoodBouns: goodbouns,
}
orderSrv := orderService.NewOrderInfoService(nil)
err = orderSrv.UpdateGoodBouns(cmd)
if err != nil {
c.ResponseError(err)
return
}
c.ResponseData(nil)
return
}
... ...
package controllers
import (
"errors"
"fmt"
"strconv"
"time"
"github.com/astaxie/beego/logs"
orderCmd "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/command"
orderQuery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/query"
orderService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/service"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)
type OrderInfoController struct {
BaseController
}
////Prepare 重写 BaseController 的Prepare方法
func (c *OrderInfoController) Prepare() {
c.BaseController.Prepare()
return
if ok := c.ValidJWTToken(); !ok {
return
}
if ok := c.ValidAdminPermission(domain.PERMISSION_ORDER); !ok {
return
}
}
//PageListOrderPurpose 分页获取意向订单列表
func (c *OrderInfoController) PageListOrderPurpose() {
type Parameter struct {
SearchText string `json:"searchText"`
Partner int64 `json:"partner"`
PageSize int `json:"pageSize"`
PageNumber int `json:"pageNumber"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if param.PageNumber == 0 {
param.PageNumber = 1
}
if param.PageSize == 0 {
param.PageSize = 20
}
orderSrv := orderService.NewOrderInfoService(nil)
orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
PartnerId: param.Partner,
OrderCode: param.SearchText,
OrderType: domain.OrderIntention,
Limit: param.PageSize,
Offset: (param.PageNumber - 1) * param.PageSize,
})
if err != nil {
c.ResponseError(err)
return
}
rsp := []map[string]interface{}{}
for i := range orderinfos {
orderinfo := orderinfos[i]
m := map[string]interface{}{
"createTime": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
"updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
"buyer": orderinfo.Buyer.BuyerName,
"id": orderinfo.Id,
"orderId": orderinfo.OrderCode,
"partner": orderinfo.PartnerInfo.PartnerName,
"orderNum": orderinfo.OrderCompute.PlanOrderCount,
"orderPrice": orderinfo.OrderCompute.PlanOrderAmount,
"orderDist": orderinfo.RegionInfo.RegionName,
}
rsp = append(rsp, m)
}
c.ResponsePageList(rsp, cnt, param.PageNumber)
}
//GetOrderPurpose 获取意向订单详情
func (c *OrderInfoController) GetOrderPurpose() {
type Parameter struct {
Id string `json:"id"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
orderid, _ := strconv.ParseInt(param.Id, 10, 64)
orderSrv := orderService.NewOrderInfoService(nil)
orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
OrderId: orderid,
})
if err != nil {
c.ResponseError(err)
return
}
if orderinfo.OrderType != domain.OrderIntention {
c.ResponseError(errors.New("参数错误"))
return
}
allGoods := []map[string]interface{}{}
for _, v := range orderinfo.Goods {
m := map[string]interface{}{
"productName": v.GoodName,
"orderNum": v.PlanGoodNumber,
"univalence": v.Price,
"partnerRatio": v.PartnerBonusPercent,
"orderPrice": v.GoodCompute.PlanAmount,
}
allGoods = append(allGoods, m)
}
rsp := map[string]interface{}{
"buyer": orderinfo.Buyer.BuyerName,
"id": orderinfo.Id,
"partnerID": orderinfo.PartnerInfo.Id,
"partner": orderinfo.PartnerInfo.PartnerName,
"orderDist": orderinfo.RegionInfo.RegionName,
"orderId": orderinfo.OrderCode,
"product": allGoods,
"commissionProportion": orderinfo.SalesmanBonusPercent,
"orderNumCount": orderinfo.OrderCompute.PlanOrderCount,
"orderAmountAdjustmentCount": orderinfo.OrderCompute.PlanOrderAmount,
}
c.ResponseData(rsp)
}
//RemoveOrderPurpose 删除意向订单
func (c *OrderInfoController) RemoveOrderPurpose() {
type Parameter struct {
Id int64 `json:"id"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
orderSrv := orderService.NewOrderInfoService(nil)
err = orderSrv.DeleteOrder(param.Id)
if err != nil {
c.ResponseError(err)
return
}
c.ResponseData(nil)
}
//postPurposeOrderDetail 请求添加/更新的订单数据
type postPurposeOrderDetail struct {
Id int64 `json:"id"`
//订单编号
OrderId string `json:"orderId"`
//买家姓名
BuyerName string `json:"buyer"`
//对应合伙人 id
PartnerId int64 `json:"partnerID"`
//业务员抽成比例
CommissionProportion float64 `json:"commissionProportion"`
//订单区域
OrderDist string `json:"orderDist"`
//商品
Product []postOrderGood `json:"product"`
}
func (postData postPurposeOrderDetail) Valid() error {
if len(postData.OrderId) == 0 {
return lib.ThrowError(lib.ARG_ERROR, "订单编号必填")
}
if len(postData.BuyerName) == 0 {
return lib.ThrowError(lib.ARG_ERROR, "买家信息必填")
}
if postData.PartnerId == 0 {
return lib.ThrowError(lib.ARG_ERROR, "合伙人信息必填")
}
if len(postData.OrderDist) == 0 {
return lib.ThrowError(lib.ARG_ERROR, "订单区域必填")
}
for i := range postData.Product {
if err := postData.Product[i].Valid(); err != nil {
return err
}
}
return nil
}
//PostPurposeOrderGood 请求添加/更新订单中的货品
type postOrderGood struct {
Id int64 `json:"id"`
ProductName string `json:"productName"`
OrderNum int `json:"orderNum"`
Univalence float64 `json:"univalence"`
PartnerRatio float64 `json:"partnerRatio"`
}
func (postData postOrderGood) Valid() error {
if len(postData.ProductName) == 0 {
return lib.ThrowError(lib.ARG_ERROR, "商品名称必填")
}
return nil
}
//UpdateOrderPurpose 更新意向订单
func (c *OrderInfoController) UpdateOrderPurpose() {
//用与适配前端定义的数据结构
var (
param postPurposeOrderDetail
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if err := param.Valid(); err != nil {
c.ResponseError(err)
return
}
if param.Id == 0 {
err = c.addOrderPurpose(param)
} else {
err = c.editOrderPurpose(param)
}
if err != nil {
c.ResponseError(err)
}
c.ResponseData(nil)
return
}
func (c *OrderInfoController) addOrderPurpose(param postPurposeOrderDetail) error {
newGoods := []orderCmd.OrderGoodData{}
for _, v := range param.Product {
g := orderCmd.OrderGoodData{
GoodName: v.ProductName,
PlanGoodNumber: v.OrderNum,
Price: v.Univalence,
PartnerBonusPercent: v.PartnerRatio,
}
newGoods = append(newGoods, g)
}
createcmd := orderCmd.CreateOrderCommand{
OrderType: domain.OrderIntention,
OrderCode: param.OrderId,
DeliveryCode: "",
BuyerName: param.BuyerName,
OrderRegion: param.OrderDist,
PartnerId: param.PartnerId,
SalesmanBonusPercent: param.CommissionProportion,
Goods: newGoods,
}
orderSrv := orderService.NewOrderInfoService(nil)
_, err := orderSrv.CreateNewOrder(createcmd)
return err
}
func (c *OrderInfoController) editOrderPurpose(param postPurposeOrderDetail) error {
orderSrv := orderService.NewOrderInfoService(nil)
newGoods := []orderCmd.OrderGoodData{}
for _, v := range param.Product {
g := orderCmd.OrderGoodData{
GoodName: v.ProductName,
PlanGoodNumber: v.OrderNum,
Price: v.Univalence,
PartnerBonusPercent: v.PartnerRatio,
}
newGoods = append(newGoods, g)
}
updatecmd := orderCmd.UpdateOrderCommand{
Id: param.Id,
OrderType: domain.OrderIntention,
OrderCode: param.OrderId,
DeliveryCode: "",
BuyerName: param.BuyerName,
OrderRegion: param.OrderDist,
PartnerId: param.PartnerId,
SalesmanBonusPercent: param.CommissionProportion,
Goods: newGoods,
}
_, err := orderSrv.UpdateOrderData(updatecmd)
return err
}
type postOrderPurposeDelivery struct {
ShipmentsId string `json:"shipmentsId"` //发货单号
Id string `json:"id"` //订单id
ProductDetail []postOrderGood `json:"productDetail"`
}
func (postData postOrderPurposeDelivery) Valid() error {
if len(postData.ShipmentsId) == 0 {
return lib.ThrowError(lib.ARG_ERROR, "发货单号必填")
}
for i := range postData.ProductDetail {
if err := postData.ProductDetail[i].Valid(); err != nil {
return err
}
}
return nil
}
//OrderPurposeDelivery 发货 意向订单转实发单
func (c *OrderInfoController) OrderPurposeDelivery() {
//用与适配前端定义的数据结构
var (
param postOrderPurposeDelivery
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
orderid, _ := strconv.ParseInt(param.Id, 10, 64)
if orderid <= 0 {
c.ResponseError(errors.New("参数错误"))
return
}
if err = param.Valid(); err != nil {
c.ResponseError(err)
return
}
goods := []orderCmd.OrderGoodData{}
for _, v := range param.ProductDetail {
g := orderCmd.OrderGoodData{
Id: v.Id, GoodName: v.ProductName, PlanGoodNumber: v.OrderNum,
Price: v.Univalence, PartnerBonusPercent: v.PartnerRatio,
}
goods = append(goods, g)
}
deliveryCommand := orderCmd.OrderDeliveryCommand{
OrderId: orderid, DeliveryCode: param.ShipmentsId,
DeliveryTime: time.Now(), Goods: goods,
}
orderSrv := orderService.NewOrderInfoService(nil)
err = orderSrv.Delivery(deliveryCommand)
if err != nil {
c.ResponseError(err)
}
c.ResponseData(nil)
return
}
//PageListOrderReal 获取实发订单列表
func (c *OrderInfoController) PageListOrderReal() {
type Parameter struct {
SearchText string `json:"searchText"`
Partner int64 `json:"partner"`
PageSize int `json:"pageSize"`
PageNumber int `json:"pageNumber"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if param.PageNumber == 0 {
param.PageNumber = 1
}
if param.PageSize == 0 {
param.PageSize = 20
}
orderSrv := orderService.NewOrderInfoService(nil)
orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
PartnerId: param.Partner,
DeliveryCode: param.SearchText,
OrderType: domain.OrderReal,
Limit: param.PageSize,
Offset: (param.PageNumber - 1) * param.PageSize,
})
if err != nil {
c.ResponseError(err)
return
}
rsp := []map[string]interface{}{}
for i := range orderinfos {
orderinfo := orderinfos[i]
m := map[string]interface{}{
"createTime": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
"updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
"buyer": orderinfo.Buyer.BuyerName,
"id": orderinfo.Id,
"orderId": orderinfo.OrderCode,
"shipmentsId": orderinfo.DeliveryCode,
"partner": orderinfo.PartnerInfo.PartnerName,
"orderNum": orderinfo.OrderCompute.PlanOrderCount,
"orderPrice": orderinfo.OrderCompute.PlanOrderAmount,
"orderDist": orderinfo.RegionInfo.RegionName,
"quantityControl": "",
"priceControl": "",
"status": orderinfo.IsDisable,
}
if orderinfo.OrderCompute.UseOrderCount >= 0 {
m["quantityControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
}
if orderinfo.OrderCompute.UseOrderAmount >= 0 {
m["priceControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
}
rsp = append(rsp, m)
}
c.ResponsePageList(rsp, cnt, param.PageNumber)
return
}
//GetOrderReal 获取实发订单详情
func (c *OrderInfoController) GetOrderReal() {
type Parameter struct {
Id string `json:"id"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
orderid, _ := strconv.ParseInt(param.Id, 10, 64)
if orderid == 0 {
c.ResponseError(errors.New("参数错误"))
return
}
orderSrv := orderService.NewOrderInfoService(nil)
orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
OrderId: orderid,
})
if err != nil {
c.ResponseError(err)
return
}
if orderinfo.OrderType != domain.OrderReal {
c.ResponseError(errors.New("参数错误"))
return
}
allGoods := []map[string]interface{}{}
for _, v := range orderinfo.Goods {
m := map[string]interface{}{
"productName": v.GoodName,
"orderNum": v.PlanGoodNumber,
"univalence": v.Price,
"partnerRatio": v.PartnerBonusPercent,
"orderPrice": v.GoodCompute.PlanAmount,
"quantityControl": "",
"orderPriceControl": "",
}
if v.GoodCompute.UseAmount >= 0 {
m["priceControl"] = fmt.Sprint(v.GoodCompute.UseAmount)
}
if v.UseGoodNumber >= 0 {
m["quantityControl"] = fmt.Sprint(v.UseGoodNumber)
}
allGoods = append(allGoods, m)
}
rsp := map[string]interface{}{
"buyer": orderinfo.Buyer.BuyerName,
"id": orderinfo.Id,
"partnerID": orderinfo.PartnerInfo.Id,
"partner": orderinfo.PartnerInfo.PartnerName,
"orderDist": orderinfo.RegionInfo.RegionName,
"orderId": orderinfo.OrderCode,
"shipmentsId": orderinfo.DeliveryCode,
"commissionProportion": orderinfo.SalesmanBonusPercent,
"orderNumCount": orderinfo.OrderCompute.PlanOrderCount,
"orderAmountAdjustmentCount": orderinfo.OrderCompute.PlanOrderAmount,
"orderNumCountControl": "",
"orderAmountAdjustmentCountControl": "",
"product": allGoods,
"create_time": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:06"),
"update_time": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:06"),
}
if orderinfo.OrderCompute.UseOrderAmount >= 0 {
rsp["orderNumCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
}
if orderinfo.OrderCompute.UseOrderCount >= 0 {
rsp["orderAmountAdjustmentCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
}
c.ResponseData(rsp)
return
}
//实际订单
type postRealOrderDetail struct {
postPurposeOrderDetail
ShipmentsId string `json:"shipmentsId"` //发货单号
}
func (postData postRealOrderDetail) Valid() error {
if len(postData.ShipmentsId) == 0 {
return lib.ThrowError(lib.ARG_ERROR, "订单的发货单号必填")
}
if err := postData.postPurposeOrderDetail.Valid(); err != nil {
return err
}
return nil
}
//UpdateOrderReal 编辑实际订单
func (c *OrderInfoController) UpdateOrderReal() {
//用与适配前端定义的数据结构
var (
param postRealOrderDetail
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if err := param.Valid(); err != nil {
c.ResponseError(err)
return
}
if param.Id == 0 {
err = c.addOrderReal(param)
} else {
err = c.editOrderReal(param)
}
if err != nil {
c.ResponseError(err)
}
c.ResponseData(nil)
return
}
func (c *OrderInfoController) addOrderReal(param postRealOrderDetail) error {
orderSrv := orderService.NewOrderInfoService(nil)
newGoods := []orderCmd.OrderGoodData{}
for _, v := range param.Product {
g := orderCmd.OrderGoodData{
GoodName: v.ProductName,
PlanGoodNumber: v.OrderNum,
Price: v.Univalence,
PartnerBonusPercent: v.PartnerRatio,
}
newGoods = append(newGoods, g)
}
createcmd := orderCmd.CreateOrderCommand{
OrderType: domain.OrderReal,
OrderCode: param.OrderId,
DeliveryCode: param.ShipmentsId,
BuyerName: param.BuyerName,
OrderRegion: param.OrderDist,
PartnerId: param.PartnerId,
SalesmanBonusPercent: param.CommissionProportion,
Goods: newGoods,
}
_, err := orderSrv.CreateNewOrder(createcmd)
return err
}
func (c *OrderInfoController) editOrderReal(param postRealOrderDetail) error {
newGoods := []orderCmd.OrderGoodData{}
for _, v := range param.Product {
g := orderCmd.OrderGoodData{
GoodName: v.ProductName,
PlanGoodNumber: v.OrderNum,
Price: v.Univalence,
PartnerBonusPercent: v.PartnerRatio,
}
newGoods = append(newGoods, g)
}
updatecmd := orderCmd.UpdateOrderCommand{
Id: param.Id,
OrderType: domain.OrderReal,
OrderCode: param.OrderId,
DeliveryCode: param.ShipmentsId,
BuyerName: param.BuyerName,
OrderRegion: param.OrderDist,
PartnerId: param.PartnerId,
SalesmanBonusPercent: param.CommissionProportion,
Goods: newGoods,
}
orderSrv := orderService.NewOrderInfoService(nil)
_, err := orderSrv.UpdateOrderData(updatecmd)
return err
}
//OrderDisable 关闭开启订单,限实发订单可操作
func (c *OrderInfoController) OrderDisable() {
//用与适配前端定义的数据结构
type PostParameter struct {
Id string `json:"id"`
Status int `json:"status"`
}
var (
param PostParameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
orderId, _ := strconv.ParseInt(param.Id, 10, 64)
if orderId == 0 {
c.ResponseError(errors.New("参数错误"))
return
}
if !(param.Status == domain.OrderDisableNot || param.Status == domain.OrderDisableYes) {
c.ResponseError(errors.New("参数错误"))
return
}
cmd := orderCmd.DisableOrderCommand{
OrderId: orderId,
IsDisable: param.Status,
OrderType: domain.OrderReal,
}
orderSrv := orderService.NewOrderInfoService(nil)
err = orderSrv.DisableOrEnable(cmd)
if err != nil {
c.ResponseError(err)
}
c.ResponseData(nil)
return
}
//RemoveOrderReal 删除意向订单
func (c *OrderInfoController) RemoveOrderReal() {
type Parameter struct {
Id int64 `json:"id"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
orderSrv := orderService.NewOrderInfoService(nil)
err = orderSrv.DeleteOrder(param.Id)
if err != nil {
c.ResponseError(err)
return
}
c.ResponseData(nil)
}
... ...
... ... @@ -28,23 +28,28 @@ func init() {
beego.NSRouter("/set-status", &controllers.PartnerInfoController{}, "POST:PartnerInfoSetState"),
),
beego.NSNamespace("/dividends",
beego.NSRouter("/edit", &controllers.DividendsController{}, "POST:Edit"),
beego.NSRouter("/detail", &controllers.DividendsController{}, "POST:Detail"),
beego.NSRouter("/list", &controllers.DividendsController{}, "POST:List"),
beego.NSRouter("/list", &controllers.OrderDividendController{}, "POST:PageListOrderDividend"),
beego.NSRouter("/edit", &controllers.OrderDividendController{}, "POST:EditOrderDividend"),
beego.NSRouter("/detail", &controllers.OrderDividendController{}, "POST:OrderDividendDetail"),
),
beego.NSNamespace("/order",
beego.NSRouter("/purpose/list", &controllers.OrderController{}, "POST:PageListOrderPurpose"),
beego.NSRouter("/purpose/update", &controllers.OrderController{}, "POST:UpdateOrderPurpose"),
beego.NSRouter("/purpose/detail", &controllers.OrderController{}, "POST:GetOrderPurpose"),
beego.NSRouter("/purpose/del", &controllers.OrderController{}, "POST:RemoveOrderPurpose"),
beego.NSRouter("/purpose/convert", &controllers.OrderController{}, "POST:OrderPurposeToReal"),
beego.NSRouter("/actual/list", &controllers.OrderController{}, "POST:PageListOrderReal"),
beego.NSRouter("/actual/update", &controllers.OrderController{}, "POST:UpdateOrderReal"),
beego.NSRouter("/actual/detail", &controllers.OrderController{}, "POST:GetOrderReal"),
beego.NSRouter("/purpose/list", &controllers.OrderInfoController{}, "POST:PageListOrderPurpose"),
beego.NSRouter("/purpose/update", &controllers.OrderInfoController{}, "POST:UpdateOrderPurpose"),
beego.NSRouter("/purpose/detail", &controllers.OrderInfoController{}, "POST:GetOrderPurpose"),
beego.NSRouter("/purpose/del", &controllers.OrderInfoController{}, "POST:RemoveOrderPurpose"),
beego.NSRouter("/purpose/sendout", &controllers.OrderInfoController{}, "POST:OrderPurposeDelivery"),
beego.NSRouter("/actual/list", &controllers.OrderInfoController{}, "POST:PageListOrderReal"),
beego.NSRouter("/actual/detail", &controllers.OrderInfoController{}, "POST:GetOrderReal"),
beego.NSRouter("/actual/del", &controllers.OrderInfoController{}, "POST:RemoveOrderReal"),
beego.NSRouter("/actual/update", &controllers.OrderInfoController{}, "POST:UpdateOrderReal"),
beego.NSRouter("/actual/close", &controllers.OrderInfoController{}, "POST:OrderDisable"),
),
beego.NSNamespace("/common",
beego.NSRouter("/partner", &controllers.CommonController{}, "POST:GetPartnerList"),
),
)
beego.AddNamespace(adminRouter)
}
... ...
package geetest
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
type GeetestLib struct {
CaptchaID string
PrivateKey string
Client *http.Client
}
type FailbackRegisterRespnse struct {
Success int `json:"success"`
GT string `json:"gt"`
Challenge string `json:"challenge"`
NewCaptcha int `json:"new_captcha"`
}
const (
geetestHost = "http://api.geetest.com"
registerURL = geetestHost + "/register.php"
validateURL = geetestHost + "/validate.php"
)
func MD5Encode(input string) string {
md5Instant := md5.New()
md5Instant.Write([]byte(input))
return hex.EncodeToString(md5Instant.Sum(nil))
}
// 初始化 GeetestLib
func NewGeetestLib(capthcaID string, privateKey string, timeOut time.Duration) (geetest GeetestLib){
client := &http.Client{Timeout: timeOut}
geetest = GeetestLib{capthcaID, privateKey, client}
return
}
func (g *GeetestLib) getFailBackRegisterResponse(success int, challenge string) []byte {
if challenge == "" {
challenge = hex.EncodeToString(md5.New().Sum(nil))
}
response := FailbackRegisterRespnse{
success,
g.CaptchaID,
challenge,
1,
}
res, _ := json.Marshal(response)
return res
}
func (g *GeetestLib) do(req *http.Request) (body []byte, err error) {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
var resp *http.Response
if resp, err = g.Client.Do(req); err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode >= http.StatusInternalServerError {
err = errors.New("http status code 5xx")
return
}
if body, err = ioutil.ReadAll(resp.Body); err != nil {
return
}
return
}
func (g *GeetestLib) PreProcess(userID string, userIP string) (int8, []byte) {
params := url.Values{}
params.Add("gt", g.CaptchaID)
params.Add("new_captcha", "1")
if userID != "" {
params.Add("user_id", userID)
}
if userIP != "" {
params.Add("ip_adress", userIP)
}
req, _ := http.NewRequest("GET", registerURL+"?"+params.Encode(), nil)
body, err := g.do(req)
if err != nil {
return 0, g.getFailBackRegisterResponse(0, "")
}
challenge := string(body)
if len(challenge) != 32 {
return 0, g.getFailBackRegisterResponse(0, "")
} else {
challenge = MD5Encode(challenge + g.PrivateKey)
return 1, g.getFailBackRegisterResponse(1, challenge)
}
}
func (g *GeetestLib) checkParas(challenge string, validate string, seccode string) bool {
if challenge == "" || validate == "" || seccode == "" {
return false
}
return true
}
func (g *GeetestLib) checkSuccessRes(challenge string, validate string) bool {
return MD5Encode(g.PrivateKey+"geetest"+challenge) == validate
}
func (g *GeetestLib) checkFailbackRes(challenge string, validate string) bool {
return MD5Encode(challenge) == validate
}
func (g *GeetestLib) SuccessValidate(challenge string, validate string, seccode string, userID string, userIP string) bool {
if !g.checkParas(challenge, validate, seccode) {
return false
}
if !g.checkSuccessRes(challenge, validate) {
return false
}
params := url.Values{}
params.Add("seccode", seccode)
params.Add("challenge", challenge)
params.Add("captchaid", g.CaptchaID)
params.Add("sdk", "golang_v1.0.0")
if userID != "" {
params.Add("user_id", userID)
}
if userIP != "" {
params.Add("ip_adress", userIP)
}
req, _ := http.NewRequest("POST", validateURL, strings.NewReader(params.Encode()))
body, err := g.do(req)
if err != nil {
return false
}
res := string(body)
return res == MD5Encode(seccode)
}
func (g *GeetestLib) FailbackValidate(challenge string, validate string, seccode string) bool {
if !g.checkParas(challenge, validate, seccode) {
return false
}
if !g.checkFailbackRes(challenge, validate) {
return false
}
return true
}
... ...
## Copyright 2014 Alvaro J. Genial. All rights reserved.
## Use of this source code is governed by a BSD-style
## license that can be found in the LICENSE file.
language: go
go:
- tip
- 1.6
- 1.5
- 1.4
- 1.3
# 1.2
before_install:
# - go get -v golang.org/x/tools/cmd/cover
# - go get -v golang.org/x/tools/cmd/vet
# - go get -v golang.org/x/lint/golint
- export PATH=$PATH:/home/travis/gopath/bin
script:
- go build -v ./...
- go test -v -cover ./...
- go vet ./...
# - golint .
... ...
Copyright (c) 2014 Alvaro J. Genial. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
... ...
form
====
A Form Encoding & Decoding Package for Go, written by [Alvaro J. Genial](http://alva.ro).
[![Build Status](https://travis-ci.org/ajg/form.png?branch=master)](https://travis-ci.org/ajg/form)
[![GoDoc](https://godoc.org/github.com/ajg/form?status.png)](https://godoc.org/github.com/ajg/form)
Synopsis
--------
This library is designed to allow seamless, high-fidelity encoding and decoding of arbitrary data in `application/x-www-form-urlencoded` format and as [`url.Values`](http://golang.org/pkg/net/url/#Values). It is intended to be useful primarily in dealing with web forms and URI query strings, both of which natively employ said format.
Unsurprisingly, `form` is modeled after other Go [`encoding`](http://golang.org/pkg/encoding/) packages, in particular [`encoding/json`](http://golang.org/pkg/encoding/json/), and follows the same conventions (see below for more.) It aims to automatically handle any kind of concrete Go [data value](#values) (i.e., not functions, channels, etc.) while providing mechanisms for custom behavior.
Status
------
The implementation is in usable shape and is fairly well tested with its accompanying test suite. The API is unlikely to change much, but still may. Lastly, the code has not yet undergone a security review to ensure it is free of vulnerabilities. Please file an issue or send a pull request for fixes & improvements.
Dependencies
------------
The only requirement is [Go 1.2](http://golang.org/doc/go1.2) or later.
Usage
-----
```go
import "github.com/ajg/form"
// or: "gopkg.in/ajg/form.v1"
```
Given a type like the following...
```go
type User struct {
Name string `form:"name"`
Email string `form:"email"`
Joined time.Time `form:"joined,omitempty"`
Posts []int `form:"posts"`
Preferences map[string]string `form:"prefs"`
Avatar []byte `form:"avatar"`
PasswordHash int64 `form:"-"`
}
```
...it is easy to encode data of that type...
```go
func PostUser(url string, u User) error {
var c http.Client
_, err := c.PostForm(url, form.EncodeToValues(u))
return err
}
```
...as well as decode it...
```go
func Handler(w http.ResponseWriter, r *http.Request) {
var u User
d := form.NewDecoder(r.Body)
if err := d.Decode(&u); err != nil {
http.Error(w, "Form could not be decoded", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Decoded: %#v", u)
}
```
...without having to do any grunt work.
Field Tags
----------
Like other encoding packages, `form` supports the following options for fields:
- `` `form:"-"` ``: Causes the field to be ignored during encoding and decoding.
- `` `form:"<name>"` ``: Overrides the field's name; useful especially when dealing with external identifiers in camelCase, as are commonly found on the web.
- `` `form:",omitempty"` ``: Elides the field during encoding if it is empty (typically meaning equal to the type's zero value.)
- `` `form:"<name>,omitempty"` ``: The way to combine the two options above.
Values
------
### Simple Values
Values of the following types are all considered simple:
- `bool`
- `int`, `int8`, `int16`, `int32`, `int64`, `rune`
- `uint`, `uint8`, `uint16`, `uint32`, `uint64`, `byte`
- `float32`, `float64`
- `complex64`, `complex128`
- `string`
- `[]byte` (see note)
- [`time.Time`](http://golang.org/pkg/time/#Time)
- [`url.URL`](http://golang.org/pkg/net/url/#URL)
- An alias of any of the above
- A pointer to any of the above
### Composite Values
A composite value is one that can contain other values. Values of the following kinds...
- Maps
- Slices; except `[]byte` (see note)
- Structs; except [`time.Time`](http://golang.org/pkg/time/#Time) and [`url.URL`](http://golang.org/pkg/net/url/#URL)
- Arrays
- An alias of any of the above
- A pointer to any of the above
...are considered composites in general, unless they implement custom marshaling/unmarshaling. Composite values are encoded as a flat mapping of paths to values, where the paths are constructed by joining the parent and child paths with a period (`.`).
(Note: a byte slice is treated as a `string` by default because it's more efficient, but can also be decoded as a slice—i.e., with indexes.)
### Untyped Values
While encouraged, it is not necessary to define a type (e.g. a `struct`) in order to use `form`, since it is able to encode and decode untyped data generically using the following rules:
- Simple values will be treated as a `string`.
- Composite values will be treated as a `map[string]interface{}`, itself able to contain nested values (both scalar and compound) ad infinitum.
- However, if there is a value (of any supported type) already present in a map for a given key, then it will be used when possible, rather than being replaced with a generic value as specified above; this makes it possible to handle partially typed, dynamic or schema-less values.
### Zero Values
By default, and without custom marshaling, zero values (also known as empty/default values) are encoded as the empty string. To disable this behavior, meaning to keep zero values in their literal form (e.g. `0` for integral types), `Encoder` offers a `KeepZeros` setter method, which will do just that when set to `true`.
### Unsupported Values
Values of the following kinds aren't supported and, if present, must be ignored.
- Channel
- Function
- Unsafe pointer
- An alias of any of the above
- A pointer to any of the above
Custom Marshaling
-----------------
There is a default (generally lossless) marshaling & unmarshaling scheme for any concrete data value in Go, which is good enough in most cases. However, it is possible to override it and use a custom scheme. For instance, a "binary" field could be marshaled more efficiently using [base64](http://golang.org/pkg/encoding/base64/) to prevent it from being percent-escaped during serialization to `application/x-www-form-urlencoded` format.
Because `form` provides support for [`encoding.TextMarshaler`](http://golang.org/pkg/encoding/#TextMarshaler) and [`encoding.TextUnmarshaler`](http://golang.org/pkg/encoding/#TextUnmarshaler) it is easy to do that; for instance, like this:
```go
import "encoding"
type Binary []byte
var (
_ encoding.TextMarshaler = &Binary{}
_ encoding.TextUnmarshaler = &Binary{}
)
func (b Binary) MarshalText() ([]byte, error) {
return []byte(base64.URLEncoding.EncodeToString([]byte(b))), nil
}
func (b *Binary) UnmarshalText(text []byte) error {
bs, err := base64.URLEncoding.DecodeString(string(text))
if err == nil {
*b = Binary(bs)
}
return err
}
```
Now any value with type `Binary` will automatically be encoded using the [URL](http://golang.org/pkg/encoding/base64/#URLEncoding) variant of base64. It is left as an exercise to the reader to improve upon this scheme by eliminating the need for padding (which, besides being superfluous, uses `=`, a character that will end up percent-escaped.)
Keys
----
In theory any value can be a key as long as it has a string representation. However, by default, periods have special meaning to `form`, and thus, under the hood (i.e. in encoded form) they are transparently escaped using a preceding backslash (`\`). Backslashes within keys, themselves, are also escaped in this manner (e.g. as `\\`) in order to permit representing `\.` itself (as `\\\.`).
(Note: it is normally unnecessary to deal with this issue unless keys are being constructed manually—e.g. literally embedded in HTML or in a URI.)
The default delimiter and escape characters used for encoding and decoding composite keys can be changed using the `DelimitWith` and `EscapeWith` setter methods of `Encoder` and `Decoder`, respectively. For example...
```go
package main
import (
"os"
"github.com/ajg/form"
)
func main() {
type B struct {
Qux string `form:"qux"`
}
type A struct {
FooBar B `form:"foo.bar"`
}
a := A{FooBar: B{"XYZ"}}
os.Stdout.WriteString("Default: ")
form.NewEncoder(os.Stdout).Encode(a)
os.Stdout.WriteString("\nCustom: ")
form.NewEncoder(os.Stdout).DelimitWith('/').Encode(a)
os.Stdout.WriteString("\n")
}
```
...will produce...
```
Default: foo%5C.bar.qux=XYZ
Custom: foo.bar%2Fqux=XYZ
```
(`%5C` and `%2F` represent `\` and `/`, respectively.)
Limitations
-----------
- Circular (self-referential) values are untested.
Future Work
-----------
The following items would be nice to have in the future—though they are not being worked on yet:
- An option to treat all values as if they had been tagged with `omitempty`.
- An option to automatically treat all field names in `camelCase` or `underscore_case`.
- Built-in support for the types in [`math/big`](http://golang.org/pkg/math/big/).
- Built-in support for the types in [`image/color`](http://golang.org/pkg/image/color/).
- Improve encoding/decoding by reading/writing directly from/to the `io.Reader`/`io.Writer` when possible, rather than going through an intermediate representation (i.e. `node`) which requires more memory.
(Feel free to implement any of these and then send a pull request.)
Related Work
------------
- Package [gorilla/schema](https://github.com/gorilla/schema), which only implements decoding.
- Package [google/go-querystring](https://github.com/google/go-querystring), which only implements encoding.
License
-------
This library is distributed under a BSD-style [LICENSE](./LICENSE).
... ...
TODO
====
- Document IgnoreCase and IgnoreUnknownKeys in README.
... ...
// Copyright 2014 Alvaro J. Genial. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package form
import (
"fmt"
"io"
"io/ioutil"
"net/url"
"reflect"
"strconv"
"time"
)
// NewDecoder returns a new form Decoder.
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{r, defaultDelimiter, defaultEscape, false, false}
}
// Decoder decodes data from a form (application/x-www-form-urlencoded).
type Decoder struct {
r io.Reader
d rune
e rune
ignoreUnknown bool
ignoreCase bool
}
// DelimitWith sets r as the delimiter used for composite keys by Decoder d and returns the latter; it is '.' by default.
func (d *Decoder) DelimitWith(r rune) *Decoder {
d.d = r
return d
}
// EscapeWith sets r as the escape used for delimiters (and to escape itself) by Decoder d and returns the latter; it is '\\' by default.
func (d *Decoder) EscapeWith(r rune) *Decoder {
d.e = r
return d
}
// Decode reads in and decodes form-encoded data into dst.
func (d Decoder) Decode(dst interface{}) error {
bs, err := ioutil.ReadAll(d.r)
if err != nil {
return err
}
vs, err := url.ParseQuery(string(bs))
if err != nil {
return err
}
v := reflect.ValueOf(dst)
return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v)))
}
// IgnoreUnknownKeys if set to true it will make the Decoder ignore values
// that are not found in the destination object instead of returning an error.
func (d *Decoder) IgnoreUnknownKeys(ignoreUnknown bool) {
d.ignoreUnknown = ignoreUnknown
}
// IgnoreCase if set to true it will make the Decoder try to set values in the
// destination object even if the case does not match.
func (d *Decoder) IgnoreCase(ignoreCase bool) {
d.ignoreCase = ignoreCase
}
// DecodeString decodes src into dst.
func (d Decoder) DecodeString(dst interface{}, src string) error {
vs, err := url.ParseQuery(src)
if err != nil {
return err
}
v := reflect.ValueOf(dst)
return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v)))
}
// DecodeValues decodes vs into dst.
func (d Decoder) DecodeValues(dst interface{}, vs url.Values) error {
v := reflect.ValueOf(dst)
return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v)))
}
// DecodeString decodes src into dst.
func DecodeString(dst interface{}, src string) error {
return NewDecoder(nil).DecodeString(dst, src)
}
// DecodeValues decodes vs into dst.
func DecodeValues(dst interface{}, vs url.Values) error {
return NewDecoder(nil).DecodeValues(dst, vs)
}
func (d Decoder) decodeNode(v reflect.Value, n node) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
if v.Kind() == reflect.Slice {
return fmt.Errorf("could not decode directly into slice; use pointer to slice")
}
d.decodeValue(v, n)
return nil
}
func (d Decoder) decodeValue(v reflect.Value, x interface{}) {
t := v.Type()
k := v.Kind()
if k == reflect.Ptr && v.IsNil() {
v.Set(reflect.New(t.Elem()))
}
if unmarshalValue(v, x) {
return
}
empty := isEmpty(x)
switch k {
case reflect.Ptr:
d.decodeValue(v.Elem(), x)
return
case reflect.Interface:
if !v.IsNil() {
d.decodeValue(v.Elem(), x)
return
} else if empty {
return // Allow nil interfaces only if empty.
} else {
panic("form: cannot decode non-empty value into into nil interface")
}
}
if empty {
v.Set(reflect.Zero(t)) // Treat the empty string as the zero value.
return
}
switch k {
case reflect.Struct:
if t.ConvertibleTo(timeType) {
d.decodeTime(v, x)
} else if t.ConvertibleTo(urlType) {
d.decodeURL(v, x)
} else {
d.decodeStruct(v, x)
}
case reflect.Slice:
d.decodeSlice(v, x)
case reflect.Array:
d.decodeArray(v, x)
case reflect.Map:
d.decodeMap(v, x)
case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func:
panic(t.String() + " has unsupported kind " + k.String())
default:
d.decodeBasic(v, x)
}
}
func (d Decoder) decodeStruct(v reflect.Value, x interface{}) {
t := v.Type()
for k, c := range getNode(x) {
if f, ok := findField(v, k, d.ignoreCase); !ok && k == "" {
panic(getString(x) + " cannot be decoded as " + t.String())
} else if !ok {
if !d.ignoreUnknown {
panic(k + " doesn't exist in " + t.String())
}
} else if !f.CanSet() {
panic(k + " cannot be set in " + t.String())
} else {
d.decodeValue(f, c)
}
}
}
func (d Decoder) decodeMap(v reflect.Value, x interface{}) {
t := v.Type()
if v.IsNil() {
v.Set(reflect.MakeMap(t))
}
for k, c := range getNode(x) {
i := reflect.New(t.Key()).Elem()
d.decodeValue(i, k)
w := v.MapIndex(i)
if w.IsValid() { // We have an actual element value to decode into.
if w.Kind() == reflect.Interface {
w = w.Elem()
}
w = reflect.New(w.Type()).Elem()
} else if t.Elem().Kind() != reflect.Interface { // The map's element type is concrete.
w = reflect.New(t.Elem()).Elem()
} else {
// The best we can do here is to decode as either a string (for scalars) or a map[string]interface {} (for the rest).
// We could try to guess the type based on the string (e.g. true/false => bool) but that'll get ugly fast,
// especially if we have to guess the kind (slice vs. array vs. map) and index type (e.g. string, int, etc.)
switch c.(type) {
case node:
w = reflect.MakeMap(stringMapType)
case string:
w = reflect.New(stringType).Elem()
default:
panic("value is neither node nor string")
}
}
d.decodeValue(w, c)
v.SetMapIndex(i, w)
}
}
func (d Decoder) decodeArray(v reflect.Value, x interface{}) {
t := v.Type()
for k, c := range getNode(x) {
i, err := strconv.Atoi(k)
if err != nil {
panic(k + " is not a valid index for type " + t.String())
}
if l := v.Len(); i >= l {
panic("index is above array size")
}
d.decodeValue(v.Index(i), c)
}
}
func (d Decoder) decodeSlice(v reflect.Value, x interface{}) {
t := v.Type()
if t.Elem().Kind() == reflect.Uint8 {
// Allow, but don't require, byte slices to be encoded as a single string.
if s, ok := x.(string); ok {
v.SetBytes([]byte(s))
return
}
}
// NOTE: Implicit indexing is currently done at the parseValues level,
// so if if an implicitKey reaches here it will always replace the last.
implicit := 0
for k, c := range getNode(x) {
var i int
if k == implicitKey {
i = implicit
implicit++
} else {
explicit, err := strconv.Atoi(k)
if err != nil {
panic(k + " is not a valid index for type " + t.String())
}
i = explicit
implicit = explicit + 1
}
// "Extend" the slice if it's too short.
if l := v.Len(); i >= l {
delta := i - l + 1
v.Set(reflect.AppendSlice(v, reflect.MakeSlice(t, delta, delta)))
}
d.decodeValue(v.Index(i), c)
}
}
func (d Decoder) decodeBasic(v reflect.Value, x interface{}) {
t := v.Type()
switch k, s := t.Kind(), getString(x); k {
case reflect.Bool:
if b, e := strconv.ParseBool(s); e == nil {
v.SetBool(b)
} else {
panic("could not parse bool from " + strconv.Quote(s))
}
case reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64:
if i, e := strconv.ParseInt(s, 10, 64); e == nil {
v.SetInt(i)
} else {
panic("could not parse int from " + strconv.Quote(s))
}
case reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64:
if u, e := strconv.ParseUint(s, 10, 64); e == nil {
v.SetUint(u)
} else {
panic("could not parse uint from " + strconv.Quote(s))
}
case reflect.Float32,
reflect.Float64:
if f, e := strconv.ParseFloat(s, 64); e == nil {
v.SetFloat(f)
} else {
panic("could not parse float from " + strconv.Quote(s))
}
case reflect.Complex64,
reflect.Complex128:
var c complex128
if n, err := fmt.Sscanf(s, "%g", &c); n == 1 && err == nil {
v.SetComplex(c)
} else {
panic("could not parse complex from " + strconv.Quote(s))
}
case reflect.String:
v.SetString(s)
default:
panic(t.String() + " has unsupported kind " + k.String())
}
}
func (d Decoder) decodeTime(v reflect.Value, x interface{}) {
t := v.Type()
s := getString(x)
// TODO: Find a more efficient way to do this.
for _, f := range allowedTimeFormats {
if p, err := time.Parse(f, s); err == nil {
v.Set(reflect.ValueOf(p).Convert(v.Type()))
return
}
}
panic("cannot decode string `" + s + "` as " + t.String())
}
func (d Decoder) decodeURL(v reflect.Value, x interface{}) {
t := v.Type()
s := getString(x)
if u, err := url.Parse(s); err == nil {
v.Set(reflect.ValueOf(*u).Convert(v.Type()))
return
}
panic("cannot decode string `" + s + "` as " + t.String())
}
var allowedTimeFormats = []string{
"2006-01-02T15:04:05.999999999Z07:00",
"2006-01-02T15:04:05.999999999Z07",
"2006-01-02T15:04:05.999999999Z",
"2006-01-02T15:04:05.999999999",
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05Z07",
"2006-01-02T15:04:05Z",
"2006-01-02T15:04:05",
"2006-01-02T15:04Z",
"2006-01-02T15:04",
"2006-01-02T15Z",
"2006-01-02T15",
"2006-01-02",
"2006-01",
"2006",
"15:04:05.999999999Z07:00",
"15:04:05.999999999Z07",
"15:04:05.999999999Z",
"15:04:05.999999999",
"15:04:05Z07:00",
"15:04:05Z07",
"15:04:05Z",
"15:04:05",
"15:04Z",
"15:04",
"15Z",
"15",
}
... ...
// Copyright 2014 Alvaro J. Genial. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package form
import (
"encoding"
"errors"
"fmt"
"io"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
// NewEncoder returns a new form Encoder.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{w, defaultDelimiter, defaultEscape, false}
}
// Encoder provides a way to encode to a Writer.
type Encoder struct {
w io.Writer
d rune
e rune
z bool
}
// DelimitWith sets r as the delimiter used for composite keys by Encoder e and returns the latter; it is '.' by default.
func (e *Encoder) DelimitWith(r rune) *Encoder {
e.d = r
return e
}
// EscapeWith sets r as the escape used for delimiters (and to escape itself) by Encoder e and returns the latter; it is '\\' by default.
func (e *Encoder) EscapeWith(r rune) *Encoder {
e.e = r
return e
}
// KeepZeros sets whether Encoder e should keep zero (default) values in their literal form when encoding, and returns the former; by default zero values are not kept, but are rather encoded as the empty string.
func (e *Encoder) KeepZeros(z bool) *Encoder {
e.z = z
return e
}
// Encode encodes dst as form and writes it out using the Encoder's Writer.
func (e Encoder) Encode(dst interface{}) error {
v := reflect.ValueOf(dst)
n, err := encodeToNode(v, e.z)
if err != nil {
return err
}
s := n.values(e.d, e.e).Encode()
l, err := io.WriteString(e.w, s)
switch {
case err != nil:
return err
case l != len(s):
return errors.New("could not write data completely")
}
return nil
}
// EncodeToString encodes dst as a form and returns it as a string.
func EncodeToString(dst interface{}) (string, error) {
v := reflect.ValueOf(dst)
n, err := encodeToNode(v, false)
if err != nil {
return "", err
}
vs := n.values(defaultDelimiter, defaultEscape)
return vs.Encode(), nil
}
// EncodeToValues encodes dst as a form and returns it as Values.
func EncodeToValues(dst interface{}) (url.Values, error) {
v := reflect.ValueOf(dst)
n, err := encodeToNode(v, false)
if err != nil {
return nil, err
}
vs := n.values(defaultDelimiter, defaultEscape)
return vs, nil
}
func encodeToNode(v reflect.Value, z bool) (n node, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
return getNode(encodeValue(v, z)), nil
}
func encodeValue(v reflect.Value, z bool) interface{} {
t := v.Type()
k := v.Kind()
if s, ok := marshalValue(v); ok {
return s
} else if !z && isEmptyValue(v) {
return "" // Treat the zero value as the empty string.
}
switch k {
case reflect.Ptr, reflect.Interface:
return encodeValue(v.Elem(), z)
case reflect.Struct:
if t.ConvertibleTo(timeType) {
return encodeTime(v)
} else if t.ConvertibleTo(urlType) {
return encodeURL(v)
}
return encodeStruct(v, z)
case reflect.Slice:
return encodeSlice(v, z)
case reflect.Array:
return encodeArray(v, z)
case reflect.Map:
return encodeMap(v, z)
case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func:
panic(t.String() + " has unsupported kind " + t.Kind().String())
default:
return encodeBasic(v)
}
}
func encodeStruct(v reflect.Value, z bool) interface{} {
t := v.Type()
n := node{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
k, oe := fieldInfo(f)
if k == "-" {
continue
} else if fv := v.Field(i); oe && isEmptyValue(fv) {
delete(n, k)
} else {
n[k] = encodeValue(fv, z)
}
}
return n
}
func encodeMap(v reflect.Value, z bool) interface{} {
n := node{}
for _, i := range v.MapKeys() {
k := getString(encodeValue(i, z))
n[k] = encodeValue(v.MapIndex(i), z)
}
return n
}
func encodeArray(v reflect.Value, z bool) interface{} {
n := node{}
for i := 0; i < v.Len(); i++ {
n[strconv.Itoa(i)] = encodeValue(v.Index(i), z)
}
return n
}
func encodeSlice(v reflect.Value, z bool) interface{} {
t := v.Type()
if t.Elem().Kind() == reflect.Uint8 {
return string(v.Bytes()) // Encode byte slices as a single string by default.
}
n := node{}
for i := 0; i < v.Len(); i++ {
n[strconv.Itoa(i)] = encodeValue(v.Index(i), z)
}
return n
}
func encodeTime(v reflect.Value) string {
t := v.Convert(timeType).Interface().(time.Time)
if t.Year() == 0 && (t.Month() == 0 || t.Month() == 1) && (t.Day() == 0 || t.Day() == 1) {
return t.Format("15:04:05.999999999Z07:00")
} else if t.Hour() == 0 && t.Minute() == 0 && t.Second() == 0 && t.Nanosecond() == 0 {
return t.Format("2006-01-02")
}
return t.Format("2006-01-02T15:04:05.999999999Z07:00")
}
func encodeURL(v reflect.Value) string {
u := v.Convert(urlType).Interface().(url.URL)
return u.String()
}
func encodeBasic(v reflect.Value) string {
t := v.Type()
switch k := t.Kind(); k {
case reflect.Bool:
return strconv.FormatBool(v.Bool())
case reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
case reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64:
return strconv.FormatUint(v.Uint(), 10)
case reflect.Float32:
return strconv.FormatFloat(v.Float(), 'g', -1, 32)
case reflect.Float64:
return strconv.FormatFloat(v.Float(), 'g', -1, 64)
case reflect.Complex64, reflect.Complex128:
s := fmt.Sprintf("%g", v.Complex())
return strings.TrimSuffix(strings.TrimPrefix(s, "("), ")")
case reflect.String:
return v.String()
}
panic(t.String() + " has unsupported kind " + t.Kind().String())
}
func isEmptyValue(v reflect.Value) bool {
switch t := v.Type(); v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Complex64, reflect.Complex128:
return v.Complex() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Struct:
if t.ConvertibleTo(timeType) {
return v.Convert(timeType).Interface().(time.Time).IsZero()
}
return reflect.DeepEqual(v, reflect.Zero(t))
}
return false
}
// canIndexOrdinally returns whether a value contains an ordered sequence of elements.
func canIndexOrdinally(v reflect.Value) bool {
if !v.IsValid() {
return false
}
switch t := v.Type(); t.Kind() {
case reflect.Ptr, reflect.Interface:
return canIndexOrdinally(v.Elem())
case reflect.Slice, reflect.Array:
return true
}
return false
}
func fieldInfo(f reflect.StructField) (k string, oe bool) {
if f.PkgPath != "" { // Skip private fields.
return omittedKey, oe
}
k = f.Name
tag := f.Tag.Get("form")
if tag == "" {
return k, oe
}
ps := strings.SplitN(tag, ",", 2)
if ps[0] != "" {
k = ps[0]
}
if len(ps) == 2 {
oe = ps[1] == "omitempty"
}
return k, oe
}
func findField(v reflect.Value, n string, ignoreCase bool) (reflect.Value, bool) {
t := v.Type()
l := v.NumField()
var lowerN string
caseInsensitiveMatch := -1
if ignoreCase {
lowerN = strings.ToLower(n)
}
// First try named fields.
for i := 0; i < l; i++ {
f := t.Field(i)
k, _ := fieldInfo(f)
if k == omittedKey {
continue
} else if n == k {
return v.Field(i), true
} else if ignoreCase && lowerN == strings.ToLower(k) {
caseInsensitiveMatch = i
}
}
// If no exact match was found try case insensitive match.
if caseInsensitiveMatch != -1 {
return v.Field(caseInsensitiveMatch), true
}
// Then try anonymous (embedded) fields.
for i := 0; i < l; i++ {
f := t.Field(i)
k, _ := fieldInfo(f)
if k == omittedKey || !f.Anonymous { // || k != "" ?
continue
}
fv := v.Field(i)
fk := fv.Kind()
for fk == reflect.Ptr || fk == reflect.Interface {
fv = fv.Elem()
fk = fv.Kind()
}
if fk != reflect.Struct {
continue
}
if ev, ok := findField(fv, n, ignoreCase); ok {
return ev, true
}
}
return reflect.Value{}, false
}
var (
stringType = reflect.TypeOf(string(""))
stringMapType = reflect.TypeOf(map[string]interface{}{})
timeType = reflect.TypeOf(time.Time{})
timePtrType = reflect.TypeOf(&time.Time{})
urlType = reflect.TypeOf(url.URL{})
)
func skipTextMarshalling(t reflect.Type) bool {
/*// Skip time.Time because its text unmarshaling is overly rigid:
return t == timeType || t == timePtrType*/
// Skip time.Time & convertibles because its text unmarshaling is overly rigid:
return t.ConvertibleTo(timeType) || t.ConvertibleTo(timePtrType)
}
func unmarshalValue(v reflect.Value, x interface{}) bool {
if skipTextMarshalling(v.Type()) {
return false
}
tu, ok := v.Interface().(encoding.TextUnmarshaler)
if !ok && !v.CanAddr() {
return false
} else if !ok {
return unmarshalValue(v.Addr(), x)
}
s := getString(x)
if err := tu.UnmarshalText([]byte(s)); err != nil {
panic(err)
}
return true
}
func marshalValue(v reflect.Value) (string, bool) {
if skipTextMarshalling(v.Type()) {
return "", false
}
tm, ok := v.Interface().(encoding.TextMarshaler)
if !ok && !v.CanAddr() {
return "", false
} else if !ok {
return marshalValue(v.Addr())
}
bs, err := tm.MarshalText()
if err != nil {
panic(err)
}
return string(bs), true
}
... ...
// Copyright 2014 Alvaro J. Genial. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package form implements encoding and decoding of application/x-www-form-urlencoded data.
package form
const (
implicitKey = "_"
omittedKey = "-"
defaultDelimiter = '.'
defaultEscape = '\\'
)
... ...
// Copyright 2014 Alvaro J. Genial. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package form
import (
"net/url"
"strconv"
"strings"
)
type node map[string]interface{}
func (n node) values(d, e rune) url.Values {
vs := url.Values{}
n.merge(d, e, "", &vs)
return vs
}
func (n node) merge(d, e rune, p string, vs *url.Values) {
for k, x := range n {
switch y := x.(type) {
case string:
vs.Add(p+escape(d, e, k), y)
case node:
y.merge(d, e, p+escape(d, e, k)+string(d), vs)
default:
panic("value is neither string nor node")
}
}
}
// TODO: Add tests for implicit indexing.
func parseValues(d, e rune, vs url.Values, canIndexFirstLevelOrdinally bool) node {
// NOTE: Because of the flattening of potentially multiple strings to one key, implicit indexing works:
// i. At the first level; e.g. Foo.Bar=A&Foo.Bar=B becomes 0.Foo.Bar=A&1.Foo.Bar=B
// ii. At the last level; e.g. Foo.Bar._=A&Foo.Bar._=B becomes Foo.Bar.0=A&Foo.Bar.1=B
// TODO: At in-between levels; e.g. Foo._.Bar=A&Foo._.Bar=B becomes Foo.0.Bar=A&Foo.1.Bar=B
// (This last one requires that there only be one placeholder in order for it to be unambiguous.)
m := map[string]string{}
for k, ss := range vs {
indexLastLevelOrdinally := strings.HasSuffix(k, string(d)+implicitKey)
for i, s := range ss {
if canIndexFirstLevelOrdinally {
k = strconv.Itoa(i) + string(d) + k
} else if indexLastLevelOrdinally {
k = strings.TrimSuffix(k, implicitKey) + strconv.Itoa(i)
}
m[k] = s
}
}
n := node{}
for k, s := range m {
n = n.split(d, e, k, s)
}
return n
}
func splitPath(d, e rune, path string) (k, rest string) {
esc := false
for i, r := range path {
switch {
case !esc && r == e:
esc = true
case !esc && r == d:
return unescape(d, e, path[:i]), path[i+1:]
default:
esc = false
}
}
return unescape(d, e, path), ""
}
func (n node) split(d, e rune, path, s string) node {
k, rest := splitPath(d, e, path)
if rest == "" {
return add(n, k, s)
}
if _, ok := n[k]; !ok {
n[k] = node{}
}
c := getNode(n[k])
n[k] = c.split(d, e, rest, s)
return n
}
func add(n node, k, s string) node {
if n == nil {
return node{k: s}
}
if _, ok := n[k]; ok {
panic("key " + k + " already set")
}
n[k] = s
return n
}
func isEmpty(x interface{}) bool {
switch y := x.(type) {
case string:
return y == ""
case node:
if s, ok := y[""].(string); ok {
return s == ""
}
return false
}
panic("value is neither string nor node")
}
func getNode(x interface{}) node {
switch y := x.(type) {
case string:
return node{"": y}
case node:
return y
}
panic("value is neither string nor node")
}
func getString(x interface{}) string {
switch y := x.(type) {
case string:
return y
case node:
if s, ok := y[""].(string); ok {
return s
}
return ""
}
panic("value is neither string nor node")
}
func escape(d, e rune, s string) string {
s = strings.Replace(s, string(e), string(e)+string(e), -1) // Escape the escape (\ => \\)
s = strings.Replace(s, string(d), string(e)+string(d), -1) // Escape the delimiter (. => \.)
return s
}
func unescape(d, e rune, s string) string {
s = strings.Replace(s, string(e)+string(d), string(d), -1) // Unescape the delimiter (\. => .)
s = strings.Replace(s, string(e)+string(e), string(e), -1) // Unescape the escape (\\ => \)
return s
}
... ...
#!/bin/bash -eu
# TODO: Only colorize messages given a suitable terminal.
# FIXME: Handle case in which no stash entry is created due to no changes.
printf "\e[30m=== PRE-COMMIT STARTING ===\e[m\n"
git stash save --quiet --keep-index --include-untracked
if go build -v ./... && go test -v -cover ./... && go vet ./... && golint . && travis-lint; then
result=$?
printf "\e[32m=== PRE-COMMIT SUCCEEDED ===\e[m\n"
else
result=$?
printf "\e[31m=== PRE-COMMIT FAILED ===\e[m\n"
fi
git stash pop --quiet
exit $result
... ...
Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
... ...
This package is a brotli compressor and decompressor implemented in Go.
It was translated from the reference implementation (https://github.com/google/brotli)
with the `c2go` tool at https://github.com/andybalholm/c2go.
I am using it in production with https://github.com/andybalholm/redwood.
... ...
package brotli
/* Copyright 2013 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
/* Function to find backward reference copies. */
func computeDistanceCode(distance uint, max_distance uint, dist_cache []int) uint {
if distance <= max_distance {
var distance_plus_3 uint = distance + 3
var offset0 uint = distance_plus_3 - uint(dist_cache[0])
var offset1 uint = distance_plus_3 - uint(dist_cache[1])
if distance == uint(dist_cache[0]) {
return 0
} else if distance == uint(dist_cache[1]) {
return 1
} else if offset0 < 7 {
return (0x9750468 >> (4 * offset0)) & 0xF
} else if offset1 < 7 {
return (0xFDB1ACE >> (4 * offset1)) & 0xF
} else if distance == uint(dist_cache[2]) {
return 2
} else if distance == uint(dist_cache[3]) {
return 3
}
}
return distance + numDistanceShortCodes - 1
}
/* "commands" points to the next output command to write to, "*num_commands" is
initially the total amount of commands output by previous
CreateBackwardReferences calls, and must be incremented by the amount written
by this call. */
func createBackwardReferences(num_bytes uint, position uint, ringbuffer []byte, ringbuffer_mask uint, params *encoderParams, hasher hasherHandle, dist_cache []int, last_insert_len *uint, commands []command, num_commands *uint, num_literals *uint) {
var max_backward_limit uint = maxBackwardLimit(params.lgwin)
var orig_commands []command = commands
var insert_length uint = *last_insert_len
var pos_end uint = position + num_bytes
var store_end uint
if num_bytes >= hasher.StoreLookahead() {
store_end = position + num_bytes - hasher.StoreLookahead() + 1
} else {
store_end = position
}
var random_heuristics_window_size uint = literalSpreeLengthForSparseSearch(params)
var apply_random_heuristics uint = position + random_heuristics_window_size
var gap uint = 0
/* Set maximum distance, see section 9.1. of the spec. */
const kMinScore uint = scoreBase + 100
/* For speed up heuristics for random data. */
/* Minimum score to accept a backward reference. */
hasher.PrepareDistanceCache(dist_cache)
var sr2 hasherSearchResult
var sr hasherSearchResult
for position+hasher.HashTypeLength() < pos_end {
var max_length uint = pos_end - position
var max_distance uint = brotli_min_size_t(position, max_backward_limit)
sr.len = 0
sr.len_code_delta = 0
sr.distance = 0
sr.score = kMinScore
hasher.FindLongestMatch(&params.dictionary, ringbuffer, ringbuffer_mask, dist_cache, position, max_length, max_distance, gap, params.dist.max_distance, &sr)
if sr.score > kMinScore {
/* Found a match. Let's look for something even better ahead. */
var delayed_backward_references_in_row int = 0
max_length--
for ; ; max_length-- {
var cost_diff_lazy uint = 175
if params.quality < minQualityForExtensiveReferenceSearch {
sr2.len = brotli_min_size_t(sr.len-1, max_length)
} else {
sr2.len = 0
}
sr2.len_code_delta = 0
sr2.distance = 0
sr2.score = kMinScore
max_distance = brotli_min_size_t(position+1, max_backward_limit)
hasher.FindLongestMatch(&params.dictionary, ringbuffer, ringbuffer_mask, dist_cache, position+1, max_length, max_distance, gap, params.dist.max_distance, &sr2)
if sr2.score >= sr.score+cost_diff_lazy {
/* Ok, let's just write one byte for now and start a match from the
next byte. */
position++
insert_length++
sr = sr2
delayed_backward_references_in_row++
if delayed_backward_references_in_row < 4 && position+hasher.HashTypeLength() < pos_end {
continue
}
}
break
}
apply_random_heuristics = position + 2*sr.len + random_heuristics_window_size
max_distance = brotli_min_size_t(position, max_backward_limit)
{
/* The first 16 codes are special short-codes,
and the minimum offset is 1. */
var distance_code uint = computeDistanceCode(sr.distance, max_distance+gap, dist_cache)
if (sr.distance <= (max_distance + gap)) && distance_code > 0 {
dist_cache[3] = dist_cache[2]
dist_cache[2] = dist_cache[1]
dist_cache[1] = dist_cache[0]
dist_cache[0] = int(sr.distance)
hasher.PrepareDistanceCache(dist_cache)
}
initCommand(&commands[0], &params.dist, insert_length, sr.len, sr.len_code_delta, distance_code)
commands = commands[1:]
}
*num_literals += insert_length
insert_length = 0
/* Put the hash keys into the table, if there are enough bytes left.
Depending on the hasher implementation, it can push all positions
in the given range or only a subset of them.
Avoid hash poisoning with RLE data. */
{
var range_start uint = position + 2
var range_end uint = brotli_min_size_t(position+sr.len, store_end)
if sr.distance < sr.len>>2 {
range_start = brotli_min_size_t(range_end, brotli_max_size_t(range_start, position+sr.len-(sr.distance<<2)))
}
hasher.StoreRange(ringbuffer, ringbuffer_mask, range_start, range_end)
}
position += sr.len
} else {
insert_length++
position++
/* If we have not seen matches for a long time, we can skip some
match lookups. Unsuccessful match lookups are very very expensive
and this kind of a heuristic speeds up compression quite
a lot. */
if position > apply_random_heuristics {
/* Going through uncompressible data, jump. */
if position > apply_random_heuristics+4*random_heuristics_window_size {
var kMargin uint = brotli_max_size_t(hasher.StoreLookahead()-1, 4)
/* It is quite a long time since we saw a copy, so we assume
that this data is not compressible, and store hashes less
often. Hashes of non compressible data are less likely to
turn out to be useful in the future, too, so we store less of
them to not to flood out the hash table of good compressible
data. */
var pos_jump uint = brotli_min_size_t(position+16, pos_end-kMargin)
for ; position < pos_jump; position += 4 {
hasher.Store(ringbuffer, ringbuffer_mask, position)
insert_length += 4
}
} else {
var kMargin uint = brotli_max_size_t(hasher.StoreLookahead()-1, 2)
var pos_jump uint = brotli_min_size_t(position+8, pos_end-kMargin)
for ; position < pos_jump; position += 2 {
hasher.Store(ringbuffer, ringbuffer_mask, position)
insert_length += 2
}
}
}
}
}
insert_length += pos_end - position
*last_insert_len = insert_length
*num_commands += uint(-cap(commands) + cap(orig_commands))
}
... ...