affiliate_repo.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. package repository
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "database/sql"
  6. "errors"
  7. "fmt"
  8. "strings"
  9. "time"
  10. dbent "github.com/Wei-Shaw/sub2api/ent"
  11. "github.com/Wei-Shaw/sub2api/ent/user"
  12. "github.com/Wei-Shaw/sub2api/internal/service"
  13. "github.com/lib/pq"
  14. )
  15. const (
  16. affiliateCodeLength = 12
  17. affiliateCodeMaxAttempts = 12
  18. )
  19. var affiliateCodeCharset = []byte("ABCDEFGHJKLMNPQRSTUVWXYZ23456789")
  20. const affiliateUserOverviewSQL = `
  21. SELECT ua.user_id,
  22. COALESCE(u.email, ''),
  23. COALESCE(u.username, ''),
  24. ua.aff_code,
  25. COALESCE(ua.aff_rebate_rate_percent, 0)::double precision,
  26. (ua.aff_rebate_rate_percent IS NOT NULL) AS has_custom_rate,
  27. ua.aff_count,
  28. COALESCE(rebated.rebated_invitee_count, 0),
  29. (ua.aff_quota + COALESCE(matured.matured_frozen_quota, 0))::double precision,
  30. ua.aff_history_quota::double precision
  31. FROM user_affiliates ua
  32. JOIN users u ON u.id = ua.user_id
  33. LEFT JOIN (
  34. SELECT user_id, COUNT(DISTINCT source_user_id)::integer AS rebated_invitee_count
  35. FROM user_affiliate_ledger
  36. WHERE action = 'accrue' AND source_user_id IS NOT NULL
  37. GROUP BY user_id
  38. ) rebated ON rebated.user_id = ua.user_id
  39. LEFT JOIN (
  40. SELECT user_id, COALESCE(SUM(amount), 0)::double precision AS matured_frozen_quota
  41. FROM user_affiliate_ledger
  42. WHERE action = 'accrue' AND frozen_until IS NOT NULL AND frozen_until <= NOW()
  43. GROUP BY user_id
  44. ) matured ON matured.user_id = ua.user_id
  45. WHERE ua.user_id = $1
  46. LIMIT 1`
  47. type affiliateQueryExecer interface {
  48. QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
  49. ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
  50. }
  51. type affiliateRepository struct {
  52. client *dbent.Client
  53. }
  54. func NewAffiliateRepository(client *dbent.Client, _ *sql.DB) service.AffiliateRepository {
  55. return &affiliateRepository{client: client}
  56. }
  57. func (r *affiliateRepository) EnsureUserAffiliate(ctx context.Context, userID int64) (*service.AffiliateSummary, error) {
  58. if userID <= 0 {
  59. return nil, service.ErrUserNotFound
  60. }
  61. client := clientFromContext(ctx, r.client)
  62. return ensureUserAffiliateWithClient(ctx, client, userID)
  63. }
  64. func (r *affiliateRepository) GetAffiliateByCode(ctx context.Context, code string) (*service.AffiliateSummary, error) {
  65. client := clientFromContext(ctx, r.client)
  66. return queryAffiliateByCode(ctx, client, code)
  67. }
  68. func (r *affiliateRepository) BindInviter(ctx context.Context, userID, inviterID int64) (bool, error) {
  69. var bound bool
  70. err := r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
  71. if _, err := ensureUserAffiliateWithClient(txCtx, txClient, userID); err != nil {
  72. return err
  73. }
  74. if _, err := ensureUserAffiliateWithClient(txCtx, txClient, inviterID); err != nil {
  75. return err
  76. }
  77. res, err := txClient.ExecContext(txCtx,
  78. "UPDATE user_affiliates SET inviter_id = $1, updated_at = NOW() WHERE user_id = $2 AND inviter_id IS NULL",
  79. inviterID, userID,
  80. )
  81. if err != nil {
  82. return fmt.Errorf("bind inviter: %w", err)
  83. }
  84. affected, _ := res.RowsAffected()
  85. if affected == 0 {
  86. bound = false
  87. return nil
  88. }
  89. if _, err = txClient.ExecContext(txCtx,
  90. "UPDATE user_affiliates SET aff_count = aff_count + 1, updated_at = NOW() WHERE user_id = $1",
  91. inviterID,
  92. ); err != nil {
  93. return fmt.Errorf("increment inviter aff_count: %w", err)
  94. }
  95. bound = true
  96. return nil
  97. })
  98. if err != nil {
  99. return false, err
  100. }
  101. return bound, nil
  102. }
  103. func (r *affiliateRepository) AccrueQuota(ctx context.Context, inviterID, inviteeUserID int64, amount float64, freezeHours int, sourceOrderID *int64) (bool, error) {
  104. if amount <= 0 {
  105. return false, nil
  106. }
  107. var applied bool
  108. err := r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
  109. // freezeHours > 0: add to frozen quota; == 0: add to available quota directly
  110. var updateSQL string
  111. if freezeHours > 0 {
  112. updateSQL = "UPDATE user_affiliates SET aff_frozen_quota = aff_frozen_quota + $1, aff_history_quota = aff_history_quota + $1, updated_at = NOW() WHERE user_id = $2"
  113. } else {
  114. updateSQL = "UPDATE user_affiliates SET aff_quota = aff_quota + $1, aff_history_quota = aff_history_quota + $1, updated_at = NOW() WHERE user_id = $2"
  115. }
  116. res, err := txClient.ExecContext(txCtx, updateSQL, amount, inviterID)
  117. if err != nil {
  118. return err
  119. }
  120. affected, _ := res.RowsAffected()
  121. if affected == 0 {
  122. applied = false
  123. return nil
  124. }
  125. if freezeHours > 0 {
  126. if _, err = txClient.ExecContext(txCtx, `
  127. INSERT INTO user_affiliate_ledger (user_id, action, amount, source_user_id, source_order_id, frozen_until, created_at, updated_at)
  128. VALUES ($1, 'accrue', $2, $3, $4, NOW() + make_interval(hours => $5), NOW(), NOW())`,
  129. inviterID, amount, inviteeUserID, nullableInt64Arg(sourceOrderID), freezeHours); err != nil {
  130. return fmt.Errorf("insert affiliate accrue ledger: %w", err)
  131. }
  132. } else {
  133. if _, err = txClient.ExecContext(txCtx, `
  134. INSERT INTO user_affiliate_ledger (user_id, action, amount, source_user_id, source_order_id, created_at, updated_at)
  135. VALUES ($1, 'accrue', $2, $3, $4, NOW(), NOW())`, inviterID, amount, inviteeUserID, nullableInt64Arg(sourceOrderID)); err != nil {
  136. return fmt.Errorf("insert affiliate accrue ledger: %w", err)
  137. }
  138. }
  139. applied = true
  140. return nil
  141. })
  142. if err != nil {
  143. return false, err
  144. }
  145. return applied, nil
  146. }
  147. func (r *affiliateRepository) GetAccruedRebateFromInvitee(ctx context.Context, inviterID, inviteeUserID int64) (float64, error) {
  148. client := clientFromContext(ctx, r.client)
  149. rows, err := client.QueryContext(ctx,
  150. `SELECT COALESCE(SUM(amount), 0)::double precision FROM user_affiliate_ledger WHERE user_id = $1 AND source_user_id = $2 AND action = 'accrue'`,
  151. inviterID, inviteeUserID)
  152. if err != nil {
  153. return 0, fmt.Errorf("query accrued rebate from invitee: %w", err)
  154. }
  155. defer func() { _ = rows.Close() }()
  156. var total float64
  157. if rows.Next() {
  158. if err := rows.Scan(&total); err != nil {
  159. return 0, err
  160. }
  161. }
  162. return total, rows.Close()
  163. }
  164. func (r *affiliateRepository) ThawFrozenQuota(ctx context.Context, userID int64) (float64, error) {
  165. var thawed float64
  166. err := r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
  167. var err error
  168. thawed, err = thawFrozenQuotaTx(txCtx, txClient, userID)
  169. return err
  170. })
  171. return thawed, err
  172. }
  173. // thawFrozenQuotaTx moves matured frozen quota to available quota within an existing tx.
  174. func thawFrozenQuotaTx(txCtx context.Context, txClient *dbent.Client, userID int64) (float64, error) {
  175. rows, err := txClient.QueryContext(txCtx, `
  176. WITH matured AS (
  177. UPDATE user_affiliate_ledger
  178. SET frozen_until = NULL, updated_at = NOW()
  179. WHERE user_id = $1
  180. AND frozen_until IS NOT NULL
  181. AND frozen_until <= NOW()
  182. RETURNING amount
  183. )
  184. SELECT COALESCE(SUM(amount), 0) FROM matured`, userID)
  185. if err != nil {
  186. return 0, fmt.Errorf("thaw frozen quota: %w", err)
  187. }
  188. defer func() { _ = rows.Close() }()
  189. var thawed float64
  190. if rows.Next() {
  191. if err := rows.Scan(&thawed); err != nil {
  192. return 0, err
  193. }
  194. }
  195. if err := rows.Close(); err != nil {
  196. return 0, err
  197. }
  198. if thawed <= 0 {
  199. return 0, nil
  200. }
  201. _, err = txClient.ExecContext(txCtx, `
  202. UPDATE user_affiliates
  203. SET aff_quota = aff_quota + $1,
  204. aff_frozen_quota = GREATEST(aff_frozen_quota - $1, 0),
  205. updated_at = NOW()
  206. WHERE user_id = $2`, thawed, userID)
  207. if err != nil {
  208. return 0, fmt.Errorf("move thawed quota: %w", err)
  209. }
  210. return thawed, nil
  211. }
  212. func (r *affiliateRepository) TransferQuotaToBalance(ctx context.Context, userID int64) (float64, float64, error) {
  213. var transferred float64
  214. var newBalance float64
  215. err := r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
  216. if _, err := ensureUserAffiliateWithClient(txCtx, txClient, userID); err != nil {
  217. return err
  218. }
  219. // Thaw any matured frozen quota before transfer.
  220. if _, err := thawFrozenQuotaTx(txCtx, txClient, userID); err != nil {
  221. return fmt.Errorf("thaw before transfer: %w", err)
  222. }
  223. rows, err := txClient.QueryContext(txCtx, `
  224. WITH claimed AS (
  225. SELECT aff_quota::double precision AS amount
  226. FROM user_affiliates
  227. WHERE user_id = $1
  228. AND aff_quota > 0
  229. FOR UPDATE
  230. ),
  231. cleared AS (
  232. UPDATE user_affiliates ua
  233. SET aff_quota = 0,
  234. updated_at = NOW()
  235. FROM claimed c
  236. WHERE ua.user_id = $1
  237. RETURNING c.amount
  238. )
  239. SELECT amount
  240. FROM cleared`, userID)
  241. if err != nil {
  242. return fmt.Errorf("claim affiliate quota: %w", err)
  243. }
  244. if !rows.Next() {
  245. _ = rows.Close()
  246. if err := rows.Err(); err != nil {
  247. return err
  248. }
  249. return service.ErrAffiliateQuotaEmpty
  250. }
  251. if err := rows.Scan(&transferred); err != nil {
  252. _ = rows.Close()
  253. return err
  254. }
  255. if err := rows.Close(); err != nil {
  256. return err
  257. }
  258. if transferred <= 0 {
  259. return service.ErrAffiliateQuotaEmpty
  260. }
  261. affected, err := txClient.User.Update().
  262. Where(user.IDEQ(userID)).
  263. AddBalance(transferred).
  264. AddTotalRecharged(transferred).
  265. Save(txCtx)
  266. if err != nil {
  267. return fmt.Errorf("credit user balance by affiliate quota: %w", err)
  268. }
  269. if affected == 0 {
  270. return service.ErrUserNotFound
  271. }
  272. newBalance, err = queryUserBalance(txCtx, txClient, userID)
  273. if err != nil {
  274. return err
  275. }
  276. snapshot, err := queryAffiliateTransferSnapshot(txCtx, txClient, userID)
  277. if err != nil {
  278. return err
  279. }
  280. if _, err = txClient.ExecContext(txCtx, `
  281. INSERT INTO user_affiliate_ledger (
  282. user_id,
  283. action,
  284. amount,
  285. source_user_id,
  286. balance_after,
  287. aff_quota_after,
  288. aff_frozen_quota_after,
  289. aff_history_quota_after,
  290. created_at,
  291. updated_at
  292. )
  293. VALUES ($1, 'transfer', $2, NULL, $3, $4, $5, $6, NOW(), NOW())`,
  294. userID,
  295. transferred,
  296. snapshot.BalanceAfter,
  297. snapshot.AvailableQuotaAfter,
  298. snapshot.FrozenQuotaAfter,
  299. snapshot.HistoryQuotaAfter,
  300. ); err != nil {
  301. return fmt.Errorf("insert affiliate transfer ledger: %w", err)
  302. }
  303. return nil
  304. })
  305. if err != nil {
  306. return 0, 0, err
  307. }
  308. return transferred, newBalance, nil
  309. }
  310. func (r *affiliateRepository) ListInvitees(ctx context.Context, inviterID int64, limit int) ([]service.AffiliateInvitee, error) {
  311. if limit <= 0 {
  312. limit = 100
  313. }
  314. client := clientFromContext(ctx, r.client)
  315. rows, err := client.QueryContext(ctx, `
  316. SELECT ua.user_id,
  317. COALESCE(u.email, ''),
  318. COALESCE(u.username, ''),
  319. ua.created_at,
  320. COALESCE(SUM(ual.amount), 0)::double precision AS total_rebate
  321. FROM user_affiliates ua
  322. LEFT JOIN users u ON u.id = ua.user_id
  323. LEFT JOIN user_affiliate_ledger ual
  324. ON ual.user_id = $1
  325. AND ual.source_user_id = ua.user_id
  326. AND ual.action = 'accrue'
  327. WHERE ua.inviter_id = $1
  328. GROUP BY ua.user_id, u.email, u.username, ua.created_at
  329. ORDER BY ua.created_at DESC
  330. LIMIT $2`, inviterID, limit)
  331. if err != nil {
  332. return nil, err
  333. }
  334. defer func() { _ = rows.Close() }()
  335. invitees := make([]service.AffiliateInvitee, 0)
  336. for rows.Next() {
  337. var item service.AffiliateInvitee
  338. var createdAt time.Time
  339. if err := rows.Scan(&item.UserID, &item.Email, &item.Username, &createdAt, &item.TotalRebate); err != nil {
  340. return nil, err
  341. }
  342. item.CreatedAt = &createdAt
  343. invitees = append(invitees, item)
  344. }
  345. if err := rows.Err(); err != nil {
  346. return nil, err
  347. }
  348. return invitees, nil
  349. }
  350. func (r *affiliateRepository) ListAffiliateInviteRecords(ctx context.Context, filter service.AffiliateRecordFilter) ([]service.AffiliateInviteRecord, int64, error) {
  351. client := clientFromContext(ctx, r.client)
  352. where, args := buildAffiliateRecordWhere(filter, "ua.created_at", []string{
  353. "inviter.email", "inviter.username", "invitee.email", "invitee.username",
  354. "ua.inviter_id::text", "ua.user_id::text", "inviter_aff.aff_code",
  355. })
  356. total, err := queryAffiliateRecordCount(ctx, client, `
  357. SELECT COUNT(*)
  358. FROM user_affiliates ua
  359. JOIN users invitee ON invitee.id = ua.user_id
  360. JOIN users inviter ON inviter.id = ua.inviter_id
  361. JOIN user_affiliates inviter_aff ON inviter_aff.user_id = ua.inviter_id
  362. `+where, args...)
  363. if err != nil {
  364. return nil, 0, err
  365. }
  366. orderBy := buildAffiliateRecordOrderBy(filter, map[string]string{
  367. "inviter": "inviter.email",
  368. "invitee": "invitee.email",
  369. "aff_code": "inviter_aff.aff_code",
  370. "total_rebate": "total_rebate",
  371. "created_at": "ua.created_at",
  372. }, "ua.created_at")
  373. args = append(args, filter.PageSize, (filter.Page-1)*filter.PageSize)
  374. rows, err := client.QueryContext(ctx, `
  375. SELECT ua.inviter_id,
  376. COALESCE(inviter.email, ''),
  377. COALESCE(inviter.username, ''),
  378. ua.user_id,
  379. COALESCE(invitee.email, ''),
  380. COALESCE(invitee.username, ''),
  381. COALESCE(inviter_aff.aff_code, ''),
  382. COALESCE(SUM(ual.amount), 0)::double precision AS total_rebate,
  383. ua.created_at
  384. FROM user_affiliates ua
  385. JOIN users invitee ON invitee.id = ua.user_id
  386. JOIN users inviter ON inviter.id = ua.inviter_id
  387. JOIN user_affiliates inviter_aff ON inviter_aff.user_id = ua.inviter_id
  388. LEFT JOIN user_affiliate_ledger ual
  389. ON ual.user_id = ua.inviter_id
  390. AND ual.source_user_id = ua.user_id
  391. AND ual.action = 'accrue'
  392. `+where+`
  393. GROUP BY ua.inviter_id, inviter.email, inviter.username, ua.user_id, invitee.email, invitee.username, inviter_aff.aff_code, ua.created_at
  394. `+orderBy+`
  395. LIMIT $`+fmt.Sprint(len(args)-1)+` OFFSET $`+fmt.Sprint(len(args)), args...)
  396. if err != nil {
  397. return nil, 0, err
  398. }
  399. defer func() { _ = rows.Close() }()
  400. items := make([]service.AffiliateInviteRecord, 0)
  401. for rows.Next() {
  402. var item service.AffiliateInviteRecord
  403. if err := rows.Scan(
  404. &item.InviterID,
  405. &item.InviterEmail,
  406. &item.InviterUsername,
  407. &item.InviteeID,
  408. &item.InviteeEmail,
  409. &item.InviteeUsername,
  410. &item.AffCode,
  411. &item.TotalRebate,
  412. &item.CreatedAt,
  413. ); err != nil {
  414. return nil, 0, err
  415. }
  416. items = append(items, item)
  417. }
  418. if err := rows.Err(); err != nil {
  419. return nil, 0, err
  420. }
  421. return items, total, nil
  422. }
  423. func (r *affiliateRepository) ListAffiliateRebateRecords(ctx context.Context, filter service.AffiliateRecordFilter) ([]service.AffiliateRebateRecord, int64, error) {
  424. client := clientFromContext(ctx, r.client)
  425. where, args := buildAffiliateRecordWhere(filter, "ual.created_at", []string{
  426. "inviter.email", "inviter.username", "invitee.email", "invitee.username",
  427. "po.id::text", "po.out_trade_no", "po.payment_type", "po.status",
  428. })
  429. baseJoin := `
  430. FROM user_affiliate_ledger ual
  431. JOIN payment_orders po ON po.id = ual.source_order_id
  432. JOIN users invitee ON invitee.id = ual.source_user_id
  433. JOIN users inviter ON inviter.id = ual.user_id
  434. WHERE ual.action = 'accrue'
  435. AND ual.source_order_id IS NOT NULL`
  436. if where != "" {
  437. where = strings.Replace(where, "WHERE ", " AND ", 1)
  438. }
  439. total, err := queryAffiliateRecordCount(ctx, client, "SELECT COUNT(*) "+baseJoin+where, args...)
  440. if err != nil {
  441. return nil, 0, err
  442. }
  443. orderBy := buildAffiliateRecordOrderBy(filter, map[string]string{
  444. "order": "po.id",
  445. "inviter": "inviter.email",
  446. "invitee": "invitee.email",
  447. "order_amount": "po.amount",
  448. "pay_amount": "po.pay_amount",
  449. "rebate_amount": "ual.amount",
  450. "payment_type": "po.payment_type",
  451. "order_status": "po.status",
  452. "created_at": "ual.created_at",
  453. }, "ual.created_at")
  454. args = append(args, filter.PageSize, (filter.Page-1)*filter.PageSize)
  455. rows, err := client.QueryContext(ctx, `
  456. SELECT po.id,
  457. po.out_trade_no,
  458. ual.user_id,
  459. COALESCE(inviter.email, ''),
  460. COALESCE(inviter.username, ''),
  461. ual.source_user_id,
  462. COALESCE(invitee.email, ''),
  463. COALESCE(invitee.username, ''),
  464. po.amount::double precision,
  465. po.pay_amount::double precision,
  466. ual.amount::double precision,
  467. po.payment_type,
  468. po.status,
  469. ual.created_at
  470. `+baseJoin+where+`
  471. `+orderBy+`
  472. LIMIT $`+fmt.Sprint(len(args)-1)+` OFFSET $`+fmt.Sprint(len(args)), args...)
  473. if err != nil {
  474. return nil, 0, err
  475. }
  476. defer func() { _ = rows.Close() }()
  477. items := make([]service.AffiliateRebateRecord, 0)
  478. for rows.Next() {
  479. var item service.AffiliateRebateRecord
  480. if err := rows.Scan(
  481. &item.OrderID,
  482. &item.OutTradeNo,
  483. &item.InviterID,
  484. &item.InviterEmail,
  485. &item.InviterUsername,
  486. &item.InviteeID,
  487. &item.InviteeEmail,
  488. &item.InviteeUsername,
  489. &item.OrderAmount,
  490. &item.PayAmount,
  491. &item.RebateAmount,
  492. &item.PaymentType,
  493. &item.OrderStatus,
  494. &item.CreatedAt,
  495. ); err != nil {
  496. return nil, 0, err
  497. }
  498. items = append(items, item)
  499. }
  500. if err := rows.Err(); err != nil {
  501. return nil, 0, err
  502. }
  503. return items, total, nil
  504. }
  505. func (r *affiliateRepository) ListAffiliateTransferRecords(ctx context.Context, filter service.AffiliateRecordFilter) ([]service.AffiliateTransferRecord, int64, error) {
  506. client := clientFromContext(ctx, r.client)
  507. where, args := buildAffiliateRecordWhere(filter, "ual.created_at", []string{
  508. "u.email", "u.username", "u.id::text",
  509. })
  510. baseJoin := `
  511. FROM user_affiliate_ledger ual
  512. JOIN users u ON u.id = ual.user_id
  513. WHERE ual.action = 'transfer'`
  514. if where != "" {
  515. where = strings.Replace(where, "WHERE ", " AND ", 1)
  516. }
  517. total, err := queryAffiliateRecordCount(ctx, client, "SELECT COUNT(*) "+baseJoin+where, args...)
  518. if err != nil {
  519. return nil, 0, err
  520. }
  521. orderBy := buildAffiliateRecordOrderBy(filter, map[string]string{
  522. "user": "u.email",
  523. "amount": "ual.amount",
  524. "balance_after": "ual.balance_after",
  525. "available_quota_after": "ual.aff_quota_after",
  526. "frozen_quota_after": "ual.aff_frozen_quota_after",
  527. "history_quota_after": "ual.aff_history_quota_after",
  528. "created_at": "ual.created_at",
  529. }, "ual.created_at")
  530. args = append(args, filter.PageSize, (filter.Page-1)*filter.PageSize)
  531. rows, err := client.QueryContext(ctx, `
  532. SELECT ual.id,
  533. ual.user_id,
  534. COALESCE(u.email, ''),
  535. COALESCE(u.username, ''),
  536. ual.amount::double precision,
  537. ual.balance_after::double precision,
  538. ual.aff_quota_after::double precision,
  539. ual.aff_frozen_quota_after::double precision,
  540. ual.aff_history_quota_after::double precision,
  541. ual.created_at
  542. `+baseJoin+where+`
  543. `+orderBy+`
  544. LIMIT $`+fmt.Sprint(len(args)-1)+` OFFSET $`+fmt.Sprint(len(args)), args...)
  545. if err != nil {
  546. return nil, 0, err
  547. }
  548. defer func() { _ = rows.Close() }()
  549. items := make([]service.AffiliateTransferRecord, 0)
  550. for rows.Next() {
  551. var item service.AffiliateTransferRecord
  552. var balanceAfter sql.NullFloat64
  553. var availableQuotaAfter sql.NullFloat64
  554. var frozenQuotaAfter sql.NullFloat64
  555. var historyQuotaAfter sql.NullFloat64
  556. if err := rows.Scan(
  557. &item.LedgerID,
  558. &item.UserID,
  559. &item.UserEmail,
  560. &item.Username,
  561. &item.Amount,
  562. &balanceAfter,
  563. &availableQuotaAfter,
  564. &frozenQuotaAfter,
  565. &historyQuotaAfter,
  566. &item.CreatedAt,
  567. ); err != nil {
  568. return nil, 0, err
  569. }
  570. item.BalanceAfter = nullableFloat64Ptr(balanceAfter)
  571. item.AvailableQuotaAfter = nullableFloat64Ptr(availableQuotaAfter)
  572. item.FrozenQuotaAfter = nullableFloat64Ptr(frozenQuotaAfter)
  573. item.HistoryQuotaAfter = nullableFloat64Ptr(historyQuotaAfter)
  574. item.SnapshotAvailable = balanceAfter.Valid &&
  575. availableQuotaAfter.Valid &&
  576. frozenQuotaAfter.Valid &&
  577. historyQuotaAfter.Valid
  578. items = append(items, item)
  579. }
  580. if err := rows.Err(); err != nil {
  581. return nil, 0, err
  582. }
  583. return items, total, nil
  584. }
  585. func (r *affiliateRepository) GetAffiliateUserOverview(ctx context.Context, userID int64) (*service.AffiliateUserOverview, error) {
  586. if userID <= 0 {
  587. return nil, service.ErrUserNotFound
  588. }
  589. client := clientFromContext(ctx, r.client)
  590. rows, err := client.QueryContext(ctx, affiliateUserOverviewSQL, userID)
  591. if err != nil {
  592. return nil, err
  593. }
  594. defer func() { _ = rows.Close() }()
  595. if !rows.Next() {
  596. if err := rows.Err(); err != nil {
  597. return nil, err
  598. }
  599. return nil, service.ErrUserNotFound
  600. }
  601. var overview service.AffiliateUserOverview
  602. var customRate float64
  603. var hasCustomRate bool
  604. if err := rows.Scan(
  605. &overview.UserID,
  606. &overview.Email,
  607. &overview.Username,
  608. &overview.AffCode,
  609. &customRate,
  610. &hasCustomRate,
  611. &overview.InvitedCount,
  612. &overview.RebatedInviteeCount,
  613. &overview.AvailableQuota,
  614. &overview.HistoryQuota,
  615. ); err != nil {
  616. return nil, err
  617. }
  618. if hasCustomRate {
  619. overview.RebateRatePercent = customRate
  620. overview.RebateRateCustom = true
  621. }
  622. return &overview, rows.Err()
  623. }
  624. func buildAffiliateRecordWhere(filter service.AffiliateRecordFilter, timeColumn string, searchColumns []string) (string, []any) {
  625. clauses := make([]string, 0, 3)
  626. args := make([]any, 0, 3)
  627. if filter.StartAt != nil {
  628. args = append(args, *filter.StartAt)
  629. clauses = append(clauses, fmt.Sprintf("%s >= $%d", timeColumn, len(args)))
  630. }
  631. if filter.EndAt != nil {
  632. args = append(args, *filter.EndAt)
  633. clauses = append(clauses, fmt.Sprintf("%s <= $%d", timeColumn, len(args)))
  634. }
  635. search := strings.TrimSpace(filter.Search)
  636. if search != "" && len(searchColumns) > 0 {
  637. args = append(args, "%"+strings.ToLower(search)+"%")
  638. parts := make([]string, 0, len(searchColumns))
  639. for _, col := range searchColumns {
  640. parts = append(parts, fmt.Sprintf("LOWER(%s) LIKE $%d", col, len(args)))
  641. }
  642. clauses = append(clauses, "("+strings.Join(parts, " OR ")+")")
  643. }
  644. if len(clauses) == 0 {
  645. return "", args
  646. }
  647. return "WHERE " + strings.Join(clauses, " AND "), args
  648. }
  649. func buildAffiliateRecordOrderBy(filter service.AffiliateRecordFilter, sortColumns map[string]string, fallbackColumn string) string {
  650. column := sortColumns[filter.SortBy]
  651. if column == "" {
  652. column = fallbackColumn
  653. }
  654. direction := "DESC"
  655. if !filter.SortDesc {
  656. direction = "ASC"
  657. }
  658. return "ORDER BY " + column + " " + direction + " NULLS LAST"
  659. }
  660. func queryAffiliateRecordCount(ctx context.Context, client affiliateQueryExecer, query string, args ...any) (int64, error) {
  661. rows, err := client.QueryContext(ctx, query, args...)
  662. if err != nil {
  663. return 0, err
  664. }
  665. defer func() { _ = rows.Close() }()
  666. if !rows.Next() {
  667. return 0, rows.Err()
  668. }
  669. var total int64
  670. if err := rows.Scan(&total); err != nil {
  671. return 0, err
  672. }
  673. return total, rows.Err()
  674. }
  675. func (r *affiliateRepository) withTx(ctx context.Context, fn func(txCtx context.Context, txClient *dbent.Client) error) error {
  676. if tx := dbent.TxFromContext(ctx); tx != nil {
  677. return fn(ctx, tx.Client())
  678. }
  679. tx, err := r.client.Tx(ctx)
  680. if err != nil {
  681. return fmt.Errorf("begin affiliate transaction: %w", err)
  682. }
  683. defer func() { _ = tx.Rollback() }()
  684. txCtx := dbent.NewTxContext(ctx, tx)
  685. if err := fn(txCtx, tx.Client()); err != nil {
  686. return err
  687. }
  688. if err := tx.Commit(); err != nil {
  689. return fmt.Errorf("commit affiliate transaction: %w", err)
  690. }
  691. return nil
  692. }
  693. func ensureUserAffiliateWithClient(ctx context.Context, client affiliateQueryExecer, userID int64) (*service.AffiliateSummary, error) {
  694. summary, err := queryAffiliateByUserID(ctx, client, userID)
  695. if err == nil {
  696. return summary, nil
  697. }
  698. if !errors.Is(err, service.ErrAffiliateProfileNotFound) {
  699. return nil, err
  700. }
  701. for i := 0; i < affiliateCodeMaxAttempts; i++ {
  702. code, codeErr := generateAffiliateCode()
  703. if codeErr != nil {
  704. return nil, codeErr
  705. }
  706. _, insertErr := client.ExecContext(ctx, `
  707. INSERT INTO user_affiliates (user_id, aff_code, created_at, updated_at)
  708. VALUES ($1, $2, NOW(), NOW())
  709. ON CONFLICT (user_id) DO NOTHING`, userID, code)
  710. if insertErr == nil {
  711. break
  712. }
  713. if isAffiliateUniqueViolation(insertErr) {
  714. continue
  715. }
  716. return nil, insertErr
  717. }
  718. return queryAffiliateByUserID(ctx, client, userID)
  719. }
  720. func queryAffiliateByUserID(ctx context.Context, client affiliateQueryExecer, userID int64) (*service.AffiliateSummary, error) {
  721. rows, err := client.QueryContext(ctx, `
  722. SELECT user_id,
  723. aff_code,
  724. aff_code_custom,
  725. aff_rebate_rate_percent,
  726. inviter_id,
  727. aff_count,
  728. aff_quota::double precision,
  729. aff_frozen_quota::double precision,
  730. aff_history_quota::double precision,
  731. created_at,
  732. updated_at
  733. FROM user_affiliates
  734. WHERE user_id = $1`, userID)
  735. if err != nil {
  736. return nil, err
  737. }
  738. defer func() { _ = rows.Close() }()
  739. if !rows.Next() {
  740. if err := rows.Err(); err != nil {
  741. return nil, err
  742. }
  743. return nil, service.ErrAffiliateProfileNotFound
  744. }
  745. var out service.AffiliateSummary
  746. var inviterID sql.NullInt64
  747. var rebateRate sql.NullFloat64
  748. if err := rows.Scan(
  749. &out.UserID,
  750. &out.AffCode,
  751. &out.AffCodeCustom,
  752. &rebateRate,
  753. &inviterID,
  754. &out.AffCount,
  755. &out.AffQuota,
  756. &out.AffFrozenQuota,
  757. &out.AffHistoryQuota,
  758. &out.CreatedAt,
  759. &out.UpdatedAt,
  760. ); err != nil {
  761. return nil, err
  762. }
  763. if inviterID.Valid {
  764. out.InviterID = &inviterID.Int64
  765. }
  766. if rebateRate.Valid {
  767. v := rebateRate.Float64
  768. out.AffRebateRatePercent = &v
  769. }
  770. return &out, nil
  771. }
  772. func queryAffiliateByCode(ctx context.Context, client affiliateQueryExecer, code string) (*service.AffiliateSummary, error) {
  773. rows, err := client.QueryContext(ctx, `
  774. SELECT user_id,
  775. aff_code,
  776. aff_code_custom,
  777. aff_rebate_rate_percent,
  778. inviter_id,
  779. aff_count,
  780. aff_quota::double precision,
  781. aff_frozen_quota::double precision,
  782. aff_history_quota::double precision,
  783. created_at,
  784. updated_at
  785. FROM user_affiliates
  786. WHERE aff_code = $1
  787. LIMIT 1`, strings.ToUpper(strings.TrimSpace(code)))
  788. if err != nil {
  789. return nil, err
  790. }
  791. defer func() { _ = rows.Close() }()
  792. if !rows.Next() {
  793. if err := rows.Err(); err != nil {
  794. return nil, err
  795. }
  796. return nil, service.ErrAffiliateProfileNotFound
  797. }
  798. var out service.AffiliateSummary
  799. var inviterID sql.NullInt64
  800. var rebateRate sql.NullFloat64
  801. if err := rows.Scan(
  802. &out.UserID,
  803. &out.AffCode,
  804. &out.AffCodeCustom,
  805. &rebateRate,
  806. &inviterID,
  807. &out.AffCount,
  808. &out.AffQuota,
  809. &out.AffFrozenQuota,
  810. &out.AffHistoryQuota,
  811. &out.CreatedAt,
  812. &out.UpdatedAt,
  813. ); err != nil {
  814. return nil, err
  815. }
  816. if inviterID.Valid {
  817. out.InviterID = &inviterID.Int64
  818. }
  819. if rebateRate.Valid {
  820. v := rebateRate.Float64
  821. out.AffRebateRatePercent = &v
  822. }
  823. return &out, nil
  824. }
  825. func queryUserBalance(ctx context.Context, client affiliateQueryExecer, userID int64) (float64, error) {
  826. rows, err := client.QueryContext(ctx,
  827. "SELECT balance::double precision FROM users WHERE id = $1 LIMIT 1",
  828. userID,
  829. )
  830. if err != nil {
  831. return 0, err
  832. }
  833. defer func() { _ = rows.Close() }()
  834. if !rows.Next() {
  835. if err := rows.Err(); err != nil {
  836. return 0, err
  837. }
  838. return 0, service.ErrUserNotFound
  839. }
  840. var balance float64
  841. if err := rows.Scan(&balance); err != nil {
  842. return 0, err
  843. }
  844. return balance, nil
  845. }
  846. type affiliateTransferSnapshot struct {
  847. BalanceAfter float64
  848. AvailableQuotaAfter float64
  849. FrozenQuotaAfter float64
  850. HistoryQuotaAfter float64
  851. }
  852. func queryAffiliateTransferSnapshot(ctx context.Context, client affiliateQueryExecer, userID int64) (*affiliateTransferSnapshot, error) {
  853. rows, err := client.QueryContext(ctx, `
  854. SELECT u.balance::double precision,
  855. ua.aff_quota::double precision,
  856. ua.aff_frozen_quota::double precision,
  857. ua.aff_history_quota::double precision
  858. FROM users u
  859. JOIN user_affiliates ua ON ua.user_id = u.id
  860. WHERE u.id = $1
  861. LIMIT 1`, userID)
  862. if err != nil {
  863. return nil, fmt.Errorf("query affiliate transfer snapshot: %w", err)
  864. }
  865. defer func() { _ = rows.Close() }()
  866. if !rows.Next() {
  867. if err := rows.Err(); err != nil {
  868. return nil, err
  869. }
  870. return nil, service.ErrUserNotFound
  871. }
  872. var snapshot affiliateTransferSnapshot
  873. if err := rows.Scan(
  874. &snapshot.BalanceAfter,
  875. &snapshot.AvailableQuotaAfter,
  876. &snapshot.FrozenQuotaAfter,
  877. &snapshot.HistoryQuotaAfter,
  878. ); err != nil {
  879. return nil, err
  880. }
  881. return &snapshot, rows.Err()
  882. }
  883. func nullableFloat64Ptr(v sql.NullFloat64) *float64 {
  884. if !v.Valid {
  885. return nil
  886. }
  887. return &v.Float64
  888. }
  889. func generateAffiliateCode() (string, error) {
  890. buf := make([]byte, affiliateCodeLength)
  891. if _, err := rand.Read(buf); err != nil {
  892. return "", fmt.Errorf("generate affiliate code: %w", err)
  893. }
  894. for i := range buf {
  895. buf[i] = affiliateCodeCharset[int(buf[i])%len(affiliateCodeCharset)]
  896. }
  897. return string(buf), nil
  898. }
  899. func isAffiliateUniqueViolation(err error) bool {
  900. var pqErr *pq.Error
  901. if errors.As(err, &pqErr) {
  902. return string(pqErr.Code) == "23505"
  903. }
  904. return false
  905. }
  906. // UpdateUserAffCode 改写用户的邀请码(自定义专属邀请码)。
  907. // 唯一性冲突返回 ErrAffiliateCodeTaken。
  908. func (r *affiliateRepository) UpdateUserAffCode(ctx context.Context, userID int64, newCode string) error {
  909. if userID <= 0 {
  910. return service.ErrUserNotFound
  911. }
  912. code := strings.ToUpper(strings.TrimSpace(newCode))
  913. if code == "" {
  914. return service.ErrAffiliateCodeInvalid
  915. }
  916. return r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
  917. if _, err := ensureUserAffiliateWithClient(txCtx, txClient, userID); err != nil {
  918. return err
  919. }
  920. res, err := txClient.ExecContext(txCtx, `
  921. UPDATE user_affiliates
  922. SET aff_code = $1,
  923. aff_code_custom = true,
  924. updated_at = NOW()
  925. WHERE user_id = $2`, code, userID)
  926. if err != nil {
  927. if isAffiliateUniqueViolation(err) {
  928. return service.ErrAffiliateCodeTaken
  929. }
  930. return fmt.Errorf("update aff_code: %w", err)
  931. }
  932. affected, _ := res.RowsAffected()
  933. if affected == 0 {
  934. return service.ErrUserNotFound
  935. }
  936. return nil
  937. })
  938. }
  939. // ResetUserAffCode 把 aff_code 还原为系统随机码,并清除 aff_code_custom 标记。
  940. func (r *affiliateRepository) ResetUserAffCode(ctx context.Context, userID int64) (string, error) {
  941. if userID <= 0 {
  942. return "", service.ErrUserNotFound
  943. }
  944. var newCode string
  945. err := r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
  946. if _, err := ensureUserAffiliateWithClient(txCtx, txClient, userID); err != nil {
  947. return err
  948. }
  949. for i := 0; i < affiliateCodeMaxAttempts; i++ {
  950. candidate, codeErr := generateAffiliateCode()
  951. if codeErr != nil {
  952. return codeErr
  953. }
  954. res, err := txClient.ExecContext(txCtx, `
  955. UPDATE user_affiliates
  956. SET aff_code = $1,
  957. aff_code_custom = false,
  958. updated_at = NOW()
  959. WHERE user_id = $2`, candidate, userID)
  960. if err != nil {
  961. if isAffiliateUniqueViolation(err) {
  962. continue
  963. }
  964. return fmt.Errorf("reset aff_code: %w", err)
  965. }
  966. affected, _ := res.RowsAffected()
  967. if affected == 0 {
  968. return service.ErrUserNotFound
  969. }
  970. newCode = candidate
  971. return nil
  972. }
  973. return fmt.Errorf("reset aff_code: exhausted attempts")
  974. })
  975. if err != nil {
  976. return "", err
  977. }
  978. return newCode, nil
  979. }
  980. // SetUserRebateRate 设置或清除用户专属返利比例。ratePercent==nil 表示清除(沿用全局)。
  981. func (r *affiliateRepository) SetUserRebateRate(ctx context.Context, userID int64, ratePercent *float64) error {
  982. if userID <= 0 {
  983. return service.ErrUserNotFound
  984. }
  985. return r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
  986. if _, err := ensureUserAffiliateWithClient(txCtx, txClient, userID); err != nil {
  987. return err
  988. }
  989. // nullableArg lets us use a single UPDATE for both "set value" and
  990. // "clear" cases — database/sql converts nil interface{} to SQL NULL.
  991. res, err := txClient.ExecContext(txCtx, `
  992. UPDATE user_affiliates
  993. SET aff_rebate_rate_percent = $1,
  994. updated_at = NOW()
  995. WHERE user_id = $2`, nullableArg(ratePercent), userID)
  996. if err != nil {
  997. return fmt.Errorf("set aff_rebate_rate_percent: %w", err)
  998. }
  999. affected, _ := res.RowsAffected()
  1000. if affected == 0 {
  1001. return service.ErrUserNotFound
  1002. }
  1003. return nil
  1004. })
  1005. }
  1006. // BatchSetUserRebateRate 批量为多个用户设置专属比例(nil 清除)。
  1007. func (r *affiliateRepository) BatchSetUserRebateRate(ctx context.Context, userIDs []int64, ratePercent *float64) error {
  1008. if len(userIDs) == 0 {
  1009. return nil
  1010. }
  1011. return r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
  1012. for _, uid := range userIDs {
  1013. if uid <= 0 {
  1014. continue
  1015. }
  1016. if _, err := ensureUserAffiliateWithClient(txCtx, txClient, uid); err != nil {
  1017. return err
  1018. }
  1019. }
  1020. _, err := txClient.ExecContext(txCtx, `
  1021. UPDATE user_affiliates
  1022. SET aff_rebate_rate_percent = $1,
  1023. updated_at = NOW()
  1024. WHERE user_id = ANY($2)`, nullableArg(ratePercent), pq.Array(userIDs))
  1025. if err != nil {
  1026. return fmt.Errorf("batch set aff_rebate_rate_percent: %w", err)
  1027. }
  1028. return nil
  1029. })
  1030. }
  1031. // nullableArg unwraps a *float64 into an interface{} suitable for SQL parameter
  1032. // binding: nil pointer → SQL NULL, non-nil → the float value.
  1033. func nullableArg(v *float64) any {
  1034. if v == nil {
  1035. return nil
  1036. }
  1037. return *v
  1038. }
  1039. func nullableInt64Arg(v *int64) any {
  1040. if v == nil {
  1041. return nil
  1042. }
  1043. return *v
  1044. }
  1045. // ListUsersWithCustomSettings 列出有专属配置(自定义码或专属比例)的用户。
  1046. //
  1047. // 单一查询同时处理"无搜索"与"按邮箱/用户名模糊搜索":
  1048. // 空 search 时拼接出的 LIKE 模式为 "%%",匹配所有行;非空时按 ILIKE 子串匹配。
  1049. // 这避免了为两种情况维护两份 SQL 模板。
  1050. func (r *affiliateRepository) ListUsersWithCustomSettings(ctx context.Context, filter service.AffiliateAdminFilter) ([]service.AffiliateAdminEntry, int64, error) {
  1051. page := filter.Page
  1052. if page < 1 {
  1053. page = 1
  1054. }
  1055. pageSize := filter.PageSize
  1056. if pageSize <= 0 || pageSize > 200 {
  1057. pageSize = 20
  1058. }
  1059. offset := (page - 1) * pageSize
  1060. likePattern := "%" + strings.TrimSpace(filter.Search) + "%"
  1061. const baseFrom = `
  1062. FROM user_affiliates ua
  1063. JOIN users u ON u.id = ua.user_id
  1064. WHERE (ua.aff_code_custom = true OR ua.aff_rebate_rate_percent IS NOT NULL)
  1065. AND (u.email ILIKE $1 OR u.username ILIKE $1)`
  1066. client := clientFromContext(ctx, r.client)
  1067. total, err := scanInt64(ctx, client, "SELECT COUNT(*)"+baseFrom, likePattern)
  1068. if err != nil {
  1069. return nil, 0, fmt.Errorf("count affiliate admin entries: %w", err)
  1070. }
  1071. listQuery := `
  1072. SELECT ua.user_id,
  1073. COALESCE(u.email, ''),
  1074. COALESCE(u.username, ''),
  1075. ua.aff_code,
  1076. ua.aff_code_custom,
  1077. ua.aff_rebate_rate_percent,
  1078. ua.aff_count` + baseFrom + `
  1079. ORDER BY ua.updated_at DESC
  1080. LIMIT $2 OFFSET $3`
  1081. rows, err := client.QueryContext(ctx, listQuery, likePattern, pageSize, offset)
  1082. if err != nil {
  1083. return nil, 0, fmt.Errorf("list affiliate admin entries: %w", err)
  1084. }
  1085. defer func() { _ = rows.Close() }()
  1086. entries := make([]service.AffiliateAdminEntry, 0)
  1087. for rows.Next() {
  1088. var e service.AffiliateAdminEntry
  1089. var rebate sql.NullFloat64
  1090. if err := rows.Scan(&e.UserID, &e.Email, &e.Username, &e.AffCode,
  1091. &e.AffCodeCustom, &rebate, &e.AffCount); err != nil {
  1092. return nil, 0, err
  1093. }
  1094. if rebate.Valid {
  1095. v := rebate.Float64
  1096. e.AffRebateRatePercent = &v
  1097. }
  1098. entries = append(entries, e)
  1099. }
  1100. if err := rows.Err(); err != nil {
  1101. return nil, 0, err
  1102. }
  1103. return entries, total, nil
  1104. }
  1105. // scanInt64 runs a query expected to return a single int64 column (e.g. COUNT).
  1106. func scanInt64(ctx context.Context, client affiliateQueryExecer, query string, args ...any) (int64, error) {
  1107. rows, err := client.QueryContext(ctx, query, args...)
  1108. if err != nil {
  1109. return 0, err
  1110. }
  1111. defer func() { _ = rows.Close() }()
  1112. if !rows.Next() {
  1113. if err := rows.Err(); err != nil {
  1114. return 0, err
  1115. }
  1116. return 0, nil
  1117. }
  1118. var v int64
  1119. if err := rows.Scan(&v); err != nil {
  1120. return 0, err
  1121. }
  1122. return v, nil
  1123. }