作者 Your Name

Merge branch 'test' into master

正在显示 34 个修改的文件 包含 2396 行增加606 行删除

要显示太多修改。

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

... ... @@ -3,6 +3,7 @@ module gitlab.fjmaimaimai.com/mmm-go/partnermg
go 1.14
require (
github.com/360EntSecGroup-Skylar/excelize/v2 v2.3.1
github.com/GeeTeam/gt3-golang-sdk v0.0.0-20200116043922-446ca8a507d2
github.com/Shopify/sarama v1.23.1
github.com/ajg/form v1.5.1 // indirect
... ...
package service
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/businessBonus/command"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/businessBonus/query"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)
type BusinessBonusService struct {
}
... ... @@ -20,160 +9,160 @@ func NewBusinessBonusService(option map[string]interface{}) *BusinessBonusServic
}
// ListBusinessBonus 列表
func (srv BusinessBonusService) ListBusinessBonus(queryOption query.ListBusinessBonusQuery) (int, interface{}, error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
err error
)
if err = transactionContext.StartTransaction(); err != nil {
return 0, nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
// func (srv BusinessBonusService) ListBusinessBonus(queryOption query.ListBusinessBonusQuery) (int, interface{}, error) {
// var (
// transactionContext, _ = factory.CreateTransactionContext(nil)
// err error
// )
// if err = transactionContext.StartTransaction(); err != nil {
// return 0, nil, err
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
var (
bonusDaoao *dao.BusinessBonusDao
)
if bonusDaoao, err = factory.CreateBusinessBonusDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return 0, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
result, err := bonusDaoao.SearchBusinessBonus(queryOption.PartnerId, queryOption.PartnerNameMatch,
queryOption.CompanyId, queryOption.Limit, queryOption.Offset)
if err != nil {
return 0, nil, err
}
cnt, err := bonusDaoao.CountBusinessBonus(queryOption.PartnerId, queryOption.PartnerNameMatch,
queryOption.CompanyId, queryOption.Limit, queryOption.Offset)
if err != nil {
return 0, nil, err
}
err = transactionContext.CommitTransaction()
// var (
// bonusDaoao *dao.BusinessBonusDao
// )
// if bonusDaoao, err = factory.CreateBusinessBonusDao(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return 0, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
// }
// result, err := bonusDaoao.SearchBusinessBonus(queryOption.PartnerId, queryOption.PartnerNameMatch,
// queryOption.CompanyId, queryOption.Limit, queryOption.Offset)
// if err != nil {
// return 0, nil, err
// }
// cnt, err := bonusDaoao.CountBusinessBonus(queryOption.PartnerId, queryOption.PartnerNameMatch,
// queryOption.CompanyId, queryOption.Limit, queryOption.Offset)
// if err != nil {
// return 0, nil, err
// }
// err = transactionContext.CommitTransaction()
returnData := []map[string]interface{}{}
for _, v := range result {
m := map[string]interface{}{
"id": v.Id,
"uncollectedDividends": v.BonusNot,
"receiveDividends": v.BonusHas,
"dividendsReceivable": v.Bonus,
"stateOfPayment": v.BonusStatus,
"stateOfPaymentName": domain.DescribeBusinessBonusStatus(v.BonusStatus),
"partner": v.PartnerName,
"updateTime": "",
}
if !v.UpdateAt.IsZero() {
m["updateTime"] = v.UpdateAt.Local().Format("2006-01-02 15:04:05")
}
returnData = append(returnData, m)
}
return cnt, returnData, nil
}
// returnData := []map[string]interface{}{}
// for _, v := range result {
// m := map[string]interface{}{
// "id": v.Id,
// "uncollectedDividends": v.BonusNot,
// "receiveDividends": v.BonusHas,
// "dividendsReceivable": v.Bonus,
// "stateOfPayment": v.BonusStatus,
// "stateOfPaymentName": domain.DescribeBusinessBonusStatus(v.BonusStatus),
// "partner": v.PartnerName,
// "updateTime": "",
// }
// if !v.UpdateAt.IsZero() {
// m["updateTime"] = v.UpdateAt.Local().Format("2006-01-02 15:04:05")
// }
// returnData = append(returnData, m)
// }
// return cnt, returnData, nil
// }
func (srv BusinessBonusService) UpdateBusinessBonus(cmd command.UpdateBusinessBonusCommand) error {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
err error
)
if err = transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
transactionContext.RollbackTransaction()
}()
var (
bonusRespository domain.BusinessBonusRepository
bonusData *domain.BusinessBonus
)
if bonusRespository, err = factory.CreateBusinessBonusRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
bonusData, err = bonusRespository.FindOne(domain.BusinessBonusFindOneQuery{
Id: cmd.Id, CompanyId: cmd.CompanyId,
})
if err != nil {
e := fmt.Sprintf("获取业务分红(id=%d;company_id=%d)数据失败:%s", cmd.Id, cmd.CompanyId, err)
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
}
bonusData.Bonus = cmd.Bonus
switch cmd.BonusStatus {
case domain.BUSINESS_BONUS_HAS_PAY:
bonusData.BusinessBonusPayStatus.PayPartnerBonus(bonusData)
case domain.BUSINESS_BONUS_WAIT_PAY:
bonusData.BusinessBonusPayStatus.WartPayPartnerBonus(bonusData)
case domain.BUSINESS_BONUS_NULL_PAY:
bonusData.BusinessBonusPayStatus.NullPayPartnerBonus(bonusData)
default:
return lib.ThrowError(lib.BUSINESS_ERROR, "支付状态错误")
}
err = bonusRespository.Edit(bonusData)
if err != nil {
e := fmt.Sprintf("更新业务分红(id=%d)数据失败:%s", bonusData.Id, err)
return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
}
err = transactionContext.CommitTransaction()
return nil
}
// func (srv BusinessBonusService) UpdateBusinessBonus(cmd command.UpdateBusinessBonusCommand) error {
// var (
// transactionContext, _ = factory.CreateTransactionContext(nil)
// err error
// )
// if err = transactionContext.StartTransaction(); err != nil {
// return err
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
// var (
// bonusRespository domain.BusinessBonusRepository
// bonusData *domain.BusinessBonus
// )
// if bonusRespository, err = factory.CreateBusinessBonusRepository(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
// }
// bonusData, err = bonusRespository.FindOne(domain.BusinessBonusFindOneQuery{
// Id: cmd.Id, CompanyId: cmd.CompanyId,
// })
// if err != nil {
// e := fmt.Sprintf("获取业务分红(id=%d;company_id=%d)数据失败:%s", cmd.Id, cmd.CompanyId, err)
// return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
// }
// bonusData.Bonus = cmd.Bonus
// switch cmd.BonusStatus {
// case domain.BUSINESS_BONUS_HAS_PAY:
// bonusData.BusinessBonusPayStatus.PayPartnerBonus(bonusData)
// case domain.BUSINESS_BONUS_WAIT_PAY:
// bonusData.BusinessBonusPayStatus.WartPayPartnerBonus(bonusData)
// case domain.BUSINESS_BONUS_NULL_PAY:
// bonusData.BusinessBonusPayStatus.NullPayPartnerBonus(bonusData)
// default:
// return lib.ThrowError(lib.BUSINESS_ERROR, "支付状态错误")
// }
// err = bonusRespository.Edit(bonusData)
// if err != nil {
// e := fmt.Sprintf("更新业务分红(id=%d)数据失败:%s", bonusData.Id, err)
// return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
// }
// err = transactionContext.CommitTransaction()
// return nil
// }
//GetBusinessBonus 获取详情
func (srv BusinessBonusService) GetBusinessBonus(queryOption query.GetBusinessBonusQuery) (map[string]interface{}, error) {
// func (srv BusinessBonusService) GetBusinessBonus(queryOption query.GetBusinessBonusQuery) (map[string]interface{}, error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
err error
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
var (
bonusRespository domain.BusinessBonusRepository
partnerInfoRepository domain.PartnerInfoRepository
bonusData *domain.BusinessBonus
partnerData *domain.PartnerInfo
)
if bonusRespository, err = factory.CreateBusinessBonusRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
bonusData, err = bonusRespository.FindOne(domain.BusinessBonusFindOneQuery{
Id: queryOption.Id, CompanyId: queryOption.CompanyId,
})
if err != nil {
e := fmt.Sprintf("获取业务分红(id=%d;company_id=%d)数据失败:%s", queryOption.Id, queryOption.CompanyId, err)
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
}
if partnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
partnerData, err = partnerInfoRepository.FindOne(domain.PartnerFindOneQuery{UserId: bonusData.PartnerInfoId})
if err != nil {
e := fmt.Sprintf("获取合伙人(id=%d)数据失败:%s", bonusData.PartnerInfoId, err)
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
}
err = transactionContext.CommitTransaction()
returnData := map[string]interface{}{
"partner": partnerData.Partner.PartnerName,
"dividendsReceivable": bonusData.Bonus,
"receiveDividends": bonusData.BonusHas,
"uncollectedDividends": bonusData.BonusNot,
"updateTime": "",
"stateOfPayment": bonusData.BonusStatus,
"stateOfPaymentName": domain.DescribeBusinessBonusStatus(bonusData.BonusStatus),
"id": bonusData.Id,
}
if !bonusData.UpdateAt.IsZero() {
returnData["updateTime"] = bonusData.UpdateAt.Local().Format("2006-01-02 15:04:05")
}
// var (
// transactionContext, _ = factory.CreateTransactionContext(nil)
// err error
// )
// if err = transactionContext.StartTransaction(); err != nil {
// return nil, err
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
// var (
// bonusRespository domain.BusinessBonusRepository
// partnerInfoRepository domain.PartnerInfoRepository
// bonusData *domain.BusinessBonus
// partnerData *domain.PartnerInfo
// )
// if bonusRespository, err = factory.CreateBusinessBonusRepository(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
// }
// bonusData, err = bonusRespository.FindOne(domain.BusinessBonusFindOneQuery{
// Id: queryOption.Id, CompanyId: queryOption.CompanyId,
// })
// if err != nil {
// e := fmt.Sprintf("获取业务分红(id=%d;company_id=%d)数据失败:%s", queryOption.Id, queryOption.CompanyId, err)
// return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
// }
// if partnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{
// "transactionContext": transactionContext,
// }); err != nil {
// return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
// }
// partnerData, err = partnerInfoRepository.FindOne(domain.PartnerFindOneQuery{UserId: bonusData.PartnerInfoId})
// if err != nil {
// e := fmt.Sprintf("获取合伙人(id=%d)数据失败:%s", bonusData.PartnerInfoId, err)
// return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
// }
// err = transactionContext.CommitTransaction()
// returnData := map[string]interface{}{
// "partner": partnerData.Partner.PartnerName,
// "dividendsReceivable": bonusData.Bonus,
// "receiveDividends": bonusData.BonusHas,
// "uncollectedDividends": bonusData.BonusNot,
// "updateTime": "",
// "stateOfPayment": bonusData.BonusStatus,
// "stateOfPaymentName": domain.DescribeBusinessBonusStatus(bonusData.BonusStatus),
// "id": bonusData.Id,
// }
// if !bonusData.UpdateAt.IsZero() {
// returnData["updateTime"] = bonusData.UpdateAt.Local().Format("2006-01-02 15:04:05")
// }
return returnData, nil
}
// return returnData, nil
// }
... ...
... ... @@ -19,4 +19,6 @@ type CreateOrderCommand struct {
//货品
Goods []OrderGoodData `json:"goods"`
CompanyId int64 `json:"companyId"`
PartnerCategory int64 `json:"partner_category"`
}
... ...
... ... @@ -20,4 +20,6 @@ type UpdateOrderCommand struct {
//货品
Goods []OrderGoodData `json:"goods"`
CompanyId int64 `json:"companyId"`
PartnerCategory int64 `json:"partner_category"`
}
... ...
... ... @@ -2,19 +2,17 @@ package query
//ListOrderQuery 获取用户列表
type ListOrderBaseQuery struct {
//合伙人id
PartnerId int64 `json:"partnerId" `
//订单编号
OrderCode string `json:"order_code"`
// 查询偏离量
Offset int `json:"offset" `
// 查询限制
Limit int `json:"limit"`
//发货单号
DeliveryCode string `json:"deliveryCode"`
PartnerOrCode string `json:"partnerOrCode"`
CompanyId int64 `json:"companyId"`
//订单类型
OrderType int `json:"orderType"`
PartnerOrCode string `json:"partner_or_code"`
//合伙人分类
PartnerCategory int `json:"partnerCategory"`
UpdateTimeBegin string `json:"updateTimeBegin"`
UpdateTimeEnd string `json:"updateTimeEnd"`
}
... ...
... ... @@ -6,7 +6,8 @@ type ListOrderBonusQuery struct {
// 查询限制
Limit int `json:"limit"`
CompanyId int64 `json:"companyId"`
PartnerCategory int `json:"partnerCategory"`
//订单类型
OrderType int `json:"orderType"`
PartnerOrCode string `json:"partner_or_code"`
PartnerOrCode string `json:"partnerOrCode"`
}
... ...
... ... @@ -29,7 +29,8 @@ func NewOrderInfoService(option map[string]interface{}) *OrderInfoService {
}
// PageListOrderBase 获取订单列表
func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrderBaseQuery) ([]domain.OrderBase, int, error) {
func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrderBaseQuery) ([]map[string]interface{}, int, error) {
var err error
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, 0, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
... ... @@ -41,28 +42,24 @@ func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrder
transactionContext.RollbackTransaction()
}()
var (
orderRepository domain.OrderBaseRepository
orders []domain.OrderBase
orderDao *dao.OrderBaseDao
orders []models.OrderBase
cnt int
)
if value, err := factory.CreateOrderBaseRepository(map[string]interface{}{
if orderDao, err = factory.CreateOrderBaseDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
} else {
orderRepository = value
}
query := domain.OrderBaseFindQuery{
PartnerId: listOrderQuery.PartnerId,
OrderCode: listOrderQuery.OrderCode,
Offset: listOrderQuery.Offset,
Limit: listOrderQuery.Limit,
OrderType: listOrderQuery.OrderType,
DeliveryCode: listOrderQuery.DeliveryCode,
CompanyId: listOrderQuery.CompanyId,
}
orders, cnt, err = orderRepository.Find(query)
orders, cnt, err = orderDao.OrderListByCondition(
listOrderQuery.CompanyId,
listOrderQuery.OrderType,
listOrderQuery.PartnerOrCode,
[2]string{listOrderQuery.UpdateTimeBegin, listOrderQuery.UpdateTimeEnd},
listOrderQuery.PartnerCategory,
listOrderQuery.Limit, listOrderQuery.Offset,
)
if err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
... ... @@ -72,6 +69,9 @@ func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrder
}); err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
orderDataReturn := make([]map[string]interface{}, 0)
for i := range orders {
partnerData := &domain.PartnerInfo{}
partnerData, err = PartnerInfoRepository.FindOne(domain.PartnerFindOneQuery{
... ... @@ -79,12 +79,35 @@ func (service OrderInfoService) PageListOrderBase(listOrderQuery query.ListOrder
})
if err != nil {
logs.Error("获取合伙(id=%d)失败%s", orders[i].PartnerId, err)
} else {
orders[i].PartnerInfo = partnerData.Partner
}
listIndex := listOrderQuery.Offset + (1 + i)
m := map[string]interface{}{
"index": listIndex,
"createTime": orders[i].CreateTime.Local().Format("2006-01-02 15:04:05"),
"updateTime": orders[i].UpdateTime.Local().Format("2006-01-02 15:04:05"),
"buyer": orders[i].Buyer.BuyerName,
"id": orders[i].Id,
"orderId": orders[i].OrderCode,
"shipmentsId": orders[i].DeliveryCode,
"partner": partnerData.Partner.PartnerName,
"orderNum": orders[i].PlanOrderCount,
"orderPrice": orders[i].PlanOrderAmount,
"orderDist": orders[i].RegionInfo.RegionName,
"quantityControl": "",
"priceControl": "",
"status": orders[i].IsDisable,
"partnerCategory": orders[i].PartnerCategory.Name,
}
if orders[i].UseOrderCount >= 0 {
m["quantityControl"] = fmt.Sprint(orders[i].UseOrderCount)
}
if orders[i].UseOrderAmount >= 0 {
m["priceControl"] = fmt.Sprint(orders[i].UseOrderAmount)
}
orderDataReturn = append(orderDataReturn, m)
}
transactionContext.CommitTransaction()
return orders, cnt, nil
return orderDataReturn, cnt, nil
}
//GetOrderDetail 获取订单详情
... ... @@ -202,11 +225,11 @@ func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
//检查order_code是否重复
// if ok, err := orderBaseDao.OrderCodeExist(cmd.OrderCode); err != nil {
// return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
// } else if ok {
// return nil, lib.ThrowError(lib.BUSINESS_ERROR, "订单号已存在")
// }
if ok, err := orderBaseDao.OrderCodeExist(cmd.OrderCode, cmd.PartnerCategory, cmd.PartnerId); err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
} else if ok {
return nil, lib.ThrowError(lib.BUSINESS_ERROR, "订单号已存在")
}
//检查delivery_code是否重复
if len(cmd.DeliveryCode) > 0 {
if ok, err := orderBaseDao.DeliveryCodeExist(cmd.DeliveryCode, cmd.CompanyId); err != nil {
... ... @@ -229,6 +252,32 @@ func (service OrderInfoService) CreateNewOrder(cmd command.CreateOrderCommand) (
SalesmanBonusPercent: cmd.SalesmanBonusPercent,
CompanyId: cmd.CompanyId,
}
var categoryRepository domain.PartnerCategoryRepository
if categoryRepository, err = factory.CreatePartnerCategoryRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
var cmdPartnerCategoryOk bool
for _, v := range partnerData.PartnerCategoryInfos {
if v.Id == cmd.PartnerCategory {
_, categorys, err := categoryRepository.Find(domain.PartnerCategoryFindQuery{
Ids: []int64{v.Id},
})
if err != nil {
e := fmt.Sprintf("获取合伙人分类数据失败:%s", err)
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
}
if len(categorys) > 0 {
newOrder.PartnerCategory = categorys[0]
cmdPartnerCategoryOk = true
}
break
}
}
if !cmdPartnerCategoryOk {
return nil, lib.ThrowError(lib.BUSINESS_ERROR, "合伙人类型选择错误")
}
var orderGoods []domain.OrderGood
for _, good := range cmd.Goods {
m := domain.NewOrderGood()
... ... @@ -378,13 +427,15 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand)
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
//检查order_code是否重复
// if ok, err := orderBaseDao.OrderCodeExist(cmd.OrderCode, cmd.Id); err != nil {
// return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
// } else if ok {
// return nil, lib.ThrowError(lib.BUSINESS_ERROR, "订单号已存在")
// }
if oldOrderData.OrderCode != cmd.OrderCode || cmd.PartnerCategory != oldOrderData.PartnerCategory.Id {
if ok, err := orderBaseDao.OrderCodeExist(cmd.OrderCode, cmd.PartnerCategory, cmd.PartnerId); err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
} else if ok {
return nil, lib.ThrowError(lib.BUSINESS_ERROR, "订单号已存在")
}
}
//检查delivery_code是否重复
if len(cmd.DeliveryCode) > 0 {
if cmd.DeliveryCode != oldOrderData.DeliveryCode {
if ok, err := orderBaseDao.DeliveryCodeExist(cmd.DeliveryCode, cmd.CompanyId, cmd.Id); err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
} else if ok {
... ... @@ -418,6 +469,16 @@ func (service OrderInfoService) UpdateOrderData(cmd command.UpdateOrderCommand)
}
newOrderGoods = append(newOrderGoods, m)
}
var cmdPartnerCategoryOk bool
for _, v := range partnerData.PartnerCategoryInfos {
if v.Id == cmd.PartnerCategory {
oldOrderData.PartnerCategory = v
cmdPartnerCategoryOk = true
}
}
if !cmdPartnerCategoryOk {
return nil, lib.ThrowError(lib.BUSINESS_ERROR, "合伙人类型选择错误")
}
oldOrderData.OrderCode = cmd.OrderCode
oldOrderData.DeliveryCode = cmd.DeliveryCode
oldOrderData.Buyer.BuyerName = cmd.BuyerName
... ... @@ -744,6 +805,7 @@ func (service OrderInfoService) PageListOrderBonus(listOrderQuery query.ListOrde
listOrderQuery.CompanyId,
listOrderQuery.OrderType,
listOrderQuery.PartnerOrCode,
listOrderQuery.PartnerCategory,
listOrderQuery.Limit,
listOrderQuery.Offset,
)
... ... @@ -804,7 +866,9 @@ func (service OrderInfoService) PageListOrderBonus(listOrderQuery query.ListOrde
hasBonusPercent = true
}
}
listIndex := listOrderQuery.Offset + (1 + i)
listItem := map[string]interface{}{
"index": listIndex,
"updateTime": orders[i].UpdateTime.Local().Format("2006-01-02 15:04:05"),
"id": orders[i].Id,
"shipmentsId": orders[i].DeliveryCode,
... ... @@ -1178,3 +1242,82 @@ func (service OrderInfoService) UpdateOrderRemarkBonus(orderId int64, adminId in
}
return nil
}
func (service OrderInfoService) ListOrderBonusForExcel(listOrderQuery query.ListOrderBonusQuery) ([]map[string]string, [][2]string, error) {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
if err = transactionContext.StartTransaction(); err != nil {
return nil, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var (
orderBaseDao *dao.OrderBaseDao
)
if orderBaseDao, err = factory.CreateOrderBaseDao(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
result, err := orderBaseDao.OrderBonusListForExcel(
listOrderQuery.CompanyId,
listOrderQuery.OrderType,
listOrderQuery.PartnerOrCode,
listOrderQuery.PartnerCategory,
)
if err != nil {
return nil, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
err = transactionContext.CommitTransaction()
if err != nil {
return nil, nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
var resultMaps []map[string]string
for i := range result {
m := map[string]string{
"num": fmt.Sprint(i + 1),
"order_type": domain.GetOrderBaseTypeName(result[i].OrderType),
"order_code": result[i].OrderCode,
"delivery_code": result[i].DeliveryCode,
"partner_name": result[i].PartnerName,
"bonus_status": "",
"update_time": result[i].UpdateTime,
"partner_bonus": fmt.Sprint(result[i].PartnerBonus),
"partner_bonus_has": fmt.Sprint(result[i].PartnerBonusHas),
"partner_bonus_not": fmt.Sprint(result[i].PartnerBonusNot),
"partner_bonus_expense": fmt.Sprint(result[i].PartnerBonusExpense),
}
if result[i].HasBonusPercent == 0 {
m["partner_bonus"] = "-"
m["partner_bonus_has"] = "-"
m["partner_bonus_not"] = "-"
m["partner_bonus_expense"] = "-"
}
switch result[i].BonusStatus {
case domain.OrderGoodWaitPay:
m["bonus_status"] = "等待支付分红"
case domain.OrderGoodHasPay:
m["bonus_status"] = "已支付分红"
}
resultMaps = append(resultMaps, m)
}
column := [][2]string{
[2]string{"num", "序号"},
[2]string{"order_type", "订单类型"},
[2]string{"order_code", "订单号"},
[2]string{"delivery_code", "发货单号"},
[2]string{"partner_name", "合伙人"},
[2]string{"bonus_status", "支付状态"},
[2]string{"update_time", "最后操作时间"},
[2]string{"partner_bonus", "应收分红"},
[2]string{"partner_bonus_has", "已收分红"},
[2]string{"partner_bonus_not", "未收分红"},
[2]string{"partner_bonus_expense", "分红支出"},
}
return resultMaps, column, nil
}
... ...
... ... @@ -250,6 +250,7 @@ func (s SyncOrderService) copyOrderBestshopToOrderBase(orderBestshop *domain.Ord
orderbase.Goods = ordergoods
orderbase.PartnerId = partnerData.Partner.Id
orderbase.CompanyId = partnerData.CompanyId
orderbase.PartnerCategory = domain.PartnerCategory{Id: 1, Name: "事业合伙人"} // 默认设定为事业合伙人订单
orderbase.Compute()
err = orderBaseRepository.Save(&orderbase)
if err != nil {
... ...
... ... @@ -20,6 +20,7 @@ type CompanyBaseApplet struct {
Name string `json:"name"`
URL string `json:"url"`
Id string `json:"id"`
ImageUrl string `json:"imageUrl"`
}
//企业平台的公司基础数据
... ... @@ -117,6 +118,7 @@ func (service SyncCompanyService) addCompany(data CompanytData) error {
Name: v.Name,
URL: v.URL,
Id: v.Id,
ImageUrl: v.ImageUrl,
}
applets = append(applets, app)
}
... ... @@ -210,6 +212,7 @@ func (service SyncCompanyService) updateCompany(data CompanytData) error {
Name: v.Name,
URL: v.URL,
Id: v.Id,
ImageUrl: v.ImageUrl,
}
applets = append(applets, app)
}
... ...
package service
import (
"errors"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/unifiedUserCenter/command"
)
... ... @@ -30,7 +28,7 @@ func NewSyncAction(cmd command.SyncCallbackCommand) error {
ok bool
)
if action, ok = actionMap[cmd.Module]; !ok {
return errors.New("module cannot found")
return nil
}
return action.DoAction(cmd.Action, cmd.Data)
}
... ...
... ... @@ -14,7 +14,7 @@ var KafkaCfg KafkaConfig
func init() {
KafkaCfg = KafkaConfig{
Servers: []string{"192.168.190.136:9092"},
Servers: []string{""},
ConsumerId: "partnermg_local",
}
if os.Getenv("KAFKA_HOST") != "" {
... ...
... ... @@ -21,6 +21,7 @@ type CompanyApplets struct {
Name string `json:"name"`
URL string `json:"url"`
Id string `json:"id"`
ImageUrl string `json:"imageUrl"`
}
// 公司信息
... ...
... ... @@ -114,6 +114,8 @@ type OrderBase struct {
DataFrom OrderDataFrom `json:"dataFrom"`
//备注
Remark OrderBaseRemark `json:"remark"`
PartnerCategory PartnerCategory `json:"partnerCategory"`
}
//GetCurrentPartnerBonus 获取当前合伙人应收分红
... ...
... ... @@ -4,7 +4,6 @@ import (
"fmt"
"github.com/go-pg/pg/v10/orm"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
... ... @@ -24,13 +23,15 @@ func NewOrderBaseDao(transactionContext *transaction.TransactionContext) (*Order
}
}
func (dao OrderBaseDao) OrderCodeExist(code string, notId ...int64) (bool, error) {
//OrderCodeExist 检查order_code是否重复
//
func (dao OrderBaseDao) OrderCodeExist(code string, partnerCategory int64, partnerId int64) (bool, error) {
tx := dao.transactionContext.GetDB()
m := &models.OrderBase{}
query := tx.Model(m).Where("order_code=?", code)
if len(notId) > 0 {
query = query.WhereIn("id not in(?)", notId)
}
query := tx.Model(m).
Where("order_code=?", code).
Where("partner_id=?", partnerId).
Where(`partner_category @>'{"id":?}'`, partnerCategory)
ok, err := query.Exists()
return ok, err
}
... ... @@ -49,7 +50,8 @@ func (dao OrderBaseDao) DeliveryCodeExist(code string, companyId int64, notId ..
//OrderListByCondition 根据条件获取订单分红列表
//orderType 订单类型
//partnerOrCode 合伙人姓名或订单号或发货单号
func (dao OrderBaseDao) OrderBonusListByCondition(companyId int64, orderType int, partnerOrCode string, limit, offset int) ([]models.OrderBase, int, error) {
func (dao OrderBaseDao) OrderBonusListByCondition(companyId int64, orderType int, partnerOrCode string,
partnerCategory int, limit, offset int) ([]models.OrderBase, int, error) {
tx := dao.transactionContext.GetDB()
var orders []models.OrderBase
query := tx.Model(&orders).Where("order_base.company_id=?", companyId)
... ... @@ -58,6 +60,9 @@ func (dao OrderBaseDao) OrderBonusListByCondition(companyId int64, orderType int
} else {
query = query.Where("order_base.order_type<>?", domain.OrderIntention)
}
if partnerCategory > 0 {
query = query.Where(`order_base.partner_category@>'{"id":?}'`, partnerCategory)
}
if len(partnerOrCode) > 0 {
query = query.Join("LEFT JOIN partner_info as p ON order_base.partner_id=p.id").
WhereGroup(func(q *orm.Query) (*orm.Query, error) {
... ... @@ -74,3 +79,128 @@ func (dao OrderBaseDao) OrderBonusListByCondition(companyId int64, orderType int
cnt, err := query.SelectAndCount()
return orders, cnt, err
}
//CustomOrderBonusForExcel 导出分红列表所用的结构
type CustomOrderBonusForExcel struct {
OrderId int64
OrderType int
OrderCode string
BonusStatus int
DeliveryCode string
UpdateTime string
PartnerBonus float64
PartnerBonusHas float64
PartnerBonusNot float64
PartnerBonusExpense float64
HasBonusPercent int
PartnerName string
}
//OrderBonusListForExcel 导出分红列表所用
//@param companyId 公司id
//@param orderType 订单类型
//@param partnerOrCode 合伙人姓名或订单号或发货单号
//@param partnerCategory 合伙人类型id
//@return result 查询结果数据
func (dao OrderBaseDao) OrderBonusListForExcel(companyId int64, orderType int, partnerOrCode string,
partnerCategory int) (result []CustomOrderBonusForExcel, err error) {
//导出分红列表所用的sql
sqlStr := `SELECT
t1.ID AS order_id,
t1.order_type,
t1.order_code,
t1.delivery_code,
t1.bonus_status,
to_char(t1.update_time AT TIME ZONE 'CCT' ,'YYYY-MM-DD HH24:MI:SS') AS update_time,
(CASE
WHEN t1.use_partner_bonus>0
THEN
t1.use_partner_bonus
ELSE
t1.plan_partner_bonus
END) AS partner_bonus,
t1.partner_bonus_has,
t1.partner_bonus_not,
t1.partner_bonus_expense,
tt1.has_bonus_percent,
t2.partner_name
FROM
order_base AS t1
LEFT JOIN partner_info AS t2 ON t1.partner_id = t2."id"
LEFT JOIN (
SELECT COUNT ( * ) AS has_bonus_percent, t3.order_id
FROM "order_good" AS t3
WHERE t3.partner_bonus_percent >= 0
GROUP BY t3.order_id
) AS tt1 ON t1."id" = tt1.order_id
WHERE 1=1 `
sqlStr += ` AND t1.company_id = ? `
param := []interface{}{companyId}
if orderType > 0 {
param = append(param, orderType)
sqlStr += ` AND t1.order_type=? `
} else {
param = append(param, domain.OrderIntention)
sqlStr += ` AND t1.order_type<>? `
}
if len(partnerOrCode) > 0 {
sqlStr += ` AND (t1.order_code like ? OR t1.delivery_code like ? OR t2.partner_name like ? )`
likeParam := "%" + partnerOrCode + "%"
param = append(param, likeParam, likeParam, likeParam)
}
if partnerCategory > 0 {
sqlStr += ` AND t1.partner_category @>'{"id":?}'`
param = append(param, partnerCategory)
}
sqlStr += ` ORDER BY t1.update_time DESC limit 10000 `
tx := dao.transactionContext.GetDB()
_, err = tx.Query(&result, sqlStr, param...)
if err != nil {
return result, err
}
return result, nil
}
//OrderListByCondition 获取实际订单列表
//@param companyId 公司id
//@param orderType 订单类型
//@param partnerOrCode 合伙人姓名或订单号或发货单号
//@param partnerCategory 合伙人类型id
//@param updateTime 订单更新时间范围"[开始时间,结束时间]",时间格式"2006-01-02 15:04:05+07"
func (dao OrderBaseDao) OrderListByCondition(companyId int64, orderType int, partnerOrCode string,
updateTime [2]string, partnerCategory int, limit, offset int) ([]models.OrderBase, int, error) {
tx := dao.transactionContext.GetDB()
var orders []models.OrderBase
query := tx.Model(&orders).Where("order_base.company_id=?", companyId)
if orderType > 0 {
query = query.Where("order_base.order_type=?", orderType)
} else {
query = query.Where("order_base.order_type<>?", domain.OrderIntention)
}
if partnerCategory > 0 {
query = query.Where(`order_base.partner_category@>'{"id":?}'`, partnerCategory)
}
if len(updateTime[0]) > 0 {
query = query.Where(`order_base.update_time>=?`, updateTime[0])
}
if len(updateTime[1]) > 0 {
query = query.Where(`order_base.update_time<=?`, updateTime[1])
}
if len(partnerOrCode) > 0 {
query = query.Join("LEFT JOIN partner_info as p ON order_base.partner_id=p.id").
WhereGroup(func(q *orm.Query) (*orm.Query, error) {
q = q.WhereOr("order_base.order_code like ? ", "%"+partnerOrCode+"%").
WhereOr("order_base.delivery_code like ? ", "%"+partnerOrCode+"%").
WhereOr("p.partner_name like ? ", "%"+partnerOrCode+"%")
return q, nil
})
}
query = query.Order("order_base.update_time DESC").
Offset(offset).
Limit(limit)
cnt, err := query.SelectAndCount()
return orders, cnt, err
}
... ...
... ... @@ -67,6 +67,8 @@ type OrderBase struct {
DataFrom domain.OrderDataFrom ``
//备注
Remark domain.OrderBaseRemark ``
//合伙人类型
PartnerCategory domain.PartnerCategory ``
}
var _ pg.BeforeUpdateHook = (*OrderBase)(nil)
... ...
... ... @@ -44,6 +44,7 @@ func (reponsitory OrderBaseRepository) transformPgModelToDomainModel(orderModel
CompanyId: orderModel.CompanyId,
DataFrom: orderModel.DataFrom,
Remark: orderModel.Remark,
PartnerCategory: orderModel.PartnerCategory,
}
return order, nil
}
... ... @@ -65,7 +66,7 @@ func (repository OrderBaseRepository) Save(orderInfo *domain.OrderBase) error {
PartnerBonusExpense: orderInfo.OrderCompute.PartnerBonusExpense, IsDisable: orderInfo.IsDisable,
CreateTime: orderInfo.CreateTime, BonusStatus: orderInfo.BonusStatus,
CompanyId: orderInfo.CompanyId, DataFrom: orderInfo.DataFrom,
Remark: orderInfo.Remark,
Remark: orderInfo.Remark, PartnerCategory: orderInfo.PartnerCategory,
}
if m.Id == 0 {
_, err = tx.Model(m).
... ...
package exceltool
import (
"errors"
"fmt"
"math/rand"
"time"
excelize "github.com/360EntSecGroup-Skylar/excelize/v2"
)
type ExcelHead struct {
Name string
Key string
}
//ExcelMaker 构建excel文档
type ExcelMaker struct {
Xlsx *excelize.File
fileName string
header []ExcelHead
}
//NewExcelMaker ....
func NewExcelMaker() *ExcelMaker {
return &ExcelMaker{
Xlsx: excelize.NewFile(),
}
}
func (e *ExcelMaker) SetListHead(h []ExcelHead) {
e.header = h
}
func (e *ExcelMaker) SetFileName(n string) {
e.fileName = n
}
func (e *ExcelMaker) GetFileName() string {
return e.fileName
}
//MakeListExcel 根据列表形式的数据创建excel文档
//@sourData []map[string]string; 原始数据,要输入excel文档的数据
func (e *ExcelMaker) MakeListExcel(sourData []map[string]string) (err error) {
if len(e.header) == 0 {
return errors.New("xlsHeader 数据格式错误")
}
headEn := []string{} //数据字段英文名
headCn := []string{} //excel字段中文描述
alphaSlice := []string{} //excel列字母索引
for key, val := range e.header {
headEn = append(headEn, val.Key)
headCn = append(headCn, val.Name)
alpha, _ := excelize.ColumnNumberToName(key + 1)
// alpha := ToAlphaString(key)
alphaSlice = append(alphaSlice, alpha)
}
//设置excel文档第一行的字段中文描述
for index := range headCn {
//索引转列名,索引从0开始
cellAlpha := fmt.Sprintf("%s%d", alphaSlice[index], 1) // 单元格行坐标从1开始,如:a1,指第一行a列。
e.Xlsx.SetCellStr("Sheet1", cellAlpha, headCn[index])
}
//从excel第二行开始设置实际数据的值
for key1 := range sourData {
for i := 0; i < len(headEn); i++ {
cellAlpha := fmt.Sprintf("%s%d", alphaSlice[i], key1+2) // 单元格行坐标从1开始,如:a1,指第一行a列。
e.Xlsx.SetCellStr("Sheet1", cellAlpha, sourData[key1][headEn[i]])
}
}
e.SetFileName(GetRandomString(8) + ".xlsx")
return nil
}
//GetRandomString 生成随机字符串
func GetRandomString(lenght int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes := []byte(str)
result := []byte{}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < lenght; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
return string(result)
}
func ToAlphaString(value int) string {
if value < 0 {
return ""
}
var ans string
i := value + 1
for i > 0 {
ans = string((i-1)%26+65) + ans
i = (i - 1) / 26
}
return ans
}
... ...
... ... @@ -8,12 +8,15 @@ import (
"strconv"
"strings"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
userQuery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/users/query"
userService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/users/service"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib/exceltool"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/protocol"
)
... ... @@ -206,3 +209,17 @@ func (controller *BaseController) GetUserCompany() int64 {
}
return uid
}
func (controller *BaseController) ResponseExcelByFile(ctx *context.Context, excelMaker *exceltool.ExcelMaker) error {
fname := excelMaker.GetFileName()
ctx.Output.Header("Content-Disposition", "attachment; filename="+fname)
ctx.Output.Header("Content-Description", "File Transfer")
ctx.Output.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
ctx.Output.Header("Content-Transfer-Encoding", "binary")
ctx.Output.Header("Expires", "0")
ctx.Output.Header("Cache-Control", "must-revalidate")
ctx.Output.Header("Pragma", "public")
//跳过保存文件,直接写入ctx.ResponseWriter
excelMaker.Xlsx.Write(ctx.ResponseWriter)
return nil
}
... ...
package controllers
import (
"errors"
"github.com/astaxie/beego/logs"
businessCommand "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/businessBonus/command"
businessQuery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/businessBonus/query"
businessService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/businessBonus/service"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
)
... ... @@ -24,95 +18,95 @@ func (c *BusinessBonusController) Prepare() {
}
}
func (c *BusinessBonusController) ListBusinessBonus() {
type Parameter struct {
PageNumber int `json:"pageNumber"`
Partner int64 `json:"partner"`
PageSize int `json:"pageSize"`
SearchText string `json:"searchText"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if param.PageSize == 0 {
param.PageSize = 20
}
if param.PageNumber == 0 {
param.PageNumber = 1
}
companyId := c.GetUserCompany()
srv := businessService.NewBusinessBonusService(nil)
cnt, result, err := srv.ListBusinessBonus(businessQuery.ListBusinessBonusQuery{
CompanyId: companyId,
Limit: param.PageSize,
Offset: param.PageSize * (param.PageNumber - 1),
PartnerId: param.Partner,
})
if err != nil {
c.ResponseError(err)
return
}
c.ResponsePageList(result, cnt, param.PageNumber)
}
// func (c *BusinessBonusController) ListBusinessBonus() {
// type Parameter struct {
// PageNumber int `json:"pageNumber"`
// Partner int64 `json:"partner"`
// PageSize int `json:"pageSize"`
// SearchText string `json:"searchText"`
// }
// var (
// param Parameter
// err error
// )
// if err = c.BindJsonData(&param); err != nil {
// logs.Error(err)
// c.ResponseError(errors.New("json数据解析失败"))
// return
// }
// if param.PageSize == 0 {
// param.PageSize = 20
// }
// if param.PageNumber == 0 {
// param.PageNumber = 1
// }
// companyId := c.GetUserCompany()
// srv := businessService.NewBusinessBonusService(nil)
// cnt, result, err := srv.ListBusinessBonus(businessQuery.ListBusinessBonusQuery{
// CompanyId: companyId,
// Limit: param.PageSize,
// Offset: param.PageSize * (param.PageNumber - 1),
// PartnerId: param.Partner,
// })
// if err != nil {
// c.ResponseError(err)
// return
// }
// c.ResponsePageList(result, cnt, param.PageNumber)
// }
func (c *BusinessBonusController) UpdateBusinessBonus() {
type Parameter struct {
Id int64 `json:"id"`
DividendsReceivable float64 `json:"dividendsReceivable"`
StateOfPayment int8 `json:"stateOfPayment"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
companyId := c.GetUserCompany()
srv := businessService.NewBusinessBonusService(nil)
err = srv.UpdateBusinessBonus(businessCommand.UpdateBusinessBonusCommand{
CompanyId: companyId,
Id: param.Id,
Bonus: param.DividendsReceivable,
BonusStatus: param.StateOfPayment,
})
if err != nil {
c.ResponseError(err)
return
}
c.ResponseData(nil)
}
// func (c *BusinessBonusController) UpdateBusinessBonus() {
// type Parameter struct {
// Id int64 `json:"id"`
// DividendsReceivable float64 `json:"dividendsReceivable"`
// StateOfPayment int8 `json:"stateOfPayment"`
// }
// var (
// param Parameter
// err error
// )
// if err = c.BindJsonData(&param); err != nil {
// logs.Error(err)
// c.ResponseError(errors.New("json数据解析失败"))
// return
// }
// companyId := c.GetUserCompany()
// srv := businessService.NewBusinessBonusService(nil)
// err = srv.UpdateBusinessBonus(businessCommand.UpdateBusinessBonusCommand{
// CompanyId: companyId,
// Id: param.Id,
// Bonus: param.DividendsReceivable,
// BonusStatus: param.StateOfPayment,
// })
// if err != nil {
// c.ResponseError(err)
// return
// }
// c.ResponseData(nil)
// }
func (c *BusinessBonusController) GetBusinessBonus() {
type Parameter struct {
Id int64 `json:"id"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
companyId := c.GetUserCompany()
srv := businessService.NewBusinessBonusService(nil)
data, err := srv.GetBusinessBonus(businessQuery.GetBusinessBonusQuery{
Id: param.Id,
CompanyId: companyId,
})
if err != nil {
c.ResponseError(err)
return
}
c.ResponseData(data)
}
// func (c *BusinessBonusController) GetBusinessBonus() {
// type Parameter struct {
// Id int64 `json:"id"`
// }
// var (
// param Parameter
// err error
// )
// if err = c.BindJsonData(&param); err != nil {
// logs.Error(err)
// c.ResponseError(errors.New("json数据解析失败"))
// return
// }
// companyId := c.GetUserCompany()
// srv := businessService.NewBusinessBonusService(nil)
// data, err := srv.GetBusinessBonus(businessQuery.GetBusinessBonusQuery{
// Id: param.Id,
// CompanyId: companyId,
// })
// if err != nil {
// c.ResponseError(err)
// return
// }
// c.ResponseData(data)
// }
... ...
... ... @@ -36,12 +36,20 @@ func (c *CommonController) GetPartnerList() {
}
resp := []map[string]interface{}{}
for i := range partners {
categorys := []map[string]interface{}{}
for _, vv := range partners[i].PartnerCategoryInfos {
c := map[string]interface{}{
"id": vv.Id,
"name": vv.Name,
}
categorys = append(categorys, c)
}
m := map[string]interface{}{
"id": partners[i].Partner.Id,
"account": partners[i].Partner.Account,
"partnerName": partners[i].Partner.PartnerName,
"categorys": categorys,
}
resp = append(resp, m)
}
c.ResponseData(resp)
... ...
... ... @@ -10,6 +10,7 @@ import (
orderQuery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/query"
orderService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/service"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib/exceltool"
)
//OrderDividendController 订单分红管理
... ... @@ -35,6 +36,7 @@ func (c *OrderDividendController) PageListOrderDividend() {
OrderType int `json:"orderType"`
PageSize int `json:"pageSize"`
PageNumber int `json:"pageNumber"`
PartnerCategoryId int `json:"partnerCategoryId"`
}
var (
param Parameter
... ... @@ -65,6 +67,7 @@ func (c *OrderDividendController) PageListOrderDividend() {
Limit: param.PageSize,
Offset: (param.PageNumber - 1) * param.PageSize,
CompanyId: companyId,
PartnerCategory: param.PartnerCategoryId,
})
if err != nil {
c.ResponseError(err)
... ... @@ -147,6 +150,8 @@ func (c *OrderDividendController) OrderDividendDetail() {
"partner": orderinfo.PartnerInfo.PartnerName,
"id": orderinfo.Id,
"orderId": orderinfo.OrderCode,
"partnerCategoryId": orderinfo.PartnerCategory.Id,
"partnerCategoryName": orderinfo.PartnerCategory.Name,
}
dividendCount := map[string]interface{}{
"orderNum": orderinfo.OrderCompute.PlanOrderCount,
... ... @@ -399,3 +404,55 @@ func (c *OrderDividendController) EditOrderRemarkBonusForBestshop() {
c.ResponseData(nil)
return
}
func (c *OrderDividendController) ListOrderBonusForExcel() {
type Parameter struct {
SearchWord string `json:"searchWord"`
OrderType int `json:"orderType"`
PageSize int `json:"pageSize"`
PageNumber int `json:"pageNumber"`
PartnerCategoryId int `json:"partnerCategoryId"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if !(param.OrderType == 0 ||
param.OrderType == domain.OrderReal ||
param.OrderType == domain.OrderTypeBestShop) {
c.ResponseError(errors.New("参数异常"))
return
}
companyId := c.GetUserCompany()
orderSrv := orderService.NewOrderInfoService(nil)
dataResult, column, err := orderSrv.ListOrderBonusForExcel(
orderQuery.ListOrderBonusQuery{
OrderType: param.OrderType,
PartnerOrCode: param.SearchWord,
CompanyId: companyId,
PartnerCategory: param.PartnerCategoryId,
})
if err != nil {
c.ResponseError(err)
return
}
var excelHeaders []exceltool.ExcelHead
for i := range column {
h := exceltool.ExcelHead{
Key: column[i][0],
Name: column[i][1],
}
excelHeaders = append(excelHeaders, h)
}
excelMaker := exceltool.NewExcelMaker()
excelMaker.SetListHead(excelHeaders)
excelMaker.MakeListExcel(dataResult)
c.ResponseExcelByFile(c.Ctx, excelMaker)
return
}
... ...
... ... @@ -33,140 +33,140 @@ func (c *OrderInfoController) Prepare() {
}
//PageListOrderPurpose 分页获取意向订单列表
func (c *OrderInfoController) PageListOrderPurpose() {
type Parameter struct {
SearchText string `json:"searchText"`
Partner int64 `json:"partner"`
PageSize int `json:"pageSize"`
PageNumber int `json:"pageNumber"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if param.PageNumber == 0 {
param.PageNumber = 1
}
if param.PageSize == 0 {
param.PageSize = 20
}
companyId := c.GetUserCompany()
orderSrv := orderService.NewOrderInfoService(nil)
orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
PartnerId: param.Partner,
OrderCode: param.SearchText,
OrderType: domain.OrderIntention,
Limit: param.PageSize,
Offset: (param.PageNumber - 1) * param.PageSize,
CompanyId: companyId,
})
if err != nil {
c.ResponseError(err)
return
}
rsp := []map[string]interface{}{}
for i := range orderinfos {
orderinfo := orderinfos[i]
m := map[string]interface{}{
"createTime": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
"updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
"buyer": orderinfo.Buyer.BuyerName,
"id": orderinfo.Id,
"orderId": orderinfo.OrderCode,
"partner": orderinfo.PartnerInfo.PartnerName,
"orderNum": orderinfo.OrderCompute.PlanOrderCount,
"orderPrice": orderinfo.OrderCompute.PlanOrderAmount,
"orderDist": orderinfo.RegionInfo.RegionName,
}
rsp = append(rsp, m)
}
c.ResponsePageList(rsp, cnt, param.PageNumber)
}
// func (c *OrderInfoController) PageListOrderPurpose() {
// type Parameter struct {
// SearchText string `json:"searchText"`
// Partner int64 `json:"partner"`
// PageSize int `json:"pageSize"`
// PageNumber int `json:"pageNumber"`
// }
// var (
// param Parameter
// err error
// )
// if err = c.BindJsonData(&param); err != nil {
// logs.Error(err)
// c.ResponseError(errors.New("json数据解析失败"))
// return
// }
// if param.PageNumber == 0 {
// param.PageNumber = 1
// }
// if param.PageSize == 0 {
// param.PageSize = 20
// }
// companyId := c.GetUserCompany()
// orderSrv := orderService.NewOrderInfoService(nil)
// orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
// PartnerId: param.Partner,
// OrderCode: param.SearchText,
// OrderType: domain.OrderIntention,
// Limit: param.PageSize,
// Offset: (param.PageNumber - 1) * param.PageSize,
// CompanyId: companyId,
// })
// if err != nil {
// c.ResponseError(err)
// return
// }
// rsp := []map[string]interface{}{}
// for i := range orderinfos {
// orderinfo := orderinfos[i]
// m := map[string]interface{}{
// "createTime": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
// "updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
// "buyer": orderinfo.Buyer.BuyerName,
// "id": orderinfo.Id,
// "orderId": orderinfo.OrderCode,
// "partner": orderinfo.PartnerInfo.PartnerName,
// "orderNum": orderinfo.OrderCompute.PlanOrderCount,
// "orderPrice": orderinfo.OrderCompute.PlanOrderAmount,
// "orderDist": orderinfo.RegionInfo.RegionName,
// }
// rsp = append(rsp, m)
// }
// c.ResponsePageList(rsp, cnt, param.PageNumber)
// }
//GetOrderPurpose 获取意向订单详情
func (c *OrderInfoController) GetOrderPurpose() {
type Parameter struct {
Id string `json:"id"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
orderid, _ := strconv.ParseInt(param.Id, 10, 64)
companyId := c.GetUserCompany()
orderSrv := orderService.NewOrderInfoService(nil)
orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
OrderId: orderid,
CompanyId: companyId,
})
if err != nil {
c.ResponseError(err)
return
}
if orderinfo.OrderType != domain.OrderIntention {
c.ResponseError(errors.New("参数错误"))
return
}
allGoods := []map[string]interface{}{}
for _, v := range orderinfo.Goods {
m := map[string]interface{}{
"id": v.Id,
"productName": v.GoodName,
"orderNum": v.PlanGoodNumber,
"univalence": v.Price,
"partnerRatio": v.PartnerBonusPercent,
"orderPrice": v.GoodCompute.PlanAmount,
}
allGoods = append(allGoods, m)
}
rsp := map[string]interface{}{
"buyer": orderinfo.Buyer.BuyerName,
"id": orderinfo.Id,
"partnerID": orderinfo.PartnerInfo.Id,
"partner": orderinfo.PartnerInfo.PartnerName,
"orderDist": orderinfo.RegionInfo.RegionName,
"orderId": orderinfo.OrderCode,
"product": allGoods,
"commissionProportion": orderinfo.SalesmanBonusPercent,
"orderNumCount": orderinfo.OrderCompute.PlanOrderCount,
"orderAmountAdjustmentCount": orderinfo.OrderCompute.PlanOrderAmount,
}
c.ResponseData(rsp)
}
// func (c *OrderInfoController) GetOrderPurpose() {
// type Parameter struct {
// Id string `json:"id"`
// }
// var (
// param Parameter
// err error
// )
// if err = c.BindJsonData(&param); err != nil {
// logs.Error(err)
// c.ResponseError(errors.New("json数据解析失败"))
// return
// }
// orderid, _ := strconv.ParseInt(param.Id, 10, 64)
// companyId := c.GetUserCompany()
// orderSrv := orderService.NewOrderInfoService(nil)
// orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
// OrderId: orderid,
// CompanyId: companyId,
// })
// if err != nil {
// c.ResponseError(err)
// return
// }
// if orderinfo.OrderType != domain.OrderIntention {
// c.ResponseError(errors.New("参数错误"))
// return
// }
// allGoods := []map[string]interface{}{}
// for _, v := range orderinfo.Goods {
// m := map[string]interface{}{
// "id": v.Id,
// "productName": v.GoodName,
// "orderNum": v.PlanGoodNumber,
// "univalence": v.Price,
// "partnerRatio": v.PartnerBonusPercent,
// "orderPrice": v.GoodCompute.PlanAmount,
// }
// allGoods = append(allGoods, m)
// }
// rsp := map[string]interface{}{
// "buyer": orderinfo.Buyer.BuyerName,
// "id": orderinfo.Id,
// "partnerID": orderinfo.PartnerInfo.Id,
// "partner": orderinfo.PartnerInfo.PartnerName,
// "orderDist": orderinfo.RegionInfo.RegionName,
// "orderId": orderinfo.OrderCode,
// "product": allGoods,
// "commissionProportion": orderinfo.SalesmanBonusPercent,
// "orderNumCount": orderinfo.OrderCompute.PlanOrderCount,
// "orderAmountAdjustmentCount": orderinfo.OrderCompute.PlanOrderAmount,
// }
// c.ResponseData(rsp)
// }
//RemoveOrderPurpose 删除意向订单
func (c *OrderInfoController) RemoveOrderPurpose() {
type Parameter struct {
Id int64 `json:"id"`
}
var (
param Parameter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
companyId := c.GetUserCompany()
orderSrv := orderService.NewOrderInfoService(nil)
err = orderSrv.DeleteOrder(param.Id, companyId)
if err != nil {
c.ResponseError(err)
return
}
c.ResponseData(nil)
}
// func (c *OrderInfoController) RemoveOrderPurpose() {
// type Parameter struct {
// Id int64 `json:"id"`
// }
// var (
// param Parameter
// err error
// )
// if err = c.BindJsonData(&param); err != nil {
// logs.Error(err)
// c.ResponseError(errors.New("json数据解析失败"))
// return
// }
// companyId := c.GetUserCompany()
// orderSrv := orderService.NewOrderInfoService(nil)
// err = orderSrv.DeleteOrder(param.Id, companyId)
// if err != nil {
// c.ResponseError(err)
// return
// }
// c.ResponseData(nil)
// }
//postPurposeOrderDetail 请求添加/更新的订单数据
type postPurposeOrderDetail struct {
... ... @@ -252,92 +252,92 @@ func (postData *postOrderGood) Valid() error {
return nil
}
//UpdateOrderPurpose 更新意向订单
func (c *OrderInfoController) UpdateOrderPurpose() {
//用与适配前端定义的数据结构
var (
param postPurposeOrderDetail
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if err := param.Valid(); err != nil {
c.ResponseError(err)
return
}
if param.Id == 0 {
err = c.addOrderPurpose(param)
} else {
err = c.editOrderPurpose(param)
}
if err != nil {
c.ResponseError(err)
}
c.ResponseData(nil)
return
}
func (c *OrderInfoController) addOrderPurpose(param postPurposeOrderDetail) error {
newGoods := []orderCmd.OrderGoodData{}
for _, v := range param.Product {
g := orderCmd.OrderGoodData{
GoodName: v.ProductName,
PlanGoodNumber: v.OrderNum,
Price: v.Univalence,
PartnerBonusPercent: v.PartnerRatio,
}
newGoods = append(newGoods, g)
}
companyId := c.GetUserCompany()
createcmd := orderCmd.CreateOrderCommand{
OrderType: domain.OrderIntention,
OrderCode: param.OrderId,
DeliveryCode: "",
BuyerName: param.BuyerName,
OrderRegion: param.OrderDist,
PartnerId: param.PartnerId,
SalesmanBonusPercent: param.CommissionProportion,
Goods: newGoods,
CompanyId: companyId,
}
orderSrv := orderService.NewOrderInfoService(nil)
_, err := orderSrv.CreateNewOrder(createcmd)
return err
}
func (c *OrderInfoController) editOrderPurpose(param postPurposeOrderDetail) error {
orderSrv := orderService.NewOrderInfoService(nil)
newGoods := []orderCmd.OrderGoodData{}
for _, v := range param.Product {
g := orderCmd.OrderGoodData{
GoodName: v.ProductName,
PlanGoodNumber: v.OrderNum,
Price: v.Univalence,
PartnerBonusPercent: v.PartnerRatio,
}
newGoods = append(newGoods, g)
}
companyId := c.GetUserCompany()
updatecmd := orderCmd.UpdateOrderCommand{
Id: param.Id,
OrderType: domain.OrderIntention,
OrderCode: param.OrderId,
DeliveryCode: "",
BuyerName: param.BuyerName,
OrderRegion: param.OrderDist,
PartnerId: param.PartnerId,
SalesmanBonusPercent: param.CommissionProportion,
Goods: newGoods,
CompanyId: companyId,
}
_, err := orderSrv.UpdateOrderData(updatecmd)
return err
}
// //UpdateOrderPurpose 更新意向订单
// func (c *OrderInfoController) UpdateOrderPurpose() {
// //用与适配前端定义的数据结构
// var (
// param postPurposeOrderDetail
// err error
// )
// if err = c.BindJsonData(&param); err != nil {
// logs.Error(err)
// c.ResponseError(errors.New("json数据解析失败"))
// return
// }
// if err := param.Valid(); err != nil {
// c.ResponseError(err)
// return
// }
// if param.Id == 0 {
// err = c.addOrderPurpose(param)
// } else {
// err = c.editOrderPurpose(param)
// }
// if err != nil {
// c.ResponseError(err)
// }
// c.ResponseData(nil)
// return
// }
// func (c *OrderInfoController) addOrderPurpose(param postPurposeOrderDetail) error {
// newGoods := []orderCmd.OrderGoodData{}
// for _, v := range param.Product {
// g := orderCmd.OrderGoodData{
// GoodName: v.ProductName,
// PlanGoodNumber: v.OrderNum,
// Price: v.Univalence,
// PartnerBonusPercent: v.PartnerRatio,
// }
// newGoods = append(newGoods, g)
// }
// companyId := c.GetUserCompany()
// createcmd := orderCmd.CreateOrderCommand{
// OrderType: domain.OrderIntention,
// OrderCode: param.OrderId,
// DeliveryCode: "",
// BuyerName: param.BuyerName,
// OrderRegion: param.OrderDist,
// PartnerId: param.PartnerId,
// SalesmanBonusPercent: param.CommissionProportion,
// Goods: newGoods,
// CompanyId: companyId,
// }
// orderSrv := orderService.NewOrderInfoService(nil)
// _, err := orderSrv.CreateNewOrder(createcmd)
// return err
// }
// func (c *OrderInfoController) editOrderPurpose(param postPurposeOrderDetail) error {
// orderSrv := orderService.NewOrderInfoService(nil)
// newGoods := []orderCmd.OrderGoodData{}
// for _, v := range param.Product {
// g := orderCmd.OrderGoodData{
// GoodName: v.ProductName,
// PlanGoodNumber: v.OrderNum,
// Price: v.Univalence,
// PartnerBonusPercent: v.PartnerRatio,
// }
// newGoods = append(newGoods, g)
// }
// companyId := c.GetUserCompany()
// updatecmd := orderCmd.UpdateOrderCommand{
// Id: param.Id,
// OrderType: domain.OrderIntention,
// OrderCode: param.OrderId,
// DeliveryCode: "",
// BuyerName: param.BuyerName,
// OrderRegion: param.OrderDist,
// PartnerId: param.PartnerId,
// SalesmanBonusPercent: param.CommissionProportion,
// Goods: newGoods,
// CompanyId: companyId,
// }
// _, err := orderSrv.UpdateOrderData(updatecmd)
// return err
// }
type postOrderPurposeDelivery struct {
ShipmentsId string `json:"shipmentsId"` //发货单号
... ... @@ -364,57 +364,58 @@ func (postData *postOrderPurposeDelivery) Valid() error {
}
//OrderPurposeDelivery 发货 意向订单转实发单
func (c *OrderInfoController) OrderPurposeDelivery() {
//用与适配前端定义的数据结构
var (
param postOrderPurposeDelivery
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
param.ShipmentsId = strings.TrimSpace(param.ShipmentsId)
orderid, _ := strconv.ParseInt(param.Id, 10, 64)
if orderid <= 0 {
c.ResponseError(errors.New("参数错误"))
return
}
if err = param.Valid(); err != nil {
c.ResponseError(err)
return
}
goods := []orderCmd.OrderGoodData{}
for _, v := range param.ProductDetail {
g := orderCmd.OrderGoodData{
Id: v.Id, GoodName: v.ProductName, PlanGoodNumber: v.OrderNum,
Price: v.Univalence, PartnerBonusPercent: v.PartnerRatio,
}
goods = append(goods, g)
}
companyId := c.GetUserCompany()
deliveryCommand := orderCmd.OrderDeliveryCommand{
OrderId: orderid, DeliveryCode: param.ShipmentsId,
DeliveryTime: time.Now(), Goods: goods, CompanyId: companyId,
}
orderSrv := orderService.NewOrderInfoService(nil)
err = orderSrv.Delivery(deliveryCommand)
if err != nil {
c.ResponseError(err)
}
c.ResponseData(nil)
return
}
// func (c *OrderInfoController) OrderPurposeDelivery() {
// //用与适配前端定义的数据结构
// var (
// param postOrderPurposeDelivery
// err error
// )
// if err = c.BindJsonData(&param); err != nil {
// logs.Error(err)
// c.ResponseError(errors.New("json数据解析失败"))
// return
// }
// param.ShipmentsId = strings.TrimSpace(param.ShipmentsId)
// orderid, _ := strconv.ParseInt(param.Id, 10, 64)
// if orderid <= 0 {
// c.ResponseError(errors.New("参数错误"))
// return
// }
// if err = param.Valid(); err != nil {
// c.ResponseError(err)
// return
// }
// goods := []orderCmd.OrderGoodData{}
// for _, v := range param.ProductDetail {
// g := orderCmd.OrderGoodData{
// Id: v.Id, GoodName: v.ProductName, PlanGoodNumber: v.OrderNum,
// Price: v.Univalence, PartnerBonusPercent: v.PartnerRatio,
// }
// goods = append(goods, g)
// }
// companyId := c.GetUserCompany()
// deliveryCommand := orderCmd.OrderDeliveryCommand{
// OrderId: orderid, DeliveryCode: param.ShipmentsId,
// DeliveryTime: time.Now(), Goods: goods, CompanyId: companyId,
// }
// orderSrv := orderService.NewOrderInfoService(nil)
// err = orderSrv.Delivery(deliveryCommand)
// if err != nil {
// c.ResponseError(err)
// }
// c.ResponseData(nil)
// return
// }
//PageListOrderReal 获取实发订单列表
func (c *OrderInfoController) PageListOrderReal() {
type Parameter struct {
SearchText string `json:"searchText"`
Partner int64 `json:"partner"`
PartnerCategory int `json:"PartnerCategory"`
PageSize int `json:"pageSize"`
PageNumber int `json:"pageNumber"`
UpdateTime []string `json:"updateTime"`
}
var (
param Parameter
... ... @@ -431,47 +432,49 @@ func (c *OrderInfoController) PageListOrderReal() {
if param.PageSize == 0 {
param.PageSize = 20
}
var (
updateTimeBegin string
updateTimeEnd string
)
if len(param.UpdateTime) > 0 {
if len(param.UpdateTime[0]) > 0 {
t, err := time.ParseInLocation("2006-01-02", param.UpdateTime[0], time.Local)
if err != nil {
c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误"))
return
}
updateTimeBegin = t.Format("2006-01-02 15:04:05-07")
}
}
if len(param.UpdateTime) > 1 {
if len(param.UpdateTime[1]) > 0 {
t, err := time.ParseInLocation("2006-01-02", param.UpdateTime[1], time.Local)
if err != nil {
c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误"))
return
}
//设定时间边界
t = t.Add(86399 * time.Second)
updateTimeEnd = t.Format("2006-01-02 15:04:05-07")
}
}
companyId := c.GetUserCompany()
orderSrv := orderService.NewOrderInfoService(nil)
orderinfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
PartnerId: param.Partner,
DeliveryCode: param.SearchText,
PartnerOrCode: param.SearchText,
OrderType: domain.OrderReal,
Limit: param.PageSize,
Offset: (param.PageNumber - 1) * param.PageSize,
CompanyId: companyId,
PartnerCategory: param.PartnerCategory,
UpdateTimeBegin: updateTimeBegin,
UpdateTimeEnd: updateTimeEnd,
})
if err != nil {
c.ResponseError(err)
return
}
rsp := []map[string]interface{}{}
for i := range orderinfos {
orderinfo := orderinfos[i]
m := map[string]interface{}{
"createTime": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
"updateTime": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
"buyer": orderinfo.Buyer.BuyerName,
"id": orderinfo.Id,
"orderId": orderinfo.OrderCode,
"shipmentsId": orderinfo.DeliveryCode,
"partner": orderinfo.PartnerInfo.PartnerName,
"orderNum": orderinfo.OrderCompute.PlanOrderCount,
"orderPrice": orderinfo.OrderCompute.PlanOrderAmount,
"orderDist": orderinfo.RegionInfo.RegionName,
"quantityControl": "",
"priceControl": "",
"status": orderinfo.IsDisable,
}
if orderinfo.OrderCompute.UseOrderCount >= 0 {
m["quantityControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
}
if orderinfo.OrderCompute.UseOrderAmount >= 0 {
m["priceControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
}
rsp = append(rsp, m)
}
c.ResponsePageList(rsp, cnt, param.PageNumber)
c.ResponsePageList(orderinfos, cnt, param.PageNumber)
return
}
... ... @@ -544,6 +547,8 @@ func (c *OrderInfoController) GetOrderReal() {
"product": allGoods,
"create_time": orderinfo.CreateTime.Local().Format("2006-01-02 15:04:06"),
"update_time": orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:06"),
"partnerCategoryId": orderinfo.PartnerCategory.Id,
"partnerCategoryName": orderinfo.PartnerCategory.Name,
}
if orderinfo.OrderCompute.UseOrderAmount >= 0 {
rsp["orderNumCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
... ... @@ -558,6 +563,7 @@ func (c *OrderInfoController) GetOrderReal() {
//实际订单
type postRealOrderDetail struct {
postPurposeOrderDetail
PartnerCategoryId int64 `json:"partnerCategoryId"`
ShipmentsId string `json:"shipmentsId"` //发货单号
}
... ... @@ -623,6 +629,7 @@ func (c *OrderInfoController) addOrderReal(param postRealOrderDetail) error {
SalesmanBonusPercent: param.CommissionProportion,
Goods: newGoods,
CompanyId: companyId,
PartnerCategory: param.PartnerCategoryId,
}
_, err := orderSrv.CreateNewOrder(createcmd)
return err
... ... @@ -652,6 +659,7 @@ func (c *OrderInfoController) editOrderReal(param postRealOrderDetail) error {
SalesmanBonusPercent: param.CommissionProportion,
Goods: newGoods,
CompanyId: companyId,
PartnerCategory: param.PartnerCategoryId,
}
orderSrv := orderService.NewOrderInfoService(nil)
_, err := orderSrv.UpdateOrderData(updatecmd)
... ...
... ... @@ -275,8 +275,10 @@ func (c *PartnerInfoController) ListPartnerInfo() {
return
}
resp := []map[string]interface{}{}
indexBegin := query.Offset
for i := range partners {
m := map[string]interface{}{
"index": indexBegin + (i + 1),
"id": partners[i].Partner.Id,
"account": partners[i].Partner.Account,
"partnerName": partners[i].Partner.PartnerName,
... ...
... ... @@ -33,17 +33,17 @@ func init() {
beego.NSRouter("/mini-program/modify", &controllers.OrderDividendController{}, "POST:EditOrderDividendForBestshop"),
beego.NSRouter("/mini-program/payDividends", &controllers.OrderDividendController{}, "POST:PayOrderGoodBonusForBestshop"),
beego.NSRouter("/mini-program/remarks", &controllers.OrderDividendController{}, "POST:EditOrderRemarkBonusForBestshop"),
beego.NSRouter("/business/detail", &controllers.BusinessBonusController{}, "POST:GetBusinessBonus"),
beego.NSRouter("/business/edit", &controllers.BusinessBonusController{}, "POST:UpdateBusinessBonus"),
beego.NSRouter("/business/list", &controllers.BusinessBonusController{}, "POST:ListBusinessBonus"),
beego.NSRouter("/list/excel", &controllers.OrderDividendController{}, "POST:ListOrderBonusForExcel"),
// beego.NSRouter("/business/detail", &controllers.BusinessBonusController{}, "POST:GetBusinessBonus"),
// beego.NSRouter("/business/edit", &controllers.BusinessBonusController{}, "POST:UpdateBusinessBonus"),
// beego.NSRouter("/business/list", &controllers.BusinessBonusController{}, "POST:ListBusinessBonus"),
),
beego.NSNamespace("/order",
beego.NSRouter("/purpose/list", &controllers.OrderInfoController{}, "POST:PageListOrderPurpose"),
beego.NSRouter("/purpose/update", &controllers.OrderInfoController{}, "POST:UpdateOrderPurpose"),
beego.NSRouter("/purpose/detail", &controllers.OrderInfoController{}, "POST:GetOrderPurpose"),
beego.NSRouter("/purpose/del", &controllers.OrderInfoController{}, "POST:RemoveOrderPurpose"),
beego.NSRouter("/purpose/sendout", &controllers.OrderInfoController{}, "POST:OrderPurposeDelivery"),
// beego.NSRouter("/purpose/list", &controllers.OrderInfoController{}, "POST:PageListOrderPurpose"),
// beego.NSRouter("/purpose/update", &controllers.OrderInfoController{}, "POST:UpdateOrderPurpose"),
// beego.NSRouter("/purpose/detail", &controllers.OrderInfoController{}, "POST:GetOrderPurpose"),
// beego.NSRouter("/purpose/del", &controllers.OrderInfoController{}, "POST:RemoveOrderPurpose"),
// beego.NSRouter("/purpose/sendout", &controllers.OrderInfoController{}, "POST:OrderPurposeDelivery"),
beego.NSRouter("/actual/list", &controllers.OrderInfoController{}, "POST:PageListOrderReal"),
beego.NSRouter("/actual/detail", &controllers.OrderInfoController{}, "POST:GetOrderReal"),
beego.NSRouter("/actual/del", &controllers.OrderInfoController{}, "POST:RemoveOrderReal"),
... ...
~$*.xlsx
test/Test*.xlsx
*.out
*.test
.idea
... ...
language: go
install:
- go get -d -t -v ./... && go build -v ./...
go:
- 1.11.x
- 1.12.x
- 1.13.x
- 1.14.x
- 1.15.x
os:
- linux
- osx
env:
jobs:
- GOARCH=amd64
- GOARCH=386
script:
- env GO111MODULE=on go vet ./...
- env GO111MODULE=on go test -v -race ./... -coverprofile=coverage.txt -covermode=atomic
after_success:
- bash <(curl -s https://codecov.io/bash)
... ...
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [xuri.me](https://xuri.me). The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct][version]
[homepage]: https://www.contributor-covenant.org
[version]: https://www.contributor-covenant.org/version/2/0/code_of_conduct
... ...
# Contributing to excelize
Want to hack on excelize? Awesome! This page contains information about reporting issues as well as some tips and
guidelines useful to experienced open source contributors. Finally, make sure
you read our [community guidelines](#community-guidelines) before you
start participating.
## Topics
* [Reporting Security Issues](#reporting-security-issues)
* [Design and Cleanup Proposals](#design-and-cleanup-proposals)
* [Reporting Issues](#reporting-other-issues)
* [Quick Contribution Tips and Guidelines](#quick-contribution-tips-and-guidelines)
* [Community Guidelines](#community-guidelines)
## Reporting security issues
The excelize maintainers take security seriously. If you discover a security
issue, please bring it to their attention right away!
Please **DO NOT** file a public issue, instead send your report privately to
[xuri.me](https://xuri.me).
Security reports are greatly appreciated and we will publicly thank you for it.
We currently do not offer a paid security bounty program, but are not
ruling it out in the future.
## Reporting other issues
A great way to contribute to the project is to send a detailed report when you
encounter an issue. We always appreciate a well-written, thorough bug report,
and will thank you for it!
Check that [our issue database](https://github.com/360EntSecGroup-Skylar/excelize/issues)
doesn't already include that problem or suggestion before submitting an issue.
If you find a match, you can use the "subscribe" button to get notified on
updates. Do *not* leave random "+1" or "I have this too" comments, as they
only clutter the discussion, and don't help resolving it. However, if you
have ways to reproduce the issue or have additional information that may help
resolving the issue, please leave a comment.
When reporting issues, always include the output of `go env`.
Also include the steps required to reproduce the problem if possible and
applicable. This information will help us review and fix your issue faster.
When sending lengthy log-files, consider posting them as a gist [https://gist.github.com](https://gist.github.com).
Don't forget to remove sensitive data from your logfiles before posting (you can
replace those parts with "REDACTED").
## Quick contribution tips and guidelines
This section gives the experienced contributor some tips and guidelines.
### Pull requests are always welcome
Not sure if that typo is worth a pull request? Found a bug and know how to fix
it? Do it! We will appreciate it. Any significant improvement should be
documented as [a GitHub issue](https://github.com/360EntSecGroup-Skylar/excelize/issues) before
anybody starts working on it.
We are always thrilled to receive pull requests. We do our best to process them
quickly. If your pull request is not accepted on the first try,
don't get discouraged!
### Design and cleanup proposals
You can propose new designs for existing excelize features. You can also design
entirely new features. We really appreciate contributors who want to refactor or
otherwise cleanup our project.
We try hard to keep excelize lean and focused. Excelize can't do everything for
everybody. This means that we might decide against incorporating a new feature.
However, there might be a way to implement that feature *on top of* excelize.
### Conventions
Fork the repository and make changes on your fork in a feature branch:
* If it's a bug fix branch, name it XXXX-something where XXXX is the number of
the issue.
* If it's a feature branch, create an enhancement issue to announce
your intentions, and name it XXXX-something where XXXX is the number of the
issue.
Submit unit tests for your changes. Go has a great test framework built in; use
it! Take a look at existing tests for inspiration. Run the full test on your branch before
submitting a pull request.
Update the documentation when creating or modifying features. Test your
documentation changes for clarity, concision, and correctness, as well as a
clean documentation build.
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
committing your changes. Most editors have plug-ins that do this automatically.
Pull request descriptions should be as clear as possible and include a reference
to all the issues that they address.
### Successful Changes
Before contributing large or high impact changes, make the effort to coordinate
with the maintainers of the project before submitting a pull request. This
prevents you from doing extra work that may or may not be merged.
Large PRs that are just submitted without any prior communication are unlikely
to be successful.
While pull requests are the methodology for submitting changes to code, changes
are much more likely to be accepted if they are accompanied by additional
engineering work. While we don't define this explicitly, most of these goals
are accomplished through communication of the design goals and subsequent
solutions. Often times, it helps to first state the problem before presenting
solutions.
Typically, the best methods of accomplishing this are to submit an issue,
stating the problem. This issue can include a problem statement and a
checklist with requirements. If solutions are proposed, alternatives should be
listed and eliminated. Even if the criteria for elimination of a solution is
frivolous, say so.
Larger changes typically work best with design documents. These are focused on
providing context to the design at the time the feature was conceived and can
inform future documentation contributions.
### Commit Messages
Commit messages must start with a capitalized and short summary
written in the imperative, followed by an optional, more detailed explanatory
text which is separated from the summary by an empty line.
Commit messages should follow best practices, including explaining the context
of the problem and how it was solved, including in caveats or follow up changes
required. They should tell the story of the change and provide readers
understanding of what led to it.
In practice, the best approach to maintaining a nice commit message is to
leverage a `git add -p` and `git commit --amend` to formulate a solid
changeset. This allows one to piece together a change, as information becomes
available.
If you squash a series of commits, don't just submit that. Re-write the commit
message, as if the series of commits was a single stroke of brilliance.
That said, there is no requirement to have a single commit for a PR, as long as
each commit tells the story. For example, if there is a feature that requires a
package, it might make sense to have the package in a separate commit then have
a subsequent commit that uses it.
Remember, you're telling part of the story with the commit message. Don't make
your chapter weird.
### Review
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Post
a comment after pushing. New commits show up in the pull request automatically,
but the reviewers are notified only when you comment.
Pull requests must be cleanly rebased on top of master without multiple branches
mixed into the PR.
**Git tip**: If your PR no longer merges cleanly, use `rebase master` in your
feature branch to update your pull request rather than `merge master`.
Before you make a pull request, squash your commits into logical units of work
using `git rebase -i` and `git push -f`. A logical unit of work is a consistent
set of patches that should be reviewed together: for example, upgrading the
version of a vendored dependency and taking advantage of its now available new
feature constitute two separate units of work. Implementing a new function and
calling it in another file constitute a single logical unit of work. The very
high majority of submissions should have a single commit, so if in doubt: squash
down to one.
After every commit, make sure the test passes. Include documentation
changes in the same pull request so that a revert would remove all traces of
the feature or fix.
Include an issue reference like `Closes #XXXX` or `Fixes #XXXX` in commits that
close an issue. Including references automatically closes the issue on a merge.
Please see the [Coding Style](#coding-style) for further guidelines.
### Merge approval
The excelize maintainers use LGTM (Looks Good To Me) in comments on the code review to
indicate acceptance.
### Sign your work
The sign-off is a simple line at the end of the explanation for the patch. Your
signature certifies that you wrote the patch or otherwise have the right to pass
it on as an open-source patch. The rules are pretty simple: if you can certify
the below (from [developercertificate.org](http://developercertificate.org/)):
```text
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
Then you just add a line to every git commit message:
```text
Signed-off-by: Ri Xu https://xuri.me
```
Use your real name (sorry, no pseudonyms or anonymous contributions.)
If you set your `user.name` and `user.email` git configs, you can sign your
commit automatically with `git commit -s`.
### How can I become a maintainer
First, all maintainers have 3 things
* They share responsibility in the project's success.
* They have made a long-term, recurring time investment to improve the project.
* They spend that time doing whatever needs to be done, not necessarily what
is the most interesting or fun.
Maintainers are often under-appreciated, because their work is harder to appreciate.
It's easy to appreciate a really cool and technically advanced feature. It's harder
to appreciate the absence of bugs, the slow but steady improvement in stability,
or the reliability of a release process. But those things distinguish a good
project from a great one.
Don't forget: being a maintainer is a time investment. Make sure you
will have time to make yourself available. You don't have to be a
maintainer to make a difference on the project!
If you want to become a meintainer, contact [xuri.me](https://xuri.me) and given a introduction of you.
## Community guidelines
We want to keep the community awesome, growing and collaborative. We need
your help to keep it that way. To help with this we've come up with some general
guidelines for the community as a whole:
* Be nice: Be courteous, respectful and polite to fellow community members:
no regional, racial, gender, or other abuse will be tolerated. We like
nice people way better than mean ones!
* Encourage diversity and participation: Make everyone in our community feel
welcome, regardless of their background and the extent of their
contributions, and do everything possible to encourage participation in
our community.
* Keep it legal: Basically, don't get us in trouble. Share only content that
you own, do not share private or sensitive information, and don't break
the law.
* Stay on topic: Make sure that you are posting to the correct channel and
avoid off-topic discussions. Remember when you update an issue or respond
to an email you are potentially sending to a large number of people. Please
consider this before you update. Also remember that nobody likes spam.
* Don't send email to the maintainers: There's no need to send email to the
maintainers to ask them to investigate an issue or to take a look at a
pull request. Instead of sending an email, GitHub mentions should be
used to ping maintainers to review a pull request, a proposal or an
issue.
### Guideline violations — 3 strikes method
The point of this section is not to find opportunities to punish people, but we
do need a fair way to deal with people who are making our community suck.
1. First occurrence: We'll give you a friendly, but public reminder that the
behavior is inappropriate according to our guidelines.
2. Second occurrence: We will send you a private message with a warning that
any additional violations will result in removal from the community.
3. Third occurrence: Depending on the violation, we may need to delete or ban
your account.
**Notes:**
* Obvious spammers are banned on first occurrence. If we don't do this, we'll
have spam all over the place.
* Violations are forgiven after 6 months of good behavior, and we won't hold a
grudge.
* People who commit minor infractions will get some education, rather than
hammering them in the 3 strikes process.
* The rules apply equally to everyone in the community, no matter how much
you've contributed.
* Extreme violations of a threatening, abusive, destructive or illegal nature
will be addressed immediately and are not subject to 3 strikes or forgiveness.
* Contact [xuri.me](https://xuri.me) to report abuse or appeal violations. In the case of
appeals, we know that mistakes happen, and we'll work with you to come up with a
fair solution if there has been a misunderstanding.
## Coding Style
Unless explicitly stated, we follow all coding guidelines from the Go
community. While some of these standards may seem arbitrary, they somehow seem
to result in a solid, consistent codebase.
It is possible that the code base does not currently comply with these
guidelines. We are not looking for a massive PR that fixes this, since that
goes against the spirit of the guidelines. All new contributions should make a
best effort to clean up and make the code base better than they left it.
Obviously, apply your best judgement. Remember, the goal here is to make the
code base easier for humans to navigate and understand. Always keep that in
mind when nudging others to comply.
The rules:
1. All code should be formatted with `gofmt -s`.
2. All code should pass the default levels of
[`golint`](https://github.com/golang/lint).
3. All code should follow the guidelines covered in [Effective
Go](http://golang.org/doc/effective_go.html) and [Go Code Review
Comments](https://github.com/golang/go/wiki/CodeReviewComments).
4. Comment the code. Tell us the why, the history and the context.
5. Document _all_ declarations and methods, even private ones. Declare
expectations, caveats and anything else that may be important. If a type
gets exported, having the comments already there will ensure it's ready.
6. Variable name length should be proportional to its context and no longer.
`noCommaALongVariableNameLikeThisIsNotMoreClearWhenASimpleCommentWouldDo`.
In practice, short methods will have short variable names and globals will
have longer names.
7. No underscores in package names. If you need a compound name, step back,
and re-examine why you need a compound name. If you still think you need a
compound name, lose the underscore.
8. No utils or helpers packages. If a function is not general enough to
warrant its own package, it has not been written generally enough to be a
part of a util package. Just leave it unexported and well-documented.
9. All tests should run with `go test` and outside tooling should not be
required. No, we don't need another unit testing framework. Assertion
packages are acceptable if they provide _real_ incremental value.
10. Even though we call these "rules" above, they are actually just
guidelines. Since you've read all the rules, you now know that.
If you are having trouble getting into the mood of idiomatic Go, we recommend
reading through [Effective Go](https://golang.org/doc/effective_go.html). The
[Go Blog](https://blog.golang.org) is also a great resource. Drinking the
kool-aid is a lot easier than going thirsty.
## Code Review Comments and Effective Go Guidelines
[CodeLingo](https://codelingo.io) automatically checks every pull request against the following guidelines from [Effective Go](https://golang.org/doc/effective_go.html) and [Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments).
### Package Comment
Every package should have a package comment, a block comment preceding the package clause.
For multi-file packages, the package comment only needs to be present in one file, and any one will do.
The package comment should introduce the package and provide information relevant to the package as a
whole. It will appear first on the godoc page and should set up the detailed documentation that follows.
### Single Method Interface Name
By convention, one-method interfaces are named by the method name plus an -er suffix
or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc.
There are a number of such names and it's productive to honor them and the function names they capture.
Read, Write, Close, Flush, String and so on have canonical signatures and meanings. To avoid confusion,
don't give your method one of those names unless it has the same signature and meaning. Conversely,
if your type implements a method with the same meaning as a method on a well-known type, give it the
same name and signature; call your string-converter method String not ToString.
### Avoid Annotations in Comments
Comments do not need extra formatting such as banners of stars. The generated output
may not even be presented in a fixed-width font, so don't depend on spacing for alignment—godoc,
like gofmt, takes care of that. The comments are uninterpreted plain text, so HTML and other
annotations such as _this_ will reproduce verbatim and should not be used. One adjustment godoc
does do is to display indented text in a fixed-width font, suitable for program snippets.
The package comment for the fmt package uses this to good effect.
### Comment First Word as Subject
Doc comments work best as complete sentences, which allow a wide variety of automated presentations.
The first sentence should be a one-sentence summary that starts with the name being declared.
### Good Package Name
It's helpful if everyone using the package can use the same name
to refer to its contents, which implies that the package name should
be good: short, concise, evocative. By convention, packages are
given lower case, single-word names; there should be no need for
underscores or mixedCaps. Err on the side of brevity, since everyone
using your package will be typing that name. And don't worry about
collisions a priori. The package name is only the default name for
imports; it need not be unique across all source code, and in the
rare case of a collision the importing package can choose a different
name to use locally. In any case, confusion is rare because the file
name in the import determines just which package is being used.
### Avoid Renaming Imports
Avoid renaming imports except to avoid a name collision; good package names
should not require renaming. In the event of collision, prefer to rename the
most local or project-specific import.
### Context as First Argument
Values of the context.Context type carry security credentials, tracing information,
deadlines, and cancellation signals across API and process boundaries. Go programs
pass Contexts explicitly along the entire function call chain from incoming RPCs
and HTTP requests to outgoing requests.
Most functions that use a Context should accept it as their first parameter.
### Do Not Discard Errors
Do not discard errors using _ variables. If a function returns an error,
check it to make sure the function succeeded. Handle the error, return it, or,
in truly exceptional situations, panic.
### Go Error Format
Error strings should not be capitalized (unless beginning with proper nouns
or acronyms) or end with punctuation, since they are usually printed following
other context. That is, use fmt.Errorf("something bad") not fmt.Errorf("Something bad"),
so that log.Printf("Reading %s: %v", filename, err) formats without a spurious
capital letter mid-message. This does not apply to logging, which is implicitly
line-oriented and not combined inside other messages.
### Use Crypto Rand
Do not use package math/rand to generate keys, even
throwaway ones. Unseeded, the generator is completely predictable.
Seeded with time.Nanoseconds(), there are just a few bits of entropy.
Instead, use crypto/rand's Reader, and if you need text, print to
hexadecimal or base64.
... ...
BSD 3-Clause License
Copyright (c) 2016-2020 The excelize Authors.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
... ...
# PR Details
<!--- Provide a general summary of your changes in the Title above -->
## Description
<!--- Describe your changes in detail -->
## Related Issue
<!--- This project only accepts pull requests related to open issues -->
<!--- If suggesting a new feature or change, please discuss it in an issue first -->
<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->
<!--- Please link to the issue here: -->
## Motivation and Context
<!--- Why is this change required? What problem does it solve? -->
## How Has This Been Tested
<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, and the tests you ran to -->
<!--- see how your change affects other areas of the code, etc. -->
## Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Docs change / refactoring / dependency upgrade
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
## Checklist
<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [ ] My code follows the code style of this project.
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have read the **CONTRIBUTING** document.
- [ ] I have added tests to cover my changes.
- [ ] All new and existing tests passed.
... ...
<p align="center"><img width="650" src="./excelize.svg" alt="Excelize logo"></p>
<p align="center">
<a href="https://travis-ci.org/360EntSecGroup-Skylar/excelize"><img src="https://travis-ci.org/360EntSecGroup-Skylar/excelize.svg?branch=master" alt="Build Status"></a>
<a href="https://codecov.io/gh/360EntSecGroup-Skylar/excelize"><img src="https://codecov.io/gh/360EntSecGroup-Skylar/excelize/branch/master/graph/badge.svg" alt="Code Coverage"></a>
<a href="https://goreportcard.com/report/github.com/360EntSecGroup-Skylar/excelize"><img src="https://goreportcard.com/badge/github.com/360EntSecGroup-Skylar/excelize" alt="Go Report Card"></a>
<a href="https://pkg.go.dev/github.com/360EntSecGroup-Skylar/excelize/v2?tab=doc"><img src="https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white" alt="go.dev"></a>
<a href="https://opensource.org/licenses/BSD-3-Clause"><img src="https://img.shields.io/badge/license-bsd-orange.svg" alt="Licenses"></a>
<a href="https://www.paypal.me/xuri"><img src="https://img.shields.io/badge/Donate-PayPal-green.svg" alt="Donate"></a>
</p>
# Excelize
## Introduction
Excelize is a library written in pure Go providing a set of functions that allow you to write to and read from XLSX / XLSM / XLTM files. Supports reading and writing spreadsheet documents generated by Microsoft Excel&trade; 2007 and later. Supports complex components by high compatibility, and provided streaming API for generating or reading data from a worksheet with huge amounts of data. This library needs Go version 1.10 or later. The full API docs can be seen using go's built-in documentation tool, or online at [go.dev](https://pkg.go.dev/github.com/360EntSecGroup-Skylar/excelize/v2?tab=doc) and [docs reference](https://xuri.me/excelize/).
## Basic Usage
### Installation
```bash
go get github.com/360EntSecGroup-Skylar/excelize
```
- If your package management with [Go Modules](https://blog.golang.org/using-go-modules), please install with following command.
```bash
go get github.com/360EntSecGroup-Skylar/excelize/v2
```
### Create spreadsheet
Here is a minimal example usage that will create spreadsheet file.
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f := excelize.NewFile()
// Create a new sheet.
index := f.NewSheet("Sheet2")
// Set value of a cell.
f.SetCellValue("Sheet2", "A2", "Hello world.")
f.SetCellValue("Sheet1", "B2", 100)
// Set active sheet of the workbook.
f.SetActiveSheet(index)
// Save xlsx file by the given path.
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
```
### Reading spreadsheet
The following constitutes the bare to read a spreadsheet document.
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Get value from cell by given worksheet name and axis.
cell, err := f.GetCellValue("Sheet1", "B2")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(cell)
// Get all the rows in the Sheet1.
rows, err := f.GetRows("Sheet1")
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "\t")
}
fmt.Println()
}
}
```
### Add chart to spreadsheet file
With Excelize chart generation and management is as easy as a few lines of code. You can build charts based off data in your worksheet or generate charts without any data in your worksheet at all.
<p align="center"><img width="650" src="./test/images/chart.png" alt="Excelize"></p>
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
f := excelize.NewFile()
for k, v := range categories {
f.SetCellValue("Sheet1", k, v)
}
for k, v := range values {
f.SetCellValue("Sheet1", k, v)
}
if err := f.AddChart("Sheet1", "E1", `{"type":"col3DClustered","series":[{"name":"Sheet1!$A$2","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$2:$D$2"},{"name":"Sheet1!$A$3","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$3:$D$3"},{"name":"Sheet1!$A$4","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$4:$D$4"}],"title":{"name":"Fruit 3D Clustered Column Chart"}}`); err != nil {
fmt.Println(err)
return
}
// Save xlsx file by the given path.
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
```
### Add picture to spreadsheet file
```go
package main
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Insert a picture.
if err := f.AddPicture("Sheet1", "A2", "image.png", ""); err != nil {
fmt.Println(err)
}
// Insert a picture to worksheet with scaling.
if err := f.AddPicture("Sheet1", "D2", "image.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`); err != nil {
fmt.Println(err)
}
// Insert a picture offset in the cell with printing support.
if err := f.AddPicture("Sheet1", "H2", "image.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`); err != nil {
fmt.Println(err)
}
// Save the xlsx file with the origin path.
if err = f.Save(); err != nil {
fmt.Println(err)
}
}
```
## Contributing
Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change. XML is compliant with [part 1 of the 5th edition of the ECMA-376 Standard for Office Open XML](http://www.ecma-international.org/publications/standards/Ecma-376.htm).
## Licenses
This program is under the terms of the BSD 3-Clause License. See [https://opensource.org/licenses/BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause).
The Excel logo is a trademark of [Microsoft Corporation](https://aka.ms/trademarks-usage). This artwork is an adaptation.
gopher.{ai,svg,png} was created by [Takuya Ueda](https://twitter.com/tenntenn). Licensed under the [Creative Commons 3.0 Attributions license](http://creativecommons.org/licenses/by/3.0/).
... ...
<p align="center"><img width="650" src="./excelize.svg" alt="Excelize logo"></p>
<p align="center">
<a href="https://travis-ci.org/360EntSecGroup-Skylar/excelize"><img src="https://travis-ci.org/360EntSecGroup-Skylar/excelize.svg?branch=master" alt="Build Status"></a>
<a href="https://codecov.io/gh/360EntSecGroup-Skylar/excelize"><img src="https://codecov.io/gh/360EntSecGroup-Skylar/excelize/branch/master/graph/badge.svg" alt="Code Coverage"></a>
<a href="https://goreportcard.com/report/github.com/360EntSecGroup-Skylar/excelize"><img src="https://goreportcard.com/badge/github.com/360EntSecGroup-Skylar/excelize" alt="Go Report Card"></a>
<a href="https://pkg.go.dev/github.com/360EntSecGroup-Skylar/excelize/v2?tab=doc"><img src="https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white" alt="go.dev"></a>
<a href="https://opensource.org/licenses/BSD-3-Clause"><img src="https://img.shields.io/badge/license-bsd-orange.svg" alt="Licenses"></a>
<a href="https://www.paypal.me/xuri"><img src="https://img.shields.io/badge/Donate-PayPal-green.svg" alt="Donate"></a>
</p>
# Excelize
## 简介
Excelize 是 Go 语言编写的用于操作 Office Excel 文档基础库,基于 ECMA-376,ISO/IEC 29500 国际标准。可以使用它来读取、写入由 Microsoft Excel&trade; 2007 及以上版本创建的电子表格文档。支持 XLSX / XLSM / XLTM 等多种文档格式,高度兼容带有样式、图片(表)、透视表、切片器等复杂组件的文档,并提供流式读写 API,用于处理包含大规模数据的工作簿。可应用于各类报表平台、云计算、边缘计算等系统。使用本类库要求使用的 Go 语言为 1.10 或更高版本,完整的 API 使用文档请访问 [go.dev](https://pkg.go.dev/github.com/360EntSecGroup-Skylar/excelize/v2?tab=doc) 或查看 [参考文档](https://xuri.me/excelize/)
## 快速上手
### 安装
```bash
go get github.com/360EntSecGroup-Skylar/excelize
```
- 如果您使用 [Go Modules](https://blog.golang.org/using-go-modules) 管理软件包,请使用下面的命令来安装最新版本。
```bash
go get github.com/360EntSecGroup-Skylar/excelize/v2
```
### 创建 Excel 文档
下面是一个创建 Excel 文档的简单例子:
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f := excelize.NewFile()
// 创建一个工作表
index := f.NewSheet("Sheet2")
// 设置单元格的值
f.SetCellValue("Sheet2", "A2", "Hello world.")
f.SetCellValue("Sheet1", "B2", 100)
// 设置工作簿的默认工作表
f.SetActiveSheet(index)
// 根据指定路径保存文件
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
```
### 读取 Excel 文档
下面是读取 Excel 文档的例子:
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// 获取工作表中指定单元格的值
cell, err := f.GetCellValue("Sheet1", "B2")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(cell)
// 获取 Sheet1 上所有单元格
rows, err := f.GetRows("Sheet1")
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "\t")
}
fmt.Println()
}
}
```
### 在 Excel 文档中创建图表
使用 Excelize 生成图表十分简单,仅需几行代码。您可以根据工作表中的已有数据构建图表,或向工作表中添加数据并创建图表。
<p align="center"><img width="650" src="./test/images/chart.png" alt="Excelize"></p>
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
f := excelize.NewFile()
for k, v := range categories {
f.SetCellValue("Sheet1", k, v)
}
for k, v := range values {
f.SetCellValue("Sheet1", k, v)
}
if err := f.AddChart("Sheet1", "E1", `{"type":"col3DClustered","series":[{"name":"Sheet1!$A$2","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$2:$D$2"},{"name":"Sheet1!$A$3","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$3:$D$3"},{"name":"Sheet1!$A$4","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$4:$D$4"}],"title":{"name":"Fruit 3D Clustered Column Chart"}}`); err != nil {
fmt.Println(err)
return
}
// 根据指定路径保存文件
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
```
### 向 Excel 文档中插入图片
```go
package main
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// 插入图片
if err := f.AddPicture("Sheet1", "A2", "image.png", ""); err != nil {
fmt.Println(err)
}
// 在工作表中插入图片,并设置图片的缩放比例
if err := f.AddPicture("Sheet1", "D2", "image.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`); err != nil {
fmt.Println(err)
}
// 在工作表中插入图片,并设置图片的打印属性
if err := f.AddPicture("Sheet1", "H2", "image.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`); err != nil {
fmt.Println(err)
}
// 保存文件
if err = f.Save(); err != nil {
fmt.Println(err)
}
}
```
## 社区合作
欢迎您为此项目贡献代码,提出建议或问题、修复 Bug 以及参与讨论对新功能的想法。 XML 符合标准: [part 1 of the 5th edition of the ECMA-376 Standard for Office Open XML](http://www.ecma-international.org/publications/standards/Ecma-376.htm)
## 开源许可
本项目遵循 BSD 3-Clause 开源许可协议,访问 [https://opensource.org/licenses/BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause) 查看许可协议文件。
Excel 徽标是 [Microsoft Corporation](https://aka.ms/trademarks-usage) 的商标,项目的图片是一种改编。
gopher.{ai,svg,png} 由 [Takuya Ueda](https://twitter.com/tenntenn) 创作,遵循 [Creative Commons 3.0 Attributions license](http://creativecommons.org/licenses/by/3.0/) 创作共用授权条款。
... ...
# Security Policy
## Supported Versions
We will dive into any security-related issue as long as your Excelize version is still supported by us. When reporting an issue, include as much information as possible, but no need to fill fancy forms or answer tedious questions. Just tell us what you found, how to reproduce it, and any concerns you have about it. We will respond as soon as possible and follow up with any missing information.
## Reporting a Vulnerability
Please e-mail us directly at `xuri.me@gmail.com` or use the security issue template on GitHub. In general, public disclosure is made after the issue has been fully identified and a patch is ready to be released. A security issue gets the highest priority assigned and a reply regarding the vulnerability is given within a typical 24 hours. Thank you!
... ...
// Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
// spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
// library needs Go version 1.10 or later.
package excelize
import (
"errors"
"strings"
)
type adjustDirection bool
const (
columns adjustDirection = false
rows adjustDirection = true
)
// adjustHelper provides a function to adjust rows and columns dimensions,
// hyperlinks, merged cells and auto filter when inserting or deleting rows or
// columns.
//
// sheet: Worksheet name that we're editing
// column: Index number of the column we're inserting/deleting before
// row: Index number of the row we're inserting/deleting before
// offset: Number of rows/column to insert/delete negative values indicate deletion
//
// TODO: adjustPageBreaks, adjustComments, adjustDataValidations, adjustProtectedCells
//
func (f *File) adjustHelper(sheet string, dir adjustDirection, num, offset int) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
if dir == rows {
f.adjustRowDimensions(xlsx, num, offset)
} else {
f.adjustColDimensions(xlsx, num, offset)
}
f.adjustHyperlinks(xlsx, sheet, dir, num, offset)
if err = f.adjustMergeCells(xlsx, dir, num, offset); err != nil {
return err
}
if err = f.adjustAutoFilter(xlsx, dir, num, offset); err != nil {
return err
}
if err = f.adjustCalcChain(dir, num, offset); err != nil {
return err
}
checkSheet(xlsx)
_ = checkRow(xlsx)
if xlsx.MergeCells != nil && len(xlsx.MergeCells.Cells) == 0 {
xlsx.MergeCells = nil
}
return nil
}
// adjustColDimensions provides a function to update column dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, col, offset int) {
for rowIdx := range xlsx.SheetData.Row {
for colIdx, v := range xlsx.SheetData.Row[rowIdx].C {
cellCol, cellRow, _ := CellNameToCoordinates(v.R)
if col <= cellCol {
if newCol := cellCol + offset; newCol > 0 {
xlsx.SheetData.Row[rowIdx].C[colIdx].R, _ = CoordinatesToCellName(newCol, cellRow)
}
}
}
}
}
// adjustRowDimensions provides a function to update row dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, row, offset int) {
for i := range xlsx.SheetData.Row {
r := &xlsx.SheetData.Row[i]
if newRow := r.R + offset; r.R >= row && newRow > 0 {
f.ajustSingleRowDimensions(r, newRow)
}
}
}
// ajustSingleRowDimensions provides a function to ajust single row dimensions.
func (f *File) ajustSingleRowDimensions(r *xlsxRow, num int) {
r.R = num
for i, col := range r.C {
colName, _, _ := SplitCellName(col.R)
r.C[i].R, _ = JoinCellName(colName, num)
}
}
// adjustHyperlinks provides a function to update hyperlinks when inserting or
// deleting rows or columns.
func (f *File) adjustHyperlinks(xlsx *xlsxWorksheet, sheet string, dir adjustDirection, num, offset int) {
// short path
if xlsx.Hyperlinks == nil || len(xlsx.Hyperlinks.Hyperlink) == 0 {
return
}
// order is important
if offset < 0 {
for i := len(xlsx.Hyperlinks.Hyperlink) - 1; i >= 0; i-- {
linkData := xlsx.Hyperlinks.Hyperlink[i]
colNum, rowNum, _ := CellNameToCoordinates(linkData.Ref)
if (dir == rows && num == rowNum) || (dir == columns && num == colNum) {
f.deleteSheetRelationships(sheet, linkData.RID)
if len(xlsx.Hyperlinks.Hyperlink) > 1 {
xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:i],
xlsx.Hyperlinks.Hyperlink[i+1:]...)
} else {
xlsx.Hyperlinks = nil
}
}
}
}
if xlsx.Hyperlinks == nil {
return
}
for i := range xlsx.Hyperlinks.Hyperlink {
link := &xlsx.Hyperlinks.Hyperlink[i] // get reference
colNum, rowNum, _ := CellNameToCoordinates(link.Ref)
if dir == rows {
if rowNum >= num {
link.Ref, _ = CoordinatesToCellName(colNum, rowNum+offset)
}
} else {
if colNum >= num {
link.Ref, _ = CoordinatesToCellName(colNum+offset, rowNum)
}
}
}
}
// adjustAutoFilter provides a function to update the auto filter when
// inserting or deleting rows or columns.
func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error {
if xlsx.AutoFilter == nil {
return nil
}
coordinates, err := f.areaRefToCoordinates(xlsx.AutoFilter.Ref)
if err != nil {
return err
}
x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
if (dir == rows && y1 == num && offset < 0) || (dir == columns && x1 == num && x2 == num) {
xlsx.AutoFilter = nil
for rowIdx := range xlsx.SheetData.Row {
rowData := &xlsx.SheetData.Row[rowIdx]
if rowData.R > y1 && rowData.R <= y2 {
rowData.Hidden = false
}
}
return nil
}
coordinates = f.adjustAutoFilterHelper(dir, coordinates, num, offset)
x1, y1, x2, y2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]
if xlsx.AutoFilter.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
return err
}
return nil
}
// adjustAutoFilterHelper provides a function for adjusting auto filter to
// compare and calculate cell axis by the given adjust direction, operation
// axis and offset.
func (f *File) adjustAutoFilterHelper(dir adjustDirection, coordinates []int, num, offset int) []int {
if dir == rows {
if coordinates[1] >= num {
coordinates[1] += offset
}
if coordinates[3] >= num {
coordinates[3] += offset
}
} else {
if coordinates[2] >= num {
coordinates[2] += offset
}
}
return coordinates
}
// areaRefToCoordinates provides a function to convert area reference to a
// pair of coordinates.
func (f *File) areaRefToCoordinates(ref string) ([]int, error) {
rng := strings.Split(ref, ":")
return areaRangeToCoordinates(rng[0], rng[1])
}
// areaRangeToCoordinates provides a function to convert cell range to a
// pair of coordinates.
func areaRangeToCoordinates(firstCell, lastCell string) ([]int, error) {
coordinates := make([]int, 4)
var err error
coordinates[0], coordinates[1], err = CellNameToCoordinates(firstCell)
if err != nil {
return coordinates, err
}
coordinates[2], coordinates[3], err = CellNameToCoordinates(lastCell)
return coordinates, err
}
// sortCoordinates provides a function to correct the coordinate area, such
// correct C1:B3 to B1:C3.
func sortCoordinates(coordinates []int) error {
if len(coordinates) != 4 {
return errors.New("coordinates length must be 4")
}
if coordinates[2] < coordinates[0] {
coordinates[2], coordinates[0] = coordinates[0], coordinates[2]
}
if coordinates[3] < coordinates[1] {
coordinates[3], coordinates[1] = coordinates[1], coordinates[3]
}
return nil
}
// coordinatesToAreaRef provides a function to convert a pair of coordinates
// to area reference.
func (f *File) coordinatesToAreaRef(coordinates []int) (string, error) {
if len(coordinates) != 4 {
return "", errors.New("coordinates length must be 4")
}
firstCell, err := CoordinatesToCellName(coordinates[0], coordinates[1])
if err != nil {
return "", err
}
lastCell, err := CoordinatesToCellName(coordinates[2], coordinates[3])
if err != nil {
return "", err
}
return firstCell + ":" + lastCell, err
}
// adjustMergeCells provides a function to update merged cells when inserting
// or deleting rows or columns.
func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error {
if xlsx.MergeCells == nil {
return nil
}
for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
areaData := xlsx.MergeCells.Cells[i]
coordinates, err := f.areaRefToCoordinates(areaData.Ref)
if err != nil {
return err
}
x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
if dir == rows {
if y1 == num && y2 == num && offset < 0 {
f.deleteMergeCell(xlsx, i)
i--
}
y1 = f.adjustMergeCellsHelper(y1, num, offset)
y2 = f.adjustMergeCellsHelper(y2, num, offset)
} else {
if x1 == num && x2 == num && offset < 0 {
f.deleteMergeCell(xlsx, i)
i--
}
x1 = f.adjustMergeCellsHelper(x1, num, offset)
x2 = f.adjustMergeCellsHelper(x2, num, offset)
}
if x1 == x2 && y1 == y2 {
f.deleteMergeCell(xlsx, i)
i--
}
if areaData.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
return err
}
}
return nil
}
// adjustMergeCellsHelper provides a function for adjusting merge cells to
// compare and calculate cell axis by the given pivot, operation axis and
// offset.
func (f *File) adjustMergeCellsHelper(pivot, num, offset int) int {
if pivot >= num {
pivot += offset
if pivot < 1 {
return 1
}
return pivot
}
return pivot
}
// deleteMergeCell provides a function to delete merged cell by given index.
func (f *File) deleteMergeCell(sheet *xlsxWorksheet, idx int) {
if len(sheet.MergeCells.Cells) > idx {
sheet.MergeCells.Cells = append(sheet.MergeCells.Cells[:idx], sheet.MergeCells.Cells[idx+1:]...)
sheet.MergeCells.Count = len(sheet.MergeCells.Cells)
}
}
// adjustCalcChain provides a function to update the calculation chain when
// inserting or deleting rows or columns.
func (f *File) adjustCalcChain(dir adjustDirection, num, offset int) error {
if f.CalcChain == nil {
return nil
}
for index, c := range f.CalcChain.C {
colNum, rowNum, err := CellNameToCoordinates(c.R)
if err != nil {
return err
}
if dir == rows && num <= rowNum {
if newRow := rowNum + offset; newRow > 0 {
f.CalcChain.C[index].R, _ = CoordinatesToCellName(colNum, newRow)
}
}
if dir == columns && num <= colNum {
if newCol := colNum + offset; newCol > 0 {
f.CalcChain.C[index].R, _ = CoordinatesToCellName(newCol, rowNum)
}
}
}
return nil
}
... ...