feat: 抽奖后台管理接口

- 活动表新增 winner_count / claim_days / rule_sections(迁移 0016),
  中奖名额数、领奖期限、活动规则可在后台配置,规则改文案不用发版
- 新增 6 个后台接口(@check_admin):
  admin/lottery/campaign/list 活动列表(含参与名额数)
  admin/lottery/campaign/save 新建 / 编辑活动
  admin/lottery/campaign/delete 停用活动(软删)
  admin/lottery/entry/list 抽奖名单
  admin/lottery/entry/result/update 批量设置中奖结果
  admin/lottery/address/list 中奖收货信息
- 小程序侧下发 claim_days 与 rule_sections(decrypt2 的 data 与详情接口),
  规则页可改为渲染后台配置、为空回退内置文案
- 修复活动列表参与名额恒为 1:Meta.ordering 会带进 GROUP BY,加 order_by() 清掉

FFIB 6 hours ago
parent
commit
6399cc30e4
4 changed files with 369 additions and 2 deletions
  1. 264 0
      api/sale/lottery_admin_views.py
  2. 10 2
      api/sale/urls.py
  3. 31 0
      sales/migrations/0016_auto_20261122_2207.py
  4. 64 0
      sales/models.py

+ 264 - 0
api/sale/lottery_admin_views.py

