From 3c2ab50d6b1ac67da76043b1f7408b808a774de3 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期三, 16 八月 2023 11:54:37 +0800
Subject: [PATCH] 销售退货单批量删除接口

---
 api/v1/salesRefund.go        |   42 +++++++
 model/salesReturn.go         |    2 
 model/salesRefund.go         |   22 ++++
 model/index.go               |    2 
 service/salesRefund.go       |   96 ++++++++++++++++++-
 model/request/salesRefund.go |    4 
 docs/swagger.yaml            |   27 ++++
 docs/docs.go                 |   38 ++++++
 docs/swagger.json            |   38 ++++++
 router/salesRefund.go        |    9 +
 10 files changed, 249 insertions(+), 31 deletions(-)

diff --git a/api/v1/salesRefund.go b/api/v1/salesRefund.go
index fcc02e1..866b9dc 100644
--- a/api/v1/salesRefund.go
+++ b/api/v1/salesRefund.go
@@ -8,13 +8,14 @@
 	"aps_crm/pkg/ecode"
 	"github.com/gin-gonic/gin"
 	"strconv"
+	"strings"
 )
 
 type SalesRefundApi struct{}
 
 // Add
 //
-//	@Tags		SalesRefund
+//	@Tags		閿�鍞��娆惧崟
 //	@Summary	娣诲姞閿�鍞��娆�
 //	@Produce	application/json
 //	@Param		object	body		request.AddSalesRefundRequest	true	"鏌ヨ鍙傛暟"
@@ -44,7 +45,7 @@
 
 // Delete
 //
-//	@Tags		SalesRefund
+//	@Tags		閿�鍞��娆惧崟
 //	@Summary	鍒犻櫎閿�鍞��娆�
 //	@Produce	application/json
 //	@Param		id	path		int	true	"鏌ヨ鍙傛暟"
@@ -66,9 +67,40 @@
 	ctx.Ok()
 }
 
+// BatchDelete
+// @Tags	閿�鍞��娆惧崟
+// @Summary	鎵归噺鍒犻櫎閿�鍞��娆惧崟
+// @Produce	application/json
+// @Param	object	body request.CommonIds	true "鍙傛暟"
+// @Success	200	{object}	contextx.Response{}
+// @Router		/api/salesRefund/delete [delete]
+func (s *SalesRefundApi) BatchDelete(c *gin.Context) {
+	var params request.CommonIds
+	ctx, ok := contextx.NewContext(c, &params)
+	if !ok {
+		return
+	}
+
+	failIds, _ := salesRefundService.BatchDeleteSalesRefund(params.Ids)
+	if len(failIds) == 0 {
+		ctx.Ok()
+		return
+	}
+	salesReturns, code := salesRefundService.GetSalesRefundListByIds(failIds)
+	if code != ecode.OK {
+		ctx.Ok()
+		return
+	}
+	var numbers []string
+	for _, salesReturn := range salesReturns {
+		numbers = append(numbers, salesReturn.Number)
+	}
+	ctx.FailWithMsg(ecode.DBErr, strings.Join(numbers, ",")+"鍒犻櫎澶辫触")
+}
+
 // Update
 //
-//	@Tags		SalesRefund
+//	@Tags		閿�鍞��娆惧崟
 //	@Summary	鏇存柊閿�鍞��娆�
 //	@Produce	application/json
 //	@Param		object	body		request.UpdateSalesRefundRequest	true	"鏌ヨ鍙傛暟"
@@ -108,13 +140,15 @@
 	salesRefundRes.IsInvoice = salesRefund.IsInvoice
 	salesRefundRes.Reason = salesRefund.Reason
 	salesRefundRes.Products = salesRefund.Products
+	salesRefundRes.SourceType = salesRefund.SourceType
+	salesRefundRes.SourceId = salesRefund.SourceId
 
 	return ecode.OK, salesRefundRes
 }
 
 // List
 //
-//	@Tags		SalesRefund
+//	@Tags		閿�鍞��娆惧崟
 //	@Summary	閿�鍞��娆惧崟鍒楄〃
 //	@Produce	application/json
 //	@Param		object	body		request.GetSalesRefundList	true	"鍙傛暟"
