settle_account_main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. package settle_account_main
  2. import (
  3. "dashoo.cn/micro_libary/request"
  4. "database/sql"
  5. "errors"
  6. "fmt"
  7. "github.com/gogf/gf/os/gtime"
  8. "github.com/gogf/gf/util/gconv"
  9. "lims_adapter/dao/account"
  10. "lims_adapter/model"
  11. accountModel "lims_adapter/model/account"
  12. "math"
  13. "strconv"
  14. "strings"
  15. )
  16. // Service 会议室服务
  17. type Service struct {
  18. Dao *account.SettleAccountMainDao
  19. Tenant string
  20. }
  21. // NewSrv 服务初始化
  22. func NewService(tenant string) Service {
  23. return Service{Dao: account.NewSettleAccountMainDao(tenant), Tenant: tenant}
  24. }
  25. // List 结算明细
  26. func (s Service) List(req model.ListReq, user request.UserInfo) ([]accountModel.MainInfo, int, error) {
  27. entityModel := s.Dao.M
  28. where := "1=1"
  29. if req.Entity != nil {
  30. entity := new(accountModel.SettleAccountMainReq)
  31. err := gconv.Struct(req.Entity, entity)
  32. if err != nil {
  33. return nil, 0, err
  34. }
  35. if entity.SearchType != "1" { // 1 查询全部;2 查询主用户;3或其他 查询从用户
  36. if entity.SearchType == "2" {
  37. where += fmt.Sprintf(" AND MainUserId='%v'", user.Id)
  38. } else {
  39. where += fmt.Sprintf(" AND AttachUserId='%v'", user.Id)
  40. }
  41. }
  42. if entity.MainUserId != 0 {
  43. where += fmt.Sprintf(" AND MainUserId='%v'", entity.MainUserId)
  44. }
  45. if entity.MainUser != "" {
  46. where += fmt.Sprintf(" AND MainUser LIKE '%%%v%%'", entity.MainUser)
  47. }
  48. if entity.AttachUserId != 0 {
  49. where += fmt.Sprintf(" AND AttachUserId='%v'", entity.AttachUserId)
  50. }
  51. if entity.AttachUser != "" {
  52. where += fmt.Sprintf(" AND AttachUser LIKE '%%%v%%'", entity.AttachUser)
  53. }
  54. if entity.InstrumentId != 0 {
  55. where += fmt.Sprintf(" AND InstrumentId='%v'", entity.InstrumentId)
  56. }
  57. if entity.InstrumentName != "" {
  58. where += fmt.Sprintf(" AND InstrumentName LIKE '%%%v%%'", entity.InstrumentName)
  59. }
  60. if entity.AppointUserId != 0 {
  61. where += fmt.Sprintf(" AND AppointUserId='%v'", entity.AppointUserId)
  62. }
  63. if entity.AppointUser != "" {
  64. where += fmt.Sprintf(" AND AppointUser LIKE '%%%v%%'", entity.AppointUser)
  65. }
  66. if entity.Status != "" {
  67. where += fmt.Sprintf(" AND Status='%v'", entity.Status)
  68. }
  69. if entity.SettleStatus != "" { // 确认状态
  70. where += fmt.Sprintf(" AND SettleStatus='%v'", entity.SettleStatus)
  71. }
  72. if entity.AccountStatus != "" { // 结算状态
  73. where += fmt.Sprintf(" AND AccountStatus='%v'", entity.AccountStatus)
  74. }
  75. if entity.SettleUser != "" { // 结算人
  76. where += fmt.Sprintf(" AND SettleUser LIKE '%%%v%%'", entity.SettleUser)
  77. }
  78. if entity.VerificationUser != "" { // 确认人
  79. where += fmt.Sprintf(" AND VerificationUser LIKE '%%%v%%'", entity.VerificationUser)
  80. }
  81. if entity.FeeType != "" {
  82. where += fmt.Sprintf(" AND FeeType='%v'", entity.FeeType)
  83. }
  84. if entity.BillId != "" {
  85. where += fmt.Sprintf(" AND BillId='%v'", entity.BillId)
  86. }
  87. if entity.AppointStartDate != "" && entity.AppointEndDate != "" {
  88. where += fmt.Sprintf(" AND AppointStartDate>='%v' AND AppointEndDate<='%v'", entity.AppointStartDate, entity.AppointEndDate)
  89. }
  90. if entity.ActualStartDate != "" && entity.ActualEndDate != "" {
  91. where += fmt.Sprintf(" AND ActualStartDate>='%v' AND ActualEndDate<='%v'", entity.ActualStartDate, entity.ActualEndDate)
  92. }
  93. if entity.SettleStartDate != "" && entity.SettleEndDate != "" {
  94. where += fmt.Sprintf(" AND SettleDate>='%v' AND SettleDate<='%v'", entity.SettleStartDate, entity.SettleEndDate)
  95. }
  96. if entity.VerificationDate != "" {
  97. timelist := strings.Split(entity.VerificationDate, ",")
  98. if len(timelist) == 2 {
  99. where += fmt.Sprintf(" AND VerificationDate>='%v' AND VerificationDate<='%v'", timelist[0], timelist[1])
  100. }
  101. }
  102. if entity.NotInBill == "1" {
  103. where += fmt.Sprintf(" AND (SettleStatus='0' OR Status='0')")
  104. }
  105. }
  106. entityModel = entityModel.Where(where)
  107. total, err := entityModel.Count()
  108. if err != nil {
  109. return nil, 0, err
  110. }
  111. if total == 0 {
  112. return nil, 0, nil
  113. }
  114. res, err := entityModel.Page(req.Current, req.Size).Order("settle_account_main.CreateOn DESC").Fields("settle_account_main.*").FindAll()
  115. if err != nil {
  116. return nil, 0, err
  117. }
  118. if res.IsEmpty() {
  119. return nil, 0, nil
  120. }
  121. list := make([]accountModel.MainInfo, 0)
  122. err = res.Structs(&list)
  123. if err != nil {
  124. return nil, 0, err
  125. }
  126. var appoints []accountModel.SearchEntity
  127. appointMap := make(map[int]accountModel.SearchEntity, 0)
  128. ids := "-1"
  129. for _, item := range list {
  130. ids += fmt.Sprintf(",%v", item.AppointId)
  131. }
  132. res, err = s.Dao.DB.Model("appointment").Where(fmt.Sprintf("Id IN (%v)", ids)).FindAll()
  133. if err != nil {
  134. return nil, 0, err
  135. }
  136. err = res.Structs(&appoints)
  137. if err != nil {
  138. if err == sql.ErrNoRows {
  139. return list, total, nil
  140. }
  141. return list, total, err
  142. }
  143. for _, item := range appoints {
  144. appointMap[item.Id] = item
  145. }
  146. for index, item := range list {
  147. if appointMap[item.AppointId].Id != 0 {
  148. list[index].SignInTime = appointMap[item.AppointId].SignInTime
  149. list[index].SignOutTime = appointMap[item.AppointId].SignOutTime
  150. list[index].AppointStatus = appointMap[item.AppointId].Status
  151. }
  152. }
  153. return list, total, nil
  154. }
  155. // 新增
  156. func (s Service) Add(req accountModel.AccountMainAddReq, user request.UserInfo) error {
  157. now := gtime.Now() // 获取当前时间
  158. var baseAccount accountModel.BaseAccount
  159. var instrument accountModel.Instrument
  160. // 更新必要信息
  161. req.Main.CreateUserId = int(user.Id)
  162. req.Main.CreateBy = user.RealName
  163. req.Main.CreateOn = now
  164. req.Main.UpdateUserId = int(user.Id)
  165. req.Main.UpdateBy = user.RealName
  166. req.Main.UpdateOn = now
  167. req.Main.ActualStartDate = nil // 默认有信息终端
  168. req.Main.ActualEndDate = nil // 默认有信息终端
  169. span := req.Main.AppointEndDate.Sub(req.Main.AppointStartDate)
  170. req.Main.FeeTime = int(math.Ceil(span.Minutes()))
  171. req.Main.ActualMachineHour = req.Main.FeeTime
  172. req.Main.Status = "0"
  173. req.Main.SettleStatus = "0"
  174. req.Main.AccountStatus = "0"
  175. // 获取账户
  176. result1, err := s.Dao.DB.Model("base_account").Where(fmt.Sprintf("MainUserId='%v'", req.Main.MainUserId)).Order("Advance ASC, Id ASC").FindOne()
  177. if err != nil {
  178. return err
  179. }
  180. err = result1.Struct(&baseAccount)
  181. if err != nil {
  182. if err == sql.ErrNoRows {
  183. return errors.New("无可用账户")
  184. }
  185. return err
  186. }
  187. // 获取设备
  188. result1, err = s.Dao.DB.Model("instrument").Where(fmt.Sprintf("Id='%v'", req.Main.InstrumentId)).FindOne()
  189. if err != nil {
  190. return err
  191. }
  192. err = result1.Struct(&instrument)
  193. if err != nil {
  194. if err == sql.ErrNoRows {
  195. return errors.New("无可用设备")
  196. }
  197. return err
  198. }
  199. if instrument.Terminal == "" { // 无信息终端时,按预约时间计算
  200. req.Main.ActualStartDate = req.Main.AppointStartDate
  201. req.Main.ActualEndDate = req.Main.AppointEndDate
  202. }
  203. tx, err := s.Dao.DB.Begin()
  204. if err != nil {
  205. return err
  206. }
  207. result, err := tx.Insert("settle_account_main", req.Main)
  208. if err != nil {
  209. tx.Rollback()
  210. return err
  211. }
  212. req.Main.TotalPrice = 0
  213. id, _ := result.LastInsertId()
  214. for index := range req.Details { // 更新必要信息
  215. req.Details[index].CreateUserId = int(user.Id)
  216. req.Details[index].CreateBy = user.RealName
  217. req.Details[index].CreateOn = now
  218. req.Details[index].UpdateUserId = int(user.Id)
  219. req.Details[index].UpdateBy = user.RealName
  220. req.Details[index].UpdateOn = now
  221. req.Details[index].Pid = int(id)
  222. if req.Details[index].PaymentType == "0" {
  223. req.Details[index].ActualMinutes = strconv.Itoa(req.Main.ActualMachineHour)
  224. req.Details[index].Minutes = strconv.Itoa(req.Main.ActualMachineHour)
  225. discount := float64(1) // 计算折扣
  226. if req.Details[index].Data5 != "" {
  227. d, _ := strconv.ParseFloat(req.Details[index].Data5, 64)
  228. discount = 1 - d/100
  229. }
  230. req.Details[index].PaymentAccount = float64(req.Main.ActualMachineHour) * req.Details[index].UnitPrice * discount / 60 // 计算实际费用
  231. }
  232. req.Main.TotalPrice += req.Details[index].PaymentAccount
  233. }
  234. baseAccount.Available -= req.Main.TotalPrice // 账户可用金额计算
  235. _, err = tx.Insert("settle_account_detail", req.Details)
  236. if err != nil {
  237. tx.Rollback()
  238. return err
  239. }
  240. _, err = tx.Save("base_account", baseAccount)
  241. if err != nil {
  242. tx.Rollback()
  243. return err
  244. }
  245. return tx.Commit()
  246. }
  247. // 确认
  248. func (s Service) Confirm(req accountModel.AccountMainConfirmReq, user request.UserInfo) error {
  249. if req.MainId == 0 {
  250. return errors.New("参数缺失")
  251. }
  252. _, err := s.Dao.M.Update(fmt.Sprintf("SettleStatus='1',VerificationUserId='%v',VerificationUser='%v',VerificationDate='%v'", user.Id, user.RealName, gtime.Now()), fmt.Sprintf("Id='%v'", req.MainId))
  253. return err
  254. }
  255. // 预约取消
  256. func (s Service) Cancel(req accountModel.AccountMainCancelReq) error {
  257. if req.AppointId == 0 {
  258. return errors.New("参数缺失")
  259. }
  260. var main accountModel.SettleAccountMain
  261. var details []accountModel.SettleAccountDetail
  262. var baseAccount accountModel.BaseAccount
  263. var rules []Param
  264. now := gtime.Now()
  265. nowStr := now.Format("Y-m-d H:i:s")
  266. per := float64(0)
  267. userNumber := 0
  268. one, err := s.Dao.M.Where(fmt.Sprintf("AppointId='%v'", req.AppointId)).FindOne()
  269. if err != nil {
  270. return err
  271. }
  272. err = one.Struct(&main)
  273. if err != nil {
  274. if err == sql.ErrNoRows {
  275. return nil
  276. }
  277. return err
  278. }
  279. if main.Id == 0 { // 该预约未生成账单
  280. return nil
  281. }
  282. all, err := s.Dao.DB.Model("settle_account_detail").Where(fmt.Sprintf("pid='%v' AND PaymentType='0'", main.Id)).FindAll()
  283. if err != nil {
  284. return err
  285. }
  286. err = all.Structs(&details)
  287. if err != nil {
  288. return err
  289. }
  290. all, err = s.Dao.DB.Model("base_param").Where("Name LIKE '违约计费规则%'").Order("Code ASC").FindAll()
  291. if err != nil {
  292. return err
  293. }
  294. err = all.Structs(&rules)
  295. if err != nil {
  296. return err
  297. }
  298. // 计算当前机器占用数量
  299. //1、上一个实验人未结束实验,未占用下一个预约开始时间,下一个实验取消预约,需要进行违约扣费
  300. //2、上一个实验人未结束实验,占用了下一个预约开始时间,下一个实验取消预约,不需要进行违约扣费
  301. //3、上一个实验人结束了实验,占用了下一个预约开始时间,下一个实验取消预约,不需要进行违约扣费
  302. //4、管理员撤销,不需要进行违约扣费
  303. userNumber, err = s.Dao.DB.Model("appointment").Where(fmt.Sprintf("RelevanceId='%v' AND ((SignInTime IS NOT NULL AND SignOutTime IS NULL AND '%v' > '%v') OR (SignOutTime > '%v'))", main.InstrumentId, nowStr, main.AppointStartDate.Format("Y-m-d H:i:s"), main.AppointStartDate.Format("Y-m-d H:i:s"))).Count()
  304. if err != nil {
  305. return err
  306. }
  307. // 获取账户
  308. result1, err := s.Dao.DB.Model("base_account").Where(fmt.Sprintf("MainUserId='%v'", main.MainUserId)).Order("Advance ASC, Id ASC").FindOne()
  309. if err != nil {
  310. return err
  311. }
  312. err = result1.Struct(&baseAccount)
  313. if err != nil {
  314. return err
  315. }
  316. var detail accountModel.SettleAccountDetail
  317. detail.PaymentType = "1"
  318. detail.PaymentAccount = 0
  319. detail.Data1 = main.AppointStartDate.Format("Y-m-d H:i:s")
  320. detail.Data2 = main.AppointEndDate.Format("Y-m-d H:i:s")
  321. detail.Data3 = now.Format("Y-m-d H:i:s") // 取消时间
  322. detail.Pid = main.Id
  323. mins := main.AppointStartDate.Sub(now).Minutes()
  324. if mins > 0 { // 正向超时,计算违约收费
  325. r := ""
  326. for _, rule := range rules {
  327. value1, _ := strconv.ParseFloat(rule.Code, 64)
  328. if mins < value1 {
  329. per, _ = strconv.ParseFloat(rule.Value, 64)
  330. per /= 100
  331. r = rule.Code + "分钟内" + rule.Value + "%"
  332. }
  333. }
  334. detail.Data4 = r // 扣费规则
  335. } else {
  336. detail.Data4 = "已开始之后取消,100%" // 扣费规则
  337. per = 1
  338. }
  339. if userNumber > 0 { // 机器被占用,机器被占用,取消不扣费
  340. detail.Data4 = "机器被占用,取消不扣费"
  341. per = 0
  342. }
  343. if req.IsAuto == "2" { // 管理员手动撤销
  344. detail.Data4 = "管理员撤销,取消不扣费"
  345. per = 0
  346. }
  347. main.ActualMachineHour = 0
  348. for _, item := range details {
  349. // 计算费用
  350. //discount := float64(1) // 计算折扣
  351. //if item.Data5 != "" {
  352. // d, _ := strconv.ParseFloat(item.Data5, 64)
  353. // discount = 1 - d / 100
  354. //}
  355. //detail.PaymentAccount += item.PaymentAccount * discount * per
  356. detail.PaymentAccount += item.PaymentAccount * 1 * per // 取消不算折扣
  357. }
  358. main.ActualStartDate = nil
  359. main.ActualEndDate = nil
  360. oldAmount := main.TotalPrice
  361. main.TotalPrice = detail.PaymentAccount
  362. diffValue := oldAmount - detail.PaymentAccount
  363. main.ActualStartDate = nil
  364. main.ActualEndDate = nil
  365. baseAccount.Available += diffValue // 账户可用金额返还
  366. tx, err := s.Dao.DB.Begin()
  367. if err != nil {
  368. return err
  369. }
  370. // 更新账单明细信息
  371. _, err = tx.Save("settle_account_main", main)
  372. if err != nil {
  373. tx.Rollback()
  374. return err
  375. }
  376. // 计费明细费用设置为0
  377. _, err = tx.Update("settle_account_detail", "PaymentAccount=0", fmt.Sprintf("pid='%v'", main.Id))
  378. if err != nil {
  379. tx.Rollback()
  380. return err
  381. }
  382. // 新增违约计费
  383. _, err = tx.Save("settle_account_detail", detail)
  384. if err != nil {
  385. tx.Rollback()
  386. return err
  387. }
  388. _, err = tx.Save("base_account", baseAccount)
  389. if err != nil {
  390. tx.Rollback()
  391. return err
  392. }
  393. return tx.Commit()
  394. }
  395. type Param struct {
  396. Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
  397. Code string `protobuf:"bytes,2,opt,name=code,proto3" json:"code,omitempty"`
  398. Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"`
  399. Value string `protobuf:"bytes,4,opt,name=value,proto3" json:"value,omitempty"`
  400. Sys string `protobuf:"bytes,5,opt,name=sys,proto3" json:"sys"`
  401. SortCode int32 `protobuf:"varint,6,opt,name=sort_code,json=sortCode,proto3" json:"sort_code"`
  402. Description string `protobuf:"bytes,7,opt,name=description,proto3" json:"description,omitempty"`
  403. CreateOn string `protobuf:"bytes,8,opt,name=create_on,json=createOn,proto3" json:"create_on,omitempty"`
  404. CreateUserId int32 `protobuf:"varint,9,opt,name=create_user_id,json=createUserId,proto3" json:"create_user_id,omitempty"`
  405. CreateBy string `protobuf:"bytes,10,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"`
  406. ModifiedOn string `protobuf:"bytes,11,opt,name=modified_on,json=modifiedOn,proto3" json:"modified_on,omitempty"`
  407. ModifiedUserId int32 `protobuf:"varint,12,opt,name=modified_user_id,json=modifiedUserId,proto3" json:"modified_user_id,omitempty"`
  408. ModifiedBy string `protobuf:"bytes,13,opt,name=modified_by,json=modifiedBy,proto3" json:"modified_by,omitempty"`
  409. }