@@ -0,0 +1,264 @@
1
+# -*- coding: utf-8 -*-
2
+
3
+import json
4
+
5
+from django.db import transaction
6
+from django.db.models import Count, Q
7
+from django_logit import logit
8
+from django_response import response
9
+from paginator import pagination
10
+from TimeConvert import TimeConvert as tc
11
+
12
+from kodo.decorators import check_admin
13
+from sales.models import LotteryAddressInfo, LotteryCampaignInfo, LotteryEntryInfo
14
+from utils.error.errno_utils import LotteryStatusCode, ParamStatusCode
15
+
16
+DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
17
+RESULT_CHOICES = (LotteryEntryInfo.PENDING, LotteryEntryInfo.WON, LotteryEntryInfo.LOST)
18
+
19
+
20
+def _parse_datetime(value):
21
+    """'2026-10-29 00:00:00' → aware datetime;空串 → None"""
22
+    value = (value or '').strip()
23
+
24
+    if not value:
25
+        return None
26
+
27
+    return tc.string_to_utc_datetime(value, format=DATETIME_FORMAT)
28
+
29
+
30
+def _parse_rule_sections(value):
31
+    """规则 JSON 字符串 → [{title, items: []}];结构非法抛 ValueError"""
32
+    value = (value or '').strip()
33
+
34
+    if not value:
35
+        return None
36
+
37
+    sections = json.loads(value)
38
+
39
+    if not isinstance(sections, list):
40
+        raise ValueError('rule_sections must be a list')
41
+
42
+    cleaned = []
43
+
44
+    for section in sections:
45
+        if not isinstance(section, dict):
46
+            raise ValueError('rule section must be an object')
47
+
48
+        title = (section.get('title') or '').strip()
49
+        items = section.get('items') or []
50
+
51
+        if not isinstance(items, list):
52
+            raise ValueError('rule section items must be a list')
53
+
54
+        items = [str(item).strip() for item in items if str(item).strip()]
55
+
56
+        if title or items:
57
+            cleaned.append({'title': title, 'items': items})
58
+
59
+    return cleaned
60
+
61
+
62
+@logit
63
+@check_admin
64
+def lottery_campaign_list_api(request, administrator):
65
+    """后台:抽奖活动列表"""
66
+    query = request.POST.get('query', '')
67
+    status = request.POST.get('status', '1')
68
+    page = request.POST.get('page', 1)
69
+    num = request.POST.get('num', 20)
70
+
71
+    campaigns = LotteryCampaignInfo.objects.all()
72
+
73
+    if status in ('0', '1'):
74
+        campaigns = campaigns.filter(status=status == '1')
75
+
76
+    if query:
77
+        campaigns = campaigns.filter(Q(title__icontains=query) | Q(campaign_id__icontains=query))
78
+
79
+    count = campaigns.count()
80
+
81
+    campaigns, left = pagination(campaigns, page, num)
82
+
83
+    entry_counts = dict(
84
+        LotteryEntryInfo.objects.filter(status=True)
85
+        .order_by()          # 清掉 Meta.ordering,否则 created_at 会进 GROUP BY,计数恒为 1
86
+        .values_list('campaign_id')
87
+        .annotate(entry_count=Count('id'))
88
+    )
89
+
90
+    data = [
91
+        dict(campaign.admindata, entry_count=entry_counts.get(campaign.campaign_id, 0))
92
+        for campaign in campaigns
93
+    ]
94
+
95
+    return response(200, 'Get Lottery Campaign List Success', u'抽奖活动列表获取成功', data={
96
+        'campaigns': data,
97
+        'count': count,
98
+        'left': left,
99
+    })
100
+
101
+
102
+@logit
103
+@check_admin
104
+@transaction.atomic
105
+def lottery_campaign_save_api(request, administrator):
106
+    """后台:新建 / 编辑抽奖活动"""
107
+    campaign_id = request.POST.get('campaign_id', '')
108
+    title = (request.POST.get('title') or '').strip()
109
+
110
+    if not title:
111
+        return response(ParamStatusCode.PARAM_INVALID)
112
+
113
+    try:
114
+        rule_sections = _parse_rule_sections(request.POST.get('rule_sections', ''))
115
+        start_at = _parse_datetime(request.POST.get('start_at', ''))
116
+        end_at = _parse_datetime(request.POST.get('end_at', ''))
117
+        draw_at = _parse_datetime(request.POST.get('draw_at', ''))
118
+        winner_count = int(request.POST.get('winner_count') or 1)
119
+        claim_days = int(request.POST.get('claim_days') or 14)
120
+    except (ValueError, TypeError):
121
+        return response(ParamStatusCode.PARAM_INVALID)
122
+
123
+    fields = {
124
+        'title': title,
125
+        'prize_text': (request.POST.get('prize_text') or '').strip(),
126
+        'winner_count': max(winner_count, 0),
127
+        'claim_days': max(claim_days, 0),
128
+        'start_at': start_at,
129
+        'end_at': end_at,
130
+        'draw_at': draw_at,
131
+        'model_ids': (request.POST.getlist('model_ids[]') or request.POST.getlist('model_ids')) or None,
132
+        'rule_sections': rule_sections,
133
+    }
134
+
135
+    if campaign_id:
136
+        campaign = LotteryCampaignInfo.objects.filter(campaign_id=campaign_id, status=True).first()
137
+
138
+        if not campaign:
139
+            return response(LotteryStatusCode.CAMPAIGN_NOT_FOUND)
140
+
141
+        for key, value in fields.items():
142
+            setattr(campaign, key, value)
143
+
144
+        campaign.save()
145
+    else:
146
+        campaign = LotteryCampaignInfo.objects.create(**fields)
147
+
148
+    return response(200, 'Save Lottery Campaign Success', u'保存抽奖活动成功', data=campaign.admindata)
149
+
150
+
151
+@logit
152
+@check_admin
153
+@transaction.atomic
154
+def lottery_campaign_delete_api(request, administrator):
155
+    """后台:停用抽奖活动(软删,名单和收货信息保留)"""
156
+    campaign = LotteryCampaignInfo.objects.filter(
157
+        campaign_id=request.POST.get('campaign_id', ''),
158
+        status=True,
159
+    ).first()
160
+
161
+    if not campaign:
162
+        return response(LotteryStatusCode.CAMPAIGN_NOT_FOUND)
163
+
164
+    campaign.status = False
165
+    campaign.save()
166
+
167
+    return response(200, 'Delete Lottery Campaign Success', u'抽奖活动已停用')
168
+
169
+
170
+@logit
171
+@check_admin
172
+def lottery_entry_list_api(request, administrator):
173
+    """后台:抽奖名单"""
174
+    campaign_id = request.POST.get('campaign_id', '')
175
+    query = request.POST.get('query', '')
176
+    result = request.POST.get('result', '')
177
+    page = request.POST.get('page', 1)
178
+    num = request.POST.get('num', 20)
179
+
180
+    entries = LotteryEntryInfo.objects.filter(status=True)
181
+
182
+    if campaign_id:
183
+        entries = entries.filter(campaign_id=campaign_id)
184
+
185
+    if result:
186
+        entries = entries.filter(result=result)
187
+
188
+    if query:
189
+        entries = entries.filter(
190
+            Q(serial_no__icontains=query) |
191
+            Q(name__icontains=query) |
192
+            Q(phone__icontains=query) |
193
+            Q(user_id__icontains=query)
194
+        )
195
+
196
+    count = entries.count()
197
+
198
+    entries, left = pagination(entries, page, num)
199
+
200
+    return response(200, 'Get Lottery Entry List Success', u'抽奖名单获取成功', data={
201
+        'entries': [entry.admindata for entry in entries],
202
+        'count': count,
203
+        'left': left,
204
+    })
205
+
206
+
207
+@logit
208
+@check_admin
209
+@transaction.atomic
210
+def lottery_entry_result_update_api(request, administrator):
211
+    """后台:批量设置中奖结果(pending / won / lost)"""
212
+    result = request.POST.get('result', '')
213
+    entry_ids = request.POST.getlist('entry_ids[]') or request.POST.getlist('entry_ids')
214
+
215
+    if result not in RESULT_CHOICES or not entry_ids:
216
+        return response(ParamStatusCode.PARAM_INVALID)
217
+
218
+    updated = LotteryEntryInfo.objects.filter(status=True, entry_id__in=entry_ids).update(result=result)
219
+
220
+    return response(200, 'Update Lottery Entry Result Success', u'中奖结果已更新', data={'updated': updated})
221
+
222
+
223
+@logit
224
+@check_admin
225
+def lottery_address_list_api(request, administrator):
226
+    """后台:中奖收货信息"""
227
+    campaign_id = request.POST.get('campaign_id', '')
228
+    query = request.POST.get('query', '')
229
+    page = request.POST.get('page', 1)
230
+    num = request.POST.get('num', 20)
231
+
232
+    addresses = LotteryAddressInfo.objects.filter(status=True)
233
+
234
+    if campaign_id:
235
+        addresses = addresses.filter(campaign_id=campaign_id)
236
+
237
+    if query:
238
+        addresses = addresses.filter(
239
+            Q(receiver__icontains=query) |
240
+            Q(phone__icontains=query) |
241
+            Q(region__icontains=query) |
242
+            Q(detail__icontains=query)
243
+        )
244
+
245
+    count = addresses.count()
246
+
247
+    addresses, left = pagination(addresses, page, num)
248
+
249
+    titles = dict(
250
+        LotteryCampaignInfo.objects.filter(
251
+            campaign_id__in={address.campaign_id for address in addresses}
252
+        ).values_list('campaign_id', 'title')
253
+    )
254
+
255
+    data = [
256
+        dict(address.admindata, campaign_title=titles.get(address.campaign_id, ''))
257
+        for address in addresses
258
+    ]
259
+
260
+    return response(200, 'Get Lottery Address List Success', u'收货信息获取成功', data={
261
+        'addresses': data,
262
+        'count': count,
263
+        'left': left,
264
+    })