diff --git a/docs/docs.go b/docs/docs.go
index 3cc0e8f..e34db9e 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -7075,7 +7075,7 @@
                     "application/json"
                 ],
                 "tags": [
-                    "SalesRefund"
+                    "閿�鍞��娆惧崟"
                 ],
                 "summary": "娣诲姞閿�鍞��娆�",
                 "parameters": [
@@ -7099,13 +7099,43 @@
                 }
             }
         },
+        "/api/salesRefund/delete": {
+            "delete": {
+                "produces": [
+                    "application/json"
+                ],
+                "tags": [
+                    "閿�鍞��娆惧崟"
+                ],
+                "summary": "鎵归噺鍒犻櫎閿�鍞��娆惧崟",
+                "parameters": [
+                    {
+                        "description": "鍙傛暟",
+                        "name": "object",
+                        "in": "body",
+                        "required": true,
+                        "schema": {
+                            "$ref": "#/definitions/request.CommonIds"
+                        }
+                    }
+                ],
+                "responses": {
+                    "200": {
+                        "description": "OK",
+                        "schema": {
+                            "$ref": "#/definitions/contextx.Response"
+                        }
+                    }
+                }
+            }
+        },
         "/api/salesRefund/delete/{id}": {
             "delete": {
                 "produces": [
                     "application/json"
                 ],
                 "tags": [
-                    "SalesRefund"
+                    "閿�鍞��娆惧崟"
                 ],
                 "summary": "鍒犻櫎閿�鍞��娆�",
                 "parameters": [
@@ -7133,7 +7163,7 @@
                     "application/json"
                 ],
                 "tags": [
-                    "SalesRefund"
+                    "閿�鍞��娆惧崟"
                 ],
                 "summary": "閿�鍞��娆惧崟鍒楄〃",
                 "parameters": [
@@ -7175,7 +7205,7 @@
                     "application/json"
                 ],
                 "tags": [
-                    "SalesRefund"
+                    "閿�鍞��娆惧崟"
                 ],
                 "summary": "鏇存柊閿�鍞��娆�",
                 "parameters": [
diff --git a/docs/swagger.json b/docs/swagger.json
index ce9b963..c945592 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -7063,7 +7063,7 @@
                     "application/json"
                 ],
                 "tags": [
-                    "SalesRefund"
+                    "閿�鍞��娆惧崟"
                 ],
                 "summary": "娣诲姞閿�鍞��娆�",
                 "parameters": [
@@ -7087,13 +7087,43 @@
                 }
             }
         },
