finance.go 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. package db
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "youngee_m_api/consts"
  11. "youngee_m_api/model/common_model"
  12. "youngee_m_api/model/gorm_model"
  13. "youngee_m_api/model/http_model"
  14. "youngee_m_api/util"
  15. "github.com/caixw/lib.go/conv"
  16. "github.com/sirupsen/logrus"
  17. "gorm.io/gorm"
  18. )
  19. func GetWithdrawRecords(ctx context.Context, pageSize, pageNum int32, req *http_model.WithdrawalRecordsRequest, condition *common_model.WithdrawRecordsCondition) (*http_model.WithdrawalRecordsPreview, error) {
  20. db := GetReadDB(ctx)
  21. var withdrawRecords []*gorm_model.YounggeeWithdrawRecord
  22. db = db.Debug().Model(gorm_model.YounggeeWithdrawRecord{})
  23. conditionType := reflect.TypeOf(condition).Elem()
  24. conditionValue := reflect.ValueOf(condition).Elem()
  25. for i := 0; i < conditionType.NumField(); i++ {
  26. field := conditionType.Field(i)
  27. tag := field.Tag.Get("condition")
  28. value := conditionValue.FieldByName(field.Name)
  29. if tag == "submit_at" && value.Interface() != "" {
  30. db = db.Where(fmt.Sprintf("submit_at like '%s%%'", value.Interface()))
  31. }
  32. if tag == "withdraw_at" && value.Interface() != "" {
  33. db = db.Where(fmt.Sprintf("withdraw_at like '%s%%'", value.Interface()))
  34. }
  35. if !util.IsBlank(value) && tag != "submit_at" && tag != "withdraw_at" {
  36. db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
  37. }
  38. }
  39. if req.TalentName != "" {
  40. fmt.Println("TalentName:", req.TalentName)
  41. db1 := GetReadDB(ctx)
  42. var talentId string
  43. db1.Model(gorm_model.YoungeeTalentInfo{}).Select("id").Where(fmt.Sprintf("talent_wx_nickname like '%%%s%%'", req.TalentName)).Find(&talentId)
  44. db = db.Where("talent_id = ?", talentId)
  45. }
  46. // 查询总数
  47. var total int64
  48. if err := db.Count(&total).Error; err != nil {
  49. logrus.WithContext(ctx).Errorf("[GetWithdrawRecords] error query mysql total, err:%+v", err)
  50. return nil, err
  51. }
  52. // 查询该页数据
  53. limit := pageSize
  54. offset := pageSize * pageNum // assert pageNum start with 0
  55. err := db.Order("submit_at").Limit(int(limit)).Offset(int(offset)).Find(&withdrawRecords).Error
  56. if err != nil {
  57. logrus.WithContext(ctx).Errorf("[GetWithdrawRecords] error query mysql limit, err:%+v", err)
  58. return nil, err
  59. }
  60. var talentIds []string
  61. for _, withdrawRecord := range withdrawRecords {
  62. talentIds = append(talentIds, withdrawRecord.TalentID)
  63. }
  64. talentIdToTalentInfoMap := make(map[string]gorm_model.YoungeeTalentInfo)
  65. for _, talentId := range talentIds {
  66. db1 := GetReadDB(ctx)
  67. talentInfo := gorm_model.YoungeeTalentInfo{}
  68. db1.Model(gorm_model.YoungeeTalentInfo{}).Where("id = ?", talentId).Find(&talentInfo)
  69. talentIdToTalentInfoMap[talentId] = talentInfo
  70. }
  71. var withdrawRecordsDatas []*http_model.WithdrawalRecordsData
  72. for _, withdrawRecord := range withdrawRecords {
  73. withdrawRecordsData := new(http_model.WithdrawalRecordsData)
  74. withdrawRecordsData.WithdrawId = withdrawRecord.WithdrawID
  75. withdrawRecordsData.TalentId = withdrawRecord.TalentID
  76. withdrawRecordsData.TalentName = talentIdToTalentInfoMap[withdrawRecord.TalentID].TalentWxNickname
  77. withdrawRecordsData.WithdrawAmount = float32(withdrawRecord.WithdrawAmount)
  78. withdrawRecordsData.AmountPayable = float32(withdrawRecord.AmountPayable)
  79. withdrawRecordsData.ReceiveInfo = withdrawRecord.ReceiveInfo
  80. withdrawRecordsData.BankType = withdrawRecord.BankType
  81. withdrawRecordsData.Phone = talentIdToTalentInfoMap[withdrawRecord.TalentID].TalentPhoneNumber
  82. withdrawRecordsData.SubmitAt = conv.MustString(withdrawRecord.SubmitAt, "")[0:19]
  83. withdrawRecordsData.WithdrawAt = conv.MustString(withdrawRecord.WithdrawAt, "")[0:19]
  84. withdrawRecordsDatas = append(withdrawRecordsDatas, withdrawRecordsData)
  85. }
  86. var withdrawRecordsPreview http_model.WithdrawalRecordsPreview
  87. withdrawRecordsPreview.WithdrawalRecordsData = withdrawRecordsDatas
  88. withdrawRecordsPreview.Total = total
  89. return &withdrawRecordsPreview, nil
  90. }
  91. func GetWithdrawRecord(ctx context.Context, req *http_model.GetWithdrawalRecordRequest) (*http_model.WithdrawalRecordPreview, error) {
  92. db := GetReadDB(ctx)
  93. //fmt.Println("talentId:", req.TalentId)
  94. var withdrawRecords []*gorm_model.YounggeeWithdrawRecord
  95. db = db.Debug().Model(gorm_model.YounggeeWithdrawRecord{}).Where("talent_id = ? AND status = ?", req.TalentId, 2).Find(&withdrawRecords)
  96. var withdrawRecordsPreview http_model.WithdrawalRecordPreview
  97. var withdrawRecordsDatas []*http_model.WithdrawalRecordData
  98. for _, withdrawRecord := range withdrawRecords {
  99. withdrawRecordData := new(http_model.WithdrawalRecordData)
  100. withdrawRecordData.WithdrawAmount = float32(withdrawRecord.WithdrawAmount)
  101. withdrawRecordData.WithdrawAt = conv.MustString(withdrawRecord.WithdrawAt, "")[0:19]
  102. withdrawRecordsDatas = append(withdrawRecordsDatas, withdrawRecordData)
  103. }
  104. withdrawRecordsPreview.WithdrawalRecordData = withdrawRecordsDatas
  105. return &withdrawRecordsPreview, nil
  106. }
  107. func GetWithdrawNums(ctx context.Context) (*http_model.WithdrawNums, error) {
  108. var withdrawNums int64
  109. db := GetReadDB(ctx)
  110. err := db.Model(gorm_model.YounggeeWithdrawRecord{}).Where("status = 1").Count(&withdrawNums).Error
  111. if err != nil {
  112. return nil, err
  113. }
  114. WithdrawNums := new(http_model.WithdrawNums)
  115. WithdrawNums.WithdrawNums = int(withdrawNums)
  116. return WithdrawNums, err
  117. }
  118. func GetRechargeValue(ctx context.Context, request http_model.GetRechargeValueRequest) (*http_model.RechargeValue, error) {
  119. var rechargeValue float64
  120. db := GetReadDB(ctx)
  121. var rechargelist []gorm_model.YounggeeRechargeRecord
  122. err := db.Model(gorm_model.YounggeeRechargeRecord{}).Where("status = ?", request.Status).Find(rechargelist).Error
  123. if err != nil {
  124. return nil, err
  125. }
  126. for _, recharge := range rechargelist {
  127. rechargeValue += recharge.RechargeAmount
  128. }
  129. RechargeValue := new(http_model.RechargeValue)
  130. RechargeValue.RechargeValue = rechargeValue
  131. return RechargeValue, err
  132. }
  133. func GetInvoiceValue(ctx context.Context, request http_model.GetInvoiceValueRequest) (*http_model.InvoiceValue, error) {
  134. var invoicevalue float64
  135. db := GetReadDB(ctx)
  136. var invoicelist []gorm_model.YounggeeInvoiceRecord
  137. err := db.Model(gorm_model.YounggeeInvoiceRecord{}).Where("status = ?", request.Status).Find(invoicelist).Error
  138. if err != nil {
  139. return nil, err
  140. }
  141. for _, invoice := range invoicelist {
  142. invoicevalue += invoice.InvoiceAmount
  143. }
  144. InvoiceValue := new(http_model.InvoiceValue)
  145. InvoiceValue.InvoiceValue = invoicevalue
  146. return InvoiceValue, err
  147. }
  148. func GetSupplierWithdrawPrevalue(ctx context.Context, request http_model.GetSupplierWithdrawPrevalueRequest) (*http_model.WithdrawValue, error) {
  149. var withdrawvalue float64
  150. db := GetReadDB(ctx)
  151. var withdrawlist []gorm_model.YounggeeSupplierWithdraw
  152. // 获取所有符合条件的发票
  153. err := db.Model(gorm_model.YounggeeSupplierWithdraw{}).Where("withdraw_status =2").Find(&withdrawlist).Error
  154. if err != nil {
  155. return nil, err
  156. }
  157. for _, withdraw := range withdrawlist {
  158. withdrawvalue += withdraw.WithdrawAmount
  159. }
  160. return &http_model.WithdrawValue{
  161. withdrawvalue,
  162. }, err
  163. }
  164. func GetTalentWithdrawPrevalue(ctx context.Context, request http_model.GetTalentWithdrawPrevalueRequest) (*http_model.TalentWithdrawValue, error) {
  165. var withdrawvalue float64
  166. db := GetReadDB(ctx)
  167. var withdrawlist []gorm_model.YounggeeWithdrawRecord
  168. // 获取所有符合条件的发票
  169. err := db.Model(gorm_model.YounggeeSupplierWithdraw{}).Where("withdraw_status =1").Find(&withdrawlist).Error
  170. if err != nil {
  171. return nil, err
  172. }
  173. for _, withdraw := range withdrawlist {
  174. withdrawvalue += withdraw.WithdrawAmount
  175. }
  176. return &http_model.TalentWithdrawValue{
  177. withdrawvalue,
  178. }, err
  179. }
  180. func GetWithDrawInfo(ctx context.Context, request http_model.GetWithDrawInfoRequest) (*http_model.WithDrawInfoResponse, error) {
  181. db := GetReadDB(ctx)
  182. var withdrawinfo gorm_model.YounggeeWithdrawRecord
  183. fmt.Println(request.Withdrawid)
  184. err := db.Model(gorm_model.YounggeeWithdrawRecord{}).Where("withdraw_id = ?", request.Withdrawid).Find(&withdrawinfo).Error
  185. if err != nil {
  186. return nil, err
  187. }
  188. res := &http_model.WithDrawInfoResponse{
  189. Operator: withdrawinfo.Name,
  190. WithdrawAmount: withdrawinfo.WithdrawAmount,
  191. AmountPayable: withdrawinfo.AmountPayable,
  192. }
  193. return res, nil
  194. }
  195. func GetWithdrawValue(ctx context.Context, request http_model.GetWithdrawValueRequest) (*http_model.ALlWithdrawValue, error) {
  196. var withdrawvalue float64
  197. db := GetReadDB(ctx)
  198. var withdrawlist []gorm_model.YounggeeWithdrawRecord
  199. // 获取所有符合条件的发票
  200. err := db.Model(gorm_model.YounggeeSupplierWithdraw{}).Where("withdraw_status =2").Find(&withdrawlist).Error
  201. if err != nil {
  202. return nil, err
  203. }
  204. for _, withdraw := range withdrawlist {
  205. withdrawvalue += withdraw.WithdrawAmount
  206. }
  207. var swithdrawlist []gorm_model.YounggeeSupplierWithdraw
  208. // 获取所有符合条件的发票
  209. err = db.Model(gorm_model.YounggeeSupplierWithdraw{}).Where("withdraw_status =3").Find(&swithdrawlist).Error
  210. if err != nil {
  211. return nil, err
  212. }
  213. for _, withdraw := range withdrawlist {
  214. withdrawvalue += withdraw.WithdrawAmount
  215. }
  216. return &http_model.ALlWithdrawValue{
  217. withdrawvalue,
  218. }, err
  219. }
  220. func GetSupplierInvoiceValue(ctx context.Context, request http_model.GetSupplierInvoiceValueRequest) (*http_model.SupplierInvoiceValue, error) {
  221. var invoicevalue float64
  222. db := GetReadDB(ctx)
  223. var invoicelist []gorm_model.YounggeeSupplierInvoice
  224. // 获取所有符合条件的发票
  225. err := db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("status = ?", request.Status).Find(&invoicelist).Error
  226. if err != nil {
  227. return nil, err
  228. }
  229. // 收集所有的 TaskIDs
  230. var taskIDList []int
  231. for _, invoice := range invoicelist {
  232. TaskIDs := strings.Split(invoice.IncomeIds, ",")
  233. for _, taskId := range TaskIDs {
  234. // 将 taskId 转换为 int 并添加到 taskIDList 中
  235. if id, err := strconv.Atoi(taskId); err == nil {
  236. taskIDList = append(taskIDList, id)
  237. }
  238. }
  239. }
  240. // 批量查询所有相关的收入数据
  241. var supplierIncome []gorm_model.YounggeeSupplierIncome
  242. err = db.Model(gorm_model.YounggeeSupplierIncome{}).Where("income_id IN ?", taskIDList).Find(&supplierIncome).Error
  243. if err != nil {
  244. return &http_model.SupplierInvoiceValue{}, err
  245. }
  246. // 将查询到的 SupplierIncome 存入 map,以便快速查找
  247. incomeMap := make(map[int]gorm_model.YounggeeSupplierIncome)
  248. for _, income := range supplierIncome {
  249. incomeMap[income.IncomeId] = income
  250. }
  251. // 根据每个发票的 IncomeIds 查找对应的收入数据,并累加 SupplierChargeActual
  252. for _, invoice := range invoicelist {
  253. TaskIDs := strings.Split(invoice.IncomeIds, ",")
  254. for _, taskId := range TaskIDs {
  255. // 将 taskId 转换为 int
  256. if id, err := strconv.Atoi(taskId); err == nil {
  257. if income, exists := incomeMap[id]; exists {
  258. invoicevalue += income.SupplierChargeActual
  259. }
  260. }
  261. }
  262. }
  263. // 返回最终的发票值
  264. InvoiceValue := new(http_model.SupplierInvoiceValue)
  265. InvoiceValue.InvoiceValue = invoicevalue
  266. return InvoiceValue, nil
  267. }
  268. func GetInvoiceNums(ctx context.Context) (*http_model.InvoiceNums, error) {
  269. var invoiceNums int64
  270. db := GetReadDB(ctx)
  271. err := db.Model(gorm_model.YounggeeInvoiceRecord{}).Where("status = 1").Count(&invoiceNums).Error
  272. if err != nil {
  273. return nil, err
  274. }
  275. InvoiceNums := new(http_model.InvoiceNums)
  276. InvoiceNums.InvoiceNums = int(invoiceNums)
  277. return InvoiceNums, err
  278. }
  279. func GetRechargeNums(ctx context.Context) (*http_model.RechargeNums, error) {
  280. var rechargeNums int64
  281. db := GetReadDB(ctx)
  282. err := db.Model(gorm_model.YounggeeRechargeRecord{}).Where("status = 1").Count(&rechargeNums).Error
  283. if err != nil {
  284. return nil, err
  285. }
  286. RechargeNums := new(http_model.RechargeNums)
  287. RechargeNums.RechargeNums = rechargeNums
  288. return RechargeNums, err
  289. }
  290. func AcceptRecharge(ctx context.Context, req http_model.AcceptRechargeRequest) (*http_model.AcceptRechargeData, error) {
  291. db := GetReadDB(ctx)
  292. err := db.Model(gorm_model.YounggeeRechargeRecord{}).Where("recharge_id=?", req.Id).Updates(map[string]interface{}{"status": 2, "agree_at": time.Now()}).Error
  293. if err != nil {
  294. logrus.WithContext(ctx).Errorf("[Recharge service] call AcceptRecharge error,err:%+v", err)
  295. return nil, err
  296. }
  297. res := &http_model.AcceptRechargeData{
  298. Id: req.Id,
  299. }
  300. return res, nil
  301. }
  302. func RefuseRecharge(ctx context.Context, req http_model.RefuseRechargeRequest) (*http_model.RefuseRechargeData, error) {
  303. db := GetReadDB(ctx)
  304. err := db.Model(gorm_model.YounggeeRechargeRecord{}).Where("recharge_id=?", req.Id).Updates(map[string]interface{}{"status": 3, "refuse_at": time.Now(), "fail_reason": req.FailReason}).Error
  305. if err != nil {
  306. logrus.WithContext(ctx).Errorf("[Recharge service] call RefuseRecharge error,err:%+v", err)
  307. return nil, err
  308. }
  309. res := &http_model.RefuseRechargeData{
  310. Id: req.Id,
  311. }
  312. return res, nil
  313. }
  314. func GetRechargeInfo(ctx context.Context, req http_model.GetRechargeInfoRequest) (*http_model.RechargeInfoResponse, error) {
  315. db := GetReadDB(ctx)
  316. var rechargeinfo gorm_model.YounggeeRechargeRecord
  317. err := db.Model(gorm_model.YounggeeRechargeRecord{}).Where("recharge_id = ?", req.RechargeId).First(&rechargeinfo).Error
  318. if err != nil {
  319. logrus.WithContext(ctx).Errorf("[Recharge service] call GetRechargeInfo error,err:%+v", err)
  320. return nil, err
  321. }
  322. var operator string
  323. enterprise := gorm_model.Enterprise{}
  324. result := db.Where(gorm_model.Enterprise{EnterpriseID: rechargeinfo.EnterpriseID}).First(&enterprise)
  325. if result.Error != nil {
  326. logrus.WithContext(ctx).Errorf("[Recharge service] call Enterprise error,err:%+v", err)
  327. return nil, result.Error
  328. }
  329. if rechargeinfo.SubAccountID != 0 {
  330. subaccountinfo := gorm_model.YounggeeSubAccount{}
  331. userResult := db.Where(gorm_model.YounggeeSubAccount{SubAccountId: rechargeinfo.SubAccountID, SubAccountType: 1}).First(&subaccountinfo)
  332. if userResult.Error != nil {
  333. logrus.WithContext(ctx).Errorf("[Recharge service] call YounggeeSubAccount error,err:%+v", err)
  334. return nil, userResult.Error
  335. }
  336. operator = subaccountinfo.SubAccountName
  337. } else {
  338. operator = enterprise.BusinessName
  339. }
  340. res := &http_model.RechargeInfoResponse{
  341. RechargeAmount: rechargeinfo.RechargeAmount,
  342. Operator: operator,
  343. MainAccount: enterprise.BusinessName,
  344. }
  345. return res, nil
  346. }
  347. func GetPreRechargeList(ctx context.Context, req http_model.GetPreRechargeListRequest) (*http_model.PreRechargeListData, error) {
  348. db := GetReadDB(ctx)
  349. // 获取分页参数
  350. page := req.PageNum
  351. pageSize := req.PageSize
  352. if page < 1 {
  353. page = 1
  354. }
  355. if pageSize < 1 {
  356. pageSize = 10 // 设置默认每页记录数为 10
  357. }
  358. var prerechargelist []gorm_model.YounggeeRechargeRecord
  359. var total int64
  360. // 先查询当前页的数据,不考虑 "Others" 筛选条件
  361. err := db.Model(gorm_model.YounggeeRechargeRecord{}).
  362. Where("status = ?", req.Status).
  363. Offset((page - 1) * pageSize). // 计算偏移量
  364. Limit(pageSize). // 设置每页限制
  365. Find(&prerechargelist).Error
  366. if err != nil {
  367. return &http_model.PreRechargeListData{}, err
  368. }
  369. // 在查询到的数据上进行筛选 (比如 "Others" 筛选条件)
  370. filteredList := make([]gorm_model.YounggeeRechargeRecord, 0)
  371. for _, recharge := range prerechargelist {
  372. var operator string
  373. enterprise := gorm_model.Enterprise{}
  374. result := db.Where(gorm_model.Enterprise{EnterpriseID: recharge.EnterpriseID}).First(&enterprise)
  375. if result.Error != nil {
  376. logrus.WithContext(ctx).Errorf("[Recharge service] call Enterprise error,err:%+v", err)
  377. return nil, result.Error
  378. }
  379. if recharge.SubAccountID != 0 {
  380. subaccountinfo := gorm_model.YounggeeSubAccount{}
  381. userResult := db.Where(gorm_model.YounggeeSubAccount{SubAccountId: recharge.SubAccountID, SubAccountType: 1}).First(&subaccountinfo)
  382. if userResult.Error != nil {
  383. logrus.WithContext(ctx).Errorf("[Recharge service] call YounggeeSubAccount error,err:%+v", err)
  384. return nil, userResult.Error
  385. }
  386. operator = subaccountinfo.SubAccountName
  387. } else {
  388. operator = enterprise.BusinessName
  389. }
  390. // 进行 "Others" 筛选条件
  391. if req.Others != "" {
  392. if operator != req.Others && req.Others != recharge.RechargeID {
  393. continue
  394. }
  395. }
  396. // 满足筛选条件的记录添加到 filteredList
  397. filteredList = append(filteredList, recharge)
  398. }
  399. // 计算筛选后的总记录数
  400. total = int64(len(filteredList))
  401. // 构建返回结果
  402. rechargePointers := make([]*http_model.PreRechargeListResponse, 0, len(filteredList))
  403. for _, recharge := range filteredList {
  404. var operator string
  405. enterprise := gorm_model.Enterprise{}
  406. result := db.Where(gorm_model.Enterprise{EnterpriseID: recharge.EnterpriseID}).First(&enterprise)
  407. if result.Error != nil {
  408. logrus.WithContext(ctx).Errorf("[Recharge service] call Enterprise error,err:%+v", err)
  409. return nil, result.Error
  410. }
  411. if recharge.SubAccountID != 0 {
  412. subaccountinfo := gorm_model.YounggeeSubAccount{}
  413. userResult := db.Where(gorm_model.YounggeeSubAccount{SubAccountId: recharge.SubAccountID, SubAccountType: 1}).First(&subaccountinfo)
  414. if userResult.Error != nil {
  415. logrus.WithContext(ctx).Errorf("[Recharge service] call YounggeeSubAccount error,err:%+v", err)
  416. return nil, userResult.Error
  417. }
  418. operator = subaccountinfo.SubAccountName
  419. } else {
  420. operator = enterprise.BusinessName
  421. }
  422. // 构建返回响应数据
  423. response := &http_model.PreRechargeListResponse{
  424. ID: recharge.RechargeID,
  425. EnterPrise: enterprise.BusinessName,
  426. Operator: operator,
  427. RechargeAmount: recharge.RechargeAmount,
  428. RechargeMethod: recharge.RechargeMethod,
  429. TransferVoucherUrl: recharge.TransferVoucherUrl,
  430. Phone: recharge.Phone,
  431. CommitAt: recharge.CommitAt.Format("2006-01-02 15:04:05"),
  432. ConfirmAt: recharge.ConfirmAt.Format("2006-01-02 15:04:05"),
  433. RefuseAt: recharge.RefuseAt.Format("2006-01-02 15:04:05"),
  434. FailReason: recharge.FailReason,
  435. }
  436. rechargePointers = append(rechargePointers, response)
  437. }
  438. return &http_model.PreRechargeListData{
  439. PreRechargeListinfo: rechargePointers,
  440. Total: total, // 返回筛选后的总记录数
  441. }, nil
  442. }
  443. func GetRechargenums(db *gorm.DB, status int) (int64, error) {
  444. query := db.Model(&gorm_model.YounggeeRechargeRecord{}).Where("status = ?", status)
  445. // 计算总数
  446. var total int64
  447. if err := query.Count(&total).Error; err != nil {
  448. return 0, err
  449. }
  450. return total, nil
  451. }
  452. func GetRechargeCount(ctx context.Context) (*http_model.RechargeCountResponse, error) {
  453. db := GetReadDB(ctx)
  454. pre, _ := GetRechargenums(db, 1)
  455. ing, _ := GetRechargenums(db, 2)
  456. ed, _ := GetRechargenums(db, 3)
  457. res := &http_model.RechargeCountResponse{
  458. PreRechargeNums: pre,
  459. RechargeNums: ing,
  460. FailNums: ed,
  461. }
  462. return res, nil
  463. }
  464. func GetWithdrawnums(db *gorm.DB, status int) (int64, error) {
  465. query := db.Model(&gorm_model.YounggeeWithdrawRecord{}).Where("status = ?", status)
  466. // 计算总数
  467. var total int64
  468. if err := query.Count(&total).Error; err != nil {
  469. return 0, err
  470. }
  471. return total, nil
  472. }
  473. func GetWithdrawCount(ctx context.Context) (*http_model.WithdrawCountResponse, error) {
  474. db := GetReadDB(ctx)
  475. pre, _ := GetWithdrawnums(db, 1)
  476. ing, _ := GetWithdrawnums(db, 2)
  477. ed, _ := GetWithdrawnums(db, 3)
  478. res := &http_model.WithdrawCountResponse{
  479. PreWithdrawNums: pre,
  480. WithdrawNums: ing,
  481. FailNums: ed,
  482. }
  483. return res, nil
  484. }
  485. func GetTalentWithdrawList(ctx context.Context, req *http_model.GetTalentWithdrawListRequest) (*http_model.TalentWithdrawListData, error) {
  486. db := GetReadDB(ctx)
  487. pageSize := req.PageSize
  488. var withdrawlist []gorm_model.YounggeeWithdrawRecord
  489. var total int64
  490. // 计算总记录数
  491. query := db.Model(gorm_model.YounggeeWithdrawRecord{}).Where("status = ?", req.Status)
  492. if req.Others != "" {
  493. query = query.Where("withdraw_id LIKE ? OR Name LIKE ?", "%"+req.Others+"%", "%"+req.Others+"%")
  494. }
  495. // 添加 during 条件(时间范围筛选)
  496. if req.During != "" {
  497. // 解析 during 参数为时间
  498. startTime, err := time.Parse("2006-01-02", req.During)
  499. if err != nil {
  500. return nil, fmt.Errorf("invalid during format, expected 'YYYY-MM-DD'")
  501. }
  502. endTime := startTime.Add(24 * time.Hour).Add(-1 * time.Second) // 当天的 23:59:59
  503. // 添加时间范围条件
  504. var timeField string
  505. switch req.Status {
  506. case 1:
  507. timeField = "submit_at"
  508. case 2:
  509. timeField = "withdraw_at"
  510. case 3:
  511. timeField = "reject_at"
  512. }
  513. query = query.Where(
  514. fmt.Sprintf("%s BETWEEN ? AND ?", timeField), // 字段名安全拼接
  515. startTime,
  516. endTime,
  517. )
  518. }
  519. if err := query.Count(&total).Error; err != nil {
  520. return nil, err
  521. }
  522. // 添加分页逻辑
  523. if pageSize == 0 {
  524. pageSize = 10
  525. }
  526. pageNum := req.PageNum
  527. if pageNum == 0 {
  528. pageNum = 1
  529. }
  530. offset := (pageNum - 1) * pageSize
  531. if err := query.Offset(offset).Limit(pageSize).Find(&withdrawlist).Error; err != nil {
  532. return nil, err
  533. }
  534. withdrawPointers := make([]*http_model.TalentWithdrawListResponse, 0, len(withdrawlist))
  535. for _, withdraw := range withdrawlist {
  536. response := &http_model.TalentWithdrawListResponse{
  537. WithdrawId: withdraw.WithdrawID,
  538. TalentId: withdraw.TalentID,
  539. WithdrawAmount: withdraw.WithdrawAmount,
  540. ActualAmount: withdraw.AmountPayable,
  541. ReajectAt: withdraw.RejectAt.Format("2006-01-02 15:04:05"),
  542. SubmitAt: withdraw.SubmitAt.Format("2006-01-02 15:04:05"),
  543. WithdrawAt: withdraw.WithdrawAt.Format("2006-01-02 15:04:05"),
  544. RejectReason: withdraw.RejectReason,
  545. Name: withdraw.Name,
  546. PhoneNumber: withdraw.PhoneNum,
  547. IdcardNumber: withdraw.IdcardNum,
  548. BankNumber: withdraw.BankNum,
  549. }
  550. withdrawPointers = append(withdrawPointers, response)
  551. }
  552. return &http_model.TalentWithdrawListData{
  553. TalentwithdrawList: withdrawPointers,
  554. Total: total,
  555. }, nil
  556. }
  557. func ConfirmWithdrawal(ctx context.Context, withdrawIdsStr string) (*http_model.ConfirmWithdrawalResponse, error) {
  558. // 分割 withdrawId 列表
  559. withdrawIds := strings.Split(withdrawIdsStr, ",")
  560. res := http_model.ConfirmWithdrawalResponse{
  561. WithdrawId: withdrawIdsStr,
  562. }
  563. if len(withdrawIds) == 0 {
  564. return &res, fmt.Errorf("empty withdrawIds list")
  565. }
  566. db := GetReadDB(ctx) // 使用统一的 DB 实例
  567. // 开启事务
  568. return &res, db.Transaction(func(tx *gorm.DB) error {
  569. // 1. 批量更新提现记录状态
  570. if err := tx.Model(&gorm_model.YounggeeWithdrawRecord{}).
  571. Where("withdraw_id IN (?)", withdrawIds).
  572. Updates(map[string]interface{}{
  573. "status": 2,
  574. "withdraw_at": time.Now(),
  575. }).Error; err != nil {
  576. return fmt.Errorf("批量更新提现记录失败: %v", err)
  577. }
  578. // 2. 获取所有提现记录的 IncomeIdList(保留重复项)
  579. var withdrawRecords []gorm_model.YounggeeWithdrawRecord
  580. if err := tx.Where("withdraw_id IN (?)", withdrawIds).
  581. Find(&withdrawRecords).Error; err != nil {
  582. return fmt.Errorf("查询提现记录失败: %v", err)
  583. }
  584. // 3. 收集所有 IncomeId(包含重复项)
  585. var rawIncomeIds []string
  586. talentAmountMap := make(map[string]float64) // talentID -> 总提现金额
  587. for _, record := range withdrawRecords {
  588. // 按原始顺序保留所有 IncomeId(含重复)
  589. ids := strings.Split(record.IncomeIdList, ",")
  590. rawIncomeIds = append(rawIncomeIds, ids...)
  591. // 累加提现金额
  592. talentAmountMap[record.TalentID] += record.WithdrawAmount
  593. }
  594. // 4. 更新所有 Income 记录状态(含重复项)
  595. if len(rawIncomeIds) > 0 {
  596. if err := tx.Model(&gorm_model.YounggeeTalentIncome{}).
  597. Where("id IN (?)", rawIncomeIds).
  598. Update("withdraw_status", 1).Error; err != nil {
  599. return fmt.Errorf("更新收入状态失败: %v", err)
  600. }
  601. }
  602. // 5. 查询所有 Income 记录详情(含重复项)
  603. var incomeList []gorm_model.YounggeeTalentIncome
  604. if err := tx.Where("id IN (?)", rawIncomeIds).
  605. Find(&incomeList).Error; err != nil {
  606. return fmt.Errorf("查询收入详情失败: %v", err)
  607. }
  608. // 6. 按类型收集所有任务ID(含重复项)
  609. type TaskRef struct {
  610. Type int
  611. TaskIDs []string
  612. }
  613. var taskRefs []TaskRef
  614. for _, income := range incomeList {
  615. var taskID string
  616. switch income.Type {
  617. case 1:
  618. taskID = income.SectaskID
  619. case 2:
  620. taskID = income.TaskID
  621. case 3:
  622. taskID = income.LocalTaskId
  623. default:
  624. continue
  625. }
  626. // 允许重复的 TaskID
  627. taskRefs = append(taskRefs, TaskRef{
  628. Type: income.Type,
  629. TaskIDs: []string{taskID},
  630. })
  631. }
  632. // 7. 批量更新任务状态(允许重复更新)
  633. for _, ref := range taskRefs {
  634. var model interface{}
  635. switch ref.Type {
  636. case 1:
  637. model = &gorm_model.YounggeeSecTaskInfo{}
  638. case 2:
  639. model = &gorm_model.YoungeeTaskInfo{}
  640. case 3:
  641. model = &gorm_model.YoungeeLocalTaskInfo{}
  642. default:
  643. continue
  644. }
  645. if err := tx.Model(model).
  646. Where("task_id IN (?)", ref.TaskIDs).
  647. Update("withdraw_status", 4).Error; err != nil {
  648. return fmt.Errorf("更新任务状态失败: %v", err)
  649. }
  650. }
  651. // 8. 更新人才账户金额
  652. for talentID, amount := range talentAmountMap {
  653. if err := tx.Model(&gorm_model.YoungeeTalentInfo{}).
  654. Where("id = ?", talentID).
  655. Updates(map[string]interface{}{
  656. "withdrawing": gorm.Expr("withdrawing - ?", amount),
  657. "withdrawed": gorm.Expr("withdrawed + ?", amount),
  658. }).Error; err != nil {
  659. return fmt.Errorf("更新人才账户失败: %v", err)
  660. }
  661. }
  662. return nil
  663. })
  664. }
  665. func RefuseTalentWithdrawal(ctx context.Context, req *http_model.RefuseTalentWithdrawalRequest) error {
  666. db := GetReadDB(ctx)
  667. // 获取撤回记录
  668. var withdrwainfo gorm_model.YounggeeWithdrawRecord
  669. err := db.Debug().Model(gorm_model.YounggeeWithdrawRecord{}).
  670. Where("withdraw_id = ?", req.WithdrawId).
  671. First(&withdrwainfo).Error // 使用 First 而不是 Updates 来查询数据
  672. if err != nil {
  673. logrus.WithContext(ctx).Errorf("[finance db] Query YounggeeWithdrawRecord error, err:%+v", err)
  674. return err
  675. }
  676. // 更新 YounggeeWithdrawRecord
  677. err = db.Debug().Model(gorm_model.YounggeeWithdrawRecord{}).
  678. Where("withdraw_id = ?", req.WithdrawId).
  679. Updates(gorm_model.YounggeeWithdrawRecord{
  680. Status: 3,
  681. RejectAt: time.Now(),
  682. RejectReason: req.Reason,
  683. }).Error
  684. if err != nil {
  685. logrus.WithContext(ctx).Errorf("[finance db] Update YounggeeWithdrawRecord error, err:%+v", err)
  686. return err
  687. }
  688. // 更新 YoungeeTalentInfo
  689. err = db.Debug().Model(gorm_model.YoungeeTalentInfo{}).
  690. Where("id = ?", withdrwainfo.TalentID).
  691. Updates(map[string]interface{}{
  692. "withdrawing": gorm.Expr("withdrawing + ?", withdrwainfo.WithdrawAmount),
  693. "canwithdraw": gorm.Expr("canwithdraw - ?", withdrwainfo.WithdrawAmount),
  694. }).Error
  695. if err != nil {
  696. logrus.WithContext(ctx).Errorf("[finance db] Update YoungeeTalentInfo error, err:%+v", err)
  697. return err
  698. }
  699. return nil
  700. }
  701. func GetBankInfo(ctx context.Context, req *http_model.GetBankInfoRequest) (*http_model.BankInfo, error) {
  702. //db := GetReadDB(ctx)
  703. //if req.BankId == "" {
  704. // return nil, nil
  705. //}
  706. //var infoBank *gorm_model.InfoBank
  707. //db.Debug().Model(gorm_model.InfoBank{}).Where("id = ?", req.BankId).First(&infoBank)
  708. db1 := GetReadDB(ctx)
  709. var infoRegion *gorm_model.InfoRegion
  710. db1.Debug().Model(gorm_model.InfoRegion{}).Where("self_code = ?", conv.MustInt(req.BankOpenAddress, 0)).First(&infoRegion)
  711. provinceCode := conv.MustString(req.BankOpenAddress, "")[0:2] + "0000"
  712. var province *gorm_model.InfoRegion
  713. db1.Debug().Model(gorm_model.InfoRegion{}).Where("self_code = ?", conv.MustInt(provinceCode, 0)).First(&province)
  714. cityCode := conv.MustString(req.BankOpenAddress, "")[0:4] + "00"
  715. var city *gorm_model.InfoRegion
  716. db1.Debug().Model(gorm_model.InfoRegion{}).Where("self_code = ?", conv.MustInt(cityCode, 0)).First(&city)
  717. data := new(http_model.BankInfo)
  718. //data.BankName = infoBank.Name
  719. data.BankOpenAddress = province.RegionName + city.RegionName + infoRegion.RegionName
  720. //db.Model(gorm_model.InfoBank{}).Where("")
  721. return data, nil
  722. }
  723. // GetEnterpriseIDByBusiness 根据企业名称查找企业ID
  724. func GetEnterpriseIDByBusiness(ctx context.Context, BusinessName string) int64 {
  725. db := GetReadDB(ctx)
  726. var EnterpriseID int64
  727. db = db.Model([]gorm_model.Enterprise{}).Select("enterprise_id").Where("business_name", BusinessName).First(&EnterpriseID)
  728. return EnterpriseID
  729. }
  730. // GetEnterpriseIDByUserId 根据企业名称查找企业ID
  731. func GetEnterpriseIDByUserId(ctx context.Context, UserId int64) int64 {
  732. db := GetReadDB(ctx)
  733. var EnterpriseID int64
  734. db = db.Model([]gorm_model.Enterprise{}).Select("enterprise_id").Where("user_id", UserId).First(&EnterpriseID)
  735. return EnterpriseID
  736. }
  737. // GetUserIDByUsername 根据用户名称查UserID
  738. func GetUserIDByUsername(ctx context.Context, Username string) int64 {
  739. db := GetReadDB(ctx)
  740. var UserID int64
  741. db = db.Model([]gorm_model.YounggeeUser{}).Select("id").Where(fmt.Sprintf("username like '%%%s%%'", Username)).First(&UserID)
  742. return UserID
  743. }
  744. func GetInvoiceRecords(ctx context.Context, req *http_model.InvoiceRecordsRequest, condition *common_model.InvoiceRecordsCondition) (*http_model.InvoiceRecordsData, error) {
  745. db := GetReadDB(ctx)
  746. var invoiceRecords []*gorm_model.YounggeeInvoiceRecord
  747. db = db.Debug().Model(gorm_model.YounggeeInvoiceRecord{}).Where("status = ?", req.InvoiceStatus)
  748. conditionType := reflect.TypeOf(condition).Elem()
  749. conditionValue := reflect.ValueOf(condition).Elem()
  750. for i := 0; i < conditionType.NumField(); i++ {
  751. field := conditionType.Field(i)
  752. tag := field.Tag.Get("condition")
  753. value := conditionValue.FieldByName(field.Name)
  754. if tag == "submit_at" && value.Interface() != "" {
  755. db = db.Where(fmt.Sprintf("submit_at like '%s%%'", value.Interface()))
  756. }
  757. if tag == "billing_at" && value.Interface() != "" {
  758. db = db.Where(fmt.Sprintf("billing_at like '%s%%'", value.Interface()))
  759. }
  760. }
  761. if req.Username != "" {
  762. UserID := GetUserIDByUsername(ctx, req.Username)
  763. enterpriseId := GetEnterpriseIDByUserId(ctx, UserID)
  764. db = db.Where("enterprise_id = ?", enterpriseId)
  765. }
  766. if req.UserId != 0 {
  767. enterpriseId := GetEnterpriseIDByUserId(ctx, req.UserId)
  768. db = db.Where("enterprise_id = ?", enterpriseId)
  769. }
  770. // 查询总数
  771. var total int64
  772. if err := db.Count(&total).Error; err != nil {
  773. logrus.WithContext(ctx).Errorf("[GetInvoiceRecords] error query mysql total, err:%+v", err)
  774. return nil, err
  775. }
  776. if req.InvoiceStatus != 3 {
  777. db.Order("submit_at")
  778. } else {
  779. db.Order("billing_at desc")
  780. }
  781. // 查询该页数据
  782. limit := req.PageSize
  783. offset := req.PageSize * req.PageNum // assert pageNum start with 0
  784. err := db.Limit(int(limit)).Offset(int(offset)).Find(&invoiceRecords).Error
  785. if err != nil {
  786. logrus.WithContext(ctx).Errorf("[GetInvoiceRecords] error query mysql limit, err:%+v", err)
  787. return nil, err
  788. }
  789. enterpriseIdToUserInfoMap := make(map[string]gorm_model.Enterprise)
  790. regionAddressMap := make(map[string]string)
  791. for _, invoiceRecord := range invoiceRecords {
  792. if _, ok := enterpriseIdToUserInfoMap[invoiceRecord.EnterpriseID]; !ok {
  793. db1 := GetReadDB(ctx)
  794. enterpriseInfo := gorm_model.Enterprise{}
  795. db1.Model(gorm_model.Enterprise{}).Where("enterprise_id = ?", invoiceRecord.EnterpriseID).Find(&enterpriseInfo)
  796. enterpriseIdToUserInfoMap[invoiceRecord.EnterpriseID] = enterpriseInfo
  797. }
  798. if _, ok := regionAddressMap[invoiceRecord.EnterpriseID]; !ok {
  799. db1 := GetReadDB(ctx)
  800. var regionCode string
  801. db1.Model(gorm_model.YounggeeInvoiceAddress{}).Select("region_code").Where("enterprise_id = ?", invoiceRecord.EnterpriseID).Find(&regionCode)
  802. regionAddressMap[invoiceRecord.EnterpriseID] = GetRegion(ctx, conv.MustInt(regionCode, 0))
  803. }
  804. }
  805. var InvoiceRecords []*http_model.InvoiceRecordsPreviews
  806. for _, invoiceRecord := range invoiceRecords {
  807. InvoiceRecord := new(http_model.InvoiceRecordsPreviews)
  808. InvoiceRecord.BillingId = invoiceRecord.BillingID
  809. InvoiceRecord.InvoiceInfo = invoiceRecord.InvoiceSnap
  810. InvoiceRecord.AddressInfo = invoiceRecord.AddressSnap
  811. InvoiceRecord.InvoiceAddress = regionAddressMap[invoiceRecord.EnterpriseID]
  812. InvoiceRecord.InvoiceType = invoiceRecord.InvoiceType
  813. InvoiceRecord.Amount = invoiceRecord.InvoiceAmount
  814. InvoiceRecord.Phone = invoiceRecord.Phone
  815. InvoiceRecord.ShipmentNumber = invoiceRecord.ShipmentNumber
  816. InvoiceRecord.BusinessName = enterpriseIdToUserInfoMap[invoiceRecord.EnterpriseID].BusinessName
  817. InvoiceRecord.UserId = invoiceRecord.EnterpriseID
  818. InvoiceRecord.Username = GetUsernameByUserID(ctx, enterpriseIdToUserInfoMap[invoiceRecord.EnterpriseID].UserID)
  819. InvoiceRecord.SubmitAt = conv.MustString(invoiceRecord.SubmitAt, "")[:19]
  820. InvoiceRecord.BillingAt = conv.MustString(invoiceRecord.BillingAt, "")[:19]
  821. InvoiceRecords = append(InvoiceRecords, InvoiceRecord)
  822. }
  823. var InvoiceRecordsData http_model.InvoiceRecordsData
  824. InvoiceRecordsData.InvoiceRecordsPreviews = InvoiceRecords
  825. InvoiceRecordsData.Total = strconv.FormatInt(total, 10)
  826. return &InvoiceRecordsData, nil
  827. }
  828. func GetInvoiceList(ctx context.Context, req http_model.GetInvoiceListRequest) (*http_model.InvoiceListData, error) {
  829. db := GetReadDB(ctx)
  830. // 获取分页参数
  831. page := req.PageNum
  832. pageSize := req.PageSize
  833. if page < 1 {
  834. page = 1
  835. }
  836. if pageSize < 1 {
  837. pageSize = 10 // 设置默认每页记录数为 10
  838. }
  839. var invoicelist []gorm_model.YounggeeInvoiceRecord
  840. var total int64
  841. // 计算总记录数
  842. err := db.Model(gorm_model.YounggeeInvoiceRecord{}).Where("status = ?", req.Status).Count(&total).Error
  843. if err != nil {
  844. return &http_model.InvoiceListData{}, err
  845. }
  846. // 查询当前页的数据
  847. err = db.Model(gorm_model.YounggeeInvoiceRecord{}).
  848. Offset((page - 1) * pageSize). // 计算偏移量
  849. Limit(pageSize). // 设置每页限制
  850. Find(&invoicelist).Error
  851. if err != nil {
  852. return &http_model.InvoiceListData{}, err
  853. }
  854. invoicePointers := make([]*http_model.InvoiceListResponse, 0, len(invoicelist))
  855. for _, invoice := range invoicelist {
  856. var operator string
  857. if invoice.SubAccountID == 0 {
  858. operator = GetEnterprisenameByEnterpriseID(ctx, invoice.EnterpriseID)
  859. } else {
  860. operator = GetOperatorBySubacountID(ctx, invoice.SubAccountID)
  861. }
  862. response := &http_model.InvoiceListResponse{
  863. BillingID: invoice.BillingID,
  864. InvoiceAmount: invoice.InvoiceAmount,
  865. Operator: operator,
  866. SubmitAt: invoice.SubmitAt,
  867. AgreeAt: invoice.BillingAt,
  868. TaskNumber: GetTasknum(invoice.TaskIds),
  869. InvoiceType: invoice.InvoiceType,
  870. }
  871. invoicePointers = append(invoicePointers, response)
  872. }
  873. return &http_model.InvoiceListData{
  874. InvoiceListinfo: invoicePointers,
  875. Total: total,
  876. }, nil
  877. }
  878. func GetSupplierWithdrawList(ctx context.Context, req http_model.GetSupplierWithdrawListRequest) (*http_model.SupplierWithdrawListData, error) {
  879. db := GetReadDB(ctx)
  880. // 获取分页参数
  881. page := req.PageNum
  882. pageSize := req.PageSize
  883. if page < 1 {
  884. page = 1
  885. }
  886. if pageSize < 1 {
  887. pageSize = 10 // 设置默认每页记录数为 10
  888. }
  889. var withdrawlist []gorm_model.YounggeeSupplierWithdraw
  890. var total int64
  891. // 计算总记录数
  892. err := db.Model(gorm_model.YounggeeSupplierWithdraw{}).Where("withdraw_status = ?", req.Status).Count(&total).Error
  893. if err != nil {
  894. return &http_model.SupplierWithdrawListData{}, err
  895. }
  896. // 查询当前页的数据
  897. err = db.Model(gorm_model.YounggeeSupplierWithdraw{}).
  898. Offset((page - 1) * pageSize). // 计算偏移量
  899. Limit(pageSize). // 设置每页限制
  900. Find(&withdrawlist).Error
  901. if err != nil {
  902. return &http_model.SupplierWithdrawListData{}, err
  903. }
  904. withdrawPointers := make([]*http_model.SupplierWithdrawListResponse, 0, len(withdrawlist))
  905. for _, withdraw := range withdrawlist {
  906. var supplier gorm_model.Supplier
  907. err = db.Model(gorm_model.Supplier{}).Where("supplier_id = ?", withdraw.SupplierId).First(&supplier).Error
  908. if err != nil {
  909. return &http_model.SupplierWithdrawListData{}, err
  910. }
  911. var name string
  912. if supplier.SupplierType == 1 {
  913. name = supplier.Name
  914. } else {
  915. name = supplier.CompanyName
  916. }
  917. var InvoiceIDList []string
  918. TaskIDs := strings.Split(withdraw.InvoiceIds, ",")
  919. for _, taskId := range TaskIDs {
  920. InvoiceIDList = append(InvoiceIDList, taskId)
  921. }
  922. var invoiceIncome []gorm_model.YounggeeSupplierInvoice
  923. err = db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_id IN ?", InvoiceIDList).Find(&invoiceIncome).Error
  924. if err != nil {
  925. return &http_model.SupplierWithdrawListData{}, err
  926. }
  927. // 收集所有的 incomeIDs
  928. var incomelist []string
  929. for _, invoice := range invoiceIncome {
  930. TaskIDs := strings.Split(invoice.IncomeIds, ",")
  931. for _, taskId := range TaskIDs {
  932. incomelist = append(incomelist, taskId)
  933. }
  934. }
  935. var supplier_income []gorm_model.YounggeeSupplierIncome
  936. err = db.Model(gorm_model.YounggeeSupplierIncome{}).Where("income_id in ?", incomelist).Find(&supplier_income).Error
  937. if err != nil {
  938. return &http_model.SupplierWithdrawListData{}, err
  939. }
  940. var taskinfo []http_model.Tasklist
  941. taskinfo = make([]http_model.Tasklist, 0, len(supplier_income)) // 预分配足够的空间
  942. for _, income := range supplier_income {
  943. var info http_model.Tasklist
  944. // 根据 IncomeType 判断信息的来源
  945. switch income.IncomeType {
  946. case 1:
  947. info.Id = income.SProjectId
  948. case 3:
  949. info.Id = income.SLocalLifeId
  950. }
  951. info.Fee = income.SupplierChargeActual
  952. // 添加到任务信息列表
  953. taskinfo = append(taskinfo, info)
  954. }
  955. withdrawinfo := &http_model.Withdrawinfo{
  956. Name: withdraw.Name,
  957. IdNumber: withdraw.IdNumber,
  958. BankName: withdraw.BankName,
  959. BankNumber: withdraw.BankNumber,
  960. Phone: withdraw.Phone,
  961. }
  962. response := &http_model.SupplierWithdrawListResponse{
  963. WithDrawId: withdraw.SupplierWithdrawId,
  964. WithdrawAmount: withdraw.WithdrawAmount,
  965. ActualAmount: withdraw.AmountPayable,
  966. PhoneNumber: withdraw.Phone,
  967. SupplierName: supplier.SupplierName,
  968. Name: name,
  969. WithDrawinfo: withdrawinfo,
  970. SubmitAt: withdraw.SupplyTime,
  971. AggreeAt: withdraw.AgreeTime,
  972. ReajectAt: withdraw.RejectTime,
  973. ReajectReason: withdraw.FailReson,
  974. Taskinfo: &taskinfo,
  975. SupplierId: supplier.SupplierId,
  976. Avater: supplier.Avater,
  977. }
  978. withdrawPointers = append(withdrawPointers, response)
  979. }
  980. return &http_model.SupplierWithdrawListData{
  981. WithdrawListinfo: withdrawPointers,
  982. Total: total,
  983. }, nil
  984. }
  985. func GetSupplierInvoiceList(ctx context.Context, req http_model.GetSupplierInvoiceListRequest) (*http_model.SupplierInvoiceListData, error) {
  986. db := GetReadDB(ctx)
  987. // 获取分页参数
  988. page := req.PageNum
  989. pageSize := req.PageSize
  990. if page < 1 {
  991. page = 1
  992. }
  993. if pageSize < 1 {
  994. pageSize = 10 // 设置默认每页记录数为 10
  995. }
  996. var invoicelist []gorm_model.YounggeeSupplierInvoice
  997. var total int64
  998. // 计算总记录数
  999. err := db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_status = ?", req.Status).Count(&total).Error
  1000. if err != nil {
  1001. return &http_model.SupplierInvoiceListData{}, err
  1002. }
  1003. // 查询当前页的数据
  1004. err = db.Model(gorm_model.YounggeeSupplierInvoice{}).
  1005. Offset((page - 1) * pageSize). // 计算偏移量
  1006. Limit(pageSize). // 设置每页限制
  1007. Find(&invoicelist).Error
  1008. if err != nil {
  1009. return &http_model.SupplierInvoiceListData{}, err
  1010. }
  1011. invoicePointers := make([]*http_model.SupplierInvoiceListResponse, 0, len(invoicelist))
  1012. for _, invoice := range invoicelist {
  1013. var supplier gorm_model.Supplier
  1014. err = db.Model(gorm_model.Supplier{}).Where("supplier_id = ?", invoice.SupplierId).First(&supplier).Error
  1015. if err != nil {
  1016. return &http_model.SupplierInvoiceListData{}, err
  1017. }
  1018. var name string
  1019. if supplier.SupplierType == 1 {
  1020. name = supplier.Name
  1021. } else {
  1022. name = supplier.CompanyName
  1023. }
  1024. var TaskIDList []string
  1025. TaskIDs := strings.Split(invoice.IncomeIds, ",")
  1026. for _, taskId := range TaskIDs {
  1027. TaskIDList = append(TaskIDList, taskId)
  1028. }
  1029. var supplier_income []gorm_model.YounggeeSupplierIncome
  1030. err = db.Model(gorm_model.YounggeeSupplierIncome{}).Where("income_id in ?", TaskIDs).Find(&supplier_income).Error
  1031. if err != nil {
  1032. return &http_model.SupplierInvoiceListData{}, err
  1033. }
  1034. var taskinfo []http_model.Tasklist
  1035. taskinfo = make([]http_model.Tasklist, 0, len(supplier_income)) // 预分配足够的空间
  1036. var AllFee float64
  1037. for _, income := range supplier_income {
  1038. var info http_model.Tasklist
  1039. // 根据 IncomeType 判断信息的来源
  1040. switch income.IncomeType {
  1041. case 1:
  1042. info.Id = income.SProjectId
  1043. case 3:
  1044. info.Id = income.SLocalLifeId
  1045. }
  1046. info.Fee = income.SupplierChargeActual
  1047. AllFee += income.SupplierChargeActual
  1048. // 添加到任务信息列表
  1049. taskinfo = append(taskinfo, info)
  1050. }
  1051. response := &http_model.SupplierInvoiceListResponse{
  1052. InvoiceId: invoice.InvoiceId,
  1053. SubmitAt: invoice.UploadInvoiceTime,
  1054. AggreeAt: invoice.AgreeTime,
  1055. ReajectAt: invoice.RejectTime,
  1056. SupplierId: invoice.SupplierId,
  1057. ReajectReason: invoice.FailReason,
  1058. PhoneNumber: supplier.PhoneNumber,
  1059. Name: name,
  1060. SupplierName: supplier.SupplierName,
  1061. CompanyName: invoice.Company,
  1062. Taskinfo: &taskinfo,
  1063. InvoiceAmount: AllFee,
  1064. Avater: supplier.Avater,
  1065. InvoiceUrl: invoice.InvoiceUrl,
  1066. }
  1067. invoicePointers = append(invoicePointers, response)
  1068. }
  1069. return &http_model.SupplierInvoiceListData{
  1070. InvoiceListinfo: invoicePointers,
  1071. Total: total,
  1072. }, nil
  1073. }
  1074. func GetInvoiceInfo(ctx context.Context, request http_model.GetInvoiceInfoRequest) (*http_model.InvoiceInfoResponse, error) {
  1075. db := GetReadDB(ctx)
  1076. var invoice gorm_model.YounggeeInvoiceRecord
  1077. err := db.Model(gorm_model.YounggeeInvoiceRecord{}).Where("billing_id=?", request.BillingID).First(&invoice).Error
  1078. if err != nil {
  1079. return nil, err
  1080. }
  1081. res := &http_model.InvoiceInfoResponse{
  1082. Businessname: GetEnterprisenameByEnterpriseID(ctx, invoice.EnterpriseID),
  1083. TaxCode: invoice.TaxCode,
  1084. RegisteredAddress: invoice.RegisteredAddress,
  1085. RegisteredPhone: invoice.RegisteredPhone,
  1086. Bank: invoice.Bank,
  1087. BankCardNumber: invoice.BankCardNumber,
  1088. InvoiceType: invoice.InvoiceType,
  1089. }
  1090. return res, nil
  1091. }
  1092. func ConfirmInvoice(ctx context.Context, request *http_model.ConfirmInvoiceRequest) error {
  1093. db := GetReadDB(ctx)
  1094. return db.Model(gorm_model.YounggeeInvoiceRecord{}).Where("billing_id = ?", request.BillingId).Updates(
  1095. gorm_model.YounggeeInvoiceRecord{
  1096. BillingAt: time.Now(),
  1097. InvoiceUrl: request.Url,
  1098. Status: 2,
  1099. }).Error
  1100. }
  1101. func SetInvoiceInfo(ctx context.Context, request *http_model.SetInvoiceInfoRequest) error {
  1102. db := GetReadDB(ctx)
  1103. invoiceInfo := gorm_model.YounggeePlatformInvoiceInfo{
  1104. EnterpriseName: request.EnterpriseName,
  1105. EnterpriseTax: request.EnterpriseTax,
  1106. Phone: request.Phone,
  1107. Address: request.Address,
  1108. BankAccount: request.BankAccount,
  1109. BankName: request.BankName,
  1110. Project: request.Project,
  1111. }
  1112. return db.Create(&invoiceInfo).Error
  1113. }
  1114. func RefuseSupplierInvoice(ctx context.Context, request *http_model.RefuseSupplierInvoiceRequest) error {
  1115. db := GetReadDB(ctx)
  1116. return db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_id = ?", request.InvoiceId).Updates(
  1117. gorm_model.YounggeeSupplierInvoice{
  1118. RejectTime: time.Now(),
  1119. InvoiceStatus: 4,
  1120. FailReason: request.Reason,
  1121. }).Error
  1122. }
  1123. func ConfirmSupplierInvoice(ctx context.Context, request *http_model.ConfirmSupplierInvoiceRequest) error {
  1124. db := GetReadDB(ctx)
  1125. return db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_id = ?", request.InvoiceId).Updates(
  1126. gorm_model.YounggeeSupplierInvoice{
  1127. AgreeTime: time.Now(),
  1128. InvoiceStatus: 3,
  1129. }).Error
  1130. }
  1131. func ConfirmWithdraw(ctx context.Context, request *http_model.ConfirmWithdrawRequest) error {
  1132. db := GetReadDB(ctx)
  1133. // 获取撤回记录
  1134. var supplierincomeinfo gorm_model.YounggeeSupplierWithdraw
  1135. err := db.Debug().Model(gorm_model.YounggeeSupplierWithdraw{}).
  1136. Where("supplier_withdraw_id = ?", request.InvoiceId).
  1137. First(&supplierincomeinfo).Error
  1138. if err != nil {
  1139. logrus.WithContext(ctx).Errorf("[finance db] Query YounggeeWithdrawRecord error, err:%+v", err)
  1140. return err
  1141. }
  1142. err = db.Model(gorm_model.YounggeeSupplierWithdraw{}).Where("supplier_withdraw_id = ?", request.InvoiceId).Updates(
  1143. gorm_model.YounggeeSupplierWithdraw{
  1144. AgreeTime: time.Now(),
  1145. WithdrawStatus: 3,
  1146. }).Error
  1147. if err != nil {
  1148. return err
  1149. }
  1150. if supplierincomeinfo.SupplierType == 2 {
  1151. var InvoiceIDList []string
  1152. InvoiceIDs := strings.Split(supplierincomeinfo.InvoiceIds, ",")
  1153. for _, taskId := range InvoiceIDs {
  1154. InvoiceIDList = append(InvoiceIDList, taskId)
  1155. }
  1156. var invoiceIncome []gorm_model.YounggeeSupplierInvoice
  1157. err = db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_id IN ?", InvoiceIDList).Find(&invoiceIncome).Error
  1158. if err != nil {
  1159. return err
  1160. }
  1161. err = db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_id in ?", InvoiceIDList).Updates(
  1162. gorm_model.YounggeeSupplierInvoice{
  1163. WithdrawStatus: 3,
  1164. }).Error
  1165. if err != nil {
  1166. return err
  1167. }
  1168. // 收集所有的 incomeIDs
  1169. var incomelist []string
  1170. for _, invoice := range invoiceIncome {
  1171. IncomeIds := strings.Split(invoice.IncomeIds, ",")
  1172. for _, IncomeId := range IncomeIds {
  1173. incomelist = append(incomelist, IncomeId)
  1174. }
  1175. }
  1176. err = db.Model(gorm_model.YounggeeSupplierIncome{}).Where("income_id in ?", incomelist).Updates(gorm_model.YounggeeSupplierIncome{WithdrawStatus: 3}).Error
  1177. if err != nil {
  1178. return err
  1179. }
  1180. } else {
  1181. incomeids := strings.Split(supplierincomeinfo.IncomeIds, ",")
  1182. err = db.Model(gorm_model.YounggeeSupplierIncome{}).Where("income_id in ?", incomeids).Updates(gorm_model.YounggeeSupplierIncome{WithdrawStatus: 3}).Error
  1183. if err != nil {
  1184. return err
  1185. }
  1186. }
  1187. return nil
  1188. }
  1189. func RefuseWithdraw(ctx context.Context, request *http_model.RefuseWithdrawRequest) error {
  1190. db := GetReadDB(ctx)
  1191. // 获取撤回记录
  1192. var supplierincomeinfo gorm_model.YounggeeSupplierWithdraw
  1193. err := db.Debug().Model(gorm_model.YounggeeSupplierWithdraw{}).
  1194. Where("supplier_withdraw_id = ?", request.InvoiceId).
  1195. First(&supplierincomeinfo).Error
  1196. if err != nil {
  1197. logrus.WithContext(ctx).Errorf("[finance db] Query YounggeeWithdrawRecord error, err:%+v", err)
  1198. return err
  1199. }
  1200. err = db.Model(gorm_model.YounggeeSupplierWithdraw{}).Where("supplier_withdraw_id = ?", request.InvoiceId).Updates(
  1201. gorm_model.YounggeeSupplierWithdraw{
  1202. RejectTime: time.Now(),
  1203. WithdrawStatus: 4,
  1204. FailReson: request.Reason,
  1205. }).Error
  1206. if err != nil {
  1207. return err
  1208. }
  1209. if supplierincomeinfo.SupplierType == 2 {
  1210. var InvoiceIDList []string
  1211. InvoiceIDs := strings.Split(supplierincomeinfo.InvoiceIds, ",")
  1212. for _, taskId := range InvoiceIDs {
  1213. InvoiceIDList = append(InvoiceIDList, taskId)
  1214. }
  1215. var invoiceIncome []gorm_model.YounggeeSupplierInvoice
  1216. err = db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_id IN ?", InvoiceIDList).Find(&invoiceIncome).Error
  1217. if err != nil {
  1218. return err
  1219. }
  1220. err = db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_id in ?", InvoiceIDList).Updates(
  1221. gorm_model.YounggeeSupplierInvoice{
  1222. WithdrawStatus: 1,
  1223. }).Error
  1224. if err != nil {
  1225. return err
  1226. }
  1227. // 收集所有的 incomeIDs
  1228. var incomelist []string
  1229. for _, invoice := range invoiceIncome {
  1230. IncomeIds := strings.Split(invoice.IncomeIds, ",")
  1231. for _, IncomeId := range IncomeIds {
  1232. incomelist = append(incomelist, IncomeId)
  1233. }
  1234. }
  1235. err = db.Model(gorm_model.YounggeeSupplierIncome{}).Where("income_id in ?", incomelist).Updates(gorm_model.YounggeeSupplierIncome{WithdrawStatus: 1}).Error
  1236. if err != nil {
  1237. return err
  1238. }
  1239. } else {
  1240. incomeids := strings.Split(supplierincomeinfo.IncomeIds, ",")
  1241. err = db.Model(gorm_model.YounggeeSupplierIncome{}).Where("income_id in ?", incomeids).Updates(gorm_model.YounggeeSupplierIncome{WithdrawStatus: 1}).Error
  1242. if err != nil {
  1243. return err
  1244. }
  1245. }
  1246. return nil
  1247. }
  1248. func GetTasknum(taskIds string) int {
  1249. var ids [][]string // 修改为二维字符串切片
  1250. if err := json.Unmarshal([]byte(taskIds), &ids); err != nil {
  1251. return 0
  1252. }
  1253. count := 0
  1254. for _, pair := range ids {
  1255. count += len(pair)
  1256. }
  1257. return count
  1258. }
  1259. func GetOperatorBySubacountID(ctx context.Context, SubaccountID int) (username string) {
  1260. db := GetReadDB(ctx)
  1261. db = db.Model([]gorm_model.YounggeeSubAccount{}).Select("sub_account_name").Where("sub_account_id = ?", SubaccountID).First(&username)
  1262. return username
  1263. }
  1264. func GetEnterprisenameByEnterpriseID(ctx context.Context, EnterpriseID string) (username string) {
  1265. db := GetReadDB(ctx)
  1266. db = db.Model([]gorm_model.Enterprise{}).Select("business_name").Where("enterprise_id = ?", EnterpriseID).First(&username)
  1267. return username
  1268. }
  1269. func GetUsernameByUserID(ctx context.Context, UserID int64) (username string) {
  1270. db := GetReadDB(ctx)
  1271. db = db.Model([]gorm_model.YounggeeUser{}).Select("username").Where("id", UserID).First(&username)
  1272. return username
  1273. }
  1274. func GetRechargeRecords(ctx context.Context, req *http_model.GetRechargeRecordsRequest, condition *common_model.RechargeRecordsCondition) (*http_model.RechargeRecordsData, error) {
  1275. db := GetReadDB(ctx)
  1276. var rechargeRecords []*gorm_model.YounggeeRechargeRecord
  1277. db = db.Debug().Model(gorm_model.YounggeeRechargeRecord{}).Where("status = ?", req.Status)
  1278. conditionType := reflect.TypeOf(condition).Elem()
  1279. conditionValue := reflect.ValueOf(condition).Elem()
  1280. for i := 0; i < conditionType.NumField(); i++ {
  1281. field := conditionType.Field(i)
  1282. tag := field.Tag.Get("condition")
  1283. value := conditionValue.FieldByName(field.Name)
  1284. if tag == "commit_at" && value.Interface() != "" {
  1285. db = db.Where(fmt.Sprintf("commit_at like '%s%%'", value.Interface()))
  1286. }
  1287. if tag == "confirm_at" && value.Interface() != "" {
  1288. db = db.Where(fmt.Sprintf("confirm_at like '%s%%'", value.Interface()))
  1289. }
  1290. }
  1291. if req.Username != "" {
  1292. UserID := GetUserIDByUsername(ctx, req.Username)
  1293. enterpriseId := GetEnterpriseIDByUserId(ctx, UserID)
  1294. db = db.Where("enterprise_id = ?", enterpriseId)
  1295. }
  1296. if req.UserId != 0 {
  1297. enterpriseId := GetEnterpriseIDByUserId(ctx, req.UserId)
  1298. db = db.Where("enterprise_id = ?", enterpriseId)
  1299. }
  1300. if req.RechargeMethod == 1 {
  1301. db = db.Where("recharge_method = ?", 1)
  1302. } else if req.RechargeMethod == 2 {
  1303. db = db.Where("recharge_method = ?", 2)
  1304. } else if req.RechargeMethod == 3 {
  1305. db = db.Where("recharge_method = ?", 3)
  1306. }
  1307. // 查询总数
  1308. var total int64
  1309. if err := db.Count(&total).Error; err != nil {
  1310. logrus.WithContext(ctx).Errorf("[GetRechargeRecords] error query mysql total, err:%+v", err)
  1311. return nil, err
  1312. }
  1313. if req.Status == 1 {
  1314. db = db.Order("commit_at")
  1315. } else {
  1316. db = db.Order("confirm_at desc")
  1317. }
  1318. // 查询该页数据
  1319. limit := req.PageSize
  1320. offset := req.PageSize * req.PageNum // assert pageNum start with 0
  1321. err := db.Limit(int(limit)).Offset(int(offset)).Find(&rechargeRecords).Error
  1322. if err != nil {
  1323. logrus.WithContext(ctx).Errorf("[GetRechargeRecords] error query mysql limit, err:%+v", err)
  1324. return nil, err
  1325. }
  1326. var enterpriseIds []string
  1327. for _, rechargeRecord := range rechargeRecords {
  1328. enterpriseIds = append(enterpriseIds, rechargeRecord.EnterpriseID)
  1329. }
  1330. util.RemoveStrRepByMap(enterpriseIds)
  1331. enterpriseIdToUserInfoMap := make(map[string]gorm_model.Enterprise)
  1332. db1 := GetReadDB(ctx)
  1333. for _, v := range enterpriseIds {
  1334. enterpriseInfo := gorm_model.Enterprise{}
  1335. db1.Model(gorm_model.Enterprise{}).Where("enterprise_id = ?", v).Find(&enterpriseInfo)
  1336. enterpriseIdToUserInfoMap[v] = enterpriseInfo
  1337. }
  1338. var RechargeRecords []*http_model.RechargeRecordsPreview
  1339. for _, rechargeRecord := range rechargeRecords {
  1340. RechargeRecord := new(http_model.RechargeRecordsPreview)
  1341. RechargeRecord.RechargeId = rechargeRecord.RechargeID
  1342. RechargeRecord.EnterpriseID = rechargeRecord.EnterpriseID
  1343. RechargeRecord.RechargeAmount = rechargeRecord.RechargeAmount
  1344. RechargeRecord.ConfirmAt = conv.MustString(rechargeRecord.ConfirmAt, "")[:19]
  1345. RechargeRecord.CommitAt = conv.MustString(rechargeRecord.CommitAt, "")[:19]
  1346. RechargeRecord.Phone = rechargeRecord.Phone
  1347. RechargeRecord.TransferVoucher = rechargeRecord.TransferVoucherUrl
  1348. RechargeRecord.RechargeMethod = consts.GetRechargeMethod(rechargeRecord.RechargeMethod)
  1349. RechargeRecord.UserId = rechargeRecord.EnterpriseID
  1350. RechargeRecord.Username = GetUsernameByUserID(ctx, enterpriseIdToUserInfoMap[rechargeRecord.EnterpriseID].UserID)
  1351. RechargeRecord.BusinessName = enterpriseIdToUserInfoMap[rechargeRecord.EnterpriseID].BusinessName
  1352. RechargeRecords = append(RechargeRecords, RechargeRecord)
  1353. }
  1354. var RechargeRecordsData http_model.RechargeRecordsData
  1355. RechargeRecordsData.RechargeRecordsPreview = RechargeRecords
  1356. RechargeRecordsData.Total = conv.MustString(total, "")
  1357. return &RechargeRecordsData, nil
  1358. }
  1359. func OperateRecharge(ctx context.Context, req *http_model.OperateRechargeRequest) error {
  1360. db := GetReadDB(ctx)
  1361. db1 := GetReadDB(ctx)
  1362. err := db1.Model(gorm_model.Enterprise{}).Where("enterprise_id = ?", req.EnterpriseId).Updates(map[string]interface{}{
  1363. "balance": gorm.Expr("balance + ?", req.RechargeAmount),
  1364. "available_balance": gorm.Expr("available_balance + ?", req.RechargeAmount)}).Error
  1365. if err != nil {
  1366. logrus.WithContext(ctx).Errorf("[OperateRecharge] error Updates balance, err:%+v", err)
  1367. return err
  1368. }
  1369. err1 := db.Model(gorm_model.YounggeeRechargeRecord{}).Where("recharge_id = ?", req.RechargeId).Updates(gorm_model.YounggeeRechargeRecord{
  1370. Status: 2,
  1371. InvoiceStatus: 2,
  1372. ConfirmAt: time.Now(),
  1373. }).Error
  1374. if err1 != nil {
  1375. logrus.WithContext(ctx).Errorf("[OperateRecharge] error Updates Status, err:%+v", err)
  1376. return err1
  1377. }
  1378. if req.Method == 1 {
  1379. db2 := GetReadDB(ctx)
  1380. db2.Model(gorm_model.YounggeeRechargeRecord{}).Where("recharge_id = ?", req.RechargeId).Updates(gorm_model.YounggeeRechargeRecord{
  1381. RechargeAmount: req.RechargeAmount,
  1382. })
  1383. }
  1384. return nil
  1385. }
  1386. func GetBillTaskList(ctx context.Context, req http_model.GetBillTaskListRequest) (*http_model.BillTaskData, error) {
  1387. db := GetReadDB(ctx)
  1388. // 获取分页参数
  1389. page := req.PageNum
  1390. pageSize := req.PageSize
  1391. if page < 1 {
  1392. page = 1
  1393. }
  1394. if pageSize < 1 {
  1395. pageSize = 10 // 设置默认每页记录数为 10
  1396. }
  1397. var invoice gorm_model.YounggeeInvoiceRecord
  1398. err := db.Model(gorm_model.YounggeeInvoiceRecord{}).Where("billing_id = ?", req.BillingID).First(&invoice).Error
  1399. if err != nil {
  1400. return nil, err
  1401. }
  1402. var ids [][]string // 二维切片用于存储二元组
  1403. if err = json.Unmarshal([]byte(invoice.TaskIds), &ids); err != nil {
  1404. return nil, err // 返回错误信息
  1405. }
  1406. var results []*http_model.BillTaskDataResponse // 用于存储合并后的结果
  1407. // 检查ID组的有效性
  1408. if len(ids) != 3 {
  1409. return nil, fmt.Errorf("task_ids must contain three groups")
  1410. }
  1411. // 第一组ID对应 selection 表
  1412. if len(ids[0]) > 0 {
  1413. var selections []gorm_model.YounggeeSelectionInfo
  1414. if err := db.Where("selection_id IN ?", ids[0]).Find(&selections).Error; err != nil {
  1415. return nil, err
  1416. }
  1417. for _, selection := range selections {
  1418. var productName string
  1419. var productPrice float64
  1420. var mainImage string
  1421. var creater string
  1422. product, err := GetProductByID(ctx, int64(selection.ProductID))
  1423. if err == nil && product != nil {
  1424. productName = product.ProductName
  1425. productPrice = product.ProductPrice
  1426. }
  1427. if selection.SubAccountId == 0 {
  1428. creater = GetEnterprisenameByEnterpriseID(ctx, selection.EnterpriseID)
  1429. } else {
  1430. creater = GetOperatorBySubacountID(ctx, selection.SubAccountId)
  1431. }
  1432. mainImage, err = GetMainPhotoByProductID(ctx, int64(selection.ProductID))
  1433. results = append(results, &http_model.BillTaskDataResponse{
  1434. TaskType: 1,
  1435. TaskForm: selection.TaskMode,
  1436. Platform: selection.Platform,
  1437. ContentType: selection.ContentType,
  1438. SettleAmount: selection.SettlementAmount,
  1439. Operator: creater,
  1440. PhotoUrl: mainImage,
  1441. Price: productPrice,
  1442. ProductName: productName,
  1443. Taskid: selection.SelectionID,
  1444. })
  1445. }
  1446. }
  1447. // 第二组ID对应 project 表
  1448. if len(ids[1]) > 0 {
  1449. var projects []gorm_model.ProjectInfo
  1450. if err := db.Where("project_id IN ?", ids[1]).Find(&projects).Error; err != nil {
  1451. return nil, err
  1452. }
  1453. for _, project := range projects {
  1454. var productName string
  1455. var productPrice float64
  1456. var mainImage string
  1457. var creater string
  1458. product, err := GetProductByID(ctx, project.ProductID)
  1459. if err == nil && product != nil {
  1460. productName = product.ProductName
  1461. productPrice = product.ProductPrice
  1462. }
  1463. if project.SubAccountID == 0 {
  1464. creater = GetEnterprisenameByEnterpriseID(ctx, project.EnterpriseID)
  1465. } else {
  1466. creater = GetOperatorBySubacountID(ctx, int(project.SubAccountID))
  1467. }
  1468. mainImage, err = GetMainPhotoByProductID(ctx, project.ProductID)
  1469. results = append(results, &http_model.BillTaskDataResponse{
  1470. TaskType: 2,
  1471. TaskForm: int(project.ProjectForm),
  1472. ContentType: int(project.ContentType),
  1473. SettleAmount: conv.MustString(project.SettlementAmount, ""),
  1474. Operator: creater,
  1475. PhotoUrl: mainImage,
  1476. Price: productPrice,
  1477. ProductName: productName,
  1478. Taskid: project.ProjectID,
  1479. })
  1480. }
  1481. }
  1482. // 第三组ID对应 llocalife 表
  1483. if len(ids[2]) > 0 {
  1484. var localifes []gorm_model.YounggeeLocalLifeInfo
  1485. if err := db.Where("local_id IN ?", ids[2]).Find(&localifes).Error; err != nil {
  1486. return nil, err
  1487. }
  1488. for _, localife := range localifes {
  1489. var productName string
  1490. var address string
  1491. var mainImage string
  1492. var creater string
  1493. store, err := GetStoreByID(ctx, int64(localife.StoreId))
  1494. if err == nil && store != nil {
  1495. productName = store.StoreName
  1496. address = store.StoreLocation
  1497. }
  1498. if localife.SubAccountId == 0 {
  1499. creater = GetEnterprisenameByEnterpriseID(ctx, localife.EnterpriseId)
  1500. } else {
  1501. creater = GetOperatorBySubacountID(ctx, localife.SubAccountId)
  1502. }
  1503. mainImage, err = GetMainPhotoByStoreID(ctx, int64(localife.StoreId))
  1504. results = append(results, &http_model.BillTaskDataResponse{
  1505. TaskType: 3,
  1506. TaskForm: localife.TaskForm,
  1507. ContentType: localife.ContentType,
  1508. SettleAmount: conv.MustString(localife.SettlementAmount, ""),
  1509. Operator: creater,
  1510. Taskid: localife.LocalId,
  1511. ProductName: productName,
  1512. Address: address,
  1513. PhotoUrl: mainImage,
  1514. })
  1515. }
  1516. }
  1517. // 计算总数
  1518. total := len(results)
  1519. // 分页处理
  1520. start := (page - 1) * pageSize
  1521. if start >= total {
  1522. return &http_model.BillTaskData{InvoiceListinfo: nil, Total: total}, nil // 返回空结果
  1523. }
  1524. end := start + pageSize
  1525. if end > total {
  1526. end = total
  1527. }
  1528. // 返回分页后的结果
  1529. return &http_model.BillTaskData{
  1530. InvoiceListinfo: results[start:end],
  1531. Total: total,
  1532. }, nil
  1533. }
  1534. func GetMainPhotoByStoreID(ctx context.Context, storeID int64) (string, error) {
  1535. db := GetReadDB(ctx)
  1536. var productPhoto gorm_model.YounggeeProductPhoto
  1537. err := db.Where("store_id = ? AND symbol = ?", storeID, 1).First(&productPhoto).Error
  1538. if err != nil {
  1539. return "", err
  1540. }
  1541. return productPhoto.PhotoUrl, nil
  1542. }
  1543. func GetMainPhotoByProductID(ctx context.Context, productId int64) (string, error) {
  1544. db := GetReadDB(ctx)
  1545. var productPhoto gorm_model.YounggeeProductPhoto
  1546. err := db.Where("product_id = ? AND symbol = ?", productId, 1).First(&productPhoto).Error
  1547. if err != nil {
  1548. return "", err
  1549. }
  1550. return productPhoto.PhotoUrl, nil
  1551. }
  1552. func GetStoreByID(ctx context.Context, stroeid int64) (*gorm_model.YounggeeStore, error) {
  1553. db := GetReadDB(ctx)
  1554. store := &gorm_model.YounggeeStore{}
  1555. err := db.First(&store, stroeid).Error
  1556. if err != nil {
  1557. if err == gorm.ErrRecordNotFound {
  1558. return nil, nil
  1559. } else {
  1560. return nil, err
  1561. }
  1562. }
  1563. return store, nil
  1564. }