finance.go 59 KB

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