作者 tangxvhui

Merge branch 'dev' into test

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

要显示太多修改。

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

@@ -22,6 +22,6 @@ @@ -22,6 +22,6 @@
22 *.sum 22 *.sum
23 23
24 24
25 -/vendor 25 +
26 /*.exe~ 26 /*.exe~
27 /logs 27 /logs
@@ -5,11 +5,12 @@ WORKDIR $APP_DIR/ @@ -5,11 +5,12 @@ WORKDIR $APP_DIR/
5 COPY ./pkg pkg 5 COPY ./pkg pkg
6 COPY ./conf conf 6 COPY ./conf conf
7 COPY ./go.mod go.mod 7 COPY ./go.mod go.mod
  8 +COPY ./vendor vendor
8 COPY ./main.go main.go 9 COPY ./main.go main.go
9 RUN ["ln","-sf","/usr/share/zoneinfo/Asia/Shanghai","/etc/localtime"] 10 RUN ["ln","-sf","/usr/share/zoneinfo/Asia/Shanghai","/etc/localtime"]
10 ENV GO111MODULE on 11 ENV GO111MODULE on
11 ENV GOPROXY https://goproxy.cn 12 ENV GOPROXY https://goproxy.cn
12 -RUN ["go","mod","tidy"]  
13 -RUN ["go","build"] 13 +# RUN ["go","mod","tidy"]
  14 +RUN ["go","build","-mod=vendor"]
14 EXPOSE 8082 15 EXPOSE 8082
15 ENTRYPOINT ["./partnermg"] 16 ENTRYPOINT ["./partnermg"]
@@ -50,3 +50,21 @@ func CreateOrderRepository(options map[string]interface{}) (domain.OrderReposito @@ -50,3 +50,21 @@ func CreateOrderRepository(options map[string]interface{}) (domain.OrderReposito
50 } 50 }
51 return repository.NewOrderRepository(transactionContext) 51 return repository.NewOrderRepository(transactionContext)
52 } 52 }
  53 +
  54 +//CreateOrderBaseRepository 订单信息
  55 +func CreateOrderBaseRepository(options map[string]interface{}) (domain.OrderBaseRepository, error) {
  56 + var transactionContext *transaction.TransactionContext
  57 + if value, ok := options["transactionContext"]; ok {
  58 + transactionContext = value.(*transaction.TransactionContext)
  59 + }
  60 + return repository.NewOrderBaseRepository(transactionContext)
  61 +}
  62 +
  63 +//CreateOrderGoodRepository 订单信息
  64 +func CreateOrderGoodRepository(options map[string]interface{}) (domain.OrderGoodRepository, error) {
  65 + var transactionContext *transaction.TransactionContext
  66 + if value, ok := options["transactionContext"]; ok {
  67 + transactionContext = value.(*transaction.TransactionContext)
  68 + }
  69 + return repository.NewOrderGoodRepository(transactionContext)
  70 +}
1 package query 1 package query
2 2
3 -//ListOrderQuery 获取用户列表 3 +//GetOrderQuery 获取订单详情
4 type GetOrderQuery struct { 4 type GetOrderQuery struct {
5 OrderId int64 `json:"orderId"` 5 OrderId int64 `json:"orderId"`
6 } 6 }
1 package query 1 package query
2 2
3 -//ListOrderQuery 获取用户列表 3 +//ListOrderQuery 获取订单列表
4 type ListOrderQuery struct { 4 type ListOrderQuery struct {
5 //合伙人id 5 //合伙人id
6 PartnerId int64 `json:"partnerId" ` 6 PartnerId int64 `json:"partnerId" `
  1 +package command
  2 +
  3 +type CreateOrderCommand struct {
  4 + //订单类型
  5 + OrderType int `json:"orderType"`
  6 + //订单编号
  7 + OrderCode string `json:"orderCode"`
  8 + //交货编号
  9 + DeliveryCode string `json:"deliveryCode"`
  10 + //买家
  11 + BuyerName string `json:"buyerName"`
  12 + //订单区域信息
  13 + OrderRegion string `json:"orderRegion"`
  14 + //订单对应的合伙人
  15 + PartnerId int64 `json:"partnerId"`
  16 + //业务员抽成比例
  17 + SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
  18 + //货品
  19 + Goods []OrderGoodData `json:"goods"`
  20 +}
  1 +package command
  2 +
  3 +//DisableOrderCommand 开启关闭订单
  4 +type DisableOrderCommand struct {
  5 + OrderId int64 `json:"orderId"`
  6 + IsDisable int `json:"isDisable"`
  7 + OrderType int `json:"orderType"`
  8 +}
  1 +package command
  2 +
  3 +type OrderGoodData struct {
  4 + //货品id
  5 + Id int64 `json:"id"`
  6 + //货品名称 长度可能较长
  7 + GoodName string `json:"goodName"`
  8 + //预计的货品数量
  9 + PlanGoodNumber int `json:"planGoodNumber"`
  10 + //货品单价
  11 + Price float64 `json:"price"`
  12 + //合伙人分红比例
  13 + PartnerBonusPercent float64 `json:"partnerBonusPercent"`
  14 + //备注信息
  15 + Remark string `json:"remark"`
  16 +}
  1 +package command
  2 +
  3 +import "time"
  4 +
  5 +type OrderDeliveryCommand struct {
  6 + OrderId int64 `json:"orderId"`
  7 + DeliveryTime time.Time `json:"deliveryTime"`
  8 + DeliveryCode string `json:"deliveryCode"`
  9 + Goods []OrderGoodData `json:"goods"`
  10 +}
  1 +package command
  2 +
  3 +//更新订单的商品数字并更新分红的数据
  4 +type UpdateGoodBouns struct {
  5 + Id int64 `json:"id"` //订单id
  6 + GoodBouns []GoodBouns `json:"goodBouns"`
  7 +}
  8 +
  9 +//GoodBoun 商品数量调整
  10 +type GoodBouns struct {
  11 + GoodId int64 `json:"goodId"` //货品id
  12 + UseGoodNumber int `json:"useGoodNumber"` //货品数量调整的数值
  13 + Remark string `json:"remark"` //原因
  14 + BounsStatus int `json:"BounsStatus"`
  15 +}
  1 +package command
  2 +
  3 +//UpdateOrderPurposeCommand 更新意向单
  4 +type UpdateOrderCommand struct {
  5 + Id int64 `json:"id"`
  6 + //订单编号
  7 + OrderCode string `json:"orderCode"`
  8 + //交货编号
  9 + DeliveryCode string `json:"deliveryCode"`
  10 + //买家
  11 + BuyerName string `json:"buyerName"`
  12 + //订单区域信息
  13 + OrderRegion string `json:"orderRegion"`
  14 + //订单对应的合伙人
  15 + PartnerId int64 `json:"partnerId"`
  16 + //业务员抽成比例
  17 + SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
  18 + //订单类型
  19 + OrderType int `json:"orderType"`
  20 + //货品
  21 + Goods []OrderGoodData `json:"goods"`
  22 +}
  1 +package query
  2 +
  3 +//GetOrderQuery 获取订单详情
  4 +type GetOrderQuery struct {
  5 + OrderId int64 `json:"orderId"`
  6 +}
  1 +package query
  2 +
  3 +//ListOrderQuery 获取用户列表
  4 +type ListOrderBaseQuery struct {
  5 + //合伙人id
  6 + PartnerId int64 `json:"partnerId" `
  7 + //订单编号
  8 + OrderCode string `json:"order_code"`
  9 + // 查询偏离量
  10 + Offset int `json:"offset" `
  11 + // 查询限制
  12 + Limit int `json:"limit"`
  13 + //订单类型
  14 + OrderType int `json:"orderType"`
  15 + //发货单号
  16 + DeliveryCode string `json:"deliveryCode"`
  17 +}
  1 +package service
  2 +
  3 +import (
  4 + "fmt"
  5 + "time"
  6 +
  7 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/command"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/query"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
  12 +)
  13 +
  14 +//OrderService 管理员相关服务
  15 +type OrderInfoService struct {
  16 +}
  17 +
  18 +func NewOrderInfoService(option map[string]interface{}) *OrderInfoService {
  19 + newAdminUserService := new(OrderInfoService)
  20 + return newAdminUserService
  21 +}
  22 +
  23 +// PageListOrderBase 获取订单列表
  24 +func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrderBaseQuery) ([]domain.OrderBase, int, error) {
  25 + transactionContext, err := factory.CreateTransactionContext(nil)
  26 + if err != nil {
  27 + return nil, 0, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
  28 + }
  29 + var (
  30 + orderRepository domain.OrderBaseRepository
  31 + orders []domain.OrderBase
  32 + cnt int
  33 + )
  34 + if value, err := factory.CreateOrderBaseRepository(map[string]interface{}{
  35 + "transactionContext": transactionContext,
  36 + }); err != nil {
  37 + return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  38 + } else {
  39 + orderRepository = value
  40 + }
  41 + query := domain.OrderBaseFindQuery{
  42 + PartnerId: listOrderQuery.PartnerId,
  43 + OrderCode: listOrderQuery.OrderCode,
  44 + Offset: listOrderQuery.Offset,
  45 + Limit: listOrderQuery.Limit,
  46 + OrderType: listOrderQuery.OrderType,
  47 + DeliveryCode: listOrderQuery.DeliveryCode,
  48 + }
  49 + orders, cnt, err = orderRepository.Find(query)
  50 + if err != nil {
  51 + return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  52 + }
  53 + var PartnerInfoRepository domain.PartnerInfoRepository
  54 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
  55 + "transactionContext": transactionContext,
  56 + }); err != nil {
  57 + return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  58 + }
  59 + for i := range orders {
  60 + var partnerData *domain.PartnerInfo
  61 + partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{
  62 + UserId: orders[i].PartnerId,
  63 + })
  64 + if err != nil {
  65 + return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  66 + }
  67 + orders[i].PartnerInfo = partnerData.Partner
  68 + }
  69 + return orders, cnt, nil
  70 +}
  71 +
  72 +//GetOrderDetail 获取订单详情
  73 +func (service OrderInfoService) GetOrderDetail(getOrderQuery query.GetOrderQuery) (*domain.OrderBase, error) {
  74 + //实际业务
  75 + transactionContext, err := factory.CreateTransactionContext(nil)
  76 + if err != nil {
  77 + return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
  78 + }
  79 + var (
  80 + orderBaseRepository domain.OrderBaseRepository
  81 + PartnerInfoRepository domain.PartnerInfoRepository
  82 + orderGoodRepository domain.OrderGoodRepository
  83 + order *domain.OrderBase
  84 + )
  85 + if err = transactionContext.StartTransaction(); err != nil {
  86 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  87 + }
  88 + defer func() {
  89 + transactionContext.RollbackTransaction()
  90 + }()
  91 + if value, err := factory.CreateOrderBaseRepository(map[string]interface{}{
  92 + "transactionContext": transactionContext,
  93 + }); err != nil {
  94 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  95 + } else {
  96 + orderBaseRepository = value
  97 + }
  98 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
  99 + "transactionContext": transactionContext,
  100 + }); err != nil {
  101 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  102 + }
  103 + if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
  104 + "transactionContext": transactionContext,
  105 + }); err != nil {
  106 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  107 + }
  108 + order, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
  109 + OrderId: getOrderQuery.OrderId,
  110 + })
  111 + if err != nil {
  112 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("获取订单数据失败:%s", err))
  113 + }
  114 + var (
  115 + partnerData *domain.PartnerInfo
  116 + goods []domain.OrderGood
  117 + )
  118 +
  119 + partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{UserId: order.PartnerId})
  120 + if err != nil {
  121 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("检索合伙人数据失败:%s", err))
  122 + }
  123 + order.PartnerInfo = partnerData.Partner
  124 + goods, _, err = orderGoodRepository.Find(domain.OrderGoodFindQuery{
  125 + OrderId: order.Id,
  126 + })
  127 + if err != nil {
  128 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("获取订单中的商品列表失败:%s", err))
  129 + }
  130 + order.Goods = goods
  131 + err = transactionContext.CommitTransaction()
  132 + if err != nil {
  133 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  134 + }
  135 + return order, nil
  136 +}
  137 +
  138 +func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (*domain.OrderBase, error) {
  139 + var (
  140 + transactionContext, _ = factory.CreateTransactionContext(nil)
  141 + err error
  142 + )
  143 +
  144 + if err = transactionContext.StartTransaction(); err != nil {
  145 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  146 + }
  147 + defer func() {
  148 + transactionContext.RollbackTransaction()
  149 + }()
  150 +
  151 + var PartnerInfoRepository domain.PartnerInfoRepository
  152 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
  153 + "transactionContext": transactionContext,
  154 + }); err != nil {
  155 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  156 + }
  157 + var partnerData *domain.PartnerInfo
  158 + partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{UserId: cmd.PartnerId})
  159 + if err != nil {
  160 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("检索合伙人数据失败"))
  161 + }
  162 + var (
  163 + orderBaseRepository domain.OrderBaseRepository
  164 + orderGoodRepository domain.OrderGoodRepository
  165 + )
  166 + if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
  167 + "transactionContext": transactionContext,
  168 + }); err != nil {
  169 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  170 + }
  171 + if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
  172 + "transactionContext": transactionContext,
  173 + }); err != nil {
  174 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  175 + }
  176 + newOrder := &domain.OrderBase{
  177 + OrderType: cmd.OrderType, OrderCode: cmd.OrderCode,
  178 + DeliveryCode: cmd.DeliveryCode,
  179 + Buyer: &domain.Buyer{
  180 + BuyerName: cmd.BuyerName,
  181 + },
  182 + RegionInfo: &domain.RegionInfo{
  183 + RegionName: cmd.OrderRegion,
  184 + },
  185 + PartnerId: cmd.PartnerId,
  186 + PartnerInfo: partnerData.Partner,
  187 + SalesmanBonusPercent: cmd.SalesmanBonusPercent,
  188 + }
  189 + var orderGoods []domain.OrderGood
  190 + for _, good := range cmd.Goods {
  191 + m := domain.NewOrderGood()
  192 + m.OrderId = 0
  193 + m.GoodName = good.GoodName
  194 + m.PlanGoodNumber = good.PlanGoodNumber
  195 + m.Price = good.Price
  196 + m.PartnerBonusPercent = good.PartnerBonusPercent
  197 + m.Remark = good.Remark
  198 + err = m.Compute()
  199 + if err != nil {
  200 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的数值失败:%s", err))
  201 + }
  202 + err = m.CurrentBonusStatus.WartPayPartnerBonus(&m)
  203 + if err != nil {
  204 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
  205 + }
  206 + orderGoods = append(orderGoods, m)
  207 + }
  208 + newOrder.Goods = orderGoods
  209 + err = newOrder.Compute()
  210 + if err != nil {
  211 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
  212 + }
  213 + err = orderBaseRepository.Save(newOrder)
  214 + if err != nil {
  215 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
  216 + }
  217 + for i := range newOrder.Goods {
  218 + newOrder.Goods[i].OrderId = newOrder.Id
  219 + }
  220 + err = orderGoodRepository.Save(orderGoods)
  221 + if err != nil {
  222 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单中的商品数据失败:%s", err))
  223 + }
  224 + newOrder.Goods = orderGoods
  225 + err = transactionContext.CommitTransaction()
  226 + if err != nil {
  227 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  228 + }
  229 + return newOrder, nil
  230 +}
  231 +
  232 +//DeleteOrder 删除订单
  233 +func (service OrderInfoService) DeleteOrder(orderId int64) error {
  234 + var (
  235 + transactionContext, _ = factory.CreateTransactionContext(nil)
  236 + err error
  237 + )
  238 + if err = transactionContext.StartTransaction(); err != nil {
  239 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  240 + }
  241 + defer func() {
  242 + transactionContext.RollbackTransaction()
  243 + }()
  244 + var (
  245 + orderBaseRepository domain.OrderBaseRepository
  246 + orderGoodRepository domain.OrderGoodRepository
  247 + )
  248 + if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
  249 + "transactionContext": transactionContext,
  250 + }); err != nil {
  251 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  252 + }
  253 + if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
  254 + "transactionContext": transactionContext,
  255 + }); err != nil {
  256 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  257 + }
  258 + err = orderBaseRepository.Remove(orderId)
  259 + if err != nil {
  260 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("删除订单数据失败:%s", err))
  261 + }
  262 + err = orderGoodRepository.Remove(orderId)
  263 + if err != nil {
  264 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("删除订单中商品数据失败:%s", err))
  265 + }
  266 + err = transactionContext.CommitTransaction()
  267 + if err != nil {
  268 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  269 + }
  270 + return nil
  271 +}
  272 +
  273 +//UpdateOrderData 编辑订单
  274 +func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand) (*domain.OrderBase, error) {
  275 + var (
  276 + transactionContext, _ = factory.CreateTransactionContext(nil)
  277 + err error
  278 + )
  279 +
  280 + if err = transactionContext.StartTransaction(); err != nil {
  281 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  282 + }
  283 + defer func() {
  284 + transactionContext.RollbackTransaction()
  285 + }()
  286 +
  287 + var PartnerInfoRepository domain.PartnerInfoRepository
  288 + if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
  289 + "transactionContext": transactionContext,
  290 + }); err != nil {
  291 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  292 + }
  293 + var partnerData *domain.PartnerInfo
  294 + partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{UserId: cmd.PartnerId})
  295 + if err != nil {
  296 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("检索合伙人数据失败"))
  297 + }
  298 + var (
  299 + orderBaseRepository domain.OrderBaseRepository
  300 + orderGoodRepository domain.OrderGoodRepository
  301 + oldOrderData *domain.OrderBase
  302 + oldOrderGoods []domain.OrderGood
  303 + newOrderGoods []domain.OrderGood
  304 + delGoods []int64
  305 + )
  306 + if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
  307 + "transactionContext": transactionContext,
  308 + }); err != nil {
  309 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  310 + }
  311 + if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
  312 + "transactionContext": transactionContext,
  313 + }); err != nil {
  314 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  315 + }
  316 + //获取旧的订单
  317 + oldOrderData, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
  318 + OrderId: cmd.Id,
  319 + })
  320 + if err != nil {
  321 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单:%s", err))
  322 + }
  323 + //判定要求的更新的订单类型
  324 + if oldOrderData.OrderType != cmd.OrderType {
  325 + return nil, lib.ThrowError(lib.BUSINESS_ERROR, fmt.Sprintf("操作失败,待更新的订单的类型已变更"))
  326 + }
  327 + //获取旧的订单中的商品
  328 + oldOrderGoods, _, err = orderGoodRepository.Find(domain.OrderGoodFindQuery{
  329 + OrderId: cmd.Id,
  330 + })
  331 + if err != nil {
  332 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单中的商品列表失败:%s", err))
  333 + }
  334 + for _, good := range cmd.Goods {
  335 + m := domain.NewOrderGood()
  336 + m.OrderId = oldOrderData.Id
  337 + m.GoodName = good.GoodName
  338 + m.PlanGoodNumber = good.PlanGoodNumber
  339 + m.Price = good.Price
  340 + m.PartnerBonusPercent = good.PartnerBonusPercent
  341 + m.Remark = good.Remark
  342 + err = m.Compute()
  343 + if err != nil {
  344 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的数值失败:%s", err))
  345 + }
  346 + err = m.CurrentBonusStatus.WartPayPartnerBonus(&m)
  347 + if err != nil {
  348 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
  349 + }
  350 + newOrderGoods = append(newOrderGoods, m)
  351 + }
  352 + oldOrderData.OrderCode = cmd.OrderCode
  353 + oldOrderData.DeliveryCode = cmd.DeliveryCode
  354 + oldOrderData.Buyer.BuyerName = cmd.BuyerName
  355 + oldOrderData.RegionInfo.RegionName = cmd.OrderRegion
  356 + oldOrderData.PartnerId = cmd.PartnerId
  357 + oldOrderData.PartnerInfo = partnerData.Partner
  358 + oldOrderData.SalesmanBonusPercent = cmd.SalesmanBonusPercent
  359 + oldOrderData.Goods = newOrderGoods
  360 + err = oldOrderData.Compute()
  361 + if err != nil {
  362 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
  363 + }
  364 +
  365 + err = orderBaseRepository.Save(oldOrderData)
  366 + if err != nil {
  367 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
  368 + }
  369 + err = orderGoodRepository.Save(newOrderGoods)
  370 + if err != nil {
  371 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单中的商品数据失败:%s", err))
  372 + }
  373 + oldOrderData.Goods = newOrderGoods
  374 + //删不需要的订单总不需要的商品
  375 + delGoods = service.deleteOldOrderGoods(newOrderGoods, oldOrderGoods)
  376 + err = orderGoodRepository.Remove(oldOrderData.Id, delGoods...)
  377 + if err != nil {
  378 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("删除订单中的商品数据失败:%s", err))
  379 + }
  380 + err = transactionContext.CommitTransaction()
  381 + if err != nil {
  382 + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  383 + }
  384 + return oldOrderData, nil
  385 +}
  386 +
  387 +//deleteOldOrderGoods 新旧商品列表对比
  388 +func (service OrderInfoService) deleteOldOrderGoods(newGoods []domain.OrderGood, oldGoods []domain.OrderGood) (goodIds []int64) {
  389 + for _, old := range oldGoods {
  390 + var hasIn bool
  391 + for _, new := range newGoods {
  392 + if old.Id == new.Id {
  393 + hasIn = true
  394 + break
  395 + }
  396 + }
  397 + if !hasIn {
  398 + goodIds = append(goodIds, old.Id)
  399 + }
  400 + }
  401 + return
  402 +}
  403 +
  404 +//Delivery 发货
  405 +func (service OrderInfoService) Delivery(cmd command.OrderDeliveryCommand) error {
  406 + var (
  407 + transactionContext, _ = factory.CreateTransactionContext(nil)
  408 + err error
  409 + )
  410 + if err = transactionContext.StartTransaction(); err != nil {
  411 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  412 + }
  413 + defer func() {
  414 + transactionContext.RollbackTransaction()
  415 + }()
  416 + var (
  417 + orderBaseRepository domain.OrderBaseRepository
  418 + orderGoodRepository domain.OrderGoodRepository
  419 + oldOrderData *domain.OrderBase
  420 + oldOrderGoods []domain.OrderGood
  421 + )
  422 + if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
  423 + "transactionContext": transactionContext,
  424 + }); err != nil {
  425 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  426 + }
  427 + if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
  428 + "transactionContext": transactionContext,
  429 + }); err != nil {
  430 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  431 + }
  432 + //获取旧的订单
  433 + oldOrderData, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
  434 + OrderId: cmd.OrderId,
  435 + })
  436 + if err != nil {
  437 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单:%s", err))
  438 + }
  439 + //获取旧的订单中的商品
  440 + oldOrderGoods, _, err = orderGoodRepository.Find(domain.OrderGoodFindQuery{
  441 + OrderId: cmd.OrderId,
  442 + })
  443 + if err != nil {
  444 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单中的商品列表失败:%s", err))
  445 + }
  446 + for _, newGood := range cmd.Goods {
  447 + for i := range oldOrderGoods {
  448 + if newGood.Id != oldOrderGoods[i].Id {
  449 + continue
  450 + }
  451 + oldOrderGoods[i].GoodName = newGood.GoodName
  452 + oldOrderGoods[i].PlanGoodNumber = newGood.PlanGoodNumber
  453 + oldOrderGoods[i].Price = newGood.Price
  454 + oldOrderGoods[i].PartnerBonusPercent = newGood.PartnerBonusPercent
  455 + oldOrderGoods[i].Remark = newGood.Remark
  456 + err = oldOrderGoods[i].Compute()
  457 + if err != nil {
  458 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的数值失败:%s", err))
  459 + }
  460 + err = oldOrderGoods[i].CurrentBonusStatus.WartPayPartnerBonus(&oldOrderGoods[i])
  461 + if err != nil {
  462 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
  463 + }
  464 + }
  465 + }
  466 + oldOrderData.DeliveryCode = cmd.DeliveryCode
  467 + oldOrderData.DeliveryTime = time.Now()
  468 + oldOrderData.Goods = oldOrderGoods
  469 + //变更订单类型
  470 + oldOrderData.OrderType = domain.OrderReal
  471 + err = oldOrderData.Compute()
  472 + if err != nil {
  473 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
  474 + }
  475 + err = orderBaseRepository.Save(oldOrderData)
  476 + if err != nil {
  477 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
  478 + }
  479 + err = orderGoodRepository.Save(oldOrderGoods)
  480 + if err != nil {
  481 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单中的商品数据失败:%s", err))
  482 + }
  483 + err = transactionContext.CommitTransaction()
  484 + if err != nil {
  485 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  486 + }
  487 + return nil
  488 +}
  489 +
  490 +//DisableOrEnable 开启关闭订单
  491 +func (service OrderInfoService) DisableOrEnable(cmd command.DisableOrderCommand) error {
  492 + var (
  493 + transactionContext, _ = factory.CreateTransactionContext(nil)
  494 + err error
  495 + )
  496 + if err = transactionContext.StartTransaction(); err != nil {
  497 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  498 + }
  499 + defer func() {
  500 + transactionContext.RollbackTransaction()
  501 + }()
  502 + var (
  503 + orderBaseRepository domain.OrderBaseRepository
  504 + oldOrderData *domain.OrderBase
  505 + )
  506 + if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
  507 + "transactionContext": transactionContext,
  508 + }); err != nil {
  509 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  510 + }
  511 + //获取旧的订单
  512 + oldOrderData, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
  513 + OrderId: cmd.OrderId,
  514 + })
  515 + if err != nil {
  516 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单:%s", err))
  517 + }
  518 + if oldOrderData.OrderType != cmd.OrderType {
  519 + return lib.ThrowError(lib.BUSINESS_ERROR, fmt.Sprintf("操作失败,指定的订单的类型发生变更"))
  520 + }
  521 + oldOrderData.IsDisable = cmd.IsDisable
  522 + err = orderBaseRepository.Save(oldOrderData)
  523 + if err != nil {
  524 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
  525 + }
  526 + err = transactionContext.CommitTransaction()
  527 + if err != nil {
  528 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  529 + }
  530 + return nil
  531 +}
  532 +
  533 +//UpdateGoodBouns 更新货品的分红相关的数值
  534 +func (service OrderInfoService) UpdateGoodBouns(cmd command.UpdateGoodBouns) error {
  535 + var (
  536 + transactionContext, _ = factory.CreateTransactionContext(nil)
  537 + err error
  538 + )
  539 + if err = transactionContext.StartTransaction(); err != nil {
  540 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  541 + }
  542 + defer func() {
  543 + transactionContext.RollbackTransaction()
  544 + }()
  545 + var (
  546 + orderBaseRepository domain.OrderBaseRepository
  547 + orderGoodRepository domain.OrderGoodRepository
  548 + oldOrderData *domain.OrderBase
  549 + oldOrderGoods []domain.OrderGood
  550 + )
  551 + if orderBaseRepository, err = factory.CreateOrderBaseRepository(map[string]interface{}{
  552 + "transactionContext": transactionContext,
  553 + }); err != nil {
  554 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  555 + }
  556 + if orderGoodRepository, err = factory.CreateOrderGoodRepository(map[string]interface{}{
  557 + "transactionContext": transactionContext,
  558 + }); err != nil {
  559 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  560 + }
  561 + //获取旧的订单
  562 + oldOrderData, err = orderBaseRepository.FindOne(domain.OrderBaseFindOneQuery{
  563 + OrderId: cmd.Id,
  564 + })
  565 + if err != nil {
  566 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单:%s", err))
  567 + }
  568 + if oldOrderData.OrderType != domain.OrderReal {
  569 + return lib.ThrowError(lib.BUSINESS_ERROR, fmt.Sprintf("指定的订单的订单类型发生变更"))
  570 + }
  571 + //获取旧的订单中的商品
  572 + oldOrderGoods, _, err = orderGoodRepository.Find(domain.OrderGoodFindQuery{
  573 + OrderId: cmd.Id,
  574 + })
  575 + if err != nil {
  576 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("未找到指定的订单中的商品列表失败:%s", err))
  577 + }
  578 + for _, newGood := range cmd.GoodBouns {
  579 + for i := range oldOrderGoods {
  580 + if newGood.GoodId != oldOrderGoods[i].Id {
  581 + continue
  582 + }
  583 + oldOrderGoods[i].UseGoodNumber = newGood.UseGoodNumber
  584 + oldOrderGoods[i].Remark = newGood.Remark
  585 + oldOrderGoods[i].BonusStatus = newGood.BounsStatus
  586 + err = oldOrderGoods[i].Compute()
  587 + if err != nil {
  588 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的数值失败:%s", err))
  589 + }
  590 + switch newGood.BounsStatus {
  591 + case domain.OrderGoodWaitPay:
  592 + err = oldOrderGoods[i].CurrentBonusStatus.WartPayPartnerBonus(&oldOrderGoods[i])
  593 + if err != nil {
  594 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
  595 + }
  596 + case domain.OrderGoodHasPay:
  597 + err = oldOrderGoods[i].CurrentBonusStatus.PayPartnerBonus(&oldOrderGoods[i])
  598 + if err != nil {
  599 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中商品的分红数值失败:%s", err))
  600 + }
  601 + default:
  602 + return lib.ThrowError(lib.ARG_ERROR, fmt.Sprintf("货品的支付状态错误"))
  603 + }
  604 + }
  605 + }
  606 + //变更订单类型
  607 + err = oldOrderData.Compute()
  608 + if err != nil {
  609 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("核算订单中合计的数值失败:%s", err))
  610 + }
  611 + err = orderBaseRepository.Save(oldOrderData)
  612 + if err != nil {
  613 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单数据失败:%s", err))
  614 + }
  615 + err = orderGoodRepository.Save(oldOrderGoods)
  616 + if err != nil {
  617 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("保存订单中的商品数据失败:%s", err))
  618 + }
  619 + err = transactionContext.CommitTransaction()
  620 + if err != nil {
  621 + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
  622 + }
  623 + return nil
  624 +
  625 +}
@@ -7,26 +7,11 @@ import ( @@ -7,26 +7,11 @@ import (
7 ) 7 )
8 8
9 const ( 9 const (
10 - OrderStatusReserve int = iota + 1 //预定中  
11 - OrderStatusDeliverSome //部分发货  
12 - OrderStatusDeliverAll //全部发货 10 + OrderStatusReserve = iota + 1 //预定中
  11 + OrderStatusDeliverSome //部分发货
  12 + OrderStatusDeliverAll //全部发货
13 ) 13 )
14 14
15 -const (  
16 - OrderReal int = iota + 1 //实发订单  
17 - OrderIntention //意向订单  
18 -)  
19 -  
20 -//买家  
21 -type Buyer struct {  
22 - //买家姓名  
23 - BuyerName string `json:"buyerName"`  
24 - //联系方式  
25 - ContactInfo string `json:"contactInfo"`  
26 - //收获地址  
27 - ShippingAddress string `json:"shippingAddress"`  
28 -}  
29 -  
30 type Order struct { 15 type Order struct {
31 Id int64 `json:"id"` 16 Id int64 `json:"id"`
32 //订单类型 17 //订单类型
@@ -157,15 +142,16 @@ type OrderFindOneQuery struct { @@ -157,15 +142,16 @@ type OrderFindOneQuery struct {
157 } 142 }
158 143
159 type OrderFindQuery struct { 144 type OrderFindQuery struct {
160 - PartnerId int64  
161 - OrderCode string  
162 - Offset int  
163 - Limit int  
164 - OrderType int 145 + PartnerId int64
  146 + OrderCode string
  147 + DeliveryCode string
  148 + Offset int
  149 + Limit int
  150 + OrderType int
165 } 151 }
166 152
167 type OrderRepository interface { 153 type OrderRepository interface {
168 - Save(order Order) error 154 + Save(order *Order) error
169 FindOne(qureyOptions OrderFindOneQuery) (*Order, error) 155 FindOne(qureyOptions OrderFindOneQuery) (*Order, error)
170 Find(queryOptions OrderFindQuery) ([]Order, error) 156 Find(queryOptions OrderFindQuery) ([]Order, error)
171 CountAll(queryOption OrderFindQuery) (int, error) 157 CountAll(queryOption OrderFindQuery) (int, error)
  1 +package domain
  2 +
  3 +import (
  4 + "time"
  5 +
  6 + "github.com/shopspring/decimal"
  7 +)
  8 +
  9 +const (
  10 + OrderReal = iota + 1 //实发订单
  11 + OrderIntention //意向订单
  12 +)
  13 +
  14 +const (
  15 + OrderDisableNot = iota //订单未关闭
  16 + OrderDisableYes //订单已关闭
  17 +)
  18 +
  19 +//Buyer 买家
  20 +type Buyer struct {
  21 + //买家姓名
  22 + BuyerName string `json:"buyerName"`
  23 + //联系方式
  24 + ContactInfo string `json:"contactInfo"`
  25 + //收获地址
  26 + ShippingAddress string `json:"shippingAddress"`
  27 +}
  28 +
  29 +//OrderBase 订单基础
  30 +type OrderBase struct {
  31 + //表id
  32 + Id int64 `json:"id"`
  33 + //订单类型
  34 + OrderType int `json:"orderType"`
  35 + //订单编号
  36 + OrderCode string `json:"orderCode"`
  37 + //交货编号
  38 + DeliveryCode string `json:"deliveryCode"`
  39 + //买家
  40 + Buyer *Buyer `json:"buyer"`
  41 + //订单区域信息
  42 + RegionInfo *RegionInfo `json:"regionInfo"`
  43 + //订单对应的合伙人
  44 + PartnerId int64 `json:"partnerId"`
  45 + PartnerInfo Partner `json:"partnerInfo"`
  46 + //业务员抽成比例
  47 + SalesmanBonusPercent float64 `json:"salesmanBonusPercent"`
  48 + //订单的创建时间
  49 + CreateTime time.Time `json:"createTime"`
  50 + //发货时间
  51 + DeliveryTime time.Time `json:"deliveryTime"`
  52 + //更新时间
  53 + UpdateTime time.Time `json:"updateTime"`
  54 + //货品
  55 + Goods []OrderGood `json:"goods"`
  56 + //核算订单相关数据
  57 + OrderCompute OrderCompute `json:"orderCompute"`
  58 + //是否关闭订单
  59 + IsDisable int `json:"isDisable"`
  60 + //分红支付状态
  61 + BonusStatus int `json:"bonusStatus"`
  62 +}
  63 +
  64 +type OrderCompute struct {
  65 + //合伙人应收分红
  66 + PlanPartnerBonus float64 `json:"planPartnerBonus"`
  67 + //调整后的合伙人应收分红 (初始值=-1);
  68 + //业务判定时0是有效值,
  69 + //所以用空串表示无值,转换到数据库中为负值
  70 + UsePartnerBonus float64 `json:"usePartnerBonus"`
  71 + //合伙人已收分红
  72 + PartnerBonusHas float64 `json:"partnerBonusHas"`
  73 + //合伙人未收分红
  74 + PartnerBonusNot float64 `json:"partnerBonusNot"`
  75 + //合伙人分红支出
  76 + PartnerBonusExpense float64 `json:"partnerBonusExpense"`
  77 + //业务员抽成
  78 + SalesmanBonus float64 `json:"salesmanBonus"`
  79 + //预计的订单内货品总数
  80 + PlanOrderCount int `json:"planOrderCount"`
  81 + //预计的订单的总金额
  82 + PlanOrderAmount float64 `json:"planOrderAmount"`
  83 + //按需使用的订单内货品总数 (初始值=-1)
  84 + //业务判定时0是有效值,
  85 + //所以用空串表示无值,转换到数据库中为负值
  86 + UseOrderCount int `json:"useOrderCount"`
  87 + //按需使用的订单内货总金额 (初始值=-1)
  88 + //业务判定时0是有效值,
  89 + //所以用空串表示无值,转换到数据库中为负值
  90 + UseOrderAmount float64 `json:"useOrderAmount"`
  91 +}
  92 +
  93 +//Compute 数据汇总核算
  94 +func (order *OrderBase) Compute() error {
  95 + planPartnerBonus := decimal.NewFromFloat(0)
  96 + planOrderAmount := decimal.NewFromFloat(0)
  97 + var (
  98 + planOrderCount int = 0
  99 + useOrderCount int = 0
  100 + HasUseOrderCount bool = false
  101 + )
  102 + usePartnerBonus := decimal.NewFromFloat(0)
  103 + var hasUsePartnerBonus bool = false
  104 + useOrderAmount := decimal.NewFromFloat(0)
  105 + var hasUseOrderAmount bool = false
  106 + partnerBonusHas := decimal.NewFromFloat(0)
  107 + partnerBonusNot := decimal.NewFromFloat(0)
  108 + partnerBonusExpense := decimal.NewFromFloat(0)
  109 + //初始订单的支付状态
  110 + order.BonusStatus = OrderGoodWaitPay
  111 + //统计所以货品的值
  112 + for i := range order.Goods {
  113 + if order.Goods[i].BonusStatus == OrderGoodHasPay {
  114 + //确定订单的支付状态
  115 + order.BonusStatus = OrderGoodHasPay
  116 + }
  117 + planPartnerBonus = planPartnerBonus.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PlanPartnerBonus))
  118 + planOrderAmount = planOrderAmount.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PlanAmount))
  119 + planOrderCount += order.Goods[i].PlanGoodNumber
  120 + goodUseAmount := decimal.NewFromFloat(order.Goods[i].GoodCompute.UseAmount)
  121 + if goodUseAmount.GreaterThanOrEqual(decimal.NewFromFloat(0)) {
  122 + //调整值非负值得情况
  123 + hasUseOrderAmount = true
  124 + useOrderAmount = useOrderAmount.Add(goodUseAmount)
  125 + } else {
  126 + useOrderAmount = useOrderAmount.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PlanAmount))
  127 + }
  128 + goodUsePartnerBonus := decimal.NewFromFloat(order.Goods[i].GoodCompute.UsePartnerBonus)
  129 + if goodUsePartnerBonus.GreaterThanOrEqual(decimal.NewFromFloat(0)) {
  130 + hasUsePartnerBonus = true
  131 + usePartnerBonus = usePartnerBonus.Add(goodUsePartnerBonus)
  132 + } else {
  133 + usePartnerBonus = usePartnerBonus.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PlanPartnerBonus))
  134 + }
  135 + if order.Goods[i].UseGoodNumber >= 0 {
  136 + HasUseOrderCount = true
  137 + useOrderCount += order.Goods[i].UseGoodNumber
  138 + } else {
  139 + useOrderCount += order.Goods[i].PlanGoodNumber
  140 + }
  141 + partnerBonusHas = partnerBonusHas.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PartnerBonusHas))
  142 + partnerBonusNot = partnerBonusNot.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PartnerBonusNot))
  143 + partnerBonusExpense = partnerBonusExpense.Add(decimal.NewFromFloat(order.Goods[i].GoodCompute.PartnerBonusExpense))
  144 + }
  145 + //汇总赋值
  146 + order.OrderCompute.PartnerBonusExpense, _ = partnerBonusExpense.Round(2).Float64()
  147 + order.OrderCompute.PartnerBonusHas, _ = partnerBonusHas.Round(2).Float64()
  148 + order.OrderCompute.PartnerBonusNot, _ = partnerBonusNot.Round(2).Float64()
  149 + order.OrderCompute.PlanPartnerBonus, _ = planPartnerBonus.Round(2).Float64()
  150 + order.OrderCompute.PlanOrderAmount, _ = planOrderAmount.Round(2).Float64()
  151 + order.OrderCompute.PlanOrderCount = planOrderCount
  152 +
  153 + if hasUsePartnerBonus {
  154 + order.OrderCompute.UsePartnerBonus, _ = usePartnerBonus.Round(2).Float64()
  155 + } else {
  156 + order.OrderCompute.UsePartnerBonus = -1
  157 + }
  158 + if hasUseOrderAmount {
  159 + order.OrderCompute.UseOrderAmount, _ = useOrderAmount.Round(2).Float64()
  160 + //计算业务员的抽成
  161 + order.OrderCompute.SalesmanBonus, _ = useOrderAmount.
  162 + Mul(decimal.NewFromFloat(order.SalesmanBonusPercent)).
  163 + Div(decimal.NewFromInt(100)).
  164 + Round(2).Float64()
  165 + } else {
  166 + order.OrderCompute.UseOrderAmount = -1
  167 + order.OrderCompute.SalesmanBonus, _ = planOrderAmount.
  168 + Mul(decimal.NewFromFloat(order.SalesmanBonusPercent)).
  169 + Div(decimal.NewFromInt(100)).
  170 + Round(2).Float64()
  171 + }
  172 + if HasUseOrderCount {
  173 + order.OrderCompute.UseOrderCount = useOrderCount
  174 + } else {
  175 + order.OrderCompute.UseOrderCount = -1
  176 + }
  177 + return nil
  178 +}
  179 +
  180 +type OrderBaseFindOneQuery struct {
  181 + OrderId int64
  182 +}
  183 +
  184 +type OrderBaseFindQuery struct {
  185 + PartnerId int64
  186 + OrderCode string
  187 + DeliveryCode string
  188 + Offset int
  189 + Limit int
  190 + OrderType int
  191 +}
  192 +
  193 +type OrderBaseRepository interface {
  194 + Save(order *OrderBase) error
  195 + FindOne(qureyOptions OrderBaseFindOneQuery) (*OrderBase, error)
  196 + Find(queryOptions OrderBaseFindQuery) ([]OrderBase, int, error)
  197 + Remove(id int64) error
  198 +}
  1 +package domain
  2 +
  3 +import (
  4 + "errors"
  5 +
  6 + "github.com/shopspring/decimal"
  7 +)
  8 +
  9 +//分红状态
  10 +type OrderGoodBonusStatus interface {
  11 + //状态变更为待支付
  12 + WartPayPartnerBonus(orderGood *OrderGood) error
  13 + //状态变更为已支付
  14 + PayPartnerBonus(orderGood *OrderGood) error
  15 +}
  16 +
  17 +//货单的支付状态
  18 +const (
  19 + //待支付
  20 + OrderGoodWaitPay int = 1
  21 + //已支付
  22 + OrderGoodHasPay int = 2
  23 +)
  24 +
  25 +//OrderGood 订单中的货品
  26 +type OrderGood struct {
  27 + //货品id
  28 + Id int64 `json:"id"`
  29 + //所属订单id
  30 + OrderId int64 `json:"orderId"`
  31 + //货品名称 长度可能较长
  32 + GoodName string `json:"goodName"`
  33 + //预计的货品数量
  34 + PlanGoodNumber int `json:"planGoodNumber"`
  35 + //调整后的货品数量
  36 + //业务判定时0是有效值,
  37 + //所以用空串表示无值,转换到数据库中为负值
  38 + UseGoodNumber int `json:"useGoodNumber"`
  39 + //货品单价
  40 + Price float64 `json:"price"`
  41 + //合伙人分红比例
  42 + PartnerBonusPercent float64 `json:"partnerBonusPercent"`
  43 + //分红支付状态
  44 + BonusStatus int `json:"bonusStatus"`
  45 + //备注信息
  46 + Remark string `json:"remark"`
  47 + //当前分红支付状态
  48 + CurrentBonusStatus OrderGoodBonusStatus `json:"-"`
  49 + ///核算订单相关数据
  50 + GoodCompute GoodCompute `json:"goodCompute"`
  51 +}
  52 +
  53 +type GoodCompute struct {
  54 + //预计的货品总额
  55 + PlanAmount float64 `json:"planAmount"`
  56 + //调整后的货品总额 (初始值=-1)
  57 + //业务判定时0是有效值,
  58 + //所以用空串表示无值,转换到数据库中为负值
  59 + UseAmount float64 `json:"useAmount"`
  60 + //预计的合伙人分红
  61 + PlanPartnerBonus float64 `json:"planPartnerBonus"`
  62 + //合伙人应收分红调整 (初始值=-1),
  63 + //业务判定时0是有效值,
  64 + //所以用空串表示无值,转换到数据库中为负值
  65 + UsePartnerBonus float64 `json:"usePartnerBonus"`
  66 + //合伙人已收分红
  67 + PartnerBonusHas float64 `json:"partnerBonusHas"`
  68 + //合伙人未收分红
  69 + PartnerBonusNot float64 `json:"partnerBonusNot"`
  70 + //合伙人分红支出
  71 + PartnerBonusExpense float64 `json:"partnerBonusExpense"`
  72 +}
  73 +
  74 +//OrderGoodBonusWaitPay 货品分红待支付
  75 +type OrderGoodBonusWaitPay struct{}
  76 +
  77 +var _ OrderGoodBonusStatus = (*OrderGoodBonusWaitPay)(nil)
  78 +
  79 +//OrderGoodBonusHasPay 货品分红已支付
  80 +type OrderGoodBonusHasPay struct{}
  81 +
  82 +var _ OrderGoodBonusStatus = (*OrderGoodBonusHasPay)(nil)
  83 +
  84 +func (waitPay OrderGoodBonusWaitPay) WartPayPartnerBonus(good *OrderGood) error {
  85 + good.GoodCompute.PartnerBonusExpense = 0
  86 + good.GoodCompute.PartnerBonusHas = 0
  87 + //初始状态为待支付时 ,合伙人未收分红等于合伙人应收分红(或者调整的)
  88 + if good.UseGoodNumber < 0 {
  89 + //数量没有调整,未收等于预计应收分红
  90 + good.GoodCompute.PartnerBonusNot = good.GoodCompute.PlanPartnerBonus
  91 + } else {
  92 + //数量有调整,未收等于调整后的应收分红
  93 + good.GoodCompute.PartnerBonusNot = good.GoodCompute.UsePartnerBonus
  94 + }
  95 + good.CurrentBonusStatus = OrderGoodBonusWaitPay{}
  96 + return nil
  97 +}
  98 +
  99 +func (waitPay OrderGoodBonusWaitPay) PayPartnerBonus(good *OrderGood) error {
  100 + //待支付状态转支付时
  101 + //合伙人已收收分红等于合伙人应收分红(或者调整的)
  102 + //计算已支付
  103 + if good.UseGoodNumber < 0 {
  104 + //数量没有调整,已收等于预计应收分红
  105 + good.GoodCompute.PartnerBonusHas = good.GoodCompute.PlanPartnerBonus
  106 + } else {
  107 + //数量有调整,已收等于调整后的应收分红
  108 + good.GoodCompute.PartnerBonusHas = good.GoodCompute.UsePartnerBonus
  109 + }
  110 + good.GoodCompute.PartnerBonusExpense = 0
  111 + good.GoodCompute.PartnerBonusNot = 0
  112 + good.CurrentBonusStatus = OrderGoodBonusHasPay{}
  113 + return nil
  114 +}
  115 +
  116 +func (hasPay OrderGoodBonusHasPay) PayPartnerBonus(good *OrderGood) error {
  117 + //已支付的值保持不变
  118 + //未支付的值保持不变
  119 + //计算分红支出
  120 + //分红支出=应收分红(有出现调整,则取调整后的应收分红)和已收分红的差额
  121 + if good.UseGoodNumber >= 0 {
  122 + //有数量调整,分红支出等于 已支付分红-调整后的已收分红
  123 + good.GoodCompute.PartnerBonusExpense = good.GoodCompute.PartnerBonusHas - good.GoodCompute.UsePartnerBonus
  124 + }
  125 + good.CurrentBonusStatus = OrderGoodBonusHasPay{}
  126 + return nil
  127 +}
  128 +
  129 +func (hasPay OrderGoodBonusHasPay) WartPayPartnerBonus(good *OrderGood) error {
  130 + return errors.New("已支付的货单不能将状态回退为待支付")
  131 +}
  132 +
  133 +//NewOrderGood 初始值设定
  134 +func NewOrderGood() OrderGood {
  135 + return OrderGood{
  136 + UseGoodNumber: -1,
  137 + BonusStatus: OrderGoodWaitPay,
  138 + GoodCompute: GoodCompute{
  139 + UsePartnerBonus: -1,
  140 + UseAmount: -1,
  141 + },
  142 + CurrentBonusStatus: OrderGoodBonusWaitPay{},
  143 + }
  144 +}
  145 +
  146 +//Compute 数据汇总核算
  147 +func (good *OrderGood) Compute() error {
  148 + //计算预计货品总值
  149 + //计算预计合伙人分红
  150 + price := decimal.NewFromFloat(good.Price)
  151 + planamount := price.Mul(decimal.NewFromInt(int64(good.PlanGoodNumber))) //price*planGoodNumber
  152 + //price*useGoodNumber
  153 + planPartnerBonus := planamount.Mul(decimal.NewFromFloat(good.PartnerBonusPercent)).Div(decimal.NewFromInt(100)) //price*planGoodNumber*PartnerBonusPercent
  154 + good.GoodCompute.PlanAmount, _ = planamount.Round(2).Float64()
  155 + good.GoodCompute.PlanPartnerBonus, _ = planPartnerBonus.Round(2).Float64()
  156 + if good.UseGoodNumber < 0 {
  157 + //没有出现数量调整
  158 + good.GoodCompute.UsePartnerBonus = -1
  159 + good.GoodCompute.UseAmount = -1
  160 + } else {
  161 + //计算调整后的货品总值
  162 + //计算调整后的合伙人分红
  163 + useamount := price.Mul(decimal.NewFromInt(int64(good.UseGoodNumber))) //price*useGoodNumber/price*useGoodNumber
  164 + usePartnerBonus := useamount.Mul(decimal.NewFromFloat(good.PartnerBonusPercent)).Div(decimal.NewFromInt(100)) //price*useGoodNumber*PartnerBonusPercent
  165 + good.GoodCompute.UsePartnerBonus, _ = usePartnerBonus.Round(2).Float64()
  166 + good.GoodCompute.UseAmount, _ = useamount.Round(2).Float64()
  167 + }
  168 +
  169 + return nil
  170 +}
  171 +
  172 +type OrderGoodFindQuery struct {
  173 + OrderId int64
  174 + Offset int
  175 + Limit int
  176 +}
  177 +
  178 +type OrderGoodRepository interface {
  179 + Save(order []OrderGood) error
  180 + Find(queryOptions OrderGoodFindQuery) ([]OrderGood, int, error)
  181 + Remove(orderid int64, ids ...int64) error
  182 +}
  1 +package models
  2 +
  3 +import (
  4 + "context"
  5 + "time"
  6 +
  7 + "github.com/go-pg/pg/v10"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  9 +)
  10 +
  11 +//OrderBase 订单基础
  12 +type OrderBase struct {
  13 + tableName struct{} `pg:"order_base"`
  14 + //表id
  15 + Id int64 `pg:",pk"`
  16 + //订单类型
  17 + OrderType int
  18 + //订单编号
  19 + OrderCode string
  20 + //交货编号
  21 + DeliveryCode string
  22 + //买家
  23 + Buyer *domain.Buyer
  24 + //订单区域信息
  25 + RegionInfo *domain.RegionInfo
  26 + //订单对应的合伙人
  27 + PartnerId int64
  28 + //业务员抽成比例
  29 + SalesmanBonusPercent float64
  30 + //业务员抽成
  31 + SalesmanBonus float64
  32 + //预计的订单内货品总数
  33 + PlanOrderCount int
  34 + //预计的订单的总金额
  35 + PlanOrderAmount float64
  36 + //按需使用的订单内货品总数 (初始值=-1)
  37 + //业务判定时0是有效值,负值无效
  38 + UseOrderCount int
  39 + //按需使用的订单内货总金额 (初始值=-1)
  40 + //业务判定时0是有效值,负值无效
  41 + UseOrderAmount float64
  42 + //订单的创建时间
  43 + CreateTime time.Time
  44 + //发货时间
  45 + DeliveryTime time.Time
  46 + //更新时间
  47 + UpdateTime time.Time
  48 + //合伙人应收分红
  49 + PlanPartnerBonus float64
  50 + //调整后的合伙人应收分红 (初始值=-1);
  51 + //业务判定时0是有效值,负值无效
  52 + UsePartnerBonus float64
  53 + //合伙人已收分红
  54 + PartnerBonusHas float64
  55 + //合伙人未收分红
  56 + PartnerBonusNot float64
  57 + //合伙人分红支出
  58 + PartnerBonusExpense float64
  59 + //上一次查看时间 已读情况
  60 + LastViewTime time.Time
  61 + //是否关闭订单
  62 + IsDisable int `pg:",use_zero"`
  63 + //分红支付状态
  64 + BonusStatus int
  65 +}
  66 +
  67 +var _ pg.BeforeUpdateHook = (*OrderBase)(nil)
  68 +
  69 +func (order *OrderBase) BeforeUpdate(ctx context.Context) (context.Context, error) {
  70 + order.UpdateTime = time.Now()
  71 + return ctx, nil
  72 +}
  73 +
  74 +var _ pg.BeforeInsertHook = (*OrderBase)(nil)
  75 +
  76 +func (order *OrderBase) BeforeInsert(ctx context.Context) (context.Context, error) {
  77 + order.CreateTime = time.Now()
  78 + order.UpdateTime = time.Now()
  79 + return ctx, nil
  80 +}
  1 +package models
  2 +
  3 +//OrderGood 订单中的货品
  4 +type OrderGood struct {
  5 + tableName struct{} `pg:"order_good"`
  6 + //货品id
  7 + Id int64
  8 + //所属订单id
  9 + OrderId int64
  10 + //货品名称 长度可能较长
  11 + GoodName string
  12 + //预计的货品数量
  13 + PlanGoodNumber int
  14 + //货品单价
  15 + Price float64
  16 + //预计的货品总额
  17 + PlanAmount float64
  18 + //调整后的货品数量(初始值=-1)
  19 + //业务判定时0是有效值,负值无效
  20 + UseGoodNumber int
  21 + //调整后的货品总额
  22 + UseAmount float64
  23 + //合伙人分红比例
  24 + PartnerBonusPercent float64
  25 + //预计的合伙人分红
  26 + PlanPartnerBonus float64
  27 + //合伙人应收分红调整 (初始值=-1)
  28 + ////业务判定时0是有效值,负值无效
  29 + UsePartnerBonus float64
  30 + //合伙人已收分红
  31 + PartnerBonusHas float64
  32 + //合伙人未收分红
  33 + PartnerBonusNot float64
  34 + //合伙人分红支出
  35 + PartnerBonusExpense float64
  36 + //分红状态
  37 + BonusStatus int
  38 + //备注信息
  39 + Remark string
  40 +}
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
  9 +)
  10 +
  11 +type OrderBaseRepository struct {
  12 + transactionContext *transaction.TransactionContext
  13 +}
  14 +
  15 +var (
  16 + _ domain.OrderBaseRepository = (*OrderBaseRepository)(nil)
  17 +)
  18 +
  19 +func NewOrderBaseRepository(transactionContext *transaction.TransactionContext) (*OrderBaseRepository, error) {
  20 + if transactionContext == nil {
  21 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  22 + }
  23 + return &OrderBaseRepository{transactionContext: transactionContext}, nil
  24 +}
  25 +
  26 +func (reponsitory OrderBaseRepository) transformPgModelToDomainModel(orderModel *models.OrderBase) (order domain.OrderBase, err error) {
  27 + order = domain.OrderBase{
  28 + Id: orderModel.Id, OrderType: orderModel.OrderType, OrderCode: orderModel.OrderCode,
  29 + DeliveryCode: orderModel.DeliveryCode, Buyer: orderModel.Buyer, RegionInfo: orderModel.RegionInfo,
  30 + PartnerId: orderModel.PartnerId, SalesmanBonusPercent: orderModel.SalesmanBonusPercent,
  31 + CreateTime: orderModel.CreateTime, DeliveryTime: orderModel.DeliveryTime, UpdateTime: orderModel.UpdateTime,
  32 + IsDisable: orderModel.IsDisable,
  33 + OrderCompute: domain.OrderCompute{
  34 + PlanPartnerBonus: orderModel.PlanPartnerBonus, UsePartnerBonus: orderModel.UsePartnerBonus,
  35 + PartnerBonusHas: orderModel.PartnerBonusHas, PartnerBonusNot: orderModel.PartnerBonusNot,
  36 + PartnerBonusExpense: orderModel.PartnerBonusExpense, SalesmanBonus: orderModel.SalesmanBonus,
  37 + PlanOrderCount: orderModel.PlanOrderCount, PlanOrderAmount: orderModel.PlanOrderAmount,
  38 + UseOrderCount: orderModel.UseOrderCount, UseOrderAmount: orderModel.UseOrderAmount,
  39 + },
  40 + PartnerInfo: domain.Partner{
  41 + Id: orderModel.PartnerId,
  42 + },
  43 + BonusStatus: orderModel.BonusStatus,
  44 + }
  45 + return order, nil
  46 +}
  47 +
  48 +func (repository OrderBaseRepository) Save(orderInfo *domain.OrderBase) error {
  49 + var (
  50 + err error
  51 + tx = repository.transactionContext.PgTx
  52 + )
  53 + m := &models.OrderBase{
  54 + Id: orderInfo.Id, OrderType: orderInfo.OrderType, OrderCode: orderInfo.OrderCode,
  55 + DeliveryCode: orderInfo.DeliveryCode, Buyer: orderInfo.Buyer, RegionInfo: orderInfo.RegionInfo,
  56 + PartnerId: orderInfo.PartnerId, SalesmanBonusPercent: orderInfo.SalesmanBonusPercent,
  57 + SalesmanBonus: orderInfo.OrderCompute.SalesmanBonus, PlanOrderCount: orderInfo.OrderCompute.PlanOrderCount,
  58 + PlanOrderAmount: orderInfo.OrderCompute.PlanOrderAmount, UseOrderCount: orderInfo.OrderCompute.UseOrderCount,
  59 + UseOrderAmount: orderInfo.OrderCompute.UseOrderAmount, DeliveryTime: orderInfo.DeliveryTime,
  60 + PlanPartnerBonus: orderInfo.OrderCompute.PlanPartnerBonus, UsePartnerBonus: orderInfo.OrderCompute.UsePartnerBonus,
  61 + PartnerBonusHas: orderInfo.OrderCompute.PartnerBonusHas, PartnerBonusNot: orderInfo.OrderCompute.PartnerBonusNot,
  62 + PartnerBonusExpense: orderInfo.OrderCompute.PartnerBonusExpense, IsDisable: orderInfo.IsDisable,
  63 + CreateTime: orderInfo.CreateTime, BonusStatus: orderInfo.BonusStatus,
  64 + }
  65 + if m.Id == 0 {
  66 + _, err = tx.Model(m).
  67 + Returning("*").
  68 + Insert()
  69 + orderInfo.Id = m.Id
  70 + orderInfo.CreateTime = m.CreateTime
  71 + orderInfo.UpdateTime = m.UpdateTime
  72 + } else {
  73 + _, err = tx.Model(m).
  74 + WherePK().
  75 + Returning("*").
  76 + Update()
  77 + orderInfo.UpdateTime = m.UpdateTime
  78 + }
  79 + return err
  80 +}
  81 +
  82 +func (repository OrderBaseRepository) Find(queryOption domain.OrderBaseFindQuery) ([]domain.OrderBase, int, error) {
  83 + db := repository.transactionContext.PgDd
  84 + orderModels := []models.OrderBase{}
  85 + query := db.Model(&orderModels)
  86 + if queryOption.PartnerId > 0 {
  87 + query = query.Where("partner_id=?", queryOption.PartnerId)
  88 + }
  89 + if len(queryOption.OrderCode) > 0 {
  90 + query = query.Where("order_code like ?", "%"+queryOption.OrderCode+"%")
  91 + }
  92 + if len(queryOption.DeliveryCode) > 0 {
  93 + query = query.Where("delivery_code like ?", "%"+queryOption.DeliveryCode+"%")
  94 + }
  95 + if queryOption.OrderType > 0 {
  96 + query = query.Where("order_type=?", queryOption.OrderType)
  97 + }
  98 + if queryOption.Offset > -1 {
  99 + query = query.Offset(queryOption.Offset)
  100 + }
  101 + if queryOption.Limit > 0 {
  102 + query = query.Limit(queryOption.Limit)
  103 + } else {
  104 + query = query.Limit(20)
  105 + }
  106 + var (
  107 + err error
  108 + ordersReturn = make([]domain.OrderBase, 0)
  109 + )
  110 + query = query.Order("order_base.id DESC")
  111 + count, err := query.SelectAndCount()
  112 + if err != nil {
  113 + return ordersReturn, 0, err
  114 + }
  115 + for i := range orderModels {
  116 + domainOrder, err := repository.transformPgModelToDomainModel(&orderModels[i])
  117 + if err != nil {
  118 + return ordersReturn, 0, err
  119 + }
  120 + ordersReturn = append(ordersReturn, domainOrder)
  121 + }
  122 + return ordersReturn, count, nil
  123 +}
  124 +
  125 +func (repository OrderBaseRepository) FindOne(qureyOptions domain.OrderBaseFindOneQuery) (*domain.OrderBase, error) {
  126 + var (
  127 + err error
  128 + tx = repository.transactionContext.PgDd
  129 + )
  130 + m := new(models.OrderBase)
  131 + err = tx.Model(m).
  132 + Where("id=?", qureyOptions.OrderId).
  133 + First()
  134 + if err != nil {
  135 + return nil, err
  136 + }
  137 + result, err := repository.transformPgModelToDomainModel(m)
  138 + return &result, err
  139 +}
  140 +
  141 +func (repository OrderBaseRepository) Remove(id int64) error {
  142 + var (
  143 + err error
  144 + tx = repository.transactionContext.PgTx
  145 + )
  146 + m := &models.OrderBase{
  147 + Id: id,
  148 + }
  149 + _, err = tx.Model(m).WherePK().Delete()
  150 + return err
  151 +}
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
  9 +)
  10 +
  11 +type OrderGoodRepository struct {
  12 + transactionContext *transaction.TransactionContext
  13 +}
  14 +
  15 +var (
  16 + _ domain.OrderGoodRepository = (*OrderGoodRepository)(nil)
  17 +)
  18 +
  19 +func NewOrderGoodRepository(transactionContext *transaction.TransactionContext) (*OrderGoodRepository, error) {
  20 + if transactionContext == nil {
  21 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  22 + }
  23 + return &OrderGoodRepository{transactionContext: transactionContext}, nil
  24 +}
  25 +
  26 +func (reponsitory OrderGoodRepository) transformPgModelToDomainModel(orderModel *models.OrderGood) (order domain.OrderGood, err error) {
  27 + order = domain.OrderGood{
  28 + Id: orderModel.Id, OrderId: orderModel.OrderId, GoodName: orderModel.GoodName,
  29 + PlanGoodNumber: orderModel.PlanGoodNumber, UseGoodNumber: orderModel.UseGoodNumber,
  30 + Price: orderModel.Price, PartnerBonusPercent: orderModel.PartnerBonusPercent,
  31 + BonusStatus: orderModel.BonusStatus, Remark: orderModel.Remark,
  32 + GoodCompute: domain.GoodCompute{
  33 + PlanAmount: orderModel.PlanAmount,
  34 + UseAmount: orderModel.UseAmount,
  35 + PlanPartnerBonus: orderModel.PlanPartnerBonus,
  36 + UsePartnerBonus: orderModel.UsePartnerBonus,
  37 + PartnerBonusHas: orderModel.PartnerBonusHas,
  38 + PartnerBonusNot: orderModel.PartnerBonusNot,
  39 + PartnerBonusExpense: orderModel.PartnerBonusExpense,
  40 + },
  41 + }
  42 + switch orderModel.BonusStatus {
  43 + case domain.OrderGoodWaitPay:
  44 + order.CurrentBonusStatus = domain.OrderGoodBonusWaitPay{}
  45 + case domain.OrderGoodHasPay:
  46 + order.CurrentBonusStatus = domain.OrderGoodBonusHasPay{}
  47 + }
  48 + return order, nil
  49 +}
  50 +
  51 +func (repository OrderGoodRepository) Save(data []domain.OrderGood) error {
  52 + var (
  53 + err error
  54 + tx = repository.transactionContext.PgTx
  55 + )
  56 + for k, v := range data {
  57 + m := &models.OrderGood{
  58 + Id: v.Id, OrderId: v.OrderId, GoodName: v.GoodName,
  59 + PlanGoodNumber: v.PlanGoodNumber, Price: v.Price,
  60 + PlanAmount: v.GoodCompute.PlanAmount, UseGoodNumber: v.UseGoodNumber,
  61 + UseAmount: v.GoodCompute.UseAmount, PartnerBonusPercent: v.PartnerBonusPercent,
  62 + PlanPartnerBonus: v.GoodCompute.PlanPartnerBonus, UsePartnerBonus: v.GoodCompute.UsePartnerBonus,
  63 + PartnerBonusHas: v.GoodCompute.PartnerBonusHas, PartnerBonusNot: v.GoodCompute.PartnerBonusNot,
  64 + PartnerBonusExpense: v.GoodCompute.PartnerBonusExpense, BonusStatus: v.BonusStatus,
  65 + Remark: v.Remark,
  66 + }
  67 + if v.Id == 0 {
  68 + _, err = tx.Model(m).
  69 + Returning("*").
  70 + Insert()
  71 + if err != nil {
  72 + return err
  73 + }
  74 + data[k].Id = m.Id
  75 + } else {
  76 + _, err = tx.Model(m).
  77 + WherePK().
  78 + Update()
  79 + if err != nil {
  80 + return err
  81 + }
  82 + }
  83 + }
  84 + return nil
  85 +}
  86 +
  87 +func (repository OrderGoodRepository) Find(queryOption domain.OrderGoodFindQuery) ([]domain.OrderGood, int, error) {
  88 + db := repository.transactionContext.PgDd
  89 + goodModes := []models.OrderGood{}
  90 + query := db.Model(&goodModes)
  91 + if queryOption.OrderId > 0 {
  92 + query = query.Where("order_id=?", queryOption.OrderId)
  93 + }
  94 + if queryOption.Offset > -1 {
  95 + query = query.Offset(queryOption.Offset)
  96 + }
  97 + if queryOption.Limit > 0 {
  98 + query = query.Limit(queryOption.Limit)
  99 + } else {
  100 + query = query.Limit(50)
  101 + }
  102 + var (
  103 + err error
  104 + orderGoods = make([]domain.OrderGood, 0)
  105 + )
  106 + query = query.Order("order_good.id DESC")
  107 + count, err := query.SelectAndCount()
  108 + if err != nil {
  109 + return orderGoods, 0, err
  110 + }
  111 + for i := range goodModes {
  112 + domainOrderGood, err := repository.transformPgModelToDomainModel(&goodModes[i])
  113 + if err != nil {
  114 + return orderGoods, 0, err
  115 + }
  116 + orderGoods = append(orderGoods, domainOrderGood)
  117 + }
  118 + return orderGoods, count, nil
  119 +}
  120 +
  121 +func (repository OrderGoodRepository) Remove(orderId int64, goodids ...int64) error {
  122 + var (
  123 + err error
  124 + tx = repository.transactionContext.PgTx
  125 + )
  126 + m := &models.OrderGood{}
  127 + query := tx.Model(m).Where("order_id=?", orderId)
  128 + if len(goodids) > 0 {
  129 + query = query.WhereIn("id in(?)", goodids)
  130 + }
  131 + _, err = query.Delete()
  132 + return err
  133 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "errors"
  5 + "fmt"
  6 + "strconv"
  7 +
  8 + "github.com/astaxie/beego/logs"
  9 + orderCmd "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/command"
  10 + orderQuery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/query"
  11 + orderService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/service"
  12 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  13 +)
  14 +
  15 +//OrderDividendController 订单分红管理
  16 +type OrderDividendController struct {
  17 + BaseController
  18 +}
  19 +
  20 +//Prepare 重写 BaseController 的Prepare方法
  21 +func (c *OrderDividendController) Prepare() {
  22 + c.BaseController.Prepare()
  23 + return
  24 + if ok := c.ValidJWTToken(); !ok {
  25 + return
  26 + }
  27 + if ok := c.ValidAdminPermission(domain.PERMISSION_DIVIDEND); !ok {
  28 + return
  29 + }
  30 +}
  31 +
  32 +//PageListOrderDividend 获取实发订单分红列表
  33 +func (c *OrderDividendController) PageListOrderDividend() {
  34 + type Parameter struct {
  35 + SearchText string `json:"searchText"`
  36 + Partner int64 `json:"partner"`
  37 + PageSize int `json:"pageSize"`
  38 + PageNumber int `json:"pageNumber"`
  39 + }
  40 + var (
  41 + param Parameter
  42 + err error
  43 + )
  44 + if err = c.BindJsonData(&param); err != nil {
  45 + logs.Error(err)
  46 + c.ResponseError(errors.New("json数据解析失败"))
  47 + return
  48 + }
  49 + if param.PageNumber == 0 {
  50 + param.PageNumber = 1
  51 + }
  52 + if param.PageSize == 0 {
  53 + param.PageSize = 20
  54 + }
  55 +
  56 + orderSrv := orderService.NewOrderInfoService(nil)
  57 + orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
  58 + PartnerId: param.Partner,
  59 + DeliveryCode: param.SearchText,
  60 + OrderType: domain.OrderReal,
  61 + Limit: param.PageSize,
  62 + Offset: (param.PageNumber - 1) * param.PageSize,
  63 + })
  64 + if err != nil {
  65 + c.ResponseError(err)
  66 + return
  67 + }
  68 + rsp := []map[string]interface{}{}
  69 + for i := range orderinfos {
  70 + orderinfo := orderinfos[i]
  71 + m := map[string]interface{}{
  72 + "updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
  73 + "id": orderinfo.Id,
  74 + "shipmentsId": orderinfo.DeliveryCode,
  75 + "partner": orderinfo.PartnerInfo.PartnerName,
  76 + "dividendsReceivable": orderinfo.OrderCompute.PlanPartnerBonus,
  77 + "dividendSpending": orderinfo.OrderCompute.PartnerBonusExpense,
  78 + "receiveDividends": orderinfo.OrderCompute.PartnerBonusHas,
  79 + "uncollectedDividends": orderinfo.OrderCompute.PartnerBonusNot,
  80 + "stateOfPayment": orderinfo.BonusStatus,
  81 + }
  82 + if orderinfo.OrderCompute.UsePartnerBonus >= 0 {
  83 + m["dividendsReceivable"] = orderinfo.OrderCompute.UsePartnerBonus
  84 + }
  85 + rsp = append(rsp, m)
  86 + }
  87 + c.ResponsePageList(rsp, cnt, param.PageNumber)
  88 + return
  89 +}
  90 +
  91 +//OrderDividendDetail 订单的分红详情
  92 +func (c *OrderDividendController) OrderDividendDetail() {
  93 + type Parameter struct {
  94 + Id string `json:"id"`
  95 + }
  96 + var (
  97 + param Parameter
  98 + err error
  99 + )
  100 + if err = c.BindJsonData(&param); err != nil {
  101 + logs.Error(err)
  102 + c.ResponseError(errors.New("json数据解析失败"))
  103 + return
  104 + }
  105 + orderid, _ := strconv.ParseInt(param.Id, 10, 64)
  106 + if orderid == 0 {
  107 + c.ResponseError(errors.New("参数错误"))
  108 + return
  109 + }
  110 + orderSrv := orderService.NewOrderInfoService(nil)
  111 + orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
  112 + OrderId: orderid,
  113 + })
  114 + if err != nil {
  115 + c.ResponseError(err)
  116 + return
  117 + }
  118 + if orderinfo.OrderType != domain.OrderReal {
  119 + c.ResponseError(errors.New("参数错误"))
  120 + return
  121 + }
  122 + allGoods := []map[string]interface{}{}
  123 + for _, v := range orderinfo.Goods {
  124 + detail := map[string]interface{}{
  125 + "productName": v.GoodName,
  126 + "orderNum": v.PlanGoodNumber,
  127 + "univalence": v.Price,
  128 + "partnerRatio": v.PartnerBonusPercent,
  129 + "orderPrice": v.GoodCompute.PlanAmount,
  130 + "partnerDividendsReceivable": v.GoodCompute.PlanPartnerBonus,
  131 + }
  132 + m := map[string]interface{}{
  133 + "detail": detail,
  134 + "quantityControl": "",
  135 + "id": v.Id,
  136 + "stateOfPayment": v.BonusStatus,
  137 + "remark": v.Remark,
  138 + "amountControl": "",
  139 + "partnerDividendControl": "",
  140 + "receivedDividends": v.GoodCompute.PartnerBonusHas,
  141 + "notReceivedDividend": v.GoodCompute.PartnerBonusNot,
  142 + "dividendSpending": v.GoodCompute.PartnerBonusExpense,
  143 + }
  144 + if v.GoodCompute.UseAmount >= 0 {
  145 + m["amountControl"] = fmt.Sprint(v.GoodCompute.UseAmount)
  146 + }
  147 + if v.UseGoodNumber >= 0 {
  148 + m["quantityControl"] = fmt.Sprint(v.UseGoodNumber)
  149 + }
  150 + if v.GoodCompute.UsePartnerBonus >= 0 {
  151 + m["partnerDividendControl"] = fmt.Sprint(v.GoodCompute.UsePartnerBonus)
  152 + }
  153 + allGoods = append(allGoods, m)
  154 + }
  155 + orderData := map[string]interface{}{
  156 + "buyer": orderinfo.Buyer.BuyerName,
  157 + "shipmentsId": orderinfo.DeliveryCode,
  158 + "orderDist": orderinfo.RegionInfo.RegionName,
  159 + "partner": orderinfo.PartnerInfo.PartnerName,
  160 + "id": orderinfo.Id,
  161 + "orderId": orderinfo.OrderCode,
  162 + }
  163 + dividendCount := map[string]interface{}{
  164 + "orderNum": orderinfo.OrderCompute.PlanOrderCount,
  165 + "orderAmountAdjustment": orderinfo.OrderCompute.PlanOrderAmount,
  166 + "orderNumControl": "",
  167 + "orderAmountAdjustmentControl": "",
  168 + "partnerDividends": orderinfo.OrderCompute.PlanPartnerBonus,
  169 + "partnerDividendsControl": "",
  170 + "receivedDividends": orderinfo.OrderCompute.PartnerBonusHas,
  171 + "notReceivedDividend": orderinfo.OrderCompute.PartnerBonusNot,
  172 + "dividendSpending": orderinfo.OrderCompute.PartnerBonusExpense,
  173 + "commissionProportion": orderinfo.SalesmanBonusPercent,
  174 + "expectedCommission": orderinfo.OrderCompute.SalesmanBonus,
  175 + }
  176 + if orderinfo.OrderCompute.UseOrderAmount >= 0 {
  177 + dividendCount["orderAmountAdjustmentControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
  178 + }
  179 + if orderinfo.OrderCompute.UsePartnerBonus >= 0 {
  180 + dividendCount["partnerDividendsControl"] = fmt.Sprint(orderinfo.OrderCompute.UsePartnerBonus)
  181 + }
  182 + if orderinfo.OrderCompute.UseOrderCount >= 0 {
  183 + dividendCount["orderNumControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
  184 + }
  185 + rsp := map[string]interface{}{
  186 + "order": orderData,
  187 + "product": allGoods,
  188 + "dividendCount": dividendCount,
  189 + "operationTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:06"),
  190 + }
  191 + if orderinfo.OrderCompute.UseOrderAmount >= 0 {
  192 + rsp["orderNumCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
  193 + }
  194 + if orderinfo.OrderCompute.UseOrderCount >= 0 {
  195 + rsp["orderAmountAdjustmentCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
  196 + }
  197 + c.ResponseData(rsp)
  198 + return
  199 +}
  200 +
  201 +type postOrderDividend struct {
  202 + Id int64 `json:"id"`
  203 + DividendPayments []postDividendPayment `json:"dividendPayment"`
  204 +}
  205 +
  206 +type postDividendPayment struct {
  207 + QuantityControl string `json:"quantityControl"`
  208 + StateOfPayment int `json:"stateOfPayment"`
  209 + ProductId int64 `json:"productId"`
  210 + Remark string `json:"remark"`
  211 +}
  212 +
  213 +func (c *OrderDividendController) EditOrderDividend() {
  214 + var (
  215 + param postOrderDividend
  216 + err error
  217 + )
  218 + if err = c.BindJsonData(&param); err != nil {
  219 + logs.Error(err)
  220 + c.ResponseError(errors.New("json数据解析失败"))
  221 + return
  222 + }
  223 +
  224 + if param.Id == 0 {
  225 + c.ResponseError(errors.New("参数错误"))
  226 + return
  227 + }
  228 + goodbouns := []orderCmd.GoodBouns{}
  229 + for _, v := range param.DividendPayments {
  230 + if v.ProductId == 0 {
  231 + c.ResponseError(errors.New("参数错误"))
  232 + return
  233 + }
  234 + if !(v.StateOfPayment == domain.OrderGoodWaitPay || v.StateOfPayment == domain.OrderGoodHasPay) {
  235 + c.ResponseError(errors.New("参数错误"))
  236 + return
  237 + }
  238 + g := orderCmd.GoodBouns{
  239 + GoodId: v.ProductId,
  240 + Remark: v.Remark,
  241 + BounsStatus: v.StateOfPayment,
  242 + }
  243 + if len(v.QuantityControl) == 0 {
  244 + g.UseGoodNumber = -1
  245 + } else {
  246 + num, err := strconv.Atoi(v.QuantityControl)
  247 + if err != nil {
  248 + c.ResponseError(errors.New("参数错误"))
  249 + return
  250 + }
  251 + g.UseGoodNumber = num
  252 + }
  253 + goodbouns = append(goodbouns, g)
  254 + }
  255 + cmd := orderCmd.UpdateGoodBouns{
  256 + Id: param.Id,
  257 + GoodBouns: goodbouns,
  258 + }
  259 + orderSrv := orderService.NewOrderInfoService(nil)
  260 + err = orderSrv.UpdateGoodBouns(cmd)
  261 + if err != nil {
  262 + c.ResponseError(err)
  263 + return
  264 + }
  265 + c.ResponseData(nil)
  266 + return
  267 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "errors"
  5 + "fmt"
  6 + "strconv"
  7 + "time"
  8 +
  9 + "github.com/astaxie/beego/logs"
  10 + orderCmd "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/command"
  11 + orderQuery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/query"
  12 + orderService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/service"
  13 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
  14 + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
  15 +)
  16 +
  17 +type OrderInfoController struct {
  18 + BaseController
  19 +}
  20 +
  21 +////Prepare 重写 BaseController 的Prepare方法
  22 +func (c *OrderInfoController) Prepare() {
  23 + c.BaseController.Prepare()
  24 + return
  25 + if ok := c.ValidJWTToken(); !ok {
  26 + return
  27 + }
  28 + if ok := c.ValidAdminPermission(domain.PERMISSION_ORDER); !ok {
  29 + return
  30 + }
  31 +}
  32 +
  33 +//PageListOrderPurpose 分页获取意向订单列表
  34 +func (c *OrderInfoController) PageListOrderPurpose() {
  35 + type Parameter struct {
  36 + SearchText string `json:"searchText"`
  37 + Partner int64 `json:"partner"`
  38 + PageSize int `json:"pageSize"`
  39 + PageNumber int `json:"pageNumber"`
  40 + }
  41 + var (
  42 + param Parameter
  43 + err error
  44 + )
  45 + if err = c.BindJsonData(&param); err != nil {
  46 + logs.Error(err)
  47 + c.ResponseError(errors.New("json数据解析失败"))
  48 + return
  49 + }
  50 + if param.PageNumber == 0 {
  51 + param.PageNumber = 1
  52 + }
  53 + if param.PageSize == 0 {
  54 + param.PageSize = 20
  55 + }
  56 +
  57 + orderSrv := orderService.NewOrderInfoService(nil)
  58 + orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
  59 + PartnerId: param.Partner,
  60 + OrderCode: param.SearchText,
  61 + OrderType: domain.OrderIntention,
  62 + Limit: param.PageSize,
  63 + Offset: (param.PageNumber - 1) * param.PageSize,
  64 + })
  65 + if err != nil {
  66 + c.ResponseError(err)
  67 + return
  68 + }
  69 + rsp := []map[string]interface{}{}
  70 + for i := range orderinfos {
  71 + orderinfo := orderinfos[i]
  72 + m := map[string]interface{}{
  73 + "createTime": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
  74 + "updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
  75 + "buyer": orderinfo.Buyer.BuyerName,
  76 + "id": orderinfo.Id,
  77 + "orderId": orderinfo.OrderCode,
  78 + "partner": orderinfo.PartnerInfo.PartnerName,
  79 + "orderNum": orderinfo.OrderCompute.PlanOrderCount,
  80 + "orderPrice": orderinfo.OrderCompute.PlanOrderAmount,
  81 + "orderDist": orderinfo.RegionInfo.RegionName,
  82 + }
  83 + rsp = append(rsp, m)
  84 + }
  85 + c.ResponsePageList(rsp, cnt, param.PageNumber)
  86 +}
  87 +
  88 +//GetOrderPurpose 获取意向订单详情
  89 +func (c *OrderInfoController) GetOrderPurpose() {
  90 + type Parameter struct {
  91 + Id string `json:"id"`
  92 + }
  93 + var (
  94 + param Parameter
  95 + err error
  96 + )
  97 + if err = c.BindJsonData(&param); err != nil {
  98 + logs.Error(err)
  99 + c.ResponseError(errors.New("json数据解析失败"))
  100 + return
  101 + }
  102 + orderid, _ := strconv.ParseInt(param.Id, 10, 64)
  103 + orderSrv := orderService.NewOrderInfoService(nil)
  104 + orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
  105 + OrderId: orderid,
  106 + })
  107 + if err != nil {
  108 + c.ResponseError(err)
  109 + return
  110 + }
  111 + if orderinfo.OrderType != domain.OrderIntention {
  112 + c.ResponseError(errors.New("参数错误"))
  113 + return
  114 + }
  115 + allGoods := []map[string]interface{}{}
  116 + for _, v := range orderinfo.Goods {
  117 + m := map[string]interface{}{
  118 + "productName": v.GoodName,
  119 + "orderNum": v.PlanGoodNumber,
  120 + "univalence": v.Price,
  121 + "partnerRatio": v.PartnerBonusPercent,
  122 + "orderPrice": v.GoodCompute.PlanAmount,
  123 + }
  124 + allGoods = append(allGoods, m)
  125 + }
  126 + rsp := map[string]interface{}{
  127 + "buyer": orderinfo.Buyer.BuyerName,
  128 + "id": orderinfo.Id,
  129 + "partnerID": orderinfo.PartnerInfo.Id,
  130 + "partner": orderinfo.PartnerInfo.PartnerName,
  131 + "orderDist": orderinfo.RegionInfo.RegionName,
  132 + "orderId": orderinfo.OrderCode,
  133 + "product": allGoods,
  134 + "commissionProportion": orderinfo.SalesmanBonusPercent,
  135 + "orderNumCount": orderinfo.OrderCompute.PlanOrderCount,
  136 + "orderAmountAdjustmentCount": orderinfo.OrderCompute.PlanOrderAmount,
  137 + }
  138 + c.ResponseData(rsp)
  139 +}
  140 +
  141 +//RemoveOrderPurpose 删除意向订单
  142 +func (c *OrderInfoController) RemoveOrderPurpose() {
  143 + type Parameter struct {
  144 + Id int64 `json:"id"`
  145 + }
  146 + var (
  147 + param Parameter
  148 + err error
  149 + )
  150 + if err = c.BindJsonData(&param); err != nil {
  151 + logs.Error(err)
  152 + c.ResponseError(errors.New("json数据解析失败"))
  153 + return
  154 + }
  155 + orderSrv := orderService.NewOrderInfoService(nil)
  156 + err = orderSrv.DeleteOrder(param.Id)
  157 + if err != nil {
  158 + c.ResponseError(err)
  159 + return
  160 + }
  161 + c.ResponseData(nil)
  162 +}
  163 +
  164 +//postPurposeOrderDetail 请求添加/更新的订单数据
  165 +type postPurposeOrderDetail struct {
  166 + Id int64 `json:"id"`
  167 + //订单编号
  168 + OrderId string `json:"orderId"`
  169 + //买家姓名
  170 + BuyerName string `json:"buyer"`
  171 + //对应合伙人 id
  172 + PartnerId int64 `json:"partnerID"`
  173 + //业务员抽成比例
  174 + CommissionProportion float64 `json:"commissionProportion"`
  175 + //订单区域
  176 + OrderDist string `json:"orderDist"`
  177 + //商品
  178 + Product []postOrderGood `json:"product"`
  179 +}
  180 +
  181 +func (postData postPurposeOrderDetail) Valid() error {
  182 + if len(postData.OrderId) == 0 {
  183 + return lib.ThrowError(lib.ARG_ERROR, "订单编号必填")
  184 + }
  185 + if len(postData.BuyerName) == 0 {
  186 + return lib.ThrowError(lib.ARG_ERROR, "买家信息必填")
  187 + }
  188 + if postData.PartnerId == 0 {
  189 + return lib.ThrowError(lib.ARG_ERROR, "合伙人信息必填")
  190 + }
  191 + if len(postData.OrderDist) == 0 {
  192 + return lib.ThrowError(lib.ARG_ERROR, "订单区域必填")
  193 + }
  194 + for i := range postData.Product {
  195 + if err := postData.Product[i].Valid(); err != nil {
  196 + return err
  197 + }
  198 + }
  199 + return nil
  200 +}
  201 +
  202 +//PostPurposeOrderGood 请求添加/更新订单中的货品
  203 +type postOrderGood struct {
  204 + Id int64 `json:"id"`
  205 + ProductName string `json:"productName"`
  206 + OrderNum int `json:"orderNum"`
  207 + Univalence float64 `json:"univalence"`
  208 + PartnerRatio float64 `json:"partnerRatio"`
  209 +}
  210 +
  211 +func (postData postOrderGood) Valid() error {
  212 + if len(postData.ProductName) == 0 {
  213 + return lib.ThrowError(lib.ARG_ERROR, "商品名称必填")
  214 + }
  215 + return nil
  216 +}
  217 +
  218 +//UpdateOrderPurpose 更新意向订单
  219 +func (c *OrderInfoController) UpdateOrderPurpose() {
  220 + //用与适配前端定义的数据结构
  221 + var (
  222 + param postPurposeOrderDetail
  223 + err error
  224 + )
  225 + if err = c.BindJsonData(&param); err != nil {
  226 + logs.Error(err)
  227 + c.ResponseError(errors.New("json数据解析失败"))
  228 + return
  229 + }
  230 + if err := param.Valid(); err != nil {
  231 + c.ResponseError(err)
  232 + return
  233 + }
  234 + if param.Id == 0 {
  235 + err = c.addOrderPurpose(param)
  236 + } else {
  237 + err = c.editOrderPurpose(param)
  238 + }
  239 + if err != nil {
  240 + c.ResponseError(err)
  241 + }
  242 + c.ResponseData(nil)
  243 + return
  244 +}
  245 +
  246 +func (c *OrderInfoController) addOrderPurpose(param postPurposeOrderDetail) error {
  247 +
  248 + newGoods := []orderCmd.OrderGoodData{}
  249 + for _, v := range param.Product {
  250 + g := orderCmd.OrderGoodData{
  251 + GoodName: v.ProductName,
  252 + PlanGoodNumber: v.OrderNum,
  253 + Price: v.Univalence,
  254 + PartnerBonusPercent: v.PartnerRatio,
  255 + }
  256 + newGoods = append(newGoods, g)
  257 + }
  258 + createcmd := orderCmd.CreateOrderCommand{
  259 + OrderType: domain.OrderIntention,
  260 + OrderCode: param.OrderId,
  261 + DeliveryCode: "",
  262 + BuyerName: param.BuyerName,
  263 + OrderRegion: param.OrderDist,
  264 + PartnerId: param.PartnerId,
  265 + SalesmanBonusPercent: param.CommissionProportion,
  266 + Goods: newGoods,
  267 + }
  268 + orderSrv := orderService.NewOrderInfoService(nil)
  269 + _, err := orderSrv.CreateNewOrder(createcmd)
  270 + return err
  271 +}
  272 +
  273 +func (c *OrderInfoController) editOrderPurpose(param postPurposeOrderDetail) error {
  274 + orderSrv := orderService.NewOrderInfoService(nil)
  275 + newGoods := []orderCmd.OrderGoodData{}
  276 + for _, v := range param.Product {
  277 + g := orderCmd.OrderGoodData{
  278 + GoodName: v.ProductName,
  279 + PlanGoodNumber: v.OrderNum,
  280 + Price: v.Univalence,
  281 + PartnerBonusPercent: v.PartnerRatio,
  282 + }
  283 + newGoods = append(newGoods, g)
  284 + }
  285 + updatecmd := orderCmd.UpdateOrderCommand{
  286 + Id: param.Id,
  287 + OrderType: domain.OrderIntention,
  288 + OrderCode: param.OrderId,
  289 + DeliveryCode: "",
  290 + BuyerName: param.BuyerName,
  291 + OrderRegion: param.OrderDist,
  292 + PartnerId: param.PartnerId,
  293 + SalesmanBonusPercent: param.CommissionProportion,
  294 + Goods: newGoods,
  295 + }
  296 + _, err := orderSrv.UpdateOrderData(updatecmd)
  297 + return err
  298 +}
  299 +
  300 +type postOrderPurposeDelivery struct {
  301 + ShipmentsId string `json:"shipmentsId"` //发货单号
  302 + Id string `json:"id"` //订单id
  303 + ProductDetail []postOrderGood `json:"productDetail"`
  304 +}
  305 +
  306 +func (postData postOrderPurposeDelivery) Valid() error {
  307 + if len(postData.ShipmentsId) == 0 {
  308 + return lib.ThrowError(lib.ARG_ERROR, "发货单号必填")
  309 + }
  310 + for i := range postData.ProductDetail {
  311 + if err := postData.ProductDetail[i].Valid(); err != nil {
  312 + return err
  313 + }
  314 + }
  315 + return nil
  316 +}
  317 +
  318 +//OrderPurposeDelivery 发货 意向订单转实发单
  319 +func (c *OrderInfoController) OrderPurposeDelivery() {
  320 + //用与适配前端定义的数据结构
  321 +
  322 + var (
  323 + param postOrderPurposeDelivery
  324 + err error
  325 + )
  326 + if err = c.BindJsonData(&param); err != nil {
  327 + logs.Error(err)
  328 + c.ResponseError(errors.New("json数据解析失败"))
  329 + return
  330 + }
  331 +
  332 + orderid, _ := strconv.ParseInt(param.Id, 10, 64)
  333 + if orderid <= 0 {
  334 + c.ResponseError(errors.New("参数错误"))
  335 + return
  336 + }
  337 + if err = param.Valid(); err != nil {
  338 + c.ResponseError(err)
  339 + return
  340 + }
  341 + goods := []orderCmd.OrderGoodData{}
  342 + for _, v := range param.ProductDetail {
  343 + g := orderCmd.OrderGoodData{
  344 + Id: v.Id, GoodName: v.ProductName, PlanGoodNumber: v.OrderNum,
  345 + Price: v.Univalence, PartnerBonusPercent: v.PartnerRatio,
  346 + }
  347 + goods = append(goods, g)
  348 + }
  349 + deliveryCommand := orderCmd.OrderDeliveryCommand{
  350 + OrderId: orderid, DeliveryCode: param.ShipmentsId,
  351 + DeliveryTime: time.Now(), Goods: goods,
  352 + }
  353 + orderSrv := orderService.NewOrderInfoService(nil)
  354 + err = orderSrv.Delivery(deliveryCommand)
  355 + if err != nil {
  356 + c.ResponseError(err)
  357 + }
  358 + c.ResponseData(nil)
  359 + return
  360 +}
  361 +
  362 +//PageListOrderReal 获取实发订单列表
  363 +func (c *OrderInfoController) PageListOrderReal() {
  364 + type Parameter struct {
  365 + SearchText string `json:"searchText"`
  366 + Partner int64 `json:"partner"`
  367 + PageSize int `json:"pageSize"`
  368 + PageNumber int `json:"pageNumber"`
  369 + }
  370 + var (
  371 + param Parameter
  372 + err error
  373 + )
  374 + if err = c.BindJsonData(&param); err != nil {
  375 + logs.Error(err)
  376 + c.ResponseError(errors.New("json数据解析失败"))
  377 + return
  378 + }
  379 + if param.PageNumber == 0 {
  380 + param.PageNumber = 1
  381 + }
  382 + if param.PageSize == 0 {
  383 + param.PageSize = 20
  384 + }
  385 +
  386 + orderSrv := orderService.NewOrderInfoService(nil)
  387 + orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
  388 + PartnerId: param.Partner,
  389 + DeliveryCode: param.SearchText,
  390 + OrderType: domain.OrderReal,
  391 + Limit: param.PageSize,
  392 + Offset: (param.PageNumber - 1) * param.PageSize,
  393 + })
  394 + if err != nil {
  395 + c.ResponseError(err)
  396 + return
  397 + }
  398 + rsp := []map[string]interface{}{}
  399 + for i := range orderinfos {
  400 + orderinfo := orderinfos[i]
  401 + m := map[string]interface{}{
  402 + "createTime": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
  403 + "updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
  404 + "buyer": orderinfo.Buyer.BuyerName,
  405 + "id": orderinfo.Id,
  406 + "orderId": orderinfo.OrderCode,
  407 + "shipmentsId": orderinfo.DeliveryCode,
  408 + "partner": orderinfo.PartnerInfo.PartnerName,
  409 + "orderNum": orderinfo.OrderCompute.PlanOrderCount,
  410 + "orderPrice": orderinfo.OrderCompute.PlanOrderAmount,
  411 + "orderDist": orderinfo.RegionInfo.RegionName,
  412 + "quantityControl": "",
  413 + "priceControl": "",
  414 + "status": orderinfo.IsDisable,
  415 + }
  416 + if orderinfo.OrderCompute.UseOrderCount >= 0 {
  417 + m["quantityControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
  418 + }
  419 + if orderinfo.OrderCompute.UseOrderAmount >= 0 {
  420 + m["priceControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
  421 + }
  422 + rsp = append(rsp, m)
  423 + }
  424 + c.ResponsePageList(rsp, cnt, param.PageNumber)
  425 + return
  426 +}
  427 +
  428 +//GetOrderReal 获取实发订单详情
  429 +func (c *OrderInfoController) GetOrderReal() {
  430 + type Parameter struct {
  431 + Id string `json:"id"`
  432 + }
  433 + var (
  434 + param Parameter
  435 + err error
  436 + )
  437 + if err = c.BindJsonData(&param); err != nil {
  438 + logs.Error(err)
  439 + c.ResponseError(errors.New("json数据解析失败"))
  440 + return
  441 + }
  442 + orderid, _ := strconv.ParseInt(param.Id, 10, 64)
  443 + if orderid == 0 {
  444 + c.ResponseError(errors.New("参数错误"))
  445 + return
  446 + }
  447 + orderSrv := orderService.NewOrderInfoService(nil)
  448 + orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
  449 + OrderId: orderid,
  450 + })
  451 + if err != nil {
  452 + c.ResponseError(err)
  453 + return
  454 + }
  455 + if orderinfo.OrderType != domain.OrderReal {
  456 + c.ResponseError(errors.New("参数错误"))
  457 + return
  458 + }
  459 + allGoods := []map[string]interface{}{}
  460 + for _, v := range orderinfo.Goods {
  461 + m := map[string]interface{}{
  462 + "productName": v.GoodName,
  463 + "orderNum": v.PlanGoodNumber,
  464 + "univalence": v.Price,
  465 + "partnerRatio": v.PartnerBonusPercent,
  466 + "orderPrice": v.GoodCompute.PlanAmount,
  467 + "quantityControl": "",
  468 + "orderPriceControl": "",
  469 + }
  470 + if v.GoodCompute.UseAmount >= 0 {
  471 + m["priceControl"] = fmt.Sprint(v.GoodCompute.UseAmount)
  472 + }
  473 + if v.UseGoodNumber >= 0 {
  474 + m["quantityControl"] = fmt.Sprint(v.UseGoodNumber)
  475 + }
  476 + allGoods = append(allGoods, m)
  477 + }
  478 + rsp := map[string]interface{}{
  479 + "buyer": orderinfo.Buyer.BuyerName,
  480 + "id": orderinfo.Id,
  481 + "partnerID": orderinfo.PartnerInfo.Id,
  482 + "partner": orderinfo.PartnerInfo.PartnerName,
  483 + "orderDist": orderinfo.RegionInfo.RegionName,
  484 + "orderId": orderinfo.OrderCode,
  485 + "shipmentsId": orderinfo.DeliveryCode,
  486 + "commissionProportion": orderinfo.SalesmanBonusPercent,
  487 + "orderNumCount": orderinfo.OrderCompute.PlanOrderCount,
  488 + "orderAmountAdjustmentCount": orderinfo.OrderCompute.PlanOrderAmount,
  489 + "orderNumCountControl": "",
  490 + "orderAmountAdjustmentCountControl": "",
  491 + "product": allGoods,
  492 + "create_time": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:06"),
  493 + "update_time": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:06"),
  494 + }
  495 + if orderinfo.OrderCompute.UseOrderAmount >= 0 {
  496 + rsp["orderNumCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
  497 + }
  498 + if orderinfo.OrderCompute.UseOrderCount >= 0 {
  499 + rsp["orderAmountAdjustmentCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
  500 + }
  501 + c.ResponseData(rsp)
  502 + return
  503 +}
  504 +
  505 +//实际订单
  506 +type postRealOrderDetail struct {
  507 + postPurposeOrderDetail
  508 + ShipmentsId string `json:"shipmentsId"` //发货单号
  509 +}
  510 +
  511 +func (postData postRealOrderDetail) Valid() error {
  512 + if len(postData.ShipmentsId) == 0 {
  513 + return lib.ThrowError(lib.ARG_ERROR, "订单的发货单号必填")
  514 + }
  515 + if err := postData.postPurposeOrderDetail.Valid(); err != nil {
  516 + return err
  517 + }
  518 + return nil
  519 +}
  520 +
  521 +//UpdateOrderReal 编辑实际订单
  522 +func (c *OrderInfoController) UpdateOrderReal() {
  523 + //用与适配前端定义的数据结构
  524 + var (
  525 + param postRealOrderDetail
  526 + err error
  527 + )
  528 + if err = c.BindJsonData(&param); err != nil {
  529 + logs.Error(err)
  530 + c.ResponseError(errors.New("json数据解析失败"))
  531 + return
  532 + }
  533 + if err := param.Valid(); err != nil {
  534 + c.ResponseError(err)
  535 + return
  536 + }
  537 + if param.Id == 0 {
  538 + err = c.addOrderReal(param)
  539 + } else {
  540 + err = c.editOrderReal(param)
  541 + }
  542 + if err != nil {
  543 + c.ResponseError(err)
  544 + }
  545 + c.ResponseData(nil)
  546 + return
  547 +}
  548 +
  549 +func (c *OrderInfoController) addOrderReal(param postRealOrderDetail) error {
  550 + orderSrv := orderService.NewOrderInfoService(nil)
  551 + newGoods := []orderCmd.OrderGoodData{}
  552 + for _, v := range param.Product {
  553 + g := orderCmd.OrderGoodData{
  554 + GoodName: v.ProductName,
  555 + PlanGoodNumber: v.OrderNum,
  556 + Price: v.Univalence,
  557 + PartnerBonusPercent: v.PartnerRatio,
  558 + }
  559 + newGoods = append(newGoods, g)
  560 + }
  561 + createcmd := orderCmd.CreateOrderCommand{
  562 + OrderType: domain.OrderReal,
  563 + OrderCode: param.OrderId,
  564 + DeliveryCode: param.ShipmentsId,
  565 + BuyerName: param.BuyerName,
  566 + OrderRegion: param.OrderDist,
  567 + PartnerId: param.PartnerId,
  568 + SalesmanBonusPercent: param.CommissionProportion,
  569 + Goods: newGoods,
  570 + }
  571 + _, err := orderSrv.CreateNewOrder(createcmd)
  572 + return err
  573 +}
  574 +
  575 +func (c *OrderInfoController) editOrderReal(param postRealOrderDetail) error {
  576 +
  577 + newGoods := []orderCmd.OrderGoodData{}
  578 + for _, v := range param.Product {
  579 + g := orderCmd.OrderGoodData{
  580 + GoodName: v.ProductName,
  581 + PlanGoodNumber: v.OrderNum,
  582 + Price: v.Univalence,
  583 + PartnerBonusPercent: v.PartnerRatio,
  584 + }
  585 + newGoods = append(newGoods, g)
  586 + }
  587 + updatecmd := orderCmd.UpdateOrderCommand{
  588 + Id: param.Id,
  589 + OrderType: domain.OrderReal,
  590 + OrderCode: param.OrderId,
  591 + DeliveryCode: param.ShipmentsId,
  592 + BuyerName: param.BuyerName,
  593 + OrderRegion: param.OrderDist,
  594 + PartnerId: param.PartnerId,
  595 + SalesmanBonusPercent: param.CommissionProportion,
  596 + Goods: newGoods,
  597 + }
  598 + orderSrv := orderService.NewOrderInfoService(nil)
  599 + _, err := orderSrv.UpdateOrderData(updatecmd)
  600 + return err
  601 +}
  602 +
  603 +//OrderDisable 关闭开启订单,限实发订单可操作
  604 +func (c *OrderInfoController) OrderDisable() {
  605 + //用与适配前端定义的数据结构
  606 + type PostParameter struct {
  607 + Id string `json:"id"`
  608 + Status int `json:"status"`
  609 + }
  610 + var (
  611 + param PostParameter
  612 + err error
  613 + )
  614 + if err = c.BindJsonData(&param); err != nil {
  615 + logs.Error(err)
  616 + c.ResponseError(errors.New("json数据解析失败"))
  617 + return
  618 + }
  619 + orderId, _ := strconv.ParseInt(param.Id, 10, 64)
  620 + if orderId == 0 {
  621 + c.ResponseError(errors.New("参数错误"))
  622 + return
  623 + }
  624 + if !(param.Status == domain.OrderDisableNot || param.Status == domain.OrderDisableYes) {
  625 + c.ResponseError(errors.New("参数错误"))
  626 + return
  627 + }
  628 + cmd := orderCmd.DisableOrderCommand{
  629 + OrderId: orderId,
  630 + IsDisable: param.Status,
  631 + OrderType: domain.OrderReal,
  632 + }
  633 + orderSrv := orderService.NewOrderInfoService(nil)
  634 + err = orderSrv.DisableOrEnable(cmd)
  635 + if err != nil {
  636 + c.ResponseError(err)
  637 + }
  638 + c.ResponseData(nil)
  639 + return
  640 +}
  641 +
  642 +//RemoveOrderReal 删除意向订单
  643 +func (c *OrderInfoController) RemoveOrderReal() {
  644 + type Parameter struct {
  645 + Id int64 `json:"id"`
  646 + }
  647 + var (
  648 + param Parameter
  649 + err error
  650 + )
  651 + if err = c.BindJsonData(&param); err != nil {
  652 + logs.Error(err)
  653 + c.ResponseError(errors.New("json数据解析失败"))
  654 + return
  655 + }
  656 + orderSrv := orderService.NewOrderInfoService(nil)
  657 + err = orderSrv.DeleteOrder(param.Id)
  658 + if err != nil {
  659 + c.ResponseError(err)
  660 + return
  661 + }
  662 + c.ResponseData(nil)
  663 +}
@@ -28,23 +28,28 @@ func init() { @@ -28,23 +28,28 @@ func init() {
28 beego.NSRouter("/set-status", &controllers.PartnerInfoController{}, "POST:PartnerInfoSetState"), 28 beego.NSRouter("/set-status", &controllers.PartnerInfoController{}, "POST:PartnerInfoSetState"),
29 ), 29 ),
30 beego.NSNamespace("/dividends", 30 beego.NSNamespace("/dividends",
31 - beego.NSRouter("/edit", &controllers.DividendsController{}, "POST:Edit"),  
32 - beego.NSRouter("/detail", &controllers.DividendsController{}, "POST:Detail"),  
33 - beego.NSRouter("/list", &controllers.DividendsController{}, "POST:List"), 31 + beego.NSRouter("/list", &controllers.OrderDividendController{}, "POST:PageListOrderDividend"),
  32 + beego.NSRouter("/edit", &controllers.OrderDividendController{}, "POST:EditOrderDividend"),
  33 + beego.NSRouter("/detail", &controllers.OrderDividendController{}, "POST:OrderDividendDetail"),
34 ), 34 ),
35 beego.NSNamespace("/order", 35 beego.NSNamespace("/order",
36 - beego.NSRouter("/purpose/list", &controllers.OrderController{}, "POST:PageListOrderPurpose"),  
37 - beego.NSRouter("/purpose/update", &controllers.OrderController{}, "POST:UpdateOrderPurpose"),  
38 - beego.NSRouter("/purpose/detail", &controllers.OrderController{}, "POST:GetOrderPurpose"),  
39 - beego.NSRouter("/purpose/del", &controllers.OrderController{}, "POST:RemoveOrderPurpose"),  
40 - beego.NSRouter("/purpose/convert", &controllers.OrderController{}, "POST:OrderPurposeToReal"),  
41 - beego.NSRouter("/actual/list", &controllers.OrderController{}, "POST:PageListOrderReal"),  
42 - beego.NSRouter("/actual/update", &controllers.OrderController{}, "POST:UpdateOrderReal"),  
43 - beego.NSRouter("/actual/detail", &controllers.OrderController{}, "POST:GetOrderReal"), 36 + beego.NSRouter("/purpose/list", &controllers.OrderInfoController{}, "POST:PageListOrderPurpose"),
  37 + beego.NSRouter("/purpose/update", &controllers.OrderInfoController{}, "POST:UpdateOrderPurpose"),
  38 + beego.NSRouter("/purpose/detail", &controllers.OrderInfoController{}, "POST:GetOrderPurpose"),
  39 + beego.NSRouter("/purpose/del", &controllers.OrderInfoController{}, "POST:RemoveOrderPurpose"),
  40 + beego.NSRouter("/purpose/sendout", &controllers.OrderInfoController{}, "POST:OrderPurposeDelivery"),
  41 + beego.NSRouter("/actual/list", &controllers.OrderInfoController{}, "POST:PageListOrderReal"),
  42 + beego.NSRouter("/actual/detail", &controllers.OrderInfoController{}, "POST:GetOrderReal"),
  43 + beego.NSRouter("/actual/del", &controllers.OrderInfoController{}, "POST:RemoveOrderReal"),
  44 +
  45 + beego.NSRouter("/actual/update", &controllers.OrderInfoController{}, "POST:UpdateOrderReal"),
  46 + beego.NSRouter("/actual/close", &controllers.OrderInfoController{}, "POST:OrderDisable"),
44 ), 47 ),
  48 +
45 beego.NSNamespace("/common", 49 beego.NSNamespace("/common",
46 beego.NSRouter("/partner", &controllers.CommonController{}, "POST:GetPartnerList"), 50 beego.NSRouter("/partner", &controllers.CommonController{}, "POST:GetPartnerList"),
47 ), 51 ),
48 ) 52 )
  53 +
49 beego.AddNamespace(adminRouter) 54 beego.AddNamespace(adminRouter)
50 } 55 }
  1 +package geetest
  2 +
  3 +import (
  4 + "crypto/md5"
  5 + "encoding/hex"
  6 + "encoding/json"
  7 + "errors"
  8 + "io/ioutil"
  9 + "net/http"
  10 + "net/url"
  11 + "strings"
  12 + "time"
  13 +)
  14 +
  15 +type GeetestLib struct {
  16 + CaptchaID string
  17 + PrivateKey string
  18 + Client *http.Client
  19 +}
  20 +
  21 +type FailbackRegisterRespnse struct {
  22 + Success int `json:"success"`
  23 + GT string `json:"gt"`
  24 + Challenge string `json:"challenge"`
  25 + NewCaptcha int `json:"new_captcha"`
  26 +}
  27 +
  28 +const (
  29 + geetestHost = "http://api.geetest.com"
  30 + registerURL = geetestHost + "/register.php"
  31 + validateURL = geetestHost + "/validate.php"
  32 +)
  33 +
  34 +func MD5Encode(input string) string {
  35 + md5Instant := md5.New()
  36 + md5Instant.Write([]byte(input))
  37 + return hex.EncodeToString(md5Instant.Sum(nil))
  38 +}
  39 +
  40 +// 初始化 GeetestLib
  41 +func NewGeetestLib(capthcaID string, privateKey string, timeOut time.Duration) (geetest GeetestLib){
  42 + client := &http.Client{Timeout: timeOut}
  43 + geetest = GeetestLib{capthcaID, privateKey, client}
  44 + return
  45 +}
  46 +
  47 +func (g *GeetestLib) getFailBackRegisterResponse(success int, challenge string) []byte {
  48 + if challenge == "" {
  49 + challenge = hex.EncodeToString(md5.New().Sum(nil))
  50 + }
  51 +
  52 + response := FailbackRegisterRespnse{
  53 + success,
  54 + g.CaptchaID,
  55 + challenge,
  56 + 1,
  57 + }
  58 + res, _ := json.Marshal(response)
  59 + return res
  60 +}
  61 +
  62 +func (g *GeetestLib) do(req *http.Request) (body []byte, err error) {
  63 + req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  64 + var resp *http.Response
  65 + if resp, err = g.Client.Do(req); err != nil {
  66 + return
  67 + }
  68 + defer resp.Body.Close()
  69 + if resp.StatusCode >= http.StatusInternalServerError {
  70 + err = errors.New("http status code 5xx")
  71 + return
  72 + }
  73 +
  74 + if body, err = ioutil.ReadAll(resp.Body); err != nil {
  75 + return
  76 + }
  77 + return
  78 +}
  79 +
  80 +func (g *GeetestLib) PreProcess(userID string, userIP string) (int8, []byte) {
  81 + params := url.Values{}
  82 + params.Add("gt", g.CaptchaID)
  83 + params.Add("new_captcha", "1")
  84 + if userID != "" {
  85 + params.Add("user_id", userID)
  86 + }
  87 + if userIP != "" {
  88 + params.Add("ip_adress", userIP)
  89 + }
  90 + req, _ := http.NewRequest("GET", registerURL+"?"+params.Encode(), nil)
  91 + body, err := g.do(req)
  92 + if err != nil {
  93 + return 0, g.getFailBackRegisterResponse(0, "")
  94 + }
  95 + challenge := string(body)
  96 + if len(challenge) != 32 {
  97 + return 0, g.getFailBackRegisterResponse(0, "")
  98 + } else {
  99 + challenge = MD5Encode(challenge + g.PrivateKey)
  100 + return 1, g.getFailBackRegisterResponse(1, challenge)
  101 + }
  102 +}
  103 +
  104 +func (g *GeetestLib) checkParas(challenge string, validate string, seccode string) bool {
  105 + if challenge == "" || validate == "" || seccode == "" {
  106 + return false
  107 + }
  108 + return true
  109 +}
  110 +
  111 +func (g *GeetestLib) checkSuccessRes(challenge string, validate string) bool {
  112 + return MD5Encode(g.PrivateKey+"geetest"+challenge) == validate
  113 +}
  114 +
  115 +func (g *GeetestLib) checkFailbackRes(challenge string, validate string) bool {
  116 + return MD5Encode(challenge) == validate
  117 +}
  118 +
  119 +func (g *GeetestLib) SuccessValidate(challenge string, validate string, seccode string, userID string, userIP string) bool {
  120 + if !g.checkParas(challenge, validate, seccode) {
  121 + return false
  122 + }
  123 + if !g.checkSuccessRes(challenge, validate) {
  124 + return false
  125 + }
  126 + params := url.Values{}
  127 + params.Add("seccode", seccode)
  128 + params.Add("challenge", challenge)
  129 + params.Add("captchaid", g.CaptchaID)
  130 + params.Add("sdk", "golang_v1.0.0")
  131 + if userID != "" {
  132 + params.Add("user_id", userID)
  133 + }
  134 + if userIP != "" {
  135 + params.Add("ip_adress", userIP)
  136 + }
  137 + req, _ := http.NewRequest("POST", validateURL, strings.NewReader(params.Encode()))
  138 + body, err := g.do(req)
  139 + if err != nil {
  140 + return false
  141 + }
  142 + res := string(body)
  143 + return res == MD5Encode(seccode)
  144 +}
  145 +
  146 +func (g *GeetestLib) FailbackValidate(challenge string, validate string, seccode string) bool {
  147 + if !g.checkParas(challenge, validate, seccode) {
  148 + return false
  149 + }
  150 + if !g.checkFailbackRes(challenge, validate) {
  151 + return false
  152 + }
  153 + return true
  154 +}
  1 +## Copyright 2014 Alvaro J. Genial. All rights reserved.
  2 +## Use of this source code is governed by a BSD-style
  3 +## license that can be found in the LICENSE file.
  4 +
  5 +language: go
  6 +
  7 +go:
  8 + - tip
  9 + - 1.6
  10 + - 1.5
  11 + - 1.4
  12 + - 1.3
  13 + # 1.2
  14 +
  15 +before_install:
  16 + # - go get -v golang.org/x/tools/cmd/cover
  17 + # - go get -v golang.org/x/tools/cmd/vet
  18 + # - go get -v golang.org/x/lint/golint
  19 + - export PATH=$PATH:/home/travis/gopath/bin
  20 +
  21 +script:
  22 + - go build -v ./...
  23 + - go test -v -cover ./...
  24 + - go vet ./...
  25 + # - golint .
  1 +Copyright (c) 2014 Alvaro J. Genial. All rights reserved.
  2 +
  3 +Redistribution and use in source and binary forms, with or without
  4 +modification, are permitted provided that the following conditions are
  5 +met:
  6 +
  7 + * Redistributions of source code must retain the above copyright
  8 +notice, this list of conditions and the following disclaimer.
  9 + * Redistributions in binary form must reproduce the above
  10 +copyright notice, this list of conditions and the following disclaimer
  11 +in the documentation and/or other materials provided with the
  12 +distribution.
  13 + * Neither the name of Google Inc. nor the names of its
  14 +contributors may be used to endorse or promote products derived from
  15 +this software without specific prior written permission.
  16 +
  17 +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18 +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19 +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20 +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21 +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22 +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23 +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24 +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25 +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26 +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27 +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1 +form
  2 +====
  3 +
  4 +A Form Encoding & Decoding Package for Go, written by [Alvaro J. Genial](http://alva.ro).
  5 +
  6 +[![Build Status](https://travis-ci.org/ajg/form.png?branch=master)](https://travis-ci.org/ajg/form)
  7 +[![GoDoc](https://godoc.org/github.com/ajg/form?status.png)](https://godoc.org/github.com/ajg/form)
  8 +
  9 +Synopsis
  10 +--------
  11 +
  12 +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.
  13 +
  14 +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.
  15 +
  16 +Status
  17 +------
  18 +
  19 +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.
  20 +
  21 +Dependencies
  22 +------------
  23 +
  24 +The only requirement is [Go 1.2](http://golang.org/doc/go1.2) or later.
  25 +
  26 +Usage
  27 +-----
  28 +
  29 +```go
  30 +import "github.com/ajg/form"
  31 +// or: "gopkg.in/ajg/form.v1"
  32 +```
  33 +
  34 +Given a type like the following...
  35 +
  36 +```go
  37 +type User struct {
  38 + Name string `form:"name"`
  39 + Email string `form:"email"`
  40 + Joined time.Time `form:"joined,omitempty"`
  41 + Posts []int `form:"posts"`
  42 + Preferences map[string]string `form:"prefs"`
  43 + Avatar []byte `form:"avatar"`
  44 + PasswordHash int64 `form:"-"`
  45 +}
  46 +```
  47 +
  48 +...it is easy to encode data of that type...
  49 +
  50 +
  51 +```go
  52 +func PostUser(url string, u User) error {
  53 + var c http.Client
  54 + _, err := c.PostForm(url, form.EncodeToValues(u))
  55 + return err
  56 +}
  57 +```
  58 +
  59 +...as well as decode it...
  60 +
  61 +
  62 +```go
  63 +func Handler(w http.ResponseWriter, r *http.Request) {
  64 + var u User
  65 +
  66 + d := form.NewDecoder(r.Body)
  67 + if err := d.Decode(&u); err != nil {
  68 + http.Error(w, "Form could not be decoded", http.StatusBadRequest)
  69 + return
  70 + }
  71 +
  72 + fmt.Fprintf(w, "Decoded: %#v", u)
  73 +}
  74 +```
  75 +
  76 +...without having to do any grunt work.
  77 +
  78 +Field Tags
  79 +----------
  80 +
  81 +Like other encoding packages, `form` supports the following options for fields:
  82 +
  83 + - `` `form:"-"` ``: Causes the field to be ignored during encoding and decoding.
  84 + - `` `form:"<name>"` ``: Overrides the field's name; useful especially when dealing with external identifiers in camelCase, as are commonly found on the web.
  85 + - `` `form:",omitempty"` ``: Elides the field during encoding if it is empty (typically meaning equal to the type's zero value.)
  86 + - `` `form:"<name>,omitempty"` ``: The way to combine the two options above.
  87 +
  88 +Values
  89 +------
  90 +
  91 +### Simple Values
  92 +
  93 +Values of the following types are all considered simple:
  94 +
  95 + - `bool`
  96 + - `int`, `int8`, `int16`, `int32`, `int64`, `rune`
  97 + - `uint`, `uint8`, `uint16`, `uint32`, `uint64`, `byte`
  98 + - `float32`, `float64`
  99 + - `complex64`, `complex128`
  100 + - `string`
  101 + - `[]byte` (see note)
  102 + - [`time.Time`](http://golang.org/pkg/time/#Time)
  103 + - [`url.URL`](http://golang.org/pkg/net/url/#URL)
  104 + - An alias of any of the above
  105 + - A pointer to any of the above
  106 +
  107 +### Composite Values
  108 +
  109 +A composite value is one that can contain other values. Values of the following kinds...
  110 +
  111 + - Maps
  112 + - Slices; except `[]byte` (see note)
  113 + - Structs; except [`time.Time`](http://golang.org/pkg/time/#Time) and [`url.URL`](http://golang.org/pkg/net/url/#URL)
  114 + - Arrays
  115 + - An alias of any of the above
  116 + - A pointer to any of the above
  117 +
  118 +...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 (`.`).
  119 +
  120 +(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.)
  121 +
  122 +### Untyped Values
  123 +
  124 +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:
  125 +
  126 + - Simple values will be treated as a `string`.
  127 + - Composite values will be treated as a `map[string]interface{}`, itself able to contain nested values (both scalar and compound) ad infinitum.
  128 + - 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.
  129 +
  130 +### Zero Values
  131 +
  132 +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`.
  133 +
  134 +### Unsupported Values
  135 +
  136 +Values of the following kinds aren't supported and, if present, must be ignored.
  137 +
  138 + - Channel
  139 + - Function
  140 + - Unsafe pointer
  141 + - An alias of any of the above
  142 + - A pointer to any of the above
  143 +
  144 +Custom Marshaling
  145 +-----------------
  146 +
  147 +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.
  148 +
  149 +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:
  150 +
  151 +```go
  152 +import "encoding"
  153 +
  154 +type Binary []byte
  155 +
  156 +var (
  157 + _ encoding.TextMarshaler = &Binary{}
  158 + _ encoding.TextUnmarshaler = &Binary{}
  159 +)
  160 +
  161 +func (b Binary) MarshalText() ([]byte, error) {
  162 + return []byte(base64.URLEncoding.EncodeToString([]byte(b))), nil
  163 +}
  164 +
  165 +func (b *Binary) UnmarshalText(text []byte) error {
  166 + bs, err := base64.URLEncoding.DecodeString(string(text))
  167 + if err == nil {
  168 + *b = Binary(bs)
  169 + }
  170 + return err
  171 +}
  172 +```
  173 +
  174 +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.)
  175 +
  176 +Keys
  177 +----
  178 +
  179 +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 `\\\.`).
  180 +
  181 +(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.)
  182 +
  183 +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...
  184 +
  185 +```go
  186 +package main
  187 +
  188 +import (
  189 + "os"
  190 +
  191 + "github.com/ajg/form"
  192 +)
  193 +
  194 +func main() {
  195 + type B struct {
  196 + Qux string `form:"qux"`
  197 + }
  198 + type A struct {
  199 + FooBar B `form:"foo.bar"`
  200 + }
  201 + a := A{FooBar: B{"XYZ"}}
  202 + os.Stdout.WriteString("Default: ")
  203 + form.NewEncoder(os.Stdout).Encode(a)
  204 + os.Stdout.WriteString("\nCustom: ")
  205 + form.NewEncoder(os.Stdout).DelimitWith('/').Encode(a)
  206 + os.Stdout.WriteString("\n")
  207 +}
  208 +
  209 +```
  210 +
  211 +...will produce...
  212 +
  213 +```
  214 +Default: foo%5C.bar.qux=XYZ
  215 +Custom: foo.bar%2Fqux=XYZ
  216 +```
  217 +
  218 +(`%5C` and `%2F` represent `\` and `/`, respectively.)
  219 +
  220 +Limitations
  221 +-----------
  222 +
  223 + - Circular (self-referential) values are untested.
  224 +
  225 +Future Work
  226 +-----------
  227 +
  228 +The following items would be nice to have in the future—though they are not being worked on yet:
  229 +
  230 + - An option to treat all values as if they had been tagged with `omitempty`.
  231 + - An option to automatically treat all field names in `camelCase` or `underscore_case`.
  232 + - Built-in support for the types in [`math/big`](http://golang.org/pkg/math/big/).
  233 + - Built-in support for the types in [`image/color`](http://golang.org/pkg/image/color/).
  234 + - 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.
  235 +
  236 +(Feel free to implement any of these and then send a pull request.)
  237 +
  238 +Related Work
  239 +------------
  240 +
  241 + - Package [gorilla/schema](https://github.com/gorilla/schema), which only implements decoding.
  242 + - Package [google/go-querystring](https://github.com/google/go-querystring), which only implements encoding.
  243 +
  244 +License
  245 +-------
  246 +
  247 +This library is distributed under a BSD-style [LICENSE](./LICENSE).
  1 +TODO
  2 +====
  3 +
  4 + - Document IgnoreCase and IgnoreUnknownKeys in README.
  1 +// Copyright 2014 Alvaro J. Genial. All rights reserved.
  2 +// Use of this source code is governed by a BSD-style
  3 +// license that can be found in the LICENSE file.
  4 +
  5 +package form
  6 +
  7 +import (
  8 + "fmt"
  9 + "io"
  10 + "io/ioutil"
  11 + "net/url"
  12 + "reflect"
  13 + "strconv"
  14 + "time"
  15 +)
  16 +
  17 +// NewDecoder returns a new form Decoder.
  18 +func NewDecoder(r io.Reader) *Decoder {
  19 + return &Decoder{r, defaultDelimiter, defaultEscape, false, false}
  20 +}
  21 +
  22 +// Decoder decodes data from a form (application/x-www-form-urlencoded).
  23 +type Decoder struct {
  24 + r io.Reader
  25 + d rune
  26 + e rune
  27 + ignoreUnknown bool
  28 + ignoreCase bool
  29 +}
  30 +
  31 +// DelimitWith sets r as the delimiter used for composite keys by Decoder d and returns the latter; it is '.' by default.
  32 +func (d *Decoder) DelimitWith(r rune) *Decoder {
  33 + d.d = r
  34 + return d
  35 +}
  36 +
  37 +// EscapeWith sets r as the escape used for delimiters (and to escape itself) by Decoder d and returns the latter; it is '\\' by default.
  38 +func (d *Decoder) EscapeWith(r rune) *Decoder {
  39 + d.e = r
  40 + return d
  41 +}
  42 +
  43 +// Decode reads in and decodes form-encoded data into dst.
  44 +func (d Decoder) Decode(dst interface{}) error {
  45 + bs, err := ioutil.ReadAll(d.r)
  46 + if err != nil {
  47 + return err
  48 + }
  49 + vs, err := url.ParseQuery(string(bs))
  50 + if err != nil {
  51 + return err
  52 + }
  53 + v := reflect.ValueOf(dst)
  54 + return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v)))
  55 +}
  56 +
  57 +// IgnoreUnknownKeys if set to true it will make the Decoder ignore values
  58 +// that are not found in the destination object instead of returning an error.
  59 +func (d *Decoder) IgnoreUnknownKeys(ignoreUnknown bool) {
  60 + d.ignoreUnknown = ignoreUnknown
  61 +}
  62 +
  63 +// IgnoreCase if set to true it will make the Decoder try to set values in the
  64 +// destination object even if the case does not match.
  65 +func (d *Decoder) IgnoreCase(ignoreCase bool) {
  66 + d.ignoreCase = ignoreCase
  67 +}
  68 +
  69 +// DecodeString decodes src into dst.
  70 +func (d Decoder) DecodeString(dst interface{}, src string) error {
  71 + vs, err := url.ParseQuery(src)
  72 + if err != nil {
  73 + return err
  74 + }
  75 + v := reflect.ValueOf(dst)
  76 + return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v)))
  77 +}
  78 +
  79 +// DecodeValues decodes vs into dst.
  80 +func (d Decoder) DecodeValues(dst interface{}, vs url.Values) error {
  81 + v := reflect.ValueOf(dst)
  82 + return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v)))
  83 +}
  84 +
  85 +// DecodeString decodes src into dst.
  86 +func DecodeString(dst interface{}, src string) error {
  87 + return NewDecoder(nil).DecodeString(dst, src)
  88 +}
  89 +
  90 +// DecodeValues decodes vs into dst.
  91 +func DecodeValues(dst interface{}, vs url.Values) error {
  92 + return NewDecoder(nil).DecodeValues(dst, vs)
  93 +}
  94 +
  95 +func (d Decoder) decodeNode(v reflect.Value, n node) (err error) {
  96 + defer func() {
  97 + if e := recover(); e != nil {
  98 + err = fmt.Errorf("%v", e)
  99 + }
  100 + }()
  101 +
  102 + if v.Kind() == reflect.Slice {
  103 + return fmt.Errorf("could not decode directly into slice; use pointer to slice")
  104 + }
  105 + d.decodeValue(v, n)
  106 + return nil
  107 +}
  108 +
  109 +func (d Decoder) decodeValue(v reflect.Value, x interface{}) {
  110 + t := v.Type()
  111 + k := v.Kind()
  112 +
  113 + if k == reflect.Ptr && v.IsNil() {
  114 + v.Set(reflect.New(t.Elem()))
  115 + }
  116 +
  117 + if unmarshalValue(v, x) {
  118 + return
  119 + }
  120 +
  121 + empty := isEmpty(x)
  122 +
  123 + switch k {
  124 + case reflect.Ptr:
  125 + d.decodeValue(v.Elem(), x)
  126 + return
  127 + case reflect.Interface:
  128 + if !v.IsNil() {
  129 + d.decodeValue(v.Elem(), x)
  130 + return
  131 +
  132 + } else if empty {
  133 + return // Allow nil interfaces only if empty.
  134 + } else {
  135 + panic("form: cannot decode non-empty value into into nil interface")
  136 + }
  137 + }
  138 +
  139 + if empty {
  140 + v.Set(reflect.Zero(t)) // Treat the empty string as the zero value.
  141 + return
  142 + }
  143 +
  144 + switch k {
  145 + case reflect.Struct:
  146 + if t.ConvertibleTo(timeType) {
  147 + d.decodeTime(v, x)
  148 + } else if t.ConvertibleTo(urlType) {
  149 + d.decodeURL(v, x)
  150 + } else {
  151 + d.decodeStruct(v, x)
  152 + }
  153 + case reflect.Slice:
  154 + d.decodeSlice(v, x)
  155 + case reflect.Array:
  156 + d.decodeArray(v, x)
  157 + case reflect.Map:
  158 + d.decodeMap(v, x)
  159 + case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func:
  160 + panic(t.String() + " has unsupported kind " + k.String())
  161 + default:
  162 + d.decodeBasic(v, x)
  163 + }
  164 +}
  165 +
  166 +func (d Decoder) decodeStruct(v reflect.Value, x interface{}) {
  167 + t := v.Type()
  168 + for k, c := range getNode(x) {
  169 + if f, ok := findField(v, k, d.ignoreCase); !ok && k == "" {
  170 + panic(getString(x) + " cannot be decoded as " + t.String())
  171 + } else if !ok {
  172 + if !d.ignoreUnknown {
  173 + panic(k + " doesn't exist in " + t.String())
  174 + }
  175 + } else if !f.CanSet() {
  176 + panic(k + " cannot be set in " + t.String())
  177 + } else {
  178 + d.decodeValue(f, c)
  179 + }
  180 + }
  181 +}
  182 +
  183 +func (d Decoder) decodeMap(v reflect.Value, x interface{}) {
  184 + t := v.Type()
  185 + if v.IsNil() {
  186 + v.Set(reflect.MakeMap(t))
  187 + }
  188 + for k, c := range getNode(x) {
  189 + i := reflect.New(t.Key()).Elem()
  190 + d.decodeValue(i, k)
  191 +
  192 + w := v.MapIndex(i)
  193 + if w.IsValid() { // We have an actual element value to decode into.
  194 + if w.Kind() == reflect.Interface {
  195 + w = w.Elem()
  196 + }
  197 + w = reflect.New(w.Type()).Elem()
  198 + } else if t.Elem().Kind() != reflect.Interface { // The map's element type is concrete.
  199 + w = reflect.New(t.Elem()).Elem()
  200 + } else {
  201 + // The best we can do here is to decode as either a string (for scalars) or a map[string]interface {} (for the rest).
  202 + // We could try to guess the type based on the string (e.g. true/false => bool) but that'll get ugly fast,
  203 + // especially if we have to guess the kind (slice vs. array vs. map) and index type (e.g. string, int, etc.)
  204 + switch c.(type) {
  205 + case node:
  206 + w = reflect.MakeMap(stringMapType)
  207 + case string:
  208 + w = reflect.New(stringType).Elem()
  209 + default:
  210 + panic("value is neither node nor string")
  211 + }
  212 + }
  213 +
  214 + d.decodeValue(w, c)
  215 + v.SetMapIndex(i, w)
  216 + }
  217 +}
  218 +
  219 +func (d Decoder) decodeArray(v reflect.Value, x interface{}) {
  220 + t := v.Type()
  221 + for k, c := range getNode(x) {
  222 + i, err := strconv.Atoi(k)
  223 + if err != nil {
  224 + panic(k + " is not a valid index for type " + t.String())
  225 + }
  226 + if l := v.Len(); i >= l {
  227 + panic("index is above array size")
  228 + }
  229 + d.decodeValue(v.Index(i), c)
  230 + }
  231 +}
  232 +
  233 +func (d Decoder) decodeSlice(v reflect.Value, x interface{}) {
  234 + t := v.Type()
  235 + if t.Elem().Kind() == reflect.Uint8 {
  236 + // Allow, but don't require, byte slices to be encoded as a single string.
  237 + if s, ok := x.(string); ok {
  238 + v.SetBytes([]byte(s))
  239 + return
  240 + }
  241 + }
  242 +
  243 + // NOTE: Implicit indexing is currently done at the parseValues level,
  244 + // so if if an implicitKey reaches here it will always replace the last.
  245 + implicit := 0
  246 + for k, c := range getNode(x) {
  247 + var i int
  248 + if k == implicitKey {
  249 + i = implicit
  250 + implicit++
  251 + } else {
  252 + explicit, err := strconv.Atoi(k)
  253 + if err != nil {
  254 + panic(k + " is not a valid index for type " + t.String())
  255 + }
  256 + i = explicit
  257 + implicit = explicit + 1
  258 + }
  259 + // "Extend" the slice if it's too short.
  260 + if l := v.Len(); i >= l {
  261 + delta := i - l + 1
  262 + v.Set(reflect.AppendSlice(v, reflect.MakeSlice(t, delta, delta)))
  263 + }
  264 + d.decodeValue(v.Index(i), c)
  265 + }
  266 +}
  267 +
  268 +func (d Decoder) decodeBasic(v reflect.Value, x interface{}) {
  269 + t := v.Type()
  270 + switch k, s := t.Kind(), getString(x); k {
  271 + case reflect.Bool:
  272 + if b, e := strconv.ParseBool(s); e == nil {
  273 + v.SetBool(b)
  274 + } else {
  275 + panic("could not parse bool from " + strconv.Quote(s))
  276 + }
  277 + case reflect.Int,
  278 + reflect.Int8,
  279 + reflect.Int16,
  280 + reflect.Int32,
  281 + reflect.Int64:
  282 + if i, e := strconv.ParseInt(s, 10, 64); e == nil {
  283 + v.SetInt(i)
  284 + } else {
  285 + panic("could not parse int from " + strconv.Quote(s))
  286 + }
  287 + case reflect.Uint,
  288 + reflect.Uint8,
  289 + reflect.Uint16,
  290 + reflect.Uint32,
  291 + reflect.Uint64:
  292 + if u, e := strconv.ParseUint(s, 10, 64); e == nil {
  293 + v.SetUint(u)
  294 + } else {
  295 + panic("could not parse uint from " + strconv.Quote(s))
  296 + }
  297 + case reflect.Float32,
  298 + reflect.Float64:
  299 + if f, e := strconv.ParseFloat(s, 64); e == nil {
  300 + v.SetFloat(f)
  301 + } else {
  302 + panic("could not parse float from " + strconv.Quote(s))
  303 + }
  304 + case reflect.Complex64,
  305 + reflect.Complex128:
  306 + var c complex128
  307 + if n, err := fmt.Sscanf(s, "%g", &c); n == 1 && err == nil {
  308 + v.SetComplex(c)
  309 + } else {
  310 + panic("could not parse complex from " + strconv.Quote(s))
  311 + }
  312 + case reflect.String:
  313 + v.SetString(s)
  314 + default:
  315 + panic(t.String() + " has unsupported kind " + k.String())
  316 + }
  317 +}
  318 +
  319 +func (d Decoder) decodeTime(v reflect.Value, x interface{}) {
  320 + t := v.Type()
  321 + s := getString(x)
  322 + // TODO: Find a more efficient way to do this.
  323 + for _, f := range allowedTimeFormats {
  324 + if p, err := time.Parse(f, s); err == nil {
  325 + v.Set(reflect.ValueOf(p).Convert(v.Type()))
  326 + return
  327 + }
  328 + }
  329 + panic("cannot decode string `" + s + "` as " + t.String())
  330 +}
  331 +
  332 +func (d Decoder) decodeURL(v reflect.Value, x interface{}) {
  333 + t := v.Type()
  334 + s := getString(x)
  335 + if u, err := url.Parse(s); err == nil {
  336 + v.Set(reflect.ValueOf(*u).Convert(v.Type()))
  337 + return
  338 + }
  339 + panic("cannot decode string `" + s + "` as " + t.String())
  340 +}
  341 +
  342 +var allowedTimeFormats = []string{
  343 + "2006-01-02T15:04:05.999999999Z07:00",
  344 + "2006-01-02T15:04:05.999999999Z07",
  345 + "2006-01-02T15:04:05.999999999Z",
  346 + "2006-01-02T15:04:05.999999999",
  347 + "2006-01-02T15:04:05Z07:00",
  348 + "2006-01-02T15:04:05Z07",
  349 + "2006-01-02T15:04:05Z",
  350 + "2006-01-02T15:04:05",
  351 + "2006-01-02T15:04Z",
  352 + "2006-01-02T15:04",
  353 + "2006-01-02T15Z",
  354 + "2006-01-02T15",
  355 + "2006-01-02",
  356 + "2006-01",
  357 + "2006",
  358 + "15:04:05.999999999Z07:00",
  359 + "15:04:05.999999999Z07",
  360 + "15:04:05.999999999Z",
  361 + "15:04:05.999999999",
  362 + "15:04:05Z07:00",
  363 + "15:04:05Z07",
  364 + "15:04:05Z",
  365 + "15:04:05",
  366 + "15:04Z",
  367 + "15:04",
  368 + "15Z",
  369 + "15",
  370 +}
  1 +// Copyright 2014 Alvaro J. Genial. All rights reserved.
  2 +// Use of this source code is governed by a BSD-style
  3 +// license that can be found in the LICENSE file.
  4 +
  5 +package form
  6 +
  7 +import (
  8 + "encoding"
  9 + "errors"
  10 + "fmt"
  11 + "io"
  12 + "net/url"
  13 + "reflect"
  14 + "strconv"
  15 + "strings"
  16 + "time"
  17 +)
  18 +
  19 +// NewEncoder returns a new form Encoder.
  20 +func NewEncoder(w io.Writer) *Encoder {
  21 + return &Encoder{w, defaultDelimiter, defaultEscape, false}
  22 +}
  23 +
  24 +// Encoder provides a way to encode to a Writer.
  25 +type Encoder struct {
  26 + w io.Writer
  27 + d rune
  28 + e rune
  29 + z bool
  30 +}
  31 +
  32 +// DelimitWith sets r as the delimiter used for composite keys by Encoder e and returns the latter; it is '.' by default.
  33 +func (e *Encoder) DelimitWith(r rune) *Encoder {
  34 + e.d = r
  35 + return e
  36 +}
  37 +
  38 +// EscapeWith sets r as the escape used for delimiters (and to escape itself) by Encoder e and returns the latter; it is '\\' by default.
  39 +func (e *Encoder) EscapeWith(r rune) *Encoder {
  40 + e.e = r
  41 + return e
  42 +}
  43 +
  44 +// 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.
  45 +func (e *Encoder) KeepZeros(z bool) *Encoder {
  46 + e.z = z
  47 + return e
  48 +}
  49 +
  50 +// Encode encodes dst as form and writes it out using the Encoder's Writer.
  51 +func (e Encoder) Encode(dst interface{}) error {
  52 + v := reflect.ValueOf(dst)
  53 + n, err := encodeToNode(v, e.z)
  54 + if err != nil {
  55 + return err
  56 + }
  57 + s := n.values(e.d, e.e).Encode()
  58 + l, err := io.WriteString(e.w, s)
  59 + switch {
  60 + case err != nil:
  61 + return err
  62 + case l != len(s):
  63 + return errors.New("could not write data completely")
  64 + }
  65 + return nil
  66 +}
  67 +
  68 +// EncodeToString encodes dst as a form and returns it as a string.
  69 +func EncodeToString(dst interface{}) (string, error) {
  70 + v := reflect.ValueOf(dst)
  71 + n, err := encodeToNode(v, false)
  72 + if err != nil {
  73 + return "", err
  74 + }
  75 + vs := n.values(defaultDelimiter, defaultEscape)
  76 + return vs.Encode(), nil
  77 +}
  78 +
  79 +// EncodeToValues encodes dst as a form and returns it as Values.
  80 +func EncodeToValues(dst interface{}) (url.Values, error) {
  81 + v := reflect.ValueOf(dst)
  82 + n, err := encodeToNode(v, false)
  83 + if err != nil {
  84 + return nil, err
  85 + }
  86 + vs := n.values(defaultDelimiter, defaultEscape)
  87 + return vs, nil
  88 +}
  89 +
  90 +func encodeToNode(v reflect.Value, z bool) (n node, err error) {
  91 + defer func() {
  92 + if e := recover(); e != nil {
  93 + err = fmt.Errorf("%v", e)
  94 + }
  95 + }()
  96 + return getNode(encodeValue(v, z)), nil
  97 +}
  98 +
  99 +func encodeValue(v reflect.Value, z bool) interface{} {
  100 + t := v.Type()
  101 + k := v.Kind()
  102 +
  103 + if s, ok := marshalValue(v); ok {
  104 + return s
  105 + } else if !z && isEmptyValue(v) {
  106 + return "" // Treat the zero value as the empty string.
  107 + }
  108 +
  109 + switch k {
  110 + case reflect.Ptr, reflect.Interface:
  111 + return encodeValue(v.Elem(), z)
  112 + case reflect.Struct:
  113 + if t.ConvertibleTo(timeType) {
  114 + return encodeTime(v)
  115 + } else if t.ConvertibleTo(urlType) {
  116 + return encodeURL(v)
  117 + }
  118 + return encodeStruct(v, z)
  119 + case reflect.Slice:
  120 + return encodeSlice(v, z)
  121 + case reflect.Array:
  122 + return encodeArray(v, z)
  123 + case reflect.Map:
  124 + return encodeMap(v, z)
  125 + case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func:
  126 + panic(t.String() + " has unsupported kind " + t.Kind().String())
  127 + default:
  128 + return encodeBasic(v)
  129 + }
  130 +}
  131 +
  132 +func encodeStruct(v reflect.Value, z bool) interface{} {
  133 + t := v.Type()
  134 + n := node{}
  135 + for i := 0; i < t.NumField(); i++ {
  136 + f := t.Field(i)
  137 + k, oe := fieldInfo(f)
  138 +
  139 + if k == "-" {
  140 + continue
  141 + } else if fv := v.Field(i); oe && isEmptyValue(fv) {
  142 + delete(n, k)
  143 + } else {
  144 + n[k] = encodeValue(fv, z)
  145 + }
  146 + }
  147 + return n
  148 +}
  149 +
  150 +func encodeMap(v reflect.Value, z bool) interface{} {
  151 + n := node{}
  152 + for _, i := range v.MapKeys() {
  153 + k := getString(encodeValue(i, z))
  154 + n[k] = encodeValue(v.MapIndex(i), z)
  155 + }
  156 + return n
  157 +}
  158 +
  159 +func encodeArray(v reflect.Value, z bool) interface{} {
  160 + n := node{}
  161 + for i := 0; i < v.Len(); i++ {
  162 + n[strconv.Itoa(i)] = encodeValue(v.Index(i), z)
  163 + }
  164 + return n
  165 +}
  166 +
  167 +func encodeSlice(v reflect.Value, z bool) interface{} {
  168 + t := v.Type()
  169 + if t.Elem().Kind() == reflect.Uint8 {
  170 + return string(v.Bytes()) // Encode byte slices as a single string by default.
  171 + }
  172 + n := node{}
  173 + for i := 0; i < v.Len(); i++ {
  174 + n[strconv.Itoa(i)] = encodeValue(v.Index(i), z)
  175 + }
  176 + return n
  177 +}
  178 +
  179 +func encodeTime(v reflect.Value) string {
  180 + t := v.Convert(timeType).Interface().(time.Time)
  181 + if t.Year() == 0 && (t.Month() == 0 || t.Month() == 1) && (t.Day() == 0 || t.Day() == 1) {
  182 + return t.Format("15:04:05.999999999Z07:00")
  183 + } else if t.Hour() == 0 && t.Minute() == 0 && t.Second() == 0 && t.Nanosecond() == 0 {
  184 + return t.Format("2006-01-02")
  185 + }
  186 + return t.Format("2006-01-02T15:04:05.999999999Z07:00")
  187 +}
  188 +
  189 +func encodeURL(v reflect.Value) string {
  190 + u := v.Convert(urlType).Interface().(url.URL)
  191 + return u.String()
  192 +}
  193 +
  194 +func encodeBasic(v reflect.Value) string {
  195 + t := v.Type()
  196 + switch k := t.Kind(); k {
  197 + case reflect.Bool:
  198 + return strconv.FormatBool(v.Bool())
  199 + case reflect.Int,
  200 + reflect.Int8,
  201 + reflect.Int16,
  202 + reflect.Int32,
  203 + reflect.Int64:
  204 + return strconv.FormatInt(v.Int(), 10)
  205 + case reflect.Uint,
  206 + reflect.Uint8,
  207 + reflect.Uint16,
  208 + reflect.Uint32,
  209 + reflect.Uint64:
  210 + return strconv.FormatUint(v.Uint(), 10)
  211 + case reflect.Float32:
  212 + return strconv.FormatFloat(v.Float(), 'g', -1, 32)
  213 + case reflect.Float64:
  214 + return strconv.FormatFloat(v.Float(), 'g', -1, 64)
  215 + case reflect.Complex64, reflect.Complex128:
  216 + s := fmt.Sprintf("%g", v.Complex())
  217 + return strings.TrimSuffix(strings.TrimPrefix(s, "("), ")")
  218 + case reflect.String:
  219 + return v.String()
  220 + }
  221 + panic(t.String() + " has unsupported kind " + t.Kind().String())
  222 +}
  223 +
  224 +func isEmptyValue(v reflect.Value) bool {
  225 + switch t := v.Type(); v.Kind() {
  226 + case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  227 + return v.Len() == 0
  228 + case reflect.Bool:
  229 + return !v.Bool()
  230 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  231 + return v.Int() == 0
  232 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  233 + return v.Uint() == 0
  234 + case reflect.Float32, reflect.Float64:
  235 + return v.Float() == 0
  236 + case reflect.Complex64, reflect.Complex128:
  237 + return v.Complex() == 0
  238 + case reflect.Interface, reflect.Ptr:
  239 + return v.IsNil()
  240 + case reflect.Struct:
  241 + if t.ConvertibleTo(timeType) {
  242 + return v.Convert(timeType).Interface().(time.Time).IsZero()
  243 + }
  244 + return reflect.DeepEqual(v, reflect.Zero(t))
  245 + }
  246 + return false
  247 +}
  248 +
  249 +// canIndexOrdinally returns whether a value contains an ordered sequence of elements.
  250 +func canIndexOrdinally(v reflect.Value) bool {
  251 + if !v.IsValid() {
  252 + return false
  253 + }
  254 + switch t := v.Type(); t.Kind() {
  255 + case reflect.Ptr, reflect.Interface:
  256 + return canIndexOrdinally(v.Elem())
  257 + case reflect.Slice, reflect.Array:
  258 + return true
  259 + }
  260 + return false
  261 +}
  262 +
  263 +func fieldInfo(f reflect.StructField) (k string, oe bool) {
  264 + if f.PkgPath != "" { // Skip private fields.
  265 + return omittedKey, oe
  266 + }
  267 +
  268 + k = f.Name
  269 + tag := f.Tag.Get("form")
  270 + if tag == "" {
  271 + return k, oe
  272 + }
  273 +
  274 + ps := strings.SplitN(tag, ",", 2)
  275 + if ps[0] != "" {
  276 + k = ps[0]
  277 + }
  278 + if len(ps) == 2 {
  279 + oe = ps[1] == "omitempty"
  280 + }
  281 + return k, oe
  282 +}
  283 +
  284 +func findField(v reflect.Value, n string, ignoreCase bool) (reflect.Value, bool) {
  285 + t := v.Type()
  286 + l := v.NumField()
  287 +
  288 + var lowerN string
  289 + caseInsensitiveMatch := -1
  290 + if ignoreCase {
  291 + lowerN = strings.ToLower(n)
  292 + }
  293 +
  294 + // First try named fields.
  295 + for i := 0; i < l; i++ {
  296 + f := t.Field(i)
  297 + k, _ := fieldInfo(f)
  298 + if k == omittedKey {
  299 + continue
  300 + } else if n == k {
  301 + return v.Field(i), true
  302 + } else if ignoreCase && lowerN == strings.ToLower(k) {
  303 + caseInsensitiveMatch = i
  304 + }
  305 + }
  306 +
  307 + // If no exact match was found try case insensitive match.
  308 + if caseInsensitiveMatch != -1 {
  309 + return v.Field(caseInsensitiveMatch), true
  310 + }
  311 +
  312 + // Then try anonymous (embedded) fields.
  313 + for i := 0; i < l; i++ {
  314 + f := t.Field(i)
  315 + k, _ := fieldInfo(f)
  316 + if k == omittedKey || !f.Anonymous { // || k != "" ?
  317 + continue
  318 + }
  319 + fv := v.Field(i)
  320 + fk := fv.Kind()
  321 + for fk == reflect.Ptr || fk == reflect.Interface {
  322 + fv = fv.Elem()
  323 + fk = fv.Kind()
  324 + }
  325 +
  326 + if fk != reflect.Struct {
  327 + continue
  328 + }
  329 + if ev, ok := findField(fv, n, ignoreCase); ok {
  330 + return ev, true
  331 + }
  332 + }
  333 +
  334 + return reflect.Value{}, false
  335 +}
  336 +
  337 +var (
  338 + stringType = reflect.TypeOf(string(""))
  339 + stringMapType = reflect.TypeOf(map[string]interface{}{})
  340 + timeType = reflect.TypeOf(time.Time{})
  341 + timePtrType = reflect.TypeOf(&time.Time{})
  342 + urlType = reflect.TypeOf(url.URL{})
  343 +)
  344 +
  345 +func skipTextMarshalling(t reflect.Type) bool {
  346 + /*// Skip time.Time because its text unmarshaling is overly rigid:
  347 + return t == timeType || t == timePtrType*/
  348 + // Skip time.Time & convertibles because its text unmarshaling is overly rigid:
  349 + return t.ConvertibleTo(timeType) || t.ConvertibleTo(timePtrType)
  350 +}
  351 +
  352 +func unmarshalValue(v reflect.Value, x interface{}) bool {
  353 + if skipTextMarshalling(v.Type()) {
  354 + return false
  355 + }
  356 +
  357 + tu, ok := v.Interface().(encoding.TextUnmarshaler)
  358 + if !ok && !v.CanAddr() {
  359 + return false
  360 + } else if !ok {
  361 + return unmarshalValue(v.Addr(), x)
  362 + }
  363 +
  364 + s := getString(x)
  365 + if err := tu.UnmarshalText([]byte(s)); err != nil {
  366 + panic(err)
  367 + }
  368 + return true
  369 +}
  370 +
  371 +func marshalValue(v reflect.Value) (string, bool) {
  372 + if skipTextMarshalling(v.Type()) {
  373 + return "", false
  374 + }
  375 +
  376 + tm, ok := v.Interface().(encoding.TextMarshaler)
  377 + if !ok && !v.CanAddr() {
  378 + return "", false
  379 + } else if !ok {
  380 + return marshalValue(v.Addr())
  381 + }
  382 +
  383 + bs, err := tm.MarshalText()
  384 + if err != nil {
  385 + panic(err)
  386 + }
  387 + return string(bs), true
  388 +}
  1 +// Copyright 2014 Alvaro J. Genial. All rights reserved.
  2 +// Use of this source code is governed by a BSD-style
  3 +// license that can be found in the LICENSE file.
  4 +
  5 +// Package form implements encoding and decoding of application/x-www-form-urlencoded data.
  6 +package form
  7 +
  8 +const (
  9 + implicitKey = "_"
  10 + omittedKey = "-"
  11 +
  12 + defaultDelimiter = '.'
  13 + defaultEscape = '\\'
  14 +)
  1 +// Copyright 2014 Alvaro J. Genial. All rights reserved.
  2 +// Use of this source code is governed by a BSD-style
  3 +// license that can be found in the LICENSE file.
  4 +
  5 +package form
  6 +
  7 +import (
  8 + "net/url"
  9 + "strconv"
  10 + "strings"
  11 +)
  12 +
  13 +type node map[string]interface{}
  14 +
  15 +func (n node) values(d, e rune) url.Values {
  16 + vs := url.Values{}
  17 + n.merge(d, e, "", &vs)
  18 + return vs
  19 +}
  20 +
  21 +func (n node) merge(d, e rune, p string, vs *url.Values) {
  22 + for k, x := range n {
  23 + switch y := x.(type) {
  24 + case string:
  25 + vs.Add(p+escape(d, e, k), y)
  26 + case node:
  27 + y.merge(d, e, p+escape(d, e, k)+string(d), vs)
  28 + default:
  29 + panic("value is neither string nor node")
  30 + }
  31 + }
  32 +}
  33 +
  34 +// TODO: Add tests for implicit indexing.
  35 +func parseValues(d, e rune, vs url.Values, canIndexFirstLevelOrdinally bool) node {
  36 + // NOTE: Because of the flattening of potentially multiple strings to one key, implicit indexing works:
  37 + // i. At the first level; e.g. Foo.Bar=A&Foo.Bar=B becomes 0.Foo.Bar=A&1.Foo.Bar=B
  38 + // ii. At the last level; e.g. Foo.Bar._=A&Foo.Bar._=B becomes Foo.Bar.0=A&Foo.Bar.1=B
  39 + // TODO: At in-between levels; e.g. Foo._.Bar=A&Foo._.Bar=B becomes Foo.0.Bar=A&Foo.1.Bar=B
  40 + // (This last one requires that there only be one placeholder in order for it to be unambiguous.)
  41 +
  42 + m := map[string]string{}
  43 + for k, ss := range vs {
  44 + indexLastLevelOrdinally := strings.HasSuffix(k, string(d)+implicitKey)
  45 +
  46 + for i, s := range ss {
  47 + if canIndexFirstLevelOrdinally {
  48 + k = strconv.Itoa(i) + string(d) + k
  49 + } else if indexLastLevelOrdinally {
  50 + k = strings.TrimSuffix(k, implicitKey) + strconv.Itoa(i)
  51 + }
  52 +
  53 + m[k] = s
  54 + }
  55 + }
  56 +
  57 + n := node{}
  58 + for k, s := range m {
  59 + n = n.split(d, e, k, s)
  60 + }
  61 + return n
  62 +}
  63 +
  64 +func splitPath(d, e rune, path string) (k, rest string) {
  65 + esc := false
  66 + for i, r := range path {
  67 + switch {
  68 + case !esc && r == e:
  69 + esc = true
  70 + case !esc && r == d:
  71 + return unescape(d, e, path[:i]), path[i+1:]
  72 + default:
  73 + esc = false
  74 + }
  75 + }
  76 + return unescape(d, e, path), ""
  77 +}
  78 +
  79 +func (n node) split(d, e rune, path, s string) node {
  80 + k, rest := splitPath(d, e, path)
  81 + if rest == "" {
  82 + return add(n, k, s)
  83 + }
  84 + if _, ok := n[k]; !ok {
  85 + n[k] = node{}
  86 + }
  87 +
  88 + c := getNode(n[k])
  89 + n[k] = c.split(d, e, rest, s)
  90 + return n
  91 +}
  92 +
  93 +func add(n node, k, s string) node {
  94 + if n == nil {
  95 + return node{k: s}
  96 + }
  97 +
  98 + if _, ok := n[k]; ok {
  99 + panic("key " + k + " already set")
  100 + }
  101 +
  102 + n[k] = s
  103 + return n
  104 +}
  105 +
  106 +func isEmpty(x interface{}) bool {
  107 + switch y := x.(type) {
  108 + case string:
  109 + return y == ""
  110 + case node:
  111 + if s, ok := y[""].(string); ok {
  112 + return s == ""
  113 + }
  114 + return false
  115 + }
  116 + panic("value is neither string nor node")
  117 +}
  118 +
  119 +func getNode(x interface{}) node {
  120 + switch y := x.(type) {
  121 + case string:
  122 + return node{"": y}
  123 + case node:
  124 + return y
  125 + }
  126 + panic("value is neither string nor node")
  127 +}
  128 +
  129 +func getString(x interface{}) string {
  130 + switch y := x.(type) {
  131 + case string:
  132 + return y
  133 + case node:
  134 + if s, ok := y[""].(string); ok {
  135 + return s
  136 + }
  137 + return ""
  138 + }
  139 + panic("value is neither string nor node")
  140 +}
  141 +
  142 +func escape(d, e rune, s string) string {
  143 + s = strings.Replace(s, string(e), string(e)+string(e), -1) // Escape the escape (\ => \\)
  144 + s = strings.Replace(s, string(d), string(e)+string(d), -1) // Escape the delimiter (. => \.)
  145 + return s
  146 +}
  147 +
  148 +func unescape(d, e rune, s string) string {
  149 + s = strings.Replace(s, string(e)+string(d), string(d), -1) // Unescape the delimiter (\. => .)
  150 + s = strings.Replace(s, string(e)+string(e), string(e), -1) // Unescape the escape (\\ => \)
  151 + return s
  152 +}
  1 +#!/bin/bash -eu
  2 +
  3 +# TODO: Only colorize messages given a suitable terminal.
  4 +# FIXME: Handle case in which no stash entry is created due to no changes.
  5 +
  6 +printf "\e[30m=== PRE-COMMIT STARTING ===\e[m\n"
  7 +git stash save --quiet --keep-index --include-untracked
  8 +
  9 +if go build -v ./... && go test -v -cover ./... && go vet ./... && golint . && travis-lint; then
  10 + result=$?
  11 + printf "\e[32m=== PRE-COMMIT SUCCEEDED ===\e[m\n"
  12 +else
  13 + result=$?
  14 + printf "\e[31m=== PRE-COMMIT FAILED ===\e[m\n"
  15 +fi
  16 +
  17 +git stash pop --quiet
  18 +exit $result
  1 +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
  2 +
  3 +Permission is hereby granted, free of charge, to any person obtaining a copy
  4 +of this software and associated documentation files (the "Software"), to deal
  5 +in the Software without restriction, including without limitation the rights
  6 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7 +copies of the Software, and to permit persons to whom the Software is
  8 +furnished to do so, subject to the following conditions:
  9 +
  10 +The above copyright notice and this permission notice shall be included in
  11 +all copies or substantial portions of the Software.
  12 +
  13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19 +THE SOFTWARE.
  1 +This package is a brotli compressor and decompressor implemented in Go.
  2 +It was translated from the reference implementation (https://github.com/google/brotli)
  3 +with the `c2go` tool at https://github.com/andybalholm/c2go.
  4 +
  5 +I am using it in production with https://github.com/andybalholm/redwood.
  1 +package brotli
  2 +
  3 +/* Copyright 2013 Google Inc. All Rights Reserved.
  4 +
  5 + Distributed under MIT license.
  6 + See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  7 +*/
  8 +
  9 +/* Function to find backward reference copies. */
  10 +
  11 +func computeDistanceCode(distance uint, max_distance uint, dist_cache []int) uint {
  12 + if distance <= max_distance {
  13 + var distance_plus_3 uint = distance + 3
  14 + var offset0 uint = distance_plus_3 - uint(dist_cache[0])
  15 + var offset1 uint = distance_plus_3 - uint(dist_cache[1])
  16 + if distance == uint(dist_cache[0]) {
  17 + return 0
  18 + } else if distance == uint(dist_cache[1]) {
  19 + return 1
  20 + } else if offset0 < 7 {
  21 + return (0x9750468 >> (4 * offset0)) & 0xF
  22 + } else if offset1 < 7 {
  23 + return (0xFDB1ACE >> (4 * offset1)) & 0xF
  24 + } else if distance == uint(dist_cache[2]) {
  25 + return 2
  26 + } else if distance == uint(dist_cache[3]) {
  27 + return 3
  28 + }
  29 + }
  30 +
  31 + return distance + numDistanceShortCodes - 1
  32 +}
  33 +
  34 +/* "commands" points to the next output command to write to, "*num_commands" is
  35 + initially the total amount of commands output by previous
  36 + CreateBackwardReferences calls, and must be incremented by the amount written
  37 + by this call. */
  38 +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) {
  39 + var max_backward_limit uint = maxBackwardLimit(params.lgwin)
  40 + var orig_commands []command = commands
  41 + var insert_length uint = *last_insert_len
  42 + var pos_end uint = position + num_bytes
  43 + var store_end uint
  44 + if num_bytes >= hasher.StoreLookahead() {
  45 + store_end = position + num_bytes - hasher.StoreLookahead() + 1
  46 + } else {
  47 + store_end = position
  48 + }
  49 + var random_heuristics_window_size uint = literalSpreeLengthForSparseSearch(params)
  50 + var apply_random_heuristics uint = position + random_heuristics_window_size
  51 + var gap uint = 0
  52 + /* Set maximum distance, see section 9.1. of the spec. */
  53 +
  54 + const kMinScore uint = scoreBase + 100
  55 +
  56 + /* For speed up heuristics for random data. */
  57 +
  58 + /* Minimum score to accept a backward reference. */
  59 + hasher.PrepareDistanceCache(dist_cache)
  60 + var sr2 hasherSearchResult
  61 + var sr hasherSearchResult
  62 +
  63 + for position+hasher.HashTypeLength() < pos_end {
  64 + var max_length uint = pos_end - position
  65 + var max_distance uint = brotli_min_size_t(position, max_backward_limit)
  66 + sr.len = 0
  67 + sr.len_code_delta = 0
  68 + sr.distance = 0
  69 + sr.score = kMinScore
  70 + hasher.FindLongestMatch(&params.dictionary, ringbuffer, ringbuffer_mask, dist_cache, position, max_length, max_distance, gap, params.dist.max_distance, &sr)
  71 + if sr.score > kMinScore {
  72 + /* Found a match. Let's look for something even better ahead. */
  73 + var delayed_backward_references_in_row int = 0
  74 + max_length--
  75 + for ; ; max_length-- {
  76 + var cost_diff_lazy uint = 175
  77 + if params.quality < minQualityForExtensiveReferenceSearch {
  78 + sr2.len = brotli_min_size_t(sr.len-1, max_length)
  79 + } else {
  80 + sr2.len = 0
  81 + }
  82 + sr2.len_code_delta = 0
  83 + sr2.distance = 0
  84 + sr2.score = kMinScore
  85 + max_distance = brotli_min_size_t(position+1, max_backward_limit)
  86 + hasher.FindLongestMatch(&params.dictionary, ringbuffer, ringbuffer_mask, dist_cache, position+1, max_length, max_distance, gap, params.dist.max_distance, &sr2)
  87 + if sr2.score >= sr.score+cost_diff_lazy {
  88 + /* Ok, let's just write one byte for now and start a match from the
  89 + next byte. */
  90 + position++
  91 +
  92 + insert_length++
  93 + sr = sr2
  94 + delayed_backward_references_in_row++
  95 + if delayed_backward_references_in_row < 4 && position+hasher.HashTypeLength() < pos_end {
  96 + continue
  97 + }
  98 + }
  99 +
  100 + break
  101 + }
  102 +
  103 + apply_random_heuristics = position + 2*sr.len + random_heuristics_window_size
  104 + max_distance = brotli_min_size_t(position, max_backward_limit)
  105 + {
  106 + /* The first 16 codes are special short-codes,
  107 + and the minimum offset is 1. */
  108 + var distance_code uint = computeDistanceCode(sr.distance, max_distance+gap, dist_cache)
  109 + if (sr.distance <= (max_distance + gap)) && distance_code > 0 {
  110 + dist_cache[3] = dist_cache[2]
  111 + dist_cache[2] = dist_cache[1]
  112 + dist_cache[1] = dist_cache[0]
  113 + dist_cache[0] = int(sr.distance)
  114 + hasher.PrepareDistanceCache(dist_cache)
  115 + }
  116 +
  117 + initCommand(&commands[0], &params.dist, insert_length, sr.len, sr.len_code_delta, distance_code)
  118 + commands = commands[1:]
  119 + }
  120 +
  121 + *num_literals += insert_length
  122 + insert_length = 0
  123 + /* Put the hash keys into the table, if there are enough bytes left.
  124 + Depending on the hasher implementation, it can push all positions
  125 + in the given range or only a subset of them.
  126 + Avoid hash poisoning with RLE data. */
  127 + {
  128 + var range_start uint = position + 2
  129 + var range_end uint = brotli_min_size_t(position+sr.len, store_end)
  130 + if sr.distance < sr.len>>2 {
  131 + range_start = brotli_min_size_t(range_end, brotli_max_size_t(range_start, position+sr.len-(sr.distance<<2)))
  132 + }
  133 +
  134 + hasher.StoreRange(ringbuffer, ringbuffer_mask, range_start, range_end)
  135 + }
  136 +
  137 + position += sr.len
  138 + } else {
  139 + insert_length++
  140 + position++
  141 +
  142 + /* If we have not seen matches for a long time, we can skip some
  143 + match lookups. Unsuccessful match lookups are very very expensive
  144 + and this kind of a heuristic speeds up compression quite
  145 + a lot. */
  146 + if position > apply_random_heuristics {
  147 + /* Going through uncompressible data, jump. */
  148 + if position > apply_random_heuristics+4*random_heuristics_window_size {
  149 + var kMargin uint = brotli_max_size_t(hasher.StoreLookahead()-1, 4)
  150 + /* It is quite a long time since we saw a copy, so we assume
  151 + that this data is not compressible, and store hashes less
  152 + often. Hashes of non compressible data are less likely to
  153 + turn out to be useful in the future, too, so we store less of
  154 + them to not to flood out the hash table of good compressible
  155 + data. */
  156 +
  157 + var pos_jump uint = brotli_min_size_t(position+16, pos_end-kMargin)
  158 + for ; position < pos_jump; position += 4 {
  159 + hasher.Store(ringbuffer, ringbuffer_mask, position)
  160 + insert_length += 4
  161 + }
  162 + } else {
  163 + var kMargin uint = brotli_max_size_t(hasher.StoreLookahead()-1, 2)
  164 + var pos_jump uint = brotli_min_size_t(position+8, pos_end-kMargin)
  165 + for ; position < pos_jump; position += 2 {
  166 + hasher.Store(ringbuffer, ringbuffer_mask, position)
  167 + insert_length += 2
  168 + }
  169 + }
  170 + }
  171 + }
  172 + }
  173 +
  174 + insert_length += pos_end - position
  175 + *last_insert_len = insert_length
  176 + *num_commands += uint(-cap(commands) + cap(orig_commands))
  177 +}