stock_template.go 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551
  1. package services
  2. import (
  3. cDto "Medical_ERP/common/dto"
  4. "Medical_ERP/common/global"
  5. db "Medical_ERP/common/initialize"
  6. model2 "Medical_ERP/common/model"
  7. "Medical_ERP/dto"
  8. "Medical_ERP/models"
  9. "Medical_ERP/utils"
  10. "errors"
  11. "fmt"
  12. "github.com/beego/beego/v2/core/logs"
  13. "gorm.io/gorm"
  14. "math/rand"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "time"
  19. )
  20. type StockTemplate struct {
  21. }
  22. func (e *StockTemplate) GetStockNumber(stock string) (number string, err error) {
  23. switch stock {
  24. case models.TypeStockIn:
  25. var stockIn models.StockIn
  26. for {
  27. rand.New(rand.NewSource(time.Now().UnixNano()))
  28. // 生成随机数后八位
  29. randomSuffix := rand.Intn(99999999)
  30. // 格式化年月日
  31. date := time.Now().Format("20060102")
  32. // 组合成16位随机数
  33. randomNumber := fmt.Sprintf("%s%08d", date, randomSuffix)
  34. // 查询数据库,检查随机数是否存在
  35. if err = db.DB.Where("number = ?", randomNumber).First(&stockIn).Error; err != nil {
  36. if err == gorm.ErrRecordNotFound {
  37. return "RK" + randomNumber, nil
  38. } else {
  39. logs.Error("db error: %s", err)
  40. return number, err
  41. }
  42. }
  43. }
  44. case models.TypeStockOut:
  45. var stockOut models.StockOut
  46. for {
  47. rand.New(rand.NewSource(time.Now().UnixNano()))
  48. // 生成随机数后八位
  49. randomSuffix := rand.Intn(99999999)
  50. // 格式化年月日
  51. date := time.Now().Format("20060102")
  52. // 组合成16位随机数
  53. randomNumber := fmt.Sprintf("%s%08d", date, randomSuffix)
  54. // 查询数据库,检查随机数是否存在
  55. if err = db.DB.Where("number = ?", randomNumber).First(&stockOut).Error; err != nil {
  56. if err == gorm.ErrRecordNotFound {
  57. return "CK" + randomNumber, nil
  58. } else {
  59. logs.Error("db error: %s", err)
  60. return number, err
  61. }
  62. }
  63. }
  64. }
  65. return number, errors.New("生成随机数失败")
  66. }
  67. // GetMedicineInfo 通过名称、生产企业、规格、批号查询药品信息
  68. func (e *StockTemplate) GetMedicineInfo(deptId int, medicine map[string]interface{}) (medicineInfo map[string]interface{}, key string, err error) {
  69. productID := utils.ToInt(medicine[models.FieldProductID])
  70. enterpriseID := utils.ToInt(medicine[models.FieldEnterpriseID])
  71. specID := utils.ToInt(medicine[models.FieldSpecID])
  72. batchNumber := medicine[models.FieldBatchNumber]
  73. sql := `SELECT * FROM ` + models.GetMedicineInfoTableName(deptId) + ` WHERE product_id = ? AND enterprise_id = ? AND spec_id = ? AND batch_number = ? `
  74. err = db.DB.Raw(sql, productID, enterpriseID, specID, batchNumber).Scan(&medicineInfo).Error
  75. key = fmt.Sprintf("%d_%d_%d_%d_%s", deptId, productID, enterpriseID, specID, batchNumber)
  76. return
  77. }
  78. func (e *StockTemplate) GetMedicineInfoForImg(medicine map[string]interface{}) (medicineImg models.MedicineImg, err error) {
  79. productID := utils.ToInt(medicine[models.FieldProductID])
  80. enterpriseID := utils.ToInt(medicine[models.FieldEnterpriseID])
  81. specID := utils.ToInt(medicine[models.FieldSpecID])
  82. unitID := utils.ToInt(medicine[models.FieldUnitID])
  83. dosageFormID := utils.ToInt(medicine[models.FieldDosageFormID])
  84. batchNumber := utils.ToString(medicine[models.FieldBatchNumber])
  85. medicineImg.BatchNumber = batchNumber
  86. medicineImg.ApprovalNumber = utils.ToString(medicine[models.FieldApprovalNumber])
  87. medicineImg.QualificationNumber = utils.ToString(medicine[models.FieldQualificationNumber])
  88. medicineImg.ProductionDate = utils.ToString(medicine[models.FieldProducedDate])
  89. medicineImg.ExpiryDate = utils.ToString(medicine[models.FieldExpiryDate])
  90. product := models.Product{}
  91. if err = db.DB.Model(&product).First(&product, productID).Error; err != nil {
  92. medicineImg.Product = product.Name
  93. }
  94. enterprise := models.Enterprise{}
  95. if err = db.DB.Model(&enterprise).First(&enterprise, enterpriseID).Error; err != nil {
  96. medicineImg.Enterprise = enterprise.Name
  97. }
  98. spec := models.Spec{}
  99. if err = db.DB.Model(&spec).First(&spec, specID).Error; err != nil {
  100. medicineImg.Spec = spec.Name
  101. }
  102. unit := models.Unit{}
  103. if unitID > 0 {
  104. if err = db.DB.Model(&unit).First(&unit, unitID).Error; err != nil {
  105. medicineImg.Unit = unit.Name
  106. }
  107. }
  108. dosageForm := models.DosageForm{}
  109. if dosageFormID > 0 {
  110. if err = db.DB.Model(&dosageForm).First(&dosageForm, dosageFormID).Error; err != nil {
  111. medicineImg.DosageForm = dosageForm.Name
  112. }
  113. }
  114. return
  115. }
  116. func (e *StockTemplate) GetMedicineInfoScanCodeForImg(medicine map[string]interface{}) (medicineImg models.MedicineImg, err error) {
  117. medicineImg.Product = utils.ToString(medicine[models.FieldProductName])
  118. medicineImg.Enterprise = utils.ToString(medicine[models.FieldEnterpriseName])
  119. medicineImg.Spec = utils.ToString(medicine[models.FieldSpecName])
  120. medicineImg.Unit = utils.ToString(medicine[models.FieldUnitName])
  121. medicineImg.DosageForm = utils.ToString(medicine[models.FieldDosageFormName])
  122. medicineImg.BatchNumber = utils.ToString(medicine[models.FieldBatchNumber])
  123. medicineImg.ApprovalNumber = utils.ToString(medicine[models.FieldApprovalNumber])
  124. medicineImg.QualificationNumber = utils.ToString(medicine[models.FieldQualificationNumber])
  125. medicineImg.ProductionDate = utils.ToString(medicine[models.FieldProducedDate])
  126. medicineImg.ExpiryDate = utils.ToString(medicine[models.FieldExpiryDate])
  127. return
  128. }
  129. // FirstOrCreateMedicineInfo 查询或创建 品名、生产企业、规格、单位、剂型
  130. func (e *StockTemplate) FirstOrCreateMedicineInfo(deptId, createBy int, medicine *map[string]interface{}) (err error) {
  131. // 查询或创建品名
  132. product := models.Product{}
  133. if productName, ok := (*medicine)[models.FieldProductName].(string); ok && len(productName) > 0 {
  134. err = db.DB.Attrs(map[string]interface{}{"create_by": createBy}).FirstOrCreate(&product, map[string]interface{}{
  135. "name": productName,
  136. "dept_id": deptId,
  137. }).Error
  138. if err != nil {
  139. return errors.New("获取品名失败")
  140. }
  141. delete(*medicine, models.FieldProductName)
  142. } else {
  143. return errors.New("品名不能为空")
  144. }
  145. // 查询或创建生产企业
  146. enterprise := models.Enterprise{}
  147. if enterpriseName, ok := (*medicine)[models.FieldEnterpriseName].(string); ok && len(enterpriseName) > 0 {
  148. err = db.DB.Attrs(map[string]interface{}{"create_by": createBy}).FirstOrCreate(&enterprise, map[string]interface{}{
  149. "name": enterpriseName,
  150. "dept_id": deptId,
  151. }).Error
  152. if err != nil {
  153. return errors.New("获取生产企业失败")
  154. }
  155. delete(*medicine, models.FieldEnterpriseName)
  156. } else {
  157. return errors.New("生产企业不能为空")
  158. }
  159. // 查询或创建规格
  160. spec := models.Spec{}
  161. if specName, ok := (*medicine)[models.FieldSpecName].(string); ok && len(specName) > 0 {
  162. err = db.DB.Attrs(map[string]interface{}{"create_by": createBy}).FirstOrCreate(&spec, map[string]interface{}{
  163. "name": specName,
  164. "dept_id": deptId,
  165. }).Error
  166. if err != nil {
  167. return errors.New("获取规格失败")
  168. }
  169. delete(*medicine, models.FieldSpecName)
  170. } else {
  171. return errors.New("规格不能为空")
  172. }
  173. // 查询或创建单位
  174. unit := models.Unit{}
  175. if unitName, ok := (*medicine)[models.FieldUnitName].(string); ok && len(unitName) > 0 {
  176. err = db.DB.Attrs(map[string]interface{}{"create_by": createBy}).FirstOrCreate(&unit, map[string]interface{}{
  177. "name": unitName,
  178. "dept_id": deptId,
  179. }).Error
  180. if err != nil {
  181. return errors.New("获取单位失败")
  182. }
  183. }
  184. // 查询或创建剂型
  185. dosageForm := models.DosageForm{}
  186. if dosageFormName, ok := (*medicine)[models.FieldDosageFormName].(string); ok && len(dosageFormName) > 0 {
  187. err = db.DB.Attrs(map[string]interface{}{"create_by": createBy}).FirstOrCreate(&dosageForm, map[string]interface{}{
  188. "name": dosageFormName,
  189. "dept_id": deptId,
  190. }).Error
  191. if err != nil {
  192. return errors.New("获取剂型失败")
  193. }
  194. }
  195. delete(*medicine, models.FieldUnitName)
  196. delete(*medicine, models.FieldDosageFormName)
  197. (*medicine)[models.FieldProductID] = product.Id
  198. (*medicine)[models.FieldEnterpriseID] = enterprise.Id
  199. (*medicine)[models.FieldSpecID] = spec.Id
  200. (*medicine)[models.FieldUnitID] = unit.Id
  201. (*medicine)[models.FieldDosageFormID] = dosageForm.Id
  202. return
  203. }
  204. // BatchStockTemplateIn 批量入库
  205. func (e *StockTemplate) BatchStockTemplateIn(req *dto.BatchStockTemplateInInsertReq) error {
  206. number, err := e.GetStockNumber(models.TypeStockIn)
  207. if err != nil {
  208. logs.Error("获取: %s", err)
  209. return err
  210. }
  211. var medicineInfoMap = make(map[string]int)
  212. //var err error
  213. tx := db.DB.Begin()
  214. for _, c := range req.StockInList {
  215. // 检查药品信息是否已存在
  216. medicineInfo, key, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
  217. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  218. tx.Rollback()
  219. logs.Error("db error: %s", err)
  220. return global.CreateFailedErr
  221. }
  222. var medicineInfoId int
  223. var ok bool
  224. // 药品已经存在,但因为事务未提交查询不到则直接获取药品信息ID
  225. medicineInfoId, ok = medicineInfoMap[key]
  226. if !ok {
  227. // 如果药品信息不存在,则创建新的药品信息
  228. if medicineInfo == nil {
  229. sql := "INSERT INTO " + models.GetMedicineInfoTableName(req.DeptId) + " SET "
  230. for k, v := range c.MedicineInfo {
  231. sql += fmt.Sprintf("`%s`='%v',", k, v)
  232. }
  233. sql += fmt.Sprintf("`%s`='%v',", "unit_price", c.UnitPrice)
  234. sql = sql[:len(sql)-1]
  235. err = tx.Exec(sql).Error
  236. if err != nil {
  237. tx.Rollback()
  238. logs.Error("db error: %s", err)
  239. return global.CreateFailedErr
  240. }
  241. err = tx.Raw("SELECT LAST_INSERT_ID()").Scan(&medicineInfoId).Error
  242. medicineInfoMap[key] = medicineInfoId
  243. if err != nil {
  244. tx.Rollback()
  245. logs.Error("db error: %s", err)
  246. return global.CreateFailedErr
  247. }
  248. // 添加药品图片信息
  249. medicineImg, err := e.GetMedicineInfoForImg(c.MedicineInfo)
  250. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  251. tx.Rollback()
  252. logs.Error("获取药品图片信息失败: %s", err)
  253. return global.CreateFailedErr
  254. }
  255. medicineImg.DeptId = req.DeptId
  256. medicineImg.CreateBy = req.CreateBy
  257. err = tx.Where(models.MedicineImg{
  258. Product: medicineImg.Product,
  259. Enterprise: medicineImg.Enterprise,
  260. Spec: medicineImg.Spec,
  261. BatchNumber: medicineImg.BatchNumber,
  262. ControlBy: model2.ControlBy{
  263. DeptId: req.DeptId,
  264. }}).
  265. Assign(medicineImg).FirstOrCreate(&medicineImg).Error
  266. if err != nil {
  267. tx.Rollback()
  268. logs.Error("添加药品图片信息失败: %s", err)
  269. return global.CreateFailedErr
  270. }
  271. } else {
  272. medicineInfoId = utils.ToInt(medicineInfo["id"])
  273. err = tx.Table(models.GetMedicineInfoTableName(req.DeptId)).Where("id = ?", medicineInfoId).Update("unit_price", c.UnitPrice).Error
  274. if err != nil {
  275. tx.Rollback()
  276. logs.Error("db error: %s", err)
  277. return global.CreateFailedErr
  278. }
  279. }
  280. }
  281. // 进行入库操作
  282. stockInRecord := models.StockIn{
  283. MedicineID: medicineInfoId,
  284. Quantity: c.Quantity,
  285. UnitPrice: c.UnitPrice,
  286. Operator: c.Operator,
  287. ForwardingUnit: c.ForwardingUnit,
  288. Date: c.Date,
  289. Number: number,
  290. State: req.State,
  291. ControlBy: model2.ControlBy{
  292. DeptId: req.DeptId,
  293. CreateBy: req.CreateBy,
  294. },
  295. }
  296. err = tx.Create(&stockInRecord).Error
  297. if err != nil {
  298. tx.Rollback()
  299. logs.Error("db error: %s", err)
  300. return global.CreateFailedErr
  301. }
  302. c.Id = stockInRecord.Id
  303. var inventory models.MedicineInventory
  304. err = tx.Last(&inventory, "medicine_id = ? and dept_id = ?", medicineInfoId, req.DeptId).Error
  305. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  306. tx.Rollback()
  307. logs.Error("db error: %s", err)
  308. return global.CreateFailedErr
  309. }
  310. // 添加库存记录
  311. data := models.MedicineInventory{
  312. MedicineID: medicineInfoId,
  313. TotalIn: c.Quantity,
  314. StockInID: stockInRecord.Id,
  315. TotalOut: 0,
  316. StockOutID: 0,
  317. Balance: inventory.Balance + c.Quantity,
  318. ForwardingUnit: c.ForwardingUnit,
  319. Operator: c.Operator,
  320. Date: c.Date,
  321. ControlBy: model2.ControlBy{
  322. DeptId: req.DeptId,
  323. CreateBy: req.CreateBy,
  324. },
  325. }
  326. err = tx.Create(&data).Error
  327. if err != nil {
  328. tx.Rollback()
  329. logs.Error("db error: %s", err)
  330. return global.CreateFailedErr
  331. }
  332. }
  333. tx.Commit()
  334. return nil
  335. }
  336. func (e *StockTemplate) CheckStockForQrcode(Qrcode string, stock string) error {
  337. var err error
  338. if !strings.HasPrefix(Qrcode, "9") {
  339. return nil
  340. }
  341. switch stock {
  342. case models.TypeStockIn:
  343. var stockIn models.StockIn
  344. err = db.DB.Where("qrcode = ?", Qrcode).First(&stockIn).Error
  345. if err != nil {
  346. if errors.Is(err, gorm.ErrRecordNotFound) {
  347. return nil
  348. }
  349. return errors.New("通过条码信息查询入库记录失败")
  350. }
  351. return errors.New(fmt.Sprintf("条码[%s]已入库,禁止重复入库", Qrcode))
  352. case models.TypeStockOut:
  353. var stockOut models.StockOut
  354. err = db.DB.Where("qrcode = ?", Qrcode).First(&stockOut).Error
  355. if err != nil {
  356. if errors.Is(err, gorm.ErrRecordNotFound) {
  357. return nil
  358. }
  359. return errors.New("通过条码信息查询入库记录失败")
  360. }
  361. return errors.New(fmt.Sprintf("条码[%s]已出库,禁止重复出库", Qrcode))
  362. }
  363. return nil
  364. }
  365. // BatchStockTemplateIn 扫码入库
  366. func (e *StockTemplate) StockTemplateInScanCode(req *dto.BatchStockTemplateInInsertReq) error {
  367. number, err := e.GetStockNumber(models.TypeStockIn)
  368. if err != nil {
  369. logs.Error("获取: %s", err)
  370. return err
  371. }
  372. for _, s := range req.StockInList {
  373. err := e.CheckStockForQrcode(s.Qrcode, models.TypeStockIn)
  374. if err != nil {
  375. return err
  376. }
  377. }
  378. var medicineInfoMap = make(map[string]int)
  379. //var err error
  380. tx := db.DB.Begin()
  381. for i, c := range req.StockInList {
  382. mi := make(map[string]interface{})
  383. for k, v := range c.MedicineInfo {
  384. mi[k] = v
  385. }
  386. if qrcode, ok := c.MedicineInfo["qrcode"].(string); ok && len(qrcode) > 0 && len(req.StockInList[i].Qrcode) == 0 {
  387. c.Qrcode = qrcode
  388. }
  389. // 检查药品信息是否已存在
  390. err := e.FirstOrCreateMedicineInfo(req.DeptId, req.CreateBy, &c.MedicineInfo)
  391. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  392. tx.Rollback()
  393. logs.Error("【扫码入库】初始化药品信息失败:%s", err)
  394. return err
  395. }
  396. // 检查药品信息是否已存在
  397. medicineInfo, key, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
  398. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  399. tx.Rollback()
  400. logs.Error("db error: %s", err)
  401. return global.CreateFailedErr
  402. }
  403. var medicineInfoId int
  404. var ok bool
  405. // 药品已经存在,但因为事务未提交查询不到则直接获取药品信息ID
  406. medicineInfoId, ok = medicineInfoMap[key]
  407. if !ok {
  408. // 如果药品信息不存在,则创建新的药品信息
  409. if medicineInfo == nil {
  410. sql := "INSERT INTO " + models.GetMedicineInfoTableName(req.DeptId) + " SET "
  411. for k, v := range c.MedicineInfo {
  412. // 不是系统初始化字段
  413. if !models.GetMedicineInfoFieldIsSysInit(k) {
  414. continue
  415. }
  416. if v == nil {
  417. continue
  418. }
  419. sql += fmt.Sprintf("`%s`='%v',", k, v)
  420. }
  421. sql += fmt.Sprintf("`%s`='%v',", "unit_price", c.UnitPrice)
  422. sql += fmt.Sprintf("`%s`='%v',", "qrcode", c.Qrcode)
  423. sql = sql[:len(sql)-1]
  424. err = tx.Exec(sql).Error
  425. if err != nil {
  426. tx.Rollback()
  427. logs.Error("db error: %s", err)
  428. return global.CreateFailedErr
  429. }
  430. err = tx.Raw("SELECT LAST_INSERT_ID()").Scan(&medicineInfoId).Error
  431. if err != nil {
  432. tx.Rollback()
  433. logs.Error("db error: %s", err)
  434. return global.CreateFailedErr
  435. }
  436. medicineInfoMap[key] = medicineInfoId
  437. // 添加药品图片信息
  438. medicineImg, err := e.GetMedicineInfoScanCodeForImg(mi)
  439. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  440. tx.Rollback()
  441. logs.Error("获取药品图片信息失败: %s", err)
  442. return global.CreateFailedErr
  443. }
  444. medicineImg.Qrcode = c.Qrcode
  445. medicineImg.DeptId = req.DeptId
  446. medicineImg.CreateBy = req.CreateBy
  447. err = tx.Where(models.MedicineImg{
  448. Product: medicineImg.Product,
  449. Enterprise: medicineImg.Enterprise,
  450. Spec: medicineImg.Spec,
  451. BatchNumber: medicineImg.BatchNumber,
  452. ControlBy: model2.ControlBy{
  453. DeptId: req.DeptId,
  454. }}).
  455. Assign(medicineImg).FirstOrCreate(&medicineImg).Error
  456. if err != nil {
  457. tx.Rollback()
  458. logs.Error("添加药品图片信息失败: %s", err)
  459. return global.CreateFailedErr
  460. }
  461. } else {
  462. medicineInfoId = utils.ToInt(medicineInfo["id"])
  463. err = tx.Table(models.GetMedicineInfoTableName(req.DeptId)).Where("id = ?", medicineInfoId).Update("unit_price", c.UnitPrice).Error
  464. if err != nil {
  465. tx.Rollback()
  466. logs.Error("db error: %s", err)
  467. return global.CreateFailedErr
  468. }
  469. }
  470. }
  471. // 进行入库操作
  472. stockInRecord := models.StockIn{
  473. MedicineID: medicineInfoId,
  474. Quantity: c.Quantity,
  475. UnitPrice: c.UnitPrice,
  476. Operator: c.Operator,
  477. ForwardingUnit: c.ForwardingUnit,
  478. Date: c.Date,
  479. Qrcode: c.Qrcode,
  480. Number: number,
  481. State: req.State,
  482. ControlBy: model2.ControlBy{
  483. DeptId: req.DeptId,
  484. CreateBy: req.CreateBy,
  485. },
  486. }
  487. err = tx.Create(&stockInRecord).Error
  488. if err != nil {
  489. tx.Rollback()
  490. logs.Error("db error: %s", err)
  491. return global.CreateFailedErr
  492. }
  493. c.Id = stockInRecord.Id
  494. var inventory models.MedicineInventory
  495. err = tx.Last(&inventory, "medicine_id = ? and dept_id = ?", medicineInfoId, req.DeptId).Error
  496. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  497. tx.Rollback()
  498. logs.Error("db error: %s", err)
  499. return global.CreateFailedErr
  500. }
  501. // 添加库存记录
  502. data := models.MedicineInventory{
  503. MedicineID: medicineInfoId,
  504. TotalIn: c.Quantity,
  505. StockInID: stockInRecord.Id,
  506. TotalOut: 0,
  507. StockOutID: 0,
  508. Balance: inventory.Balance + c.Quantity,
  509. ForwardingUnit: c.ForwardingUnit,
  510. Operator: c.Operator,
  511. Date: c.Date,
  512. ControlBy: model2.ControlBy{
  513. DeptId: req.DeptId,
  514. CreateBy: req.CreateBy,
  515. },
  516. }
  517. err = tx.Create(&data).Error
  518. if err != nil {
  519. tx.Rollback()
  520. logs.Error("db error: %s", err)
  521. return global.CreateFailedErr
  522. }
  523. }
  524. tx.Commit()
  525. return nil
  526. }
  527. // StockTemplateIn 入库
  528. func (e *StockTemplate) StockTemplateIn(c *dto.StockTemplateInInsertReq) error {
  529. var err error
  530. number, err := e.GetStockNumber(models.TypeStockIn)
  531. if err != nil {
  532. logs.Error("获取: %s", err)
  533. return err
  534. }
  535. // 检查药品信息是否已存在
  536. medicineInfo, _, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
  537. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  538. logs.Error("db error: %s", err)
  539. return global.CreateFailedErr
  540. }
  541. var medicineInfoId int
  542. tx := db.DB.Begin()
  543. // 如果药品信息不存在,则创建新的药品信息
  544. if medicineInfo == nil {
  545. sql := "INSERT INTO " + models.GetMedicineInfoTableName(c.DeptId) + " SET "
  546. for k, v := range c.MedicineInfo {
  547. sql += fmt.Sprintf("`%s`='%v',", k, v)
  548. }
  549. sql += fmt.Sprintf("`%s`='%v',", "unit_price", c.UnitPrice)
  550. sql = sql[:len(sql)-1]
  551. err = tx.Exec(sql).Error
  552. if err != nil {
  553. tx.Rollback()
  554. logs.Error("db error: %s", err)
  555. return global.CreateFailedErr
  556. }
  557. err = tx.Raw("SELECT LAST_INSERT_ID()").Scan(&medicineInfoId).Error
  558. if err != nil {
  559. tx.Rollback()
  560. logs.Error("db error: %s", err)
  561. return global.CreateFailedErr
  562. }
  563. // 添加药品图片信息
  564. medicineImg, err := e.GetMedicineInfoForImg(c.MedicineInfo)
  565. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  566. tx.Rollback()
  567. logs.Error("获取药品图片信息失败: %s", err)
  568. return global.CreateFailedErr
  569. }
  570. medicineImg.DeptId = c.DeptId
  571. medicineImg.CreateBy = c.CreateBy
  572. err = tx.Where(models.MedicineImg{
  573. Product: medicineImg.Product,
  574. Enterprise: medicineImg.Enterprise,
  575. Spec: medicineImg.Spec,
  576. BatchNumber: medicineImg.BatchNumber,
  577. ControlBy: model2.ControlBy{
  578. DeptId: c.DeptId,
  579. }}).
  580. Assign(medicineImg).FirstOrCreate(&medicineImg).Error
  581. if err != nil {
  582. tx.Rollback()
  583. logs.Error("添加药品图片信息失败: %s", err)
  584. return global.CreateFailedErr
  585. }
  586. } else {
  587. medicineInfoId = utils.ToInt(medicineInfo["id"])
  588. err = tx.Table(models.GetMedicineInfoTableName(c.DeptId)).Where("id = ?", medicineInfoId).Update("unit_price", c.UnitPrice).Error
  589. if err != nil {
  590. tx.Rollback()
  591. logs.Error("db error: %s", err)
  592. return global.CreateFailedErr
  593. }
  594. }
  595. // 进行入库操作
  596. stockInRecord := models.StockIn{
  597. MedicineID: medicineInfoId,
  598. Quantity: c.Quantity,
  599. UnitPrice: c.UnitPrice,
  600. Operator: c.Operator,
  601. ForwardingUnit: c.ForwardingUnit,
  602. Date: c.Date,
  603. Number: number,
  604. State: c.State,
  605. ControlBy: model2.ControlBy{
  606. DeptId: c.DeptId,
  607. CreateBy: c.CreateBy,
  608. },
  609. }
  610. err = tx.Create(&stockInRecord).Error
  611. if err != nil {
  612. tx.Rollback()
  613. logs.Error("db error: %s", err)
  614. return global.CreateFailedErr
  615. }
  616. c.Id = stockInRecord.Id
  617. var inventory models.MedicineInventory
  618. err = tx.Last(&inventory, "medicine_id = ? and dept_id = ?", medicineInfoId, c.DeptId).Error
  619. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  620. tx.Rollback()
  621. logs.Error("db error: %s", err)
  622. return global.CreateFailedErr
  623. }
  624. // 添加库存记录
  625. data := models.MedicineInventory{
  626. MedicineID: medicineInfoId,
  627. TotalIn: c.Quantity,
  628. StockInID: stockInRecord.Id,
  629. TotalOut: 0,
  630. StockOutID: 0,
  631. Balance: inventory.Balance + c.Quantity,
  632. ForwardingUnit: c.ForwardingUnit,
  633. Operator: c.Operator,
  634. Date: c.Date,
  635. ControlBy: model2.ControlBy{
  636. DeptId: c.DeptId,
  637. CreateBy: c.CreateBy,
  638. },
  639. }
  640. err = tx.Create(&data).Error
  641. if err != nil {
  642. tx.Rollback()
  643. logs.Error("db error: %s", err)
  644. return global.CreateFailedErr
  645. }
  646. tx.Commit()
  647. return nil
  648. }
  649. func (e *StockTemplate) StockTemplateInEdit(c *dto.StockTemplateInEditReq) error {
  650. var err error
  651. // 检查药品信息是否已存在
  652. medicineInfo, _, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
  653. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  654. logs.Error("db error: %s", err)
  655. return global.UpdateFailedErr
  656. }
  657. var medicineInfoId int
  658. tx := db.DB.Begin()
  659. // 如果药品信息不存在,则创建新的药品信息
  660. if medicineInfo == nil {
  661. sql := "INSERT INTO " + models.GetMedicineInfoTableName(c.DeptId) + " SET "
  662. for k, v := range c.MedicineInfo {
  663. sql += fmt.Sprintf("`%s`='%v',", k, v)
  664. }
  665. sql += fmt.Sprintf("`%s`='%v',", "unit_price", c.UnitPrice)
  666. sql = sql[:len(sql)-1]
  667. err = tx.Exec(sql).Error
  668. if err != nil {
  669. tx.Rollback()
  670. logs.Error("db error: %s", err)
  671. return global.UpdateFailedErr
  672. }
  673. err = tx.Raw("SELECT LAST_INSERT_ID()").Scan(&medicineInfoId).Error
  674. if err != nil {
  675. tx.Rollback()
  676. logs.Error("db error: %s", err)
  677. return global.CreateFailedErr
  678. }
  679. } else {
  680. medicineInfoId = utils.ToInt(medicineInfo["id"])
  681. c.MedicineInfo["unit_price"] = c.UnitPrice
  682. err = tx.Table(models.GetMedicineInfoTableName(c.DeptId)).Where("id = ?", medicineInfoId).Updates(c.MedicineInfo).Error
  683. if err != nil {
  684. tx.Rollback()
  685. logs.Error("db error: %s", err)
  686. return global.UpdateFailedErr
  687. }
  688. }
  689. var StockInInfo models.StockIn
  690. // 查询入库信息
  691. err = tx.Model(StockInInfo).Where("id = ? AND dept_id = ?", c.Id, c.DeptId).Find(&StockInInfo).Error
  692. if err != nil {
  693. tx.Rollback()
  694. logs.Error("db error: %s", err)
  695. return global.UpdateFailedErr
  696. }
  697. // 修改入库信息
  698. //stockInRecord := models.StockIn{
  699. // MedicineID: medicineInfoId,
  700. // Quantity: c.Quantity,
  701. // UnitPrice: c.UnitPrice,
  702. // Operator: c.Operator,
  703. // ForwardingUnit: c.ForwardingUnit,
  704. // Date: c.Date,
  705. // ControlBy: model2.ControlBy{
  706. // UpdateBy: c.UpdateBy,
  707. // },
  708. //}
  709. stockInRecordMap := map[string]interface{}{
  710. "medicine_id": medicineInfoId,
  711. "quantity": c.Quantity,
  712. "unit_price": c.UnitPrice,
  713. "operator": c.Operator,
  714. "forwarding_unit": c.ForwardingUnit,
  715. "date": c.Date,
  716. "update_by": c.UpdateBy,
  717. }
  718. err = tx.Model(models.StockIn{}).Where("id = ?", c.Id).Updates(stockInRecordMap).Error
  719. if err != nil {
  720. tx.Rollback()
  721. logs.Error("db error: %s", err)
  722. return global.UpdateFailedErr
  723. }
  724. // 1 查询收发记录
  725. medicineInventory := models.MedicineInventory{}
  726. err = tx.Model(models.MedicineInventory{}).Where("stock_in_id = ?", c.Id).First(&medicineInventory).Error
  727. if err != nil {
  728. tx.Rollback()
  729. logs.Error("db error: %s", err)
  730. return global.UpdateFailedErr
  731. }
  732. // 修改为同一药品id
  733. if StockInInfo.MedicineID == medicineInfoId {
  734. // 数量相等 只更改入库信息 (购入单价、经办人、发货单位、入库日期)
  735. if StockInInfo.Quantity != c.Quantity {
  736. // 数量不相等 修改收发记录
  737. // 2 修改数量
  738. err = tx.Model(models.MedicineInventory{}).Where("id = ?", medicineInventory.Id).Updates(
  739. map[string]interface{}{
  740. "total_in": c.Quantity,
  741. "update_by": c.UpdateBy,
  742. }).Error
  743. if err != nil {
  744. tx.Rollback()
  745. logs.Error("db error: %s", err)
  746. return global.UpdateFailedErr
  747. }
  748. // 3、修改的数量差
  749. err = tx.Model(models.MedicineInventory{}).Where("medicine_id = ? AND id >= ? AND dept_id = ?", medicineInfoId, medicineInventory.Id, c.DeptId).
  750. UpdateColumn("balance", gorm.Expr("balance + ?", c.Quantity-medicineInventory.TotalIn)).Error
  751. if err != nil {
  752. tx.Rollback()
  753. logs.Error("db error: %s", err)
  754. return global.UpdateFailedErr
  755. }
  756. }
  757. } else {
  758. // 2 查询收发记录
  759. newMedicineInventory := models.MedicineInventory{}
  760. err = tx.Model(models.MedicineInventory{}).Where("id < ? AND medicine_id = ? AND dept_id = ?", medicineInventory.Id, medicineInfoId, c.DeptId).Last(&newMedicineInventory).Error
  761. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  762. tx.Rollback()
  763. logs.Error("db error: %s", err)
  764. return global.UpdateFailedErr
  765. }
  766. // 2 修改入库数量、药品id、结余数量
  767. err = tx.Model(models.MedicineInventory{}).Where("id = ?", medicineInventory.Id).Updates(
  768. map[string]interface{}{
  769. "medicine_id": medicineInfoId,
  770. "total_in": c.Quantity,
  771. "balance": newMedicineInventory.Balance + c.Quantity,
  772. "update_by": c.UpdateBy,
  773. }).Error
  774. if err != nil {
  775. tx.Rollback()
  776. logs.Error("db error: %s", err)
  777. return global.UpdateFailedErr
  778. }
  779. // 查询原药品id当前收发记录结余最小值
  780. var balance *int
  781. err = tx.Model(&models.MedicineInventory{}).Select("MIN(balance)").
  782. Where("id >= ? AND medicine_id = ? AND dept_id = ?", medicineInventory.Id, StockInInfo.MedicineID, c.DeptId).Scan(&balance).Error
  783. if err != nil {
  784. tx.Rollback()
  785. logs.Error("db error: %s", err)
  786. return global.UpdateFailedErr
  787. }
  788. if balance != nil && *balance-c.Quantity < 0 {
  789. tx.Rollback()
  790. return errors.New("修改后将导致库存记录数据为负数,禁止修改")
  791. }
  792. // 3、修改原药品id的数量差
  793. err = tx.Model(models.MedicineInventory{}).Where("medicine_id = ? AND id > ? AND dept_id = ?", medicineInventory.MedicineID, medicineInventory.Id, c.DeptId).
  794. UpdateColumn("balance", gorm.Expr("balance - ?", c.Quantity)).Error
  795. if err != nil {
  796. tx.Rollback()
  797. logs.Error("db error: %s", err)
  798. return global.UpdateFailedErr
  799. }
  800. // 4、修改新药品id的数量差
  801. err = tx.Model(models.MedicineInventory{}).Where("medicine_id = ? AND id > ? AND dept_id = ?", medicineInfoId, medicineInventory.Id, c.DeptId).
  802. UpdateColumn("balance", gorm.Expr("balance + ?", c.Quantity)).Error
  803. if err != nil {
  804. tx.Rollback()
  805. logs.Error("db error: %s", err)
  806. return global.UpdateFailedErr
  807. }
  808. }
  809. tx.Commit()
  810. return nil
  811. }
  812. func (e *StockTemplate) StockTemplateInDelete(c *dto.StockTemplateInDeleteReq) error {
  813. var err error
  814. var StockInInfo models.StockIn
  815. tx := db.DB.Begin()
  816. // 1 查询入库信息
  817. err = tx.Model(StockInInfo).Where("id = ? AND dept_id = ?", c.Id, c.DeptId).Find(&StockInInfo).Error
  818. if err != nil {
  819. tx.Rollback()
  820. logs.Error("db error: %s", err)
  821. return global.DeleteFailedErr
  822. }
  823. // 2 查询收发记录
  824. medicineInventory := models.MedicineInventory{}
  825. err = tx.Model(models.MedicineInventory{}).Where("stock_in_id = ?", c.Id).First(&medicineInventory).Error
  826. if err != nil {
  827. tx.Rollback()
  828. logs.Error("db error: %s", err)
  829. return global.DeleteFailedErr
  830. }
  831. // 3 查询当前收发记录结余最小值
  832. var balance *int
  833. err = tx.Model(&models.MedicineInventory{}).Select("MIN(balance)").
  834. Where("id > ? AND medicine_id = ? AND dept_id = ?", medicineInventory.Id, StockInInfo.MedicineID, c.DeptId).Scan(&balance).Error
  835. if err != nil {
  836. tx.Rollback()
  837. logs.Error("db error: %s", err)
  838. return global.UpdateFailedErr
  839. }
  840. if balance != nil && *balance-medicineInventory.Balance < 0 {
  841. tx.Rollback()
  842. return errors.New("删除后将导致库存为负数,禁止删除")
  843. }
  844. // 4 删除收发记录
  845. err = tx.Model(models.MedicineInventory{}).Where("stock_in_id = ?", c.Id).Delete(&medicineInventory).Error
  846. if err != nil {
  847. tx.Rollback()
  848. logs.Error("db error: %s", err)
  849. return global.DeleteFailedErr
  850. }
  851. // 5 删除入库记录
  852. err = tx.Where("id = ?", c.Id).Delete(&StockInInfo).Error
  853. if err != nil {
  854. tx.Rollback()
  855. logs.Error("db error: %s", err)
  856. return global.DeleteFailedErr
  857. }
  858. // 6 修改原药品id的数量差
  859. err = tx.Model(models.MedicineInventory{}).Where("medicine_id = ? AND id > ? AND dept_id = ?", medicineInventory.MedicineID, medicineInventory.Id, c.DeptId).
  860. UpdateColumn("balance", gorm.Expr("balance - ?", medicineInventory.TotalIn)).Error
  861. if err != nil {
  862. tx.Rollback()
  863. logs.Error("db error: %s", err)
  864. return global.DeleteFailedErr
  865. }
  866. tx.Commit()
  867. return nil
  868. }
  869. // StockTemplateOut 出库
  870. func (e *StockTemplate) StockTemplateOut(c *dto.StockTemplateOutInsertReq) error {
  871. var err error
  872. number, err := e.GetStockNumber(models.TypeStockIn)
  873. if err != nil {
  874. logs.Error("获取: %s", err)
  875. return err
  876. }
  877. // 检查药品信息是否已存在
  878. medicineInfo, _, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
  879. if err != nil {
  880. logs.Error("db error: %s", err)
  881. return global.CreateFailedErr
  882. }
  883. // 如果药品信息不存在,则不能出库
  884. if medicineInfo == nil {
  885. logs.Error("db error: %s", err)
  886. return errors.New("药品信息不存在,禁止出库")
  887. }
  888. medicineInfoId := utils.ToInt(medicineInfo["id"])
  889. // 查询库查询信息
  890. var mi models.MedicineInventory
  891. err = db.DB.Model(mi).Where("medicine_id = ? AND dept_id = ?", medicineInfoId, c.DeptId).Last(&mi).Error
  892. if err != nil {
  893. logs.Error("db error: %s", err)
  894. return global.CreateFailedErr
  895. }
  896. if mi.Balance < c.Quantity {
  897. return errors.New(fmt.Sprintf("库存量【%d】小于出库库存量【%d】,出库失败", mi.Balance, c.Quantity))
  898. }
  899. tx := db.DB.Begin()
  900. //err = tx.Table(models.GetMedicineInfoTableName(c.DeptId)).Where("id = ?", medicineInfoId).Update("sales_unit_price", c.UnitPrice).Error
  901. //if err != nil {
  902. // tx.Rollback()
  903. // logs.Error("db error: %s", err)
  904. // return global.CreateFailedErr
  905. //}
  906. // 进行出库操作
  907. stockOutRecord := models.StockOut{
  908. MedicineID: medicineInfoId,
  909. Quantity: c.Quantity,
  910. //UnitPrice: c.UnitPrice,
  911. Operator: c.Operator,
  912. ReceivingUnit: c.ReceivingUnit,
  913. Date: c.Date,
  914. Number: number,
  915. State: c.State,
  916. ControlBy: model2.ControlBy{
  917. DeptId: c.DeptId,
  918. CreateBy: c.CreateBy,
  919. },
  920. }
  921. err = tx.Create(&stockOutRecord).Error
  922. if err != nil {
  923. tx.Rollback()
  924. logs.Error("db error: %s", err)
  925. return global.CreateFailedErr
  926. }
  927. c.Id = stockOutRecord.Id
  928. var inventory models.MedicineInventory
  929. err = tx.Last(&inventory, "medicine_id = ? and dept_id = ?", medicineInfoId, c.DeptId).Error
  930. if err != nil {
  931. tx.Rollback()
  932. logs.Error("db error: %s", err)
  933. return global.CreateFailedErr
  934. }
  935. // 添加库存记录
  936. data := models.MedicineInventory{
  937. MedicineID: medicineInfoId,
  938. TotalIn: 0,
  939. StockInID: 0,
  940. TotalOut: c.Quantity,
  941. StockOutID: stockOutRecord.Id,
  942. Balance: inventory.Balance - c.Quantity,
  943. ReceivingUnit: c.ReceivingUnit,
  944. Operator: c.Operator,
  945. Date: c.Date,
  946. ControlBy: model2.ControlBy{
  947. DeptId: c.DeptId,
  948. CreateBy: c.CreateBy,
  949. },
  950. }
  951. err = tx.Create(&data).Error
  952. if err != nil {
  953. tx.Rollback()
  954. logs.Error("db error: %s", err)
  955. return global.CreateFailedErr
  956. }
  957. tx.Commit()
  958. return nil
  959. }
  960. // StockTemplateOutEdit 修改出库
  961. func (e *StockTemplate) StockTemplateOutEdit(c *dto.StockTemplateOutEditReq) error {
  962. var err error
  963. // 检查药品信息是否已存在
  964. medicineInfo, _, err := e.GetMedicineInfo(c.DeptId, c.MedicineInfo)
  965. if err != nil {
  966. logs.Error("db error: %s", err)
  967. if errors.Is(err, gorm.ErrRecordNotFound) {
  968. return errors.New("药品信息不存在,禁止出库")
  969. } else {
  970. return global.UpdateFailedErr
  971. }
  972. }
  973. var medicineInfoId int
  974. tx := db.DB.Begin()
  975. medicineInfoId = utils.ToInt(medicineInfo["id"])
  976. //c.MedicineInfo["sales_unit_price"] = c.UnitPrice
  977. err = tx.Table(models.GetMedicineInfoTableName(c.DeptId)).Where("id = ?", medicineInfoId).Updates(c.MedicineInfo).Error
  978. if err != nil {
  979. tx.Rollback()
  980. logs.Error("db error: %s", err)
  981. return global.UpdateFailedErr
  982. }
  983. var StockOutInfo models.StockOut
  984. // 查询出库信息
  985. err = tx.Model(StockOutInfo).Where("id = ? AND dept_id = ?", c.Id, c.DeptId).Find(&StockOutInfo).Error
  986. if err != nil {
  987. tx.Rollback()
  988. logs.Error("db error: %s", err)
  989. return global.UpdateFailedErr
  990. }
  991. stockOutRecordMap := map[string]interface{}{
  992. "medicine_id": medicineInfoId,
  993. "quantity": c.Quantity,
  994. //"unit_price": c.UnitPrice,
  995. "operator": c.Operator,
  996. "receiving_unit": c.ReceivingUnit,
  997. "date": c.Date,
  998. "update_by": c.UpdateBy,
  999. }
  1000. err = tx.Model(models.StockOut{}).Where("id = ?", c.Id).Updates(stockOutRecordMap).Error
  1001. if err != nil {
  1002. tx.Rollback()
  1003. logs.Error("db error: %s", err)
  1004. return global.UpdateFailedErr
  1005. }
  1006. // 1 查询收发记录
  1007. medicineInventory := models.MedicineInventory{}
  1008. err = tx.Model(models.MedicineInventory{}).Where("stock_out_id = ?", c.Id).First(&medicineInventory).Error
  1009. if err != nil {
  1010. tx.Rollback()
  1011. logs.Error("db error: %s", err)
  1012. return global.UpdateFailedErr
  1013. }
  1014. // 修改为同一药品id
  1015. if medicineInventory.MedicineID == medicineInfoId {
  1016. // 数量相等 只更改入库信息 (购入单价、经办人、发货单位、入库日期)
  1017. if StockOutInfo.Quantity != c.Quantity {
  1018. // 查询收发记录
  1019. lastMedicineInventory := models.MedicineInventory{}
  1020. err = tx.Model(models.MedicineInventory{}).Where("id < ? AND medicine_id = ? AND dept_id = ?", medicineInventory.Id, medicineInfoId, c.DeptId).Last(&lastMedicineInventory).Error
  1021. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1022. tx.Rollback()
  1023. logs.Error("db error: %s", err)
  1024. return global.UpdateFailedErr
  1025. }
  1026. if lastMedicineInventory.Balance < c.Quantity {
  1027. tx.Rollback()
  1028. return errors.New("修改后将导致库存记录数据为负数,禁止修改")
  1029. }
  1030. // 查询新药品id当前收发记录结余最小值
  1031. var balance *int
  1032. err = tx.Model(&models.MedicineInventory{}).Select("MIN(balance)").
  1033. Where("id >= ? AND medicine_id = ? AND dept_id = ?", medicineInventory.Id, medicineInfoId, c.DeptId).Scan(&balance).Error
  1034. if err != nil {
  1035. tx.Rollback()
  1036. logs.Error("db error: %s", err)
  1037. return global.UpdateFailedErr
  1038. }
  1039. if balance != nil && *balance-c.Quantity+medicineInventory.TotalOut < 0 {
  1040. tx.Rollback()
  1041. return errors.New("修改后将导致库存记录数据为负数,禁止修改")
  1042. }
  1043. // 2 修改数量
  1044. err = tx.Model(models.MedicineInventory{}).Where("id = ?", medicineInventory.Id).Updates(
  1045. map[string]interface{}{
  1046. "total_out": c.Quantity,
  1047. "update_by": c.UpdateBy,
  1048. }).Error
  1049. if err != nil {
  1050. tx.Rollback()
  1051. logs.Error("db error: %s", err)
  1052. return global.UpdateFailedErr
  1053. }
  1054. // 3、修改的数量差
  1055. err = tx.Model(models.MedicineInventory{}).Where("medicine_id = ? AND id >= ? AND dept_id = ?", medicineInfoId, medicineInventory.Id, c.DeptId).
  1056. UpdateColumn("balance", gorm.Expr("balance - ?", c.Quantity-medicineInventory.TotalOut)).Error
  1057. if err != nil {
  1058. tx.Rollback()
  1059. logs.Error("db error: %s", err)
  1060. return global.UpdateFailedErr
  1061. }
  1062. }
  1063. } else {
  1064. // 2 查询收发记录
  1065. newMedicineInventory := models.MedicineInventory{}
  1066. err = tx.Model(models.MedicineInventory{}).Where("id < ? AND medicine_id = ? AND dept_id = ?", medicineInventory.Id, medicineInfoId, c.DeptId).Last(&newMedicineInventory).Error
  1067. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1068. tx.Rollback()
  1069. logs.Error("db error: %s", err)
  1070. return global.UpdateFailedErr
  1071. }
  1072. if newMedicineInventory.Balance < c.Quantity {
  1073. tx.Rollback()
  1074. return errors.New("修改后将导致库存记录数据为负数,禁止修改")
  1075. }
  1076. // 3 查询新药品id当前收发记录结余最小值
  1077. var balance *int
  1078. err = tx.Model(&models.MedicineInventory{}).Select("MIN(balance)").
  1079. Where("id >= ? AND medicine_id = ? AND dept_id = ?", medicineInventory.Id, medicineInfoId, c.DeptId).Scan(&balance).Error
  1080. if err != nil {
  1081. tx.Rollback()
  1082. logs.Error("db error: %s", err)
  1083. return global.UpdateFailedErr
  1084. }
  1085. if balance != nil && *balance-c.Quantity < 0 {
  1086. tx.Rollback()
  1087. return errors.New("修改后将导致库存记录数据为负数,禁止修改")
  1088. }
  1089. // 2 修改出库数量、药品id、结余数量
  1090. err = tx.Model(models.MedicineInventory{}).Where("id = ?", medicineInventory.Id).Updates(
  1091. map[string]interface{}{
  1092. "medicine_id": medicineInfoId,
  1093. "total_out": c.Quantity,
  1094. "balance": newMedicineInventory.Balance - c.Quantity,
  1095. "update_by": c.UpdateBy,
  1096. }).Error
  1097. if err != nil {
  1098. tx.Rollback()
  1099. logs.Error("db error: %s", err)
  1100. return global.UpdateFailedErr
  1101. }
  1102. // 3、修改原药品id的数量差
  1103. err = tx.Model(models.MedicineInventory{}).Where("medicine_id = ? AND id > ? AND dept_id = ?", medicineInventory.MedicineID, medicineInventory.Id, c.DeptId).
  1104. UpdateColumn("balance", gorm.Expr("balance + ?", c.Quantity)).Error
  1105. if err != nil {
  1106. tx.Rollback()
  1107. logs.Error("db error: %s", err)
  1108. return global.UpdateFailedErr
  1109. }
  1110. // 4、修改新药品id的数量差
  1111. err = tx.Model(models.MedicineInventory{}).Where("medicine_id = ? AND id > ? AND dept_id = ?", medicineInfoId, medicineInventory.Id, c.DeptId).
  1112. UpdateColumn("balance", gorm.Expr("balance - ?", c.Quantity)).Error
  1113. if err != nil {
  1114. tx.Rollback()
  1115. logs.Error("db error: %s", err)
  1116. return global.UpdateFailedErr
  1117. }
  1118. }
  1119. tx.Commit()
  1120. return nil
  1121. }
  1122. // 删除出库
  1123. func (e *StockTemplate) StockTemplateOutDelete(c *dto.StockTemplateOutDeleteReq) error {
  1124. var err error
  1125. var StockOutInfo models.StockOut
  1126. tx := db.DB.Begin()
  1127. // 1 查询入库信息
  1128. err = tx.Model(StockOutInfo).Where("id = ? AND dept_id = ?", c.Id, c.DeptId).Find(&StockOutInfo).Error
  1129. if err != nil {
  1130. tx.Rollback()
  1131. logs.Error("db error: %s", err)
  1132. return global.DeleteFailedErr
  1133. }
  1134. // 2 查询收发记录
  1135. medicineInventory := models.MedicineInventory{}
  1136. err = tx.Model(models.MedicineInventory{}).Where("stock_out_id = ?", c.Id).First(&medicineInventory).Error
  1137. if err != nil {
  1138. tx.Rollback()
  1139. logs.Error("db error: %s", err)
  1140. return global.DeleteFailedErr
  1141. }
  1142. // 4 删除收发记录
  1143. err = tx.Model(models.MedicineInventory{}).Where("stock_out_id = ?", c.Id).Delete(&medicineInventory).Error
  1144. if err != nil {
  1145. tx.Rollback()
  1146. logs.Error("db error: %s", err)
  1147. return global.DeleteFailedErr
  1148. }
  1149. // 5 删除入库记录
  1150. err = tx.Where("id = ?", c.Id).Delete(&StockOutInfo).Error
  1151. if err != nil {
  1152. tx.Rollback()
  1153. logs.Error("db error: %s", err)
  1154. return global.DeleteFailedErr
  1155. }
  1156. // 6 修改原药品id的数量差
  1157. err = tx.Model(models.MedicineInventory{}).Where("medicine_id = ? AND id > ? AND dept_id = ?", medicineInventory.MedicineID, medicineInventory.Id, c.DeptId).
  1158. UpdateColumn("balance", gorm.Expr("balance + ?", medicineInventory.TotalOut)).Error
  1159. if err != nil {
  1160. tx.Rollback()
  1161. logs.Error("db error: %s", err)
  1162. return global.DeleteFailedErr
  1163. }
  1164. tx.Commit()
  1165. return nil
  1166. }
  1167. // BatchStockTemplateOut 批量出库
  1168. func (e *StockTemplate) BatchStockTemplateOut(req *dto.BatchStockTemplateOutInsertReq) error {
  1169. number, err := e.GetStockNumber(models.TypeStockIn)
  1170. if err != nil {
  1171. logs.Error("获取: %s", err)
  1172. return err
  1173. }
  1174. tx := db.DB.Begin()
  1175. for _, c := range req.StockOutList {
  1176. // 检查药品信息是否已存在
  1177. medicineInfo, _, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
  1178. if err != nil {
  1179. tx.Rollback()
  1180. logs.Error("db error: %s", err)
  1181. return global.CreateFailedErr
  1182. }
  1183. // 如果药品信息不存在,则不能出库
  1184. if medicineInfo == nil {
  1185. tx.Rollback()
  1186. logs.Error("db error: %s", err)
  1187. return errors.New("药品信息不存在,禁止出库")
  1188. }
  1189. medicineInfoId := utils.ToInt(medicineInfo["id"])
  1190. // 查询库查询信息
  1191. var mi models.MedicineInventory
  1192. err = tx.Model(mi).Where("medicine_id = ? AND dept_id = ?", medicineInfoId, req.DeptId).Last(&mi).Error
  1193. if err != nil {
  1194. tx.Rollback()
  1195. logs.Error("db error: %s", err)
  1196. return global.CreateFailedErr
  1197. }
  1198. if mi.Balance < c.Quantity {
  1199. tx.Rollback()
  1200. return errors.New(fmt.Sprintf("库存量【%d】小于出库库存量【%d】,出库失败", mi.Balance, c.Quantity))
  1201. }
  1202. //err = tx.Table(models.GetMedicineInfoTableName(req.DeptId)).Where("id = ?", medicineInfoId).Update("sales_unit_price", c.UnitPrice).Error
  1203. //if err != nil {
  1204. // tx.Rollback()
  1205. // logs.Error("db error: %s", err)
  1206. // return global.CreateFailedErr
  1207. //}
  1208. // 进行出库操作
  1209. stockOutRecord := models.StockOut{
  1210. MedicineID: medicineInfoId,
  1211. Quantity: c.Quantity,
  1212. //UnitPrice: c.UnitPrice,
  1213. Operator: c.Operator,
  1214. ReceivingUnit: c.ReceivingUnit,
  1215. Date: c.Date,
  1216. Number: number,
  1217. State: req.State,
  1218. ControlBy: model2.ControlBy{
  1219. DeptId: req.DeptId,
  1220. CreateBy: req.CreateBy,
  1221. },
  1222. }
  1223. err = tx.Create(&stockOutRecord).Error
  1224. if err != nil {
  1225. tx.Rollback()
  1226. logs.Error("db error: %s", err)
  1227. return global.CreateFailedErr
  1228. }
  1229. c.Id = stockOutRecord.Id
  1230. var inventory models.MedicineInventory
  1231. err = tx.Last(&inventory, "medicine_id = ? and dept_id = ?", medicineInfoId, req.DeptId).Error
  1232. if err != nil {
  1233. tx.Rollback()
  1234. logs.Error("db error: %s", err)
  1235. return global.CreateFailedErr
  1236. }
  1237. // 添加库存记录
  1238. data := models.MedicineInventory{
  1239. MedicineID: medicineInfoId,
  1240. TotalIn: 0,
  1241. StockInID: 0,
  1242. TotalOut: c.Quantity,
  1243. StockOutID: stockOutRecord.Id,
  1244. Balance: inventory.Balance - c.Quantity,
  1245. ReceivingUnit: c.ReceivingUnit,
  1246. Operator: c.Operator,
  1247. Date: c.Date,
  1248. ControlBy: model2.ControlBy{
  1249. DeptId: req.DeptId,
  1250. CreateBy: req.CreateBy,
  1251. },
  1252. }
  1253. err = tx.Create(&data).Error
  1254. if err != nil {
  1255. tx.Rollback()
  1256. logs.Error("db error: %s", err)
  1257. return global.CreateFailedErr
  1258. }
  1259. }
  1260. tx.Commit()
  1261. return nil
  1262. }
  1263. // StockTemplateOutScanCode 扫码出库
  1264. func (e *StockTemplate) StockTemplateOutScanCode(req *dto.BatchStockTemplateOutInsertReq) error {
  1265. number, err := e.GetStockNumber(models.TypeStockIn)
  1266. if err != nil {
  1267. logs.Error("获取: %s", err)
  1268. return err
  1269. }
  1270. for _, s := range req.StockOutList {
  1271. err := e.CheckStockForQrcode(s.Qrcode, models.TypeStockOut)
  1272. if err != nil {
  1273. return err
  1274. }
  1275. }
  1276. tx := db.DB.Begin()
  1277. for _, c := range req.StockOutList {
  1278. medicineName := c.MedicineInfo[models.FieldProductName]
  1279. // 初始化药品信息
  1280. err := e.FirstOrCreateMedicineInfo(req.DeptId, req.CreateBy, &c.MedicineInfo)
  1281. if err != nil {
  1282. tx.Rollback()
  1283. logs.Error("【扫码出库】初始化药品信息失败: %s", err)
  1284. return err
  1285. }
  1286. // 检查药品信息是否已存在
  1287. medicineInfo, _, err := e.GetMedicineInfo(req.DeptId, c.MedicineInfo)
  1288. if err != nil {
  1289. tx.Rollback()
  1290. logs.Error("db error: %s", err)
  1291. return global.CreateFailedErr
  1292. }
  1293. // 如果药品信息不存在,则不能出库
  1294. if medicineInfo == nil {
  1295. tx.Rollback()
  1296. logs.Error("db error: %s", err)
  1297. return errors.New("药品信息不存在,禁止出库")
  1298. }
  1299. medicineInfoId := utils.ToInt(medicineInfo["id"])
  1300. // 查询库查询信息
  1301. var mi models.MedicineInventory
  1302. err = tx.Model(mi).Where("medicine_id = ? AND dept_id = ?", medicineInfoId, req.DeptId).Last(&mi).Error
  1303. if err != nil {
  1304. tx.Rollback()
  1305. logs.Error("db error: %s", err)
  1306. return global.CreateFailedErr
  1307. }
  1308. if mi.Balance < c.Quantity {
  1309. tx.Rollback()
  1310. return errors.New(fmt.Sprintf("【%s】库存量【%d】小于出库库存量【%d】,出库失败", medicineName, mi.Balance, c.Quantity))
  1311. }
  1312. //err = tx.Table(models.GetMedicineInfoTableName(req.DeptId)).Where("id = ?", medicineInfoId).Update("sales_unit_price", c.UnitPrice).Error
  1313. //if err != nil {
  1314. // tx.Rollback()
  1315. // logs.Error("db error: %s", err)
  1316. // return global.CreateFailedErr
  1317. //}
  1318. // 进行出库操作
  1319. stockOutRecord := models.StockOut{
  1320. MedicineID: medicineInfoId,
  1321. Quantity: c.Quantity,
  1322. //UnitPrice: c.UnitPrice,
  1323. Operator: c.Operator,
  1324. ReceivingUnit: c.ReceivingUnit,
  1325. Date: c.Date,
  1326. Qrcode: c.Qrcode,
  1327. Number: number,
  1328. State: req.State,
  1329. ControlBy: model2.ControlBy{
  1330. DeptId: req.DeptId,
  1331. CreateBy: req.CreateBy,
  1332. },
  1333. }
  1334. err = tx.Create(&stockOutRecord).Error
  1335. if err != nil {
  1336. tx.Rollback()
  1337. logs.Error("db error: %s", err)
  1338. return global.CreateFailedErr
  1339. }
  1340. c.Id = stockOutRecord.Id
  1341. var inventory models.MedicineInventory
  1342. err = tx.Last(&inventory, "medicine_id = ? and dept_id = ?", medicineInfoId, req.DeptId).Error
  1343. if err != nil {
  1344. tx.Rollback()
  1345. logs.Error("db error: %s", err)
  1346. return global.CreateFailedErr
  1347. }
  1348. // 添加库存记录
  1349. data := models.MedicineInventory{
  1350. MedicineID: medicineInfoId,
  1351. TotalIn: 0,
  1352. StockInID: 0,
  1353. TotalOut: c.Quantity,
  1354. StockOutID: stockOutRecord.Id,
  1355. Balance: inventory.Balance - c.Quantity,
  1356. ReceivingUnit: c.ReceivingUnit,
  1357. Operator: c.Operator,
  1358. Date: c.Date,
  1359. ControlBy: model2.ControlBy{
  1360. DeptId: req.DeptId,
  1361. CreateBy: req.CreateBy,
  1362. },
  1363. }
  1364. err = tx.Create(&data).Error
  1365. if err != nil {
  1366. tx.Rollback()
  1367. logs.Error("db error: %s", err)
  1368. return global.CreateFailedErr
  1369. }
  1370. }
  1371. tx.Commit()
  1372. return nil
  1373. }
  1374. // StockTemplateInList 入库列表
  1375. func (e *StockTemplate) StockTemplateInList(c *dto.StockTemplateInPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
  1376. mtable := models.GetMedicineInfoTableName(deptId)
  1377. whereSql := "stock_in.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_in.deleted_at is null"
  1378. if c.ProductID > 0 {
  1379. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  1380. }
  1381. if c.EnterpriseID > 0 {
  1382. whereSql += " AND " + mtable + ".enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1383. }
  1384. if len(c.BatchNumber) > 0 {
  1385. whereSql += " AND " + mtable + ".batch_number = " + c.BatchNumber
  1386. }
  1387. if len(c.StartDate) > 0 {
  1388. whereSql += " AND stock_in.date >= '" + c.StartDate + "'"
  1389. }
  1390. if len(c.EndDate) > 0 {
  1391. whereSql += " AND stock_in.date <= '" + c.EndDate + "'"
  1392. }
  1393. if len(c.ForwardingUnit) > 0 {
  1394. whereSql += " AND stock_in.forwarding_unit like '%" + c.ForwardingUnit + "%'"
  1395. }
  1396. if len(c.Qrcode) > 0 {
  1397. whereSql += " AND stock_in.qrcode like '%" + c.Qrcode + "%'"
  1398. }
  1399. err = db.DB.Table("stock_in").
  1400. Select(mtable + ".*,stock_in.*,stock_in.id AS id").
  1401. Scopes(
  1402. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  1403. ).
  1404. Joins("left join " + mtable + " on stock_in.medicine_id = " + mtable + ".id").
  1405. Where(whereSql).
  1406. Order("stock_in.date desc,stock_in.id desc").
  1407. Scan(&list).Limit(-1).Offset(-1).
  1408. Count(&count).Error
  1409. if err != nil {
  1410. logs.Error("db error: %s ", err)
  1411. return list, count, global.GetFailedErr
  1412. }
  1413. models.InitBasicData(deptId)
  1414. for i := 0; i < len(list); i++ {
  1415. if id, ok := list[i][models.FieldProductID]; ok {
  1416. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1417. }
  1418. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1419. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1420. }
  1421. if id, ok := list[i][models.FieldSpecID]; ok {
  1422. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1423. }
  1424. if id, ok := list[i][models.FieldUnitID]; ok {
  1425. if utils.ToInt(id) == 0 {
  1426. list[i][models.FieldUnitID] = nil
  1427. } else {
  1428. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1429. }
  1430. }
  1431. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1432. if utils.ToInt(id) == 0 {
  1433. list[i][models.FieldDosageFormID] = nil
  1434. } else {
  1435. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1436. }
  1437. }
  1438. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  1439. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  1440. }
  1441. return list, count, nil
  1442. }
  1443. func (e *StockTemplate) StockTemplateRefundInList(c *dto.StockTemplateInPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
  1444. mtable := models.GetMedicineInfoTableName(deptId)
  1445. whereSql := "stock_in.dept_id = " + strconv.Itoa(deptId) + " AND state = 2 AND stock_in.deleted_at is null"
  1446. if c.ProductID > 0 {
  1447. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  1448. }
  1449. if c.EnterpriseID > 0 {
  1450. whereSql += " AND " + mtable + ".enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1451. }
  1452. if len(c.BatchNumber) > 0 {
  1453. whereSql += " AND " + mtable + ".batch_number = " + c.BatchNumber
  1454. }
  1455. if len(c.StartDate) > 0 {
  1456. whereSql += " AND stock_in.date >= '" + c.StartDate + "'"
  1457. }
  1458. if len(c.EndDate) > 0 {
  1459. whereSql += " AND stock_in.date <= '" + c.EndDate + "'"
  1460. }
  1461. if len(c.ForwardingUnit) > 0 {
  1462. whereSql += " AND stock_in.forwarding_unit like '%" + c.ForwardingUnit + "%'"
  1463. }
  1464. if len(c.Qrcode) > 0 {
  1465. whereSql += " AND stock_in.qrcode like '%" + c.Qrcode + "%'"
  1466. }
  1467. err = db.DB.Table("stock_in").
  1468. Select(mtable + ".*,stock_in.*,stock_in.id AS id").
  1469. Scopes(
  1470. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  1471. ).
  1472. Joins("left join " + mtable + " on stock_in.medicine_id = " + mtable + ".id").
  1473. Where(whereSql).
  1474. Order("stock_in.date desc,stock_in.id desc").
  1475. Scan(&list).Limit(-1).Offset(-1).
  1476. Count(&count).Error
  1477. if err != nil {
  1478. logs.Error("db error: %s ", err)
  1479. return list, count, global.GetFailedErr
  1480. }
  1481. models.InitBasicData(deptId)
  1482. for i := 0; i < len(list); i++ {
  1483. if id, ok := list[i][models.FieldProductID]; ok {
  1484. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1485. }
  1486. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1487. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1488. }
  1489. if id, ok := list[i][models.FieldSpecID]; ok {
  1490. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1491. }
  1492. if id, ok := list[i][models.FieldUnitID]; ok {
  1493. if utils.ToInt(id) == 0 {
  1494. list[i][models.FieldUnitID] = nil
  1495. } else {
  1496. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1497. }
  1498. }
  1499. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1500. if utils.ToInt(id) == 0 {
  1501. list[i][models.FieldDosageFormID] = nil
  1502. } else {
  1503. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1504. }
  1505. }
  1506. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  1507. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  1508. }
  1509. return list, count, nil
  1510. }
  1511. // StockTemplateInList 出库列表
  1512. func (e *StockTemplate) StockTemplateOutList(c *dto.StockTemplateOutPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
  1513. mtable := models.GetMedicineInfoTableName(deptId)
  1514. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
  1515. if c.ProductID > 0 {
  1516. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  1517. }
  1518. if c.EnterpriseID > 0 {
  1519. whereSql += " AND " + mtable + ".enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1520. }
  1521. if len(c.BatchNumber) > 0 {
  1522. whereSql += " AND " + mtable + ".batch_number = " + c.BatchNumber
  1523. }
  1524. if len(c.StartDate) > 0 {
  1525. whereSql += " AND stock_out.date >= '" + c.StartDate + "'"
  1526. }
  1527. if len(c.EndDate) > 0 {
  1528. whereSql += " AND stock_out.date <= '" + c.EndDate + "'"
  1529. }
  1530. if len(c.ReceivingUnit) > 0 {
  1531. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  1532. }
  1533. if len(c.Qrcode) > 0 {
  1534. whereSql += " AND stock_out.qrcode like '%" + c.Qrcode + "%'"
  1535. }
  1536. err = db.DB.Table("stock_out").
  1537. Select(mtable + ".*," + "stock_out.*,stock_out.id AS id," + mtable + ".unit_price as sales_unit_price").
  1538. Scopes(
  1539. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  1540. ).
  1541. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  1542. Where(whereSql).
  1543. Order("stock_out.date desc,stock_out.id desc").
  1544. Scan(&list).Limit(-1).Offset(-1).
  1545. Count(&count).Error
  1546. if err != nil {
  1547. logs.Error("db error: %s ", err)
  1548. return list, count, global.GetFailedErr
  1549. }
  1550. models.InitBasicData(deptId)
  1551. for i := 0; i < len(list); i++ {
  1552. if id, ok := list[i][models.FieldProductID]; ok {
  1553. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1554. }
  1555. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1556. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1557. }
  1558. if id, ok := list[i][models.FieldSpecID]; ok {
  1559. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1560. }
  1561. if id, ok := list[i][models.FieldUnitID]; ok {
  1562. if utils.ToInt(id) == 0 {
  1563. list[i][models.FieldUnitID] = nil
  1564. } else {
  1565. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1566. }
  1567. }
  1568. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1569. if utils.ToInt(id) == 0 {
  1570. list[i][models.FieldDosageFormID] = nil
  1571. } else {
  1572. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1573. }
  1574. }
  1575. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  1576. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  1577. }
  1578. return list, count, nil
  1579. }
  1580. func (e *StockTemplate) StockTemplateRefundOutList(c *dto.StockTemplateOutPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
  1581. mtable := models.GetMedicineInfoTableName(deptId)
  1582. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
  1583. if c.ProductID > 0 {
  1584. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  1585. }
  1586. if c.EnterpriseID > 0 {
  1587. whereSql += " AND " + mtable + ".enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1588. }
  1589. if len(c.BatchNumber) > 0 {
  1590. whereSql += " AND " + mtable + ".batch_number = " + c.BatchNumber
  1591. }
  1592. if len(c.StartDate) > 0 {
  1593. whereSql += " AND stock_out.date >= '" + c.StartDate + "'"
  1594. }
  1595. if len(c.EndDate) > 0 {
  1596. whereSql += " AND stock_out.date <= '" + c.EndDate + "'"
  1597. }
  1598. if len(c.ReceivingUnit) > 0 {
  1599. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  1600. }
  1601. if len(c.Qrcode) > 0 {
  1602. whereSql += " AND stock_out.qrcode like '%" + c.Qrcode + "%'"
  1603. }
  1604. if c.State > 0 {
  1605. whereSql += " AND stock_out.state = " + strconv.Itoa(c.State)
  1606. }
  1607. err = db.DB.Table("stock_out").
  1608. Select(mtable + ".*," + "stock_out.*,stock_out.id AS id," + mtable + ".unit_price as sales_unit_price").
  1609. Scopes(
  1610. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  1611. ).
  1612. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  1613. Where(whereSql).
  1614. Order("stock_out.date desc,stock_out.id desc").
  1615. Scan(&list).Limit(-1).Offset(-1).
  1616. Count(&count).Error
  1617. if err != nil {
  1618. logs.Error("db error: %s ", err)
  1619. return list, count, global.GetFailedErr
  1620. }
  1621. models.InitBasicData(deptId)
  1622. for i := 0; i < len(list); i++ {
  1623. if id, ok := list[i][models.FieldProductID]; ok {
  1624. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1625. }
  1626. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1627. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1628. }
  1629. if id, ok := list[i][models.FieldSpecID]; ok {
  1630. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1631. }
  1632. if id, ok := list[i][models.FieldUnitID]; ok {
  1633. if utils.ToInt(id) == 0 {
  1634. list[i][models.FieldUnitID] = nil
  1635. } else {
  1636. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1637. }
  1638. }
  1639. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1640. if utils.ToInt(id) == 0 {
  1641. list[i][models.FieldDosageFormID] = nil
  1642. } else {
  1643. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1644. }
  1645. }
  1646. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  1647. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  1648. }
  1649. return list, count, nil
  1650. }
  1651. // StockTemplateInventoryList 库存统计列表
  1652. func (e *StockTemplate) StockTemplateInventoryList(c *dto.StockTemplateInventoryPageReq, deptId int) (list []map[string]interface{}, count int64, err error) {
  1653. mtable := models.GetMedicineInfoTableName(deptId)
  1654. whereSql := "medicine_inventory.dept_id = " + strconv.Itoa(deptId) + " AND medicine_inventory.deleted_at is null"
  1655. if c.ProductID > 0 {
  1656. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  1657. }
  1658. if c.EnterpriseID > 0 {
  1659. whereSql += " AND " + mtable + ".enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1660. }
  1661. if len(c.BatchNumber) > 0 {
  1662. whereSql += " AND " + mtable + ".batch_number = " + c.BatchNumber
  1663. }
  1664. if len(c.StartDate) > 0 {
  1665. whereSql += " AND medicine_inventory.date >= '" + c.StartDate + "'"
  1666. }
  1667. if len(c.EndDate) > 0 {
  1668. whereSql += " AND medicine_inventory.date <= '" + c.EndDate + "'"
  1669. }
  1670. if len(c.SendReceiveUnit) > 0 {
  1671. whereSql += " AND (medicine_inventory.forwarding_unit like '%" + c.SendReceiveUnit + "%' OR medicine_inventory.receiving_unit like '%" + c.SendReceiveUnit + "%')"
  1672. }
  1673. err = db.DB.Table("medicine_inventory").
  1674. Select(mtable + ".*,medicine_inventory.*,medicine_inventory.id AS id").
  1675. Scopes(
  1676. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  1677. ).
  1678. Joins("left join " + mtable + " on medicine_inventory.medicine_id = " + mtable + ".id").
  1679. Where(whereSql).
  1680. Scan(&list).Limit(-1).Offset(-1).
  1681. Count(&count).Error
  1682. if err != nil {
  1683. logs.Error("db error: %s ", err)
  1684. return list, count, global.GetFailedErr
  1685. }
  1686. models.InitBasicData(deptId)
  1687. for i := 0; i < len(list); i++ {
  1688. if id, ok := list[i][models.FieldProductID]; ok {
  1689. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1690. }
  1691. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1692. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1693. }
  1694. if id, ok := list[i][models.FieldSpecID]; ok {
  1695. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1696. }
  1697. if id, ok := list[i][models.FieldUnitID]; ok {
  1698. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1699. }
  1700. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1701. if utils.ToInt(id) == 0 {
  1702. list[i][models.FieldDosageFormID] = nil
  1703. } else {
  1704. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1705. }
  1706. }
  1707. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  1708. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  1709. }
  1710. return list, count, nil
  1711. }
  1712. // StockTemplateInventoryList 库存统计列表
  1713. func (e *StockTemplate) StockTemplateInventoryExcel(c *dto.StockTemplateInventoryExcelReq, deptId int) (list []map[string]interface{}, err error) {
  1714. mtable := models.GetMedicineInfoTableName(deptId)
  1715. whereSql := "medicine_inventory.dept_id = " + strconv.Itoa(deptId) + " AND medicine_inventory.deleted_at is null"
  1716. if c.ProductID > 0 {
  1717. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  1718. }
  1719. if c.EnterpriseID > 0 {
  1720. whereSql += " AND " + mtable + ".enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1721. }
  1722. if len(c.BatchNumber) > 0 {
  1723. whereSql += " AND " + mtable + ".batch_number = " + c.BatchNumber
  1724. }
  1725. if len(c.StartDate) > 0 {
  1726. whereSql += " AND medicine_inventory.date >= '" + c.StartDate + "'"
  1727. }
  1728. if len(c.EndDate) > 0 {
  1729. whereSql += " AND medicine_inventory.date <= '" + c.EndDate + "'"
  1730. }
  1731. err = db.DB.Table("medicine_inventory").
  1732. Joins("left join " + mtable + " on medicine_inventory.medicine_id = " + mtable + ".id").
  1733. Where(whereSql).
  1734. Scan(&list).Error
  1735. if err != nil {
  1736. logs.Error("db error: %s ", err)
  1737. return list, global.GetFailedErr
  1738. }
  1739. models.InitBasicData(deptId)
  1740. for i := 0; i < len(list); i++ {
  1741. if id, ok := list[i][models.FieldProductID]; ok {
  1742. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1743. }
  1744. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1745. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1746. }
  1747. if id, ok := list[i][models.FieldSpecID]; ok {
  1748. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1749. }
  1750. if id, ok := list[i][models.FieldUnitID]; ok {
  1751. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1752. }
  1753. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1754. if utils.ToInt(id) == 0 {
  1755. list[i][models.FieldDosageFormID] = nil
  1756. } else {
  1757. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1758. }
  1759. }
  1760. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  1761. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  1762. }
  1763. return list, nil
  1764. }
  1765. // StockUnitList 发货单位,收货单位 去重列表
  1766. func (e *StockTemplate) StockUnitList(c *dto.StockUnitListReq, deptId int) (list []string, err error) {
  1767. whereSql := "dept_id = " + strconv.Itoa(deptId) + " AND deleted_at is null"
  1768. switch c.Type {
  1769. case 1:
  1770. if len(c.Name) > 0 {
  1771. whereSql += " AND forwarding_unit like '%" + c.Name + "%'"
  1772. }
  1773. whereSql += " AND forwarding_unit is not null AND forwarding_unit != ''"
  1774. err = db.DB.Table("stock_in").
  1775. Distinct("forwarding_unit").
  1776. Where(whereSql).
  1777. Scan(&list).Error
  1778. if err != nil {
  1779. logs.Error("db error: %s ", err)
  1780. return list, global.GetFailedErr
  1781. }
  1782. return
  1783. case 2:
  1784. if len(c.Name) > 0 {
  1785. whereSql += " AND receiving_unit like '%" + c.Name + "%'"
  1786. }
  1787. whereSql += " AND receiving_unit is not null AND receiving_unit != ''"
  1788. err = db.DB.Table("stock_out").
  1789. Distinct("receiving_unit").
  1790. Where(whereSql).
  1791. Scan(&list).Error
  1792. if err != nil {
  1793. logs.Error("db error: %s ", err)
  1794. return list, global.GetFailedErr
  1795. }
  1796. return
  1797. default:
  1798. if len(c.Name) > 0 {
  1799. whereSql += " AND (forwarding_unit like '%" + c.Name + "%' OR receiving_unit like '%" + c.Name + "%')"
  1800. }
  1801. forwarding_unit, receiving_unit := []string{}, []string{}
  1802. err = db.DB.Table("medicine_inventory").
  1803. Distinct("forwarding_unit").
  1804. Where(whereSql + " AND forwarding_unit is not null AND forwarding_unit != ''").
  1805. Scan(&forwarding_unit).Error
  1806. if err != nil {
  1807. logs.Error("db error: %s ", err)
  1808. return list, global.GetFailedErr
  1809. }
  1810. err = db.DB.Table("medicine_inventory").
  1811. Distinct("receiving_unit").
  1812. Where(whereSql + " AND receiving_unit is not null AND receiving_unit != ''").
  1813. Scan(&receiving_unit).Error
  1814. if err != nil {
  1815. logs.Error("db error: %s ", err)
  1816. return list, global.GetFailedErr
  1817. }
  1818. list = append(forwarding_unit, receiving_unit...)
  1819. return
  1820. }
  1821. }
  1822. func (e *StockTemplate) StockOperatorList(c *dto.StockOperatorListReq, deptId int) (list []string, err error) {
  1823. whereSql := "dept_id = " + strconv.Itoa(deptId) + " AND deleted_at is null"
  1824. if len(c.Name) > 0 {
  1825. whereSql += " AND operator like '%" + c.Name + "%'"
  1826. }
  1827. err = db.DB.Table("medicine_inventory").
  1828. Distinct("operator").
  1829. Where(whereSql).
  1830. Scan(&list).Error
  1831. if err != nil {
  1832. logs.Error("db error: %s ", err)
  1833. return list, global.GetFailedErr
  1834. }
  1835. return list, nil
  1836. }
  1837. // 库存查询
  1838. func (e *StockTemplate) StockInquiryList(c *dto.StockStatListReq, deptId int) (list []map[string]interface{}, count int64, err error) {
  1839. mtable := models.GetMedicineInfoTableName(deptId)
  1840. whereSql := ""
  1841. if c.ProductID > 0 {
  1842. whereSql += " AND m_info.product_id = " + strconv.Itoa(c.ProductID)
  1843. }
  1844. if c.EnterpriseID > 0 {
  1845. whereSql += " AND m_info.enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1846. }
  1847. if len(c.BatchNumber) > 0 {
  1848. whereSql += " AND m_info.batch_number = '" + c.BatchNumber + "'"
  1849. }
  1850. if len(c.StartDate) > 0 {
  1851. whereSql += " AND m_info.expiry_date >= '" + c.StartDate + "'"
  1852. }
  1853. if len(c.EndDate) > 0 {
  1854. whereSql += " AND m_info.expiry_date <= '" + c.EndDate + "'"
  1855. }
  1856. if len(whereSql) > 0 {
  1857. whereSql = " WHERE " + strings.TrimLeft(whereSql, " AND ")
  1858. }
  1859. offset := (c.Page - 1) * c.PageSize
  1860. sql := "SELECT mi.*,m_info.* FROM (SELECT medicine_id,MAX(id) AS latest_id FROM medicine_inventory WHERE dept_id = " + strconv.Itoa(deptId) + " AND deleted_at is null GROUP BY medicine_id) AS mi_latest " +
  1861. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  1862. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id" + whereSql + " order by m_info.expiry_date limit ? offset ?;"
  1863. sqlWhereCount := "SELECT COUNT(1) FROM (SELECT medicine_id,MAX(id) AS latest_id FROM medicine_inventory WHERE dept_id = " + strconv.Itoa(deptId) + " AND deleted_at is null GROUP BY medicine_id) AS mi_latest " +
  1864. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  1865. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id" + whereSql
  1866. err = db.DB.Raw(sqlWhereCount).Scan(&count).Error
  1867. if err != nil {
  1868. logs.Error("db error: %s ", err)
  1869. return list, count, err
  1870. }
  1871. err = db.DB.Raw(sql, c.PageSize, offset).Scan(&list).Error
  1872. if err != nil {
  1873. logs.Error("db error: %s ", err)
  1874. return list, count, err
  1875. }
  1876. models.InitBasicData(deptId)
  1877. for i := 0; i < len(list); i++ {
  1878. if id, ok := list[i][models.FieldProductID]; ok {
  1879. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1880. }
  1881. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1882. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1883. }
  1884. if id, ok := list[i][models.FieldSpecID]; ok {
  1885. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1886. }
  1887. if id, ok := list[i][models.FieldUnitID]; ok {
  1888. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1889. }
  1890. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1891. if utils.ToInt(id) == 0 {
  1892. list[i][models.FieldDosageFormID] = nil
  1893. } else {
  1894. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1895. }
  1896. }
  1897. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  1898. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  1899. }
  1900. return list, count, nil
  1901. }
  1902. func (e *StockTemplate) GetStockInquiry(c *dto.GetStockStatReq, deptId int) (res map[string]interface{}, err error) {
  1903. mtable := models.GetMedicineInfoTableName(deptId)
  1904. whereSql := ""
  1905. if c.ProductID > 0 {
  1906. whereSql += " AND m_info.product_id = " + strconv.Itoa(c.ProductID)
  1907. }
  1908. if c.EnterpriseID > 0 {
  1909. whereSql += " AND m_info.enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1910. }
  1911. if c.SpecID > 0 {
  1912. whereSql += " AND m_info.spec_id = " + strconv.Itoa(c.SpecID)
  1913. }
  1914. if len(c.BatchNumber) > 0 {
  1915. whereSql += " AND m_info.batch_number = '" + c.BatchNumber + "'"
  1916. }
  1917. if len(whereSql) > 0 {
  1918. whereSql = " WHERE " + strings.TrimLeft(whereSql, " AND ")
  1919. }
  1920. sql := "SELECT mi.* FROM (SELECT medicine_id,MAX(id) AS latest_id FROM medicine_inventory WHERE dept_id = " + strconv.Itoa(deptId) + " AND deleted_at is null GROUP BY medicine_id) AS mi_latest " +
  1921. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  1922. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id" + whereSql + " order by m_info.expiry_date ;"
  1923. err = db.DB.Raw(sql).Last(&res).Error
  1924. if err != nil {
  1925. logs.Error("db error: %s ", err)
  1926. if errors.Is(err, gorm.ErrRecordNotFound) {
  1927. //return res, errors.New("药品信息不存在,查询药品库存失败!")
  1928. res = make(map[string]interface{})
  1929. res["balance"] = 0
  1930. return res, nil
  1931. }
  1932. return res, global.GetFailedErr
  1933. }
  1934. return res, nil
  1935. }
  1936. // 库存查询excel
  1937. func (e *StockTemplate) StockInquiryExcel(c *dto.StockStatListReq, deptId int) (list []map[string]interface{}, err error) {
  1938. mtable := models.GetMedicineInfoTableName(deptId)
  1939. whereSql := ""
  1940. if c.ProductID > 0 {
  1941. whereSql += " AND m_info.product_id = " + strconv.Itoa(c.ProductID)
  1942. }
  1943. if c.EnterpriseID > 0 {
  1944. whereSql += " AND m_info.enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1945. }
  1946. if len(c.BatchNumber) > 0 {
  1947. whereSql += " AND m_info.batch_number = " + c.BatchNumber
  1948. }
  1949. if len(c.StartDate) > 0 {
  1950. whereSql += " AND m_info.expiry_date >= '" + c.StartDate + "'"
  1951. }
  1952. if len(c.EndDate) > 0 {
  1953. whereSql += " AND m_info.expiry_date <= '" + c.EndDate + "'"
  1954. }
  1955. if len(whereSql) > 0 {
  1956. whereSql = " WHERE " + strings.TrimLeft(whereSql, " AND ")
  1957. }
  1958. sql := "SELECT mi.*,m_info.* FROM (SELECT medicine_id,MAX(id) AS latest_id FROM medicine_inventory WHERE dept_id = " + strconv.Itoa(deptId) + " AND deleted_at is null GROUP BY medicine_id) AS mi_latest " +
  1959. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  1960. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id" + whereSql + " order by m_info.expiry_date"
  1961. err = db.DB.Raw(sql).Scan(&list).Error
  1962. if err != nil {
  1963. logs.Error("db error: %s ", err)
  1964. return list, global.GetFailedErr
  1965. }
  1966. models.InitBasicData(deptId)
  1967. for i := 0; i < len(list); i++ {
  1968. if id, ok := list[i][models.FieldProductID]; ok {
  1969. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1970. }
  1971. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1972. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1973. }
  1974. if id, ok := list[i][models.FieldSpecID]; ok {
  1975. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1976. }
  1977. if id, ok := list[i][models.FieldUnitID]; ok {
  1978. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1979. }
  1980. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1981. if utils.ToInt(id) == 0 {
  1982. list[i][models.FieldDosageFormID] = nil
  1983. } else {
  1984. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1985. }
  1986. }
  1987. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  1988. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  1989. }
  1990. return list, nil
  1991. }
  1992. func (e *StockTemplate) StockStat(c *dto.StockStatReq, deptId int) (list []map[string]interface{}, count int64, err error) {
  1993. mtable := models.GetMedicineInfoTableName(deptId)
  1994. whereSql := ""
  1995. if c.ProductID > 0 {
  1996. whereSql += " AND m_info.product_id = " + strconv.Itoa(c.ProductID)
  1997. }
  1998. if c.SpecID > 0 {
  1999. whereSql += " AND m_info.spec_id = " + strconv.Itoa(c.SpecID)
  2000. }
  2001. if len(whereSql) > 0 {
  2002. whereSql = " WHERE " + strings.TrimLeft(whereSql, " AND ")
  2003. }
  2004. var result []map[string]interface{}
  2005. sql := "SELECT mi.balance,m_info.product_id,m_info.spec_id,m_info.unit_id FROM (SELECT medicine_id,MAX(id) AS latest_id FROM medicine_inventory WHERE dept_id = " + strconv.Itoa(deptId) + " AND deleted_at is null GROUP BY medicine_id) AS mi_latest " +
  2006. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  2007. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id" + whereSql
  2008. err = db.DB.Raw(sql).Scan(&result).Error
  2009. if err != nil {
  2010. logs.Error("db error: %s ", err)
  2011. return list, count, global.GetFailedErr
  2012. }
  2013. models.InitBasicData(deptId)
  2014. statMap := map[string]int{}
  2015. unitMap := map[string]string{}
  2016. for i := 0; i < len(result); i++ {
  2017. key := fmt.Sprintf("%v-%v", result[i][models.FieldProductID], result[i][models.FieldSpecID])
  2018. if num, ok := statMap[key]; ok {
  2019. statMap[key] = num + utils.ToInt(result[i]["balance"])
  2020. } else {
  2021. statMap[key] = utils.ToInt(result[i]["balance"])
  2022. }
  2023. if result[i][models.FieldUnitID] != nil && utils.ToInt(result[i][models.FieldUnitID]) != 0 {
  2024. if v, ok := unitMap[key]; ok {
  2025. id := fmt.Sprintf("|%v|", result[i][models.FieldUnitID])
  2026. if strings.Contains(v, id) {
  2027. unitMap[key] = v + id
  2028. }
  2029. } else {
  2030. unitMap[key] = fmt.Sprintf("|%v|", result[i][models.FieldUnitID])
  2031. }
  2032. }
  2033. }
  2034. models.InitBasicData(deptId)
  2035. for key, num := range statMap {
  2036. product_id := utils.ToInt(strings.Split(key, "-")[0])
  2037. spec_id := utils.ToInt(strings.Split(key, "-")[1])
  2038. unit_ids := []string{}
  2039. if len(unitMap[key]) > 0 {
  2040. unit_ids = strings.Split(strings.Trim(unitMap[key], "|"), "|")
  2041. }
  2042. unit_name := ""
  2043. unit_ids_int := []int{}
  2044. for _, id := range unit_ids {
  2045. unit_name += models.Read_Unit_Get(utils.ToInt(id))
  2046. unit_name += "/"
  2047. unit_ids_int = append(unit_ids_int, utils.ToInt(id))
  2048. }
  2049. unit_name = strings.Trim(unit_name, "/")
  2050. list = append(list, map[string]interface{}{
  2051. "product_id": product_id,
  2052. "product_name": models.Read_Product_Get(product_id),
  2053. "spec_id": spec_id,
  2054. "spec_name": models.Read_Spec_Get(spec_id),
  2055. "balance": num,
  2056. "unit_name": unit_name,
  2057. "unit_ids": unit_ids_int,
  2058. })
  2059. }
  2060. sort.Slice(list, func(i, j int) bool {
  2061. return utils.ToInt(list[i]["product_id"]) < utils.ToInt(list[j]["product_id"])
  2062. })
  2063. return list, count, nil
  2064. }
  2065. func (e *StockTemplate) StockHomeStat(deptId int) (list map[string]interface{}, count int64, err error) {
  2066. mtable := models.GetMedicineInfoTableName(deptId)
  2067. var result []map[string]interface{}
  2068. sql := "SELECT mi.balance,m_info.unit_price FROM (SELECT medicine_id,MAX(id) AS latest_id FROM medicine_inventory WHERE dept_id = " + strconv.Itoa(deptId) + " AND deleted_at is null GROUP BY medicine_id) AS mi_latest " +
  2069. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  2070. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id"
  2071. err = db.DB.Raw(sql).Scan(&result).Error
  2072. if err != nil {
  2073. logs.Error("db error: %s ", err)
  2074. return list, count, global.GetFailedErr
  2075. }
  2076. inventoryQuantity := 0
  2077. inventoryAmount := 0.0
  2078. for i := 0; i < len(result); i++ {
  2079. unit_price := utils.ToFloat64(result[i]["unit_price"])
  2080. inventoryQuantity += utils.ToInt(result[i]["balance"])
  2081. inventoryAmount += utils.ToFloat64(inventoryQuantity) * unit_price
  2082. }
  2083. var totalOut, totalIn int
  2084. var totalOutMoney, totalInMoney float64
  2085. err = db.DB.Model(models.StockIn{}).Select("COALESCE(SUM(quantity),0)").Where("dept_id = ?", deptId).Scan(&totalIn).Error
  2086. if err != nil {
  2087. logs.Error("db error: %s ", err)
  2088. return list, count, err
  2089. }
  2090. err = db.DB.Table("stock_in").
  2091. Select("COALESCE(SUM(stock_in.quantity * "+mtable+".unit_price),0)").
  2092. Joins("join "+mtable+" on stock_in.medicine_id = "+mtable+".id").
  2093. Where("dept_id = ? ", deptId).
  2094. Scan(&totalInMoney).Error
  2095. if err != nil {
  2096. logs.Error("db error: %s ", err)
  2097. return list, count, err
  2098. }
  2099. err = db.DB.Model(models.StockOut{}).Select("COALESCE(SUM(quantity),0)").Where("dept_id = ?", deptId).Scan(&totalOut).Error
  2100. if err != nil {
  2101. logs.Error("db error: %s ", err)
  2102. return list, count, err
  2103. }
  2104. err = db.DB.Table("stock_out").
  2105. Select("COALESCE(SUM(stock_out.quantity * "+mtable+".unit_price),0)").
  2106. Joins("join "+mtable+" on stock_out.medicine_id = "+mtable+".id").
  2107. Where("dept_id = ? ", deptId).
  2108. Scan(&totalOutMoney).Error
  2109. if err != nil {
  2110. logs.Error("db error: %s ", err)
  2111. return list, count, err
  2112. }
  2113. list = make(map[string]interface{})
  2114. list["inventoryQuantity"] = inventoryQuantity // 库存总量
  2115. list["inventoryAmount"] = inventoryAmount // 库存总额(成本金额)
  2116. list["totalOut"] = totalOut // 出库
  2117. list["totalOutMoney"] = totalOutMoney // 出库总金额
  2118. list["totalIn"] = totalIn // 入库
  2119. list["totalInMoney"] = totalInMoney // 入库总金额
  2120. return list, count, nil
  2121. }
  2122. func (e *StockTemplate) StockTemplateTransportRecordWord2(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
  2123. mtable := models.GetMedicineInfoTableName(deptId)
  2124. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
  2125. if c.ProductID > 0 {
  2126. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  2127. }
  2128. if len(c.Date) > 0 {
  2129. whereSql += " AND stock_out.date = '" + c.Date + "'"
  2130. }
  2131. if len(c.ReceivingUnit) > 0 {
  2132. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  2133. }
  2134. if len(c.StockOutIds) > 0 {
  2135. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2136. }
  2137. err = db.DB.Table("stock_out").
  2138. Select(mtable + ".*,stock_out.quantity as quantity,stock_out.id as stock_out_id," + mtable + ".id as medicine_id").
  2139. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2140. Where(whereSql).
  2141. Scan(&list).Error
  2142. if err != nil {
  2143. logs.Error("db error: %s ", err)
  2144. return list, global.GetFailedErr
  2145. }
  2146. models.InitBasicData(deptId)
  2147. for i := 0; i < len(list); i++ {
  2148. if id, ok := list[i][models.FieldProductID]; ok {
  2149. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2150. }
  2151. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2152. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2153. }
  2154. if id, ok := list[i][models.FieldSpecID]; ok {
  2155. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2156. }
  2157. if id, ok := list[i][models.FieldUnitID]; ok {
  2158. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2159. }
  2160. }
  2161. return list, nil
  2162. }
  2163. func (e *StockTemplate) StockTemplateTransportRecordWord(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
  2164. mtable := models.GetMedicineInfoTableName(deptId)
  2165. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
  2166. if c.ProductID > 0 {
  2167. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  2168. }
  2169. if len(c.Date) > 0 {
  2170. whereSql += " AND stock_out.date = '" + c.Date + "'"
  2171. }
  2172. if len(c.ReceivingUnit) > 0 {
  2173. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  2174. }
  2175. if len(c.StockOutIds) > 0 {
  2176. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2177. }
  2178. err = db.DB.Table("stock_out").
  2179. Select("stock_out.*,stock_out.id as stock_out_id," + mtable + ".*," + mtable + ".id as medicine_id").
  2180. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2181. Order("stock_out.date desc,stock_out.id desc").
  2182. Where(whereSql).
  2183. Scan(&list).Error
  2184. if err != nil {
  2185. logs.Error("db error: %s ", err)
  2186. return list, global.GetFailedErr
  2187. }
  2188. models.InitBasicData(deptId)
  2189. for i := 0; i < len(list); i++ {
  2190. list[i]["unit_price"] = utils.ToFloat64(list[i]["unit_price"])
  2191. // 金额
  2192. list[i]["money"] = utils.ToFloat64(list[i]["unit_price"]) * utils.ToFloat64(list[i]["quantity"])
  2193. if id, ok := list[i][models.FieldProductID]; ok {
  2194. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2195. }
  2196. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2197. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2198. }
  2199. if id, ok := list[i][models.FieldSpecID]; ok {
  2200. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2201. }
  2202. if id, ok := list[i][models.FieldUnitID]; ok {
  2203. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2204. }
  2205. if id, ok := list[i][models.FieldDosageFormID]; ok {
  2206. if utils.ToInt(id) == 0 {
  2207. list[i][models.FieldDosageFormID] = nil
  2208. } else {
  2209. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  2210. }
  2211. }
  2212. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  2213. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  2214. }
  2215. return list, nil
  2216. }
  2217. func (e *StockTemplate) StockRefundOutTransportRecordPdf(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
  2218. mtable := models.GetMedicineInfoTableName(deptId)
  2219. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
  2220. if c.ProductID > 0 {
  2221. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  2222. }
  2223. if len(c.Date) > 0 {
  2224. whereSql += " AND stock_out.date = '" + c.Date + "'"
  2225. }
  2226. if len(c.ReceivingUnit) > 0 {
  2227. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  2228. }
  2229. if len(c.StockOutIds) > 0 {
  2230. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2231. }
  2232. err = db.DB.Table("stock_out").
  2233. Select(mtable + ".*," + "stock_out.*,stock_out.id as stock_out_id," + mtable + ".id as medicine_id").
  2234. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2235. Order("stock_out.date desc,stock_out.id desc").
  2236. Where(whereSql).
  2237. Scan(&list).Error
  2238. if err != nil {
  2239. logs.Error("db error: %s ", err)
  2240. return list, global.GetFailedErr
  2241. }
  2242. models.InitBasicData(deptId)
  2243. for i := 0; i < len(list); i++ {
  2244. list[i]["unit_price"] = utils.ToFloat64(list[i]["unit_price"])
  2245. // 金额
  2246. list[i]["money"] = utils.ToFloat64(list[i]["unit_price"]) * utils.ToFloat64(list[i]["quantity"])
  2247. if id, ok := list[i][models.FieldProductID]; ok {
  2248. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2249. }
  2250. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2251. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2252. }
  2253. if id, ok := list[i][models.FieldSpecID]; ok {
  2254. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2255. }
  2256. if id, ok := list[i][models.FieldUnitID]; ok {
  2257. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2258. }
  2259. if id, ok := list[i][models.FieldDosageFormID]; ok {
  2260. if utils.ToInt(id) == 0 {
  2261. list[i][models.FieldDosageFormID] = nil
  2262. } else {
  2263. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  2264. }
  2265. }
  2266. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  2267. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  2268. }
  2269. return list, nil
  2270. }
  2271. func (e *StockTemplate) GetRefundOutBarCodeInfo(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
  2272. mtable := models.GetMedicineInfoTableName(deptId)
  2273. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
  2274. if c.ProductID > 0 {
  2275. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  2276. }
  2277. if len(c.Date) > 0 {
  2278. whereSql += " AND stock_out.date = '" + c.Date + "'"
  2279. }
  2280. if len(c.ReceivingUnit) > 0 {
  2281. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  2282. }
  2283. if len(c.StockOutIds) > 0 {
  2284. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2285. }
  2286. err = db.DB.Table("stock_out").
  2287. Select(mtable + ".*,stock_out.quantity as quantity,stock_out.id as stock_out_id," + mtable + ".id as medicine_id").
  2288. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2289. Where(whereSql).
  2290. Scan(&list).Error
  2291. if err != nil {
  2292. logs.Error("db error: %s ", err)
  2293. return list, global.GetFailedErr
  2294. }
  2295. models.InitBasicData(deptId)
  2296. for i := 0; i < len(list); i++ {
  2297. if id, ok := list[i][models.FieldProductID]; ok {
  2298. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2299. }
  2300. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2301. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2302. }
  2303. if id, ok := list[i][models.FieldSpecID]; ok {
  2304. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2305. }
  2306. if id, ok := list[i][models.FieldUnitID]; ok {
  2307. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2308. }
  2309. }
  2310. return list, nil
  2311. }
  2312. func (e *StockTemplate) StockRefundOutPdf(c *dto.StockRefundOutExport, deptId int) (list []map[string]interface{}, err error) {
  2313. mtable := models.GetMedicineInfoTableName(deptId)
  2314. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
  2315. if len(c.StockOutIds) > 0 {
  2316. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2317. }
  2318. err = db.DB.Table("stock_out").
  2319. Select("stock_out.*,stock_out.id as stock_out_id," + mtable + ".*," + mtable + ".id as medicine_id").
  2320. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2321. Where(whereSql).
  2322. Scan(&list).Error
  2323. if err != nil {
  2324. logs.Error("db error: %s ", err)
  2325. return list, global.GetFailedErr
  2326. }
  2327. models.InitBasicData(deptId)
  2328. for i := 0; i < len(list); i++ {
  2329. list[i]["unit_price"] = utils.ToFloat64(list[i]["unit_price"])
  2330. // 金额
  2331. list[i]["money"] = utils.ToFloat64(list[i]["unit_price"]) * utils.ToFloat64(list[i]["quantity"])
  2332. if id, ok := list[i][models.FieldProductID]; ok {
  2333. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2334. }
  2335. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2336. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2337. }
  2338. if id, ok := list[i][models.FieldSpecID]; ok {
  2339. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2340. }
  2341. if id, ok := list[i][models.FieldUnitID]; ok {
  2342. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2343. }
  2344. if id, ok := list[i][models.FieldDosageFormID]; ok {
  2345. if utils.ToInt(id) == 0 {
  2346. list[i][models.FieldDosageFormID] = nil
  2347. } else {
  2348. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  2349. }
  2350. }
  2351. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  2352. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  2353. }
  2354. return list, nil
  2355. }