+        "/api/salesRefund/delete": {
+            "delete": {
+                "produces": [
+                    "application/json"
+                ],
+                "tags": [
+                    "閿�鍞��娆惧崟"
+                ],
+                "summary": "鎵归噺鍒犻櫎閿�鍞��娆惧崟",
+                "parameters": [
+                    {
+                        "description": "鍙傛暟",
+                        "name": "object",
+                        "in": "body",
+                        "required": true,
+                        "schema": {
+                            "$ref": "#/definitions/request.CommonIds"
+                        }
+                    }
+                ],
+                "responses": {
+                    "200": {
+                        "description": "OK",
+                        "schema": {
+                            "$ref": "#/definitions/contextx.Response"
+                        }
+                    }
+                }
+            }
+        },
         "/api/salesRefund/delete/{id}": {
             "delete": {
                 "produces": [
                     "application/json"
                 ],
                 "tags": [
-                    "SalesRefund"
+                    "閿�鍞��娆惧崟"
                 ],
                 "summary": "鍒犻櫎閿�鍞��娆�",
                 "parameters": [
@@ -7121,7 +7151,7 @@
                     "application/json"
                 ],
                 "tags": [
-                    "SalesRefund"
+                    "閿�鍞��娆惧崟"
                 ],
                 "summary": "閿�鍞��娆惧崟鍒楄〃",
                 "parameters": [
@@ -7163,7 +7193,7 @@
                     "application/json"
                 ],
                 "tags": [
-                    "SalesRefund"
+                    "閿�鍞��娆惧崟"
                 ],
                 "summary": "鏇存柊閿�鍞��娆�",
                 "parameters": [
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index e1cb595..f631977 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -10307,7 +10307,26 @@
             $ref: '#/definitions/contextx.Response'
       summary: 娣诲姞閿�鍞��娆�
       tags:
-      - SalesRefund
+      - 閿�鍞��娆惧崟
+  /api/salesRefund/delete:
+    delete:
+      parameters:
+      - description: 鍙傛暟
+        in: body
+        name: object
+        required: true
+        schema:
+          $ref: '#/definitions/request.CommonIds'
+      produces:
+      - application/json
+      responses:
+        "200":
+          description: OK
+          schema:
+            $ref: '#/definitions/contextx.Response'
+      summary: 鎵归噺鍒犻櫎閿�鍞��娆惧崟
+      tags:
+      - 閿�鍞��娆惧崟
   /api/salesRefund/delete/{id}:
     delete:
       parameters:
@@ -10325,7 +10344,7 @@
             $ref: '#/definitions/contextx.Response'
       summary: 鍒犻櫎閿�鍞��娆�
       tags:
-      - SalesRefund
+      - 閿�鍞��娆惧崟
   /api/salesRefund/list:
     post:
       parameters:
@@ -10349,7 +10368,7 @@
               type: object
       summary: 閿�鍞��娆惧崟鍒楄〃
       tags:
-      - SalesRefund
+      - 閿�鍞��娆惧崟
   /api/salesRefund/update:
     put:
       parameters:
@@ -10368,7 +10387,7 @@
             $ref: '#/definitions/contextx.Response'
       summary: 鏇存柊閿�鍞��娆�
       tags:
-      - SalesRefund
+      - 閿�鍞��娆惧崟
   /api/salesReturn/add:
     post:
       parameters:
diff --git a/model/index.go b/model/index.go
index 340ce2b..8ea162c 100644
--- a/model/index.go
+++ b/model/index.go
@@ -85,6 +85,8 @@
 		Currency{},
 		CollectionProjection{},
 		ContactInformation{},
+		SalesReturn{},
+		SalesRefund{},
 	)
 	return err
 }
diff --git a/model/request/salesRefund.go b/model/request/salesRefund.go
index d8fd5b5..0f132db 100644
--- a/model/request/salesRefund.go
+++ b/model/request/salesRefund.go
@@ -13,8 +13,8 @@
 	ClientId      int                       `json:"clientId"`
 	Number        string                    `json:"number"`
 	MemberId      int                       `json:"memberId"`
-	SourceType    constvar.RefundSourceType `gorm:"column:source_type;type:int;not null;default 0;comment:鏉ユ簮绫诲瀷锛�1閿�鍞槑缁嗗崟2鏈嶅姟鍚堝悓3閿�鍞彂绁�4鏀舵璁″垝5鍑哄簱鍗曪級" json:"sourceType"` // 鏉ユ簮绫诲瀷锛�1閿�鍞槑缁嗗崟2鏈嶅姟鍚堝悓3閿�鍞彂绁�4鏀舵璁″垝5鍑哄簱鍗曪級
-	SourceId      int                       `gorm:"column:source_id;type:int;not null;default 0;comment:婧愬崟id " json:"sourceId"`                               // 婧愬崟id
+	SourceType    constvar.RefundSourceType `gorm:"column:source_type;type:int;not null;default 0;comment:鏉ユ簮绫诲瀷锛�1閿�鍞��娆剧殑锛�" json:"sourceType" binding:"required"` // 鏉ユ簮绫诲瀷锛�1閿�鍞��娆惧崟锛�
+	SourceId      int                       `gorm:"column:source_id;type:int;not null;default 0;comment:婧愬崟id " json:"sourceId"  binding:"required"`           // 婧愬崟id
 	RefundDate    string                    `json:"refundDate"`
 	PaymentTypeId int                       `gorm:"column:payment_type_id;type:int;not null;default 0;comment:鏀舵鏂瑰紡ID" json:"paymentTypeId"` // 鏀舵鏂瑰紡ID
 	BankAccountId int                       `gorm:"column:bank_account_id;type:int;not null;default 0;comment:璐︽埛id" json:"bankAccountId"`   // 璐︽埛id
diff --git a/model/salesRefund.go b/model/salesRefund.go
index 2a3fe92..233aa72 100644
--- a/model/salesRefund.go
+++ b/model/salesRefund.go
@@ -19,7 +19,7 @@
 		SourceId      int                       `gorm:"column:source_id;type:int;not null;default 0;comment:婧愬崟id " json:"sourceId"`           // 婧愬崟id
 		MemberId      int                       `json:"memberId" gorm:"column:member_id;type:int;comment:璐熻矗浜篿d"`
 		Member        User                      `json:"member" gorm:"foreignKey:MemberId"`
-		RefundDate    string                    `json:"refundDate" gorm:"column:refund_date;type:datetime;comment:閫�娆炬棩鏈�"`
+		RefundDate    string                    `json:"refundDate" gorm:"column:refund_date;type:varchar(255);comment:閫�娆炬棩鏈�"`
 		PaymentTypeId int                       `gorm:"column:payment_type_id;type:int;not null;default 0;comment:鏀舵鏂瑰紡ID" json:"paymentTypeId"` // 鏀舵鏂瑰紡ID
 		PaymentType   PaymentType               `gorm:"foreignKey:PaymentTypeId" json:"paymentType"`
 		BankAccountId int                       `gorm:"column:bank_account_id;type:int;not null;default 0;comment:璐︽埛id" json:"bankAccountId"` // 璐︽埛id
@@ -40,6 +40,7 @@
 		PageNum     int
 		PageSize    int
 		Preload     bool
+		Ids         []int
 	}
 )
 
