-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutes.py
More file actions
3337 lines (2823 loc) Β· 143 KB
/
routes.py
File metadata and controls
3337 lines (2823 loc) Β· 143 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# routes.py
import json
import os
import decimal
import qrcode
import io
import base64
import time
import uuid
import queue
import threading
import requests
import re
from datetime import datetime, date, timedelta # Added timedelta
import csv
import io
from functools import wraps
from flask import (
Blueprint, render_template, request, jsonify, redirect,
url_for, flash, g, session, current_app, abort, send_from_directory,
Response
)
from werkzeug.utils import secure_filename
from sqlalchemy import or_, func, distinct, case, text
from sqlalchemy.orm.attributes import flag_modified
from sqlalchemy.ext.declarative import DeclarativeMeta
from models.nyota import (
db, Creator, CreatorSetting, DigitalAsset, AssetFile,
Purchase, Customer, Comment,
Ambassador, AssetStatus, AssetType, PurchaseStatus,
SubscriptionInterval,
AccessAttempt, SMSMagicLink,
SMSCampaign, SMSCampaignLog, SMSCampaignStatus,
SMSLog, SMSLogType
)
from utils.security import creator_login_required, generate_totp_secret, get_totp_uri, verify_totp
from utils.translator import translate
from utils.image_utils import optimize_cover_image
from extensions import limiter
from services.sms_service import get_sms_provider
# --- Helper for JSON serialization ---
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code."""
if isinstance(obj, (datetime, date)): return obj.isoformat()
if isinstance(obj, decimal.Decimal): return float(obj)
if hasattr(obj, 'value'): return obj.value
raise TypeError(f"Type {type(obj)} not serializable")
# --- Blueprint Definitions ---
main_bp = Blueprint('main', __name__)
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
# ==============================================================================
# == ADMIN BLUEPRINT (The Creator Hub)
# ==============================================================================
@admin_bp.before_request
def before_admin_request():
"""Smart request hook to handle all admin authentication and setup logic."""
public_endpoints = ['admin.creator_setup', 'admin.creator_login', 'admin.creator_login_verify']
if not Creator.query.first():
if request.endpoint not in ['admin.creator_setup']:
return redirect(url_for('admin.creator_setup'))
elif 'creator_id' not in session and request.endpoint not in public_endpoints:
return redirect(url_for('admin.creator_login'))
elif 'creator_id' in session:
g.creator = Creator.query.get(session['creator_id'])
if not g.creator:
session.clear()
return redirect(url_for('admin.creator_login'))
@admin_bp.context_processor
def utility_processor():
def resolve_avatar(supporter):
from utils.avatar_helper import get_avatar_data
return get_avatar_data(supporter)
return dict(resolve_avatar=resolve_avatar)
# --- AUTH & SETUP ROUTES ---
@admin_bp.route('/')
def admin_home():
"""Primary entry point for `/admin`. Redirects user based on their state."""
if 'creator_id' in session:
return redirect(url_for('admin.creator_dashboard'))
elif Creator.query.first():
return redirect(url_for('admin.creator_login'))
else:
return redirect(url_for('admin.creator_setup'))
@admin_bp.route('/setup', methods=['GET', 'POST'])
def creator_setup():
if Creator.query.first(): return redirect(url_for('admin.creator_login'))
if request.method == 'POST':
action = request.form.get('action')
if action == 'create_user':
username = request.form.get('username')
if not username or len(username) < 3:
flash(translate('username_required'), 'danger')
return render_template('admin/setup.html', stage=1)
totp_secret = generate_totp_secret()
session['setup_info'] = {'username': username, 'totp_secret': totp_secret}
totp_uri = get_totp_uri(username, session['setup_info']['totp_secret'])
img = qrcode.make(totp_uri)
buf = io.BytesIO()
img.save(buf)
qr_code_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
return render_template('admin/setup.html', stage=2, qr_code=qr_code_b64, username=username)
elif action == 'verify_totp':
setup_info, token = session.get('setup_info'), request.form.get('token')
if not setup_info or not token:
flash(translate('session_expired_setup'), 'danger')
return redirect(url_for('admin.creator_setup'))
if verify_totp(setup_info['totp_secret'], token):
new_creator = Creator(username=setup_info['username'], totp_secret=setup_info['totp_secret'])
db.session.add(new_creator)
db.session.commit()
session.pop('setup_info', None)
flash(translate('setup_complete_success'), 'success')
return redirect(url_for('admin.creator_login'))
else:
flash(translate('invalid_2fa_token'), 'danger')
totp_uri = get_totp_uri(setup_info['username'], setup_info['totp_secret'])
img = qrcode.make(totp_uri)
buf = io.BytesIO()
img.save(buf)
qr_code_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
return render_template('admin/setup.html', stage=2, qr_code=qr_code_b64, username=setup_info['username'])
return render_template('admin/setup.html', stage=1)
@admin_bp.route('/login', methods=['GET', 'POST'])
def creator_login():
if not Creator.query.first(): return redirect(url_for('admin.creator_setup'))
if 'creator_id' in session: return redirect(url_for('admin.creator_dashboard'))
if request.method == 'POST':
creator = Creator.query.filter_by(username=request.form.get('username')).first()
if creator:
session['2fa_creator_id'] = creator.id
return redirect(url_for('admin.creator_login_verify'))
flash(translate('invalid_username'), 'danger')
return render_template('admin/login.html')
@admin_bp.route('/login/verify', methods=['GET', 'POST'])
def creator_login_verify():
if '2fa_creator_id' not in session: return redirect(url_for('admin.creator_login'))
if request.method == 'POST':
creator = Creator.query.get(session['2fa_creator_id'])
if verify_totp(creator.totp_secret, request.form.get('token')):
session.pop('2fa_creator_id', None)
session['creator_id'] = creator.id
return redirect(url_for('admin.creator_dashboard'))
flash(translate('invalid_2fa_token'), 'danger')
return render_template('admin/login_verify.html')
@admin_bp.route('/logout')
def creator_logout():
session.clear()
flash(translate('logged_out'), 'info')
return redirect(url_for('admin.creator_login'))
# --- CORE ADMIN ROUTES (Protected) ---
@admin_bp.route('/dashboard')
@creator_login_required
def creator_dashboard():
# --- FILTERS ---
period = request.args.get('period', '30d') # Default to last 30 days
asset_id = request.args.get('asset_id', type=int)
start_date = None
end_date = datetime.utcnow()
if period == '7d':
start_date = end_date - timedelta(days=7)
elif period == '30d':
start_date = end_date - timedelta(days=30)
elif period == '90d':
start_date = end_date - timedelta(days=90)
elif period == '1y':
start_date = end_date - timedelta(days=365)
elif period == 'all':
start_date = None
elif period == 'custom':
start_date_str = request.args.get('start_date')
end_date_str = request.args.get('end_date')
if start_date_str:
try:
start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
except ValueError:
pass
if end_date_str:
try:
end_date = datetime.strptime(end_date_str, '%Y-%m-%d') + timedelta(days=1) - timedelta(seconds=1) # End of day
except ValueError:
pass
# Base Query for Completed Purchases
base_query = db.session.query(Purchase).join(DigitalAsset).filter(
DigitalAsset.creator_id == g.creator.id,
Purchase.status == PurchaseStatus.COMPLETED
)
if asset_id:
base_query = base_query.filter(Purchase.asset_id == asset_id)
# --- STATS CALCULATION ---
# Total Earnings (Filtered by Asset, but usually we want Total All Time or Filtered Period?)
# Let's make the "Total Earnings" card respect the Time Filter too, or maybe keep it All Time?
# Usually "Total Earnings" implies All Time. "Earnings (Period)" implies Filter.
# But for a standard dashboard, often top cards update with filters.
# Let's align with "Earnings (This Month)" replacement -> "Earnings (Selected Period)"
# 1. Total Earnings (All Time, but filtered by Asset if selected)
total_earnings_query = db.session.query(func.sum(Purchase.amount_paid)).join(DigitalAsset).filter(
DigitalAsset.creator_id == g.creator.id,
Purchase.status == PurchaseStatus.COMPLETED
)
if asset_id:
total_earnings_query = total_earnings_query.filter(Purchase.asset_id == asset_id)
total_earnings = total_earnings_query.scalar() or decimal.Decimal(0)
# 2. Earnings (Selected Period)
period_earnings_query = base_query
if start_date:
period_earnings_query = period_earnings_query.filter(Purchase.purchase_date >= start_date)
if end_date and period == 'custom':
period_earnings_query = period_earnings_query.filter(Purchase.purchase_date <= end_date)
period_earnings = period_earnings_query.with_entities(func.sum(Purchase.amount_paid)).scalar() or decimal.Decimal(0)
# 3. Total Sales (Selected Period)
period_sales = period_earnings_query.with_entities(func.count(Purchase.id)).scalar() or 0
# 4. Supporters (Total Unique, filtered by Asset if selected)
# Note: Supporters count usually refers to total unique customers all time for the creator/asset
supporters_query = db.session.query(func.count(Customer.id.distinct())).join(Purchase).join(DigitalAsset).filter(
DigitalAsset.creator_id == g.creator.id,
Purchase.status == PurchaseStatus.COMPLETED
)
if asset_id:
supporters_query = supporters_query.filter(Purchase.asset_id == asset_id)
supporters_count = supporters_query.scalar() or 0
# New Supporters (Selected Period) - Customers whose *first* purchase was in this period?
# Or just unique customers who bought in this period?
# Let's do unique customers who bought in this period for simplicity as "Active Supporters"
# period_supporters = period_earnings_query.with_entities(func.count(Purchase.customer_id.distinct())).scalar() or 0
stats = {
'total_earnings': total_earnings,
'period_earnings': period_earnings,
'period_sales': period_sales,
'supporters_count': supporters_count,
'period': period
}
# --- RECENT ACTIVITY (SALES) with PAGINATION ---
page = request.args.get('page', 1, type=int)
search = request.args.get('search', '').strip()
per_page = 10
activity_query = Purchase.query.join(DigitalAsset).filter(
DigitalAsset.creator_id == g.creator.id
)
if asset_id:
activity_query = activity_query.filter(Purchase.asset_id == asset_id)
if start_date:
activity_query = activity_query.filter(Purchase.purchase_date >= start_date)
if end_date and period == 'custom':
activity_query = activity_query.filter(Purchase.purchase_date <= end_date)
# --- STATUS FILTER ---
status = request.args.get('status', '').strip()
if status and status in [s.name for s in PurchaseStatus]:
activity_query = activity_query.filter(Purchase.status == PurchaseStatus[status])
if search:
activity_query = activity_query.join(Customer).filter(
or_(
Customer.whatsapp_number.ilike(f"%{search}%"),
DigitalAsset.title.ilike(f"%{search}%")
)
)
recent_activity = activity_query.order_by(Purchase.purchase_date.desc()).paginate(
page=page, per_page=per_page, error_out=False
)
# Fetch all assets for the filter dropdown
all_assets = DigitalAsset.query.filter_by(creator_id=g.creator.id).with_entities(DigitalAsset.id, DigitalAsset.title).all()
return render_template(
'admin/dashboard.html',
stats=stats,
activity=recent_activity,
assets=all_assets,
current_filters={
'period': period,
'asset_id': asset_id,
'search': search,
'status': status
}
)
@admin_bp.route('/dashboard/export')
@creator_login_required
def export_dashboard_data():
"""Exports the current dashboard view (Recent Orders) to CSV with creative stats."""
# --- REPLICATE FILTERS ---
period = request.args.get('period', '30d')
asset_id = request.args.get('asset_id', type=int)
search = request.args.get('search', '').strip()
status = request.args.get('status', '').strip()
start_date = None
end_date = datetime.utcnow()
if period == '7d': start_date = end_date - timedelta(days=7)
elif period == '30d': start_date = end_date - timedelta(days=30)
elif period == '90d': start_date = end_date - timedelta(days=90)
elif period == '1y': start_date = end_date - timedelta(days=365)
elif period == 'custom':
start_date_str = request.args.get('start_date')
end_date_str = request.args.get('end_date')
if start_date_str:
try: start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
except ValueError: pass
if end_date_str:
try: end_date = datetime.strptime(end_date_str, '%Y-%m-%d') + timedelta(days=1) - timedelta(seconds=1)
except ValueError: pass
# Build Query
query = Purchase.query.join(DigitalAsset).filter(DigitalAsset.creator_id == g.creator.id)
if asset_id: query = query.filter(Purchase.asset_id == asset_id)
if start_date: query = query.filter(Purchase.purchase_date >= start_date)
if end_date and period == 'custom': query = query.filter(Purchase.purchase_date <= end_date)
if search:
query = query.join(Customer).filter(
or_(
Customer.whatsapp_number.ilike(f"%{search}%"),
DigitalAsset.title.ilike(f"%{search}%")
)
)
if status and status in [s.name for s in PurchaseStatus]:
query = query.filter(Purchase.status == PurchaseStatus[status])
# Order by date desc
purchases = query.order_by(Purchase.purchase_date.desc()).all()
# Generate CSV
si = io.StringIO()
cw = csv.writer(si)
# Headers
headers = [
'Order ID', 'Date', 'Time', 'Customer Phone', 'Asset', 'Status', 'Amount',
'Past Purchase 1 (Date - Asset - Amount)',
'Past Purchase 2 (Date - Asset - Amount)'
]
cw.writerow(headers)
for p in purchases:
# Creative Stats: Fetch up to 2 past purchases for this customer, BEFORE this purchase
past_purchases = Purchase.query.filter(
Purchase.customer_id == p.customer_id,
Purchase.id < p.id, # Strictly before this purchase
Purchase.status == PurchaseStatus.COMPLETED # Only count completed past purchases? Or all? Usually Completed is more relevant for value.
).order_by(Purchase.purchase_date.desc()).limit(2).all()
past_1_str = "N/A"
if len(past_purchases) > 0:
pp1 = past_purchases[0]
asset_title = pp1.asset.title if pp1.asset else "Unknown Asset"
past_1_str = f"{pp1.purchase_date.strftime('%Y-%m-%d')} - {asset_title} - {pp1.amount_paid}"
past_2_str = "N/A"
if len(past_purchases) > 1:
pp2 = past_purchases[1]
asset_title = pp2.asset.title if pp2.asset else "Unknown Asset"
past_2_str = f"{pp2.purchase_date.strftime('%Y-%m-%d')} - {asset_title} - {pp2.amount_paid}"
cw.writerow([
p.id,
p.purchase_date.strftime('%Y-%m-%d'),
p.purchase_date.strftime('%H:%M:%S'),
p.customer.whatsapp_number,
p.asset.title,
p.status.name,
p.amount_paid,
past_1_str,
past_2_str
])
output = si.getvalue()
return Response(
output,
mimetype="text/csv",
headers={"Content-disposition": f"attachment; filename=orders_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"}
)
@admin_bp.route('/assets')
@creator_login_required
def list_assets():
# --- FILTERS & PAGINATION ---
page = request.args.get('page', 1, type=int)
search = request.args.get('search', '').strip()
status = request.args.get('status', '').strip()
per_page = 20
query = DigitalAsset.query.filter_by(creator_id=g.creator.id)
if search:
query = query.filter(DigitalAsset.title.ilike(f"%{search}%"))
if status and status in [s.value for s in AssetStatus]:
query = query.filter(DigitalAsset.status == AssetStatus(status))
pagination = query.order_by(DigitalAsset.updated_at.desc()).paginate(
page=page, per_page=per_page, error_out=False
)
creator_assets = pagination.items
assets_data = [{
'id': a.id,
'title': a.title,
'description': a.description,
'cover': a.cover_image_url,
'type': a.asset_type.name,
'status': a.status.value,
'sales': a.total_sales,
'revenue': float(a.total_revenue),
'updated_at': a.updated_at
} for a in creator_assets]
# --- STATS ---
stats = {
'total_assets': DigitalAsset.query.filter_by(creator_id=g.creator.id).count(),
'published_count': DigitalAsset.query.filter_by(creator_id=g.creator.id, status=AssetStatus.PUBLISHED).count(),
'total_revenue': db.session.query(func.sum(DigitalAsset.total_revenue)).filter_by(creator_id=g.creator.id).scalar() or 0.0,
'total_sales': db.session.query(func.sum(DigitalAsset.total_sales)).filter_by(creator_id=g.creator.id).scalar() or 0
}
return render_template(
'admin/assets.html',
assets_json=json.dumps(assets_data, default=json_serial),
assets=assets_data,
pagination=pagination,
stats=stats,
current_filters={'search': search, 'status': status}
)
@admin_bp.route('/assets/new', methods=['GET', 'POST'])
@creator_login_required
def asset_new():
if request.method == 'POST':
try:
new_asset = DigitalAsset(creator_id=g.creator.id)
save_asset_from_form(new_asset, request)
db.session.add(new_asset)
db.session.commit()
flash(f"Asset '{new_asset.title}' created successfully!", "success")
return redirect(url_for('admin.asset_edit', asset_id=new_asset.id))
except ValueError as e:
flash(str(e), 'danger')
return render_template('admin/asset_form.html', asset=request.form.get('asset_data', '{}'))
return render_template('admin/asset_form.html', asset='{}')
@admin_bp.route('/assets/<int:asset_id>/edit', methods=['GET'])
@creator_login_required
def asset_edit(asset_id):
asset = DigitalAsset.query.filter_by(id=asset_id, creator_id=g.creator.id).first_or_404()
recent_purchases = Purchase.query.filter_by(asset_id=asset.id).order_by(Purchase.purchase_date.desc()).limit(5).all()
recent_comments = Comment.query.filter_by(asset_id=asset.id).order_by(Comment.created_at.desc()).limit(5).all()
return render_template('admin/asset_view.html', asset=asset, recent_purchases=recent_purchases, recent_comments=recent_comments, statuses=[s.value for s in AssetStatus])
@admin_bp.route('/api/assets/<int:asset_id>/update', methods=['POST'])
@creator_login_required
def update_asset_details(asset_id):
"""API endpoint to handle edits from the asset_view page."""
asset = DigitalAsset.query.filter_by(id=asset_id, creator_id=g.creator.id).first_or_404()
data = request.get_json()
if not data:
return jsonify({'success': False, 'message': 'Invalid request.'}), 400
title = data.get('title', '').strip()
if not title:
return jsonify({'success': False, 'message': 'Asset title cannot be empty.'}), 422
try:
asset.title = title
asset.description = data.get('description', asset.description)
asset.story = data.get('story', asset.story)
asset.price = decimal.Decimal(data.get('price', asset.price))
new_status_str = data.get('status')
if new_status_str in [s.value for s in AssetStatus]:
asset.status = AssetStatus(new_status_str)
# --- Slug Editing ---
new_slug = data.get('slug', '').strip()
if new_slug:
from slugify import slugify as _slugify
new_slug = _slugify(new_slug)
if len(new_slug) < 2:
return jsonify({'success': False, 'message': 'URL slug must be at least 2 characters.'}), 422
# Only process if slug is actually changing
if new_slug != asset.slug:
# Check uniqueness
existing = DigitalAsset.query.filter(DigitalAsset.slug == new_slug, DigitalAsset.id != asset.id).first()
if existing:
return jsonify({'success': False, 'message': f"The URL '{new_slug}' is already in use by another asset."}), 422
# Store old slug in details for redirect support
asset.details = dict(asset.details or {})
old_slugs = asset.details.get('old_slugs', [])
if asset.slug not in old_slugs:
old_slugs.append(asset.slug)
asset.details['old_slugs'] = old_slugs
flag_modified(asset, 'details')
asset.slug = new_slug
# Update type-specific fields
if asset.asset_type == AssetType.TICKET:
event_details = data.get('eventDetails', {})
asset.event_location = event_details.get('link')
if event_details.get('date') and event_details.get('time'):
asset.event_date = datetime.strptime(f"{event_details['date']} {event_details['time']}", '%Y-%m-%d %H:%M')
asset.max_attendees = int(event_details.get('maxAttendees')) if event_details.get('maxAttendees') else None
elif asset.asset_type in [AssetType.SUBSCRIPTION, AssetType.NEWSLETTER]:
asset.details = data.get('details', asset.details)
db.session.commit()
return jsonify({'success': True, 'message': f"'{asset.title}' updated successfully.", 'slug': asset.slug})
except Exception as e:
db.session.rollback()
current_app.logger.error(f"Error updating asset {asset_id} via API: {e}")
return jsonify({'success': False, 'message': 'A server error occurred while saving.'}), 500
# --- RENDER THE VIEW/EDIT PAGE (GET request) ---
# Fetch recent purchases for this asset
recent_purchases = Purchase.query.filter_by(asset_id=asset.id).order_by(Purchase.purchase_date.desc()).limit(5).all()
# Fetch recent comments for this asset
recent_comments = Comment.query.filter_by(asset_id=asset.id).order_by(Comment.created_at.desc()).limit(5).all()
return render_template(
'admin/asset_view.html',
asset=asset,
recent_purchases=recent_purchases,
recent_comments=recent_comments,
statuses=[s.value for s in AssetStatus]
)
@admin_bp.route('/assets/save', methods=['POST'])
@creator_login_required
def save_asset():
try:
if 'asset_data' not in request.form:
raise ValueError("Form submission incomplete.")
form_data = json.loads(request.form['asset_data'])
asset_id = form_data.get('asset', {}).get('id')
if asset_id:
asset = DigitalAsset.query.filter_by(id=asset_id, creator_id=g.creator.id).first_or_404()
else:
asset = DigitalAsset(creator_id=g.creator.id)
save_asset_from_form(asset, request)
if not asset_id:
db.session.add(asset)
db.session.commit()
if request.headers.get('Accept') == 'application/json':
return jsonify({'success': True, 'message': f"Asset '{asset.title}' saved successfully!"})
flash(f"Asset '{asset.title}' saved successfully!", "success")
return redirect(url_for('admin.asset_edit', asset_id=asset.id))
except ValueError as e:
if request.headers.get('Accept') == 'application/json':
return jsonify({'success': False, 'message': str(e)}), 400
flash(str(e), 'danger')
return redirect(url_for('admin.asset_new'))
except Exception as e:
current_app.logger.error(f"Error saving asset: {e}")
if request.headers.get('Accept') == 'application/json':
return jsonify({'success': False, 'message': 'A server error occurred.'}), 500
flash("An error occurred while saving the asset.", "danger")
return redirect(url_for('admin.list_assets'))
@main_bp.route('/content/<int:file_id>')
def serve_content(file_id):
# Get the file and asset first to check if it's free
asset_file = AssetFile.query.get_or_404(file_id)
is_free = float(asset_file.asset.price) == 0
# Check if user is logged in
customer_phone = session.get('customer_phone')
creator_id = session.get('creator_id')
is_creator = creator_id and asset_file.asset.creator_id == creator_id
# STRICT SESSION CHECK: Ensure the session is fully verified, UNLESS it's a free asset or creator
if not is_creator:
if not customer_phone:
abort(403)
if not is_free and not session.get('is_verified'):
abort(403)
# For free assets with an unverified session, ensure they just bought THIS specific asset
if is_free and not session.get('is_verified'):
unverified_ids = session.get('unverified_purchase_ids', [])
# We must check if ANY purchase in their unverified list matches this asset
has_valid_unverified_purchase = False
if unverified_ids:
has_valid_unverified_purchase = Purchase.query.filter(
Purchase.id.in_(unverified_ids),
Purchase.asset_id == asset_file.asset_id,
Purchase.status == PurchaseStatus.COMPLETED
).first() is not None
if not has_valid_unverified_purchase:
abort(403)
# Check if user purchased the asset (if not creator)
purchase = None
if not is_creator:
customer = Customer.query.filter_by(whatsapp_number=customer_phone).first()
if not customer:
abort(403)
purchase = Purchase.query.filter_by(
customer_id=customer.id,
asset_id=asset_file.asset_id,
status=PurchaseStatus.COMPLETED
).order_by(Purchase.purchase_date.desc()).first()
if not purchase:
abort(403)
# Check subscription status
if purchase.asset.is_subscription:
is_active, expiry_date = check_subscription_status(purchase)
if not is_active:
flash(f"Your subscription expired on {expiry_date.strftime('%Y-%m-%d')}. Please renew to access this content.", "warning")
return redirect(url_for('main.asset_detail', slug=purchase.asset.slug))
# --- Content Date Enforcement ---
# Check publish date and expiry date encoded in the file's description
if not is_creator and asset_file.description:
import re
now = datetime.utcnow()
# Check publish date: content not yet available
date_match = re.search(r'\[Date:(\d{4}-\d{2}-\d{2})\]', asset_file.description)
if date_match:
publish_date = datetime.strptime(date_match.group(1), '%Y-%m-%d')
if now < publish_date:
flash("This content is not yet available.", "info")
return redirect(url_for('main.asset_detail', slug=asset_file.asset.slug))
# Check expiry date: content no longer available
expiry_match = re.search(r'\[Expiry:(\d{4}-\d{2}-\d{2})\]', asset_file.description)
if expiry_match:
expiry_date = datetime.strptime(expiry_match.group(1), '%Y-%m-%d')
if now > expiry_date:
flash("This content has expired and is no longer available.", "warning")
return redirect(url_for('main.asset_detail', slug=asset_file.asset.slug))
# Serve the file
# storage_path is stored as "secure_uploads/filename"
if asset_file.storage_path.startswith('secure_uploads/'):
filename = asset_file.storage_path.replace('secure_uploads/', '')
directory = current_app.config['SECURE_UPLOADS_DIR']
return send_from_directory(directory, filename)
else:
# It's an external link, redirect to it
return redirect(asset_file.storage_path)
@main_bp.route('/media/covers/<path:filename>')
def serve_cover_image(filename):
"""Serve cover images from the persistent user data directory with caching."""
response = send_from_directory(current_app.config['COVERS_DIR'], filename)
# 30-day browser cache β filenames include timestamps so re-uploads bust the cache
response.headers['Cache-Control'] = 'public, max-age=2592000, immutable'
return response
@main_bp.route('/media/logos/<path:filename>')
def serve_logo_image(filename):
"""Serve logo images from the persistent user data directory."""
return send_from_directory(current_app.config['LOGOS_DIR'], filename)
def check_subscription_status(purchase):
"""
Checks if a subscription purchase is still active.
Returns (is_active, expiry_date).
Handles both is_subscription assets and any purchase where the customer
selected a recurring tier (ticket_data['tier']['interval'] is set).
"""
has_tier_interval = (
purchase.ticket_data
and 'tier' in purchase.ticket_data
and purchase.ticket_data['tier'].get('interval')
)
if not purchase.asset.is_subscription and not has_tier_interval:
return True, None
start_date = purchase.purchase_date
interval = purchase.asset.subscription_interval.name.lower() if purchase.asset.subscription_interval else 'monthly'
if purchase.ticket_data and 'tier' in purchase.ticket_data:
interval = purchase.ticket_data['tier'].get('interval', interval).lower()
interval_map = {
'daily': timedelta(days=1),
'weekly': timedelta(days=7),
'biweekly': timedelta(days=14),
'monthly': timedelta(days=30),
'quarterly': timedelta(days=90),
'halfyearly': timedelta(days=183),
'yearly': timedelta(days=365),
}
delta = interval_map.get(interval, timedelta(days=30))
expiry_date = start_date + delta
is_active = datetime.utcnow() < expiry_date
return is_active, expiry_date
def save_asset_from_form(asset, req):
if 'asset_data' not in req.form: raise ValueError("Form submission incomplete. Please try again.")
form_data = json.loads(req.form['asset_data'])
asset_details = form_data.get('asset', {})
title = asset_details.get('title')
asset_type_enum_str = form_data.get('assetTypeEnum')
if not asset_type_enum_str: raise ValueError("No asset type selected. Please go back to Step 1.")
if not title or not title.strip(): raise ValueError("A Title is required. Please enter a title in Step 2.")
asset.asset_type = AssetType[asset_type_enum_str]
asset.title, asset.description, asset.story = title, asset_details.get('description'), asset_details.get('story_snippet')
if 'cover_image' in req.files:
file = req.files['cover_image']
if file and file.filename:
upload_path = current_app.config['COVERS_DIR']
filename_prefix = f"{asset.id or 'new'}_{int(datetime.now().timestamp())}"
try:
optimized_filename = optimize_cover_image(file, upload_path, filename_prefix)
asset.cover_image_url = f'/media/covers/{optimized_filename}'
except Exception as e:
# Fallback: save original file if optimization fails
current_app.logger.warning(f"Image optimization failed, saving original: {e}")
fallback_name = f"{filename_prefix}_{secure_filename(file.filename)}"
file.seek(0)
file.save(os.path.join(upload_path, fallback_name))
asset.cover_image_url = f'/media/covers/{fallback_name}'
pricing_data = form_data.get('pricing', {})
asset.price = decimal.Decimal(pricing_data.get('amount') or 0.0)
asset.is_subscription = pricing_data.get('type') == 'recurring'
asset.subscription_interval = SubscriptionInterval[pricing_data.get('billingCycle', 'monthly').upper()] if asset.is_subscription else None
# Handle allow_download setting (default to True if not explicitly set)
allow_download = form_data.get('allow_download')
if allow_download is not None:
asset.allow_download = bool(allow_download)
# Ensure details is a dictionary and create a copy to modify
asset.details = dict(asset.details or {})
# Store UZA Product ID for the asset
uza_product_id = asset_details.get('uza_product_id', '').strip()
if uza_product_id:
asset.details['uza_product_id'] = uza_product_id
# --- Slug Editing ---
new_slug = asset_details.get('slug', '').strip()
if new_slug and asset.id:
from slugify import slugify as _slugify
new_slug = _slugify(new_slug)
if len(new_slug) >= 2 and new_slug != asset.slug:
existing = DigitalAsset.query.filter(DigitalAsset.slug == new_slug, DigitalAsset.id != asset.id).first()
if not existing:
old_slugs = asset.details.get('old_slugs', [])
if asset.slug and asset.slug not in old_slugs:
old_slugs.append(asset.slug)
asset.details['old_slugs'] = old_slugs
asset.slug = new_slug
# Handle Custom Labels
if 'labels' in form_data:
asset.details['labels'] = form_data['labels']
# Handle Subscription Tiers (which may also have UZA Product IDs)
if asset.is_subscription:
asset.details['subscription_tiers'] = pricing_data.get('tiers', [])
if asset.asset_type == AssetType.TICKET:
event_details = form_data.get('eventDetails', {})
asset.event_location, asset.custom_fields = event_details.get('link'), form_data.get('customFields', [])
if event_details.get('date') and event_details.get('time'):
try: asset.event_date = datetime.strptime(f"{event_details['date']} {event_details['time']}", '%Y-%m-%d %H:%M')
except (ValueError, TypeError): asset.event_date = None
asset.max_attendees = int(event_details.get('maxAttendees')) if event_details.get('maxAttendees') else None
# Store post-purchase instructions
asset.details['postPurchaseInstructions'] = event_details.get('postPurchaseInstructions', '')
elif asset.asset_type == AssetType.SUBSCRIPTION:
# Merge existing details with subscription details
asset.details.update(form_data.get('subscriptionDetails', {}))
elif asset.asset_type == AssetType.NEWSLETTER:
# Merge existing details with newsletter details
asset.details.update(form_data.get('newsletterDetails', {}))
# Explicitly flag details as modified to ensure SQLAlchemy saves the JSON changes
flag_modified(asset, 'details')
# Preserve existing file paths if not re-uploaded
existing_files_map = {}
if asset.id:
existing_files = AssetFile.query.filter_by(asset_id=asset.id).all()
for f in existing_files:
existing_files_map[f.id] = {'path': f.storage_path, 'type': f.file_type}
AssetFile.query.filter_by(asset_id=asset.id).delete()
secure_upload_dir = current_app.config['SECURE_UPLOADS_DIR']
# os.makedirs(secure_upload_dir, exist_ok=True) # Already handled in config
for i, item in enumerate(form_data.get('contentItems', [])):
# Check for uploaded file
file_key = f'content_file_{i}'
uploaded_file = req.files.get(file_key)
storage_path = item.get('link', '')
file_type = None
if uploaded_file and uploaded_file.filename:
# Save new file
filename = secure_filename(uploaded_file.filename)
unique_filename = f"{int(datetime.now().timestamp())}_{filename}"
uploaded_file.save(os.path.join(secure_upload_dir, unique_filename))
storage_path = f"secure_uploads/{unique_filename}"
# Infer type from filename
extension = filename.split('.')[-1].lower()
elif storage_path:
# Check if it's a secure link that needs resolving
if storage_path.startswith('/content/'):
try:
old_file_id = int(storage_path.split('/')[-1])
if old_file_id in existing_files_map:
storage_path = existing_files_map[old_file_id]['path']
file_type = existing_files_map[old_file_id]['type']
except (ValueError, IndexError):
pass # Keep as is if parsing fails
# If we resolved it (or it was external), infer type if missing
if not file_type:
extension = storage_path.split('.')[-1].lower().split('?')[0]
else:
extension = ''
# Infer file type if not already set (from existing file)
if not file_type:
if extension in ['pdf']:
file_type = 'pdf'
elif extension in ['mp3', 'wav', 'ogg', 'm4a', 'aac']:
file_type = 'audio'
elif extension in ['mp4', 'webm', 'mov', 'avi']:
file_type = 'video'
elif extension in ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']:
file_type = 'image'
else:
file_type = 'other'
db.session.add(AssetFile(
asset=asset,
title=item.get('title'),
description=item.get('description'),
storage_path=storage_path,
file_type=file_type,
position=i
))
asset.status = AssetStatus.DRAFT if form_data.get('action') == 'draft' else AssetStatus.PUBLISHED
return asset
# --- API ENDPOINTS FOR ASSET ACTIONS ---
@admin_bp.route('/api/assets/bulk-action', methods=['POST'])
@creator_login_required
def assets_bulk_action():
data = request.get_json()
asset_ids, action = data.get('ids'), data.get('action')
if not asset_ids or not action: return jsonify({'success': False, 'message': 'Missing data.'}), 400
query = DigitalAsset.query.filter(DigitalAsset.id.in_(asset_ids), DigitalAsset.creator_id == g.creator.id)
if query.count() != len(asset_ids): return jsonify({'success': False, 'message': 'Authorization error or some assets not found.'}), 403
try:
if action == 'publish': query.update({'status': AssetStatus.PUBLISHED}); msg = f"{len(asset_ids)} asset(s) published."
elif action == 'draft': query.update({'status': AssetStatus.DRAFT}); msg = f"{len(asset_ids)} asset(s) moved to drafts."
elif action == 'archive': query.update({'status': AssetStatus.ARCHIVED}); msg = f"{len(asset_ids)} asset(s) archived."
elif action == 'delete': query.delete(synchronize_session=False); msg = f"{len(asset_ids)} asset(s) permanently deleted."
else: return jsonify({'success': False, 'message': 'Invalid action.'}), 400
db.session.commit()
return jsonify({'success': True, 'message': msg})
except Exception as e:
db.session.rollback(); current_app.logger.error(f"Bulk action error: {e}"); return jsonify({'success': False, 'message': 'A server error occurred.'}), 500
@admin_bp.route('/api/assets/<int:asset_id>/duplicate', methods=['POST'])
@creator_login_required
def duplicate_asset(asset_id):
original = DigitalAsset.query.filter_by(id=asset_id, creator_id=g.creator.id).first_or_404()
try:
new_asset = DigitalAsset(
creator_id=g.creator.id,
title=f"Copy of {original.title}",
status=AssetStatus.DRAFT,
description=original.description,
story=original.story,
cover_image_url=original.cover_image_url,
asset_type=original.asset_type,
price=original.price,
is_subscription=original.is_subscription,
subscription_interval=original.subscription_interval,
event_date=original.event_date,
event_location=original.event_location,
max_attendees=original.max_attendees,
custom_fields=original.custom_fields,
details=original.details
)
db.session.add(new_asset)
db.session.flush() # Get the ID for the new asset
# Duplicate files
for file in original.files:
db.session.add(AssetFile(
asset_id=new_asset.id,
title=file.title,
description=file.description,
storage_path=file.storage_path,
file_type=file.file_type,
position=file.position
))
db.session.commit()
return jsonify({'success': True, 'message': f"'{original.title}' was duplicated successfully."})
except Exception as e:
db.session.rollback(); current_app.logger.error(f"Duplication error: {e}"); return jsonify({'success': False, 'message': 'A server error occurred.'}), 500
@admin_bp.route('/supporters')
@creator_login_required
def supporters():
"""Fetches all customers and their aggregated data for the admin supporters page."""
# --- FILTERS & PAGINATION ---
page = request.args.get('page', 1, type=int)
search = request.args.get('search', '').strip()
asset_id = request.args.get('asset_id', type=int)
per_page = 20
# 1. Base Query to Find Supporter IDs (Efficient Filtering)
# Start with Customer to facilitate search on phone number
query = db.session.query(Customer.id).distinct().join(Purchase).join(DigitalAsset).filter(
DigitalAsset.creator_id == g.creator.id
)
if search:
# Search by phone number (whatsapp_number)
query = query.filter(Customer.whatsapp_number.ilike(f"%{search}%"))
if asset_id:
query = query.filter(Purchase.asset_id == asset_id)
# 2. Get TOTAL COUNT for pagination (before slicing logic, but wait, distinct makes count tricky)