Browse Source

add:退货入库、退货出库

zoie 1 year ago
parent
commit
dfd3cbfab7

+ 15 - 16
conf/app.conf

@@ -6,19 +6,19 @@ copyrequestbody = true
 EnableDocs = true
 
 # 数据库配置(Mysql)
-# mysqlUrlPort = "192.168.11.77:3306"
-# mysqlDB = "medical_erp"
-# mysqlUser = "medical_erp"
-# mysqlPass= "XMzTDthD4By3ArjG"
-# mysqlMaxConns = 100
-# MysqlMaxOpen = 200
-# 数据库配置(Mysql)
-mysqlUrlPort = "127.0.0.1:40306"
-mysqlDB = "godown"
-mysqlUser = "godown"
-mysqlPass= "wCHDXHL35kZGSD8r"
+mysqlUrlPort = "192.168.11.77:3306"
+mysqlDB = "medical_erp"
+mysqlUser = "medical_erp"
+mysqlPass= "XMzTDthD4By3ArjG"
 mysqlMaxConns = 100
 MysqlMaxOpen = 200
+# 数据库配置(Mysql)
+# mysqlUrlPort = "127.0.0.1:40306"
+# mysqlDB = "godown"
+# mysqlUser = "godown"
+# mysqlPass= "wCHDXHL35kZGSD8r"
+# mysqlMaxConns = 100
+# MysqlMaxOpen = 200
 
 # 日志配置
 # 0-控制台输出 1-文件输出 2-文件和控制台输出
@@ -35,8 +35,8 @@ slow_threshold = 200
 maxlines = 10000
 
 #redis
-# Redis_address = "192.168.11.77:6379"
-Redis_address = "127.0.0.1:43379"
+Redis_address = "192.168.11.77:6379"
+# Redis_address = "127.0.0.1:43379"
 Redis_password = ""
 Redis_dbNum = "3"
 
@@ -48,8 +48,8 @@ FilterOnlyLoginCheckURL = "/api/role-api"
 FilterNotEnterDeptURL = "/api/medicine-template/init"
 
 # 统一身份认证
-# OAuth_baseUrl = "http://192.168.11.77:8100"
-OAuth_baseUrl = "http://127.0.0.1:6400"
+OAuth_baseUrl = "http://192.168.11.77:8100"
+# OAuth_baseUrl = "http://127.0.0.1:6400"
 # 服务发现服务信息
 Service_number = "q9YeglML"
 Service_authCode = "3EDJRaagFTVVo2Ilo80nHJfLVN1O1234"
@@ -68,5 +68,4 @@ Qiniu_SecretKey = "KFhkYxTAJ2ZPN3ZS3euTsfWk8-C92rKgkhAMkDRN"
 Qiniu_BUCKET = "godownoss"
 Qiniu_Url = "https://godownoss.coldbaozhida.com/"
 
-# 宝智达溯码平台
 BZD_pcodeUrl = "https://pcode.baozhida.cn/api/"

+ 16 - 15
conf/app1.conf → conf/app_prov.conf

@@ -6,19 +6,19 @@ copyrequestbody = true
 EnableDocs = true
 
 # 数据库配置(Mysql)
-mysqlUrlPort = "192.168.11.77:3306"
-mysqlDB = "medical_erp"
-mysqlUser = "medical_erp"
-mysqlPass= "XMzTDthD4By3ArjG"
-mysqlMaxConns = 100
-MysqlMaxOpen = 200
-# 数据库配置(Mysql)
-# mysqlUrlPort = "127.0.0.1:40306"
-# mysqlDB = "godown"
-# mysqlUser = "godown"
-# mysqlPass= "wCHDXHL35kZGSD8r"
+# mysqlUrlPort = "192.168.11.77:3306"
+# mysqlDB = "medical_erp"
+# mysqlUser = "medical_erp"
+# mysqlPass= "XMzTDthD4By3ArjG"
 # mysqlMaxConns = 100
 # MysqlMaxOpen = 200
+# 数据库配置(Mysql)
+mysqlUrlPort = "127.0.0.1:40306"
+mysqlDB = "godown"
+mysqlUser = "godown"
+mysqlPass= "wCHDXHL35kZGSD8r"
+mysqlMaxConns = 100
+MysqlMaxOpen = 200
 
 # 日志配置
 # 0-控制台输出 1-文件输出 2-文件和控制台输出
@@ -35,8 +35,8 @@ slow_threshold = 200
 maxlines = 10000
 
 #redis
-Redis_address = "192.168.11.77:6379"
-# Redis_address = "127.0.0.1:43379"
+# Redis_address = "192.168.11.77:6379"
+Redis_address = "127.0.0.1:43379"
 Redis_password = ""
 Redis_dbNum = "3"
 
@@ -48,8 +48,8 @@ FilterOnlyLoginCheckURL = "/api/role-api"
 FilterNotEnterDeptURL = "/api/medicine-template/init"
 
 # 统一身份认证
-# OAuth_baseUrl = "http://192.168.11.77:8100"
-OAuth_baseUrl = "http://127.0.0.1:6400"
+OAuth_baseUrl = "http://192.168.11.77:8100"
+# OAuth_baseUrl = "http://127.0.0.1:6400"
 # 服务发现服务信息
 Service_number = "q9YeglML"
 Service_authCode = "3EDJRaagFTVVo2Ilo80nHJfLVN1O1234"
@@ -68,4 +68,5 @@ Qiniu_SecretKey = "KFhkYxTAJ2ZPN3ZS3euTsfWk8-C92rKgkhAMkDRN"
 Qiniu_BUCKET = "godownoss"
 Qiniu_Url = "https://godownoss.coldbaozhida.com/"
 
+# 宝智达溯码平台
 BZD_pcodeUrl = "https://pcode.baozhida.cn/api/"

+ 2 - 0
controllers/medicine.go

@@ -136,6 +136,7 @@ func (c MedicineController) MSFXQuery() {
 		mock_ := make(map[string]interface{})
 		mock_["product_name"] = mock["名称"]
 		mock_["enterprise_name"] = mock["厂家"]
+		mock_["quantity"] = mock["包装数量"]
 		mock_["spec_name"] = fmt.Sprintf("%s×%s", mock["规格摘要"], mock["规格"])
 		mock_["dosage_form_name"] = mock["类型"]
 		mock_["batch_number"] = mock["批号"]
@@ -180,6 +181,7 @@ func (c MedicineController) MSFXQuery() {
 		}
 		info_[i]["product_name"] = info[i]["名称"]
 		info_[i]["enterprise_name"] = info[i]["厂家"]
+		info_[i]["quantity"] = info[i]["包装数量"]
 		info_[i]["spec_name"] = fmt.Sprintf("%s×%s", info[i]["规格摘要"], info[i]["规格"])
 		info_[i]["dosage_form_name"] = info[i]["类型"]
 		info_[i]["batch_number"] = info[i]["批号"]

+ 1 - 1
controllers/sales.go

@@ -382,7 +382,7 @@ func (c SalesController) SalesStockOutExcel(reqData dto.SalesStockOutExcelReq) {
 	f.MergeCell("Sheet1", fmt.Sprintf("A%d", line), fmt.Sprintf("D%d", line))
 	f.MergeCell("Sheet1", fmt.Sprintf("E%d", line), fmt.Sprintf("K%d", line))
 	f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), fmt.Sprintf("整单合计金额(小写):¥%.2f元", money))
-	f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), fmt.Sprintf("整单合计金额(大写):%s", utils.AmountConvert(money, true)))
+	f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), fmt.Sprintf("整单合计金额(发货人签名:):%s", utils.AmountConvert(money, true)))
 
 	line += 1
 	f.SetRowHeight("Sheet1", line, 25)

+ 1379 - 26
controllers/stock_template.go