@@ -57,6 +58,10 @@
 	var db = slf.Orm.Model(&SalesRefund{})
 	if slf.Id != 0 {
 		db = db.Where("id = ?", slf.Id)
+	}
+
+	if len(slf.Ids) != 0 {
+		db = db.Where("id in ?", slf.Ids)
 	}
 
 	if slf.Preload {
@@ -107,11 +112,19 @@
 	return db.Updates(record).Error
 }
 
-func (slf *SalesRefundSearch) Find() (*SalesRefund, error) {
+func (slf *SalesRefundSearch) First() (*SalesRefund, error) {
 	var db = slf.build()
 	var record = new(SalesRefund)
 	err := db.First(record).Error
 	return record, err
+}
+
+func (slf *SalesRefundSearch) Find() ([]*SalesRefund, error) {
+	var db = slf.build()
+	var records = make([]*SalesRefund, 0)
+
+	err := db.Find(&records).Error
+	return records, err
 }
 
 func (slf *SalesRefundSearch) FindAll() ([]*SalesRefund, int64, error) {
@@ -138,6 +151,11 @@
 	return slf
 }
 
+func (slf *SalesRefundSearch) SetIds(id []int) *SalesRefundSearch {
+	slf.Ids = id
+	return slf
+}
+
 func (slf *SalesRefundSearch) SetSourceType(sourceType constvar.RefundSourceType) *SalesRefundSearch {
 	slf.SourceType = sourceType
 	return slf
diff --git a/model/salesReturn.go b/model/salesReturn.go
index 8012443..5149d5f 100644
--- a/model/salesReturn.go
+++ b/model/salesReturn.go
@@ -20,7 +20,7 @@
 		Repository          string                         `json:"repository" gorm:"column:repository;type:varchar(255);comment:浠撳簱"`
 		MemberId            int                            `json:"memberId" gorm:"column:member_id;type:int;comment:璐熻矗浜篿d"`
 		Member              User                           `json:"Member"  gorm:"foreignKey:MemberId"`
-		ReturnDate          string                         `json:"returnDate" gorm:"column:return_date;type:datetime(3);comment:閫�璐ф棩鏈�"`                     //閫�璐ф棩鏈�
+		ReturnDate          string                         `json:"returnDate" gorm:"column:return_date;type:varchar(255);comment:閫�璐ф棩鏈�"`                    //閫�璐ф棩鏈�
 		SalesReturnStatusId int                            `json:"salesReturnStatusId" gorm:"column:sales_return_status;type:int;comment:閫�璐х姸鎬�"`            //閫�璐х姸鎬乮d
 		SalesReturnStatus   SalesReturnStatus              `json:"SalesReturnStatus" gorm:"foreignKey:SalesReturnStatusId"`                                //閫�璐х姸鎬�
 		CreatorId           int                            `json:"-" gorm:"column:creator_id;type:int;comment:鍒涘缓浜篿d"`                                      //鍒涘缓浜篒D
diff --git a/router/salesRefund.go b/router/salesRefund.go
index c017d70..3410876 100644
--- a/router/salesRefund.go
+++ b/router/salesRefund.go
@@ -11,9 +11,10 @@
 	salesRefundRouter := router.Group("salesRefund")
 	salesRefundApi := v1.ApiGroup.SalesRefundApi
 	{
-		salesRefundRouter.POST("add", salesRefundApi.Add)             // 娣诲姞閿�鍞��娆�
-		salesRefundRouter.DELETE("delete/:id", salesRefundApi.Delete) // 鍒犻櫎閿�鍞��娆�
-		salesRefundRouter.PUT("update", salesRefundApi.Update)        // 鏇存柊閿�鍞��娆�
+		salesRefundRouter.POST("add", salesRefundApi.Add)              // 娣诲姞閿�鍞��娆�
+		salesRefundRouter.DELETE("delete/:id", salesRefundApi.Delete)  // 鍒犻櫎閿�鍞��娆�
+		salesRefundRouter.DELETE("delete", salesRefundApi.BatchDelete) // 鎵归噺鍒犻櫎閿�鍞��娆惧崟
+		salesRefundRouter.PUT("update", salesRefundApi.Update)         // 鏇存柊閿�鍞��娆�
 		salesRefundRouter.POST("list", salesRefundApi.List)            // 鑾峰彇閿�鍞��娆惧崟鍒楄〃
 	}
-}
\ No newline at end of file
+}
diff --git a/service/salesRefund.go b/service/salesRefund.go
index 1c90148..cf548d9 100644
--- a/service/salesRefund.go
+++ b/service/salesRefund.go
@@ -4,6 +4,8 @@
 	"aps_crm/constvar"
 	"aps_crm/model"
 	"aps_crm/pkg/ecode"
