finance.go 59 KB

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