@@ -54,6 +54,7 @@ func (c StockTemplateController) StockTemplateIn() {
 
 	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
 	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockRefundIn
 	err := s.StockTemplateIn(&reqData)
 	if err != nil {
 		c.Error(500, err, err.Error())
@@ -80,6 +81,7 @@ func (c StockTemplateController) StockTemplateInScanCode() {
 
 	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
 	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockIn
 	err := s.StockTemplateInScanCode(&reqData)
 	if err != nil {
 		c.Error(500, err, err.Error())
@@ -158,6 +160,88 @@ func (c StockTemplateController) BatchStockTemplateIn() {
 
 	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
 	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockIn
+	err := s.BatchStockTemplateIn(&reqData)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.OK(nil, "入库成功")
+}
+
+// StockTemplateRefundIn 退货入库
+// @Summary 退货入库
+// @Description 退货入库
+// @Tags 库存
+// @Param body body dto.StockTemplateInInsertReq true "body"
+// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
+// @Router /stock-template/in [post]
+// @Security Bearer
+func (c StockTemplateController) StockTemplateRefundIn() {
+	s := services.StockTemplate{}
+	reqData := dto.StockTemplateInInsertReq{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+
+	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
+	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockRefundIn
+	err := s.StockTemplateIn(&reqData)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.OK(reqData.GetId(), "入库成功")
+}
+
+// StockTemplateRefundInScanCode 扫码退货入库
+// @Summary 扫码入库
+// @Description 扫码入库
+// @Tags 库存
+// @Param body body dto.StockTemplateInInsertReq true "body"
+// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
+// @Router /stock-template/in [post]
+// @Security Bearer
+func (c StockTemplateController) StockTemplateRefundInScanCode() {
+	s := services.StockTemplate{}
+	reqData := dto.BatchStockTemplateInInsertReq{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+
+	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
+	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockRefundIn
+	err := s.StockTemplateInScanCode(&reqData)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.OK(nil, "扫码退货入库成功")
+}
+
+// BatchStockTemplateRefundIn 批量退货入库
+// @Summary 批量退货入库
+// @Description 批量退货入库
+// @Tags 库存
+// @Param body body dto.BatchStockTemplateInInsertReq true "body"
+// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
+// @Router /stock-template/in [post]
+// @Security Bearer
+func (c StockTemplateController) BatchStockTemplateRefundIn() {
+	s := services.StockTemplate{}
+	reqData := dto.BatchStockTemplateInInsertReq{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+
+	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
+	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockRefundIn
 	err := s.BatchStockTemplateIn(&reqData)
 	if err != nil {
 		c.Error(500, err, err.Error())
@@ -184,6 +268,7 @@ func (c StockTemplateController) StockTemplateOut() {
 
 	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
 	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockOut
 	err := s.StockTemplateOut(&reqData)
 	if err != nil {
 		c.Error(500, err, err.Error())
@@ -210,6 +295,7 @@ func (c StockTemplateController) StockTemplateOutScanCode() {
 
 	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
 	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockOut
 	err := s.StockTemplateOutScanCode(&reqData)
 	if err != nil {
 		c.Error(500, err, err.Error())
@@ -288,6 +374,7 @@ func (c StockTemplateController) BatchStockTemplateOut() {
 
 	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
 	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	reqData.State = models.StateStockOut
 	err := s.BatchStockTemplateOut(&reqData)
 	if err != nil {
 		c.Error(500, err, err.Error())
@@ -296,6 +383,99 @@ func (c StockTemplateController) BatchStockTemplateOut() {
 	c.OK(nil, "出库成功")
 }
 
+// StockTemplateRefundOut 退货/报废出库
+// @Summary 退货/报废出库
+// @Description 退货/报废出库
+// @Tags 库存
+// @Param body body dto.StockTemplateOutInsertReq true "body"
+// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
+// @Router /stock-template/out [post]
+// @Security Bearer
+func (c StockTemplateController) StockTemplateRefundOut() {
+	s := services.StockTemplate{}
+	reqData := dto.StockTemplateOutInsertReq{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+
+	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
+	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	if reqData.State != models.StateStockRefundOut && reqData.State != models.StateStockScrapOut {
+		err := errors.New("出库状态错误")
+		c.Error(500, err, err.Error())
+		return
+	}
+	err := s.StockTemplateOut(&reqData)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.OK(reqData.GetId(), "退货(报废)出库成功")
+}
+
+// StockTemplateOutScanRefundCode 扫码退货/报废出库
+// @Summary 扫码退货/报废出库
+// @Description 扫码退货/报废出库
+// @Tags 库存
+// @Param body body dto.StockTemplateOutInsertReq true "body"
+// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
+// @Router /stock-template/out [post]
+// @Security Bearer
+func (c StockTemplateController) StockTemplateRefundOutScanCode() {
+	s := services.StockTemplate{}
+	reqData := dto.BatchStockTemplateOutInsertReq{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+
+	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
+	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	if reqData.State != models.StateStockRefundOut && reqData.State != models.StateStockScrapOut {
+		err := errors.New("出库状态错误")
+		c.Error(500, err, err.Error())
+		return
+	}
+	err := s.StockTemplateOutScanCode(&reqData)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.OK(nil, "扫码退货(报废)出库成功")
+}
+
+// BatchStockTemplateRefundOut 批量退货/报废出库
+// @Summary 批量退货/报废出库
+// @Description 批量退货/报废出库
+// @Tags 库存
+// @Param body body dto.StockTemplateOutInsertReq true "body"
+// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
+// @Router /stock-template/out [post]
+// @Security Bearer
+func (c StockTemplateController) BatchStockTemplateRefundOut() {
+	s := services.StockTemplate{}
+	reqData := dto.BatchStockTemplateOutInsertReq{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+
+	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
+	reqData.SetDeptId(beegouser.GetDeptId(c.Ctx))
+	if reqData.State != models.StateStockRefundOut && reqData.State != models.StateStockScrapOut {
+		err := errors.New("出库状态错误")
+		c.Error(500, err, err.Error())
+		return
+	}
+	err := s.BatchStockTemplateOut(&reqData)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.OK(nil, "退货(报废)出库成功")
+}
+
 // StockTemplateInList 入库列表
 // @Summary 入库列表
 // @Description 入库列表
@@ -353,7 +533,7 @@ func (c StockTemplateController) StockTemplateOutList() {
 // @Param body body dto.StockTemplateInventoryPageReq true "body"
 // @Success 200 {object} response.Page "{"code": 200, "data": [...]}"
 // @Router /stock/inventory/list [post]
-// @Security Bearer
+// @Security Bearer
 func (c StockTemplateController) StockTemplateInventoryList() {
 	s := services.StockTemplate{}
 	reqData := dto.StockTemplateInventoryPageReq{}
@@ -383,7 +563,7 @@ func (c StockTemplateController) StockTemplateInventoryExcel(reqData dto.StockTe
 	s := services.StockTemplate{}
 	deptId := beegouser.GetDeptId(c.Ctx)
 	models.InitBasicData(deptId)
-	medicineInfo, err := s.GetMedicineInfo(deptId, map[string]interface{}{
+	medicineInfo, _, err := s.GetMedicineInfo(deptId, map[string]interface{}{
 		"product_id":    reqData.ProductID,
 		"enterprise_id": reqData.EnterpriseID,
 		"spec_id":       reqData.SpecId,
@@ -558,7 +738,7 @@ func (c StockTemplateController) StockTemplateInventoryPdf(reqData dto.StockTemp
 	s := services.StockTemplate{}
 	deptId := beegouser.GetDeptId(c.Ctx)
 	models.InitBasicData(deptId)
-	medicineInfo, err := s.GetMedicineInfo(deptId, map[string]interface{}{
+	medicineInfo, _, err := s.GetMedicineInfo(deptId, map[string]interface{}{
 		"product_id":    reqData.ProductID,
 		"enterprise_id": reqData.EnterpriseID,
 		"spec_id":       reqData.SpecId,
@@ -1621,7 +1801,7 @@ func (c StockTemplateController) TransportRecordWord(reqData models.TransportRec
 	run = para.AddRun()
 	run.Properties().SetFontFamily("宋体")
 	run.Properties().SetSize(10)
-	run.AddText("发货单位:")
+	run.AddText("发货单位")
 	run = para.AddRun()
 	run.Properties().SetFontFamily("宋体")
 	run.Properties().SetSize(10)
@@ -1636,7 +1816,7 @@ func (c StockTemplateController) TransportRecordWord(reqData models.TransportRec
 	run = para.AddRun()
 	run.Properties().SetFontFamily("宋体")
 	run.Properties().SetSize(10)
-	run.AddText("发货人签名:")
+	run.AddText("发货人签名")
 	run = para.AddRun()
 	run.Properties().SetSize(5)
 	run.AddText("________________________________________________________________")
@@ -1652,7 +1832,7 @@ func (c StockTemplateController) TransportRecordWord(reqData models.TransportRec
 	run = para.AddRun()
 	run.Properties().SetFontFamily("宋体")
 	run.Properties().SetSize(10)
-	run.AddText("收货单位:")
+	run.AddText("收货单位")
 	run = para.AddRun()
 	run.Properties().SetFontFamily("宋体")
 	run.Properties().SetSize(10)
@@ -1667,7 +1847,7 @@ func (c StockTemplateController) TransportRecordWord(reqData models.TransportRec
 	run = para.AddRun()
 	run.Properties().SetFontFamily("宋体")
 	run.Properties().SetSize(10)
-	run.AddText("收货人签名:")
+	run.AddText("收货人签名")
 	run = para.AddRun()
 	run.Properties().SetSize(5)
 	run.AddText("________________________________________________________________")
@@ -1677,7 +1857,7 @@ func (c StockTemplateController) TransportRecordWord(reqData models.TransportRec
 	run = para.AddRun()
 	run.Properties().SetFontFamily("宋体")
 	run.Properties().SetSize(10)
-	run.AddText("填表说明:本表供疫苗配送企业、疾病预防控制机构、接种单位疫苗运输时填写;出入库单号为单位编码+年月日+2位流水号;运输超过6小时需记录途中温度,间隔不超过6小时;使用无自动温度显示的冰排保冷设备时,只在启运和达到时填写冰排状态(冻结、冰水混合物、完全融化)。")
+	run.AddText("填表说明:本表供冷链配送企业、疾病预防控制机构、接种单位冷链运输时填写;出入库单号为单位编码+年月日+2位流水号;运输超过6小时需记录途中温度,间隔不超过6小时;使用无自动温度显示的冰排保冷设备时,只在启运和达到时填写冰排状态(冻结、冰水混合物、完全融化)。")
 	doc.BodySection().SetFooter(ftr, wml.ST_HdrFtrDefault)
 
 	filename := "运输记录表" + time.Now().Format("20060102150405") + ".docx"
@@ -1758,9 +1938,9 @@ func (c StockTemplateController) TransportRecordPdf(reqData models.TransportReco
 		temp = append(temp, utils.ToString(row[models.FieldApprovalNumber]))
 		temp = append(temp, utils.ToString(row[models.FieldQualificationNumber]))
 		temp = append(temp, spec)
-		temp = append(temp, utils.ToDate(row[models.FieldProducedDate]))
+		temp = append(temp, utils.ToString(row[models.FieldProducedDate]))
 		temp = append(temp, batchNumber)
-		temp = append(temp, utils.ToDate(row[models.FieldExpiryDate]))
+		temp = append(temp, utils.ToString(row[models.FieldExpiryDate]))
 		temp = append(temp, fmt.Sprintf("%d", utils.ToInt(row["quantity"])))
 		temp = append(temp, utils.ToString(row[models.FieldUnitName]))
 		rows = append(rows, temp)
@@ -1768,7 +1948,6 @@ func (c StockTemplateController) TransportRecordPdf(reqData models.TransportReco
 		// 获取药品信息图片
 		img, err := imgSvc.Get(deptId, rootId, product, enterprise, spec, batchNumber)
 		if err == nil && img.Img != "" {
-			log.Println("==============", img.Img)
 			imgList = append(imgList, img.Img)
 		}
 	}
@@ -1797,7 +1976,7 @@ func (c StockTemplateController) TransportRecordPdf(reqData models.TransportReco
 
 	imgPath2 := "ofile/img/" + code + ".jpg"
 	png2j.Con2jpg(imgPath, imgPath2)
-	pdf.Image(imgPath2, 20, 35, nil)
+	pdf.Image(imgPath2, -5, 35, &gopdf.Rect{W: 175, H: 30})
 
 	titleStr := "表3-4 运输记录表"
 	pdf.SetFont("simsun", "", 22)
@@ -1971,17 +2150,17 @@ func (c StockTemplateController) TransportRecordPdf(reqData models.TransportReco
 	}
 	pdf.SetX(curx)
 	y = pdf.GetY()
-	pdf.Text("发货单位:")
-	txtWd, _ := pdf.MeasureTextWidth("发货单位:")
+	pdf.Text("发货单位")
+	txtWd, _ := pdf.MeasureTextWidth("发货单位")
 	pdf.SetLineWidth(0.8)
 	pdf.SetXY(curx+txtWd, y)
 	pdf.Text(beegouser.GetDeptName(c.Ctx))
-	pdf.Line(57, y+3, 207, y+3)
+	pdf.Line(60, y+3, 207, y+3)
 
 	pdf.SetXY(300, y)
-	pdf.Text("发货人签名:")
-	txtWd, _ = pdf.MeasureTextWidth("发货人签名:")
-	pdf.Line(345, y+3, 495, y+3)
+	pdf.Text("发货人签名")
+	txtWd, _ = pdf.MeasureTextWidth("发货人签名")
+	pdf.Line(348, y+3, 495, y+3)
 
 	y = pdf.GetY()
 	y += 25
@@ -1991,16 +2170,16 @@ func (c StockTemplateController) TransportRecordPdf(reqData models.TransportReco
 	}
 	pdf.SetX(curx)
 	y = pdf.GetY()
-	pdf.Text("收货单位:")
-	txtWd, _ = pdf.MeasureTextWidth("收货单位:")
+	pdf.Text("收货单位")
+	txtWd, _ = pdf.MeasureTextWidth("收货单位")
 	pdf.SetXY(curx+txtWd, y)
 	pdf.Text(reqData.ReceivingUnit)
-	pdf.Line(57, y+3, 207, y+3)
+	pdf.Line(60, y+3, 207, y+3)
 
 	pdf.SetXY(300, y)
-	pdf.Text("收货人签名:")
-	txtWd, _ = pdf.MeasureTextWidth("收货人签名:")
-	pdf.Line(345, y+3, 495, y+3)
+	pdf.Text("收货人签名")
+	txtWd, _ = pdf.MeasureTextWidth("收货人签名")
+	pdf.Line(348, y+3, 495, y+3)
 
 	y = pdf.GetY()
 	y += 20
@@ -2010,7 +2189,7 @@ func (c StockTemplateController) TransportRecordPdf(reqData models.TransportReco
 	}
 	pdf.SetX(curx)
 	pdf.SetCharSpacing(0.5)
-	txt := "填表说明:本表供疫苗配送企业、疾病预防控制机构、接种单位疫苗运输时填写;出入库单号为单位编码+年月日+2位流水号;运输超过6小时需记录途中温度,间隔不超过6小时;使用无自动温度显示的冰排保冷设备时,只在启运和达到时填写冰排状态(冻结、冰水混合物、完全融化)。"
+	txt := "填表说明:本表供冷链配送企业、疾病预防控制机构、接种单位冷链运输时填写;出入库单号为单位编码+年月日+2位流水号;运输超过6小时需记录途中温度,间隔不超过6小时;使用无自动温度显示的冰排保冷设备时,只在启运和达到时填写冰排状态(冻结、冰水混合物、完全融化)。"
 	pdf.MultiCell(&gopdf.Rect{W: 555, H: 50}, txt)
 	//imgList = append(imgList,
 	//	"https://godownoss.coldbaozhida.com/UpImage/17115067977062dc7f-0354-4e70-aefe-3423338b44be.jpg",
@@ -2119,6 +2298,32 @@ func (c StockTemplateController) TransportRecordExport() {
 
 }
 
+// TransportRecordExport 运输记录表
+// @Summary 收发登记表word
+// @Description 收发登记表word
+// @Tags 库存
+// @Param body body dto.TransportRecordWordReq true "body"
+// @Success 200 {object} response.Page "{"code": 200, "data": [...]}"
+// @Router /stock-template/inventory/list [post]
+// @Security Bearer
+func (c StockTemplateController) TransportRecordExportList() {
+	s := services.StockTemplate{}
+	reqData := models.TransportRecord{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+	deptId := beegouser.GetDeptId(c.Ctx)
+	models.InitBasicData(deptId)
+
+	list, err := s.StockTemplateTransportRecordWord(&reqData, deptId)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.PageOK(list, 0, 0, 0, "查询成功")
+}
+
 // StockUnitList 获取收货单位,发货单位,收发单位
 // @Summary 获取收货单位,发货单位,收发单位
 // @Description 获取收货单位,发货单位,收发单位
@@ -2376,7 +2581,7 @@ func (c StockTemplateController) StockTemplateInScanBarCode() {
 	c.OK(nil, "扫码出库成功")
 }
 
-func (c StockTemplateController) GetBarCodeInfo() {
+func (c StockTemplateController) GetTransportRecordBarCodeInfo() {
 	barcodeSvc := services.Barcode{}
 	s := services.StockTemplate{}
 	//if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
@@ -2405,3 +2610,1151 @@ func (c StockTemplateController) GetBarCodeInfo() {
 
 	c.OK(list, "查询成功")
 }
+
+func (c StockTemplateController) StockRefundOutTransportRecordPdf(reqData models.TransportRecord) {
+	s := services.StockTemplate{}
+	imgSvc := services.MedicineImg{}
+	barcodeServ := services.Barcode{}
+	deptId := beegouser.GetDeptId(c.Ctx)
+
+	p := actions.GetPermissionFromContext(c.Ctx)
+	rootId, err := imgSvc.GetRootID((*context2.Context)(c.Ctx), p.DeptId)
+	if err != nil {
+		c.Error(global.BadRequest, err, err.Error())
+		return
+	}
+
+	list, err := s.StockRefundOutTransportRecordPdf(&reqData, deptId)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	reqData.DeptID = deptId
+	reqData.DeptName = beegouser.GetDeptName(c.Ctx)
+	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
+	reqData.SetDeptId(deptId)
+	code, err := barcodeServ.Insert(reqData)
+	if err != nil {
+		err = errors.New("生成条码失败")
+		c.Error(500, err, err.Error())
+		return
+	}
+	cs, _ := code128.Encode(code)
+	// 创建一个要输出数据的文件
+	imgPath := "ofile/img/" + code + ".png"
+	file, _ := os.Create(imgPath)
+	defer file.Close()
+
+	// 设置图片像素大小
+	qrCode, _ := barcode.Scale(cs, 205, 50)
+	// 将code128的条形码编码为png图片
+	png.Encode(file, qrCode)
+
+	cols := []float64{83, 50, 55, 72, 72, 50, 66, 50, 27, 30}
+
+	header := []string{"品种", "生产企业", "批准文号", "批签发合格编号", "规格(剂/支或粒)", "生产日期", "批号", "失效日期", "数量", "单位"}
+	rows := [][]string{}
+	imgList := []string{}
+
+	for _, row := range list {
+		temp := []string{}
+		product := utils.ToString(row[models.FieldProductName])
+		enterprise := utils.ToString(row[models.FieldEnterpriseName])
+		spec := utils.ToString(row[models.FieldSpecName])
+		batchNumber := utils.ToString(row[models.FieldBatchNumber])
+		temp = append(temp, product)
+		temp = append(temp, fmt.Sprintf("%s", enterprise))
+		temp = append(temp, utils.ToString(row[models.FieldApprovalNumber]))
+		temp = append(temp, utils.ToString(row[models.FieldQualificationNumber]))
+		temp = append(temp, spec)
+		temp = append(temp, utils.ToString(row[models.FieldProducedDate]))
+		temp = append(temp, batchNumber)
+		temp = append(temp, utils.ToString(row[models.FieldExpiryDate]))
+		temp = append(temp, fmt.Sprintf("%d", utils.ToInt(row["quantity"])))
+		temp = append(temp, utils.ToString(row[models.FieldUnitName]))
+		rows = append(rows, temp)
+
+		// 获取药品信息图片
+		img, err := imgSvc.Get(deptId, rootId, product, enterprise, spec, batchNumber)
+		if err == nil && img.Img != "" {
+			log.Println("==============", img.Img)
+			imgList = append(imgList, img.Img)
+		}
+	}
+
+	pdf := &gopdf.GoPdf{}
+	pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 595.28, H: 841.89}})
+	pdf.SetMarginTop(40)
+	pdf.SetMarginBottom(40)
+
+	pdf.AddPage()
+	pdf.AddTTFFont("simsun", "static/fonts/MiSans-Medium.ttf")
+
+	pdf.SetMargins(2, 5, 5, 5)
+	pdf.SetFont("simsun", "", 10)
+	//pdf.SetX(20)
+	//pdf.SetY(20)
+	//pdf.Text("[退货出库]")
+	pdf.SetX(420)
+	pdf.SetY(60)
+	pdf.Text(code)
+
+	imgPath2 := "ofile/img/" + code + ".jpg"
+	png2j.Con2jpg(imgPath, imgPath2)
+	pdf.Image(imgPath2, 390, 15, &gopdf.Rect{W: 200, H: 35})
+
+	titleStr := "退货出库运输温度记录表"
+	pdf.SetFont("simsun", "", 22)
+	textw, _ := pdf.MeasureTextWidth(titleStr)
+	pdf.SetX((595 / 2) - (textw / 2) - 50)
+	pdf.SetY(40)
+	pdf.Text(titleStr)
+
+	pdf.SetFont("simsun", "", 10)
+	// 第一行
+	curx, y := 20., pdf.GetY()
+	y += 35
+	pdf.SetXY(curx, y)
+	pdf.Text("出/入库日期:")
+	txtWd, _ := pdf.MeasureTextWidth("出/入库日期:")
+	pdf.SetXY(curx+txtWd, y)
+	pdf.Text(reqData.Date)
+	pdf.Line(curx+txtWd, y+3, curx+txtWd+110, y+3)
+
+	curx = 230
+	pdf.SetXY(curx, y)
+	pdf.Text("出/入库单号:")
+	txtWd, _ = pdf.MeasureTextWidth("出/入库单号:")
+	pdf.SetXY(curx+txtWd, y)
+	pdf.Text(code)
+	pdf.Line(curx+txtWd, y+3, curx+txtWd+130, y+3)
+
+	// 第二行
+	curx, y = 20., pdf.GetY()
+	y += 25
+	pdf.SetXY(curx, y)
+	pdf.Text("运输工具:(1)冷藏车")
+	txtWd, _ = pdf.MeasureTextWidth("运输工具:(1)冷藏车")
+	pdf.SetXY(curx+txtWd, y)
+	//pdf.Text(reqData.Date)
+	pdf.Line(curx+txtWd, y+3, curx+txtWd+110, y+3)
+
+	curx = 230
+	pdf.SetXY(curx, y)
+	pdf.Text("(2)运输车")
+	txtWd, _ = pdf.MeasureTextWidth("(2)运输车")
+	pdf.SetXY(curx+txtWd, y)
+	//pdf.Text(code)
+	pdf.Line(curx+txtWd+2, y+3, curx+txtWd+130, y+3)
+
+	curx = 410
+	pdf.SetXY(curx, y)
+	pdf.Text("(3)其他")
+	txtWd, _ = pdf.MeasureTextWidth("(3)其他")
+	pdf.SetXY(curx+txtWd, y)
+	//pdf.Text(code)
+	pdf.Line(curx+txtWd+2, y+3, curx+txtWd+130, y+3)
+
+	// 第三行
+	curx, y = 20., pdf.GetY()
+	y += 25
+	pdf.SetXY(curx, y)
+	pdf.Text("冷藏方式:(1)冷藏车")
+	txtWd, _ = pdf.MeasureTextWidth("运输工具:(1)冷藏车")
+	pdf.SetXY(curx+txtWd, y)
+	//pdf.Text(reqData.Date)
+	pdf.Line(curx+txtWd, y+3, curx+txtWd+110, y+3)
+
+	curx = 230
+	pdf.SetXY(curx, y)
+	pdf.Text("(2)冷藏箱")
+	txtWd, _ = pdf.MeasureTextWidth("(2)冷藏箱")
+	pdf.SetXY(curx+txtWd, y)
+	//pdf.Text(code)
+	pdf.Line(curx+txtWd, y+3, curx+txtWd+130, y+3)
+
+	curx = 410
+	pdf.SetXY(curx, y)
+	pdf.Text("(3)其他")
+	txtWd, _ = pdf.MeasureTextWidth("(3)其他")
+	pdf.SetXY(curx+txtWd, y)
+	//pdf.Text(code)
+	pdf.Line(curx+txtWd, y+3, curx+txtWd+130, y+3)
+
+	curx = 20
+	y += 20
+	pdf.SetXY(curx, y)
+	pdf.Text("运输情况:")
+	y += 6
+	pdf.SetXY(curx, y)
+	h := 20.0
+	x := curx
+	pdf.SetFont("simsun", "", 9)
+	for i := 0; i < len(header); i++ {
+		utils.RectFillColorMultiCell(pdf, header[i], 9, x, y, cols[i], h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += cols[i]
+	}
+	y += h
+	pdf.SetXY(curx, y)
+	pdf.SetFont("simsun", "", 8)
+
+	for _, row := range rows {
+		curx, y = pdf.GetX(), pdf.GetY()
+		x = curx
+
+		height := h
+		for i, txt := range row {
+			lineTexts, _ := pdf.SplitText(txt, cols[i])
+			//lineHt := h * float64(len(lineTexts))
+			if len(lineTexts) > 1 {
+				lineTexts, _ = pdf.SplitText(txt, cols[i]-4)
+				lineHt := h * float64(len(lineTexts)) * 0.6
+				if lineHt > height {
+					height = lineHt
+				}
+			}
+		}
+
+		for i, txt := range row {
+			width := cols[i]
+			utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, height, 0, 0, 0, gopdf.Center, gopdf.Middle)
+			x += width
+		}
+		pdf.SetNewY(y+height, height)
+		pdf.SetX(curx)
+	}
+	pdf.SetFont("simsun", "", 9)
+	y = pdf.GetY()
+	y += 20
+	pdf.SetNewY(y, 20)
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	pdf.SetX(curx)
+	pdf.Text("运输温度记录:")
+	header2 := []string{"项目", "日期/时间", "储存温度", "冰排状态", "环境温度"}
+	cols2 := []float64{55, 210, 105, 94, 91}
+	y = pdf.GetY()
+	y += 5
+	h = 35.0
+	pdf.SetNewY(y, h)
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	y = pdf.GetY()
+	pdf.SetX(curx)
+	x = curx
+	for i := 0; i < len(header2); i++ {
+		utils.RectFillColorMultiCell(pdf, header2[i], 9, x, y, cols2[i], h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += cols2[i]
+	}
+	y = pdf.GetY()
+	y += h
+	pdf.SetNewY(y, h)
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	pdf.SetX(curx)
+	row2 := [][]string{
+		{"启运", "______年___月___日___时___分", "________℃", "", "________℃"},
+		{"途中", "______年___月___日___时___分", "________℃", "————", "________℃"},
+		{"到达", "______年___月___日___时___分", "________℃", "", "________℃"},
+	}
+
+	for j, row := range row2 {
+		curx, y = pdf.GetX(), pdf.GetY()
+		x = curx
+		pdf.SetTextColor(0, 0, 0)
+
+		height := h
+		if j == 1 {
+			height = height * 2
+		}
+		for i, txt := range row {
+			width := cols2[i]
+			txtWd, _ := pdf.MeasureTextWidth(txt)
+
+			txtX := x + (width-txtWd)/2
+
+			pdf.SetLineWidth(0.8)
+			pdf.SetFillColor(255, 255, 255) //setup fill color
+			pdf.SetLineType("")             // 线条样式
+			pdf.RectFromUpperLeftWithStyle(x, y, width, height, "FD")
+
+			if j == 1 {
+				if i == 1 || i == 2 || i == 4 {
+					txtY := y + height/5*2
+					pdf.SetXY(txtX, txtY)
+					pdf.Text(txt)
+					txtY = y + height/5*4
+					pdf.SetXY(txtX, txtY)
+					pdf.Text(txt)
+				} else {
+					txtY := y + height/5*3
+					pdf.SetXY(txtX, txtY)
+					pdf.Text(txt)
+				}
+			} else {
+				txtY := y + height/3*2
+				pdf.SetXY(txtX, txtY)
+				pdf.Text(txt)
+			}
+
+			x += width
+		}
+
+		pdf.SetNewY(y+height, height)
+
+		if pdf.GetY() < 30 || pdf.GetY() > 810 {
+			pdf.SetY(30)
+		}
+		pdf.SetX(curx)
+	}
+
+	y = pdf.GetY()
+	y += 20
+	pdf.SetNewY(y, 20)
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	pdf.SetX(curx)
+	pdf.Text("启运至到达行驶里程数:_________千米")
+
+	y = pdf.GetY()
+	y += 25
+	pdf.SetNewY(y, 25)
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	pdf.SetX(curx)
+	y = pdf.GetY()
+	pdf.Text("发货单位:")
+	txtWd, _ = pdf.MeasureTextWidth("发货单位:")
+	pdf.SetLineWidth(0.8)
+	pdf.SetXY(curx+txtWd, y)
+	pdf.Text(beegouser.GetDeptName(c.Ctx))
+	pdf.Line(60, y+3, 207, y+3)
+
+	pdf.SetXY(300, y)
+	pdf.Text("发货人签名:")
+	txtWd, _ = pdf.MeasureTextWidth("发货人签名:")
+	pdf.Line(348, y+3, 495, y+3)
+
+	y = pdf.GetY()
+	y += 25
+	pdf.SetNewY(y, 25)
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	pdf.SetX(curx)
+	y = pdf.GetY()
+	pdf.Text("收货单位:")
+	txtWd, _ = pdf.MeasureTextWidth("收货单位:")
+	pdf.SetXY(curx+txtWd, y)
+	pdf.Text(reqData.ReceivingUnit)
+	pdf.Line(60, y+3, 207, y+3)
+
+	pdf.SetXY(300, y)
+	pdf.Text("收货人签名:")
+	txtWd, _ = pdf.MeasureTextWidth("收货人签名:")
+	pdf.Line(348, y+3, 495, y+3)
+
+	y = pdf.GetY()
+	y += 20
+	pdf.SetNewY(y, 20)
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	pdf.SetX(curx)
+	pdf.SetCharSpacing(0.5)
+	txt := "填表说明:本表供冷链配送企业、疾病预防控制机构、接种单位冷链运输时填写;出入库单号为单位编码+年月日+2位流水号;运输超过6小时需记录途中温度,间隔不超过6小时;使用无自动温度显示的冰排保冷设备时,只在启运和达到时填写冰排状态(冻结、冰水混合物、完全融化)。"
+	pdf.MultiCell(&gopdf.Rect{W: 555, H: 50}, txt)
+	//imgList = append(imgList,
+	//	"https://godownoss.coldbaozhida.com/UpImage/17115067977062dc7f-0354-4e70-aefe-3423338b44be.jpg",
+	//	"https://godownoss.coldbaozhida.com/UpImage/17115068019adbd486-993e-48c5-8155-c2c30265638a.jpg",
+	//)
+	for _, v := range imgList {
+		urlList := strings.Split(strings.Trim(v, ","), ",")
+		for _, url := range urlList {
+			pdf.AddPage()
+			imgH, errImg := utils.GetImage(url)
+			if errImg != nil {
+				err = errors.New("获取图片失败")
+				c.Error(500, err, err.Error())
+				return
+			}
+			imgWidth := float64(imgH.Bounds().Dx())
+			imgHeight := float64(imgH.Bounds().Dy())
+			W, H := imgWidth, imgHeight
+			if imgWidth >= imgHeight && imgWidth > 555 {
+				W = 555
+				H = 555 * float64(imgHeight) / float64(imgWidth)
+			}
+
+			if imgWidth < imgHeight && imgWidth > 760 {
+				W = 760 * float64(imgWidth) / float64(imgHeight)
+				H = 760
+				if W > 555 {
+					H = 555 * 760 / W
+					W = 555
+				}
+
+			}
+
+			if strings.Contains(url, ".png") {
+				err = pdf.ImageFrom(imgH, (595-W)/2, (840-H)/2, &gopdf.Rect{W: W, H: H})
+				if err != nil {
+					err = errors.New("写入图片失败")
+					c.Error(500, err, err.Error())
+					return
+				}
+			} else {
+				fileName := "./ofile/" + path.Base(url)
+				f, _ := os.Create(fileName)
+				defer f.Close()
+				defer func() {
+					os.Remove(fileName)
+				}()
+				jpeg.Encode(f, imgH, &jpeg.Options{100})
+				err = pdf.Image(fileName, (595-W)/2, (840-H)/2, &gopdf.Rect{W: W, H: H})
+				if err != nil {
+					err = errors.New("写入图片失败")
+					c.Error(500, err, err.Error())
+					return
+				}
+			}
+
+		}
+
+	}
+
+	for i := 0; i < pdf.GetNumberOfPages(); i++ {
+
+	}
+
+	filename := "退货出库运输温度记录表" + time.Now().Format("20060102150405") + ".pdf"
+	// 保存文件
+	if err = pdf.WritePdf("ofile/" + filename); err != nil {
+		fmt.Println(err)
+	}
+	defer func() {
+		os.Remove("ofile/" + filename)
+		os.Remove(imgPath)
+		os.Remove(imgPath2)
+	}()
+
+	// 返回生成的 Excel 文件
+	c.Ctx.Output.Download("ofile/" + filename)
+
+}
+
+// StockRefundOutTransportRecordExport 退货出库运输登记表
+// @Summary 退货出库运输登记表
+// @Description 退货出库运输登记表
+// @Tags 库存
+// @Param body body dto.TransportRecordWordReq true "body"
+// @Success 200 {object} response.Page "{"code": 200, "data": [...]}"
+// @Router /stock-template/inventory/list [post]
+// @Security Bearer
+func (c StockTemplateController) StockRefundOutTransportRecordExport() {
+	reqData := models.TransportRecord{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+	deptId := beegouser.GetDeptId(c.Ctx)
+	models.InitBasicData(deptId)
+
+	if reqData.Type == "pdf" {
+		c.StockRefundOutTransportRecordPdf(reqData)
+
+	}
+
+}
+
+func (c StockTemplateController) GetRefundOutBarCodeInfo() {
+	barcodeSvc := services.Barcode{}
+	s := services.StockTemplate{}
+	//if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+	//	c.Error(global.ParseFormErr, err, err.Error())
+	//	return
+	//}
+	codeStr := c.GetString("code")
+	reqData := dto.GetBarCodeInfoReq{Code: codeStr}
+
+	var code models.Barcode
+	//数据权限检查
+	err := barcodeSvc.Get(&reqData, &code)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+
+	list, err := s.GetRefundOutBarCodeInfo(&code.Data, code.Data.DeptID)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	for _, v := range list {
+		v["forwardingUnit"] = code.Data.DeptName
+	}
+
+	c.OK(list, "查询成功")
+}
+
+// StockTemplateInList 入库列表
+// @Summary 入库列表
+// @Description 入库列表
+// @Tags 库存
+// @Param body body dto.StockTemplateInPageReq true "body"
+// @Success 200 {object} response.Page "{"code": 200, "data": [...]}"
+// @Router /stock-template/in/list [post]
+// @Security Bearer
+func (c StockTemplateController) StockTemplateRefundInList() {
+	s := services.StockTemplate{}
+	reqData := dto.StockTemplateInPageReq{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+
+	deptId := beegouser.GetDeptId(c.Ctx)
+	list, count, err := s.StockTemplateRefundInList(&reqData, deptId)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.PageOK(list, int(count), reqData.GetPageIndex(), reqData.GetPageSize(), "查询成功")
+}
+
+// StockTemplateOutList 出库列表
+// @Summary 出库列表
+// @Description 出库列表
+// @Tags 库存
+// @Param body body dto.StockTemplateOutPageReq true "body"
+// @Success 200 {object} response.Page "{"code": 200, "data": [...]}"
+// @Router /stock-template/out/list [post]
+// @Security Bearer
+func (c StockTemplateController) StockTemplateRefundOutList() {
+	s := services.StockTemplate{}
+	reqData := dto.StockTemplateOutPageReq{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+
+	deptId := beegouser.GetDeptId(c.Ctx)
+	list, count, err := s.StockTemplateRefundOutList(&reqData, deptId)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	c.PageOK(list, int(count), reqData.GetPageIndex(), reqData.GetPageSize(), "查询成功")
+}
+
+// StockRefundOutExport 退货出库单
+// @Summary 退货出库运输登记表
+// @Description 退货出库运输登记表
+// @Tags 库存
+// @Param body body dto.StockRefundOutExport true "body"
+// @Success 200 {object} response.Page "{"code": 200, "data": [...]}"
+// @Router /stock-template/inventory/list [post]
+// @Security Bearer
+func (c StockTemplateController) StockRefundOutExport() {
+	reqData := dto.StockRefundOutExport{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+	deptId := beegouser.GetDeptId(c.Ctx)
+	models.InitBasicData(deptId)
+
+	s := services.StockTemplate{}
+	barcodeServ := services.Barcode{}
+
+	list, err := s.StockRefundOutPdf(&reqData, deptId)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	reqData.DeptId = deptId
+	reqData.DeptName = beegouser.GetDeptName(c.Ctx)
+	code, err := barcodeServ.InsertRefundOut(reqData)
+	if err != nil {
+		err = errors.New("生成条码失败")
+		c.Error(500, err, err.Error())
+		return
+	}
+	cs, _ := code128.Encode(code)
+	// 创建一个要输出数据的文件
+	imgPath := "ofile/img/" + code + ".png"
+	file, _ := os.Create(imgPath)
+	defer file.Close()
+
+	// 设置图片像素大小
+	qrCode, _ := barcode.Scale(cs, 205, 50)
+	// 将code128的条形码编码为png图片
+	png.Encode(file, qrCode)
+
+	cols := []float64{160, 140, 45, 70, 70, 105, 105, 105}
+
+	header := []string{"品种", "生产企业", "单位", "单价", "数量", "金额", "批号", "有效期"}
+	rows := [][]string{}
+	var totalMoney float64
+	for _, row := range list {
+		temp := []string{}
+		product := utils.ToString(row[models.FieldProductName])
+		enterprise := utils.ToString(row[models.FieldEnterpriseName])
+		batchNumber := utils.ToString(row[models.FieldBatchNumber])
+		temp = append(temp, product)
+		temp = append(temp, fmt.Sprintf("%s", enterprise))
+		temp = append(temp, utils.ToString(row[models.FieldUnitName]))
+		temp = append(temp, fmt.Sprintf("%.01f", utils.ToFloat64(row["unit_price"])))
+		temp = append(temp, fmt.Sprintf("%d", utils.ToInt(row["quantity"])))
+		temp = append(temp, fmt.Sprintf("%.01f", utils.ToFloat64(row["money"])))
+		temp = append(temp, batchNumber)
+		temp = append(temp, utils.ToString(row[models.FieldExpiryDate]))
+
+		rows = append(rows, temp)
+		totalMoney += utils.ToFloat64(row["money"])
+	}
+
+	pdf := &gopdf.GoPdf{}
+	pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 841.89, H: 595.28}})
+	pdf.SetMarginTop(40)
+	pdf.SetMarginBottom(40)
+
+	pdf.AddPage()
+	pdf.AddTTFFont("simsun", "static/fonts/MiSans-Medium.ttf")
+
+	pdf.SetMargins(2, 5, 5, 5)
+	pdf.SetFont("simsun", "", 12)
+	//pdf.SetX(20)
+	//pdf.SetY(20)
+	//pdf.Text("[退货出库]")
+	pdf.SetX(668)
+	pdf.SetY(60)
+	pdf.Text(code)
+
+	titleStr := reqData.DeptName + "退货单"
+	pdf.SetFont("simsun", "", 25)
+	textw, _ := pdf.MeasureTextWidth(titleStr)
+	pdf.SetX((840 / 2) - (textw / 2))
+	pdf.SetY(40)
+	pdf.Text(titleStr)
+
+	pdf.SetFont("simsun", "", 12)
+	// 第一行
+	curx, y := 30., pdf.GetY()
+	y += 40
+	pdf.SetXY(curx, y)
+	pdf.Text("开票日期:" + time.Now().Format("2006-01-02"))
+
+	// 第二行
+	curx, y = 30., pdf.GetY()
+	y += 20
+	pdf.SetXY(curx, y)
+	pdf.Text("退货原因:" + reqData.Reason)
+
+	curx = 20
+	y += 10
+	pdf.SetXY(curx, y)
+	h := 20.0
+	x := curx
+	pdf.SetFont("simsun", "", 10)
+	for i := 0; i < len(header); i++ {
+		utils.RectFillColorMultiCell(pdf, header[i], 9, x, y, cols[i], h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += cols[i]
+	}
+	y += h
+	pdf.SetXY(curx, y)
+	pdf.SetFont("simsun", "", 10)
+
+	for _, row := range rows {
+		curx, y = pdf.GetX(), pdf.GetY()
+		x = curx
+
+		height := h
+		for i, txt := range row {
+			lineTexts, _ := pdf.SplitText(txt, cols[i])
+			//lineHt := h * float64(len(lineTexts))
+			if len(lineTexts) > 1 {
+				lineTexts, _ = pdf.SplitText(txt, cols[i]-4)
+				lineHt := h * float64(len(lineTexts)) * 0.6
+				if lineHt > height {
+					height = lineHt
+				}
+			}
+		}
+
+		for i, txt := range row {
+			width := cols[i]
+			utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, height, 0, 0, 0, gopdf.Center, gopdf.Middle)
+			x += width
+		}
+		pdf.SetNewY(y+height, height)
+		pdf.SetX(curx)
+	}
+
+	curx, y = pdf.GetX(), pdf.GetY()
+	x = curx
+	cols2 := []float64{160, 140, 45, 70, 70, 105, 210}
+	row2 := []string{"", "", "", "", "合计:", fmt.Sprintf("%.02f", totalMoney), utils.AmountConvert(totalMoney, true)}
+	for i, txt := range row2 {
+		width := cols2[i]
+		utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += width
+	}
+
+	pdf.SetFont("simsun", "", 12)
+	// 第一行
+	curx, y = 30., pdf.GetY()
+	y += 25
+	pdf.SetXY(curx, y)
+	pdf.Text("制  单 人:" + beegouser.GetUserName(c.Ctx))
+	curx = 265
+	pdf.SetXY(curx, y)
+	pdf.Text("经    办    人:")
+	curx = 565
+	pdf.SetXY(curx, y)
+	pdf.Text("科室负责人:")
+
+	// 第二行
+	curx, y = 30., pdf.GetY()
+	y += 30
+	pdf.SetXY(curx, y)
+	pdf.Text("分管主任:")
+	curx = 265
+	pdf.SetXY(curx, y)
+	pdf.Text("财务部负责人:")
+	curx = 565
+	pdf.SetXY(curx, y)
+	pdf.Text("单位负责人:")
+
+	filename := titleStr + time.Now().Format("20060102150405") + ".pdf"
+	// 保存文件
+	if err = pdf.WritePdf("ofile/" + filename); err != nil {
+		fmt.Println(err)
+	}
+	defer func() {
+		os.Remove("ofile/" + filename)
+	}()
+
+	// 返回生成的 Excel 文件
+	c.Ctx.Output.Download("ofile/" + filename)
+
+}
+
+// StockScrapOutExport 报废出库单
+// @Summary 报废出库单
+// @Description 报废出库单
+// @Tags 库存
+// @Param body body dto.StockRefundOutExport true "body"
+// @Success 200 {object} response.Page "{"code": 200, "data": [...]}"
+// @Router /stock-template/inventory/list [post]
+// @Security Bearer
+func (c StockTemplateController) StockScrapOutExport() {
+	reqData := dto.StockRefundOutExport{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+	deptId := beegouser.GetDeptId(c.Ctx)
+	models.InitBasicData(deptId)
+
+	s := services.StockTemplate{}
+
+	list, err := s.StockRefundOutPdf(&reqData, deptId)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	reqData.DeptId = deptId
+	reqData.DeptName = beegouser.GetDeptName(c.Ctx)
+
+	cols := []float64{160, 140, 45, 70, 70, 105, 105, 105}
+
+	header := []string{"品种", "生产企业", "单位", "单价", "数量", "金额", "批号", "有效期"}
+	rows := [][]string{}
+	var totalMoney float64
+	for _, row := range list {
+		temp := []string{}
+		product := utils.ToString(row[models.FieldProductName])
+		enterprise := utils.ToString(row[models.FieldEnterpriseName])
+		batchNumber := utils.ToString(row[models.FieldBatchNumber])
+		temp = append(temp, product)
+		temp = append(temp, fmt.Sprintf("%s", enterprise))
+		temp = append(temp, utils.ToString(row[models.FieldUnitName]))
+		temp = append(temp, fmt.Sprintf("%.01f", utils.ToFloat64(row["unit_price"])))
+		temp = append(temp, fmt.Sprintf("%d", utils.ToInt(row["quantity"])))
+		temp = append(temp, fmt.Sprintf("%.01f", utils.ToFloat64(row["money"])))
+		temp = append(temp, batchNumber)
+		temp = append(temp, utils.ToString(row[models.FieldExpiryDate]))
+
+		rows = append(rows, temp)
+		totalMoney += utils.ToFloat64(row["money"])
+	}
+
+	pdf := &gopdf.GoPdf{}
+	pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 841.89, H: 595.28}})
+	pdf.SetMarginTop(40)
+	pdf.SetMarginBottom(40)
+
+	pdf.AddPage()
+	pdf.AddTTFFont("simsun", "static/fonts/MiSans-Medium.ttf")
+
+	pdf.SetMargins(2, 5, 5, 5)
+	pdf.SetFont("simsun", "", 12)
+
+	titleStr := reqData.DeptName + "报废出库单"
+	pdf.SetFont("simsun", "", 25)
+	textw, _ := pdf.MeasureTextWidth(titleStr)
+	pdf.SetX((840 / 2) - (textw / 2))
+	pdf.SetY(40)
+	pdf.Text(titleStr)
+
+	pdf.SetFont("simsun", "", 12)
+	// 第一行
+	curx, y := 30., pdf.GetY()
+	y += 40
+	pdf.SetXY(curx, y)
+	pdf.Text("开票日期:" + time.Now().Format("2006-01-02"))
+
+	// 第二行
+	curx, y = 30., pdf.GetY()
+	y += 20
+	pdf.SetXY(curx, y)
+	pdf.Text("报废原因:" + reqData.Reason)
+
+	curx = 20
+	y += 10
+	pdf.SetXY(curx, y)
+	h := 20.0
+	x := curx
+	pdf.SetFont("simsun", "", 10)
+	for i := 0; i < len(header); i++ {
+		utils.RectFillColorMultiCell(pdf, header[i], 9, x, y, cols[i], h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += cols[i]
+	}
+	y += h
+	pdf.SetXY(curx, y)
+	pdf.SetFont("simsun", "", 10)
+
+	for _, row := range rows {
+		curx, y = pdf.GetX(), pdf.GetY()
+		x = curx
+
+		height := h
+		for i, txt := range row {
+			lineTexts, _ := pdf.SplitText(txt, cols[i])
+			//lineHt := h * float64(len(lineTexts))
+			if len(lineTexts) > 1 {
+				lineTexts, _ = pdf.SplitText(txt, cols[i]-4)
+				lineHt := h * float64(len(lineTexts)) * 0.6
+				if lineHt > height {
+					height = lineHt
+				}
+			}
+		}
+
+		for i, txt := range row {
+			width := cols[i]
+			utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, height, 0, 0, 0, gopdf.Center, gopdf.Middle)
+			x += width
+		}
+		pdf.SetNewY(y+height, height)
+		pdf.SetX(curx)
+	}
+
+	curx, y = pdf.GetX(), pdf.GetY()
+	x = curx
+	cols2 := []float64{160, 140, 45, 70, 70, 105, 210}
+	row2 := []string{"", "", "", "", "合计:", fmt.Sprintf("%.02f", totalMoney), utils.AmountConvert(totalMoney, true)}
+	for i, txt := range row2 {
+		width := cols2[i]
+		utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += width
+	}
+
+	pdf.SetFont("simsun", "", 12)
+	// 第一行
+	curx, y = 30., pdf.GetY()
+	y += 25
+	pdf.SetXY(curx, y)
+	pdf.Text("制  单 人:" + beegouser.GetUserName(c.Ctx))
+	curx = 265
+	pdf.SetXY(curx, y)
+	pdf.Text("经    办    人:")
+	curx = 565
+	pdf.SetXY(curx, y)
+	pdf.Text("科室负责人:")
+
+	// 第二行
+	curx, y = 30., pdf.GetY()
+	y += 30
+	pdf.SetXY(curx, y)
+	pdf.Text("分管主任:")
+	curx = 265
+	pdf.SetXY(curx, y)
+	pdf.Text("财务部负责人:")
+	curx = 565
+	pdf.SetXY(curx, y)
+	pdf.Text("单位负责人:")
+
+	filename := titleStr + time.Now().Format("20060102150405") + ".pdf"
+	// 保存文件
+	if err = pdf.WritePdf("ofile/" + filename); err != nil {
+		fmt.Println(err)
+	}
+	defer func() {
+		os.Remove("ofile/" + filename)
+	}()
+
+	// 返回生成的 Excel 文件
+	c.Ctx.Output.Download("ofile/" + filename)
+
+}
+
+// TransportRecordExport 运输记录表
+// @Summary 收发登记表word
+// @Description 收发登记表word
+// @Tags 库存
+// @Param body body dto.TransportRecordWordReq true "body"
+// @Success 200 {object} response.Page "{"code": 200, "data": [...]}"
+// @Router /stock-template/inventory/list [post]
+// @Security Bearer
+func (c StockTemplateController) StockOutExport() {
+	reqData := models.TransportRecord{}
+	if err := c.ParseAndValidate(&c.Ctx.Input.RequestBody, &reqData); err != nil {
+		c.Error(global.ParseFormErr, err, err.Error())
+		return
+	}
+	deptId := beegouser.GetDeptId(c.Ctx)
+	models.InitBasicData(deptId)
+
+	s := services.StockTemplate{}
+	barcodeServ := services.Barcode{}
+
+	list, err := s.StockTemplateTransportRecordWord(&reqData, deptId)
+	if err != nil {
+		c.Error(500, err, err.Error())
+		return
+	}
+	reqData.DeptID = deptId
+	reqData.DeptName = beegouser.GetDeptName(c.Ctx)
+	reqData.SetCreateBy(beegouser.GetUserId(c.Ctx))
+	reqData.SetDeptId(deptId)
+	code, err := barcodeServ.Insert(reqData)
+	if err != nil {
+		err = errors.New("生成条码失败")
+		c.Error(500, err, err.Error())
+		return
+	}
+	cs, _ := code128.Encode(code)
+	// 创建一个要输出数据的文件
+	imgPath := "ofile/img/" + code + ".png"
+	file, _ := os.Create(imgPath)
+	defer file.Close()
+
+	// 设置图片像素大小
+	qrCode, _ := barcode.Scale(cs, 205, 50)
+	// 将code128的条形码编码为png图片
+	png.Encode(file, qrCode)
+
+	cols := []float64{100, 80, 85, 70, 70, 30, 35, 35, 50}
+
+	header := []string{"品种", "生产企业", "规格", "批号", "有效期", "单位", "数量", "单价", "总价"}
+	rows := [][]string{}
+	var totalMoney float64
+	var totalQuantity int
+	for _, row := range list {
+		temp := []string{}
+		product := utils.ToString(row[models.FieldProductName])
+		enterprise := utils.ToString(row[models.FieldEnterpriseName])
+		spec := utils.ToString(row[models.FieldSpecName])
+		batchNumber := utils.ToString(row[models.FieldBatchNumber])
+		temp = append(temp, product)
+		temp = append(temp, fmt.Sprintf("%s", enterprise))
+		temp = append(temp, spec)
+		temp = append(temp, batchNumber)
+		temp = append(temp, utils.ToString(row[models.FieldExpiryDate]))
+		temp = append(temp, utils.ToString(row[models.FieldUnitName]))
+		temp = append(temp, fmt.Sprintf("%d", utils.ToInt(row["quantity"])))
+		temp = append(temp, fmt.Sprintf("%.01f", utils.ToFloat64(row["unit_price"])))
+		temp = append(temp, fmt.Sprintf("%.01f", utils.ToFloat64(row["money"])))
+		totalMoney += utils.ToFloat64(row["money"])
+		totalQuantity += utils.ToInt(row["quantity"])
+		rows = append(rows, temp)
+	}
+
+	pdf := &gopdf.GoPdf{}
+	pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 595.28, H: 841.89}})
+	pdf.SetMarginTop(40)
+	pdf.SetMarginBottom(40)
+
+	pdf.AddPage()
+	pdf.AddTTFFont("simsun", "static/fonts/MiSans-Medium.ttf")
+
+	pdf.SetMargins(2, 5, 5, 5)
+	pdf.SetFont("simsun", "", 10)
+	//pdf.SetX(20)
+	//pdf.SetY(20)
+	//pdf.Text("[退货出库]")
+	pdf.SetX(420)
+	pdf.SetY(60)
+	pdf.Text(code)
+
+	imgPath2 := "ofile/img/" + code + ".jpg"
+	png2j.Con2jpg(imgPath, imgPath2)
+	pdf.Image(imgPath2, 390, 15, &gopdf.Rect{W: 200, H: 35})
+
+	titleStr := reqData.DeptName + "出库单"
+	pdf.SetFont("simsun", "", 22)
+	textw, _ := pdf.MeasureTextWidth(titleStr)
+	pdf.SetX((595 / 2) - (textw / 2) - 50)
+	pdf.SetY(40)
+	pdf.Text(titleStr)
+
+	pdf.SetFont("simsun", "", 10)
+	// 第一行
+	curx, y := 20., pdf.GetY()
+	y += 60
+	pdf.SetXY(curx, y)
+	pdf.Text("收货单位:" + reqData.ReceivingUnit)
+
+	curx = 220
+	pdf.SetXY(curx, y)
+	pdf.Text("收货人/电话:")
+
+	curx = 330
+	pdf.SetXY(curx, y)
+	pdf.Text("日期:" + reqData.Date)
+
+	curx = 430
+	pdf.SetXY(curx, y)
+	pdf.Text("单据:" + code)
+
+	curx = 20
+	y += 10
+	pdf.SetXY(curx, y)
+	h := 20.0
+	x := curx
+	pdf.SetFont("simsun", "", 9)
+	for i := 0; i < len(header); i++ {
+		utils.RectFillColorMultiCell(pdf, header[i], 9, x, y, cols[i], h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += cols[i]
+	}
+	y += h
+	pdf.SetXY(curx, y)
+	pdf.SetFont("simsun", "", 8)
+
+	for _, row := range rows {
+		curx, y = pdf.GetX(), pdf.GetY()
+		x = curx
+		height := h
+		for i, txt := range row {
+			lineTexts, _ := pdf.SplitText(txt, cols[i])
+			//lineHt := h * float64(len(lineTexts))
+			if len(lineTexts) > 1 {
+				lineTexts, _ = pdf.SplitText(txt, cols[i]-4)
+				lineHt := h * float64(len(lineTexts)) * 0.6
+				if lineHt > height {
+					height = lineHt
+				}
+			}
+		}
+
+		for i, txt := range row {
+			width := cols[i]
+			utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, height, 0, 0, 0, gopdf.Center, gopdf.Middle)
+			x += width
+		}
+		pdf.SetNewY(y+height, height)
+		pdf.SetX(curx)
+	}
+	curx, y = 20, pdf.GetY()
+	x = curx
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	rows2 := []string{"金额(大写)", utils.AmountConvert(totalMoney, true), fmt.Sprintf("%.1f", totalMoney)}
+	cols2 := [3]float64{}
+	cols2[0] = cols[0]
+	cols2[1] = cols[1] + cols[2] + cols[3]
+	cols2[2] = cols[4] + cols[5] + cols[6] + cols[7] + cols[8]
+	for i, txt := range rows2 {
+		width := cols2[i]
+		utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += width
+	}
+	pdf.SetNewY(y, 20)
+	pdf.SetX(curx)
+
+	curx, y = 20, pdf.GetY()
+	y += 20
+	x = curx
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	rows3 := []string{"数量", fmt.Sprintf("%d", totalQuantity)}
+	cols3 := [2]float64{}
+	cols3[0] = cols[0]
+	cols3[1] = cols[1] + cols[2] + cols[3] + cols[4] + cols[5] + cols[6] + cols[7] + cols[8]
+	for i, txt := range rows3 {
+		width := cols3[i]
+		utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, h, 0, 0, 0, gopdf.Center, gopdf.Middle)
+		x += width
+	}
+	pdf.SetNewY(y, 20)
+	pdf.SetX(curx)
+
+	curx, y = 20, pdf.GetY()
+	y += 20
+	x = curx
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	rows4 := []string{"备注:"}
+	cols4 := [1]float64{}
+	cols4[0] = cols[0] + cols[1] + cols[2] + cols[3] + cols[4] + cols[5] + cols[6] + cols[7] + cols[8]
+	for i, txt := range rows4 {
+		width := cols4[i]
+		utils.RectFillColorMultiCell(pdf, txt, 9, x, y, width, h, 0, 0, 0, gopdf.Left, gopdf.Middle)
+		x += width
+	}
+	pdf.SetNewY(y, 20)
+
+	if pdf.GetY() < 30 {
+		pdf.SetY(30)
+	}
+	y = pdf.GetY()
+	pdf.SetX(curx)
+	y += 40
+	pdf.SetFont("simsun", "", 10)
+	curx = 40
+	pdf.SetXY(curx, y)
+	pdf.Text("主管:")
+
+	curx = 200
+	pdf.SetXY(curx, y)
+	pdf.Text("制单:")
+
+	curx = 400
+	pdf.SetXY(curx, y)
+	pdf.Text("库管:")
+
+	filename := titleStr + time.Now().Format("20060102150405") + ".pdf"
+	// 保存文件
+	if err = pdf.WritePdf("ofile/" + filename); err != nil {
+		fmt.Println(err)
+	}
+	defer func() {
+		os.Remove("ofile/" + filename)
+		os.Remove(imgPath)
+		os.Remove(imgPath2)
+	}()
+
+	// 返回生成的 Excel 文件
+	c.Ctx.Output.Download("ofile/" + filename)
+
+}

+ 22 - 7
dto/stock_template.go

@@ -16,6 +16,7 @@ type StockTemplateInInsertReq struct {
 	Operator       string  `json:"operator"`       // 经办人
 	ForwardingUnit string  `json:"forwardingUnit"` // 发货单位
 	Date           string  `json:"date"`           // 入库日期
+	State          int     `json:"state"`          // 状态 1-正常 2-退货入库
 
 	Img string `json:"img"` // 药品图片
 
@@ -68,6 +69,7 @@ type BatchStockTemplateInInsertReq struct {
 		Date           string                 `json:"date" valid:"MinSize(1)"` // 入库日期
 		Qrcode         string                 `json:"Qrcode"`                  // 追溯码
 	} `json:"stockInList"`
+	State int `json:"state" swaggerignore:"true"` // 状态 1-正常 2-退货入库
 
 	common.ControlBy `swaggerignore:"true"`
 }
@@ -83,8 +85,9 @@ type BatchStockTemplateOutInsertReq struct {
 		ReceivingUnit string `json:"receivingUnit"`           // 收货单位
 		Date          string `json:"date" valid:"MinSize(1)"` // 出库日期
 		Qrcode        string `json:"Qrcode"`                  // 追溯码
-
 	} `json:"stockOutList"`
+	State int `json:"state" swaggerignore:"true"` // 状态 1-正常 2-退货出库 3-报废出库
+
 	common.ControlBy `swaggerignore:"true"`
 }
 
@@ -99,6 +102,7 @@ type StockTemplateOutInsertReq struct {
 	Operator      string `json:"operator"`      // 经办人
 	ReceivingUnit string `json:"receivingUnit"` // 收货单位
 	Date          string `json:"date"`          // 出库日期
+	State         int    `json:"state"`         // 状态 1-正常 2-退货出库 3-报废出库
 
 	common.ControlBy `swaggerignore:"true"`
 }
@@ -142,12 +146,14 @@ func (s *StockTemplateOutDeleteReq) GetId() interface{} {
 // StockTemplateInPageReq 列表或者搜索使用结构体
 type StockTemplateInPageReq struct {
 	dto.Pagination `search:"-"`
-	ProductID      int    `json:"productId"`      // 药品名称id
-	EnterpriseID   int    `json:"enterpriseId"`   // 生产企业id
-	StartDate      string `json:"startDate"`      // 入库开始时间
-	EndDate        string `json:"endDate"`        // 入库结束时间
-	BatchNumber    string `json:"batchNumber"`    // 批号
-	ForwardingUnit string `json:"forwardingUnit"` // 发货单位
+	ProductID      int    `json:"productId"`                  // 药品名称id
+	EnterpriseID   int    `json:"enterpriseId"`               // 生产企业id
+	StartDate      string `json:"startDate"`                  // 入库开始时间
+	EndDate        string `json:"endDate"`                    // 入库结束时间
+	BatchNumber    string `json:"batchNumber"`                // 批号
+	ForwardingUnit string `json:"forwardingUnit"`             // 发货单位
+	Qrcode         string `json:"qrcode"`                     // 条码
+	State          int    `json:"state" swaggerignore:"true"` // 状态 1-正常 2-退货入库
 }
 
 // StockTemplateOutPageReq 列表或者搜索使用结构体
@@ -159,6 +165,8 @@ type StockTemplateOutPageReq struct {
 	EndDate        string `json:"endDate"`       // 出库结束时间
 	BatchNumber    string `json:"batchNumber"`   // 批号
 	ReceivingUnit  string `json:"receivingUnit"` // 收货单位
+	Qrcode         string `json:"qrcode"`        // 条码
+	State          int    `json:"state"`         // 状态 1-正常 2-退货出库 3-报废出库
 }
 
 // StockTemplateInventoryPageReq 列表或者搜索使用结构体
@@ -224,3 +232,10 @@ type StockOperatorListReq struct {
 type GetBarCodeInfoReq struct {
 	Code string `json:"code"`
 }
+
+type StockRefundOutExport struct {
+	Reason      string `json:"reason"`                         // 出库时间
+	DeptId      int    `json:"deptId"  swaggerignore:"true"`   // 部门id
+	DeptName    string `json:"deptName"  swaggerignore:"true"` // 部门名称
+	StockOutIds []int  `json:"stockOutIds"`                    // 出库id列表
+}

+ 1 - 0
models/barcode.go

@@ -14,6 +14,7 @@ type TransportRecord struct {
 	Type             string `json:"type"`                           // 类型
 	DeptID           int    `json:"deptId"  swaggerignore:"true"`   // 部门id
 	DeptName         string `json:"deptName"  swaggerignore:"true"` // 部门名称
+	StockOutIds      []int  `json:"stockOutIds"`                    // 出库id列表
 	model2.ControlBy `gorm:"-"`
 }
 

+ 6 - 1
models/stock_in.go

@@ -4,7 +4,11 @@ import model2 "Medical_ERP/common/model"
 
 // 入库
 
-const TypeStockIn = "stock_in"
+const (
+	TypeStockIn        = "stock_in"
+	StateStockIn       = 1
+	StateStockRefundIn = 2
+)
 
 type StockIn struct {
 	model2.Model
@@ -16,6 +20,7 @@ type StockIn struct {
 	Date           string  `json:"date" gorm:"size:128;"`                            // 入库日期
 	Qrcode         string  `json:"qrcode" gorm:"size:128;"`                          // 条码
 	Number         string  `json:"number" gorm:"size:128;"`                          // 入库单号
+	State          int     `json:"state" gorm:"size:128;default:1;"`                 // 入库状态 1-正常 2-退货入库
 	model2.ControlBy
 	model2.ModelTime
 }

+ 12 - 7
models/stock_out.go

@@ -2,19 +2,24 @@ package models
 
 import model2 "Medical_ERP/common/model"
 
-const TypeStockOut = "stock_out"
+const (
+	TypeStockOut        = "stock_out"
+	StateStockOut       = 1
+	StateStockRefundOut = 2
+	StateStockScrapOut  = 3
+)
 
 type StockOut struct {
 	model2.Model
 	MedicineID int `json:"medicineId" gorm:"size:4;not null;comment:药品信息ID"` // 药品信息ID
 	Quantity   int `json:"quantity" gorm:"size:128;"`                        // 数量
 	//UnitPrice     float32 `json:"unitPrice"`                                        // 销售单价
-	Operator      string `json:"operator" gorm:"size:128;"`      // 经办人
-	ReceivingUnit string `json:"receivingUnit" gorm:"size:128;"` // 收货单位
-	Date          string `json:"date" gorm:"size:128;"`          // 入库日期
-	Qrcode        string `json:"qrcode" gorm:"size:128;"`        // 条码
-	Number        string `json:"number" gorm:"size:128;"`        // 出库入库单号
-
+	Operator      string `json:"operator" gorm:"size:128;"`        // 经办人
+	ReceivingUnit string `json:"receivingUnit" gorm:"size:128;"`   // 收货单位
+	Date          string `json:"date" gorm:"size:128;"`            // 入库日期
+	Qrcode        string `json:"qrcode" gorm:"size:128;"`          // 条码
+	Number        string `json:"number" gorm:"size:128;"`          // 出库入库单号
+	State         int    `json:"state" gorm:"size:128;default:1;"` // 出库状态 1-正常 2-退货出库 3-报废出库
 	model2.ControlBy
 	model2.ModelTime
 }

+ 33 - 16
routers/stock.go

@@ -8,22 +8,39 @@ import (
 func init() {
 	// 分组
 	stockTemplate := beego.NewNamespace("/api/stock-template",
-		beego.NSRouter("/in", &controllers.StockTemplateController{}, "*:StockTemplateIn"),                            // 入库
-		beego.NSRouter("/in/edit", &controllers.StockTemplateController{}, "*:StockTemplateInEdit"),                   // 入库 - 编辑
-		beego.NSRouter("/in/delete", &controllers.StockTemplateController{}, "*:StockTemplateInDelete"),               // 入库 - 删除
-		beego.NSRouter("/batch-in", &controllers.StockTemplateController{}, "*:BatchStockTemplateIn"),                 // 批量入库
-		beego.NSRouter("/out", &controllers.StockTemplateController{}, "*:StockTemplateOut"),                          // 出库
-		beego.NSRouter("/out/edit", &controllers.StockTemplateController{}, "*:StockTemplateOutEdit"),                 // 出库 - 编辑
-		beego.NSRouter("/out/delete", &controllers.StockTemplateController{}, "*:StockTemplateOutDelete"),             // 出库 - 删除
-		beego.NSRouter("/batch-out", &controllers.StockTemplateController{}, "*:BatchStockTemplateOut"),               // 批量出库
-		beego.NSRouter("/in/list", &controllers.StockTemplateController{}, "*:StockTemplateInList"),                   // 入库列表
-		beego.NSRouter("/out/list", &controllers.StockTemplateController{}, "*:StockTemplateOutList"),                 // 出库列表
-		beego.NSRouter("/inventory/list", &controllers.StockTemplateController{}, "*:StockTemplateInventoryList"),     // 收发记录
-		beego.NSRouter("/inventory/export", &controllers.StockTemplateController{}, "*:StockTemplateInventoryExport"), // 库存 - excel
-		beego.NSRouter("/transport-record/export", &controllers.StockTemplateController{}, "*:TransportRecordExport"),
-		beego.NSRouter("/transport-record/barcode-info", &controllers.StockTemplateController{}, "*:GetBarCodeInfo"), // 获取条码信息
-		beego.NSRouter("/scan-code-in", &controllers.StockTemplateController{}, "*:StockTemplateInScanCode"),         // 扫码入库
-		beego.NSRouter("/scan-code-out", &controllers.StockTemplateController{}, "*:StockTemplateOutScanCode"),       // 扫码出库
+		beego.NSRouter("/in", &controllers.StockTemplateController{}, "*:StockTemplateIn"),                                          // 入库
+		beego.NSRouter("/in/edit", &controllers.StockTemplateController{}, "*:StockTemplateInEdit"),                                 // 入库 - 编辑
+		beego.NSRouter("/in/delete", &controllers.StockTemplateController{}, "*:StockTemplateInDelete"),                             // 入库 - 删除
+		beego.NSRouter("/batch-in", &controllers.StockTemplateController{}, "*:BatchStockTemplateIn"),                               // 批量入库
+		beego.NSRouter("/out", &controllers.StockTemplateController{}, "*:StockTemplateOut"),                                        // 出库
+		beego.NSRouter("/out/edit", &controllers.StockTemplateController{}, "*:StockTemplateOutEdit"),                               // 出库 - 编辑
+		beego.NSRouter("/out/delete", &controllers.StockTemplateController{}, "*:StockTemplateOutDelete"),                           // 出库 - 删除
+		beego.NSRouter("/batch-out", &controllers.StockTemplateController{}, "*:BatchStockTemplateOut"),                             // 批量出库
+		beego.NSRouter("/in/list", &controllers.StockTemplateController{}, "*:StockTemplateInList"),                                 // 入库列表
+		beego.NSRouter("/out/list", &controllers.StockTemplateController{}, "*:StockTemplateOutList"),                               // 出库列表
+		beego.NSRouter("/inventory/list", &controllers.StockTemplateController{}, "*:StockTemplateInventoryList"),                   // 收发记录
+		beego.NSRouter("/inventory/export", &controllers.StockTemplateController{}, "*:StockTemplateInventoryExport"),               // 库存 - excel
+		beego.NSRouter("/transport-record/export", &controllers.StockTemplateController{}, "*:TransportRecordExport"),               // 运输登记表
+		beego.NSRouter("/transport-record/list", &controllers.StockTemplateController{}, "*:TransportRecordExportList"),             // 运输登记表产品明细
+		beego.NSRouter("/transport-record/barcode-info", &controllers.StockTemplateController{}, "*:GetTransportRecordBarCodeInfo"), // 获取条码信息
+		beego.NSRouter("/scan-code-in", &controllers.StockTemplateController{}, "*:StockTemplateInScanCode"),                        // 扫码入库
+		beego.NSRouter("/scan-code-out", &controllers.StockTemplateController{}, "*:StockTemplateOutScanCode"),                      // 扫码出库
+		beego.NSRouter("/out/export", &controllers.StockTemplateController{}, "*:StockOutExport"),                                   // 出库单
+
+		beego.NSRouter("/refund/in/list", &controllers.StockTemplateController{}, "*:StockTemplateRefundInList"),          // 退货入库列表
+		beego.NSRouter("/refund/in", &controllers.StockTemplateController{}, "*:StockTemplateRefundIn"),                   // 退货入库
+		beego.NSRouter("/refund/batch-in", &controllers.StockTemplateController{}, "*:BatchStockTemplateRefundIn"),        // 批量退货入库
+		beego.NSRouter("/refund/scan-code-in", &controllers.StockTemplateController{}, "*:StockTemplateRefundInScanCode"), // 扫码退货入库
+
+		beego.NSRouter("/refund/out/list", &controllers.StockTemplateController{}, "*:StockTemplateRefundOutList"),                             // 退货/报废出库列表
+		beego.NSRouter("/refund/out", &controllers.StockTemplateController{}, "*:StockTemplateRefundOut"),                                      // 退货/报废出库
+		beego.NSRouter("/refund/batch-out", &controllers.StockTemplateController{}, "*:BatchStockTemplateRefundOut"),                           // 批量退货/报废出库
+		beego.NSRouter("/refund/scan-code-out", &controllers.StockTemplateController{}, "*:StockTemplateRefundOutScanCode"),                    // 扫码退货/报废出库
+		beego.NSRouter("/refund/out/transport-record/export", &controllers.StockTemplateController{}, "*:StockRefundOutTransportRecordExport"), // 退货出库运输温度记录表
+		beego.NSRouter("/refund/out/barcode-info", &controllers.StockTemplateController{}, "*:GetRefundOutBarCodeInfo"),                        // 退货出库二维码信息
+		beego.NSRouter("/refund/out/export", &controllers.StockTemplateController{}, "*:StockRefundOutExport"),                                 // 退货单
+		beego.NSRouter("/scrap/out/export", &controllers.StockTemplateController{}, "*:StockScrapOutExport"),                                   // 退货单
+
 	)
 	stock := beego.NewNamespace("/api/stock",
 		beego.NSRouter("/unit/list", &controllers.StockTemplateController{}, "*:StockUnitList"),         // 收/发货单位列表

+ 23 - 3
services/barcode.go

@@ -17,10 +17,10 @@ type Barcode struct {
 }
 
 // getNextIncrementalCode 从数据库中获取下一个递增码
-func (e *Barcode) getNextIncrementalCode() (string, error) {
+func (e *Barcode) getNextIncrementalCode(deptId int) (string, error) {
 	// 获取当前日期
 	var count int64
-	current := time.Now().Format("20060102")
+	current := fmt.Sprintf("%05d%s", deptId, time.Now().Format("20060102"))
 	err := db.DB.Model(&models.Barcode{}).Where("code LIKE ?", current+"%").Count(&count).Error
 	if err != nil {
 		logs.Error("db error: %s", err)
@@ -32,7 +32,7 @@ func (e *Barcode) getNextIncrementalCode() (string, error) {
 
 // Insert 创建Spec对象
 func (e *Barcode) Insert(c models.TransportRecord) (code string, err error) {
-	incrementalCode, err := e.getNextIncrementalCode()
+	incrementalCode, err := e.getNextIncrementalCode(c.DeptID)
 	if err != nil {
 		logs.Error("生成条形码失败", err)
 		return code, global.CreateFailedErr
@@ -46,6 +46,26 @@ func (e *Barcode) Insert(c models.TransportRecord) (code string, err error) {
 	return data.Code, nil
 }
 
+// Insert 创建Spec对象
+func (e *Barcode) InsertRefundOut(c dto.StockRefundOutExport) (code string, err error) {
+	incrementalCode, err := e.getNextIncrementalCode(c.DeptId)
+	if err != nil {
+		logs.Error("生成条形码失败", err)
+		return code, global.CreateFailedErr
+	}
+	var obj models.TransportRecord
+	obj.StockOutIds = c.StockOutIds
+	obj.DeptID = c.DeptId
+	obj.DeptName = c.DeptName
+	data := models.Barcode{Code: incrementalCode, Data: obj, ControlBy: model2.ControlBy{CreateBy: obj.CreateBy, DeptId: c.DeptId}}
+	err = db.DB.Create(&data).Error
+	if err != nil {
+		logs.Error("db error: %s", err)
+		return code, global.CreateFailedErr
+	}
+	return data.Code, nil
+}
+
 // Get 获取DosageForm对象
 func (e *Barcode) Get(d *dto.GetBarCodeInfoReq, barcodeModel *models.Barcode) error {
 	err := db.DB.Where("code = ?", d.Code).First(barcodeModel).Error

+ 5 - 0
services/medicine_template.go

@@ -379,6 +379,11 @@ func (e *MedicineTemplate) GetColumns(columnsList *[]dto.MedicineColumnsRes, p *
 		return global.GetFailedErr
 	}
 
+	*columnsList = append(*columnsList, dto.MedicineColumnsRes{
+		Label: "条码",
+		Prop:  "qrcode",
+		Width: 200,
+	})
 	for _, v := range list {
 
 		fieldName := v.FieldName

+ 5 - 7
services/sales.go

@@ -18,7 +18,7 @@ type Sales struct {
 func (e *Sales) SalesList(c *dto.SalesPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND stock_out.deleted_at is null"
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
 	if c.ProductID > 0 {
 		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
 	}
@@ -38,7 +38,6 @@ func (e *Sales) SalesList(c *dto.SalesPageReq, deptId int) (list []map[string]in
 		whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
 	}
 	err = db.DB.Table("stock_out").
-		//Select(mtable + ".*,stock_out.*,stock_out.unit_price as sales_unit_price").
 		Scopes(
 			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
 		).
@@ -76,7 +75,7 @@ func (e *Sales) SalesList(c *dto.SalesPageReq, deptId int) (list []map[string]in
 func (e *Sales) SalesListExcel(c *dto.SalesPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND stock_out.deleted_at is null"
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
 	if c.ProductID > 0 {
 		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
 	}
@@ -96,7 +95,6 @@ func (e *Sales) SalesListExcel(c *dto.SalesPageReq, deptId int) (list []map[stri
 		whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
 	}
 	err = db.DB.Table("stock_out").
-		//Select(mtable + ".*,stock_out.*," + mtable + ".unit_price as unit_price").
 		Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
 		Where(whereSql).
 		Scan(&list).Error
@@ -132,7 +130,7 @@ func (e *Sales) SalesListExcel(c *dto.SalesPageReq, deptId int) (list []map[stri
 func (e *Sales) SalesReportList(c *dto.SalesPageReq, deptId int) (list []map[string]interface{}, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND stock_out.deleted_at is null"
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
 	if c.ProductID > 0 {
 		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
 	}
@@ -186,7 +184,7 @@ func (e *Sales) SalesReportList(c *dto.SalesPageReq, deptId int) (list []map[str
 func (e *Sales) SalesOrderList(c *dto.SalesOrderPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND stock_out.deleted_at is null"
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
 	if c.ProductID > 0 {
 		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
 	}
@@ -244,7 +242,7 @@ func (e *Sales) SalesOrderList(c *dto.SalesOrderPageReq, deptId int) (list []map
 func (e *Sales) SalesStockOutExcel(c *dto.SalesStockOutExcelReq, deptId int) (list []map[string]interface{}, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND stock_out.deleted_at is null"
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
 	if len(c.Date) > 0 {
 		whereSql += " AND stock_out.date = '" + c.Date + "'"
 	}

+ 480 - 129
services/stock_template.go

@@ -79,7 +79,7 @@ func (e *StockTemplate) GetStockNumber(stock string) (number string, err error)
 }
 
 // GetMedicineInfo 通过名称、生产企业、规格、批号查询药品信息
-func (e *StockTemplate) GetMedicineInfo(deptId int, medicine map[string]interface{}) (medicineInfo map[string]interface{}, err error) {
+func (e *StockTemplate) GetMedicineInfo(deptId int, medicine map[string]interface{}) (medicineInfo map[string]interface{}, key string, err error) {
 
 	productID := utils.ToInt(medicine[models.FieldProductID])
 	enterpriseID := utils.ToInt(medicine[models.FieldEnterpriseID])
@@ -87,6 +87,7 @@ func (e *StockTemplate) GetMedicineInfo(deptId int, medicine map[string]interfac
 	batchNumber := medicine[models.FieldBatchNumber]
 	sql := `SELECT * FROM ` + models.GetMedicineInfoTableName(deptId) + ` WHERE product_id = ? AND enterprise_id = ? AND spec_id = ? AND batch_number = ? `
 	err = db.DB.Raw(sql, productID, enterpriseID, specID, batchNumber).Scan(&medicineInfo).Error
+	key = fmt.Sprintf("%d_%d_%d_%d_%s", deptId, productID, enterpriseID, specID, batchNumber)
 	return
 }
 func (e *StockTemplate) GetMedicineInfoForImg(medicine map[string]interface{}) (medicineImg models.MedicineImg, err error) {
@@ -240,70 +241,76 @@ func (e *StockTemplate) BatchStockTemplateIn(req *dto.BatchStockTemplateInInsert
 		return err
 	}
 
+	var medicineInfoMap = make(map[string]int)
 	//var err error
 	tx := db.DB.Begin()
 
 	for _, c := range req.StockInList {
 		// 检查药品信息是否已存在
-		medicineInfo, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
+		medicineInfo, key, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
 		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
 			tx.Rollback()
 			logs.Error("db error: %s", err)
 			return global.CreateFailedErr
 		}
 		var medicineInfoId int
+		var ok bool
+		// 药品已经存在,但因为事务未提交查询不到则直接获取药品信息ID
+		medicineInfoId, ok = medicineInfoMap[key]
+		if !ok {
+			// 如果药品信息不存在,则创建新的药品信息
+			if medicineInfo == nil {
+				sql := "INSERT INTO " + models.GetMedicineInfoTableName(req.DeptId) + " SET "
+				for k, v := range c.MedicineInfo {
+					sql += fmt.Sprintf("`%s`='%v',", k, v)
+				}
+				sql += fmt.Sprintf("`%s`='%v',", "unit_price", c.UnitPrice)
 
-		// 如果药品信息不存在,则创建新的药品信息
-		if medicineInfo == nil {
-			sql := "INSERT INTO " + models.GetMedicineInfoTableName(req.DeptId) + " SET "
-			for k, v := range c.MedicineInfo {
-				sql += fmt.Sprintf("`%s`='%v',", k, v)
-			}
-			sql += fmt.Sprintf("`%s`='%v',", "unit_price", c.UnitPrice)
-
-			sql = sql[:len(sql)-1]
-			err = tx.Exec(sql).Error
-			if err != nil {
-				tx.Rollback()
-				logs.Error("db error: %s", err)
-				return global.CreateFailedErr
-			}
-			err = tx.Raw("SELECT LAST_INSERT_ID()").Scan(&medicineInfoId).Error
-			if err != nil {
-				tx.Rollback()
-				logs.Error("db error: %s", err)
-				return global.CreateFailedErr
-			}
-			// 添加药品图片信息
-			medicineImg, err := e.GetMedicineInfoForImg(c.MedicineInfo)
-			if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
-				tx.Rollback()
-				logs.Error("获取药品图片信息失败: %s", err)
-				return global.CreateFailedErr
-			}
-			medicineImg.DeptId = req.DeptId
-			medicineImg.CreateBy = req.CreateBy
-			err = tx.Where(models.MedicineImg{
-				Product:     medicineImg.Product,
-				Enterprise:  medicineImg.Enterprise,
-				Spec:        medicineImg.Spec,
-				BatchNumber: medicineImg.BatchNumber,
-				ControlBy: model2.ControlBy{
-					DeptId: req.DeptId,
-				}}).
-				Assign(medicineImg).FirstOrCreate(&medicineImg).Error
-			if err != nil {
-				tx.Rollback()
-				logs.Error("添加药品图片信息失败: %s", err)
-				return global.CreateFailedErr
-			}
-		} else {
-			medicineInfoId = utils.ToInt(medicineInfo["id"])
-			err = tx.Table(models.GetMedicineInfoTableName(req.DeptId)).Where("id = ?", medicineInfoId).Update("unit_price", c.UnitPrice).Error
-			if err != nil {
-				tx.Rollback()
-				logs.Error("db error: %s", err)
-				return global.CreateFailedErr
+				sql = sql[:len(sql)-1]
+				err = tx.Exec(sql).Error
+				if err != nil {
+					tx.Rollback()
+					logs.Error("db error: %s", err)
+					return global.CreateFailedErr
+				}
+				err = tx.Raw("SELECT LAST_INSERT_ID()").Scan(&medicineInfoId).Error
+				medicineInfoMap[key] = medicineInfoId
+				if err != nil {
+					tx.Rollback()
+					logs.Error("db error: %s", err)
+					return global.CreateFailedErr
+				}
+				// 添加药品图片信息
+				medicineImg, err := e.GetMedicineInfoForImg(c.MedicineInfo)
+				if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+					tx.Rollback()
+					logs.Error("获取药品图片信息失败: %s", err)
+					return global.CreateFailedErr
+				}
+				medicineImg.DeptId = req.DeptId
+				medicineImg.CreateBy = req.CreateBy
+				err = tx.Where(models.MedicineImg{
+					Product:     medicineImg.Product,
+					Enterprise:  medicineImg.Enterprise,
+					Spec:        medicineImg.Spec,
+					BatchNumber: medicineImg.BatchNumber,
+					ControlBy: model2.ControlBy{
+						DeptId: req.DeptId,
+					}}).
+					Assign(medicineImg).FirstOrCreate(&medicineImg).Error
+				if err != nil {
+					tx.Rollback()
+					logs.Error("添加药品图片信息失败: %s", err)
+					return global.CreateFailedErr
+				}
+			} else {
+				medicineInfoId = utils.ToInt(medicineInfo["id"])
+				err = tx.Table(models.GetMedicineInfoTableName(req.DeptId)).Where("id = ?", medicineInfoId).Update("unit_price", c.UnitPrice).Error
+				if err != nil {
+					tx.Rollback()
+					logs.Error("db error: %s", err)
+					return global.CreateFailedErr
+				}
 			}
 		}
 
@@ -316,6 +323,7 @@ func (e *StockTemplate) BatchStockTemplateIn(req *dto.BatchStockTemplateInInsert
 			ForwardingUnit: c.ForwardingUnit,
 			Date:           c.Date,
 			Number:         number,
+			State:          req.State,
 			ControlBy: model2.ControlBy{
 				DeptId:   req.DeptId,
 				CreateBy: req.CreateBy,
@@ -409,7 +417,7 @@ func (e *StockTemplate) StockTemplateInScanCode(req *dto.BatchStockTemplateInIns
 			return err
 		}
 	}
-
+	var medicineInfoMap = make(map[string]int)
 	//var err error
 	tx := db.DB.Begin()
 
@@ -427,76 +435,83 @@ func (e *StockTemplate) StockTemplateInScanCode(req *dto.BatchStockTemplateInIns
 		}
 
 		// 检查药品信息是否已存在
-		medicineInfo, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
+		medicineInfo, key, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
 		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
 			tx.Rollback()
 			logs.Error("db error: %s", err)
 			return global.CreateFailedErr
 		}
+
 		var medicineInfoId int
+		var ok bool
+		// 药品已经存在,但因为事务未提交查询不到则直接获取药品信息ID
+		medicineInfoId, ok = medicineInfoMap[key]
+		if !ok {
+			// 如果药品信息不存在,则创建新的药品信息
+			if medicineInfo == nil {
+				sql := "INSERT INTO " + models.GetMedicineInfoTableName(req.DeptId) + " SET "
+				for k, v := range c.MedicineInfo {
+					// 不是系统初始化字段
+					if !models.GetMedicineInfoFieldIsSysInit(k) {
+						continue
+					}
+					if v == nil {
+						continue
+					}
+					sql += fmt.Sprintf("`%s`='%v',", k, v)
 
-		// 如果药品信息不存在,则创建新的药品信息
-		if medicineInfo == nil {
-			sql := "INSERT INTO " + models.GetMedicineInfoTableName(req.DeptId) + " SET "
-			for k, v := range c.MedicineInfo {
-				// 不是系统初始化字段
-				if !models.GetMedicineInfoFieldIsSysInit(k) {
-					continue
-				}
-				if v == nil {
-					continue
 				}
-				sql += fmt.Sprintf("`%s`='%v',", k, v)
+				sql += fmt.Sprintf("`%s`='%v',", "unit_price", c.UnitPrice)
+				sql += fmt.Sprintf("`%s`='%v',", "qrcode", c.Qrcode)
 
+				sql = sql[:len(sql)-1]
+				err = tx.Exec(sql).Error
+				if err != nil {
+					tx.Rollback()
+					logs.Error("db error: %s", err)
+					return global.CreateFailedErr
+				}
+				err = tx.Raw("SELECT LAST_INSERT_ID()").Scan(&medicineInfoId).Error
+				if err != nil {
+					tx.Rollback()
+					logs.Error("db error: %s", err)
+					return global.CreateFailedErr
+				}
+				medicineInfoMap[key] = medicineInfoId
+				// 添加药品图片信息
+				medicineImg, err := e.GetMedicineInfoScanCodeForImg(mi)
+				if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+					tx.Rollback()
+					logs.Error("获取药品图片信息失败: %s", err)
+					return global.CreateFailedErr
+				}
+				medicineImg.Qrcode = c.Qrcode
+				medicineImg.DeptId = req.DeptId
+				medicineImg.CreateBy = req.CreateBy
+				err = tx.Where(models.MedicineImg{
+					Product:     medicineImg.Product,
+					Enterprise:  medicineImg.Enterprise,
+					Spec:        medicineImg.Spec,
+					BatchNumber: medicineImg.BatchNumber,
+					ControlBy: model2.ControlBy{
+						DeptId: req.DeptId,
+					}}).
+					Assign(medicineImg).FirstOrCreate(&medicineImg).Error
+				if err != nil {
+					tx.Rollback()
+					logs.Error("添加药品图片信息失败: %s", err)
+					return global.CreateFailedErr
+				}
+			} else {
+				medicineInfoId = utils.ToInt(medicineInfo["id"])
+				err = tx.Table(models.GetMedicineInfoTableName(req.DeptId)).Where("id = ?", medicineInfoId).Update("unit_price", c.UnitPrice).Error
+				if err != nil {
+					tx.Rollback()
+					logs.Error("db error: %s", err)
+					return global.CreateFailedErr
+				}
 			}
-			sql += fmt.Sprintf("`%s`='%v',", "unit_price", c.UnitPrice)
-			sql += fmt.Sprintf("`%s`='%v',", "qrcode", c.Qrcode)
 
-			sql = sql[:len(sql)-1]
-			err = tx.Exec(sql).Error
-			if err != nil {
-				tx.Rollback()
-				logs.Error("db error: %s", err)
-				return global.CreateFailedErr
-			}
-			err = tx.Raw("SELECT LAST_INSERT_ID()").Scan(&medicineInfoId).Error
-			if err != nil {
-				tx.Rollback()
-				logs.Error("db error: %s", err)
-				return global.CreateFailedErr
-			}
-			// 添加药品图片信息
-			medicineImg, err := e.GetMedicineInfoScanCodeForImg(mi)
-			if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
-				tx.Rollback()
-				logs.Error("获取药品图片信息失败: %s", err)
-				return global.CreateFailedErr
-			}
-			medicineImg.Qrcode = c.Qrcode
-			medicineImg.DeptId = req.DeptId
-			medicineImg.CreateBy = req.CreateBy
-			err = tx.Where(models.MedicineImg{
-				Product:     medicineImg.Product,
-				Enterprise:  medicineImg.Enterprise,
-				Spec:        medicineImg.Spec,
-				BatchNumber: medicineImg.BatchNumber,
-				ControlBy: model2.ControlBy{
-					DeptId: req.DeptId,
-				}}).
-				Assign(medicineImg).FirstOrCreate(&medicineImg).Error
-			if err != nil {
-				tx.Rollback()
-				logs.Error("添加药品图片信息失败: %s", err)
-				return global.CreateFailedErr
-			}
-		} else {
-			medicineInfoId = utils.ToInt(medicineInfo["id"])
-			err = tx.Table(models.GetMedicineInfoTableName(req.DeptId)).Where("id = ?", medicineInfoId).Update("unit_price", c.UnitPrice).Error
-			if err != nil {
-				tx.Rollback()
-				logs.Error("db error: %s", err)
-				return global.CreateFailedErr
-			}
 		}
 
 		// 进行入库操作
@@ -509,6 +524,7 @@ func (e *StockTemplate) StockTemplateInScanCode(req *dto.BatchStockTemplateInIns
 			Date:           c.Date,
 			Qrcode:         c.Qrcode,
 			Number:         number,
+			State:          req.State,
 			ControlBy: model2.ControlBy{
 				DeptId:   req.DeptId,
 				CreateBy: req.CreateBy,
@@ -567,7 +583,7 @@ func (e *StockTemplate) StockTemplateIn(c *dto.StockTemplateInInsertReq) error {
 		return err
 	}
 	// 检查药品信息是否已存在
-	medicineInfo, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
+	medicineInfo, _, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
 	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
 		logs.Error("db error: %s", err)
 		return global.CreateFailedErr
@@ -639,6 +655,7 @@ func (e *StockTemplate) StockTemplateIn(c *dto.StockTemplateInInsertReq) error {
 		ForwardingUnit: c.ForwardingUnit,
 		Date:           c.Date,
 		Number:         number,
+		State:          c.State,
 		ControlBy: model2.ControlBy{
 			DeptId:   c.DeptId,
 			CreateBy: c.CreateBy,
@@ -689,7 +706,7 @@ func (e *StockTemplate) StockTemplateIn(c *dto.StockTemplateInInsertReq) error {
 func (e *StockTemplate) StockTemplateInEdit(c *dto.StockTemplateInEditReq) error {
 	var err error
 	// 检查药品信息是否已存在
-	medicineInfo, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
+	medicineInfo, _, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
 	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
 		logs.Error("db error: %s", err)
 		return global.UpdateFailedErr
@@ -935,7 +952,7 @@ func (e *StockTemplate) StockTemplateOut(c *dto.StockTemplateOutInsertReq) error
 		return err
 	}
 	// 检查药品信息是否已存在
-	medicineInfo, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
+	medicineInfo, _, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
 	if err != nil {
 		logs.Error("db error: %s", err)
 		return global.CreateFailedErr
@@ -974,6 +991,7 @@ func (e *StockTemplate) StockTemplateOut(c *dto.StockTemplateOutInsertReq) error
 		ReceivingUnit: c.ReceivingUnit,
 		Date:          c.Date,
 		Number:        number,
+		State:         c.State,
 		ControlBy: model2.ControlBy{
 			DeptId:   c.DeptId,
 			CreateBy: c.CreateBy,
@@ -1025,7 +1043,7 @@ func (e *StockTemplate) StockTemplateOut(c *dto.StockTemplateOutInsertReq) error
 func (e *StockTemplate) StockTemplateOutEdit(c *dto.StockTemplateOutEditReq) error {
 	var err error
 	// 检查药品信息是否已存在
-	medicineInfo, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
+	medicineInfo, _, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
 	if err != nil {
 		logs.Error("db error: %s", err)
 		if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -1264,7 +1282,7 @@ func (e *StockTemplate) BatchStockTemplateOut(req *dto.BatchStockTemplateOutInse
 	tx := db.DB.Begin()
 	for _, c := range req.StockOutList {
 		// 检查药品信息是否已存在
-		medicineInfo, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
+		medicineInfo, _, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
 		if err != nil {
 			tx.Rollback()
 			logs.Error("db error: %s", err)
@@ -1380,7 +1398,7 @@ func (e *StockTemplate) StockTemplateOutScanCode(req *dto.BatchStockTemplateOutI
 			return err
 		}
 		// 检查药品信息是否已存在
-		medicineInfo, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
+		medicineInfo, _, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
 		if err != nil {
 			tx.Rollback()
 			logs.Error("db error: %s", err)
@@ -1423,6 +1441,7 @@ func (e *StockTemplate) StockTemplateOutScanCode(req *dto.BatchStockTemplateOutI
 			Date:          c.Date,
 			Qrcode:        c.Qrcode,
 			Number:        number,
+			State:         req.State,
 			ControlBy: model2.ControlBy{
 				DeptId:   req.DeptId,
 				CreateBy: req.CreateBy,
@@ -1476,7 +1495,7 @@ func (e *StockTemplate) StockTemplateOutScanCode(req *dto.BatchStockTemplateOutI
 func (e *StockTemplate) StockTemplateInList(c *dto.StockTemplateInPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_in.dept_id = " + strconv.Itoa(deptId) + " AND stock_in.deleted_at is null"
+	whereSql := "stock_in.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_in.deleted_at is null"
 	if c.ProductID > 0 {
 		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
 	}
@@ -1495,6 +1514,78 @@ func (e *StockTemplate) StockTemplateInList(c *dto.StockTemplateInPageReq, deptI
 	if len(c.ForwardingUnit) > 0 {
 		whereSql += " AND stock_in.forwarding_unit like '%" + c.ForwardingUnit + "%'"
 	}
+	if len(c.Qrcode) > 0 {
+		whereSql += " AND stock_in.qrcode like '%" + c.Qrcode + "%'"
+	}
+	err = db.DB.Table("stock_in").
+		Select(mtable + ".*,stock_in.*,stock_in.id AS id").
+		Scopes(
+			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
+		).
+		Joins("left join " + mtable + " on stock_in.medicine_id = " + mtable + ".id").
+		Where(whereSql).
+		Order("stock_in.date desc,stock_in.id desc").
+		Scan(&list).Limit(-1).Offset(-1).
+		Count(&count).Error
+	if err != nil {
+		logs.Error("db error: %s ", err)
+		return list, count, global.GetFailedErr
+	}
+	models.InitBasicData(deptId)
+	for i := 0; i < len(list); i++ {
+		if id, ok := list[i][models.FieldProductID]; ok {
+			list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldEnterpriseID]; ok {
+			list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldSpecID]; ok {
+			list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldUnitID]; ok {
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldUnitID] = nil
+			} else {
+				list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
+			}
+		}
+		if id, ok := list[i][models.FieldDosageFormID]; ok {
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
+		}
+		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
+	}
+	return list, count, nil
+}
+func (e *StockTemplate) StockTemplateRefundInList(c *dto.StockTemplateInPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
+
+	mtable := models.GetMedicineInfoTableName(deptId)
+	whereSql := "stock_in.dept_id = " + strconv.Itoa(deptId) + " AND state = 2 AND stock_in.deleted_at is null"
+	if c.ProductID > 0 {
+		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
+	}
+	if c.EnterpriseID > 0 {
+		whereSql += " AND " + mtable + ".enterprise_id = " + strconv.Itoa(c.EnterpriseID)
+	}
+	if len(c.BatchNumber) > 0 {
+		whereSql += " AND " + mtable + ".batch_number = " + c.BatchNumber
+	}
+	if len(c.StartDate) > 0 {
+		whereSql += " AND stock_in.date >= '" + c.StartDate + "'"
+	}
+	if len(c.EndDate) > 0 {
+		whereSql += " AND stock_in.date <= '" + c.EndDate + "'"
+	}
+	if len(c.ForwardingUnit) > 0 {
+		whereSql += " AND stock_in.forwarding_unit like '%" + c.ForwardingUnit + "%'"
+	}
+	if len(c.Qrcode) > 0 {
+		whereSql += " AND stock_in.qrcode like '%" + c.Qrcode + "%'"
+	}
 	err = db.DB.Table("stock_in").
 		Select(mtable + ".*,stock_in.*,stock_in.id AS id").
 		Scopes(
@@ -1544,7 +1635,7 @@ func (e *StockTemplate) StockTemplateInList(c *dto.StockTemplateInPageReq, deptI
 func (e *StockTemplate) StockTemplateOutList(c *dto.StockTemplateOutPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND stock_out.deleted_at is null"
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
 	if c.ProductID > 0 {
 		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
 	}
@@ -1563,6 +1654,9 @@ func (e *StockTemplate) StockTemplateOutList(c *dto.StockTemplateOutPageReq, dep
 	if len(c.ReceivingUnit) > 0 {
 		whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
 	}
+	if len(c.Qrcode) > 0 {
+		whereSql += " AND stock_out.qrcode like '%" + c.Qrcode + "%'"
+	}
 	err = db.DB.Table("stock_out").
 		Select(mtable + ".*," + "stock_out.*,stock_out.id AS id," + mtable + ".unit_price as sales_unit_price").
 		Scopes(
@@ -1602,8 +1696,81 @@ func (e *StockTemplate) StockTemplateOutList(c *dto.StockTemplateOutPageReq, dep
 				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
 			}
 		}
+		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
+	}
+	return list, count, nil
+}
+func (e *StockTemplate) StockTemplateRefundOutList(c *dto.StockTemplateOutPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
+
+	mtable := models.GetMedicineInfoTableName(deptId)
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
 
+	if c.ProductID > 0 {
+		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
+	}
+	if c.EnterpriseID > 0 {
+		whereSql += " AND " + mtable + ".enterprise_id = " + strconv.Itoa(c.EnterpriseID)
+	}
+	if len(c.BatchNumber) > 0 {
+		whereSql += " AND " + mtable + ".batch_number = " + c.BatchNumber
+	}
+	if len(c.StartDate) > 0 {
+		whereSql += " AND stock_out.date >= '" + c.StartDate + "'"
+	}
+	if len(c.EndDate) > 0 {
+		whereSql += " AND stock_out.date <= '" + c.EndDate + "'"
+	}
+	if len(c.ReceivingUnit) > 0 {
+		whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
+	}
+	if len(c.Qrcode) > 0 {
+		whereSql += " AND stock_out.qrcode like '%" + c.Qrcode + "%'"
+	}
+	if c.State > 0 {
+		whereSql += " AND stock_out.state = " + strconv.Itoa(c.State)
+	}
+	err = db.DB.Table("stock_out").
+		Select(mtable + ".*," + "stock_out.*,stock_out.id AS id," + mtable + ".unit_price as sales_unit_price").
+		Scopes(
+			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
+		).
+		Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
+		Where(whereSql).
+		Order("stock_out.date desc,stock_out.id desc").
+		Scan(&list).Limit(-1).Offset(-1).
+		Count(&count).Error
+	if err != nil {
+		logs.Error("db error: %s ", err)
+		return list, count, global.GetFailedErr
+	}
+	models.InitBasicData(deptId)
+	for i := 0; i < len(list); i++ {
+		if id, ok := list[i][models.FieldProductID]; ok {
+			list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldEnterpriseID]; ok {
+			list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldSpecID]; ok {
+			list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldUnitID]; ok {
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldUnitID] = nil
+			} else {
+				list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
+			}
+		}
+		if id, ok := list[i][models.FieldDosageFormID]; ok {
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
+		}
 		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
 	}
 	return list, count, nil
 }
@@ -1659,9 +1826,14 @@ func (e *StockTemplate) StockTemplateInventoryList(c *dto.StockTemplateInventory
 			list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
 		}
 		if id, ok := list[i][models.FieldDosageFormID]; ok {
-			list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
 		}
 		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
 	}
 	return list, count, nil
 }
@@ -1709,8 +1881,14 @@ func (e *StockTemplate) StockTemplateInventoryExcel(c *dto.StockTemplateInventor
 			list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
 		}
 		if id, ok := list[i][models.FieldDosageFormID]; ok {
-			list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
 		}
+		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
 	}
 	return list, nil
 }
@@ -1855,9 +2033,14 @@ func (e *StockTemplate) StockInquiryList(c *dto.StockStatListReq, deptId int) (l
 			list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
 		}
 		if id, ok := list[i][models.FieldDosageFormID]; ok {
-			list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
 		}
 		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
 	}
 	return list, count, nil
 
@@ -1911,9 +2094,14 @@ func (e *StockTemplate) StockInquiryExcel(c *dto.StockStatListReq, deptId int) (
 			list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
 		}
 		if id, ok := list[i][models.FieldDosageFormID]; ok {
-			list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
 		}
 		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
 	}
 	return list, nil
 
@@ -2068,10 +2256,106 @@ func (e *StockTemplate) StockHomeStat(deptId int) (list map[string]interface{},
 	return list, count, nil
 
 }
+func (e *StockTemplate) StockTemplateTransportRecordWord2(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
+
+	mtable := models.GetMedicineInfoTableName(deptId)
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
+	if c.ProductID > 0 {
+		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
+	}
+	if len(c.Date) > 0 {
+		whereSql += " AND stock_out.date = '" + c.Date + "'"
+	}
+	if len(c.ReceivingUnit) > 0 {
+		whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
+	}
+	if len(c.StockOutIds) > 0 {
+		whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
+	}
+	err = db.DB.Table("stock_out").
+		Select(mtable + ".*,stock_out.quantity as quantity,stock_out.id as stock_out_id," + mtable + ".id as medicine_id").
+		Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
+		Where(whereSql).
+		Scan(&list).Error
+	if err != nil {
+		logs.Error("db error: %s ", err)
+		return list, global.GetFailedErr
+	}
+	models.InitBasicData(deptId)
+	for i := 0; i < len(list); i++ {
+		if id, ok := list[i][models.FieldProductID]; ok {
+			list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldEnterpriseID]; ok {
+			list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldSpecID]; ok {
+			list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldUnitID]; ok {
+			list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
+		}
+	}
+	return list, nil
+
+}
+
 func (e *StockTemplate) StockTemplateTransportRecordWord(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND stock_out.deleted_at is null"
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
+	if c.ProductID > 0 {
+		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
+	}
+	if len(c.Date) > 0 {
+		whereSql += " AND stock_out.date = '" + c.Date + "'"
+	}
+	if len(c.ReceivingUnit) > 0 {
+		whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
+	}
+	if len(c.StockOutIds) > 0 {
+		whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
+	}
+	err = db.DB.Table("stock_out").
+		Select("stock_out.*,stock_out.id as stock_out_id," + mtable + ".*," + mtable + ".id as medicine_id").
+		Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
+		Where(whereSql).
+		Scan(&list).Error
+	if err != nil {
+		logs.Error("db error: %s ", err)
+		return list, global.GetFailedErr
+	}
+	models.InitBasicData(deptId)
+	for i := 0; i < len(list); i++ {
+		if id, ok := list[i][models.FieldProductID]; ok {
+			list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldEnterpriseID]; ok {
+			list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldSpecID]; ok {
+			list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldUnitID]; ok {
+			list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldDosageFormID]; ok {
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
+		}
+		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
+	}
+	return list, nil
+
+}
+func (e *StockTemplate) StockRefundOutTransportRecordPdf(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
+
+	mtable := models.GetMedicineInfoTableName(deptId)
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
 	if c.ProductID > 0 {
 		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
 	}
@@ -2081,7 +2365,11 @@ func (e *StockTemplate) StockTemplateTransportRecordWord(c *models.TransportReco
 	if len(c.ReceivingUnit) > 0 {
 		whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
 	}
+	if len(c.StockOutIds) > 0 {
+		whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
+	}
 	err = db.DB.Table("stock_out").
+		Select("stock_out.*,stock_out.id as stock_out_id," + mtable + ".*," + mtable + ".id as medicine_id").
 		Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
 		Where(whereSql).
 		Scan(&list).Error
@@ -2091,6 +2379,9 @@ func (e *StockTemplate) StockTemplateTransportRecordWord(c *models.TransportReco
 	}
 	models.InitBasicData(deptId)
 	for i := 0; i < len(list); i++ {
+		list[i]["unit_price"] = utils.ToFloat64(list[i]["unit_price"])
+		// 金额
+		list[i]["money"] = utils.ToFloat64(list[i]["unit_price"]) * utils.ToFloat64(list[i]["quantity"])
 		if id, ok := list[i][models.FieldProductID]; ok {
 			list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
 		}
@@ -2103,14 +2394,24 @@ func (e *StockTemplate) StockTemplateTransportRecordWord(c *models.TransportReco
 		if id, ok := list[i][models.FieldUnitID]; ok {
 			list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
 		}
+		if id, ok := list[i][models.FieldDosageFormID]; ok {
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
+		}
+		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
 	}
 	return list, nil
 
 }
-func (e *StockTemplate) StockTemplateTransportRecordWord2(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
+
+func (e *StockTemplate) GetRefundOutBarCodeInfo(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
 
 	mtable := models.GetMedicineInfoTableName(deptId)
-	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND stock_out.deleted_at is null"
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
 	if c.ProductID > 0 {
 		whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
 	}
@@ -2120,8 +2421,11 @@ func (e *StockTemplate) StockTemplateTransportRecordWord2(c *models.TransportRec
 	if len(c.ReceivingUnit) > 0 {
 		whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
 	}
+	if len(c.StockOutIds) > 0 {
+		whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
+	}
 	err = db.DB.Table("stock_out").
-		Select(mtable + ".*,stock_out.quantity as quantity").
+		Select(mtable + ".*,stock_out.quantity as quantity,stock_out.id as stock_out_id," + mtable + ".id as medicine_id").
 		Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
 		Where(whereSql).
 		Scan(&list).Error
@@ -2147,3 +2451,50 @@ func (e *StockTemplate) StockTemplateTransportRecordWord2(c *models.TransportRec
 	return list, nil
 
 }
+
+func (e *StockTemplate) StockRefundOutPdf(c *dto.StockRefundOutExport, deptId int) (list []map[string]interface{}, err error) {
+
+	mtable := models.GetMedicineInfoTableName(deptId)
+	whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
+	if len(c.StockOutIds) > 0 {
+		whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
+	}
+	err = db.DB.Table("stock_out").
+		Select("stock_out.*,stock_out.id as stock_out_id," + mtable + ".*," + mtable + ".id as medicine_id").
+		Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
+		Where(whereSql).
+		Scan(&list).Error
+	if err != nil {
+		logs.Error("db error: %s ", err)
+		return list, global.GetFailedErr
+	}
+	models.InitBasicData(deptId)
+	for i := 0; i < len(list); i++ {
+		list[i]["unit_price"] = utils.ToFloat64(list[i]["unit_price"])
+		// 金额
+		list[i]["money"] = utils.ToFloat64(list[i]["unit_price"]) * utils.ToFloat64(list[i]["quantity"])
+		if id, ok := list[i][models.FieldProductID]; ok {
+			list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldEnterpriseID]; ok {
+			list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldSpecID]; ok {
+			list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldUnitID]; ok {
+			list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
+		}
+		if id, ok := list[i][models.FieldDosageFormID]; ok {
+			if utils.ToInt(id) == 0 {
+				list[i][models.FieldDosageFormID] = nil
+			} else {
+				list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
+			}
+		}
+		list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
+		list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
+	}
+	return list, nil
+
+}

+ 7 - 1
utils/comm.go

@@ -294,7 +294,7 @@ func IsChineseOnly(s string) bool {
 
 func AmountConvert(p_money float64, p_round bool) string {
 	var NumberUpper = []string{"壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "零"}
-	var Unit = []string{"分", "角", "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"}
+	var Unit = []string{"分", "角", "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"}
 	var regex = [][]string{
 		{"零拾", "零"}, {"零佰", "零"}, {"零仟", "零"}, {"零零零", "零"}, {"零零", "零"},
 		{"零角零分", "整"}, {"零分", "整"}, {"零角", "零"}, {"零亿零万零元", "亿元"},
@@ -345,3 +345,9 @@ func AmountConvert(p_money float64, p_round bool) string {
 	}
 	return str
 }
+func IntArrayToStringArray(list []int) (res []string) {
+	for i := 0; i < len(list); i++ {
+		res = append(res, strconv.Itoa(list[i]))
+	}
+	return res
+}