+	"github.com/shopspring/decimal"
+	"gorm.io/gorm"
 )
 
 type SalesRefundService struct{}
@@ -17,8 +19,25 @@
 	if code := CheckProduct(salesReturnRecord.Products, salesRefund.Products); code != ecode.OK {
 		return code
 	}
+	var amount decimal.Decimal
+	for _, product := range salesRefund.Products {
+		amount = amount.Add(product.Amount.Mul(product.Price))
+	}
 
-	err = model.NewSalesRefundSearch().Create(salesRefund)
+	err = model.WithTransaction(func(db *gorm.DB) error {
+		err = model.NewSalesRefundSearch().Create(salesRefund)
+		if err != nil {
+			return err
+		}
+		salesReturnRecord.AmountHasRefund = salesReturnRecord.AmountHasRefund.Add(amount).Round(2)
+		salesReturnRecord.AmountShouldRefund = salesReturnRecord.AmountTotal.Sub(salesReturnRecord.AmountHasRefund).Round(2)
+		err = model.NewSalesReturnSearch().SetId(salesRefund.SourceId).Update(salesReturnRecord)
+		if err != nil {
+			return err
+		}
+		return nil
+	})
+
 	if err != nil {
 		return ecode.SalesRefundExist
 	}
@@ -42,22 +61,54 @@
 	return ecode.OK
 }
 