+ 10 - 2
api/sale/urls.py

@@ -2,14 +2,22 @@
2 2
 
3 3
 from django.conf.urls import include, url
4 4
 
5
-from api.sale import lottery_views
5
+from api.sale import lottery_admin_views, lottery_views
6 6
 
7 7
 urlpatterns = [
8 8
     url(r'^lottery/join$', lottery_views.lottery_join_api, name='lottery_join_api'),
9 9
 
10
-    # 我的抽奖
10
+    # 我的抽奖(小程序)
11 11
     url(r'^mp/lottery/campaign/list$', lottery_views.lottery_campaign_list_api, name='lottery_campaign_list_api'),
12 12
     url(r'^mp/lottery/campaign/detail$', lottery_views.lottery_campaign_detail_api, name='lottery_campaign_detail_api'),
13 13
     url(r'^mp/lottery/campaign/info/update$', lottery_views.lottery_campaign_info_update_api, name='lottery_campaign_info_update_api'),
14 14
     url(r'^mp/lottery/campaign/address/update$', lottery_views.lottery_campaign_address_update_api, name='lottery_campaign_address_update_api'),
15
+
16
+    # 抽奖管理(后台 tonglan_admin)
17
+    url(r'^admin/lottery/campaign/list$', lottery_admin_views.lottery_campaign_list_api, name='lottery_admin_campaign_list_api'),
18
+    url(r'^admin/lottery/campaign/save$', lottery_admin_views.lottery_campaign_save_api, name='lottery_admin_campaign_save_api'),
19
+    url(r'^admin/lottery/campaign/delete$', lottery_admin_views.lottery_campaign_delete_api, name='lottery_admin_campaign_delete_api'),
20
+    url(r'^admin/lottery/entry/list$', lottery_admin_views.lottery_entry_list_api, name='lottery_admin_entry_list_api'),
21
+    url(r'^admin/lottery/entry/result/update$', lottery_admin_views.lottery_entry_result_update_api, name='lottery_admin_entry_result_update_api'),
22
+    url(r'^admin/lottery/address/list$', lottery_admin_views.lottery_address_list_api, name='lottery_admin_address_list_api'),
15 23
 ]

