erp_server/app/admin/apis/commoditymanage/commodity.go
2023-09-16 11:11:36 +08:00

1231 lines
34 KiB
Go

package commoditymanage
import (
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
model "go-admin/app/admin/models"
orm "go-admin/common/global"
"go-admin/logger"
"go-admin/tools/app"
"golang.org/x/sync/errgroup"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
func ErpStockBatchImport(c *gin.Context) {
//req := struct {
// File []byte `json:"file"`
//}{}
//if err := c.ShouldBindJSON(&req); err != nil {
// logger.Error(err)
// app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
// return
//}
model.EsStockLock.Lock()
defer model.EsStockLock.Unlock()
file, header, err := c.Request.FormFile("file")
if err != nil {
logger.Error("form file err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
readAll, err := ioutil.ReadAll(file)
if err != nil {
logger.Error("read all err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
fmt.Println("header:", header.Filename)
//fmt.Println("readAll:", readAll)
fileStart := time.Now().UnixMilli()
bCol, _, err := model.FileExcelReaderImport(readAll, model.ErpStockFileExcelCols)
if err != nil {
logger.Error("file excel reader err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
fmt.Println("FileExcelReader", time.Now().UnixMilli()-fileStart)
//fmt.Println("bCol", string(bCol))
var stockFiles []model.ErpStockFileExcel
err = json.Unmarshal(bCol, &stockFiles)
if err != nil {
logger.Error("erp commodity file excel unmarshal err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
if len(stockFiles) != 0 {
stockFiles = stockFiles[1:]
}
stockier := model.NewStockImporter()
fileStart = time.Now().UnixMilli()
err = stockier.ErpStockFileExcelListProcessing(stockFiles)
if err != nil {
logger.Error("processing err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
fmt.Println("ErpStockFileExcelListProcessing", time.Now().UnixMilli()-fileStart)
erpStocks := make([]model.ErpStockCommodity, 0, len(stockFiles))
for i, _ := range stockFiles {
erpStocks = append(erpStocks, stockFiles[i].ErpStockCommodity)
}
begin := orm.Eloquent.Begin()
total := len(erpStocks)
size := 200
page := total / size
if total%size != 0 {
page += 1
}
errGroup := errgroup.Group{}
for i := 0; i < page; i++ {
if i == page-1 {
stockList := erpStocks[i*size:]
err = begin.Create(&stockList).Error
if err != nil {
begin.Rollback()
logger.Error("create commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
} else {
errGroup.Go(func() error {
stockList := erpStocks[i*size : (i+1)*size]
err = begin.Create(&stockList).Error
if err != nil {
begin.Rollback()
logger.Error("create commodity err:", err)
return err
}
return nil
})
}
}
err = stockier.ErpStockCountUpdate(begin)
if err != nil {
begin.Rollback()
logger.Error("erp stock count update err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
err = stockier.ErpInventoryStockCreate(begin, stockFiles)
if err != nil {
begin.Rollback()
logger.Error("erp inventory stock create err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
err = errGroup.Wait()
if err != nil {
begin.Rollback()
logger.Error("err group wait err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
err = begin.Commit().Error
if err != nil {
begin.Rollback()
logger.Error("commit err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
logging := model.Logging{
Function: "库存导入",
Event: model.LoggingEventInventoryImport,
EventName: "库存导入",
}
logging.Create(c)
//app.OK(c, erpStocks, "")
app.OK(c, nil, "")
//return
}
func ErpCommodityCreate(c *gin.Context) {
req := struct {
Name string `json:"name" binding:"required"`
ErpCategoryId uint32 `json:"erp_category_id" binding:"required"`
IMEIType uint32 `json:"imei_type" binding:"required"` // 1-无串码 2-串码
ErpSupplierId uint32 `json:"erp_supplier_id" binding:"required"`
RetailPrice uint32 `json:"retail_price" binding:"required"`
MinRetailPrice uint32 `json:"min_retail_price" binding:"required"`
StaffCostPrice uint32 `json:"staff_cost_price" binding:"required"`
WholesalePrice uint32 `json:"wholesale_price" binding:"required"`
Brokerage1 string `json:"brokerage_1" binding:"required"`
Brokerage2 string `json:"brokerage_2"`
MemberDiscount string `json:"member_discount"`
Origin string `json:"origin"`
Remark string `json:"remark" gorm:"type:varchar(512)"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
brokerage1Float, err := strconv.ParseFloat(req.Brokerage1, 64)
if err != nil {
logger.Error("brokerage1 err:", err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
brokerage2Float, err := strconv.ParseFloat(req.Brokerage2, 64)
if err != nil {
logger.Error("brokerage2 err:", err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
memberDiscountFloat, err := strconv.ParseFloat(req.MemberDiscount, 64)
if err != nil {
logger.Error("member discount err:", err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
commodity := &model.ErpCommodity{
Number: 1,
Name: req.Name,
ErpCategoryId: req.ErpCategoryId,
ErpCategoryName: "",
IMEIType: req.IMEIType,
ErpSupplierId: req.ErpSupplierId,
ErpSupplierName: "",
RetailPrice: req.RetailPrice,
MinRetailPrice: req.MinRetailPrice,
StaffCostPrice: req.StaffCostPrice + req.WholesalePrice,
WholesalePrice: req.WholesalePrice,
Brokerage1: brokerage1Float,
Brokerage2: brokerage2Float,
MemberDiscount: memberDiscountFloat,
Origin: req.Origin,
Remark: req.Remark,
}
err = commodity.SetErpCategory()
if err != nil {
logger.Error("set erp category err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
commodity.IdInit()
var catCommodity model.ErpCommodity
err = orm.Eloquent.Table("erp_commodity").Where("erp_category_id=?", req.ErpCategoryId).
Order("id DESC").Limit(1).Find(&catCommodity).Error
if err != nil && err != model.RecordNotFound {
logger.Error("cat erp commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
if catCommodity.Number != 0 {
commodity.Number = catCommodity.Number + 1
}
commodity.SerialNumber = fmt.Sprintf("%06d%04d", commodity.ErpCategory.FullNum, commodity.Number)
err = orm.Eloquent.Create(commodity).Error
if err != nil {
logger.Error("create commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
app.OK(c, commodity, "")
return
}
func ErpCommodityList(c *gin.Context) {
req := &model.ErpCommodityListReq{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
resp, err := req.List()
if err != nil {
logger.Error("erp commodity list err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
app.OK(c, resp, "")
return
}
func ErpCommodityDetail(c *gin.Context) {
req := struct {
ErpCommodityId uint32 `json:"erp_commodity_id"`
SerialNumber string `json:"serial_number"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
var commodity model.ErpCommodity
qs := orm.Eloquent.Table("erp_commodity")
if req.ErpCommodityId != 0 {
qs = qs.Where("id=?", req.ErpCommodityId)
}
if req.SerialNumber != "" {
qs = qs.Where("serial_number=?", req.SerialNumber)
}
err := qs.Find(&commodity).Error
if err != nil {
logger.Error("erp commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
app.OK(c, commodity, "")
return
}
func ErpCommodityDel(c *gin.Context) {
req := struct {
ErpCommodityId uint32 `json:"erp_commodity_id" binding:"required"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
err := orm.Eloquent.Table("erp_commodity").Where("id=?", req.ErpCommodityId).Delete(&model.ErpCommodity{}).Error
if err != nil {
logger.Error("erp commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
app.OK(c, nil, "删除成功")
return
}
func ErpCommodityEdit(c *gin.Context) {
req := struct {
Id uint32 `json:"id" binding:"required"`
Name string `json:"name" binding:"required"`
ErpCategoryId uint32 `json:"erp_category_id" binding:"required"`
IMEIType uint32 `json:"imei_type" binding:"required"` // 1-无串码 2-串码
ErpSupplierId uint32 `json:"erp_supplier_id" binding:"required"`
RetailPrice uint32 `json:"retail_price" binding:"required"`
MinRetailPrice uint32 `json:"min_retail_price" binding:"required"`
StaffCostPrice uint32 `json:"staff_cost_price" binding:"required"`
WholesalePrice uint32 `json:"wholesale_price" binding:"required"`
//Brokerage1 string `json:"brokerage_1" binding:"required"`
//Brokerage2 string `json:"brokerage_2"`
//MemberDiscount string `json:"member_discount"`
Brokerage1 float64 `json:"brokerage_1" binding:"required"`
Brokerage2 float64 `json:"brokerage_2"`
MemberDiscount float64 `json:"member_discount"`
Origin string `json:"origin"`
Remark string `json:"remark" gorm:"type:varchar(512)"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
brokerage1Float := req.Brokerage1
brokerage2Float := req.Brokerage2
memberDiscountFloat := req.MemberDiscount
//brokerage1Float, err := strconv.ParseFloat(req.Brokerage1, 64)
//if err != nil {
// logger.Error("brokerage1 err:", err)
// app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
// return
//}
//brokerage2Float, err := strconv.ParseFloat(req.Brokerage2, 64)
//if err != nil {
// logger.Error("brokerage2 err:", err)
// app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
// return
//}
//memberDiscountFloat, err := strconv.ParseFloat(req.MemberDiscount, 64)
//if err != nil {
// logger.Error("member discount err:", err)
// app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
// return
//}
commodity := &model.ErpCommodity{
Name: req.Name,
ErpCategoryId: req.ErpCategoryId,
ErpCategoryName: "",
IMEIType: req.IMEIType,
ErpSupplierId: req.ErpSupplierId,
ErpSupplierName: "",
RetailPrice: req.RetailPrice,
MinRetailPrice: req.MinRetailPrice,
StaffCostPrice: req.StaffCostPrice + req.WholesalePrice,
WholesalePrice: req.WholesalePrice,
Brokerage1: brokerage1Float,
Brokerage2: brokerage2Float,
MemberDiscount: memberDiscountFloat,
Origin: req.Origin,
Remark: req.Remark,
}
commodity.ID = req.Id
err := commodity.SetErpCategory()
if err != nil {
logger.Error("set erp category err:", err)
app.Error(c, http.StatusInternalServerError, err, "操作失败")
return
}
commodity.IdInit()
var catCommodity model.ErpCommodity
//err = orm.Eloquent.Table("erp_commodity").Where("erp_category_id=?", req.Id).Limit(1).Find(&catCommodity).Error
err = orm.Eloquent.Table("erp_commodity").Where("id=?", req.Id).Find(&catCommodity).Error
if err != nil {
logger.Error("cat erp commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "操作失败")
return
}
commodity.Number = catCommodity.Number
commodity.SerialNumber = catCommodity.SerialNumber
err = orm.Eloquent.Save(commodity).Error
if err != nil {
logger.Error("create commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "操作失败")
return
}
app.OK(c, commodity, "")
return
}
func ErpCommodityBatchImport(c *gin.Context) {
//req := struct {
// File []byte `json:"file"`
//}{}
//if err := c.ShouldBindJSON(&req); err != nil {
// logger.Error(err)
// app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
// return
//}
model.EsfLock.Lock()
defer model.EsfLock.Unlock()
file, header, err := c.Request.FormFile("file")
if err != nil {
logger.Error("form file err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
readAll, err := ioutil.ReadAll(file)
if err != nil {
logger.Error("read all err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
fmt.Println("header:", header.Filename)
//fmt.Println("readAll:", readAll)
// 导入商品自动添加分类
bCol, _, err := model.FileExcelReader([]byte(readAll), model.ErpCommodityFileExcelCols)
//bCol, err := model.FileExcelReader(req.File, model.ErpCommodityFileExcelCols, nil)
if err != nil {
logger.Error("file excel reader err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
fmt.Println("bCol", string(bCol))
var commodityFiles []model.ErpCommodityFileExcel
err = json.Unmarshal(bCol, &commodityFiles)
if err != nil {
logger.Error("erp commodity file excel unmarshal err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
if len(commodityFiles) != 0 {
commodityFiles = commodityFiles[1:]
}
model.ErpCommodityFileExcelListProcessing(commodityFiles)
commodities := make([]model.ErpCommodity, 0, len(commodityFiles))
begin := orm.Eloquent.Begin()
for i, _ := range commodityFiles {
commodities = append(commodities, commodityFiles[i].ErpCommodity)
err := begin.Create(&commodityFiles[i].ErpCommodity).Error
if err != nil {
begin.Rollback()
logger.Error("create commodity files err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
}
err = begin.Commit().Error
if err != nil {
begin.Rollback()
logger.Error("commit err:", err)
app.Error(c, http.StatusInternalServerError, err, "导入失败")
return
}
app.OK(c, commodities, "")
return
}
func BatchImportView(c *gin.Context) {
//req := struct {
// File []byte `json:"file"`
//}{}
//if err := c.ShouldBindJSON(&req); err != nil {
// logger.Error(err)
// app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
// return
//}
file, header, err := c.Request.FormFile("file")
if err != nil {
logger.Error("form file err:", err)
app.Error(c, http.StatusInternalServerError, err, "预览失败")
return
}
readAll, err := ioutil.ReadAll(file)
if err != nil {
logger.Error("read all err:", err)
app.Error(c, http.StatusInternalServerError, err, "预览失败")
return
}
fmt.Println("header:", header.Filename)
//fmt.Println("readAll:", readAll)
//colsMap := make([]map[string]interface{}, 0)
// 导入商品自动添加分类
_, colsMap, err := model.FileExcelReader([]byte(readAll), nil)
//_, err = model.FileExcelReader([]byte(readAll), model.ErpCommodityFileExcelCols, colsMap)
//bCol, err := model.FileExcelReader(req.File, model.ErpCommodityFileExcelCols, nil)
if err != nil {
logger.Error("file excel reader err:", err)
app.Error(c, http.StatusInternalServerError, err, "预览失败")
return
}
fmt.Println("colsMap:", colsMap)
if len(colsMap) != 0 {
colsMap = colsMap[1:]
}
//cols, err := json.Marshal(&colsMap)
//if err != nil {
// logger.Error("marshal err:", err)
// app.Error(c, http.StatusInternalServerError, err, "预览失败")
// return
//}
//fmt.Println("cols", string(cols))
// 加锁
//var commodityFiles []model.ErpCommodityFileExcel
//err = json.Unmarshal(bCol, &commodityFiles)
//if err != nil {
// logger.Error("erp commodity file excel unmarshal err:", err)
// app.Error(c, http.StatusInternalServerError, err, "导入失败")
// return
//}
//if len(commodityFiles) != 0 {
// commodityFiles = commodityFiles[1:]
//}
//model.ErpCommodityFileExcelListProcessing(commodityFiles)
//commodities := make([]model.ErpCommodity, 0, len(commodityFiles))
//begin := orm.Eloquent.Begin()
//for i, _ := range commodityFiles {
// commodities = append(commodities, commodityFiles[i].ErpCommodity)
// err := begin.Create(&commodityFiles[i].ErpCommodity).Error
// if err != nil {
// begin.Rollback()
// logger.Error("create commodity files err:", err)
// app.Error(c, http.StatusInternalServerError, err, "导入失败")
// return
// }
//}
//err = begin.Commit().Error
//if err != nil {
// begin.Rollback()
// logger.Error("commit err:", err)
// app.Error(c, http.StatusInternalServerError, err, "导入失败")
// return
//}
app.OK(c, &colsMap, "")
return
}
func ErpSupplierSave(c *gin.Context) {
req := struct {
Id uint32 `json:"id"`
Name string `json:"name" binding:"required"`
Contact string `json:"contact" binding:"required"`
Tel string `json:"tel" binding:"required"`
Address string `json:"address" binding:"required"`
OpeningBank string `json:"opening_bank" binding:"required"`
BankAccount string `json:"bank_account" binding:"required"`
PaymentCycle uint32 `json:"payment_cycle" binding:"required"`
TaxNumber string `json:"tax_number"`
StoreIds string `json:"store_ids"`
Landline string `json:"landline"`
Email string `json:"email"`
CompanyWebsite string `json:"company_website"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
supplier := &model.ErpSupplier{
Name: req.Name,
Contact: req.Contact,
Tel: req.Tel,
Address: req.Address,
OpeningBank: req.OpeningBank,
BankAccount: req.BankAccount,
PaymentCycle: req.PaymentCycle,
TaxNumber: req.TaxNumber,
StoreIds: req.StoreIds,
Landline: req.Landline,
Email: req.Email,
CompanyWebsite: req.CompanyWebsite,
}
supplier.ID = req.Id
err := orm.Eloquent.Save(supplier).Error
if err != nil {
logger.Error("create commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "操作失败")
return
}
if supplier.Number == "" {
err = orm.Eloquent.Table("erp_supplier").Where("id=?", supplier.ID).
Update("number", fmt.Sprintf("%03d", supplier.ID)).Error
if err != nil {
logger.Error("err:", err)
app.Error(c, http.StatusInternalServerError, err, "操作失败")
return
}
}
var logging model.Logging
if req.Id == 0 {
logging = model.Logging{
//Machine: "",
//StoreId: 0,
//StoreName: "",
//OperatorUid: 0,
//Operator: "",
Function: "供应商资料",
Event: model.LoggingEventCreateSupplier,
EventName: "新建供应商",
//Ip: "",
}
} else {
logging = model.Logging{
//Machine: "",
//StoreId: 0,
//StoreName: "",
//OperatorUid: 0,
//Operator: "",
Function: "供应商资料",
Event: model.LoggingEventEditSupplier,
EventName: "编辑供应商资料",
//Ip: "",
}
}
logging.Create(c)
app.OK(c, supplier, "")
return
}
func ErpSupplierList(c *gin.Context) {
req := &struct {
Number string `json:"number"`
Name string `json:"name"`
PageNum int `json:"page_num"`
PageSize int `json:"page_size"`
IsExport uint32 `json:"is_export"` // 1-导出
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
resp := &model.ErpSupplierListResp{
PageNum: req.PageNum,
PageSize: req.PageSize,
}
page := req.PageNum - 1
if page < 0 {
page = 0
}
if req.PageSize == 0 {
req.PageSize = 10
}
qs := orm.Eloquent.Table("erp_supplier")
if req.Number != "" {
qs = qs.Where("number=?", req.Number)
}
if req.Name != "" {
qs = qs.Where("name LIKE ?", req.Name)
}
var count int64
err := qs.Count(&count).Error
if err != nil {
logger.Error("count err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
resp.Total = int(count)/req.PageSize + 1
var suppliers []model.ErpSupplier
if req.IsExport == 1 {
err = qs.Order("id DESC").Find(&suppliers).Error
if err != nil && err != model.RecordNotFound {
logger.Error("dailys err:", err)
app.Error(c, http.StatusInternalServerError, err, "导出失败")
return
}
listExport, err := model.ErpSupplierListExport(suppliers)
if err != nil {
logger.Error("list export err:", err)
app.Error(c, http.StatusInternalServerError, err, "导出失败")
return
}
resp.ExportUrl = listExport
} else {
err = qs.Order("id DESC").Offset(page * req.PageSize).Limit(req.PageSize).Find(&suppliers).Error
if err != nil && err != model.RecordNotFound {
logger.Error("erp commodity list err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
//rsp.List = list
resp.List = suppliers
}
app.OK(c, resp, "")
return
}
func ErpSupplierDetail(c *gin.Context) {
req := struct {
ErpSupplierId uint32 `json:"erp_supplier_id" binding:"required"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
var supplier model.ErpSupplier
err := orm.Eloquent.Table("erp_supplier").Where("id=?", req.ErpSupplierId).Find(&supplier).Error
if err != nil {
logger.Error("erp commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
app.OK(c, supplier, "")
return
}
func ErpSupplierDel(c *gin.Context) {
req := struct {
ErpSupplierId uint32 `json:"erp_supplier_id" binding:"required"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
err := orm.Eloquent.Table("erp_supplier").Where("id=?", req.ErpSupplierId).Delete(&model.ErpSupplier{}).Error
if err != nil {
logger.Error("erp commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
app.OK(c, nil, "")
return
}
func ErpCategoryCreate(c *gin.Context) {
req := struct {
Name string `json:"name" binding:"required"`
Pid uint32 `json:"pid"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
category, err := model.ErpCategoryCreate(req.Name, req.Pid)
if err != nil {
logger.Error("category create err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
app.OK(c, category, "")
return
}
func ErpCategoryList(c *gin.Context) {
req := &model.ErpCategoryListReq{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
resp, err := req.List()
if err != nil {
logger.Error("erp commodity list err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
app.OK(c, resp, "")
return
}
func ErpCategoryDetail(c *gin.Context) {
req := struct {
ErpCategoryId uint32 `json:"erp_category_id" binding:"required"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
var category model.ErpCategory
err := orm.Eloquent.Table("erp_category").Where("id=?", req.ErpCategoryId).Find(&category).Error
if err != nil {
logger.Error("erp commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
app.OK(c, category, "")
return
}
func ErpCategoryDel(c *gin.Context) {
req := struct {
ErpCategoryId uint32 `json:"erp_category_id" binding:"required"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
err := orm.Eloquent.Where("id=?", req.ErpCategoryId).Delete(&model.ErpCategory{}).Error
if err != nil {
logger.Error("erp commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "删除失败")
return
}
app.OK(c, nil, "")
return
}
func ErpCategoryEdit(c *gin.Context) {
req := struct {
Id uint32 `json:"id" binding:"required"`
Name string `json:"name"`
State uint32 `json:"state"`
Pid uint32 `json:"pid"`
Level uint32 `json:"level"` // 分类层级
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
category, err := model.GetErpCategory(req.Id)
if err != nil {
logger.Error("get erp category err:", err)
app.Error(c, http.StatusInternalServerError, err, "操作失败")
return
}
if req.Name != "" {
var precede string
if category.Level == 1 {
precede = fmt.Sprintf("%03d", category.FullNum/1000)
} else {
precede = fmt.Sprintf("%03d-%03d", category.FullNum/1000, category.FullNum%1000)
}
if strings.HasPrefix(req.Name, precede) {
category.Name = req.Name
} else {
category.Name = precede + req.Name
}
}
if req.State != 0 {
category.State = req.State
}
if req.Pid != 0 {
category.Pid = req.Pid
}
if req.Level != 0 {
category.Level = req.Level
if category.Level == 1 {
category.Pid = 0
}
}
err = orm.Eloquent.Save(category).Error
if err != nil {
logger.Error("create commodity err:", err)
app.Error(c, http.StatusInternalServerError, err, "操作失败")
return
}
app.OK(c, category, "")
return
}
func ErpCashierStoreCreate(c *gin.Context) {
req := struct {
Name string `json:"name" binding:"required"`
BankName string `json:"bank_name"`
BankAccount string `json:"bank_account"`
StoreNames []uint32 `json:"store_name"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
exist, err := model.QueryRecordExist(fmt.Sprintf("SELECT * FROM erp_cashier WHERE `name`='%s'", req.Name))
if err != nil {
logger.Error("exist erp cashier err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
var cashier model.ErpCashier
if !exist {
//logger.Error("")
//app.Error(c, http.StatusInternalServerError, err, "已存在")
//return
cashier = model.ErpCashier{
Name: req.Name,
BankName: req.BankName,
BankAccount: req.BankAccount,
State: 1,
Remark: "",
}
err = orm.Eloquent.Create(&cashier).Error
if err != nil {
logger.Error("cashier err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
} else {
err = orm.Eloquent.Table("erp_cashier").Where("name=?", req.Name).Find(&cashier).Error
if err != nil {
logger.Error("erp cashier err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
}
//cashier := &model.ErpCashier{
// Name: req.Name,
// BankName: req.BankName,
// BankAccount: req.BankAccount,
// State: 1,
// Remark: "",
//}
//err = orm.Eloquent.Create(cashier).Error
//if err != nil {
// logger.Error("cashier err:", err)
// app.Error(c, http.StatusInternalServerError, err, "创建失败")
// return
//}
if len(req.StoreNames) > 0 {
var stores []model.Store
err := orm.Eloquent.Table("store").Where("id IN (?)", req.StoreNames).Find(&stores).Error
if err != nil {
logger.Error("stores err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
//fmt.Println("stores", stores)
storeMap := make(map[uint32]string)
for i, _ := range stores {
storeMap[stores[i].ID] = stores[i].Name
}
begin := orm.Eloquent.Begin()
for i, _ := range req.StoreNames {
v, ok := storeMap[req.StoreNames[i]]
storeCategory := &model.ErpStoreCashier{
ErpCashierId: cashier.ID,
Name: req.Name,
BankName: req.BankName,
BankAccount: req.BankAccount,
StoreId: req.StoreNames[i],
State: 1,
Remark: "",
}
if ok {
storeCategory.StoreName = v
//fmt.Println("StoreName", storeCategory.StoreName)
}
//fmt.Println("storeCategory", storeCategory)
err := begin.Create(storeCategory).Error
if err != nil {
begin.Rollback()
logger.Error("store category err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
}
err = begin.Commit().Error
if err != nil {
begin.Rollback()
logger.Error("commit err:", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
}
app.OK(c, nil, "")
return
}
func ErpCashierStoreBind(c *gin.Context) {
req := struct {
ErpCashierIds []uint32 `json:"erp_cashier_ids"`
StoreId uint32 `json:"store_id"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
cashierMap, err := model.GetErpCashierMap(req.ErpCashierIds)
if err != nil {
logger.Error("get erp cashier map err:", err)
app.Error(c, http.StatusInternalServerError, err, "绑定失败")
return
}
begin := orm.Eloquent.Begin()
if len(req.ErpCashierIds) > 0 {
for i, _ := range req.ErpCashierIds {
v, ok := cashierMap[req.ErpCashierIds[i]]
if ok && v != nil {
storeCategory := &model.ErpStoreCashier{
ErpCashierId: v.ID,
Name: v.Name,
BankName: v.BankName,
BankAccount: v.BankAccount,
StoreId: req.StoreId,
State: 1,
Remark: "",
}
err := begin.Create(storeCategory).Error
if err != nil {
begin.Rollback()
logger.Error("store category err:", err)
app.Error(c, http.StatusInternalServerError, err, "绑定失败")
return
}
}
}
}
err = begin.Commit().Error
if err != nil {
begin.Rollback()
logger.Error("commit err:", err)
app.Error(c, http.StatusInternalServerError, err, "绑定失败")
return
}
app.OK(c, nil, "")
return
}
func ErpCashierStoreDel(c *gin.Context) {
req := struct {
ErpStoreCashierId uint32 `json:"erp_store_cashier_id"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
err := orm.Eloquent.Table("erp_store_cashier").Where("id=?", req.ErpStoreCashierId).Delete(&model.ErpStoreCashier{}).Error
if err != nil {
logger.Error("erp store cashier err:", err)
app.Error(c, http.StatusInternalServerError, err, "操作失败")
return
}
app.OK(c, nil, "")
return
}
func ErpCashierStoreList(c *gin.Context) {
req := struct {
StoreId uint32 `json:"store_id"`
PageNum int `json:"page_num"`
PageSize int `json:"page_size"`
IsExport uint32 `json:"is_export"` // 1-导出
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
//sysUser, err := model.GetSysUserByCtx(c)
//if err != nil {
// logger.Error("sys user err:", err)
// app.Error(c, http.StatusUnauthorized, errors.New("para err"), "参数错误")
// return
//}
//req.StoreId = sysUser.StoreId
resp := &model.ErpCashierStoreListResp{
PageNum: req.PageNum,
PageSize: req.PageSize,
}
page := req.PageNum - 1
if page < 0 {
page = 0
}
if req.PageSize == 0 {
req.PageSize = 10
}
qs := orm.Eloquent.Table("erp_store_cashier")
if req.StoreId != 0 {
qs = qs.Where("store_id=?", req.StoreId)
}
var count int64
err := qs.Count(&count).Error
if err != nil {
logger.Error("count err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
//total := int(count)/req.PageSize + 1
resp.Total = int(count)/req.PageSize + 1
var categories []model.ErpStoreCashier
if req.IsExport == 1 {
err = qs.Order("id DESC").Find(&categories).Error
if err != nil && err != model.RecordNotFound {
logger.Error("dailys err:", err)
app.Error(c, http.StatusInternalServerError, err, "导出失败")
return
}
listExport, err := model.ErpStoreCashierListExport(categories)
if err != nil {
logger.Error("list export err:", err)
app.Error(c, http.StatusInternalServerError, err, "导出失败")
return
}
resp.ExportUrl = listExport
} else {
err = qs.Order("id DESC").Offset(page * req.PageSize).Limit(req.PageSize).Find(&categories).Error
if err != nil && err != model.RecordNotFound {
logger.Error("erp commodity list err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
resp.List = categories
}
//resp.List = categories
//ret := map[string]interface{}{
// "total": total,
// "page_num": req.PageNum,
// "page_size": req.PageSize,
// "list": categories,
//}
app.OK(c, resp, "")
return
}
func ErpCashierList(c *gin.Context) {
req := struct {
Type uint32 `json:"type"`
PageNum int `json:"page_num"`
PageSize int `json:"page_size"`
}{}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(err)
app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
return
}
resp := &model.ErpCashierListResp{
PageNum: req.PageNum,
PageSize: req.PageSize,
}
page := req.PageNum - 1
if page < 0 {
page = 0
}
if req.PageSize == 0 {
req.PageSize = 10
}
qs := orm.Eloquent.Table("erp_cashier")
if req.Type != 0 {
qs = qs.Where("type=?", req.Type)
}
var count int64
err := qs.Count(&count).Error
if err != nil {
logger.Error("count err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
//total := int(count)/req.PageSize + 1
resp.Total = int(count)/req.PageSize + 1
var categories []model.ErpCashier
err = qs.Order("id DESC").Offset(page * req.PageSize).Limit(req.PageSize).Find(&categories).Error
if err != nil && err != model.RecordNotFound {
logger.Error("erp commodity list err:", err)
app.Error(c, http.StatusInternalServerError, err, "获取失败")
return
}
resp.List = categories
//ret := map[string]interface{}{
// "total": total,
// "page_num": req.PageNum,
// "page_size": req.PageSize,
// "list": categories,
//}
app.OK(c, resp, "")
return
}