You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

934 lines
30 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package goods
import (
"fmt"
"io"
"os"
"path/filepath"
"recook/internal/back"
"recook/internal/dbc"
"recook/internal/model/freight"
"recook/internal/model/goods"
"recook/internal/model/manage"
"recook/internal/model/vend"
"recook/internal/static_path"
"recook/internal/v2/model/gys/enterprise"
strict "recook/internal/v2/model/http/goods"
goods3 "recook/internal/v2/model/recook/goods"
manage2 "recook/internal/v2/model/recook/manage"
"recook/tools"
"strconv"
"strings"
"time"
mysql2 "git.oa00.com/go/mysql"
"github.com/360EntSecGroup-Skylar/excelize/v2"
"gorm.io/gorm/clause"
"github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
)
type category struct {
First goods.Category `json:"first"`
Second goods.Category `json:"second"`
}
type goodsListResp struct {
ID uint `gorm:"column:id;primary_key" json:"id,omitempty"`
BrandID uint `gorm:"column:brand_id" json:"brandId,omitempty"`
BrandName string `json:"brandName"`
VendorID uint `gorm:"vendor_id" json:"vendorId"`
VendorName string `json:"vendorName"`
MainPhotoURL string `json:"mainPhotoUrl"`
GoodsName string `gorm:"column:goods_name" json:"goodsName,omitempty"`
Description string `gorm:"description" json:"description"`
FirstCategoryID uint `gorm:"column:first_category_id" json:"firstCategoryId"`
SecondCategoryID uint `gorm:"column:second_category_id" json:"secondCategoryId"`
CategoryName string `json:"categoryName"`
PublishStatus uint `gorm:"column:publish_status" json:"publish_status"`
PublishDesc string `json:"publishDesc"`
FreightID uint `gorm:"column:freight_id" json:"freightId"`
FreightName string `json:"freightName"`
SkuList []goods.Sku `json:"skuList"`
BomaoId int `json:"bomaoId"`
BomaoStatus int `json:"bomaoStatus"`
ThirdPartyId uint `json:"third_party_id"` //第三方id
CommissionRateList []float64 `json:"commission_rate_list"`
}
type queryListParam struct {
UserID uint `json:"userId"`
FirstCateID uint `json:"firstCateId"`
SecondCateID uint `json:"secondCateId"`
BrandID uint `json:"brandId"`
VendorID uint `json:"vendorId"`
Page uint `json:"page"`
Limit uint `json:"limit" validator:"required"`
Keyword string `json:"keyword"`
Type uint `json:"type"`
Sku string `json:"sku"`
BomaoStatus int `json:"bomaoStatus"`
ThirdPartyState uint `json:"third_party_state"` //接口拉取的产品1上架2下架
CommissionRateStart float64 `json:"commission_rate"` //传入的佣金最小值
CommissionRateEnd float64 `json:"commission_rate_end"` //传入的佣金最大值
IsSale bool `json:"is_sale"`
}
type export struct {
GoodsId string `json:"goods_id"`
GoodsName string `json:"goods_name"`
Category string `json:"category"`
Brand string `json:"brand"`
Vendor string `json:"vendor"`
SkuName string `json:"sku_name"`
SkuCode string `json:"sku_code"`
PurchasePrice decimal.Decimal `json:"purchase_price"`
DiscountPrice decimal.Decimal `json:"discount_price"`
Coupon decimal.Decimal `json:"coupon"`
CommissionRate decimal.Decimal `json:"commission_rate"`
Commission decimal.Decimal `json:"commission"`
Inventory int `json:"inventory"`
GoodsNum string `json:"goods_num"`
PublishStatus string `json:"publish_status"`
}
func QueryGoodsList(c *gin.Context) {
var p queryListParam
err := tools.Params(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
if p.CommissionRateStart < 0 || p.CommissionRateEnd >= 100 {
back.Fail(c, "传入的佣金区间有误")
return
}
//获取供应商
gys_token := c.Request.Header.Get("X-Recook-GYSToken")
gysId, _ := dbc.Rds.Get(gys_token).Result()
myGysId, _ := strconv.Atoi(gysId)
if myGysId > 0 {
p.VendorID = uint(myGysId)
}
var limit uint = 5
if p.Limit > 0 {
limit = p.Limit
}
where1 := "(1=1)"
if p.Keyword != "" {
//where1 = fmt.Sprintf("MATCH(goods_name) AGAINST ('%v')", p.Keyword)
where1 = "goods_name LIKE '%" + p.Keyword + "%'"
}
where2 := ""
if p.IsSale {
if p.Type == 1 {
where2 = "sale_publish = 1"
} else if p.Type == 2 {
where2 = "sale_publish = 0"
}
} else {
if p.Type == 1 {
where2 = "publish_status = 1"
} else if p.Type == 2 {
where2 = "publish_status = 0"
}
}
where3 := ""
if len(p.Sku) > 0 {
var skuInfo goods.Sku
dbc.DB.First(&skuInfo, "code = ?", p.Sku)
if skuInfo.GoodsID == 0 {
where3 = "id = 0"
} else {
where3 = "id = " + string(strconv.Itoa(int(skuInfo.GoodsID)))
}
}
where4 := ""
//0表示全部1下架2上架
if p.BomaoStatus == 0 {
} else if p.BomaoStatus == 1 {
where4 = "bomao_status=0 and bomao_id>0 and brand_id not in (1,2,6,12)"
} else if p.BomaoStatus == 2 {
where4 = "bomao_status=1 and bomao_id>0 and brand_id not in (1,2,6,12)"
}
// 采购根据权限获取商品
var userId = c.MustGet("Manager_ID").(uint)
var user manage.UserInfo
user.ID = userId
if err = dbc.DB.Find(&user).Error; err != nil {
back.Fail(c, "数据错误:"+err.Error())
return
}
if user.RoleID == 92 {
where1 += " and first_category_id In(" + user.GoodsType + ")"
}
recookManageRoleModel := &manage2.RecookManageRoleModel{}
roleInfo := recookManageRoleModel.FindById(uint(user.NewroleId))
categoryIdsStr := ""
if roleInfo.ParentId > 0 && roleInfo.DataAuth == manage2.RecookManageRoleDataAuthOn {
recookManageRoleCategoryModel := &manage2.RecookManageRoleCategoryModel{}
roleMenus := recookManageRoleCategoryModel.FindByRoleId(uint(user.NewroleId))
for _, menu := range roleMenus {
categoryIdsStr += fmt.Sprintf(",%d", menu.CategoryId)
}
}
if categoryIdsStr != "" {
where1 += " and first_category_id In(" + categoryIdsStr[1:] + ")"
}
/*
根据要求,新增回显第三方供应商的上下架状态,和佣金率
*/
//新增内容开始
where5 := ""
if p.ThirdPartyState == 1 {
//上架中
where5 += "third_party_id>0 and publish_status=1"
} else if p.ThirdPartyState == 2 {
where5 += "third_party_id>0 and publish_status=0"
}
where6 := ""
if p.CommissionRateStart > 0 && p.CommissionRateEnd > 0 {
fmt.Println(p.CommissionRateStart, p.CommissionRateEnd)
n1 := p.CommissionRateStart / 100.0
n2 := p.CommissionRateEnd / 100.0
fmt.Println("******", n1, n2)
var gl []uint
var sk goods.Sku
dbc.DB.Table(sk.TableName()).Where("commission_rate between ? and ? ", n1, n2).Pluck("goods_id", &gl)
str := ""
for _, v := range gl {
str += fmt.Sprintf(",%d", v)
}
if str != "" {
where6 += "id in (" + str[1:] + ")"
}
}
where7 := dbc.DB
//新增内容结束
if p.IsSale {
where7 = dbc.DB.Where("is_sale=?", p.IsSale)
}
var total uint
var goodsList []goods.Information
dbc.DB.Table((&goods.Information{}).TableName()).
Where(where1).Where(where2).Where(where3).Where(where4).Where(where5).Where(where6).Where(where7).Where(goods.Information{
BrandID: p.BrandID,
VendorID: p.VendorID,
FirstCategoryID: p.FirstCateID,
SecondCategoryID: p.SecondCateID,
}).Count(&total)
dbc.DB.Limit(limit).Offset(limit*p.Page).Where("is_sale=?", p.IsSale).
Where(where1).Where(where2).Where(where3).Where(where4).Where(where5).Where(where6).Where(where7).Find(&goodsList, goods.Information{
BrandID: p.BrandID,
VendorID: p.VendorID,
FirstCategoryID: p.FirstCateID,
SecondCategoryID: p.SecondCateID,
})
list := make([]goodsListResp, 0, 0)
for _, goodsInfo := range goodsList {
var photo goods.MainPhoto
dbc.DB.Select("url").First(&photo, "goods_id = ? AND is_master = 1", goodsInfo.ID)
var brandInfo goods.Brand
dbc.DB.Select("name").First(&brandInfo, goodsInfo.BrandID)
var freightInfo freight.Information
dbc.DB.First(&freightInfo, goodsInfo.FreightID)
var firCate goods.Category
dbc.DB.Select("name").First(&firCate, goodsInfo.FirstCategoryID)
var secCate goods.Category
dbc.DB.Select("name").First(&secCate, goodsInfo.SecondCategoryID)
var skuList []goods.Sku
dbc.DB.Find(&skuList, "goods_id = ?", goodsInfo.ID)
var comL []float64
dbc.DB.Table((&goods.Sku{}).TableName()).Where("goods_id=?", goodsInfo.ID).Pluck("commission_rate", &comL)
vendorName := "自营"
if goodsInfo.VendorID > 0 {
var vendor vend.Information
dbc.DB.First(&vendor, goodsInfo.VendorID)
vendorName = vendor.Username
}
publishDesc := "上架中"
if goodsInfo.PublishStatus == 0 {
publishDesc = "仓库"
}
tempStatus := 0
if goodsInfo.BoMaoStatus == 1 {
tempStatus = 2
} else {
tempStatus = 1
}
list = append(list, goodsListResp{
ID: goodsInfo.ID,
BrandID: goodsInfo.BrandID,
BrandName: brandInfo.Name,
VendorID: goodsInfo.VendorID,
VendorName: vendorName,
MainPhotoURL: photo.URL,
GoodsName: goodsInfo.GoodsName,
Description: goodsInfo.Description,
FirstCategoryID: goodsInfo.FirstCategoryID,
SecondCategoryID: goodsInfo.SecondCategoryID,
CategoryName: firCate.Name + "/" + secCate.Name,
PublishStatus: goodsInfo.PublishStatus,
PublishDesc: publishDesc,
FreightID: goodsInfo.FreightID,
FreightName: freightInfo.Name,
SkuList: skuList,
BomaoId: goodsInfo.BoMaoId,
BomaoStatus: tempStatus,
ThirdPartyId: goodsInfo.ThirdPartyId,
CommissionRateList: comL,
})
}
back.Suc(c, "操作成功", gin.H{
"total": total,
"list": list,
})
}
/*仓库中的数量*/
func QueryGoodsCount(c *gin.Context) {
// 采购根据权限获取商品数量
auto := "1=1"
var userId = c.MustGet("Manager_ID").(uint)
var user manage.UserInfo
user.ID = userId
if err := dbc.DB.Find(&user).Error; err != nil {
back.Fail(c, "数据错误:"+err.Error())
return
}
if user.RoleID == 92 {
auto += " and first_category_id In(" + user.GoodsType + ")"
}
//获取供应商
gys_token := c.Request.Header.Get("X-Recook-GYSToken")
gysId, _ := dbc.Rds.Get(gys_token).Result()
myGysId, _ := strconv.Atoi(gysId)
if myGysId > 0 {
auto += " and vendor_id=" + strconv.Itoa(myGysId)
}
var total uint
dbc.DB.Table((&goods.Information{}).TableName()).Where(auto).Count(&total)
var publishCount uint
dbc.DB.Table((&goods.Information{}).TableName()).Where(auto).Where("publish_status = 1").Count(&publishCount)
back.Suc(c, "操作成功", gin.H{
"total": total,
"publishCount": publishCount,
"NoPublishCount": total - publishCount,
})
}
type queryDetailParam struct {
GoodsID uint `json:"goodsID" validate:"required"`
}
type skus struct {
goods.Sku
OccupyInventory uint `json:"occupyInventory"`
}
type detailResponse struct {
goods.Information
BrandName string `json:"brandName"`
CategoryName string `json:"categoryName"`
VendorName string `json:"vendorName"`
FreightName string `json:"freightName"`
PublishDesc string `json:"publishDesc"`
MomentCopyCnt uint `json:"momentCopyCnt"`
PromotionPhoto *goods.PromotionPhoto `json:"promotionPhoto"`
Category category `json:"category"`
Brand goods.Brand `json:"brand"`
Video *goods.Video `json:"video"`
MainPhotos []goods.MainPhoto `gorm:"column:mainPhotos" json:"mainPhotos"`
DetailPhotos []goods.DetailPhoto `gorm:"column:detailPhotos" json:"detailPhotos"`
Attributes []goods.Attribute `gorm:"column:attributes" json:"attributes"`
Sku []skus `gorm:"column:sku" json:"sku"`
}
type gysDetailResponse struct {
vend.GysGoodsInfo
BrandName string `json:"brandName"`
CategoryName string `json:"categoryName"`
FreightName string `json:"freightName"`
PublishDesc string `json:"publishDesc"`
PromotionPhoto *vend.GysGoodsPromotionPhoto `json:"promotionPhoto"`
Category category `json:"category"`
BrandReally vend.GysEnterpriseBrand `json:"brandReally"`
FreightReally freight.Information `json:"freightReally"`
Video *vend.GysGoodsVideo `json:"video"`
MainPhotos []vend.GysGoodsMainPhoto `gorm:"column:mainPhotos" json:"mainPhotos"`
DetailPhotos []vend.GysGoodsDetailPhoto `gorm:"column:detailPhotos" json:"detailPhotos"`
Attributes []vend.GysAttribute `gorm:"column:attributes" json:"attributes"`
Sku []vend.GysGoodsSku `gorm:"column:sku" json:"sku"`
}
type totalSkuQuantity struct {
SkuId uint `gorm:"column:sku_id"`
TotalQuantity uint `gorm:"column:totalQuantity"`
}
/*
详情
*/
func QueryGoodsDetail(c *gin.Context) {
var p queryDetailParam
err := tools.Params(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
var summary detailResponse
dbc.DB.Table((&goods.Information{}).TableName()).First(&summary, "id = ?", p.GoodsID)
var video goods.Video
dbc.DB.First(&(video), "goods_id = ?", p.GoodsID)
if video.ID > 0 {
summary.Video = &video
}
var photo goods.PromotionPhoto
dbc.DB.First(&(photo), "goods_id = ?", p.GoodsID)
if photo.ID > 0 {
summary.PromotionPhoto = &photo
}
dbc.DB.Table((&goods.MomentsCopy{}).TableName()).Where("goods_id = ?", p.GoodsID).Count(&summary.MomentCopyCnt)
dbc.DB.Table((&goods.Brand{}).TableName()).First(&(summary.Brand), "id = ?", summary.Information.BrandID)
dbc.DB.Table((&goods.Category{}).TableName()).First(&(summary.Category.First), "id = ?", summary.Information.FirstCategoryID)
dbc.DB.Table((&goods.Category{}).TableName()).First(&(summary.Category.Second), "id = ?", summary.Information.SecondCategoryID)
dbc.DB.Table((&goods.MainPhoto{}).TableName()).Order("order_no asc, is_master desc").Find(&(summary.MainPhotos), "goods_id = ?", p.GoodsID)
dbc.DB.Table((&goods.DetailPhoto{}).TableName()).Order("order_no asc").Find(&summary.DetailPhotos, "goods_id = ?", p.GoodsID)
dbc.DB.Table((&goods.Sku{}).TableName()).Find(&(summary.Sku), "goods_id = ?", p.GoodsID)
dbc.DB.Table((&goods.Attribute{}).TableName()).Find(&(summary.Attributes), "goods_id = ?", p.GoodsID)
// 占用库存处理
var skuIds []uint
for _, item := range summary.Sku {
skuIds = append(skuIds, item.ID)
}
var totalSkuQuantitys []totalSkuQuantity
// 联合统计
dbc.DB.Table("recook_order_info").Joins("join recook_order_goods_detail on recook_order_info.id = order_id").
Select("sku_id,sum(quantity) totalQuantity").
Where("recook_order_info.status = ? and sku_id in (?)", 0, skuIds).
Group("sku_id").
Find(&totalSkuQuantitys)
quantityMap := map[uint]totalSkuQuantity{}
for _, item := range totalSkuQuantitys {
quantityMap[item.SkuId] = item
}
for key, item := range summary.Sku {
summary.Sku[key].OccupyInventory = quantityMap[item.ID].TotalQuantity
}
var brandInfo goods.Brand
dbc.DB.Select("name").First(&brandInfo, summary.BrandID)
var freightInfo freight.Information
dbc.DB.Select("name").First(&freightInfo, summary.FreightID)
var firCate goods.Category
dbc.DB.Select("name").First(&firCate, summary.FirstCategoryID)
var secCate goods.Category
dbc.DB.Select("name").First(&secCate, summary.SecondCategoryID)
summary.BrandName = brandInfo.Name
summary.FreightName = freightInfo.Name
summary.CategoryName = firCate.Name + "/" + secCate.Name
vendorName := "自营"
if summary.VendorID > 0 {
var userID []uint
dbc.DB.Table("gys_users AS u1").
Select("IF(u1.main_id = 0, u1.id, u2.id) AS id").
Joins("LEFT JOIN gys_users AS u2 ON u1.main_id = u2.id WHERE u1.id = ?", summary.VendorID).
Pluck("id", &userID)
if len(userID) == 0 {
var vendor vend.Information
dbc.DB.First(&vendor, summary.VendorID)
vendorName = vendor.Name
} else {
var ve vend.GysEnterpriseState
dbc.DB.First(&ve, "user_id = ?", userID[0])
vendorName = ve.EnterpriseName
}
}
summary.VendorName = vendorName
publishDesc := "上架中"
if summary.PublishStatus == 0 {
publishDesc = "仓库"
}
summary.PublishDesc = publishDesc
back.Suc(c, "操作成功", &summary)
}
//新品提报
type GysQueryGoodsDetailPem struct {
GoodsID uint `json:"goods_id"`
}
/*
详情
*/
func GysQueryGoodsDetail(c *gin.Context) {
var p GysQueryGoodsDetailPem
err := tools.Params(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
var summary gysDetailResponse
dbc.DB.Table((&vend.GysGoodsInfo{}).TableName()).First(&summary, "id = ?", p.GoodsID)
var video vend.GysGoodsVideo
dbc.DB.First(&(video), "goods_id = ?", p.GoodsID)
if video.ID > 0 {
summary.Video = &video
}
var photo vend.GysGoodsPromotionPhoto
dbc.DB.First(&(photo), "goods_id = ?", p.GoodsID)
if photo.ID > 0 {
summary.PromotionPhoto = &photo
}
dbc.DB.Table((&vend.GysEnterpriseBrand{}).TableName()).First(&(summary.Brand), "id = ?", summary.GysGoodsInfo.Brand)
dbc.DB.Table((&goods.Category{}).TableName()).First(&(summary.Category.First), "id = ?", summary.GysGoodsInfo.FirstCategoryId)
dbc.DB.Table((&goods.Category{}).TableName()).First(&(summary.Category.Second), "id = ?", summary.GysGoodsInfo.SecondCategoryId)
dbc.DB.Table((&vend.GysGoodsMainPhoto{}).TableName()).Order("order_no asc, is_master desc").Find(&(summary.MainPhotos), "goods_id = ?", p.GoodsID)
dbc.DB.Table((&vend.GysGoodsDetailPhoto{}).TableName()).Order("order_no asc").Find(&summary.DetailPhotos, "goods_id = ?", p.GoodsID)
dbc.DB.Table((&vend.GysGoodsSku{}).TableName()).Find(&(summary.Sku), "goods_id = ?", p.GoodsID)
dbc.DB.Table((&vend.GysAttribute{}).TableName()).Find(&(summary.Attributes), "goods_id = ?", p.GoodsID)
var brandInfo vend.GysEnterpriseBrand
dbc.DB.First(&brandInfo, summary.Brand)
var freightInfo freight.Information
dbc.DB.First(&freightInfo, summary.Freight)
var firCate goods.Category
dbc.DB.First(&firCate, summary.FirstCategoryId)
var secCate goods.Category
dbc.DB.First(&secCate, summary.SecondCategoryId)
summary.BrandName = brandInfo.Name
summary.FreightName = freightInfo.Name
summary.CategoryName = firCate.Name + "/" + secCate.Name
summary.BrandReally = brandInfo
summary.FreightReally = freightInfo
publishDesc := GetGoodsStatus(summary.PublishStatus)
summary.PublishDesc = publishDesc
back.Suc(c, "操作成功", &summary)
}
func ExportSku(c *gin.Context) {
args := strict.ArgsRecookGoodsList{}
if err := tools.Params(&args, c); err != nil {
back.Fail(c, err.Error())
return
}
exportRes := goodsList(&args)
fmt.Println(len(exportRes))
//var exportRes []export
name := "sku.xlsx"
nameTemp := time.Now().Format("20060102-150405") + tools.GenerateGoodsHashSign() + ".xlsx"
baseUrl := filepath.Join(static_path.Dir.Root, static_path.Dir.Excel, name)
tempUrl := filepath.Join(static_path.Dir.Root, static_path.Dir.Temp, nameTemp)
tempExport := filepath.Join(static_path.Dir.Static, static_path.Dir.Temp, nameTemp)
//dbc.DB.Raw(`SELECT
// goods_id,
// goods_name,
// CONCAT((
// SELECT NAME
// FROM
// recook_goods_category AS cat
// WHERE
// cat.id = info.first_category_id
// ),
// "/",(
// SELECT NAME
// FROM
// recook_goods_category AS cat
// WHERE
// cat.id = info.second_category_id
// )) AS "category",
// (
// SELECT NAME
// FROM
// recook_goods_brand AS brand
// WHERE
// info.brand_id = brand.id
// ) AS "brand",
// (
// SELECT
// ge.enterprise_name
// FROM
// gys_users AS users LEFT JOIN gys_enterprise_state as ge ON users.id = ge.user_id
// WHERE
// users.id = info.vendor_id
// ) AS "vendor",
// sku.NAME AS "sku_name",
// sku.CODE AS "sku_code",
// sku.purchase_price AS "purchase_price",
// sku.discount_price AS "discount_price",
// sku.coupon AS "coupon",
// sku.commission_rate AS "commission_rate",
// sku.commission AS "commission",
// sku.inventory AS "inventory",
// sku.goods_num As "goods_num",
// IF(info.publish_status=0,"仓库中","已上架") as publish_status
//FROM
// recook_goods_info AS info
// LEFT JOIN recook_goods_sku AS sku ON info.id = sku.goods_id`).Scan(&exportRes)
//
//fmt.Println(len(exportRes))
//权限过滤
var userId = c.MustGet("Manager_ID").(uint)
var user manage.UserInfo
var categorys []goods.Category
user.ID = userId
if err := dbc.DB.Find(&user).Error; err != nil {
back.Fail(c, "数据错误:"+err.Error())
return
}
if user.RoleID == 92 {
categoryIDSArr := strings.Split(user.GoodsType, ",")
//根据Category_id获取对应brand名
var exportResAuto []export
dbc.DB.Find(&categorys, "category_id in (?)", categoryIDSArr)
for _, exp := range exportRes {
for _, cat := range categorys {
if exp.Category == cat.Name {
exportResAuto = append(exportResAuto, exp)
break
}
}
}
exportRes = exportResAuto
}
f, err := createExcelSku(exportRes, baseUrl, tempUrl)
if err != nil {
back.Err(c, err.Error())
return
}
f.Save()
back.Suc(c, "", gin.H{
"path": tempExport,
})
}
func createExcelSku(rows []export, baseUrl, tempUrl string) (*excelize.File, error) {
const BUFFERSIZE = 1024
SheetName := "Sheet1"
baseFile, err := os.Open(baseUrl)
if err != nil {
return nil, err
}
tempFile, err := os.Create(tempUrl)
if err != nil {
return nil, err
}
buf := make([]byte, BUFFERSIZE)
for {
n, err := baseFile.Read(buf)
if err != nil && err != io.EOF {
return nil, err
}
if n == 0 {
break
}
if _, err := tempFile.Write(buf[:n]); err != nil {
return nil, err
}
}
f, err := excelize.OpenFile(tempUrl)
pointLine := 2
for _, r := range rows {
PurchasePrice, _ := r.PurchasePrice.Float64()
DiscountPrice, _ := r.DiscountPrice.Float64()
Coupon, _ := r.Coupon.Float64()
CommissionRate, _ := r.CommissionRate.Float64()
Commission, _ := r.Commission.Float64()
_ = f.SetRowHeight(SheetName, pointLine, 21) // 设置行高度
_ = f.SetCellValue(SheetName, axis("A", pointLine), r.GoodsId)
_ = f.SetCellValue(SheetName, axis("B", pointLine), r.GoodsName)
_ = f.SetCellValue(SheetName, axis("C", pointLine), r.Category)
_ = f.SetCellValue(SheetName, axis("D", pointLine), r.Brand)
_ = f.SetCellValue(SheetName, axis("E", pointLine), r.Vendor)
_ = f.SetCellValue(SheetName, axis("F", pointLine), r.SkuName)
_ = f.SetCellValue(SheetName, axis("G", pointLine), r.SkuCode)
_ = f.SetCellValue(SheetName, axis("H", pointLine), PurchasePrice)
_ = f.SetCellValue(SheetName, axis("I", pointLine), DiscountPrice)
_ = f.SetCellValue(SheetName, axis("J", pointLine), Coupon)
_ = f.SetCellValue(SheetName, axis("K", pointLine), CommissionRate)
_ = f.SetCellValue(SheetName, axis("L", pointLine), Commission)
_ = f.SetCellValue(SheetName, axis("M", pointLine), r.Inventory)
_ = f.SetCellValue(SheetName, axis("N", pointLine), r.GoodsNum)
_ = f.SetCellValue(SheetName, axis("O", pointLine), r.PublishStatus)
pointLine++
}
index := f.GetSheetIndex("Sheet1")
f.SetActiveSheet(index)
return f, nil
}
func axis(letter string, line int) string {
return fmt.Sprintf("%v%d", letter, line)
}
func goodsList(args *strict.ArgsRecookGoodsList) []export {
var rg goods3.RecookGoodsInfoModel
query := "1=1 "
if args.IsSale {
query += fmt.Sprintf("and a.is_sale=1 ")
}
if args.GoodsID != 0 {
query += fmt.Sprintf("and a.id=%v ", args.GoodsID)
}
if args.GoodsName != "" {
query += fmt.Sprintf("and a.goods_name like ('%%%s%%')", args.GoodsName)
}
if args.First != 0 {
query += fmt.Sprintf(" and a.first_category_id = %v", args.First)
}
if args.Second != 0 {
query += fmt.Sprintf(" and a.second_category_id=%v", args.Second)
}
if args.BrandID != 0 {
query += fmt.Sprintf(" and a.brand_id = %v", args.BrandID)
}
if args.GoodsCode != "" {
query += fmt.Sprintf(" and b.code like ('%%%s%%')", args.GoodsCode)
//sub := dbc.DB.Table((&goods3.RecookGoodsSkuModel{}).TableName()).Select("goods_id").
// Where("code like (?)", fmt.Sprintf("%%%s%%", args.GoodsCode)).SubQuery()
//query = query.Where("id in ?", sub)
}
if args.GoodsNum != "" {
query += fmt.Sprintf(" and b.goods_num like ('%%%s%%')", args.GoodsNum)
//sub := dbc.DB.Table((&goods3.RecookGoodsSkuModel{}).TableName()).Select("goods_id").
// Where("goods_num like (?)", fmt.Sprintf("%%%s%%", args.GoodsNum)).SubQuery()
//query = query.Where("id in ?", sub)
}
if args.VendorID != 0 {
query += fmt.Sprintf(" and a.vendor_id = %v", args.VendorID)
}
if args.Status > 0 {
switch args.Status {
case 1: // 仓库
query += fmt.Sprintf(" and a.publish_status =%v and a.is_del = %v", goods3.RecookGoodsInfoPublishStatusFalse, goods3.RecookGoodsInfoIsDelFalse)
case 2: // 回收站
query += fmt.Sprintf(" and a.is_del = %v", goods3.RecookGoodsInfoIsDelFalse)
default: // 上架
query += fmt.Sprintf(" and a.publish_status = %v", goods3.RecookGoodsInfoPublishStatusTrue)
}
}
if args.Source > 0 {
switch args.Source {
case 1: // 供应商提报
query += fmt.Sprintf(" and a.third_party_type = %v", goods3.RecookGoodsInfoThirdPartyTypeNone)
case 2: // 接口获取
query += fmt.Sprintf(" and a.third_party_type > %v", goods3.RecookGoodsInfoThirdPartyTypeNone)
}
}
if args.SourceStatus > 0 {
switch args.SourceStatus {
case 1: // 上架
query += fmt.Sprintf(" and a.bomao_status = %v", goods3.RecookGoodsInfoBomaoStatusOn)
case 2: // 下架
query += fmt.Sprintf(" and a.bomao_status = %v", goods3.RecookGoodsInfoBomaoStatusOff)
}
query += fmt.Sprintf(" and a.bomao_status > %v", goods3.RecookGoodsInfoThirdPartyTypeNone)
}
fmt.Println(query)
//query.Count(&total)
var list []export
//var base []goods3.RecookGoodsInfoModel
dbc.DB.Table(fmt.Sprintf("%s as a", rg.TableName())).
Joins(fmt.Sprintf("left join %s as b on b.goods_id = a.id ", (&goods3.RecookGoodsSkuModel{}).TableName())).
Joins(fmt.Sprintf("left join %s as c on c.id=a.first_category_id", (&goods3.RecookGoodsCategoryModel{}).TableName())).
Joins(fmt.Sprintf("left join %s as d on d.id=a.second_category_id", (&goods3.RecookGoodsCategoryModel{}).TableName())).
Joins(fmt.Sprintf("left join %s as e on e.user_id=a.vendor_id", (&enterprise.GysEnterpriseStateModel{}).TableName())).
Joins(fmt.Sprintf("left join %s as f on f.id=a.brand_id", (&goods3.RecookGoodsBrandModel{}).TableName())).
Where(query).
Select("a.id as goods_id ," +
"a.goods_name as goods_name," +
fmt.Sprintf("concat(%s,'/',%s) as category,", "c.name", "d.name") +
"f.name as brand," +
"e.enterprise_name as vendor ," +
"b.name as sku_name ," +
"b.code as sku_code," +
"b.purchase_price as purchase_price," +
"b.discount_price as discount_price," +
"b.coupon as coupon," +
"b.commission_rate*100 as commission_rate," +
"b.commission as commission," +
"b.inventory as inventory," +
"b.goods_num as goods_num," +
"IF(a.publish_status=1,'已上架','仓库中')as publish_status").Find(&list)
return list
}
type exportDown struct {
Dst string `json:"dst"`
}
func ExportPromotionDown(c *gin.Context) {
//一键excel导入精品特推商品
p := exportDown{}
if err := tools.Params(&p, c); err != nil {
back.Fail(c, err.Error())
return
}
fmt.Println(filepath.Join(static_path.Dir.Root, p.Dst))
file, err := excelize.OpenFile(filepath.Join(static_path.Dir.Root, p.Dst))
if err != nil {
back.Fail(c, err.Error())
return
}
rows, err := file.GetRows(file.GetSheetName(file.GetActiveSheetIndex()))
if err != nil {
back.Fail(c, err.Error())
return
}
fmt.Println(rows)
//08:00 88
//08:00 99
var gmp = make(map[string][]uint)
for _, row := range rows[1:] {
if len(row) == 0 || len(strings.TrimSpace(row[0])) == 0 {
continue
}
//第一行时间段 第二行goods_id
num, _ := strconv.Atoi(row[1])
if _, ok := gmp[row[0]]; ok {
gmp[row[0]] = append(gmp[row[0]], uint(num))
} else {
gmp[row[0]] = append(gmp[row[0]], uint(num))
}
}
fmt.Println(gmp["08:00"])
str := ""
var list []exportData
for i := 8; i < 25; i = i + 2 {
if i > 9 {
str = fmt.Sprintf("%v:00", i)
} else {
str = fmt.Sprintf("0%v:00", i)
}
if _, ok := gmp[str]; ok {
place := make([]string, 0)
ids := make([]interface{}, 0)
for _, v := range gmp[str] {
place = append(place, "?")
ids = append(ids, v)
}
field := fmt.Sprintf("FIELD(id, %s)", strings.Join(place, ","))
var goodsListS []goods3.RecookGoodsInfoModel
mysql2.Db.Table((&goods3.RecookGoodsInfoModel{}).TableName()).
Where("id in(?)", gmp[str]).
Clauses(clause.OrderBy{
Expression: clause.Expr{SQL: field, Vars: ids, WithoutParentheses: true},
}).
Preload("Brand").
Preload("FirstCategory").
Preload("SecondCategory").
Preload("MainPhoto", "is_master=1").
Preload("SkuPath").
Preload("Vendor").Find(&goodsListS)
var listOne []goodsData
for _, model := range goodsListS {
listOne = append(listOne, goodsData{
BrandName: model.Brand.Name,
CateName: fmt.Sprintf("%s/%s", model.FirstCategory.Name, model.SecondCategory.Name),
GoodsId: model.Id,
GoodsName: model.GoodsName,
MainPhotoUrl: model.MainPhoto.Url,
PublishStatus: model.PublishStatus,
Subtitle: model.Description,
VendorName: model.Vendor.EnterpriseName,
SkuList: model.SkuPath,
})
}
list = append(list, exportData{SortStr: str, Data: listOne})
} else {
continue
}
}
back.Suc(c, "", list)
}
type exportData struct {
SortStr string `json:"sort_str"`
Data []goodsData `json:"data"`
}
type goodsData struct {
BrandName string `json:"brand_name"`
CateName string `json:"cate_name"`
GoodsId uint `json:"goods_id"`
GoodsName string `json:"goods_name"`
MainPhotoUrl string `json:"main_photo_url"`
PublishStatus uint `json:"publish_status"`
SkuList []goods3.RecookGoodsSkuModel `json:"sku_list"`
Subtitle string `json:"subtitle"`
VendorName string `json:"vendor_name"`
}