+ 31 - 0
sales/migrations/0016_auto_20261122_2207.py

@@ -0,0 +1,31 @@
1
+# -*- coding: utf-8 -*-
2
+
3
+# Generated by Django 3.2.16 on 2026-11-22 14:07
4
+
5
+from django.db import migrations, models
6
+import jsonfield.fields
7
+
8
+
9
+class Migration(migrations.Migration):
10
+
11
+    dependencies = [
12
+        ('sales', '0015_auto_20261115_1730'),
13
+    ]
14
+
15
+    operations = [
16
+        migrations.AddField(
17
+            model_name='lotterycampaigninfo',
18
+            name='claim_days',
19
+            field=models.IntegerField(default=14, help_text='开奖后联系期限(工作日)', verbose_name='claim_days'),
20
+        ),
21
+        migrations.AddField(
22
+            model_name='lotterycampaigninfo',
23
+            name='rule_sections',
24
+            field=jsonfield.fields.JSONField(blank=True, help_text='活动规则段落:[{title, items: []}]', null=True, verbose_name='rule_sections'),
25
+        ),
26
+        migrations.AddField(
27
+            model_name='lotterycampaigninfo',
28
+            name='winner_count',
29
+            field=models.IntegerField(default=1, help_text='中奖名额数', verbose_name='winner_count'),
30
+        ),
31
+    ]

+ 64 - 0
sales/models.py

@@ -20,6 +20,13 @@ def to_local_iso(dt):
20 20
     return '%s+08:00' % tc.local_string(utc_dt=dt, format='%Y-%m-%d')
21 21
 
22 22
 
23
+def to_local_datetime_string(dt):
24
+    """aware datetime → '2026-10-29 00:00:00'(北京时间,后台表单回填用)"""
25
+    if not dt:
26
+        return ''
27
+    return tc.local_string(utc_dt=dt, format='%Y-%m-%d %H:%M:%S')
28
+
29
+
23 30
 class SalesResponsibilityInfo(BaseModelMixin):
24 31
     REFUSED = -1
25 32
     UNVERIFIED = 0
@@ -201,6 +208,11 @@ class LotteryCampaignInfo(BaseModelMixin):
201 208
     draw_at = models.DateTimeField(_(u'draw_at'), blank=True, null=True, help_text=u'开奖时间', db_index=True)