-func (SalesRefundService) DeleteSalesRefund(id int) int {
-	_, err := model.NewSalesRefundSearch().SetId(id).Find()
+func (slf SalesRefundService) DeleteSalesRefund(id int) int {
+	refund, err := model.NewSalesRefundSearch().SetId(id).First()
 	if err != nil {
 		return ecode.SalesRefundNotExist
 	}
+	salesReturnRecord, err := model.NewSalesReturnSearch().SetId(refund.SourceId).SetPreload(true).First()
+	if err != nil {
+		return ecode.SalesReturnNotExist
+	}
 
-	err = model.NewSalesRefundSearch().SetId(id).Delete()
+	var amount decimal.Decimal
+	for _, product := range refund.Products {
+		amount = amount.Add(product.Amount.Mul(product.Price))
+	}
+
+	err = model.WithTransaction(func(db *gorm.DB) error {
+		err = model.NewSalesRefundSearch().SetId(id).Delete()
+		if err != nil {
+			return err
+		}
+		salesReturnRecord.AmountHasRefund = salesReturnRecord.AmountHasRefund.Sub(amount).Round(2)
+		salesReturnRecord.AmountShouldRefund = salesReturnRecord.AmountTotal.Sub(salesReturnRecord.AmountHasRefund).Round(2)
+		err = model.NewSalesReturnSearch().SetId(refund.SourceId).Update(salesReturnRecord)
+		if err != nil {
+			return err
+		}
+		return nil
+	})
+
 	if err != nil {
 		return ecode.SalesRefundNotExist
 	}
 	return ecode.OK
 }
 
+func (slf SalesRefundService) BatchDeleteSalesRefund(ids []int) (failIds []int, code int) {
+	for _, id := range ids {
+		code = slf.DeleteSalesRefund(id)
+		if code != ecode.OK {
+			failIds = append(failIds, id)
+		}
+	}
+	return failIds, code
+}
+
 func (SalesRefundService) UpdateSalesRefund(salesRefund *model.SalesRefund) int {
 	// check salesRefund exist
-	_, err := model.NewSalesRefundSearch().SetId(salesRefund.Id).Find()
+	oldRefund, err := model.NewSalesRefundSearch().SetId(salesRefund.Id).First()
 	if err != nil {
 		return ecode.SalesRefundNotExist
 	}
@@ -71,7 +122,29 @@
 		return code
 	}
 
-	err = model.NewSalesRefundSearch().SetId(salesRefund.Id).Update(salesRefund)
+	var diffAmount decimal.Decimal
+
+	for _, product := range salesRefund.Products {
+		diffAmount = diffAmount.Add(product.Amount.Mul(product.Price))
+	}
+	for _, product := range oldRefund.Products {
+		diffAmount = diffAmount.Sub(product.Amount.Mul(product.Price))
+	}
+
+	err = model.WithTransaction(func(db *gorm.DB) error {
+		err = model.NewSalesRefundSearch().SetId(salesRefund.Id).Update(salesRefund)
+		if err != nil {
+			return err
+		}
+		salesReturnRecord.AmountHasRefund = salesReturnRecord.AmountHasRefund.Sub(diffAmount).Round(2)
+		salesReturnRecord.AmountShouldRefund = salesReturnRecord.AmountTotal.Sub(salesReturnRecord.AmountHasRefund).Round(2)
+		err = model.NewSalesReturnSearch().SetId(salesRefund.SourceId).Update(salesReturnRecord)
+		if err != nil {
+			return err
+		}
+		return nil
+	})
+
 	if err != nil {
 		return ecode.SalesRefundSetErr
 	}
@@ -91,3 +164,14 @@
 	}
 	return contacts, total, ecode.OK
 }
+
+func (SalesRefundService) GetSalesRefundListByIds(ids []int) ([]*model.SalesRefund, int) {
+	// get contact list
+	salesRefunds, err := model.NewSalesRefundSearch().
+		SetIds(ids).
+		Find()
+	if err != nil {
+		return nil, ecode.SalesReturnListErr
+	}
+	return salesRefunds, ecode.OK
+}

--
Gitblit v1.8.0