stock_template.go 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567
  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. return res, err
  1927. }
  1928. //models.InitBasicData(deptId)
  1929. //if id, ok := res[models.FieldProductID]; ok {
  1930. // res[models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1931. //}
  1932. //if id, ok := res[models.FieldEnterpriseID]; ok {
  1933. // res[models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1934. //}
  1935. //if id, ok := res[models.FieldSpecID]; ok {
  1936. // res[models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1937. //}
  1938. //if id, ok := res[models.FieldUnitID]; ok {
  1939. // res[models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1940. //}
  1941. //if id, ok := res[models.FieldDosageFormID]; ok {
  1942. // if utils.ToInt(id) == 0 {
  1943. // res[models.FieldDosageFormID] = nil
  1944. // } else {
  1945. // res[models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  1946. // }
  1947. //}
  1948. //res[models.FieldExpiryDate] = utils.ToDate(res[models.FieldExpiryDate])
  1949. //res[models.FieldProducedDate] = utils.ToDate(res[models.FieldProducedDate])
  1950. return res, nil
  1951. }
  1952. // 库存查询excel
  1953. func (e *StockTemplate) StockInquiryExcel(c *dto.StockStatListReq, deptId int) (list []map[string]interface{}, err error) {
  1954. mtable := models.GetMedicineInfoTableName(deptId)
  1955. whereSql := ""
  1956. if c.ProductID > 0 {
  1957. whereSql += " AND m_info.product_id = " + strconv.Itoa(c.ProductID)
  1958. }
  1959. if c.EnterpriseID > 0 {
  1960. whereSql += " AND m_info.enterprise_id = " + strconv.Itoa(c.EnterpriseID)
  1961. }
  1962. if len(c.BatchNumber) > 0 {
  1963. whereSql += " AND m_info.batch_number = " + c.BatchNumber
  1964. }
  1965. if len(c.StartDate) > 0 {
  1966. whereSql += " AND m_info.expiry_date >= '" + c.StartDate + "'"
  1967. }
  1968. if len(c.EndDate) > 0 {
  1969. whereSql += " AND m_info.expiry_date <= '" + c.EndDate + "'"
  1970. }
  1971. if len(whereSql) > 0 {
  1972. whereSql = " WHERE " + strings.TrimLeft(whereSql, " AND ")
  1973. }
  1974. 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 " +
  1975. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  1976. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id" + whereSql + " order by m_info.expiry_date"
  1977. err = db.DB.Raw(sql).Scan(&list).Error
  1978. if err != nil {
  1979. logs.Error("db error: %s ", err)
  1980. return list, err
  1981. }
  1982. models.InitBasicData(deptId)
  1983. for i := 0; i < len(list); i++ {
  1984. if id, ok := list[i][models.FieldProductID]; ok {
  1985. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  1986. }
  1987. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  1988. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  1989. }
  1990. if id, ok := list[i][models.FieldSpecID]; ok {
  1991. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  1992. }
  1993. if id, ok := list[i][models.FieldUnitID]; ok {
  1994. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  1995. }
  1996. if id, ok := list[i][models.FieldDosageFormID]; ok {
  1997. if utils.ToInt(id) == 0 {
  1998. list[i][models.FieldDosageFormID] = nil
  1999. } else {
  2000. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  2001. }
  2002. }
  2003. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  2004. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  2005. }
  2006. return list, nil
  2007. }
  2008. func (e *StockTemplate) StockStat(c *dto.StockStatReq, deptId int) (list []map[string]interface{}, count int64, err error) {
  2009. mtable := models.GetMedicineInfoTableName(deptId)
  2010. whereSql := ""
  2011. if c.ProductID > 0 {
  2012. whereSql += " AND m_info.product_id = " + strconv.Itoa(c.ProductID)
  2013. }
  2014. if c.SpecID > 0 {
  2015. whereSql += " AND m_info.spec_id = " + strconv.Itoa(c.SpecID)
  2016. }
  2017. if len(whereSql) > 0 {
  2018. whereSql = " WHERE " + strings.TrimLeft(whereSql, " AND ")
  2019. }
  2020. var result []map[string]interface{}
  2021. 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 " +
  2022. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  2023. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id" + whereSql
  2024. err = db.DB.Raw(sql).Scan(&result).Error
  2025. if err != nil {
  2026. logs.Error("db error: %s ", err)
  2027. return list, count, err
  2028. }
  2029. models.InitBasicData(deptId)
  2030. statMap := map[string]int{}
  2031. unitMap := map[string]string{}
  2032. for i := 0; i < len(result); i++ {
  2033. key := fmt.Sprintf("%v-%v", result[i][models.FieldProductID], result[i][models.FieldSpecID])
  2034. if num, ok := statMap[key]; ok {
  2035. statMap[key] = num + utils.ToInt(result[i]["balance"])
  2036. } else {
  2037. statMap[key] = utils.ToInt(result[i]["balance"])
  2038. }
  2039. if result[i][models.FieldUnitID] != nil && utils.ToInt(result[i][models.FieldUnitID]) != 0 {
  2040. if v, ok := unitMap[key]; ok {
  2041. id := fmt.Sprintf("|%v|", result[i][models.FieldUnitID])
  2042. if strings.Contains(v, id) {
  2043. unitMap[key] = v + id
  2044. }
  2045. } else {
  2046. unitMap[key] = fmt.Sprintf("|%v|", result[i][models.FieldUnitID])
  2047. }
  2048. }
  2049. }
  2050. models.InitBasicData(deptId)
  2051. for key, num := range statMap {
  2052. product_id := utils.ToInt(strings.Split(key, "-")[0])
  2053. spec_id := utils.ToInt(strings.Split(key, "-")[1])
  2054. unit_ids := []string{}
  2055. if len(unitMap[key]) > 0 {
  2056. unit_ids = strings.Split(strings.Trim(unitMap[key], "|"), "|")
  2057. }
  2058. unit_name := ""
  2059. unit_ids_int := []int{}
  2060. for _, id := range unit_ids {
  2061. unit_name += models.Read_Unit_Get(utils.ToInt(id))
  2062. unit_name += "/"
  2063. unit_ids_int = append(unit_ids_int, utils.ToInt(id))
  2064. }
  2065. unit_name = strings.Trim(unit_name, "/")
  2066. list = append(list, map[string]interface{}{
  2067. "product_id": product_id,
  2068. "product_name": models.Read_Product_Get(product_id),
  2069. "spec_id": spec_id,
  2070. "spec_name": models.Read_Spec_Get(spec_id),
  2071. "balance": num,
  2072. "unit_name": unit_name,
  2073. "unit_ids": unit_ids_int,
  2074. })
  2075. }
  2076. sort.Slice(list, func(i, j int) bool {
  2077. return utils.ToInt(list[i]["product_id"]) < utils.ToInt(list[j]["product_id"])
  2078. })
  2079. return list, count, nil
  2080. }
  2081. func (e *StockTemplate) StockHomeStat(deptId int) (list map[string]interface{}, count int64, err error) {
  2082. mtable := models.GetMedicineInfoTableName(deptId)
  2083. var result []map[string]interface{}
  2084. 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 " +
  2085. "JOIN medicine_inventory AS mi ON mi.medicine_id=mi_latest.medicine_id AND mi.id=mi_latest.latest_id " +
  2086. "LEFT JOIN " + mtable + " AS m_info ON mi.medicine_id=m_info.id"
  2087. err = db.DB.Raw(sql).Scan(&result).Error
  2088. if err != nil {
  2089. logs.Error("db error: %s ", err)
  2090. return list, count, err
  2091. }
  2092. inventoryQuantity := 0
  2093. inventoryAmount := 0.0
  2094. for i := 0; i < len(result); i++ {
  2095. unit_price := utils.ToFloat64(result[i]["unit_price"])
  2096. inventoryQuantity += utils.ToInt(result[i]["balance"])
  2097. inventoryAmount += utils.ToFloat64(inventoryQuantity) * unit_price
  2098. }
  2099. var totalOut, totalIn int
  2100. var totalOutMoney, totalInMoney float64
  2101. err = db.DB.Model(models.StockIn{}).Select("COALESCE(SUM(quantity),0)").Where("dept_id = ?", deptId).Scan(&totalIn).Error
  2102. if err != nil {
  2103. logs.Error("db error: %s ", err)
  2104. return list, count, err
  2105. }
  2106. err = db.DB.Table("stock_in").
  2107. Select("COALESCE(SUM(stock_in.quantity * "+mtable+".unit_price),0)").
  2108. Joins("join "+mtable+" on stock_in.medicine_id = "+mtable+".id").
  2109. Where("dept_id = ? ", deptId).
  2110. Scan(&totalInMoney).Error
  2111. if err != nil {
  2112. logs.Error("db error: %s ", err)
  2113. return list, count, err
  2114. }
  2115. err = db.DB.Model(models.StockOut{}).Select("COALESCE(SUM(quantity),0)").Where("dept_id = ?", deptId).Scan(&totalOut).Error
  2116. if err != nil {
  2117. logs.Error("db error: %s ", err)
  2118. return list, count, err
  2119. }
  2120. err = db.DB.Table("stock_out").
  2121. Select("COALESCE(SUM(stock_out.quantity * "+mtable+".unit_price),0)").
  2122. Joins("join "+mtable+" on stock_out.medicine_id = "+mtable+".id").
  2123. Where("dept_id = ? ", deptId).
  2124. Scan(&totalOutMoney).Error
  2125. if err != nil {
  2126. logs.Error("db error: %s ", err)
  2127. return list, count, err
  2128. }
  2129. list = make(map[string]interface{})
  2130. list["inventoryQuantity"] = inventoryQuantity // 库存总量
  2131. list["inventoryAmount"] = inventoryAmount // 库存总额(成本金额)
  2132. list["totalOut"] = totalOut // 出库
  2133. list["totalOutMoney"] = totalOutMoney // 出库总金额
  2134. list["totalIn"] = totalIn // 入库
  2135. list["totalInMoney"] = totalInMoney // 入库总金额
  2136. return list, count, nil
  2137. }
  2138. func (e *StockTemplate) StockTemplateTransportRecordWord2(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
  2139. mtable := models.GetMedicineInfoTableName(deptId)
  2140. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
  2141. if c.ProductID > 0 {
  2142. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  2143. }
  2144. if len(c.Date) > 0 {
  2145. whereSql += " AND stock_out.date = '" + c.Date + "'"
  2146. }
  2147. if len(c.ReceivingUnit) > 0 {
  2148. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  2149. }
  2150. if len(c.StockOutIds) > 0 {
  2151. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2152. }
  2153. err = db.DB.Table("stock_out").
  2154. Select(mtable + ".*,stock_out.quantity as quantity,stock_out.id as stock_out_id," + mtable + ".id as medicine_id").
  2155. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2156. Where(whereSql).
  2157. Scan(&list).Error
  2158. if err != nil {
  2159. logs.Error("db error: %s ", err)
  2160. return list, global.GetFailedErr
  2161. }
  2162. models.InitBasicData(deptId)
  2163. for i := 0; i < len(list); i++ {
  2164. if id, ok := list[i][models.FieldProductID]; ok {
  2165. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2166. }
  2167. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2168. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2169. }
  2170. if id, ok := list[i][models.FieldSpecID]; ok {
  2171. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2172. }
  2173. if id, ok := list[i][models.FieldUnitID]; ok {
  2174. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2175. }
  2176. }
  2177. return list, nil
  2178. }
  2179. func (e *StockTemplate) StockTemplateTransportRecordWord(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
  2180. mtable := models.GetMedicineInfoTableName(deptId)
  2181. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state = 1 AND stock_out.deleted_at is null"
  2182. if c.ProductID > 0 {
  2183. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  2184. }
  2185. if len(c.Date) > 0 {
  2186. whereSql += " AND stock_out.date = '" + c.Date + "'"
  2187. }
  2188. if len(c.ReceivingUnit) > 0 {
  2189. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  2190. }
  2191. if len(c.StockOutIds) > 0 {
  2192. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2193. }
  2194. err = db.DB.Table("stock_out").
  2195. Select("stock_out.*,stock_out.id as stock_out_id," + mtable + ".*," + mtable + ".id as medicine_id").
  2196. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2197. Order("stock_out.date desc,stock_out.id desc").
  2198. Where(whereSql).
  2199. Scan(&list).Error
  2200. if err != nil {
  2201. logs.Error("db error: %s ", err)
  2202. return list, global.GetFailedErr
  2203. }
  2204. models.InitBasicData(deptId)
  2205. for i := 0; i < len(list); i++ {
  2206. list[i]["unit_price"] = utils.ToFloat64(list[i]["unit_price"])
  2207. // 金额
  2208. list[i]["money"] = utils.ToFloat64(list[i]["unit_price"]) * utils.ToFloat64(list[i]["quantity"])
  2209. if id, ok := list[i][models.FieldProductID]; ok {
  2210. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2211. }
  2212. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2213. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2214. }
  2215. if id, ok := list[i][models.FieldSpecID]; ok {
  2216. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2217. }
  2218. if id, ok := list[i][models.FieldUnitID]; ok {
  2219. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2220. }
  2221. if id, ok := list[i][models.FieldDosageFormID]; ok {
  2222. if utils.ToInt(id) == 0 {
  2223. list[i][models.FieldDosageFormID] = nil
  2224. } else {
  2225. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  2226. }
  2227. }
  2228. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  2229. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  2230. }
  2231. return list, nil
  2232. }
  2233. func (e *StockTemplate) StockRefundOutTransportRecordPdf(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
  2234. mtable := models.GetMedicineInfoTableName(deptId)
  2235. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
  2236. if c.ProductID > 0 {
  2237. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  2238. }
  2239. if len(c.Date) > 0 {
  2240. whereSql += " AND stock_out.date = '" + c.Date + "'"
  2241. }
  2242. if len(c.ReceivingUnit) > 0 {
  2243. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  2244. }
  2245. if len(c.StockOutIds) > 0 {
  2246. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2247. }
  2248. err = db.DB.Table("stock_out").
  2249. Select(mtable + ".*," + "stock_out.*,stock_out.id as stock_out_id," + mtable + ".id as medicine_id").
  2250. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2251. Order("stock_out.date desc,stock_out.id desc").
  2252. Where(whereSql).
  2253. Scan(&list).Error
  2254. if err != nil {
  2255. logs.Error("db error: %s ", err)
  2256. return list, global.GetFailedErr
  2257. }
  2258. models.InitBasicData(deptId)
  2259. for i := 0; i < len(list); i++ {
  2260. list[i]["unit_price"] = utils.ToFloat64(list[i]["unit_price"])
  2261. // 金额
  2262. list[i]["money"] = utils.ToFloat64(list[i]["unit_price"]) * utils.ToFloat64(list[i]["quantity"])
  2263. if id, ok := list[i][models.FieldProductID]; ok {
  2264. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2265. }
  2266. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2267. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2268. }
  2269. if id, ok := list[i][models.FieldSpecID]; ok {
  2270. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2271. }
  2272. if id, ok := list[i][models.FieldUnitID]; ok {
  2273. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2274. }
  2275. if id, ok := list[i][models.FieldDosageFormID]; ok {
  2276. if utils.ToInt(id) == 0 {
  2277. list[i][models.FieldDosageFormID] = nil
  2278. } else {
  2279. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  2280. }
  2281. }
  2282. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  2283. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  2284. }
  2285. return list, nil
  2286. }
  2287. func (e *StockTemplate) GetRefundOutBarCodeInfo(c *models.TransportRecord, deptId int) (list []map[string]interface{}, err error) {
  2288. mtable := models.GetMedicineInfoTableName(deptId)
  2289. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
  2290. if c.ProductID > 0 {
  2291. whereSql += " AND " + mtable + ".product_id = " + strconv.Itoa(c.ProductID)
  2292. }
  2293. if len(c.Date) > 0 {
  2294. whereSql += " AND stock_out.date = '" + c.Date + "'"
  2295. }
  2296. if len(c.ReceivingUnit) > 0 {
  2297. whereSql += " AND stock_out.receiving_unit like '%" + c.ReceivingUnit + "%'"
  2298. }
  2299. if len(c.StockOutIds) > 0 {
  2300. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2301. }
  2302. err = db.DB.Table("stock_out").
  2303. Select(mtable + ".*,stock_out.quantity as quantity,stock_out.id as stock_out_id," + mtable + ".id as medicine_id").
  2304. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2305. Where(whereSql).
  2306. Scan(&list).Error
  2307. if err != nil {
  2308. logs.Error("db error: %s ", err)
  2309. return list, global.GetFailedErr
  2310. }
  2311. models.InitBasicData(deptId)
  2312. for i := 0; i < len(list); i++ {
  2313. if id, ok := list[i][models.FieldProductID]; ok {
  2314. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2315. }
  2316. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2317. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2318. }
  2319. if id, ok := list[i][models.FieldSpecID]; ok {
  2320. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2321. }
  2322. if id, ok := list[i][models.FieldUnitID]; ok {
  2323. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2324. }
  2325. }
  2326. return list, nil
  2327. }
  2328. func (e *StockTemplate) StockRefundOutPdf(c *dto.StockRefundOutExport, deptId int) (list []map[string]interface{}, err error) {
  2329. mtable := models.GetMedicineInfoTableName(deptId)
  2330. whereSql := "stock_out.dept_id = " + strconv.Itoa(deptId) + " AND state > 1 AND stock_out.deleted_at is null"
  2331. if len(c.StockOutIds) > 0 {
  2332. whereSql += " AND stock_out.id in (" + strings.Join(utils.IntArrayToStringArray(c.StockOutIds), ",") + ")"
  2333. }
  2334. err = db.DB.Table("stock_out").
  2335. Select("stock_out.*,stock_out.id as stock_out_id," + mtable + ".*," + mtable + ".id as medicine_id").
  2336. Joins("left join " + mtable + " on stock_out.medicine_id = " + mtable + ".id").
  2337. Where(whereSql).
  2338. Scan(&list).Error
  2339. if err != nil {
  2340. logs.Error("db error: %s ", err)
  2341. return list, global.GetFailedErr
  2342. }
  2343. models.InitBasicData(deptId)
  2344. for i := 0; i < len(list); i++ {
  2345. list[i]["unit_price"] = utils.ToFloat64(list[i]["unit_price"])
  2346. // 金额
  2347. list[i]["money"] = utils.ToFloat64(list[i]["unit_price"]) * utils.ToFloat64(list[i]["quantity"])
  2348. if id, ok := list[i][models.FieldProductID]; ok {
  2349. list[i][models.FieldProductName] = models.Read_Product_Get(utils.ToInt(id))
  2350. }
  2351. if id, ok := list[i][models.FieldEnterpriseID]; ok {
  2352. list[i][models.FieldEnterpriseName] = models.Read_Enterprise_Get(utils.ToInt(id))
  2353. }
  2354. if id, ok := list[i][models.FieldSpecID]; ok {
  2355. list[i][models.FieldSpecName] = models.Read_Spec_Get(utils.ToInt(id))
  2356. }
  2357. if id, ok := list[i][models.FieldUnitID]; ok {
  2358. list[i][models.FieldUnitName] = models.Read_Unit_Get(utils.ToInt(id))
  2359. }
  2360. if id, ok := list[i][models.FieldDosageFormID]; ok {
  2361. if utils.ToInt(id) == 0 {
  2362. list[i][models.FieldDosageFormID] = nil
  2363. } else {
  2364. list[i][models.FieldDosageFormName] = models.Read_DosageForm_Get(utils.ToInt(id))
  2365. }
  2366. }
  2367. list[i][models.FieldExpiryDate] = utils.ToDate(list[i][models.FieldExpiryDate])
  2368. list[i][models.FieldProducedDate] = utils.ToDate(list[i][models.FieldProducedDate])
  2369. }
  2370. return list, nil
  2371. }