202 209
     model_ids = JSONField(_(u'model_ids'), blank=True, null=True, help_text=u'参与型号列表')
203 210
 
211
+    winner_count = models.IntegerField(_(u'winner_count'), default=1, help_text=u'中奖名额数')
212
+    claim_days = models.IntegerField(_(u'claim_days'), default=14, help_text=u'开奖后联系期限(工作日)')
213
+    rule_sections = JSONField(_(u'rule_sections'), blank=True, null=True,
214
+                              help_text=u'活动规则段落:[{title, items: []}]')
215
+
204 216
     class Meta:
205 217
         verbose_name = _(u'抽奖活动')
206 218
         verbose_name_plural = _(u'抽奖活动')
@@ -227,6 +239,26 @@ class LotteryCampaignInfo(BaseModelMixin):
227 239
             'end_at': to_local_iso(self.end_at),
228 240
             'draw_at': to_local_iso(self.draw_at),
229 241
             'model_ids': self.model_ids,
242
+            'claim_days': self.claim_days,
243
+            'rule_sections': self.rule_sections or [],
244
+        }
245
+
246
+    @property
247
+    def admindata(self):
248
+        """后台列表 / 表单回填"""
249
+        return {
250
+            'campaign_id': self.campaign_id,
251
+            'title': self.title,
252
+            'prize_text': self.prize_text or '',
253
+            'winner_count': self.winner_count,
254
+            'claim_days': self.claim_days,
255
+            'start_at': to_local_datetime_string(self.start_at),
256
+            'end_at': to_local_datetime_string(self.end_at),
257
+            'draw_at': to_local_datetime_string(self.draw_at),
258
+            'model_ids': self.model_ids or [],
259
+            'rule_sections': self.rule_sections or [],
260
+            'status': self.status,
261
+            'created_at': to_local_datetime_string(self.created_at),
230 262
         }
231 263
 
232 264
     def list_data(self, entries):
@@ -253,6 +285,8 @@ class LotteryCampaignInfo(BaseModelMixin):
253 285
             'phone': phone,
254 286
             'address': address.data if address else None,
255 287
             'locked': self.is_locked(),
288
+            'claim_days': self.claim_days,
289
+            'rule_sections': self.rule_sections or [],
256 290
         })
257 291
 
258 292
         return data
@@ -356,6 +390,23 @@ class LotteryEntryInfo(BaseModelMixin):
356 390
             'status': self.result or self.PENDING,
357 391
         }
358 392
 
393
+    @property
394
+    def admindata(self):
395
+        """后台名单列表"""
396
+        return {
397
+            'entry_id': self.entry_id,
398
+            'campaign_id': self.campaign_id,
399
+            'campaign_title': self.campaign_title or '',
400
+            'user_id': self.user_id or '',
401
+            'name': self.name or '',
402
+            'phone': self.phone or '',
403
+            'serial_no': self.serial_no,
404
+            'model_id': self.model_id or '',
405
+            'model_name': self.model_name or '',
406
+            'result': self.result or self.PENDING,
407
+            'created_at': to_local_datetime_string(self.created_at),
408
+        }
409
+
359 410
 
360 411
 class LotteryAddressQuerySet(models.QuerySet):
361 412
     """抽奖收货信息查询集"""
@@ -399,3 +450,16 @@ class LotteryAddressInfo(BaseModelMixin):
399 450
             'region': self.region or '',
400 451
             'detail': self.detail or '',
401 452
         }
453
+
454
+    @property
455
+    def admindata(self):
456
+        """后台收货信息列表"""
457
+        return {
458
+            'campaign_id': self.campaign_id,
459
+            'user_id': self.user_id or '',
460
+            'receiver': self.receiver or '',
461
+            'phone': self.phone or '',
462
+            'region': self.region or '',
463
+            'detail': self.detail or '',
464
+            'created_at': to_local_datetime_string(self.created_at),
465
+        }