Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
845 lines (719 loc) · 35 KB
/
Copy pathdatabase.py
File metadata and controls
845 lines (719 loc) · 35 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
import sqlite3
import os
import datetime
import uuid
import hashlib
class Database:
def __init__(self, db_file="inventory.db"):
"""Initialize database connection and create tables if they don't exist"""
self.db_file = db_file
self.conn = None
self.create_connection()
self.create_tables()
def create_connection(self):
"""Create a database connection to the SQLite database"""
try:
self.conn = sqlite3.connect(self.db_file)
self.conn.execute("PRAGMA foreign_keys = ON")
return True
except sqlite3.Error as e:
print(f"Database connection error: {e}")
return False
def close_connection(self):
"""Close the database connection"""
if self.conn:
self.conn.close()
def create_tables(self):
"""Create all necessary tables for the inventory management system"""
try:
cursor = self.conn.cursor()
# Users table (for admin and employees)
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT,
role TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Products table
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_code TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
description TEXT,
cost_price REAL NOT NULL,
selling_price REAL NOT NULL,
max_discount REAL DEFAULT 0,
store_quantity INTEGER DEFAULT 0,
warehouse_quantity INTEGER DEFAULT 0,
category TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Product Items table (for individual items with QR codes)
cursor.execute('''
CREATE TABLE IF NOT EXISTS product_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER NOT NULL,
item_unique_id TEXT UNIQUE NOT NULL,
qr_code_path TEXT,
status TEXT DEFAULT 'in_store', -- in_store, sold, in_warehouse
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE
)
''')
# Customers table
cursor.execute('''
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
phone TEXT,
email TEXT,
address TEXT,
gst_number TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Sales table
cursor.execute('''
CREATE TABLE IF NOT EXISTS sales (
id INTEGER PRIMARY KEY AUTOINCREMENT,
invoice_number TEXT UNIQUE NOT NULL,
customer_id INTEGER,
user_id INTEGER NOT NULL,
sale_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
total_amount REAL NOT NULL,
discount_amount REAL DEFAULT 0,
tax_amount REAL DEFAULT 0,
final_amount REAL NOT NULL,
payment_method TEXT,
gst_included BOOLEAN DEFAULT 0,
FOREIGN KEY (customer_id) REFERENCES customers (id),
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
# Sale Items table
cursor.execute('''
CREATE TABLE IF NOT EXISTS sale_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sale_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
product_item_id INTEGER,
quantity INTEGER NOT NULL,
price_per_unit REAL NOT NULL,
discount_percentage REAL DEFAULT 0,
total_price REAL NOT NULL,
FOREIGN KEY (sale_id) REFERENCES sales (id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (id),
FOREIGN KEY (product_item_id) REFERENCES product_items (id)
)
''')
# Inventory Transactions table (for tracking all inventory changes)
cursor.execute('''
CREATE TABLE IF NOT EXISTS inventory_transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER NOT NULL,
transaction_type TEXT NOT NULL, -- add_to_store, add_to_warehouse, sell, transfer, restock
quantity INTEGER NOT NULL,
from_location TEXT, -- store, warehouse, supplier
to_location TEXT, -- store, warehouse, customer
user_id INTEGER NOT NULL,
transaction_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
notes TEXT,
FOREIGN KEY (product_id) REFERENCES products (id),
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
self.conn.commit()
# Insert default admin user if not exists
cursor.execute("SELECT COUNT(*) FROM users WHERE username = 'admin'")
if cursor.fetchone()[0] == 0:
admin_password = hashlib.sha256("sam3804".encode()).hexdigest()
cursor.execute("INSERT INTO users (username, password, role) VALUES (?, ?, ?)",
("admin", admin_password, "admin"))
# Insert default employee user
cursor.execute("INSERT INTO users (username, password, role) VALUES (?, ?, ?)",
("employee", "", "employee"))
self.conn.commit()
except sqlite3.Error as e:
print(f"Table creation error: {e}")
# User management methods
def authenticate_user(self, username, password=""):
"""Authenticate a user based on username and password"""
try:
cursor = self.conn.cursor()
if username == "employee" and password == "":
cursor.execute("SELECT id, username, role FROM users WHERE username = ? AND role = 'employee'", (username,))
return cursor.fetchone()
else:
hashed_password = hashlib.sha256(password.encode()).hexdigest()
cursor.execute("SELECT id, username, role FROM users WHERE username = ? AND password = ?",
(username, hashed_password))
return cursor.fetchone()
except sqlite3.Error as e:
print(f"Authentication error: {e}")
return None
# Product management methods
def add_product(self, product_data):
"""Add a new product to the database"""
try:
cursor = self.conn.cursor()
# Generate a unique product code if not provided
if not product_data.get('product_code'):
prefix = product_data.get('category', 'GEN')[:3].upper()
product_data['product_code'] = f"{prefix}{uuid.uuid4().hex[:8].upper()}"
cursor.execute('''
INSERT INTO products (product_code, name, description, cost_price, selling_price,
max_discount, store_quantity, warehouse_quantity, category)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (product_data['product_code'], product_data['name'],
product_data.get('description', ''),
product_data.get('cost_price', 0),
product_data.get('selling_price', 0),
product_data.get('max_discount', 0),
product_data.get('store_quantity', 0),
product_data.get('warehouse_quantity', 0),
product_data.get('category', 'General')))
product_id = cursor.lastrowid
self.conn.commit()
# Generate individual product items with QR codes if store quantity > 0
if product_data.get('store_quantity', 0) > 0:
qr_paths = self.generate_product_items(product_id, product_data['store_quantity'])
print(f"Generated {len(qr_paths)} QR codes for new product")
return product_id
except sqlite3.Error as e:
print(f"Add product error: {e}")
self.conn.rollback()
return None
def update_product(self, product_id, product_data):
"""Update an existing product"""
try:
cursor = self.conn.cursor()
# Get current product data
cursor.execute("SELECT store_quantity, warehouse_quantity FROM products WHERE id = ?", (product_id,))
current_data = cursor.fetchone()
if not current_data:
return False
current_store_qty, current_warehouse_qty = current_data
new_store_qty = product_data.get('store_quantity', current_store_qty)
new_warehouse_qty = product_data.get('warehouse_quantity', current_warehouse_qty)
# Calculate quantity changes
store_qty_change = new_store_qty - current_store_qty
warehouse_qty_change = new_warehouse_qty - current_warehouse_qty
# Handle transfer from warehouse to store if needed
if store_qty_change > 0 and warehouse_qty_change < 0 and abs(warehouse_qty_change) >= store_qty_change:
# This is a transfer from warehouse to store
transfer_qty = store_qty_change
new_warehouse_qty = current_warehouse_qty - transfer_qty
# Generate new product items for the transferred items
if transfer_qty > 0:
qr_paths = self.generate_product_items(product_id, transfer_qty)
print(f"Generated {len(qr_paths)} QR codes for transferred items")
# Record the transfer transaction
cursor.execute('''
INSERT INTO inventory_transactions
(product_id, transaction_type, quantity, from_location, to_location, user_id, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (product_id, 'transfer', transfer_qty, 'warehouse', 'store', 1, 'Transfer from warehouse to store'))
# Handle direct warehouse quantity update (restocking)
elif warehouse_qty_change > 0 and store_qty_change == 0:
# This is a warehouse restock
cursor.execute('''
INSERT INTO inventory_transactions
(product_id, transaction_type, quantity, from_location, to_location, user_id, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (product_id, 'restock', warehouse_qty_change, 'supplier', 'warehouse', 1, 'Warehouse restock'))
# Handle direct store quantity addition (without warehouse transfer)
elif store_qty_change > 0 and warehouse_qty_change == 0:
# Generate new product items for the new store items
qr_paths = self.generate_product_items(product_id, store_qty_change)
print(f"Generated {len(qr_paths)} QR codes for new store items")
cursor.execute('''
INSERT INTO inventory_transactions
(product_id, transaction_type, quantity, from_location, to_location, user_id, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (product_id, 'add_to_store', store_qty_change, 'supplier', 'store', 1, 'Direct store addition'))
# Update the product record
cursor.execute('''
UPDATE products SET
name = COALESCE(?, name),
description = COALESCE(?, description),
cost_price = COALESCE(?, cost_price),
selling_price = COALESCE(?, selling_price),
max_discount = COALESCE(?, max_discount),
store_quantity = ?,
warehouse_quantity = ?,
category = COALESCE(?, category),
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
''', (product_data.get('name'), product_data.get('description'),
product_data.get('cost_price'), product_data.get('selling_price'),
product_data.get('max_discount'), new_store_qty, new_warehouse_qty,
product_data.get('category'), product_id))
self.conn.commit()
return True
except sqlite3.Error as e:
print(f"Update product error: {e}")
self.conn.rollback()
return False
def generate_product_items(self, product_id, quantity, status='in_store'):
"""Generate individual product items with unique IDs and QR codes
Args:
product_id: The ID of the product
quantity: Number of items to generate
status: Status of the items (default: 'in_store')
Returns:
True if successful, False otherwise
"""
try:
import os
import uuid
from qr_manager import QRManager
cursor = self.conn.cursor()
# Get product code and name
cursor.execute("SELECT product_code, name FROM products WHERE id = ?",(product_id,))
product_info = cursor.fetchone()
product_code = product_info[0]
product_name = product_info[1]
# Create QR codes directory if it doesn't exist
qr_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qr_codes")
if not os.path.exists(qr_dir):
os.makedirs(qr_dir)
# Initialize QR manager
qr_manager = QRManager(qr_dir=qr_dir)
# Generate items
qr_paths = []
for i in range(quantity):
# Generate a unique 12-character ID for the item
unique_id = f"{product_code}I{uuid.uuid4().hex[:8].upper()}"
# QR code path
qr_path = os.path.join(qr_dir, f"{unique_id}.png")
# Generate the actual QR code image
qr_manager.generate_qr_code(unique_id, product_name, qr_path)
qr_paths.append(qr_path)
# Insert the item
cursor.execute('''
INSERT INTO product_items (product_id, item_unique_id, qr_code_path, status)
VALUES (?, ?, ?, ?)
''', (product_id, unique_id, qr_path, status))
self.conn.commit()
return qr_paths
except Exception as e:
print(f"Generate product items error: {e}")
self.conn.rollback()
return []
def get_all_products(self):
"""Get all products from the database"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT id, product_code, name, description, cost_price, selling_price,
max_discount, store_quantity, warehouse_quantity, category,
created_at, updated_at
FROM products
ORDER BY name
''')
columns = [column[0] for column in cursor.description]
products = [dict(zip(columns, row)) for row in cursor.fetchall()]
return products
except sqlite3.Error as e:
print(f"Get products error: {e}")
return []
def get_product_by_id(self, product_id):
"""Get a product by its ID"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT id, product_code, name, description, cost_price, selling_price,
max_discount, store_quantity, warehouse_quantity, category,
created_at, updated_at
FROM products
WHERE id = ?
''', (product_id,))
columns = [column[0] for column in cursor.description]
row = cursor.fetchone()
if row:
return dict(zip(columns, row))
return None
except sqlite3.Error as e:
print(f"Get product error: {e}")
return None
def get_product_by_code(self, product_code):
"""Get a product by its code"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT id, product_code, name, description, cost_price, selling_price,
max_discount, store_quantity, warehouse_quantity, category,
created_at, updated_at
FROM products
WHERE product_code = ?
''', (product_code,))
columns = [column[0] for column in cursor.description]
row = cursor.fetchone()
if row:
return dict(zip(columns, row))
return None
except sqlite3.Error as e:
print(f"Get product error: {e}")
return None
def get_product_item_by_id(self, item_unique_id):
"""Get a product item by its unique ID"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT pi.id, pi.product_id, pi.item_unique_id, pi.qr_code_path, pi.status,
p.name, p.product_code, p.selling_price, p.max_discount
FROM product_items pi
JOIN products p ON pi.product_id = p.id
WHERE pi.item_unique_id = ? AND pi.status = 'in_store'
''', (item_unique_id,))
columns = [column[0] for column in cursor.description]
row = cursor.fetchone()
if row:
return dict(zip(columns, row))
return None
except sqlite3.Error as e:
print(f"Get product item error: {e}")
return None
# Customer management methods
def add_customer(self, customer_data):
"""Add a new customer to the database"""
try:
cursor = self.conn.cursor()
cursor.execute('''
INSERT INTO customers (name, phone, email, address, gst_number)
VALUES (?, ?, ?, ?, ?)
''', (customer_data['name'], customer_data.get('phone', ''),
customer_data.get('email', ''), customer_data.get('address', ''),
customer_data.get('gst_number', '')))
customer_id = cursor.lastrowid
self.conn.commit()
return customer_id
except sqlite3.Error as e:
print(f"Add customer error: {e}")
self.conn.rollback()
return None
def get_all_customers(self):
"""Get all customers from the database"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT id, name, phone, email, address, gst_number, created_at
FROM customers
ORDER BY name
''')
columns = [column[0] for column in cursor.description]
customers = [dict(zip(columns, row)) for row in cursor.fetchall()]
return customers
except sqlite3.Error as e:
print(f"Get customers error: {e}")
return []
def get_customer_by_id(self, customer_id):
"""Get a customer by their ID"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT id, name, phone, email, address, gst_number, created_at
FROM customers
WHERE id = ?
''', (customer_id,))
columns = [column[0] for column in cursor.description]
row = cursor.fetchone()
if row:
return dict(zip(columns, row))
return None
except sqlite3.Error as e:
print(f"Get customer error: {e}")
return None
# Sales methods
def create_sale(self, sale_data, sale_items):
"""Create a new sale with multiple items"""
try:
cursor = self.conn.cursor()
# Generate a unique invoice number
invoice_number = f"INV{datetime.datetime.now().strftime('%Y%m%d')}{uuid.uuid4().hex[:6].upper()}"
# Insert the sale record
cursor.execute('''
INSERT INTO sales (invoice_number, customer_id, user_id, total_amount,
discount_amount, tax_amount, final_amount, payment_method, gst_included)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (invoice_number, sale_data.get('customer_id'), sale_data['user_id'],
sale_data['total_amount'], sale_data.get('discount_amount', 0),
sale_data.get('tax_amount', 0), sale_data['final_amount'],
sale_data.get('payment_method', 'cash'), sale_data.get('gst_included', 0)))
sale_id = cursor.lastrowid
# Insert each sale item
for item in sale_items:
cursor.execute('''
INSERT INTO sale_items (sale_id, product_id, product_item_id, quantity,
price_per_unit, discount_percentage, total_price)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (sale_id, item['product_id'], item.get('product_item_id'),
item['quantity'], item['price_per_unit'], item.get('discount_percentage', 0),
item['total_price']))
# Update product item status if it's a unique item
if 'product_item_id' in item and item['product_item_id']:
cursor.execute('''
UPDATE product_items SET status = 'sold' WHERE id = ?
''', (item['product_item_id'],))
# Update product store quantity
cursor.execute('''
UPDATE products SET store_quantity = store_quantity - ? WHERE id = ?
''', (item['quantity'], item['product_id']))
# Record the inventory transaction
cursor.execute('''
INSERT INTO inventory_transactions
(product_id, transaction_type, quantity, from_location, to_location, user_id, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (item['product_id'], 'sell', item['quantity'], 'store', 'customer',
sale_data['user_id'], f"Sale invoice: {invoice_number}"))
self.conn.commit()
return sale_id, invoice_number
except sqlite3.Error as e:
print(f"Create sale error: {e}")
self.conn.rollback()
return None, None
def get_sale_by_id(self, sale_id):
"""Get a sale by its ID with all related items"""
try:
cursor = self.conn.cursor()
# Get the sale record
cursor.execute('''
SELECT s.id, s.invoice_number, s.customer_id, s.user_id, s.sale_date,
s.total_amount, s.discount_amount, s.tax_amount, s.final_amount,
s.payment_method, s.gst_included,
c.name as customer_name, c.phone as customer_phone, c.gst_number,
u.username as user_name
FROM sales s
LEFT JOIN customers c ON s.customer_id = c.id
JOIN users u ON s.user_id = u.id
WHERE s.id = ?
''', (sale_id,))
columns = [column[0] for column in cursor.description]
sale_row = cursor.fetchone()
if not sale_row:
return None
sale_data = dict(zip(columns, sale_row))
# Get the sale items
cursor.execute('''
SELECT si.id, si.product_id, si.product_item_id, si.quantity,
si.price_per_unit, si.discount_percentage, si.total_price,
p.name as product_name, p.product_code
FROM sale_items si
JOIN products p ON si.product_id = p.id
WHERE si.sale_id = ?
''', (sale_id,))
item_columns = [column[0] for column in cursor.description]
sale_items = [dict(zip(item_columns, row)) for row in cursor.fetchall()]
sale_data['items'] = sale_items
return sale_data
except sqlite3.Error as e:
print(f"Get sale error: {e}")
return None
def get_sales_by_date_range(self, start_date, end_date):
"""Get all sales within a date range"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT s.id, s.invoice_number, s.customer_id, s.user_id, s.sale_date,
s.total_amount, s.discount_amount, s.tax_amount, s.final_amount,
s.payment_method, s.gst_included,
c.name as customer_name
FROM sales s
LEFT JOIN customers c ON s.customer_id = c.id
WHERE DATE(s.sale_date) BETWEEN DATE(?) AND DATE(?)
ORDER BY s.sale_date DESC
''', (start_date, end_date))
columns = [column[0] for column in cursor.description]
sales = [dict(zip(columns, row)) for row in cursor.fetchall()]
return sales
except sqlite3.Error as e:
print(f"Get sales error: {e}")
return []
# Analytics methods
def get_top_selling_products(self, limit=10, start_date=None, end_date=None):
"""Get the top selling products within an optional date range"""
try:
cursor = self.conn.cursor()
query = '''
SELECT p.id, p.product_code, p.name,
SUM(si.quantity) as total_quantity,
SUM(si.total_price) as total_revenue,
COUNT(DISTINCT s.id) as sale_count
FROM products p
JOIN sale_items si ON p.id = si.product_id
JOIN sales s ON si.sale_id = s.id
'''
params = []
if start_date and end_date:
query += "WHERE DATE(s.sale_date) BETWEEN DATE(?) AND DATE(?)"
params.extend([start_date, end_date])
query += '''
GROUP BY p.id
ORDER BY total_quantity DESC
LIMIT ?
'''
params.append(limit)
cursor.execute(query, params)
columns = [column[0] for column in cursor.description]
products = [dict(zip(columns, row)) for row in cursor.fetchall()]
return products
except sqlite3.Error as e:
print(f"Get top selling products error: {e}")
return []
def get_non_selling_products(self, days=30, limit=10):
"""Get products that haven't sold in the specified number of days"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT p.id, p.product_code, p.name, p.store_quantity, p.warehouse_quantity,
p.cost_price, p.selling_price, p.category,
MAX(s.sale_date) as last_sale_date
FROM products p
LEFT JOIN sale_items si ON p.id = si.product_id
LEFT JOIN sales s ON si.sale_id = s.id
GROUP BY p.id
HAVING last_sale_date IS NULL OR
julianday('now') - julianday(last_sale_date) > ?
ORDER BY last_sale_date ASC NULLS FIRST, p.store_quantity DESC
LIMIT ?
''', (days, limit))
columns = [column[0] for column in cursor.description]
products = [dict(zip(columns, row)) for row in cursor.fetchall()]
return products
except sqlite3.Error as e:
print(f"Get non-selling products error: {e}")
return []
def get_profit_by_period(self, period_type='monthly', year=None, month=None):
"""Get profit analysis by period (daily, monthly, yearly)"""
try:
cursor = self.conn.cursor()
if not year:
year = datetime.datetime.now().year
if period_type == 'yearly':
group_by = "strftime('%Y', s.sale_date)"
date_format = "strftime('%Y', s.sale_date) as period"
where_clause = ""
params = []
elif period_type == 'monthly':
group_by = "strftime('%Y-%m', s.sale_date)"
date_format = "strftime('%Y-%m', s.sale_date) as period"
where_clause = "WHERE strftime('%Y', s.sale_date) = ?"
params = [str(year)]
else: # daily
group_by = "DATE(s.sale_date)"
date_format = "DATE(s.sale_date) as period"
if month:
where_clause = "WHERE strftime('%Y', s.sale_date) = ? AND strftime('%m', s.sale_date) = ?"
params = [str(year), str(month).zfill(2)]
else:
where_clause = "WHERE strftime('%Y', s.sale_date) = ?"
params = [str(year)]
query = f'''
SELECT {date_format},
SUM(s.final_amount) as total_revenue,
SUM(si.quantity * p.cost_price) as total_cost,
SUM(s.final_amount) - SUM(si.quantity * p.cost_price) as gross_profit,
COUNT(DISTINCT s.id) as sale_count,
SUM(si.quantity) as items_sold
FROM sales s
JOIN sale_items si ON s.id = si.sale_id
JOIN products p ON si.product_id = p.id
{where_clause}
GROUP BY {group_by}
ORDER BY period
'''
cursor.execute(query, params)
columns = [column[0] for column in cursor.description]
profit_data = [dict(zip(columns, row)) for row in cursor.fetchall()]
return profit_data
except sqlite3.Error as e:
print(f"Get profit analysis error: {e}")
return []
def get_inventory_value_summary(self):
"""Get a summary of current inventory value"""
try:
cursor = self.conn.cursor()
cursor.execute('''
SELECT
SUM(store_quantity * cost_price) as store_inventory_cost,
SUM(store_quantity * selling_price) as store_inventory_value,
SUM(warehouse_quantity * cost_price) as warehouse_inventory_cost,
SUM(warehouse_quantity * selling_price) as warehouse_inventory_value,
SUM((store_quantity + warehouse_quantity) * cost_price) as total_inventory_cost,
SUM((store_quantity + warehouse_quantity) * selling_price) as total_inventory_value,
COUNT(*) as total_products,
SUM(store_quantity) as total_store_items,
SUM(warehouse_quantity) as total_warehouse_items
FROM products
''')
columns = [column[0] for column in cursor.description]
summary = dict(zip(columns, cursor.fetchone()))
return summary
except sqlite3.Error as e:
print(f"Get inventory value summary error: {e}")
return {}
def get_product_items(self, product_id, status=None):
"""Get all product items for a specific product, optionally filtered by status"""
try:
cursor = self.conn.cursor()
query = '''
SELECT pi.id, pi.product_id, pi.item_unique_id, pi.qr_code_path, pi.status, pi.created_at,
p.name as product_name, p.product_code, p.selling_price
FROM product_items pi
JOIN products p ON pi.product_id = p.id
WHERE pi.product_id = ?
'''
params = [product_id]
if status:
query += "AND pi.status = ?"
params.append(status)
cursor.execute(query, params)
columns = [column[0] for column in cursor.description]
items = [dict(zip(columns, row)) for row in cursor.fetchall()]
return items
except sqlite3.Error as e:
print(f"Get product items error: {e}")
return []
def transfer_items(self, product_id, quantity, user_id):
"""Transfer items from warehouse to store and generate QR codes for them"""
try:
cursor = self.conn.cursor()
# Get the product to check if there's enough quantity in warehouse
cursor.execute('''
SELECT id, product_code, name, warehouse_quantity
FROM products
WHERE id = ?
''', (product_id,))
product = cursor.fetchone()
if not product or product[3] < quantity:
print(f"Not enough items in warehouse. Available: {product[3] if product else 0}, Requested: {quantity}")
return False
# Update product quantities
cursor.execute('''
UPDATE products
SET warehouse_quantity = warehouse_quantity - ?,
store_quantity = store_quantity + ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
''', (quantity, quantity, product_id))
# Generate product items with QR codes for the transferred quantity
qr_code_paths = self.generate_product_items(product_id, quantity, 'in_store')
# Record the inventory transaction
cursor.execute('''
INSERT INTO inventory_transactions
(product_id, transaction_type, quantity, from_location, to_location, user_id, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (product_id, 'transfer', quantity, 'warehouse', 'store',
user_id, f"Transferred {quantity} items from warehouse to store"))
self.conn.commit()
return True
except sqlite3.Error as e:
print(f"Transfer items error: {e}")
self.conn.rollback()
return False