广告平台(站长使用)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

svc_wx_data.go 21 KiB

3 months ago
2 months ago
3 months ago
1 month ago
1 month ago
3 months ago
1 month ago
3 months ago
2 months ago
3 months ago
1 month ago
3 months ago
1 month ago
1 month ago
3 months ago
1 month ago
3 months ago
1 month ago
3 months ago
1 month ago
1 month ago
3 months ago
1 month ago
3 months ago
1 month ago
3 months ago
1 month ago
3 months ago
2 months ago
3 months ago
1 month ago
2 months ago
3 months ago
1 month ago
3 months ago
1 month ago
1 month ago
3 months ago
1 month ago
3 months ago
2 months ago
3 months ago
1 month ago
3 months ago
1 month ago
3 months ago
1 month ago
3 months ago
1 month ago
3 months ago
1 month ago
3 months ago
1 month ago
1 month ago
3 months ago
1 month ago
1 month ago
3 months ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
2 months ago
1 month ago
2 months ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
2 months ago
1 month ago
2 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. package svc
  2. import (
  3. "applet/app/enum"
  4. "applet/app/md"
  5. "applet/app/utils"
  6. db "code.fnuoos.com/zhimeng/model.git/src"
  7. "code.fnuoos.com/zhimeng/model.git/src/super/implement"
  8. "code.fnuoos.com/zhimeng/model.git/src/super/model"
  9. "errors"
  10. "fmt"
  11. "github.com/shopspring/decimal"
  12. "time"
  13. )
  14. func GenerateWxAdData(req md.GenerateWxAdData) (err error, generateWxAdData model.GenerateWxAdData) {
  15. // 1、查找原始数据记录
  16. originalWxAdDataDb := implement.NewOriginalWxAdDataDb(db.Db)
  17. originalWxAdData, err := originalWxAdDataDb.GetOriginalWxAdData(req.OriginalDataId)
  18. if err != nil {
  19. return
  20. }
  21. if originalWxAdData == nil {
  22. err = errors.New("未查询到原始数据记录")
  23. return
  24. }
  25. // 2、查询对应媒体、代理的分成策略
  26. mediumDivisionStrategyDb := implement.NewMediumDivisionStrategyDb(db.Db)
  27. mediumDivisionStrategy, err := mediumDivisionStrategyDb.GetOriginalWxAdDataByMediumId(originalWxAdData.MediumId)
  28. if err != nil {
  29. return
  30. }
  31. if mediumDivisionStrategy == nil {
  32. err = errors.New("未查询到对应代理的分成策略")
  33. return
  34. }
  35. mediumDivisionStrategyWithAgentFlowDb := implement.NewMediumDivisionStrategyWithAgentFlowDb(db.Db)
  36. mediumDivisionStrategyWithAgentFlows, err := mediumDivisionStrategyWithAgentFlowDb.FindMediumDivisionStrategyWithAgentFlowByStrategyId(mediumDivisionStrategy.MediumId)
  37. if err != nil {
  38. return
  39. }
  40. // 3、计算媒体、代理收益、平台留存、佣金留存、协议分成、协议总分成
  41. publisherIncome := float64(originalWxAdData.PublisherIncome)
  42. mediaRevenue := publisherIncome * float64(mediumDivisionStrategy.MediaRevenueRate) / 100 // 媒体收益
  43. agentRevenue := publisherIncome * float64(mediumDivisionStrategy.AgentRevenueRate) / 100 // 代理收益
  44. platformRetention := publisherIncome * float64(mediumDivisionStrategy.PlatformRetentionRate) / 100 // 平台留存
  45. commissionRetention := publisherIncome * float64(mediumDivisionStrategy.CommissionRetentionRate) / 100 // 佣金留存
  46. agreementSharingTotal := (mediaRevenue + agentRevenue) / ((100 - float64(mediumDivisionStrategy.AgreementSharingRate)) / 100) // 协议总分成(倒推)
  47. agreementSharing := agreementSharingTotal - (mediaRevenue + agentRevenue) // 协议分成
  48. // 3、判断是否有调价留存
  49. var priceAdjustmentRetention int
  50. if req.NowEcpm != req.OriginalEcpm || req.NowExposureCount != req.OriginalExposureCount {
  51. tmpMediaRevenue := int(utils.StrToFloat64(req.NowEcpm) * float64(req.NowExposureCount) / 1000)
  52. priceAdjustmentRetention = int(float64(tmpMediaRevenue) - mediaRevenue)
  53. mediaRevenue = float64(tmpMediaRevenue)
  54. }
  55. // 4、计算各代理收益
  56. var extraRevenue float64
  57. var agentRevenueFlows []struct {
  58. AgentId int `json:"agent_id"`
  59. AgentRevenueRate int `json:"agent_revenue_rate"`
  60. ExtraRevenueRate int `json:"extra_revenue_rate"`
  61. AgentRevenue int `json:"agent_revenue"`
  62. ExtraRevenue int `json:"extra_revenue"`
  63. }
  64. for _, v := range *mediumDivisionStrategyWithAgentFlows {
  65. tmpAgentRevenue := agentRevenue * float64(v.AgentRevenueRate) / 100
  66. tmpExtraRevenue := commissionRetention * float64(v.ExtraRevenueRate) / 100
  67. extraRevenue += tmpExtraRevenue
  68. agentRevenueFlows = append(agentRevenueFlows, struct {
  69. AgentId int `json:"agent_id"`
  70. AgentRevenueRate int `json:"agent_revenue_rate"`
  71. ExtraRevenueRate int `json:"extra_revenue_rate"`
  72. AgentRevenue int `json:"agent_revenue"`
  73. ExtraRevenue int `json:"extra_revenue"`
  74. }{
  75. AgentId: v.AgentId,
  76. AgentRevenueRate: v.AgentRevenueRate,
  77. ExtraRevenueRate: v.ExtraRevenueRate,
  78. AgentRevenue: int(tmpAgentRevenue),
  79. ExtraRevenue: int(tmpExtraRevenue),
  80. })
  81. }
  82. // 5、插入 generate_wx_ad_data 、generate_wx_ad_data_with_agent_flow 数据
  83. session := db.Db.NewSession()
  84. defer session.Close()
  85. session.Begin()
  86. now := time.Now()
  87. generateWxAdData = model.GenerateWxAdData{
  88. MediumId: originalWxAdData.MediumId,
  89. Uuid: originalWxAdData.Uuid,
  90. AppId: originalWxAdData.AppId,
  91. PlatformAppId: originalWxAdData.PlatformAppId,
  92. OriginalDataId: originalWxAdData.Id,
  93. SlotId: originalWxAdData.SlotId,
  94. AdSlot: originalWxAdData.AdSlot,
  95. Date: originalWxAdData.Date,
  96. ReqSuccCount: originalWxAdData.ReqSuccCount,
  97. ExposureCount: req.NowExposureCount, // 现-曝光量
  98. ExposureRate: originalWxAdData.ExposureRate,
  99. ClickCount: originalWxAdData.ClickCount,
  100. ClickRate: originalWxAdData.ClickRate,
  101. Ecpm: req.NowEcpm, // 现-ecpm
  102. PlatformRetention: int(platformRetention),
  103. CommissionRetention: int(commissionRetention),
  104. PriceAdjustmentRetention: priceAdjustmentRetention,
  105. MediaRevenue: int(mediaRevenue),
  106. AgentRevenue: int(agentRevenue),
  107. ExtraRevenue: int(extraRevenue),
  108. AgreementSharing: int(agreementSharing),
  109. AgreementSharingTotal: int(agreementSharingTotal),
  110. PlatformRetentionRate: mediumDivisionStrategy.PlatformRetentionRate,
  111. CommissionRetentionRate: mediumDivisionStrategy.CommissionRetentionRate,
  112. MediaRevenueRate: mediumDivisionStrategy.MediaRevenueRate,
  113. AgentRevenueRate: mediumDivisionStrategy.AgentRevenueRate,
  114. ExtraRevenueRate: mediumDivisionStrategy.ExtraRevenueRate,
  115. AgreementSharingRate: mediumDivisionStrategy.AgreementSharingRate,
  116. IsGenerateReport: 0,
  117. CreateAt: now.Format("2006-01-02 15:04:05"),
  118. UpdateAt: now.Format("2006-01-02 15:04:05"),
  119. Platform: originalWxAdData.Platform,
  120. }
  121. generateWxAdDataDb := implement.NewGenerateWxAdDataDb(db.Db)
  122. _, err = generateWxAdDataDb.GenerateWxAdDataInsertBySession(session, &generateWxAdData)
  123. if err != nil {
  124. _ = session.Rollback()
  125. return
  126. }
  127. var generateWxAdDataWithAgentFlows []*model.GenerateWxAdDataWithAgentFlow
  128. for _, v := range agentRevenueFlows {
  129. generateWxAdDataWithAgentFlows = append(generateWxAdDataWithAgentFlows, &model.GenerateWxAdDataWithAgentFlow{
  130. Uuid: generateWxAdData.Uuid,
  131. AppId: generateWxAdData.AppId,
  132. PlatformAppId: generateWxAdData.PlatformAppId,
  133. AgentId: v.AgentId,
  134. GenerateDataId: generateWxAdData.Id,
  135. SlotId: generateWxAdData.SlotId,
  136. AdSlot: generateWxAdData.AdSlot,
  137. Date: generateWxAdData.Date,
  138. AgentRevenue: v.AgentRevenue,
  139. AgentRevenueRate: v.AgentRevenueRate,
  140. ExtraRevenue: v.ExtraRevenue,
  141. ExtraRevenueRate: v.ExtraRevenueRate,
  142. CreateAt: now.Format("2006-01-02 15:04:05"),
  143. UpdateAt: now.Format("2006-01-02 15:04:05"),
  144. })
  145. }
  146. if len(generateWxAdDataWithAgentFlows) > 0 {
  147. generateWxAdDataWithAgentFlowDb := implement.NewGenerateWxAdDataWithAgentFlowDb(db.Db)
  148. _, err = generateWxAdDataWithAgentFlowDb.BatchAddGenerateWxAdDataWithAgentFlow(session, generateWxAdDataWithAgentFlows)
  149. if err != nil {
  150. _ = session.Rollback()
  151. return
  152. }
  153. }
  154. // 6、修改 original_wx_ad_data 记录中的 is_apply(是否已应用(0:未 1:已) )
  155. originalWxAdData.IsApply = 1
  156. _, err = originalWxAdDataDb.UpdateOriginalWxAdDataBySession(session, originalWxAdData, "is_apply")
  157. if err != nil {
  158. _ = session.Rollback()
  159. return
  160. }
  161. return session.Commit(), generateWxAdData
  162. }
  163. func ClacEcpm(req md.ClacEcpmReq) (err error, ecpm string) {
  164. // 1、查找原始数据记录
  165. originalWxAdDataDb := implement.NewOriginalWxAdDataDb(db.Db)
  166. originalWxAdData, err := originalWxAdDataDb.GetOriginalWxAdData(req.GenerateDataId)
  167. if err != nil {
  168. return
  169. }
  170. if originalWxAdData == nil {
  171. err = errors.New("未查询到原始数据记录")
  172. return
  173. }
  174. // 2、查询对应媒体分成策略
  175. mediumDivisionStrategyDb := implement.NewMediumDivisionStrategyDb(db.Db)
  176. mediumDivisionStrategy, err := mediumDivisionStrategyDb.GetOriginalWxAdDataByMediumId(originalWxAdData.MediumId)
  177. if err != nil {
  178. return
  179. }
  180. if mediumDivisionStrategy == nil {
  181. err = errors.New("未查询到对应代理的分成策略")
  182. return
  183. }
  184. // 3、计算媒体、代理收益、协议总分成
  185. publisherIncome := decimal.NewFromInt(int64(originalWxAdData.PublisherIncome))
  186. mediaRevenueRate := decimal.NewFromInt(int64(mediumDivisionStrategy.MediaRevenueRate))
  187. agentRevenueRate := decimal.NewFromInt(int64(mediumDivisionStrategy.AgentRevenueRate))
  188. agreementSharingRate := decimal.NewFromInt(int64(mediumDivisionStrategy.AgreementSharingRate))
  189. exposureCount := decimal.NewFromInt(int64(originalWxAdData.ExposureCount))
  190. rateValue := decimal.NewFromInt(100)
  191. thousandRateValue := decimal.NewFromInt(1000)
  192. mediaRevenue := publisherIncome.Mul(mediaRevenueRate.Div(rateValue)) // 媒体收益
  193. agentRevenue := publisherIncome.Mul(agentRevenueRate.Div(rateValue)) // 代理收益
  194. agreementSharingTotal := mediaRevenue.Add(agentRevenue).Div(rateValue.Sub(agreementSharingRate).Div(rateValue)) // 协议总分成(倒推)
  195. fmt.Println(mediaRevenue, agentRevenue, agreementSharingRate, rateValue.Sub(agreementSharingRate), agreementSharingTotal)
  196. // 4、倒退出当前ecpm值
  197. ecpm = agreementSharingTotal.Div(exposureCount.Div(thousandRateValue)).Round(2).String()
  198. return
  199. }
  200. func SettlementWxAdData(req md.SettlementWxAdData) (err error) {
  201. // 1、查找生成数据记录
  202. generateWxAdDataDb := implement.NewGenerateWxAdDataDb(db.Db)
  203. generateWxAdData, err := generateWxAdDataDb.GetGenerateWxAdData(req.GenerateDataId)
  204. if err != nil {
  205. return
  206. }
  207. if generateWxAdData == nil {
  208. err = errors.New("未查询到生成数据记录")
  209. return
  210. }
  211. originalWxAdDataDb := implement.NewOriginalWxAdDataDb(db.Db)
  212. originalWxAdData, err := originalWxAdDataDb.GetOriginalWxAdData(generateWxAdData.OriginalDataId)
  213. if err != nil {
  214. return
  215. }
  216. if originalWxAdData == nil {
  217. err = errors.New("未查询到原始数据记录")
  218. return
  219. }
  220. // 2、查询 生成数据-代理明细 记录
  221. generateWxAdDataWithAgentFlowDb := implement.NewGenerateWxAdDataWithAgentFlowDb(db.Db)
  222. generateWxAdDataWithAgentFlow, err := generateWxAdDataWithAgentFlowDb.FindGenerateWxAdDataWithAgentFlowByStrategyId(generateWxAdData.Id)
  223. if err != nil {
  224. return
  225. }
  226. // 3、查询 媒体、代理的结算方式
  227. mediumListDb := implement.NewMediumListDb(db.Db)
  228. medium, err := mediumListDb.GetMediumList(originalWxAdData.MediumId)
  229. if err != nil {
  230. return
  231. }
  232. if medium == nil {
  233. return errors.New("媒体:" + utils.IntToStr(originalWxAdData.MediumId) + "未查询到对应记录")
  234. }
  235. var agentMap = map[int]model.AgentList{}
  236. agentListDb := implement.NewAgentListDb(db.Db)
  237. for _, v := range *generateWxAdDataWithAgentFlow {
  238. agent, err1 := agentListDb.GetAgentList(v.AgentId)
  239. if err1 != nil {
  240. return err1
  241. }
  242. if agent == nil {
  243. return errors.New("代理:" + utils.IntToStr(v.AgentId) + "未查询到对应记录")
  244. }
  245. agentMap[v.AgentId] = *agent
  246. }
  247. // 4、生成数据
  248. now := time.Now()
  249. session := db.Db.NewSession()
  250. defer session.Close()
  251. session.Begin()
  252. // 4.1 新增/更新 medium_settlement 数据
  253. mediumSettlementDb := implement.NewMediumSettlementDb(db.Db)
  254. mediumSettlement, err := mediumSettlementDb.GetMediumSettlementForAvailable(originalWxAdData.MediumId)
  255. if err != nil {
  256. return
  257. }
  258. var basicIncomeBefore, mediumSettlementState, mediumSettlementPayState int
  259. // 判断是否为预付结算类型
  260. if medium.SettlementType == enum.MediumSettlementTypeForPaymentInAdvance {
  261. mediumSettlementState = enum.MediumSettlementStateForCompleteSign
  262. mediumSettlementPayState = enum.MediumSettlementPayStateForPaymentAlready
  263. }
  264. if mediumSettlement == nil {
  265. // 新增一条数据
  266. mediumSettlement = &model.MediumSettlement{
  267. Uuid: originalWxAdData.Uuid,
  268. MediumId: originalWxAdData.MediumId,
  269. AppId: originalWxAdData.AppId,
  270. PlatformAppId: originalWxAdData.PlatformAppId,
  271. BusinessKind: 1,
  272. Kind: medium.SettlementType,
  273. BasicIncome: generateWxAdData.MediaRevenue,
  274. OtherIncome: 0,
  275. OriginalIncome: originalWxAdData.PublisherIncome,
  276. PlatformRetention: generateWxAdData.PlatformRetention,
  277. CommissionRetention: generateWxAdData.CommissionRetention,
  278. PriceAdjustmentRetention: generateWxAdData.PriceAdjustmentRetention,
  279. State: mediumSettlementState,
  280. PayState: mediumSettlementPayState,
  281. StartDate: now.Format("2006-01-02"),
  282. EndDate: "",
  283. CreateAt: now.Format("2006-01-02 15:04:05"),
  284. UpdateAt: now.Format("2006-01-02 15:04:05"),
  285. SettleFile: "",
  286. }
  287. _, err = mediumSettlementDb.MediumSettlementInsertBySession(session, mediumSettlement)
  288. if err != nil {
  289. _ = session.Rollback()
  290. return
  291. }
  292. } else {
  293. // 更新数据
  294. if medium.SettlementType != mediumSettlement.Kind {
  295. // TODO::前后结算类型不一致,之前结算单状态自动变成"核算中"
  296. mediumSettlement.State = enum.MediumSettlementStateForAccountingInProgress
  297. // mediumSettlement.PayState = mediumSettlementPayState
  298. _, err = mediumSettlementDb.UpdateMediumSettlementBySession(session, mediumSettlement, "state")
  299. if err != nil {
  300. _ = session.Rollback()
  301. return
  302. }
  303. // 新增一条数据
  304. mediumSettlement = &model.MediumSettlement{
  305. Uuid: originalWxAdData.Uuid,
  306. MediumId: originalWxAdData.MediumId,
  307. AppId: originalWxAdData.AppId,
  308. PlatformAppId: originalWxAdData.PlatformAppId,
  309. BusinessKind: 1,
  310. Kind: medium.SettlementType,
  311. BasicIncome: generateWxAdData.MediaRevenue,
  312. OtherIncome: 0,
  313. OriginalIncome: originalWxAdData.PublisherIncome,
  314. PlatformRetention: generateWxAdData.PlatformRetention,
  315. CommissionRetention: generateWxAdData.CommissionRetention,
  316. PriceAdjustmentRetention: generateWxAdData.PriceAdjustmentRetention,
  317. State: mediumSettlementState,
  318. PayState: mediumSettlementPayState,
  319. StartDate: now.Format("2006-01-02"),
  320. EndDate: "",
  321. CreateAt: now.Format("2006-01-02 15:04:05"),
  322. UpdateAt: now.Format("2006-01-02 15:04:05"),
  323. SettleFile: "",
  324. }
  325. _, err = mediumSettlementDb.MediumSettlementInsertBySession(session, mediumSettlement)
  326. if err != nil {
  327. _ = session.Rollback()
  328. return
  329. }
  330. } else {
  331. basicIncomeBefore = mediumSettlement.BasicIncome
  332. mediumSettlement.BasicIncome += generateWxAdData.MediaRevenue
  333. mediumSettlement.OriginalIncome += originalWxAdData.PublisherIncome
  334. mediumSettlement.PlatformRetention += generateWxAdData.PlatformRetention
  335. mediumSettlement.CommissionRetention += generateWxAdData.CommissionRetention
  336. mediumSettlement.PriceAdjustmentRetention += generateWxAdData.PriceAdjustmentRetention
  337. _, err = mediumSettlementDb.UpdateMediumSettlementBySession(session, mediumSettlement, "basic_income", "original_income", "platform_retention", "commission_retention", "price_adjustment_retention")
  338. if err != nil {
  339. _ = session.Rollback()
  340. return
  341. }
  342. }
  343. }
  344. if medium.SettlementType == enum.MediumSettlementTypeForPaymentInAdvance {
  345. err = DealMediumAmount(session, md.DealMediumAmount{
  346. Mid: utils.IntToStr(originalWxAdData.Uuid),
  347. Type: md.FinMediumFlowDirectionExpenditure,
  348. Kind: md.SettlementSubKindForMediumFlow,
  349. OrdId: utils.IntToStr(mediumSettlement.Id),
  350. MediumId: originalWxAdData.MediumId,
  351. Amount: float64(generateWxAdData.MediaRevenue) / 100,
  352. Memo: md.SettlementSubTitleForMediumFlow,
  353. })
  354. if err != nil {
  355. _ = session.Rollback()
  356. return
  357. }
  358. }
  359. // 4.2 新增 medium_settlement_with_flow 数据
  360. mediumSettlementWithFlowDb := implement.NewMediumSettlementWithFlowDb(db.Db)
  361. _, err = mediumSettlementWithFlowDb.MediumSettlementWithFlowInsertBySession(session, &model.MediumSettlementWithFlow{
  362. SettlementId: mediumSettlement.Id,
  363. GenerateDataId: generateWxAdData.Id,
  364. Amount: generateWxAdData.MediaRevenue,
  365. BasicIncomeBefore: basicIncomeBefore,
  366. BasicIncomeAfter: mediumSettlement.BasicIncome,
  367. OtherIncomeBefore: 0,
  368. OtherIncomeAfter: 0,
  369. Kind: enum.MediumSettlementWithFlowKindForBasicIncome,
  370. CreateAt: now.Format("2006-01-02 15:04:05"),
  371. UpdateAt: now.Format("2006-01-02 15:04:05"),
  372. })
  373. if err != nil {
  374. _ = session.Rollback()
  375. return
  376. }
  377. // 4.3 新增 agent_settlement、agent_settlement_with_flow 数据
  378. agentSettlementDb := implement.NewAgentSettlementDb(db.Db)
  379. agentSettlementWithFlowDb := implement.NewAgentSettlementWithFlowDb(db.Db)
  380. for _, v := range *generateWxAdDataWithAgentFlow {
  381. agentSettlement, err1 := agentSettlementDb.GetAgentSettlementForAvailable(v.AgentId)
  382. if err1 != nil {
  383. _ = session.Rollback()
  384. return err1
  385. }
  386. var agentBasicIncomeBefore, agentOtherIncomeBefore, agentSettlementState, agentSettlementPayState int
  387. // 判断是否为预付结算类型
  388. if agentMap[v.AgentId].SettlementType == enum.AgentSettlementTypeForPaymentInAdvance {
  389. agentSettlementState = enum.AgentSettlementStateForCompleteSign
  390. agentSettlementPayState = enum.AgentSettlementPayStateForPaymentAlready
  391. }
  392. if agentSettlement == nil {
  393. // 新增一条数据
  394. agentSettlement = &model.AgentSettlement{
  395. Uuid: v.Uuid,
  396. AgentId: v.AgentId,
  397. MediumId: originalWxAdData.MediumId,
  398. AppId: v.AppId,
  399. PlatformAppId: v.PlatformAppId,
  400. BusinessKind: 1,
  401. Kind: agentMap[v.AgentId].SettlementType,
  402. BasicIncome: v.AgentRevenue,
  403. OtherIncome: v.ExtraRevenue,
  404. State: agentSettlementState,
  405. PayState: agentSettlementPayState,
  406. StartDate: now.Format("2006-01-02"),
  407. EndDate: "",
  408. CreateAt: now.Format("2006-01-02 15:04:05"),
  409. UpdateAt: now.Format("2006-01-02 15:04:05"),
  410. }
  411. _, err = agentSettlementDb.AgentSettlementInsertBySession(session, agentSettlement)
  412. if err != nil {
  413. _ = session.Rollback()
  414. return
  415. }
  416. } else {
  417. // 更新数据
  418. if agentMap[v.AgentId].SettlementType != agentSettlement.Kind {
  419. // TODO::前后结算类型不一致,之前结算单状态自动变成"核算中"
  420. agentSettlement.State = enum.AgentSettlementStateForAccountingInProgress
  421. _, err = agentSettlementDb.UpdateAgentSettlementBySession(session, agentSettlement, "state")
  422. if err != nil {
  423. _ = session.Rollback()
  424. return
  425. }
  426. // 新增一条数据
  427. agentSettlement = &model.AgentSettlement{
  428. Uuid: v.Uuid,
  429. AgentId: v.AgentId,
  430. MediumId: originalWxAdData.MediumId,
  431. AppId: v.AppId,
  432. PlatformAppId: v.PlatformAppId,
  433. BusinessKind: 1,
  434. Kind: agentMap[v.AgentId].SettlementType,
  435. BasicIncome: v.AgentRevenue,
  436. OtherIncome: v.ExtraRevenue,
  437. State: agentSettlementState,
  438. PayState: agentSettlementPayState,
  439. StartDate: now.Format("2006-01-02"),
  440. EndDate: "",
  441. CreateAt: now.Format("2006-01-02 15:04:05"),
  442. UpdateAt: now.Format("2006-01-02 15:04:05"),
  443. }
  444. _, err = agentSettlementDb.AgentSettlementInsertBySession(session, agentSettlement)
  445. if err != nil {
  446. _ = session.Rollback()
  447. return
  448. }
  449. } else {
  450. agentBasicIncomeBefore = agentSettlement.BasicIncome
  451. agentOtherIncomeBefore = agentSettlement.OtherIncome
  452. agentSettlement.BasicIncome += v.AgentRevenue
  453. agentSettlement.OtherIncome += v.ExtraRevenue
  454. _, err = agentSettlementDb.UpdateAgentSettlementBySession(session, agentSettlement, "basic_income", "other_income")
  455. if err != nil {
  456. _ = session.Rollback()
  457. return
  458. }
  459. }
  460. }
  461. if agentMap[v.AgentId].SettlementType == enum.AgentSettlementTypeForPaymentInAdvance {
  462. err = DealAgentAmount(session, md.DealAgentAmount{
  463. Mid: utils.IntToStr(originalWxAdData.Uuid),
  464. Type: md.FinAgentFlowDirectionExpenditure,
  465. Kind: md.SettlementSubKindForAgentFlow,
  466. OrdId: utils.IntToStr(v.Id),
  467. Amount: float64(v.AgentRevenue)/100 + float64(v.ExtraRevenue)/100,
  468. Memo: md.SettlementSubTitleForMediumFlow,
  469. })
  470. if err != nil {
  471. _ = session.Rollback()
  472. return
  473. }
  474. }
  475. _, err = agentSettlementWithFlowDb.AgentSettlementWithFlowInsertBySession(session, &model.AgentSettlementWithFlow{
  476. SettlementId: mediumSettlement.Id,
  477. GenerateDataId: generateWxAdData.Id,
  478. Amount: v.AgentRevenue,
  479. BasicIncomeBefore: agentBasicIncomeBefore,
  480. BasicIncomeAfter: agentSettlement.BasicIncome,
  481. OtherIncomeBefore: agentOtherIncomeBefore,
  482. OtherIncomeAfter: agentSettlement.OtherIncome,
  483. Kind: enum.AgentSettlementWithFlowKindForBasicIncome,
  484. CreateAt: now.Format("2006-01-02 15:04:05"),
  485. UpdateAt: now.Format("2006-01-02 15:04:05"),
  486. })
  487. if err != nil {
  488. _ = session.Rollback()
  489. return
  490. }
  491. }
  492. // 4、修改 generate_wx_ad_data 记录中的 is_generate_report (是否已应用(0:未 1:已) )
  493. generateWxAdData.IsGenerateReport = 1
  494. _, err = generateWxAdDataDb.UpdateGenerateWxAdDataBySession(session, generateWxAdData, "is_generate_report")
  495. if err != nil {
  496. _ = session.Rollback()
  497. return
  498. }
  499. return session.Commit()
  500. }