-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1308 lines (1101 loc) · 58.4 KB
/
app.py
File metadata and controls
1308 lines (1101 loc) · 58.4 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
# ---------------------------------------------------------------------------------------------------------
# app.py - Kognit AI (Updated for Separate Credit & Capital CSVs, Debt Tracking & Reconciliation, Itemized Transactions in Reports & Summaries, Time-Based Financial Summaries, Smart Business Insights, Robust Credit Accounting & Reporting, Paper-to-Digital Accounting (OCR for both images and documents) and Improved Conversational Capabilities)
# ---------------------------------------------------------------------------------------------------------
import os
import json
import csv
import re
import mimetypes
from datetime import datetime, timedelta
import gradio as gr
from google import genai
from google.genai import types
from dotenv import load_dotenv
from huggingface_hub import HfApi, hf_hub_download
# --- Load environment and init clients
load_dotenv()
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
# --- HF CONFIGURATION START:
HF_TOKEN = os.getenv("HF_TOKEN")
REPO_ID = "fullstack-overlord/kognit_ai_data"
api = HfApi()
def sync_cloud(filename, action="push"):
"""Pulls or Pushes files to HF Dataset to ensure data persists after app restart."""
if not HF_TOKEN or not REPO_ID:
return
try:
if action == "push":
api.upload_file(
path_or_fileobj=filename,
path_in_repo=filename,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN
)
elif action == "pull":
hf_hub_download(repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN, local_dir=".")
except Exception: # as e:
pass # print(f"Cloud sync error: {e}")
# --- HF CONFIGURATION END
# --- IDENTITY HELPER
def create_user_slug(name):
"""Turns 'Mama's Kitchen!' into 'mamas_kitchen' for safe filing."""
if not name: return "default_user"
return re.sub(r'[^a-z0-9]', '_', name.lower().strip())
# -----------------------------
# DATABASE & CALCULATION LOGIC
# -----------------------------
# --- CAPITAL: moved from single txt to appendable CSV
def get_capital(biz_slug):
"""
capital is now stored (in <biz_slug>_capital.csv) as multiple rows.
This function sums all 'amount' values and returns the total capital.
"""
capital_file = f"{biz_slug}_capital.csv"
sync_cloud(capital_file, action="pull")
if not os.path.exists(capital_file):
return 0.0
total_capital = 0.0
with open(capital_file, "r", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
try:
total_capital += float(row.get("amount", 0) or 0)
except Exception:
continue
return total_capital
def set_capital(amount, biz_slug, description="Owner added capital"):
"""
Appends a capital injection row instead of overwriting.
"""
capital_file = f"{biz_slug}_capital.csv"
sync_cloud(capital_file, action="pull")
file_exists = os.path.isfile(capital_file)
with open(capital_file, "a", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["date", "type", "amount", "description"])
if not file_exists:
writer.writeheader()
writer.writerow({
"date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"type": "capital_injection",
"amount": amount,
"description": description
})
sync_cloud(capital_file, action="push")
# --- LEDGER:
def save_to_ledger(rows, biz_slug):
"""
Save cash sales / purchases / expenses to <biz_slug>_ledger.csv
"""
db_file = f"{biz_slug}_ledger.csv"
sync_cloud(db_file, action="pull")
file_exists = os.path.isfile(db_file)
with open(db_file, 'a', newline='') as f:
writer = csv.DictWriter(f, fieldnames=["date", "type", "item", "qty", "unit_price", "total"])
if not file_exists: writer.writeheader()
for row in rows:
row['date'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
writer.writerow(row)
sync_cloud(db_file, action="push")
# --- CREDIT ACCOUNTING (credit sales/purchases recording)
def save_to_credit(rows, biz_slug):
"""
Append credit-related rows (credit_sale, credit_purchase,
payment_received, payment_made) to <biz_slug>_credit.csv
"""
credit_file = f"{biz_slug}_credit.csv"
sync_cloud(credit_file, action="pull")
file_exists = os.path.isfile(credit_file)
with open(credit_file, "a", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["date", "type", "entity_name", "item_description", "qty", "unit_price", "total", "status"])
if not file_exists: writer.writeheader()
for row in rows:
r = {
"date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"type": row.get("type", ""),
"entity_name": row.get("entity_name", "").strip(),
"item_description": row.get("item_description", "") or "",
"qty": row.get("qty", 1),
"unit_price": row.get("unit_price", 0),
"total": row.get("total", 0),
"status": row.get("status", "unpaid")
}
writer.writerow(r)
sync_cloud(credit_file, action="push")
# -----------------------------
# PROFITABILITY ADVICE & ANALYSIS
# -----------------------------
def get_profitability_analysis(biz_slug):
db_file = f"{biz_slug}_ledger.csv"
sync_cloud(db_file, action="pull")
if not os.path.isfile(db_file): return "No data yet to analyze."
analysis = {} # Structure: {item_name: {'cost': 0, 'sales': 0}}
with open(db_file, 'r', newline="") as f:
reader = csv.DictReader(f)
for row in reader:
item = row['item'].lower().strip()
# Defensive programming: String data treated as 0
try:
total = float(row['total'])
except Exception:
total = 0.0
if item not in analysis: analysis[item] = {'cost': 0, 'sales': 0}
if row['type'] == 'purchase': analysis[item]['cost'] += total
elif row['type'] == 'sale': analysis[item]['sales'] += total
if not analysis: return "No transactions found to analyze."
report = "💡 **KOGNIT AI BUSINESS ADVICE**\n\n"
best_item = None
max_profit = -float('inf')
for item, figures in analysis.items():
profit = figures['sales'] - figures['cost']
# Only analyze if we have both purchase and sale data
if figures['cost'] > 0:
margin = (profit / figures['cost']) * 100
report += f"🔸 **{item.capitalize()}**: Profit ₦{profit:,.0f} ({margin:.1f}% margin)\n"
if profit > max_profit:
max_profit = profit
best_item = item
else:
report += f"🔸 **{item.capitalize()}**: Currently in stock (No sales recorded yet).\n"
if best_item:
report += f"\n⭐ **Recommendation:** Your best performing item is **{best_item.upper()}**. You should consider stocking more of it to maximize your returns!"
return report
# -----------------------------
# STATEMENT OF ACCOUNT / REPORT GENERATION
# -----------------------------
def generate_professional_report(biz_slug):
"""
Updated generate_professional_report with robust credit/payout logic.
- Replaces credit parsing with per-entity aggregation so the report can:
* show "No credit purchase history" when there are no credit purchases
* show "All supplier debts cleared" when all supplier debts are fully paid
* list unpaid supplier debts when outstanding exists
* show payments made itemized or suitable fallback message
* same logic mirrored for customer credit sales & payments received
This makes the report intelligent, adapt based on data and not just static.
"""
db_file = f"{biz_slug}_ledger.csv"
credit_file = f"{biz_slug}_credit.csv"
capital_file = f"{biz_slug}_capital.csv"
# --- Pull cloud copies
sync_cloud(db_file, action="pull")
sync_cloud(credit_file, action="pull")
sync_cloud(capital_file, action="pull")
# --- If no ledger exists at all
if not os.path.isfile(db_file):
return "No transactions recorded yet."
# --- Capital (sum) and (detailed list will be read later for report)
capital = get_capital(biz_slug)
purchases = []
sales = []
other_expenses = 0.0
# --- Ccredit data aggregates
payments_received = 0.0
payments_made = 0.0
payments_received_list = [] # itemized list
payments_made_list = [] # itemized list
# --- Builds both full history lists and per-entity outstanding summaries:
credit_purchase_rows = [] # all credit_purchase rows
credit_sale_rows = [] # all credit_sale rows
payment_made_rows = [] # all payment_made rows
payment_received_rows = [] # all payment_received rows
# --- Read ledger.csv
with open(db_file, 'r', newline="") as f:
reader = csv.DictReader(f)
for row in reader:
item_str = f"{row.get('qty','')} {row.get('item','')} @ ₦{float(row.get('unit_price',0) or 0):,.0f}"
try:
total = float(row.get('total', 0) or 0)
except Exception:
total = 0.0
if row.get('type') == 'purchase':
purchases.append((item_str, total))
elif row.get('type') == 'sale':
sales.append((item_str, total))
else:
other_expenses += total
# --- Read credit.csv and aggregate into structured lists for robust per-entity math
if os.path.exists(credit_file):
with open(credit_file, "r", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
r_type = (row.get("type") or "").strip()
try:
total = float(row.get("total", 0) or 0)
except Exception:
total = 0.0
date = row.get("date", "")
entity = row.get("entity_name", "").strip()
desc = row.get("item_description", "").strip()
status = (row.get("status") or "").lower().strip()
try:
qty = int(float(row.get("qty", 1) or 1))
except Exception:
qty = 1
# Collect full rows for history & itemized payments
if r_type == "credit_purchase":
credit_purchase_rows.append({
"date": date, "entity": entity, "desc": desc, "qty": qty,
"total": total, "status": status, "unit_price": row.get("unit_price", 0)
})
elif r_type == "credit_sale":
credit_sale_rows.append({
"date": date, "entity": entity, "desc": desc, "qty": qty,
"total": total, "status": status, "unit_price": row.get("unit_price", 0)
})
elif r_type == "payment_made":
payment_made_rows.append({
"date": date, "entity": entity, "desc": desc, "qty": qty,
"total": total, "status": status, "unit_price": row.get("unit_price", 0)
})
payments_made += total
payments_made_list.append((entity, desc, total, date))
elif r_type == "payment_received":
payment_received_rows.append({
"date": date, "entity": entity, "desc": desc, "qty": qty,
"total": total, "status": status, "unit_price": row.get("unit_price", 0)
})
payments_received += total
payments_received_list.append((entity, desc, total, date))
# -----------------------------
# Per-entity outstanding calculation (SUPPLIERS / CUSTOMERS)
# -----------------------------
# --- Build supplier map:
supplier_map = {}
for r in credit_purchase_rows:
key = r["entity"].strip().lower()
if not key:
continue
ent = supplier_map.setdefault(key, {"name": r["entity"], "purchases": 0.0, "payments": 0.0, "qty": 0, "first_date": r["date"], "descriptions":[]})
ent["purchases"] += float(r["total"] or 0)
try:
ent["qty"] += int(r.get("qty", 1) or 0)
except Exception:
ent["qty"] += 0
if r.get("date") and (not ent["first_date"] or ent["first_date"] == ""):
ent["first_date"] = r.get("date")
if r.get("desc"):
ent["descriptions"].append(r.get("desc"))
for r in payment_made_rows:
key = r["entity"].strip().lower()
if not key:
continue
ent = supplier_map.setdefault(key, {"name": r["entity"], "purchases": 0.0, "payments": 0.0, "qty": 0, "first_date": r.get("date",""), "descriptions":[]})
ent["payments"] += float(r["total"] or 0)
if r.get("desc"):
ent["descriptions"].append(r.get("desc"))
# --- Compute outstanding per supplier and prepare unpaid list
credit_purchases_unpaid = [] # list of (display_name, outstanding_amount, first_date, description_summary)
total_outstanding_payables = 0.0
for k, v in supplier_map.items():
# outstanding = total purchases - total payments for that supplier
outstanding = float(v.get("purchases", 0.0) or 0.0) - float(v.get("payments", 0.0) or 0.0)
# treat tiny float rounding as zero
if abs(outstanding) > 1e-6:
qty = int(v.get("qty", 0) or 0)
# Derive a sensible unit_price for the summary if qty > 0, else 0
try:
unit_price = float(v["purchases"]) / qty if qty > 0 else 0.0
except Exception:
unit_price = 0.0
credit_purchases_unpaid.append({
"entity": v.get("name", ""),
"total": outstanding,
"date": v.get("first_date", ""),
"desc": ", ".join(v.get("descriptions", [])[:2]) if v.get("descriptions") else "",
"qty": qty,
"unit_price": unit_price
})
total_outstanding_payables += outstanding
# --- Build customer map: Mirror same logic for customers (credit sales / payments received)
customer_map = {}
for r in credit_sale_rows:
key = r["entity"].strip().lower()
if not key:
continue
ent = customer_map.setdefault(key, {"name": r["entity"], "sales": 0.0, "payments": 0.0, "qty": 0, "first_date": r.get("date",""), "descriptions":[]})
ent["sales"] += float(r["total"] or 0)
try:
ent["qty"] += int(r.get("qty", 1) or 0)
except Exception:
ent["qty"] += 0
if r.get("desc"):
ent["descriptions"].append(r.get("desc"))
for r in payment_received_rows:
key = r["entity"].strip().lower()
if not key:
continue
ent = customer_map.setdefault(key, {"name": r["entity"], "sales": 0.0, "payments": 0.0, "qty": 0, "first_date": r.get("date",""), "descriptions":[]})
ent["payments"] += float(r["total"] or 0)
if r.get("desc"):
ent["descriptions"].append(r.get("desc"))
# --- Compute outstanding per customer and prepare unpaid list
credit_sales_unpaid = []
total_outstanding_receivables = 0.0
for k, v in customer_map.items():
outstanding = float(v.get("sales", 0.0) or 0.0) - float(v.get("payments", 0.0) or 0.0)
if abs(outstanding) > 1e-6:
qty = int(v.get("qty", 0) or 0)
try:
unit_price = float(v["sales"]) / qty if qty > 0 else 0.0
except Exception:
unit_price = 0.0
credit_sales_unpaid.append({
"entity": v.get("name", ""),
"total": outstanding,
"date": v.get("first_date", ""),
"desc": ", ".join(v.get("descriptions", [])[:2]) if v.get("descriptions") else "",
"qty": qty,
"unit_price": unit_price
})
total_outstanding_receivables += outstanding
# --- UPDATED CALCULATIONS
total_expenses = sum(p[1] for p in purchases) + other_expenses + payments_made
total_income = sum(s[1] for s in sales) + payments_received
profit = total_income - total_expenses
balance = (capital - total_expenses) + total_income
# --- BUILD REPORT & STATEMENT OF ACCOUNT
capital_entries = []
if os.path.exists(capital_file):
with open(capital_file, "r", newline="") as cf:
cap_reader = csv.DictReader(cf)
for row in cap_reader:
desc = row.get("description", "").strip() if row.get("description") else ""
try:
amt = float(row.get("amount", 0) or 0)
except Exception:
amt = 0.0
capital_entries.append((amt, desc, row.get("date", "")))
report = "📋 **OFFICIAL STATEMENT OF ACCOUNT**\n\n"
# CAPITAL CONTRIBUTIONS
report += "🏦 CAPITAL CONTRIBUTIONS\n"
if capital_entries:
for amt, desc, date in capital_entries:
label = desc if desc else "Capital injection"
report += f"• ₦{amt:,.0f} — {label}\n"
else:
report += "• ₦0 — No capital contributions recorded yet\n"
report += "\n-----------------------\n\n"
# CASH PURCHASES
report += "🛒 CASH PURCHASES\n"
if purchases:
report += "\n".join([f"• {p[0]}: ₦{p[1]:,.0f}" for p in purchases]) + "\n"
else:
report += "• No cash purchases recorded.\n"
report += "\n\n"
# CREDIT PURCHASES (Suppliers' Debts Unpaid)
report += "💳 CREDIT PURCHASES (List of Suppliers' Debts)\n"
if not credit_purchase_rows:
# Case: No credit purchase history at all
report += "• You haven't purchased any goods on credit, No credit purchase history.\n"
else:
# There is credit purchase history; all cleared or list unpaid
if total_outstanding_payables <= 1e-6:
# Case: All cleared (sum of purchases equals sum of payments)
report += "• All suppliers' debts paid\n"
else:
# Case: Some outstanding remains; itemized list of unpaid suppliers' debts
report += "\n".join([
f"• {c['entity']} — {c['qty']} {c['desc']} @ ₦{float(c['unit_price']or 0):,.0f} (₦{c['total']:,.0f}) — {c['date']}"
for c in credit_purchases_unpaid
]) + "\n"
report += "\n\n"
# PAYMENTS MADE (Suppliers' Debts Paid)
report += "📤 PAYMENTS MADE (List of Paid Suppliers' Debts)\n"
if payments_made_list:
# Case: Itemized payments exist
report += "\n".join([f"• {p[0]} — ₦{p[2]:,.0f} ({p[3]}){(' - '+p[1]) if p[1] else ''}" for p in payments_made_list]) + "\n"
else:
# No payments_made rows
if not credit_purchase_rows:
# Case: No credit purchase history at all
report += "• No credit purchase history\n"
else:
# Case: There are credit purchases but nothing has been paid yet
report += "• No supplier debt has been paid\n"
report += "\n\n"
# OTHER EXPENSES
report += "⛽ OTHER EXPENSES\n"
report += f"• ₦{other_expenses:,.0f}\n"
report += "\n-----------------------\n\n"
# CASH SALES
report += "💰 CASH SALES\n"
if sales:
report += "\n".join([f"• {s[0]}: ₦{s[1]:,.0f}" for s in sales]) + "\n"
else:
report += "• No cash sales recorded.\n"
report += "\n\n"
# CREDIT SALES (Customers still Owing)
report += "🧾 CREDIT SALES (List of customers' debts)\n"
# Case: No credit sale history at all
if not credit_sale_rows:
report += "• You haven't sold any goods on credit, No credit sale history\n"
else:
# There is credit sale history; all cleared or list unpaid
if total_outstanding_receivables <= 1e-6:
# Case: All cleared
report += "• All customers' debts cleared\n"
else:
# Case: Some outstanding remains; itemized list of unpaid customers' debts
report += "\n".join([
f"• {c['entity']} — {c['qty']} {c['desc']} @ ₦{float(c['unit_price']or 0):,.0f} (₦{c['total']:,.0f}) — {c['date']}"
for c in credit_sales_unpaid
]) + "\n"
report += "\n\n"
# PAYMENTS RECEIVED (Customers Debt Payoff)
report += "📥 PAYMENTS RECEIVED (List of Customers' Debt Payoff)\n"
if payments_received_list:
# Case: Itemized payments exist
report += "\n".join([f"• {p[0]} — ₦{p[2]:,.0f} ({p[3]}){(' - '+p[1]) if p[1] else ''}" for p in payments_received_list]) + "\n"
else:
# No payments_received rows
if not credit_sale_rows:
# Case: No credit sale history at all
report += "• No credit sale history\n"
else:
# Case: There are credit sales but nothing has been paid yet
report += "• No customer has paid their debt\n"
report += "\n-----------------------\n\n"
# Totals & Summary
report += "**TOTALS & SUMMARY**\n"
report += f"📉 TOTAL EXPENSES: ₦{total_expenses:,.0f}\n"
report += f"📈 TOTAL INCOME: ₦{total_income:,.0f}\n"
# Use computed totals from per-entity outstanding
report += f"💳 Total Outstanding Payables: ₦{total_outstanding_payables:,.0f}\n"
report += f"💰 Total Outstanding Receivables: ₦{total_outstanding_receivables:,.0f}\n"
report += f"✨ NET PROFIT: ₦{profit:,.0f}\n"
report += f"💎 CURRENT BALANCE: ₦{balance:,.0f}\n"
return report
# -----------------------------
# TIME-BASED FINANCIAL SUMMARIES + SMART BUSINESS INSIGHTS
# Gemini only handles intent; Python calculates and formats.
# -----------------------------
def _safe_parse_datetime(date_text):
"""
NEW: Safely parse the timestamp stored in CSV rows.
Your app writes dates like: YYYY-MM-DD HH:MM:SS
"""
if not date_text:
return None
raw = str(date_text).strip().split(".")[0] # remove microseconds if any
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d", "%Y/%m/%d"):
try:
return datetime.strptime(raw, fmt)
except Exception:
pass
try:
return datetime.fromisoformat(raw)
except Exception:
return None
def _get_period_bounds(period):
"""
Convert a period name into a start/end datetime window.
Supported periods:
- Daily
- Weekly
- Monthly
"""
now = datetime.now()
period = (period or "monthly").lower().strip()
if period == "daily":
start_dt = now.replace(hour=0, minute=0, second=0, microsecond=0)
end_dt = start_dt + timedelta(days=1)
return start_dt, end_dt
if period == "weekly":
# Monday 00:00 to next Monday 00:00
start_dt = (now - timedelta(days=now.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
end_dt = start_dt + timedelta(days=7)
return start_dt, end_dt
# monthly (default)
start_dt = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
if start_dt.month == 12:
end_dt = start_dt.replace(year=start_dt.year + 1, month=1, day=1)
else:
end_dt = start_dt.replace(month=start_dt.month + 1, day=1)
return start_dt, end_dt
def _get_previous_period_bounds(period, current_start_dt):
"""
Get the previous comparable period.
This is used for Smart Business Insights comparison.
This lets us compare:
- today vs yesterday
- this week vs last week
- this month vs last month
- and other specific user's request
"""
period = (period or "monthly").lower().strip()
if period == "daily":
prev_start = (current_start_dt - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
prev_end = current_start_dt
return prev_start, prev_end
if period == "weekly":
prev_start = (current_start_dt - timedelta(days=7)).replace(hour=0, minute=0, second=0, microsecond=0)
prev_end = current_start_dt
return prev_start, prev_end
# monthly
if current_start_dt.month == 1:
prev_start = current_start_dt.replace(year=current_start_dt.year - 1, month=12, day=1)
else:
prev_start = current_start_dt.replace(month=current_start_dt.month - 1, day=1)
prev_end = current_start_dt
return prev_start, prev_end
def _aggregate_period_data(biz_slug, start_dt, end_dt):
"""
Core engine that reads ledger.csv and credit.csv for a specific time window and computes Daily / Weekly / Monthly Financial Summaries and Smart Business Insights for:
- cash sales
- credit sales
- payments received
- cash purchases
- other expenses
- payments made
- total sales recorded
- total income collected
- total expenses paid
- profit
- outstanding receivables/payables
- top customer
- top expense
- counts of unpaid customers/suppliers
"""
db_file = f"{biz_slug}_ledger.csv"
credit_file = f"{biz_slug}_credit.csv"
# --- pull cloud copies so we analyze the latest data
sync_cloud(db_file, action="pull")
sync_cloud(credit_file, action="pull")
# --- Core totals
cash_sales = 0.0
credit_sales = 0.0
payments_received = 0.0
cash_purchases = 0.0
other_expenses = 0.0
payments_made = 0.0
total_credit_purchases = 0.0
# --- Detailed maps for smarter analytics, rankings and debt insights
expense_map = {} # item_name -> {"name": display_name, "total": amount}
customer_sales_map = {} # customer_name -> {"name": display_name, "credit_sales": amount}
customer_payments_map = {} # customer_name -> {"name": display_name, "payments": amount}
supplier_purchases_map = {} # supplier_name -> {"name": display_name, "credit_purchases": amount}
supplier_payments_map = {} # supplier_name -> {"name": display_name, "payments": amount}
# -----------------------------
# Read ledger.csv (cash sales/purchases/expenses)
# -----------------------------
if os.path.exists(db_file):
with open(db_file, "r", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
dt = _safe_parse_datetime(row.get("date", ""))
if not dt or not (start_dt <= dt < end_dt):
continue
row_type = (row.get("type") or "").strip().lower()
try:
total = float(row.get("total", 0) or 0)
except Exception:
total = 0.0
item_name = (row.get("item") or row_type or "Unknown").strip() or "Unknown"
if row_type == "sale":
cash_sales += total
elif row_type == "purchase":
cash_purchases += total
key = item_name.lower()
item_bucket = expense_map.setdefault(key, {"name": item_name, "total": 0.0})
item_bucket["total"] += total
else:
# Any other ledger row that is non-sale/non-purchase is treated as expense category
other_expenses += total
key = item_name.lower()
item_bucket = expense_map.setdefault(key, {"name": item_name, "total": 0.0})
item_bucket["total"] += total
# -----------------------------
# Read credit.csv (credit sales/purchases/repayments)
# -----------------------------
if os.path.exists(credit_file):
with open(credit_file, "r", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
dt = _safe_parse_datetime(row.get("date", ""))
if not dt or not (start_dt <= dt < end_dt):
continue
row_type = (row.get("type") or "").strip().lower()
entity_name = (row.get("entity_name") or "").strip()
display_name = entity_name if entity_name else "Unknown"
try:
total = float(row.get("total", 0) or 0)
except Exception:
total = 0.0
# Credit sales (customer owes business)
if row_type == "credit_sale":
credit_sales += total
key = display_name.lower()
cust_bucket = customer_sales_map.setdefault(key, {"name": display_name, "credit_sales": 0.0})
cust_bucket["credit_sales"] += total
# Payments received from customers
elif row_type == "payment_received":
payments_received += total
key = display_name.lower()
pay_bucket = customer_payments_map.setdefault(key, {"name": display_name, "payments": 0.0})
pay_bucket["payments"] += total
# Credit purchases (business owes supplier)
elif row_type == "credit_purchase":
total_credit_purchases += total
key = display_name.lower()
supp_bucket = supplier_purchases_map.setdefault(key, {"name": display_name, "credit_purchases": 0.0})
supp_bucket["credit_purchases"] += total
# Payments made to suppliers
elif row_type == "payment_made":
payments_made += total
key = display_name.lower()
pay_bucket = supplier_payments_map.setdefault(key, {"name": display_name, "payments": 0.0})
pay_bucket["payments"] += total
# -----------------------------
# Per-entity outstanding calculations
# -----------------------------
outstanding_receivables = 0.0
outstanding_payables = 0.0
unpaid_customers = []
unpaid_suppliers = []
# --- Customers: credit sales - payments received
all_customer_keys = set(customer_sales_map.keys()) | set(customer_payments_map.keys())
for key in all_customer_keys:
sales_total = customer_sales_map.get(key, {}).get("credit_sales", 0.0)
payments_total = customer_payments_map.get(key, {}).get("payments", 0.0)
remaining = sales_total - payments_total
if remaining > 1e-6:
name = customer_sales_map.get(key, customer_payments_map.get(key, {"name": key}))["name"]
unpaid_customers.append((name, remaining))
outstanding_receivables += remaining
# --- Suppliers: credit purchases - payments made
all_supplier_keys = set(supplier_purchases_map.keys()) | set(supplier_payments_map.keys())
for key in all_supplier_keys:
purchase_total = supplier_purchases_map.get(key, {}).get("credit_purchases", 0.0)
payments_total = supplier_payments_map.get(key, {}).get("payments", 0.0)
remaining = purchase_total - payments_total
if remaining > 1e-6:
name = supplier_purchases_map.get(key, supplier_payments_map.get(key, {"name": key}))["name"]
unpaid_suppliers.append((name, remaining))
outstanding_payables += remaining
# -----------------------------
# Cash-basis summary numbers
# -----------------------------
total_sales_recorded = cash_sales + credit_sales
total_income_collected = cash_sales + payments_received
total_expenses_paid = cash_purchases + other_expenses + payments_made
profit_cash_basis = total_income_collected - total_expenses_paid
# --- Top customer by credit sales
top_customer = None
if customer_sales_map:
top_customer_key = max(customer_sales_map.keys(), key=lambda k: customer_sales_map[k]["credit_sales"])
top_customer = (
customer_sales_map[top_customer_key]["name"],
customer_sales_map[top_customer_key]["credit_sales"]
)
# --- Top expense item
top_expense = None
if expense_map:
top_expense_key = max(expense_map.keys(), key=lambda k: expense_map[k]["total"])
top_expense = (
expense_map[top_expense_key]["name"],
expense_map[top_expense_key]["total"]
)
return {
"cash_purchases": cash_purchases,
"credit_purchases": total_credit_purchases,
"payments_made": payments_made,
"other_expenses": other_expenses,
"cash_sales": cash_sales,
"credit_sales": credit_sales,
"payments_received": payments_received,
"total_sales_recorded": total_sales_recorded,
"total_income_collected": total_income_collected,
"total_expenses_paid": total_expenses_paid,
"profit_cash_basis": profit_cash_basis,
"outstanding_receivables": outstanding_receivables,
"outstanding_payables": outstanding_payables,
"unpaid_customers_count": len(unpaid_customers),
"unpaid_suppliers_count": len(unpaid_suppliers),
"top_customer": top_customer,
"top_expense": top_expense,
"unpaid_customers": unpaid_customers,
"unpaid_suppliers": unpaid_suppliers,
"expense_map": expense_map,
}
# -----------------------------
# Generates TIME-BASED FINANCIAL SUMMARIES
# -----------------------------
def generate_period_financial_summary(biz_slug, period="monthly"):
"""
Daily / Weekly / Monthly Financial Summary Report.
This is the report users can ask for naturally.
"""
period = (period or "monthly").lower().strip()
start_dt, end_dt = _get_period_bounds(period)
data = _aggregate_period_data(biz_slug, start_dt, end_dt)
# --- Friendly titles and period labels
if period == "daily":
title = "📊 Daily Financial Summary"
period_label = start_dt.strftime("%d %b %Y")
elif period == "weekly":
title = "📊 Weekly Financial Summary"
period_label = f"{start_dt.strftime('%d %b %Y')} - {(end_dt - timedelta(seconds=1)).strftime('%d %b %Y')}"
else:
title = f"📊 {start_dt.strftime('%B')} Financial Summary"
period_label = start_dt.strftime("%B %Y")
report = f"{title}\n\n"
report += f"📅 Period: {period_label}\n\n"
# --- Sales / payments / expenses breakdown
report += f"🛒 Cash Purchases: ₦{data['cash_purchases']:,.0f}\n"
report += f"💳 Credit Purchases: ₦{data['credit_purchases']:,.0f}\n"
report += f"📤 Payments Made: ₦{data['payments_made']:,.0f}\n"
report += f"⛽ Other Expenses: ₦{data['other_expenses']:,.0f}\n"
report += f"💰 Cash Sales: ₦{data['cash_sales']:,.0f}\n"
report += f"🧾 Credit Sales: ₦{data['credit_sales']:,.0f}\n"
report += f"📥 Payments Received: ₦{data['payments_received']:,.0f}\n"
report += "\n-----------------------\n\n"
# --- Totals & Summary
report += "**TOTALS & SUMMARY**\n"
report += f"📈 Total Sales (Cash + Credit): ₦{data['total_sales_recorded']:,.0f}\n"
report += f"💵 Total Income Collected: ₦{data['total_income_collected']:,.0f}\n"
report += f"📉 Total Expenses: ₦{data['total_expenses_paid']:,.0f}\n"
report += f"✨ Profit: ₦{data['profit_cash_basis']:,.0f}\n"
# Helpful business ranking lines
if data["top_customer"]:
report += f"🏆 Top Customer: {data['top_customer'][0]} — ₦{data['top_customer'][1]:,.0f}\n"
else:
report += "🏆 Top Customer: No credit customer activity recorded for this period.\n"
if data["top_expense"]:
report += f"⛽ Top Expense: {data['top_expense'][0]} — ₦{data['top_expense'][1]:,.0f}\n"
else:
report += "⛽ Top Expense: No expense activity recorded for this period.\n"
report += f"💳 Total Outstanding Payables: ₦{data['outstanding_payables']:,.0f}\n"
report += f"💰 Total Outstanding Receivables: ₦{data['outstanding_receivables']:,.0f}\n"
return report
# -----------------------------
# Computes SMART BUSINESS INSIGHTS
# -----------------------------
def compute_smart_business_insights(biz_slug, period="weekly"):
"""
Compare current period to previous comparable period and generate
short, actionable business insights.
"""
period = (period or "weekly").lower().strip()
current_start, current_end = _get_period_bounds(period)
previous_start, previous_end = _get_previous_period_bounds(period, current_start)
current = _aggregate_period_data(biz_slug, current_start, current_end)
previous = _aggregate_period_data(biz_slug, previous_start, previous_end)
def pct_change(now, before):
if before <= 0:
return None
return ((now - before) / before) * 100.0
insights = []
# --- Sales trend comparison
sales_change = pct_change(current["total_sales_recorded"], previous["total_sales_recorded"])
if sales_change is not None:
if sales_change > 0:
insights.append(f"📈 Sales increased by {sales_change:.1f}% compared to the previous {period}.")
elif sales_change < 0:
insights.append(f"📉 Sales decreased by {abs(sales_change):.1f}% compared to the previous {period}.")
# --- Expense trend comparison
expense_change = pct_change(current["total_expenses_paid"], previous["total_expenses_paid"])
if expense_change is not None:
if expense_change > 0:
insights.append(f"⚠️ Expenses increased by {expense_change:.1f}% compared to the previous {period}.")
elif expense_change < 0:
insights.append(f"✅ Expenses reduced by {abs(expense_change):.1f}% compared to the previous {period}.")
# --- Profit trend comparison
profit_change = pct_change(current["profit_cash_basis"], previous["profit_cash_basis"])
if profit_change is not None:
if profit_change > 0:
insights.append(f"✨ Profit improved by {profit_change:.1f}% compared to the previous {period}.")
elif profit_change < 0:
insights.append(f"⚠️ Profit dropped by {abs(profit_change):.1f}% compared to the previous {period}.")
# --- Outstanding customer debts
if current["outstanding_receivables"] > 0:
insights.append(
f"⚠️ You have {current['unpaid_customers_count']} unpaid customer debts worth ₦{current['outstanding_receivables']:,.0f}. You may want to follow up."
)
# --- Outstanding supplier debts
if current["outstanding_payables"] > 0:
insights.append(
f"⚠️ You owe suppliers ₦{current['outstanding_payables']:,.0f} across {current['unpaid_suppliers_count']} unpaid supplier debts."
)
# --- Top expense trend check / unusual rise
if current["top_expense"]:
current_item_name = current["top_expense"][0]
current_item_total = current["top_expense"][1]
previous_item_total = previous["expense_map"].get(current_item_name.lower(), {}).get("total", 0.0)
if previous_item_total > 0 and current_item_total > (previous_item_total * 1.2):
insights.append(f"⛽ {current_item_name} costs are higher than usual compared to the previous {period}.")
# --- If nothing triggered, return a calm status message
if not insights:
insights.append("✅ No major changes detected. The business looks stable for this period.")
report = f"💡 **KOGNIT AI BUSINESS INSIGHTS ({period.upper()})**\n\n"
report += "\n".join([f"• {item}" for item in insights])
return report
# -----------------------------
# AI (MASTER PROMPT) & CONTROLLER
# -----------------------------
def kognit_ai_accountant(text_input, audio_input, document_input, business_name):
biz_slug = create_user_slug(business_name)
try:
# Gemini is the brain that handles intent and routing; Python is the calculation engine.
# --- Financial Statements and Product Analysis & Profitability Advice
current_report = generate_professional_report(biz_slug)
current_advice = get_profitability_analysis(biz_slug)
# --- Time-Based Financial Summaries
current_daily_summary = generate_period_financial_summary(biz_slug, "daily")
current_weekly_summary = generate_period_financial_summary(biz_slug, "weekly")
current_monthly_summary = generate_period_financial_summary(biz_slug, "monthly")
# --- Smart Business Insights (with trend detection and actionable advice)
current_daily_insights = compute_smart_business_insights(biz_slug, "daily")
current_weekly_insights = compute_smart_business_insights(biz_slug, "weekly")
current_monthly_insights = compute_smart_business_insights(biz_slug, "monthly")
# -----------------------------
# THE MASTER PROMPT
# -----------------------------
prompt = f"""
You are 'Kognit AI', a Smart AI-Powered Accounting Assistant & Financial Intelligence AI for Nigerian Businesses (especially SMEs). Built by 'Ridwan Oyeniyi (fullstack_overlord)'.