Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
5353 lines (4411 loc) Β· 206 KB
/
Copy pathapp.py
File metadata and controls
5353 lines (4411 loc) Β· 206 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
import os
import sqlite3
import uuid
import json
import smtplib
import time
from datetime import datetime, timedelta
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify, send_file, render_template_string
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
import requests
import resend
from dotenv import load_dotenv
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
load_dotenv()
app = Flask(__name__)
# Template filters
@app.template_filter('get_product_images')
def get_product_images_filter(images_string):
return get_product_images(images_string)
@app.template_filter('from_json')
def from_json_filter(json_string):
try:
return json.loads(json_string)
except (json.JSONDecodeError, TypeError):
# Fallback for old comma-separated format
if json_string:
return [img.strip() for img in json_string.split(',') if img.strip()]
return []
# Image handling functions
ALLOWED_IMAGE_EXTENSIONS = {'jpg', 'jpeg', 'png', 'webp'}
MAX_IMAGE_SIZE = 5 * 1024 * 1024 # 5MB
def allowed_image_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_IMAGE_EXTENSIONS
def save_product_images(files):
"""Save multiple product images and return JSON list of filenames"""
if not files:
return None
saved_filenames = []
skipped_files = []
for file in files:
if file and file.filename and allowed_image_file(file.filename):
# Check file size
file.seek(0, 2) # Seek to end
file_size = file.tell()
file.seek(0) # Reset to beginning
if file_size <= MAX_IMAGE_SIZE:
# Generate unique filename
file_extension = file.filename.rsplit('.', 1)[1].lower()
unique_filename = f"{uuid.uuid4().hex}.{file_extension}"
file_path = os.path.join('static', 'products', unique_filename)
file.save(file_path)
saved_filenames.append(unique_filename)
else:
skipped_files.append(f"{file.filename} (too large)")
elif file and file.filename:
skipped_files.append(f"{file.filename} (invalid format)")
if skipped_files:
flash(f'Skipped files: {", ".join(skipped_files)}', 'warning')
return json.dumps(saved_filenames) if saved_filenames else None
def delete_product_images(images_json):
"""Delete product images from filesystem"""
if not images_json:
return
try:
image_filenames = json.loads(images_json)
for filename in image_filenames:
if filename:
file_path = os.path.join('static', 'products', filename)
try:
if os.path.exists(file_path):
os.remove(file_path)
print(f"β
Deleted image: {filename}")
except Exception as e:
print(f"β οΈ Could not delete image {filename}: {e}")
except json.JSONDecodeError:
# Fallback for old comma-separated format
image_filenames = images_json.split(',')
for filename in image_filenames:
if filename.strip():
file_path = os.path.join('static', 'products', filename.strip())
try:
if os.path.exists(file_path):
os.remove(file_path)
print(f"β
Deleted image: {filename}")
except Exception as e:
print(f"β οΈ Could not delete image {filename}: {e}")
def get_product_images(images_json):
"""Convert JSON string to list of image URLs"""
if not images_json:
return []
try:
image_filenames = json.loads(images_json)
return [f"/static/products/{img}" for img in image_filenames if img]
except json.JSONDecodeError:
# Fallback for old comma-separated format
return [f"/static/products/{img.strip()}" for img in images_json.split(',') if img.strip()]
def get_categories():
"""Get all categories"""
conn = get_db()
categories = conn.execute('SELECT * FROM categories ORDER BY name').fetchall()
conn.close()
return [dict(cat) for cat in categories]
def get_tags():
"""Get all tags"""
conn = get_db()
tags = conn.execute('SELECT * FROM tags ORDER BY name').fetchall()
conn.close()
return [dict(tag) for tag in tags]
def get_product_tags(product_id):
"""Get tags for a specific product"""
conn = get_db()
tags = conn.execute('''
SELECT t.* FROM tags t
JOIN product_tags pt ON t.id = pt.tag_id
WHERE pt.product_id = ?
ORDER BY t.name
''', (product_id,)).fetchall()
conn.close()
return [dict(tag) for tag in tags]
def get_bundles():
"""Get all bundles with their products"""
conn = get_db()
bundles = conn.execute('SELECT * FROM bundles ORDER BY name').fetchall()
bundle_list = []
for bundle in bundles:
bundle_dict = dict(bundle)
# Get products in this bundle
products = conn.execute('''
SELECT p.* FROM products p
JOIN bundle_products bp ON p.id = bp.product_id
WHERE bp.bundle_id = ?
''', (bundle['id'],)).fetchall()
bundle_dict['products'] = [dict(p) for p in products]
bundle_dict['image_urls'] = get_product_images(bundle['images'])
bundle_dict['main_image'] = bundle_dict['image_urls'][0] if bundle_dict['image_urls'] else None
bundle_list.append(bundle_dict)
conn.close()
return bundle_list
def calculate_bundle_price(bundle_id):
"""Calculate the total price of a bundle with discount"""
conn = get_db()
# Get bundle info
bundle = conn.execute('SELECT * FROM bundles WHERE id = ?', (bundle_id,)).fetchone()
if not bundle:
return 0
# Get total price of all products in bundle
total_price = conn.execute('''
SELECT SUM(p.price_dzd) FROM products p
JOIN bundle_products bp ON p.id = bp.product_id
WHERE bp.bundle_id = ?
''', (bundle_id,)).fetchone()[0] or 0
conn.close()
# Apply discount
if bundle['discount_percentage'] > 0:
discount = total_price * (bundle['discount_percentage'] / 100)
return max(0, total_price - discount)
elif bundle['discount_amount'] > 0:
return max(0, total_price - bundle['discount_amount'])
return total_price
app.secret_key = os.getenv('SECRET_KEY', 'your-secret-key-here')
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['PRODUCTS_FOLDER'] = 'products'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.config['STORE_NAME'] = os.getenv('STORE_NAME', 'Digital Store')
app.config['BASE_URL'] = os.getenv('BASE_URL', 'https://dzkeyz.onrender.com')
app.config['CONTACT_EMAIL'] = os.getenv('CONTACT_EMAIL', 'support@yourdomain.com')
app.config['TELEGRAM_LINK'] = os.getenv('TELEGRAM_LINK', 'https://t.me/StockilyBot')
# Ensure directories exist
os.makedirs('uploads', exist_ok=True)
os.makedirs('products', exist_ok=True)
os.makedirs('static', exist_ok=True)
os.makedirs('static/products', exist_ok=True)
os.makedirs('templates', exist_ok=True)
os.makedirs('receipts', exist_ok=True)
# Database setup
def init_db():
conn = sqlite3.connect('store.db')
c = conn.cursor()
# Categories table
c.execute('''CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
description TEXT,
icon TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)''')
# Tags table
c.execute('''CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
color TEXT DEFAULT '#007bff',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)''')
# Bundles table
c.execute('''CREATE TABLE IF NOT EXISTS bundles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
discount_percentage REAL DEFAULT 0,
discount_amount REAL DEFAULT 0,
is_visible BOOLEAN DEFAULT TRUE,
images TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)''')
# Bundle products relationship table
c.execute('''CREATE TABLE IF NOT EXISTS bundle_products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
bundle_id INTEGER,
product_id INTEGER,
FOREIGN KEY (bundle_id) REFERENCES bundles (id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
UNIQUE(bundle_id, product_id)
)''')
# Products table
c.execute('''CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
price_dzd REAL NOT NULL,
stock_count INTEGER DEFAULT 0,
type TEXT CHECK(type IN ('key', 'file', 'bundle')) NOT NULL,
file_or_key_path TEXT,
images TEXT,
category_id INTEGER,
is_visible BOOLEAN DEFAULT TRUE,
is_featured BOOLEAN DEFAULT FALSE,
stock_limit INTEGER DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories (id)
)''')
# Product tags relationship table
c.execute('''CREATE TABLE IF NOT EXISTS product_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER,
tag_id INTEGER,
FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
FOREIGN KEY (tag_id) REFERENCES tags (id) ON DELETE CASCADE,
UNIQUE(product_id, tag_id)
)''')
# Add new columns to existing products table if they don't exist
new_columns = [
('category_id', 'INTEGER'),
('is_visible', 'BOOLEAN DEFAULT TRUE'),
('is_featured', 'BOOLEAN DEFAULT FALSE'),
('stock_limit', 'INTEGER DEFAULT NULL'),
('images', 'TEXT')
]
for column_name, column_def in new_columns:
try:
c.execute(f'ALTER TABLE products ADD COLUMN {column_name} {column_def}')
except sqlite3.OperationalError:
# Column already exists
pass
# Product keys table for individual key management
c.execute('''CREATE TABLE IF NOT EXISTS product_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER,
key_value TEXT NOT NULL,
is_used BOOLEAN DEFAULT FALSE,
used_by_order_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
used_at TIMESTAMP,
FOREIGN KEY (product_id) REFERENCES products (id),
FOREIGN KEY (used_by_order_id) REFERENCES orders (id)
)''')
# Orders table
c.execute('''CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER,
user_id INTEGER,
buyer_name TEXT NOT NULL,
email TEXT NOT NULL,
phone TEXT,
telegram_username TEXT,
payment_method TEXT CHECK(payment_method IN ('baridimob', 'ccp')),
payment_proof_path TEXT,
transaction_id TEXT,
status TEXT CHECK(status IN ('pending', 'confirmed', 'rejected')) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
confirmed_at TIMESTAMP,
FOREIGN KEY (product_id) REFERENCES products (id),
FOREIGN KEY (user_id) REFERENCES users (id)
)''')
# Add phone column if it doesn't exist (for existing databases)
try:
c.execute('ALTER TABLE orders ADD COLUMN phone TEXT')
except sqlite3.OperationalError:
# Column already exists
pass
# Add user_id column if it doesn't exist (for existing databases)
try:
c.execute('ALTER TABLE orders ADD COLUMN user_id INTEGER')
except sqlite3.OperationalError:
# Column already exists
pass
# Add activation columns to users table if they don't exist (for existing databases)
try:
c.execute('ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT FALSE')
except sqlite3.OperationalError:
# Column already exists
pass
try:
c.execute('ALTER TABLE users ADD COLUMN activation_token TEXT')
except sqlite3.OperationalError:
# Column already exists
pass
# Contact messages table
c.execute('''CREATE TABLE IF NOT EXISTS contact_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL,
subject TEXT NOT NULL,
message TEXT NOT NULL,
attachment_path TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status TEXT DEFAULT 'new' CHECK(status IN ('new', 'read', 'replied'))
)''')
# Add receipt_path column if it doesn't exist (for existing databases)
try:
c.execute('ALTER TABLE orders ADD COLUMN receipt_path TEXT')
except sqlite3.OperationalError:
# Column already exists
pass
# Audit log table
c.execute('''CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id INTEGER,
action TEXT NOT NULL,
actor TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
note TEXT,
FOREIGN KEY (order_id) REFERENCES orders (id)
)''')
# Users table for customer accounts - REBUILT
c.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
is_active BOOLEAN DEFAULT FALSE,
is_admin BOOLEAN DEFAULT FALSE,
activation_token TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)''')
# Add new columns to existing users table if they don't exist
user_columns = [
('is_admin', 'BOOLEAN DEFAULT FALSE'),
]
for column_name, column_def in user_columns:
try:
c.execute(f'ALTER TABLE users ADD COLUMN {column_name} {column_def}')
print(f"β
Added column {column_name} to users table")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower():
print(f"β
Column {column_name} already exists")
else:
print(f"β οΈ Error adding column {column_name}: {e}")
# Continue anyway
# Admin table
c.execute('''CREATE TABLE IF NOT EXISTS admin (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL
)''')
# Download tokens table for secure file downloads
c.execute('''CREATE TABLE IF NOT EXISTS download_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token TEXT UNIQUE NOT NULL,
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
file_path TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL,
is_used BOOLEAN DEFAULT FALSE,
used_at TIMESTAMP,
download_count INTEGER DEFAULT 0,
max_downloads INTEGER DEFAULT 3,
FOREIGN KEY (order_id) REFERENCES orders (id),
FOREIGN KEY (product_id) REFERENCES products (id)
)''')
# Landing pages table for custom promo pages
c.execute('''CREATE TABLE IF NOT EXISTS landing_pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
slug TEXT UNIQUE NOT NULL,
description TEXT,
banner_image TEXT,
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)''')
# Landing page products relationship
c.execute('''CREATE TABLE IF NOT EXISTS landing_page_products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
landing_page_id INTEGER,
product_id INTEGER,
display_order INTEGER DEFAULT 0,
FOREIGN KEY (landing_page_id) REFERENCES landing_pages (id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE
)''')
# Store branding settings
c.execute('''CREATE TABLE IF NOT EXISTS store_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
setting_key TEXT UNIQUE NOT NULL,
setting_value TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)''')
# Reviews table
c.execute('''CREATE TABLE IF NOT EXISTS reviews (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
rating INTEGER NOT NULL CHECK(rating >= 1 AND rating <= 5),
comment TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (product_id) REFERENCES products (id),
UNIQUE(user_id, product_id)
)''')
# Wishlists table
c.execute('''CREATE TABLE IF NOT EXISTS wishlists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (product_id) REFERENCES products (id),
UNIQUE(user_id, product_id)
)''')
# Social login providers
c.execute('''CREATE TABLE IF NOT EXISTS user_social_accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
provider TEXT NOT NULL,
provider_id TEXT NOT NULL,
provider_email TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
UNIQUE(provider, provider_id)
)''')
# Add login_method column to users table if it doesn't exist
try:
c.execute('ALTER TABLE users ADD COLUMN login_method TEXT DEFAULT "email"')
except sqlite3.OperationalError:
# Column already exists
pass
# Add special offers columns to products table if they don't exist
try:
c.execute('ALTER TABLE products ADD COLUMN special_offer BOOLEAN DEFAULT FALSE')
except sqlite3.OperationalError:
# Column already exists
pass
try:
c.execute('ALTER TABLE products ADD COLUMN offer_label TEXT')
except sqlite3.OperationalError:
# Column already exists
pass
try:
c.execute('ALTER TABLE products ADD COLUMN banner_image TEXT')
except sqlite3.OperationalError:
# Column already exists
pass
try:
c.execute('ALTER TABLE products ADD COLUMN offer_order INTEGER DEFAULT 0')
except sqlite3.OperationalError:
# Column already exists
pass
# Create default admin if not exists
c.execute('SELECT COUNT(*) FROM admin')
if c.fetchone()[0] == 0:
admin_hash = generate_password_hash('admin123')
c.execute('INSERT INTO admin (username, password_hash) VALUES (?, ?)', ('admin', admin_hash))
# Create indexes for performance optimization
try:
# Optimize homepage products query
c.execute('CREATE INDEX IF NOT EXISTS idx_products_visible_featured ON products(is_visible, is_featured, created_at)')
# Optimize order lookups
c.execute('CREATE INDEX IF NOT EXISTS idx_orders_product_id ON orders(product_id)')
c.execute('CREATE INDEX IF NOT EXISTS idx_orders_user_id ON orders(user_id)')
# Optimize product stock checks
c.execute('CREATE INDEX IF NOT EXISTS idx_product_keys_status ON product_keys(product_id, is_used)')
# Optimize reviews lookup
c.execute('CREATE INDEX IF NOT EXISTS idx_reviews_product ON reviews(product_id)')
print("β
Database indexes created/verified")
except Exception as e:
print(f"β οΈ Error creating indexes: {e}")
conn.commit()
conn.close()
# Initialize database when app starts
try:
init_db()
print("β
Database initialized successfully")
except Exception as e:
print(f"β οΈ Database initialization warning: {e}")
# Continue anyway - database might already exist
def get_db():
conn = sqlite3.connect('store.db')
conn.row_factory = sqlite3.Row
return conn
def log_action(order_id, action, actor, note=None):
conn = get_db()
conn.execute('INSERT INTO audit_log (order_id, action, actor, note) VALUES (?, ?, ?, ?)',
(order_id, action, actor, note))
conn.commit()
conn.close()
def generate_receipt_pdf(order_data):
"""Generate professional branded PDF receipt for confirmed order"""
try:
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
from datetime import datetime
# Create filename
receipt_filename = f"receipt_{order_data['id']}.pdf"
receipt_path = os.path.join('receipts', receipt_filename)
# Create PDF document
doc = SimpleDocTemplate(receipt_path, pagesize=letter,
rightMargin=50, leftMargin=50,
topMargin=50, bottomMargin=50)
# Container for the 'Flowable' objects
elements = []
# Get styles
styles = getSampleStyleSheet()
# Custom styles
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=24,
spaceAfter=30,
textColor=colors.HexColor('#2c3e50'),
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
subtitle_style = ParagraphStyle(
'CustomSubtitle',
parent=styles['Heading2'],
fontSize=16,
spaceAfter=20,
textColor=colors.HexColor('#34495e'),
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
header_style = ParagraphStyle(
'CustomHeader',
parent=styles['Heading3'],
fontSize=14,
spaceAfter=10,
textColor=colors.HexColor('#2c3e50'),
fontName='Helvetica-Bold'
)
normal_style = ParagraphStyle(
'CustomNormal',
parent=styles['Normal'],
fontSize=11,
spaceAfter=6,
textColor=colors.HexColor('#2c3e50')
)
# Store information
store_name = os.getenv('STORE_NAME', 'Espamoda')
# Header with store branding
elements.append(Paragraph(f"π€ {store_name}", title_style))
elements.append(Paragraph("RECEIPT", subtitle_style))
elements.append(Spacer(1, 20))
# Order information section
elements.append(Paragraph("Order Information", header_style))
order_info_data = [
['Order ID:', f"#{order_data['id']}"],
['Date:', datetime.now().strftime('%B %d, %Y at %I:%M %p')],
['Status:', 'CONFIRMED β
'],
]
order_table = Table(order_info_data, colWidths=[2*inch, 4*inch])
order_table.setStyle(TableStyle([
('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
('FONTSIZE', (0, 0), (-1, -1), 11),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('TEXTCOLOR', (0, 0), (-1, -1), colors.HexColor('#2c3e50')),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
('LEFTPADDING', (0, 0), (-1, -1), 0),
('RIGHTPADDING', (0, 0), (-1, -1), 0),
('TOPPADDING', (0, 0), (-1, -1), 3),
('BOTTOMPADDING', (0, 0), (-1, -1), 3),
]))
elements.append(order_table)
elements.append(Spacer(1, 20))
# Customer information section
elements.append(Paragraph("Customer Information", header_style))
customer_data = [
['Name:', order_data['buyer_name']],
['Email:', order_data['email']],
['Phone:', order_data['phone'] or 'Not provided'],
['Telegram:', f"@{order_data['telegram_username']}" if order_data['telegram_username'] else 'Not provided'],
]
customer_table = Table(customer_data, colWidths=[2*inch, 4*inch])
customer_table.setStyle(TableStyle([
('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
('FONTSIZE', (0, 0), (-1, -1), 11),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('TEXTCOLOR', (0, 0), (-1, -1), colors.HexColor('#2c3e50')),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
('LEFTPADDING', (0, 0), (-1, -1), 0),
('RIGHTPADDING', (0, 0), (-1, -1), 0),
('TOPPADDING', (0, 0), (-1, -1), 3),
('BOTTOMPADDING', (0, 0), (-1, -1), 3),
]))
elements.append(customer_table)
elements.append(Spacer(1, 20))
# Product and payment section
elements.append(Paragraph("Order Summary", header_style))
# Product details table
product_data = [
['Product', 'Quantity', 'Price'],
[order_data['product_name'], '1', f"{order_data['price_dzd']:,.0f} DZD"],
]
product_table = Table(product_data, colWidths=[3*inch, 1*inch, 2*inch])
product_table.setStyle(TableStyle([
# Header row
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34495e')),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 12),
('ALIGN', (0, 0), (-1, 0), 'CENTER'),
# Data rows
('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
('FONTSIZE', (0, 1), (-1, -1), 11),
('TEXTCOLOR', (0, 1), (-1, -1), colors.HexColor('#2c3e50')),
('ALIGN', (1, 1), (1, -1), 'CENTER'),
('ALIGN', (2, 1), (2, -1), 'RIGHT'),
# Grid
('GRID', (0, 0), (-1, -1), 1, colors.HexColor('#bdc3c7')),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('TOPPADDING', (0, 0), (-1, -1), 8),
('BOTTOMPADDING', (0, 0), (-1, -1), 8),
]))
elements.append(product_table)
elements.append(Spacer(1, 15))
# Total section
total_data = [
['', 'Total Amount:', f"{order_data['price_dzd']:,.0f} DZD"],
]
total_table = Table(total_data, colWidths=[3*inch, 1*inch, 2*inch])
total_table.setStyle(TableStyle([
('FONTNAME', (1, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (1, 0), (-1, 0), 14),
('TEXTCOLOR', (1, 0), (-1, 0), colors.HexColor('#27ae60')),
('ALIGN', (1, 0), (1, 0), 'CENTER'),
('ALIGN', (2, 0), (2, 0), 'RIGHT'),
('TOPPADDING', (0, 0), (-1, -1), 8),
('BOTTOMPADDING', (0, 0), (-1, -1), 8),
('LINEBELOW', (1, 0), (-1, 0), 2, colors.HexColor('#27ae60')),
]))
elements.append(total_table)
elements.append(Spacer(1, 20))
# Payment information
elements.append(Paragraph("Payment Information", header_style))
payment_data = [
['Payment Method:', order_data['payment_method'].upper()],
['Payment Status:', 'CONFIRMED β
'],
['Confirmation Date:', order_data['confirmed_at'][:19] if order_data['confirmed_at'] else datetime.now().strftime('%Y-%m-%d %H:%M:%S')],
]
payment_table = Table(payment_data, colWidths=[2*inch, 4*inch])
payment_table.setStyle(TableStyle([
('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
('FONTSIZE', (0, 0), (-1, -1), 11),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('TEXTCOLOR', (0, 0), (-1, -1), colors.HexColor('#2c3e50')),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
('LEFTPADDING', (0, 0), (-1, -1), 0),
('RIGHTPADDING', (0, 0), (-1, -1), 0),
('TOPPADDING', (0, 0), (-1, -1), 3),
('BOTTOMPADDING', (0, 0), (-1, -1), 3),
]))
elements.append(payment_table)
elements.append(Spacer(1, 30))
# Thank you footer
footer_style = ParagraphStyle(
'Footer',
parent=styles['Normal'],
fontSize=14,
textColor=colors.HexColor('#e74c3c'),
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
elements.append(Paragraph("Thank you for shopping with Espamoda π€", footer_style))
elements.append(Spacer(1, 10))
# Additional footer info
footer_info_style = ParagraphStyle(
'FooterInfo',
parent=styles['Normal'],
fontSize=10,
textColor=colors.HexColor('#7f8c8d'),
alignment=TA_CENTER
)
elements.append(Paragraph("This is an official receipt for your purchase.", footer_info_style))
elements.append(Paragraph("For support, please contact us with your order ID.", footer_info_style))
# Build PDF
doc.build(elements)
print(f"β
Professional PDF receipt generated: {receipt_path}")
return receipt_path
except Exception as e:
print(f"β Professional PDF generation failed: {e}")
import traceback
traceback.print_exc()
# Fallback to simple PDF
try:
receipt_filename = f"receipt_{order_data['id']}.pdf"
receipt_path = os.path.join('receipts', receipt_filename)
c = canvas.Canvas(receipt_path, pagesize=letter)
width, height = letter
store_name = os.getenv('STORE_NAME', 'Espamoda')
c.setFont("Helvetica-Bold", 20)
c.drawString(50, height - 50, f"π€ {store_name}")
c.setFont("Helvetica-Bold", 16)
c.drawString(50, height - 80, "RECEIPT")
c.setFont("Helvetica", 12)
y_position = height - 120
details = [
f"Order ID: #{order_data['id']}",
f"Customer: {order_data['buyer_name']}",
f"Email: {order_data['email']}",
f"Product: {order_data['product_name']}",
f"Amount: {order_data['price_dzd']:,.0f} DZD",
f"Payment: {order_data['payment_method'].upper()}",
f"Status: CONFIRMED",
"",
"Thank you for shopping with Espamoda π€"
]
for detail in details:
c.drawString(50, y_position, detail)
y_position -= 20
c.save()
print(f"β
Fallback PDF receipt generated: {receipt_path}")
return receipt_path
except Exception as fallback_error:
print(f"β Fallback PDF generation also failed: {fallback_error}")
return None
def format_professional_email(customer_name, content, email_type="general"):
"""Format email content using the professional template you liked"""
store_name = os.getenv('STORE_NAME', 'Espamoda')
# Professional greeting
greeting = f"Dear {customer_name}," if customer_name else "Dear Customer,"
# Professional closing based on email type
if email_type == "order_confirmation":
closing = f"""Features:
- Faster delivery times
- Better inbox placement
- More reliable service
- Professional email formatting
Thank you for choosing {store_name}!
Best regards,
{store_name} Team"""
elif email_type == "order_received":
closing = f"""Features:
- Secure payment processing
- Fast order verification
- Professional customer service
- Reliable delivery system
We appreciate your business!
Best regards,
{store_name} Team"""
elif email_type == "order_rejection":
closing = f"""Our Commitment:
- Transparent communication
- Fair payment verification
- Professional customer service
- Quick issue resolution
We value your understanding and look forward to serving you better.
Best regards,
{store_name} Support Team"""
elif email_type == "account_activation":
closing = f"""Account Benefits:
- Track all your orders in one place
- Faster checkout with saved information
- Access download links anytime
- Professional customer support
Welcome to {store_name}!
Best regards,
{store_name} Team"""
else:
closing = f"""Features:
- Faster delivery times
- Better inbox placement
- More reliable service
- Professional email formatting
Best regards,
{store_name} Team"""
# Combine all parts
formatted_content = f"""{greeting}
{content}
{closing}"""
return formatted_content
def send_activation_email(user_email, user_name, activation_link):
"""Send activation email using direct Resend API calls"""
try:
import requests
resend_key = os.getenv('RESEND_API_KEY')
if not resend_key:
print("β RESEND_API_KEY not found in environment")
return False
print(f"π§ Sending activation email to: {user_email}")
print(f"π§ Activation link: {activation_link}")
print(f"π§ API Key: {resend_key[:10]}...{resend_key[-4:]}")
# Email data
data = {
"from": "Espamoda <info@espamoda.store>",
"to": [user_email],
"subject": "Activate your DZKeyz Account",
"html": f"""
<div style='font-family:Arial,sans-serif;padding:20px;background:#fff;border-radius:8px;border:1px solid #eee;max-width:600px;margin:auto'>
<h2 style='color:#111;margin-bottom:20px'>Welcome to DZKeyz π</h2>
<p style='font-size:16px;color:#333;margin-bottom:20px'>Hi {user_name},</p>
<p style='font-size:16px;color:#333;margin-bottom:20px'>Click the button below to activate your account and start shopping securely:</p>
<div style='text-align:center;margin:30px 0'>
<a href="{activation_link}" style='background:#111;color:#fff;padding:12px 24px;border-radius:6px;text-decoration:none;font-weight:bold;display:inline-block'>Activate Account</a>
</div>
<p style='font-size:14px;color:#666;margin-top:30px'>If you didn't create this account, you can safely ignore this email.</p>
<hr style='border:none;border-top:1px solid #eee;margin:20px 0'>
<p style='font-size:12px;color:#999;text-align:center'>DZKeyz - Your trusted digital game store</p>
</div>
""",
"text": f"Welcome to DZKeyz! Please visit this link to activate your account: {activation_link}"
}
# Send via Resend API
headers = {
"Authorization": f"Bearer {resend_key}",
"Content-Type": "application/json"
}
response = requests.post("https://api.resend.com/emails", json=data, headers=headers)
if response.status_code == 200:
result = response.json()
print(f"β
Email sent successfully! ID: {result.get('id', 'Unknown')}")
return True
else:
print(f"β Email sending failed: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"β Email sending error: {e}")
import traceback
traceback.print_exc()
return False
def send_email(to, subject, body, customer_name=None, email_type="general", attachment_path=None):