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.

906 lines
28 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 vend
import (
"fmt"
"math/rand"
"os"
"path/filepath"
"recook/internal/back"
"recook/internal/dbc"
"recook/internal/model/freight"
"recook/internal/model/manage"
"recook/internal/static_path"
"strconv"
"strings"
"time"
"github.com/jinzhu/gorm"
"github.com/gin-gonic/gin"
"github.com/golangkit/formatime"
"github.com/shopspring/decimal"
"recook/internal/model/goods"
"recook/internal/model/vend"
"recook/tools"
)
func init() {
// 初始化随机数种子
rand.Seed(time.Now().UnixNano())
}
type GoodsQuery struct {
Page int64 `json:"page" validate:"numeric"`
IsPage int `json:"is_page"` //1。table 0下拉框
Status string `json:"status"`
VendorId string `json:"vendorId"`
BrandId int64 `json:"brandId"`
GoodsSn string `json:"goodsSn"`
GoodsName string `json:"goodsName"`
Date string `json:"date"`
Action string `json:"action"`
}
func QueryGoodsList(c *gin.Context) {
var goodsState = make(map[int]string)
goodsState[2] = "待采购审核"
goodsState[3] = "已驳回"
goodsState[4] = "审核通过"
goodsState[5] = "下架"
goodsState[6] = "待上级审核"
goodsState[7] = "运营驳回"
var goodsStateQc = make(map[int]string)
goodsStateQc[2] = "待QC审核"
goodsStateQc[3] = "已驳回"
goodsStateQc[4] = "审核通过"
goodsStateQc[5] = "待运营审核"
var goodsStateYy = make(map[int]string)
goodsStateYy[2] = "待运营审核"
goodsStateYy[3] = "已驳回"
goodsStateYy[4] = "审核通过"
var limit int64 = 10
// 每页显示数据条数
var page GoodsQuery
err := tools.Params(&page, c)
if err != nil {
back.Fail(c, err.Error())
return
}
var list []vend.GysGoodsInfo
count := 0
whereStr := ""
if page.Status == "8" {
// 用于待运营审核的特殊情况
whereStr += " and publish_status =6 and qc_status = 2"
} else {
if page.Status != "" {
whereStr += " and publish_status =" + page.Status
}
}
if page.BrandId != 0 {
brandStr := strconv.FormatInt(page.BrandId, 10)
whereStr += " and main_branid = " + brandStr
}
if page.GoodsSn != "" {
whereStr += " and goods_sn = '" + page.GoodsSn + "'"
}
if page.GoodsName != "" {
whereStr += " and title LIKE '%" + page.GoodsName + "%'"
}
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
}
order := ""
if page.Action == "gc" {
if user.RoleID != 1 {
whereStr += " and first_category_id In(" + user.GoodsType + ")"
gysUsers := []vend.GysUsers{}
if user.VendsList == "" {
dbc.DB.Model(&vend.GysUsers{}).Select("id").Where("is_interior = ?", 0).Find(&gysUsers)
} else {
dbc.DB.Model(&vend.GysUsers{}).Select("id").Where("is_interior = ? or id in ("+user.VendsList+")", 0).Find(&gysUsers)
}
strUserIds := ""
for _, gysUser := range gysUsers {
strUserIds += fmt.Sprintf(",%v", gysUser.ID)
}
if strUserIds != "" {
whereStr += " and user_id in (" + strUserIds[1:] + ")"
}
}
order = "updated_ats desc"
} else if page.Action == "qc" {
//如果是待审核状态
tempStatus, _ := strconv.Atoi(page.Status)
if tempStatus == 6 {
whereStr += " and (gc_status = 2 )"
} else {
whereStr += " and (gc_status > 1 )"
}
order = "admin_date desc"
} else if page.Action == "yy" {
whereStr += " and (qc_status > 1 )"
order = "admin_date_qc desc"
}
if page.Date != "" {
loc, _ := time.LoadLocation("Local")
start, _ := time.ParseInLocation("2006-01-02 15:04:05", page.Date+" 00:00:00", loc)
startStr := strconv.FormatInt(start.Unix(), 10)
endS := page.Date + " 23:59:59"
end, _ := time.ParseInLocation("2006-01-02 15:04:05", endS, loc)
endStr := strconv.FormatInt(end.Unix(), 10)
whereStr += " and (updated_ats >= " + startStr + " and updated_ats<=" + endStr + ")"
}
if page.VendorId != "" {
whereStr += " and user_id =" + page.VendorId
}
if page.IsPage == 1 {
dbc.DB.Where("publish_status > 1" + whereStr).Limit(limit).Offset((page.Page) * limit).Order(order).Find(&list)
dbc.DB.Table("gys_goods_info").Where("publish_status > 1" + whereStr).Count(&count)
} else {
dbc.DB.Where("publish_status > 1").Order(order).Find(&list)
}
newList := []vend.GysGoodsInfo{}
for _, info := range list {
var main []vend.GysGoodsMainPhoto
dbc.DB.Where("goods_id = ? and is_master = 1", info.ID).Find(&main)
info.Main = main
user := vend.GysUsers{}
dbc.DB.Where("id = ?", info.UserID).Find(&user)
info.User = user
if page.Action == "qc" {
if info.GcStatus == 3 && info.QcStatus == 3 && info.AdminDate.Time.Unix() < info.AdminDateYy.Time.Unix() {
info.StateInfo = goodsStateQc[info.GcStatus]
} else {
info.StateInfo = goodsStateQc[info.GcStatus]
}
} else if page.Action == "yy" {
info.StateInfo = goodsStateYy[info.QcStatus]
} else {
if info.GcStatus == 3 && info.PublishStatus == 3 && info.AdminDate.Time.Unix() < info.AdminDateQc.Time.Unix() {
info.StateInfo = goodsState[info.PublishStatus]
} else {
if info.GcStatus == 2 {
info.StateInfo = goodsState[info.PublishStatus] + "(QC)"
} else if info.QcStatus == 2 {
info.StateInfo = goodsState[info.PublishStatus] + "(运营)"
} else {
info.StateInfo = goodsState[info.PublishStatus]
}
}
}
brandInfo := goods.Brand{}
dbc.DB.Where("id = ?", info.MainBranid).First(&brandInfo)
info.BrandInfo = brandInfo
newList = append(newList, info)
}
if page.IsPage == 1 {
back.Suc(c, "", &BaseResponse{
List: newList,
Total: count,
})
} else {
back.Suc(c, "", newList)
}
}
type SkuQuery struct {
GoodsID string `json:"goods_id"`
Info string `json:"info"`
Action string `json:"action"`
}
func GoodsSkuList(c *gin.Context) {
var p SkuQuery
err := tools.Params(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
a := ""
if p.Action == "qc" {
a = " and gc_status = 2"
} else if p.Action == "yy" {
a = " and qc_status = 2"
} else if p.Info == "1" {
a = " and (publish_status = 2 or publish_status = 7)"
}
var goodsList []vend.GysGoodsInfo
dbc.DB.Where("id in(" + p.GoodsID + ",0)" + a).Find(&goodsList)
mainGoodsIds := []uint{}
for _, info := range goodsList {
if info.MainGoodsID > 0 {
mainGoodsIds = append(mainGoodsIds, info.MainGoodsID)
}
}
mainGoodsSkuMap := map[string]goods.Sku{}
if len(mainGoodsIds) > 0 {
goodsSkus := []goods.Sku{}
dbc.DB.Model(&goods.Sku{}).Find(&goodsSkus, "goods_id in (?)", mainGoodsIds)
for _, sku := range goodsSkus {
mainGoodsSkuMap[sku.Code] = sku
}
}
var skuList []vend.GysGoodsSku
dbc.DB.Where("goods_id in(" + p.GoodsID + ",0)").Find(&skuList)
if p.Info != "1" && p.Info != "2" {
for key, info := range skuList {
if sku, ok := mainGoodsSkuMap[info.Code]; ok {
discountPrice, _ := sku.DiscountPrice.Float64()
skuList[key].DiscountPrice = float32(discountPrice)
}
}
back.Suc(c, "", skuList)
return
}
skuMap := make(map[uint][]vend.GysGoodsSku)
for _, info := range skuList {
if sku, ok := mainGoodsSkuMap[info.Code]; ok {
discountPrice, _ := sku.DiscountPrice.Float64()
info.DiscountPrice = float32(discountPrice)
}
skuInfo := skuMap[info.GoodsId]
skuInfo = append(skuInfo, info)
skuMap[info.GoodsId] = skuInfo
}
for key, info := range goodsList {
var main []vend.GysGoodsMainPhoto
dbc.DB.Where("goods_id = ?", info.ID).Find(&main)
info.Main = main
user := vend.GysUsers{}
dbc.DB.Where("id = ?", info.UserID).Find(&user)
info.User = user
info.SkuList = skuMap[info.ID]
var infoImg []vend.GysGoodsDetailPhoto
dbc.DB.Where("goods_id = ? and type = 0", info.ID).Find(&infoImg)
info.InfoImg = infoImg
var InspectionImg []vend.GysGoodsDetailPhoto
dbc.DB.Where("goods_id = ? and type = 1", info.ID).Find(&InspectionImg)
info.InspectionImg = InspectionImg
var OtherImg []vend.GysGoodsDetailPhoto
dbc.DB.Where("goods_id = ? and type = 2", info.ID).Find(&OtherImg)
info.OtherImg = OtherImg
one := goods.Category{}
dbc.DB.Where("id = ?", info.FirstCategoryId).First(&one)
two := goods.Category{}
dbc.DB.Where("id = ?", info.SecondCategoryId).First(&two)
info.One = one
info.Two = two
freights := freight.Information{}
dbc.DB.Where("id = ?", info.Freight).First(&freights)
info.FreightInfo = freights
active := vend.GysGoodsPromotionPhoto{}
dbc.DB.Where("goods_id = ?", info.ID).First(&active)
info.Active = active
video := vend.GysGoodsVideo{}
dbc.DB.Where("goods_id = ?", info.ID).First(&video)
info.Video = video
brandInfo := goods.Brand{}
dbc.DB.Where("id = ?", info.MainBranid).First(&brandInfo)
info.BrandInfo = brandInfo
goodsList[key] = info
}
back.Suc(c, "", goodsList)
}
type GoodsNoRequest struct {
Data []Datum `json:"data"`
Detail string `json:"detail"`
Action string `json:"action"`
}
type Datum struct {
ID int64 `json:"id"`
Brand int64 `json:"Brand"`
Title string `json:"Style"`
ViceTitle string `json:"SubTitle"`
FirstCategoryID int64 `json:"FirstCategoryId"`
SecondCategoryID int64 `json:"SecondCategoryId"`
PublishStatus int64 `json:"PublishStatus"`
Freight int64 `json:"Freight"`
Weight float32 `json:"Weight"`
Hash string `json:"Hash"`
CreatedAt string `json:"CreatedAt"`
UpdatedAt string `json:"UpdatedAt"`
UserID int64 `json:"UserID"`
GoodsSn string `json:"GoodsSn"`
InspectionURL string `json:"InspectionUrl"`
PermissionURL string `json:"PermissionUrl"`
OtherURL string `json:"OtherUrl"`
NoInfo string `json:"NoInfo"`
Main []Main `json:"Main"`
StateInfo string `json:"StateInfo"`
SkuList []SkuList `json:"SkuList"`
InfoImg []Active `json:"InfoImg"`
One One `json:"One"`
Two One `json:"Two"`
FreightInfo FreightInfo `json:"FreightInfo"`
Active Active `json:"Active"`
Video Video `json:"Video"`
}
type Active struct {
ID int64 `json:"id"`
GoodsID int64 `json:"GoodsID"`
URL string `json:"Url"`
Name string `json:"name"`
Width int64 `json:"Width"`
Height int64 `json:"Height"`
OrderNo *int64 `json:"OrderNo,omitempty"`
}
type FreightInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
AllFree int64 `json:"allFree"`
ShippingAddr string `json:"shippingAddr"`
}
type Main struct {
ID int64 `json:"id"`
GoodsID int64 `json:"GoodsID"`
URL string `json:"Url"`
Nmae string `json:"Nmae"`
IsMaster int64 `json:"IsMaster"`
OrderNo int64 `json:"OrderNo"`
Height int64 `json:"Height"`
}
type One struct {
ID int64 `json:"id"`
Name string `json:"name"`
ParentID int64 `json:"parentId"`
LogoURL string `json:"logoUrl"`
}
type SkuList struct {
ID int64 `json:"id"`
GoodsID int64 `json:"GoodsID"`
Name string `json:"name"`
CombineID string `json:"CombineId"`
PicURL string `json:"PicUrl"`
Code string `json:"Code"`
PurchasePrice float32 `json:"PurchasePrice"`
OriginalPrice float32 `json:"OriginalPrice"`
DiscountPrice float32 `json:"DiscountPrice"`
CommissionRate float32 `json:"commissionRate"`
Inventory uint `json:"inventory"`
Coupon float64 `json:"coupon"`
}
type User struct {
ID int64 `json:"id"`
CreatedAt interface{} `json:"created_at"`
Username string `json:"username"`
IsState int64 `json:"is_state"`
StateStr string `json:"state_str"`
EnterpriseState EnterpriseState `json:"enterprise_state"`
EnterpriseStateUp EnterpriseState `json:"enterprise_state_up"`
Name string `json:"name"`
}
type EnterpriseState struct {
ID int64 `json:"id"`
ContactEmail string `json:"contact_email"`
ContactPhone string `json:"contact_phone"`
Recommended string `json:"recommended"`
RecommendedName string `json:"recommended_name"`
RecommendedPhone string `json:"recommended_phone"`
EnterpriseName string `json:"enterprise_name"`
RegistrationAddress string `json:"registration_address"`
Trade string `json:"trade"`
CompanyType string `json:"company_type"`
CompantTypeInfo string `json:"compant_type_info"`
Capital string `json:"capital"`
Currency string `json:"currency"`
BusinessStart string `json:"business_start"`
BusinessEnd string `json:"business_end"`
RegistrationProvince string `json:"registration_province"`
RegistrationCity string `json:"registration_city"`
RegistrationDistrict string `json:"registration_district"`
OperationProvince string `json:"operation_province"`
OperationCity string `json:"operation_city"`
OperationDistrict string `json:"operation_district"`
OperationAddress string `json:"operation_address"`
EnterpriseCode string `json:"enterprise_code"`
LicenseURL string `json:"license_url"`
PayTaxes string `json:"pay_taxes"`
PaytaxesURL string `json:"paytaxes_url"`
AccountURL string `json:"account_url"`
LegalPerson string `json:"legal_person"`
LegalPersonCode string `json:"legal_person_code"`
LegalPersonURL string `json:"legal_person_url"`
OverseasRegistration string `json:"overseas_registration"`
OverseasOperation string `json:"overseas_operation"`
OverseasOperationInfo string `json:"overseas_operation_info"`
OverseasCode string `json:"overseas_code"`
OverseasCodeURL string `json:"overseas_code_url"`
OverseasAccountURL string `json:"overseas_account_url"`
OverseasLegalPerson string `json:"overseas_legal_person"`
OverseasLegalPersonURL string `json:"overseas_legal_person_url"`
State string `json:"state"`
StateInfo string `json:"state_info"`
ComitTime string `json:"comit_time"`
UserID string `json:"user_id"`
BrandList interface{} `json:"brand_list"`
SectorList interface{} `json:"sector_list"`
}
type Video struct {
ID int64 `json:"id"`
GoodsID int64 `json:"GoodsID"`
URL string `json:"Url"`
}
func GoodsNo(c *gin.Context) {
var p = GoodsNoRequest{}
err := tools.Params(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
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
}
for _, info := range p.Data {
goodsInfo := vend.GysGoodsInfo{}
if p.Action == "cg" {
if err = dbc.DB.Model(&goodsInfo).Where("id = ?", info.ID).Update(map[string]interface{}{
"publish_status": 3,
"no_info": p.Detail,
"admin_id": user.ID,
"admin_user": user.Name,
"admin_date": formatime.NewSecondNow(),
}).Error; err != nil {
if gorm.IsRecordNotFoundError(err) {
back.Fail(c, "数据不存在:"+err.Error())
return
}
back.Fail(c, "操作错误:"+err.Error())
return
}
} else if p.Action == "qc" {
if err = dbc.DB.Model(&goodsInfo).Where("id = ?", info.ID).Update(map[string]interface{}{
"publish_status": 3,
"no_info": p.Detail,
"admin_id_qc": user.ID,
"admin_user_qc": user.Name,
"admin_date_qc": formatime.NewSecondNow(),
"gc_status": 3,
}).Error; err != nil {
if gorm.IsRecordNotFoundError(err) {
back.Fail(c, "数据不存在:"+err.Error())
return
}
back.Fail(c, "操作错误:"+err.Error())
return
}
} else if p.Action == "yy" {
if err = dbc.DB.Model(&goodsInfo).Where("id = ?", info.ID).Update(map[string]interface{}{
"no_info": p.Detail,
"admin_id_yy": user.ID,
"admin_user_yy": user.Name,
"admin_date_yy": formatime.NewSecondNow(),
"gc_status": 3,
"qc_status": 3,
"publish_status": 7,
}).Error; err != nil {
if gorm.IsRecordNotFoundError(err) {
back.Fail(c, "数据不存在:"+err.Error())
return
}
back.Fail(c, "操作错误:"+err.Error())
return
}
}
}
back.Suc(c, "", "")
}
type GoodsOkRequest struct {
Data []Datum2 `json:"data"`
Action string `json:"action"`
}
type Datum2 struct {
ID int64 `json:"id"`
Brand int64 `json:"Brand"`
Title string `json:"Style"`
ViceTitle string `json:"SubTitle"`
FirstCategoryID int64 `json:"FirstCategoryId"`
SecondCategoryID int64 `json:"SecondCategoryId"`
PublishStatus int64 `json:"PublishStatus"`
Freight int64 `json:"Freight"`
Weight float32 `json:"Weight"`
Hash string `json:"Hash"`
CreatedAt string `json:"CreatedAt"`
UpdatedAt string `json:"UpdatedAt"`
UserID int64 `json:"UserID"`
GoodsSn string `json:"GoodsSn"`
InspectionURL string `json:"InspectionUrl"`
PermissionURL string `json:"PermissionUrl"`
OtherURL string `json:"OtherUrl"`
NoInfo string `json:"NoInfo"`
MainBranid int64 `json:"MainBranid"`
StateInfo string `json:"StateInfo"`
SkuList []SkuList `json:"SkuList"`
IsJoinTeamPerformance uint `json:"isJoinTeamPerformance"`
}
type BrandInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
Desc string `json:"desc"`
Web string `json:"web"`
GoodsCount int64 `json:"goodsCount"`
LogoURL string `json:"logoUrl"`
AuthURL string `json:"authUrl"`
ShowURL string `json:"showUrl"`
}
func GoodsOk(c *gin.Context) {
var p = GoodsOkRequest{}
err := tools.Params(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
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
}
tx := dbc.DB.Begin()
{
msg := ""
flage := 0
msg2 := ""
flage2 := 0
for _, info := range p.Data {
goodsInfo := vend.GysGoodsInfo{}
dbc.DB.Where("id = (?)", info.ID).Find(&goodsInfo)
if goodsInfo.ID == 0 {
if flage == 0 {
msg += "商品不存在:{" + info.Title + "新品单号:" + info.GoodsSn + "}"
flage = 1
continue
} else {
msg += "{" + info.Title + "新品单号:" + info.GoodsSn + "}"
continue
}
} else if (goodsInfo.PublishStatus != 2 && goodsInfo.PublishStatus != 7 && p.Action == "cg") || (goodsInfo.GcStatus != 2 && p.Action == "qc") {
if flage2 == 0 {
msg2 += "商品状态错误:{" + info.Title + "新品单号:" + info.GoodsSn + "}"
flage2 = 1
continue
} else {
msg2 += "{" + info.Title + "新品单号:" + info.GoodsSn + "}"
continue
}
}
var brand goods.Brand
if err := dbc.DB.First(&brand, "id = ?", goodsInfo.MainBranid).Error; err != nil {
back.Err(c, "品牌不存在")
return
}
//采购审核
if p.Action == "cg" {
for _, _sku := range info.SkuList {
skuInfo := vend.GysGoodsSku{}
dbc.DB.First(&skuInfo, "id = ?", _sku.ID)
skuInfo.PurchasePrice = _sku.PurchasePrice
skuInfo.OriginalPrice = _sku.OriginalPrice
skuInfo.DiscountPrice = _sku.DiscountPrice
skuInfo.Inventory = _sku.Inventory
skuInfo.CommissionRate = decimal.NewFromFloat(float64(_sku.CommissionRate)).Truncate(2)
if err := dbc.DB.Model(&vend.GysGoodsSku{}).Where("id = ?", _sku.ID).Updates(&skuInfo).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
}
if err := dbc.DB.Model(&goodsInfo).Updates(map[string]interface{}{
"publish_status": 6,
"admin_id": user.ID,
"admin_user": user.Name,
"admin_date": formatime.NewSecondNow(),
"gc_status": 2,
}).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
continue
} else if p.Action == "qc" {
if err := dbc.DB.Model(&goodsInfo).Updates(map[string]interface{}{
"admin_id_qc": user.ID,
"admin_user_qc": user.Name,
"admin_date_qc": formatime.NewSecondNow(),
"gc_status": 5,
"qc_status": 2,
}).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
continue
}
// 审核通过,总虚拟销量
var totalSalesVolumeInc uint
salesVolumeIncs := []uint{}
skusMap := map[int64]vend.GysGoodsSku{}
for _, _sku := range info.SkuList {
skuInfo := vend.GysGoodsSku{}
dbc.DB.First(&skuInfo, "id = ?", _sku.ID)
//skuInfo.OriginalPrice = _sku.OriginalPrice
skuInfo.Coupon = _sku.Coupon
if err := dbc.DB.Model(&vend.GysGoodsSku{}).Where("id = ?", _sku.ID).Updates(&skuInfo).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
salesVolumeInc := uint(rand.Intn(899) + 100)
totalSalesVolumeInc += salesVolumeInc
salesVolumeIncs = append(salesVolumeIncs, salesVolumeInc)
skusMap[_sku.ID] = skuInfo
}
var goodsMain = goods.Information{
BrandID: goodsInfo.MainBranid,
VendorID: goodsInfo.UserID,
GoodsName: goodsInfo.Title,
Description: goodsInfo.ViceTitle,
FirstCategoryID: goodsInfo.FirstCategoryId,
SecondCategoryID: goodsInfo.SecondCategoryId,
PublishStatus: 1,
Weight: goodsInfo.Weight,
FreightID: goodsInfo.Freight,
IsJoinTeamPerformance: info.IsJoinTeamPerformance,
Hash: tools.GenerateGoodsHashSign(),
SalesVolume: totalSalesVolumeInc,
}
if err := tx.Create(&goodsMain).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
// ---------------------------更新商品品牌属性---------------------------------
if err := tx.Model(&brand).Update(goods.Brand{GoodsCount: brand.GoodsCount + 1}).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
// ---------------------------存储属性---------------------------------
/*存储attrs*/
attrsValueMap := map[string]uint{}
var goodsAttributList []vend.GysAttribute
dbc.DB.Where("goods_id = ?", goodsInfo.ID).Find(&goodsAttributList)
for _, _attributInfo := range goodsAttributList {
attr := goods.Attribute{
GoodsID: goodsMain.ID,
Name: _attributInfo.Name,
Value: _attributInfo.Value,
}
if err := tx.Create(&attr).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
attrsValueMap[attr.Value] = attr.ID
}
// ------------------------------存储sku------------------------------
for index, _skuInfo := range info.SkuList {
array := strings.Split(_skuInfo.Name, ",")
combineIDs := make([]string, 0, 0)
combineNames := make([]string, 0, 0)
for _, v := range array {
idStr := strconv.Itoa(int(attrsValueMap[v]))
combineIDs = append(combineIDs, idStr)
combineNames = append(combineNames, v)
}
skuInfoLod := goods.Sku{}
dbc.DB.Where("code = ?", _skuInfo.Code).First(&skuInfoLod)
if skuInfoLod.ID > 0 {
back.Err(c, "sku编号已存在"+_skuInfo.Code)
tx.Rollback()
return
}
sku := goods.Sku{
GoodsID: goodsMain.ID,
Name: strings.Join(combineNames, "+"),
CombineID: strings.Join(combineIDs, ","),
PicURL: _skuInfo.PicURL,
Code: _skuInfo.Code,
PurchasePrice: decimal.NewFromFloat(float64(_skuInfo.PurchasePrice)).Truncate(2),
OriginalPrice: decimal.NewFromFloat(float64(_skuInfo.OriginalPrice)).Truncate(2),
DiscountPrice: decimal.NewFromFloat(float64(_skuInfo.DiscountPrice)).Truncate(2),
Commission: decimal.NewFromFloat(float64(_skuInfo.CommissionRate / 100)).Mul(decimal.NewFromFloat(float64(_skuInfo.DiscountPrice))).Truncate(2),
CommissionRate: decimal.NewFromFloat(float64(_skuInfo.CommissionRate / 100)).Truncate(2),
SalesVolume: 0,
Inventory: _skuInfo.Inventory,
Coupon: decimal.NewFromFloat(_skuInfo.Coupon).Truncate(2),
SalesVolumeInc: salesVolumeIncs[index], // 虚拟销量
ControlPrice: decimal.NewFromFloat(float64(skusMap[_skuInfo.ID].OriginalPrice)).Truncate(2), // 虚拟销量
}
if err := tx.Create(&sku).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
}
// -----------------------------存储主图-------------------------------
var mainList []vend.GysGoodsMainPhoto
dbc.DB.Where("goods_id = ?", goodsInfo.ID).Find(&mainList)
for _, _mainInfo := range mainList {
mainPicturePath := filepath.Join(static_path.Dir.Root, _mainInfo.Url)
_, err := os.Stat(mainPicturePath)
if err != nil && os.IsNotExist(err) {
back.Err(c, err.Error())
tx.Rollback()
return
}
mp := goods.MainPhoto{
GoodsID: goodsMain.ID,
URL: _mainInfo.Url,
IsMaster: _mainInfo.IsMaster,
OrderNo: _mainInfo.OrderNo,
Width: _mainInfo.Width,
Height: _mainInfo.Height,
Name: _mainInfo.Name,
}
err = tx.Create(&mp).Error
if err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
}
// -----------------------------存储详情图-------------------------------
var infoList []vend.GysGoodsDetailPhoto
dbc.DB.Where("goods_id = ? and type=0", goodsInfo.ID).Find(&infoList)
for _, _infoInfo := range infoList {
detailPicturePath := filepath.Join(static_path.Dir.Root, _infoInfo.Url)
_, err := os.Stat(detailPicturePath)
if err != nil && os.IsNotExist(err) {
back.Err(c, err.Error())
tx.Rollback()
return
}
dp := goods.DetailPhoto{
GoodsID: goodsMain.ID,
URL: _infoInfo.Url,
OrderNo: _infoInfo.OrderNo,
Width: _infoInfo.Width,
Height: _infoInfo.Height,
Name: _infoInfo.Name,
}
err = tx.Create(&dp).Error
if err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
}
// ------------------------存储活动图片---------------------------
activeImg := vend.GysGoodsPromotionPhoto{}
dbc.DB.Where("goods_id = ?", goodsInfo.ID).First(&activeImg)
if activeImg.ID > 0 {
promotionPhoto := goods.PromotionPhoto{
GoodsID: goodsMain.ID,
URL: activeImg.Url,
Width: activeImg.Width,
Height: activeImg.Height,
}
if err := tx.Create(&promotionPhoto).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
}
// ------------------------存储视频------------------------------
videInfo := vend.GysGoodsVideo{}
dbc.DB.Where("goods_id = ?", goodsInfo.ID).First(&videInfo)
if videInfo.ID > 0 {
videoPath := filepath.Join(static_path.Dir.Root, videInfo.Url)
fileInfo, err := os.Stat(videoPath)
if err != nil && os.IsNotExist(err) {
back.Err(c, err.Error())
tx.Rollback()
return
}
fileSize := fileInfo.Size()
duration, err := tools.ParseVideoDuration(videoPath)
if err != nil {
back.Err(c, err.Error()+"视频解析失败")
tx.Rollback()
return
}
v := goods.Video{
GoodsID: goodsInfo.ID,
Thumbnail: tools.GenerateVideoThumbnail(videInfo.Url),
URL: videInfo.Url,
Duration: uint(duration),
Size: float64(fileSize)/(1<<20) + 0.005,
}
err = tx.Create(&v).Error
if err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
}
if err := dbc.DB.Model(&goodsInfo).Updates(map[string]interface{}{
"publish_status": 4,
"main_goods_id": goodsMain.ID,
"admin_id_yy": user.ID,
"admin_user_yy": user.Name,
"admin_date_yy": formatime.NewSecondNow(),
"gc_status": 4,
"qc_status": 4,
}).Error; err != nil {
back.Err(c, err.Error())
tx.Rollback()
return
}
}
}
tx.Commit()
back.Suc(c, "操作成功", "")
}