-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
4386 lines (3806 loc) · 168 KB
/
Copy pathapp.py
File metadata and controls
4386 lines (3806 loc) · 168 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 requests
import io
from PIL import Image
from functools import wraps
from email_service import send_welcome_email, send_partnership_notification
from datetime import datetime, timedelta
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, abort
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_login import (
LoginManager,
login_user,
logout_user,
login_required,
current_user,
)
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from dotenv import load_dotenv
from supabase import create_client
# ── Security layer ────────────────────────────────────────────────────────────
from security import (
sanitize,
validate_phone,
validate_email,
validate_password,
validate_price,
validate_quantity,
require_active_account,
require_admin,
apply_security_headers,
)
import base64
import json as json_lib
import re
import enum
load_dotenv()
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", "dev-key-change-in-production")
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"DATABASE_URL", "sqlite:///agrolink.db"
)
if app.config["SQLALCHEMY_DATABASE_URI"].startswith("postgresql+psycopg://"):
app.config["SQLALCHEMY_DATABASE_URI"] = app.config[
"SQLALCHEMY_DATABASE_URI"
].replace("postgresql+psycopg://", "postgresql+psycopg://", 1)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"pool_pre_ping": True, "pool_recycle": 300}
app.config["MAX_CONTENT_LENGTH"] = 6 * 1024 * 1024 # 6MB hard cap (upload route itaangalia 5MB baadaye)
SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
GEMINI_VISION_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
WFP_API_URL = "https://api.vam.wfp.org/api/1/vam-data-bridges/1.0.0"
WFP_COMMODITY_MAP = {
"mahindi": {"id": 1, "name": "Maize"},
"mpunga": {"id": 82, "name": "Rice"},
"maharage": {"id": 36, "name": "Beans"},
"viazi": {"id": 117, "name": "Potatoes"},
"vitunguu": {"id": 63, "name": "Onions"},
"nyanya": {"id": 63, "name": "Tomatoes"},
"alizeti": {"id": 56, "name": "Oil (sunflower)"},
"muhogo": {"id": 55, "name": "Cassava"},
"ndizi": {"id": 15, "name": "Bananas"},
"korosho": {"id": 165, "name": "Cashewnuts"},
"kahawa": {"id": 33, "name": "Coffee"},
"mtama": {"id": 83, "name": "Sorghum"},
}
WFP_COUNTRY_ID = 214
supabase_client = (
create_client(SUPABASE_URL, SUPABASE_ANON_KEY) if SUPABASE_URL else None
)
WEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY", "")
WEATHER_BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
FORECAST_BASE_URL = "https://api.openweathermap.org/data/2.5/forecast"
db = SQLAlchemy()
db.init_app(app)
migrate = Migrate(app, db)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = "login"
login_manager.login_message = "Tafadhali ingia kwanza."
# ── CORS: restrict to your own domain only ───────────────────────────────────
# BADILISHA "https://agrolink.co.tz" ukipata domain yako halisi
ALLOWED_ORIGINS = os.environ.get(
"ALLOWED_ORIGINS", "https://agrolink-y9za.onrender.com"
).split(",")
CORS(app, origins=ALLOWED_ORIGINS, supports_credentials=True)
# ── Rate Limiter ──────────────────────────────────────────────────────────────
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["200 per day", "60 per minute"],
storage_uri="memory://",
)
# ── OTP SMS Helper ────────────────────────────────────────────────────────────
OTP_MOCK = os.environ.get("OTP_MOCK", "true").lower() == "true"
def send_otp_sms(phone: str, otp_code: str) -> bool:
"""Tuma OTP kwa SMS. OTP_MOCK=true → log tu (development/staging)."""
if OTP_MOCK:
app.logger.info(f"[OTP MOCK] Phone={phone} OTP={otp_code}")
return True
try:
import africastalking
africastalking.initialize(
os.environ.get("AT_USERNAME", ""),
os.environ.get("AT_API_KEY", ""),
)
sms = africastalking.SMS
msg = f"AgroLink Tanzania: Nambari yako ya uthibitisho ni {otp_code}. Inaisha baada ya dakika 10. Usishirikishe mtu yeyote."
response = sms.send(msg, [f"+255{phone.lstrip('0')}"])
return True
except Exception as e:
app.logger.error(f"[OTP SMS ERROR] {e}")
return False
# ── Security Headers (kila response) ─────────────────────────────────────────
apply_security_headers(app)
# ── Models ───────────────────────────────────────────────────────────────────
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
full_name = db.Column(db.String(120), nullable=False)
phone = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=True)
password_hash = db.Column(db.String(255), nullable=False)
region = db.Column(db.String(80), nullable=True)
role = db.Column(db.String(20), default="farmer")
is_active = db.Column(db.Boolean, default=True)
is_verified = db.Column(db.Boolean, default=False)
accepted_terms = db.Column(db.Boolean, default=False) # ← T&C checkbox
terms_accepted_at = db.Column(db.DateTime, nullable=True) # ← wakati wa kukubali
phone_verified = db.Column(db.Boolean, default=False, nullable=False) # ← OTP imethibitishwa
# ── Trust system ──────────────────────────────────────────────────────────
trust_level = db.Column(db.String(10), default="gray", nullable=False)
trust_points = db.Column(db.Integer, default=0, nullable=False)
flag_count = db.Column(db.Integer, default=0, nullable=False)
transaction_count = db.Column(db.Integer, default=0, nullable=False)
avg_rating = db.Column(db.Float, default=0.0, nullable=False)
trust_updated_at = db.Column(db.DateTime, nullable=True)
can_post_listing = db.Column(db.Boolean, default=False, nullable=False)
can_advise = db.Column(db.Boolean, default=False, nullable=False)
can_b2b = db.Column(db.Boolean, default=False, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
crops = db.relationship("Crop", backref="owner", lazy=True)
listings = db.relationship("MarketListing", backref="seller", lazy=True)
def set_password(self, password):
self.password_hash = bcrypt.generate_password_hash(password).decode("utf-8")
def check_password(self, password):
return bcrypt.check_password_hash(self.password_hash, password)
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return False
@property
def is_active_user(self):
return self.is_active
def get_id(self):
return str(self.id)
class PhoneOTP(db.Model):
__tablename__ = "phone_otps"
id = db.Column(db.Integer, primary_key=True)
phone = db.Column(db.String(20), nullable=False, index=True)
otp_code = db.Column(db.String(6), nullable=False)
form_data = db.Column(db.Text, nullable=False) # JSON ya form yote
attempts = db.Column(db.Integer, default=0)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
expires_at = db.Column(db.DateTime, nullable=False)
verified = db.Column(db.Boolean, default=False)
def is_expired(self):
return datetime.utcnow() > self.expires_at
def is_valid(self, code):
return (
not self.verified
and not self.is_expired()
and self.attempts < 5
and self.otp_code == code.strip()
)
class Crop(db.Model):
__tablename__ = "crops"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
name_sw = db.Column(db.String(100), nullable=False)
name_en = db.Column(db.String(100), nullable=False)
category = db.Column(db.String(50), nullable=False)
season = db.Column(db.String(50), nullable=True)
hectares = db.Column(db.Float, nullable=True)
region = db.Column(db.String(80), nullable=True)
description = db.Column(db.Text, nullable=True)
image_url = db.Column(db.String(300), nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(
db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
)
class MarketPrice(db.Model):
__tablename__ = "market_prices"
id = db.Column(db.Integer, primary_key=True)
crop_name = db.Column(db.String(100), nullable=False)
unit = db.Column(db.String(30), nullable=False, default="kg")
price_tzs = db.Column(db.Numeric(12, 2), nullable=False)
region = db.Column(db.String(100), nullable=False, default="Kitaifa")
market = db.Column(db.String(120), nullable=True)
source = db.Column(db.String(50), nullable=False, default="manual")
recorded_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
created_by_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
submitted_by_id= db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
status = db.Column(db.String(20), nullable=False, default="approved")
def to_dict(self):
return {
"id": self.id,
"crop_name": self.crop_name,
"unit": self.unit,
"price_tzs": float(self.price_tzs),
"region": self.region,
"market": self.market or "",
"source": self.source,
"recorded_at": self.recorded_at.strftime("%Y-%m-%d"),
}
class MarketListing(db.Model):
__tablename__ = "market_listings"
id = db.Column(db.Integer, primary_key=True)
seller_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
title = db.Column(db.String(200), nullable=False)
crop_name = db.Column(db.String(100), nullable=False)
quantity_kg = db.Column(db.Float, nullable=False)
unit = db.Column(db.String(20), default="kg")
price_tzs = db.Column(db.Float, nullable=False)
region = db.Column(db.String(80), nullable=False)
contact = db.Column(db.String(50), nullable=False)
description = db.Column(db.String(500), nullable=True)
is_available = db.Column(db.Boolean, default=True)
image_url = db.Column(db.String(300), nullable=True)
posted_at = db.Column(db.DateTime, default=datetime.utcnow)
is_sponsored = db.Column(db.Boolean, default=False, nullable=False)
sponsored_until = db.Column(db.DateTime, nullable=True)
class ListingReport(db.Model):
__tablename__ = "listing_reports"
id = db.Column(db.Integer, primary_key=True)
reporter_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
listing_id = db.Column(
db.Integer, db.ForeignKey("market_listings.id"), nullable=False
)
reason = db.Column(db.String(200), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
__table_args__ = (
db.UniqueConstraint("reporter_id", "listing_id", name="unique_report"),
)
reporter = db.relationship(
"User", foreign_keys=[reporter_id], backref="reports_made"
)
listing = db.relationship(
"MarketListing", foreign_keys=[listing_id], backref="reports"
)
class SellerRating(db.Model):
__tablename__ = "seller_ratings"
id = db.Column(db.Integer, primary_key=True)
seller_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
rater_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
listing_id = db.Column(
db.Integer, db.ForeignKey("market_listings.id"), nullable=False
)
stars = db.Column(db.Integer, nullable=False)
comment = db.Column(db.String(300), nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
__table_args__ = (
db.UniqueConstraint("rater_id", "listing_id", name="unique_rating"),
)
seller = db.relationship(
"User", foreign_keys=[seller_id], backref="ratings_received"
)
rater = db.relationship("User", foreign_keys=[rater_id], backref="ratings_given")
listing = db.relationship(
"MarketListing", foreign_keys=[listing_id], backref="ratings"
)
class BannedEmail(db.Model):
__tablename__ = "banned_emails"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), nullable=True, unique=True)
phone = db.Column(db.String(20), nullable=True, unique=True)
reason = db.Column(db.String(300), nullable=True)
banned_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
banned_at = db.Column(db.DateTime, default=datetime.utcnow)
class PricePredictionCache(db.Model):
__tablename__ = "price_prediction_cache"
id = db.Column(db.Integer, primary_key=True)
cache_key = db.Column(db.String(200), unique=True, nullable=False, index=True)
crop_name = db.Column(db.String(100), nullable=False)
region = db.Column(db.String(80), nullable=False)
month = db.Column(db.String(20), nullable=False)
ai_response = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
class PricePredictionLog(db.Model):
__tablename__ = "price_prediction_logs"
id = db.Column(db.Integer, primary_key=True)
crop_name = db.Column(db.String(100), nullable=False)
region = db.Column(db.String(80), nullable=False)
month = db.Column(db.String(20), nullable=False)
season = db.Column(db.String(30), nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
ai_response = db.Column(db.Text, nullable=True)
queried_at = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship("User", foreign_keys=[user_id], backref="price_queries")
class WeatherLog(db.Model):
__tablename__ = "weather_logs"
id = db.Column(db.Integer, primary_key=True)
city = db.Column(db.String(100), nullable=False)
temperature = db.Column(db.Float)
humidity = db.Column(db.Float)
description = db.Column(db.String(200))
wind_speed = db.Column(db.Float)
icon = db.Column(db.String(20))
fetched_at = db.Column(db.DateTime, default=datetime.utcnow)
# ── Phone Masking: Conversation + Message Models ─────────────────────────────
class ConvStatus(enum.Enum):
active = "active"
closed = "closed"
blocked = "blocked"
class Conversation(db.Model):
__tablename__ = "conversations"
id = db.Column(db.Integer, primary_key=True)
listing_id = db.Column(db.Integer, db.ForeignKey("market_listings.id"), nullable=False)
buyer_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
seller_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
status = db.Column(db.Enum(ConvStatus), default=ConvStatus.active, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
messages = db.relationship("Message", backref="conversation", lazy=True,
order_by="Message.sent_at")
listing = db.relationship("MarketListing", backref="conversations", lazy=True)
buyer = db.relationship("User", foreign_keys=[buyer_id],
backref="bought_conversations", lazy=True)
seller = db.relationship("User", foreign_keys=[seller_id],
backref="sold_conversations", lazy=True)
__table_args__ = (
db.UniqueConstraint("listing_id", "buyer_id", name="uq_listing_buyer"),
)
class Message(db.Model):
__tablename__ = "messages"
id = db.Column(db.Integer, primary_key=True)
conversation_id = db.Column(db.Integer, db.ForeignKey("conversations.id"), nullable=False)
sender_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
body = db.Column(db.Text, nullable=False)
is_read = db.Column(db.Boolean, default=False)
is_deleted = db.Column(db.Boolean, default=False, nullable=False, server_default="false")
reply_to_id = db.Column(db.Integer, db.ForeignKey("messages.id"), nullable=True)
sent_at = db.Column(db.DateTime, default=datetime.utcnow)
sender = db.relationship("User", foreign_keys=[sender_id], lazy=True)
class MessageDeletion(db.Model):
"""'Futa kwangu' — mtumiaji anaficha ujumbe mmoja kutoka mwonekano wake pekee."""
__tablename__ = "message_deletions"
id = db.Column(db.Integer, primary_key=True)
message_id = db.Column(db.Integer, db.ForeignKey("messages.id"), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
deleted_at = db.Column(db.DateTime, default=datetime.utcnow)
__table_args__ = (db.UniqueConstraint("message_id", "user_id", name="uq_message_deletion"),)
class ConversationClear(db.Model):
"""'Futa Mazungumzo' — mtumiaji anaficha ujumbe wote uliotumwa kabla ya wakati fulani."""
__tablename__ = "conversation_clears"
id = db.Column(db.Integer, primary_key=True)
conversation_id = db.Column(db.Integer, db.ForeignKey("conversations.id"), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
cleared_before = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
__table_args__ = (db.UniqueConstraint("conversation_id", "user_id", name="uq_conversation_clear"),)
# ── Escrow Model ─────────────────────────────────────────────────────────────
class EscrowStatus(enum.Enum):
held = "held"
released = "released"
refunded = "refunded"
class EscrowTransaction(db.Model):
__tablename__ = "escrow_transactions"
id = db.Column(db.Integer, primary_key=True)
conversation_id = db.Column(db.Integer, db.ForeignKey("conversations.id"), nullable=False)
buyer_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
seller_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
amount_tzs = db.Column(db.BigInteger, nullable=False)
status = db.Column(db.Enum(EscrowStatus), default=EscrowStatus.held, nullable=False)
reference = db.Column(db.String(32), unique=True, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
buyer = db.relationship("User", foreign_keys=[buyer_id], lazy=True)
seller = db.relationship("User", foreign_keys=[seller_id], lazy=True)
conversation = db.relationship("Conversation", foreign_keys=[conversation_id], lazy=True)
# ── Order State Machine ──────────────────────────────────────────────────────
class OrderStatus(enum.Enum):
draft = "draft"
submitted = "submitted"
approved = "approved"
paid = "paid"
completed = "completed"
cancelled = "cancelled"
class PageView(db.Model):
__tablename__ = "page_views"
id = db.Column(db.Integer, primary_key=True)
path = db.Column(db.String(255), nullable=False)
method = db.Column(db.String(10), default="GET")
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
ip_address = db.Column(db.String(45))
user_agent = db.Column(db.String(512))
browser = db.Column(db.String(64))
device = db.Column(db.String(32)) # mobile / desktop / tablet
referrer = db.Column(db.String(512))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
class PWAInstall(db.Model):
__tablename__ = "pwa_installs"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
ip_address = db.Column(db.String(45))
user_agent = db.Column(db.String(512))
platform = db.Column(db.String(32)) # android / ios / desktop
created_at = db.Column(db.DateTime, default=datetime.utcnow)
class Order(db.Model):
__tablename__ = "orders"
id = db.Column(db.Integer, primary_key=True)
conversation_id = db.Column(db.Integer, db.ForeignKey("conversations.id"), nullable=False, unique=True)
buyer_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
seller_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
listing_id = db.Column(db.Integer, db.ForeignKey("market_listings.id"), nullable=False)
quantity_kg = db.Column(db.Float, nullable=False)
price_tzs = db.Column(db.BigInteger, nullable=False)
status = db.Column(db.Enum(OrderStatus), default=OrderStatus.draft, nullable=False)
note = db.Column(db.Text, nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
buyer = db.relationship("User", foreign_keys=[buyer_id], lazy=True)
seller = db.relationship("User", foreign_keys=[seller_id], lazy=True)
listing = db.relationship("MarketListing", foreign_keys=[listing_id], lazy=True)
conversation = db.relationship("Conversation", foreign_keys=[conversation_id], lazy=True)
# ── EscrowFee (Sprint 8 — Framework-ready, off by default) ───────────────────
class EscrowFee(db.Model):
__tablename__ = "escrow_fees"
id = db.Column(db.Integer, primary_key=True)
order_id = db.Column(db.Integer, db.ForeignKey("orders.id"), nullable=False, unique=True)
buyer_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
seller_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
order_amount = db.Column(db.BigInteger, nullable=False)
fee_rate = db.Column(db.Float, default=0.025, nullable=False)
fee_amount = db.Column(db.BigInteger, default=0, nullable=False)
status = db.Column(db.String(20), default="pending", nullable=False)
is_active = db.Column(db.Boolean, default=False, nullable=False)
waived_reason = db.Column(db.String(255), nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
released_at = db.Column(db.DateTime, nullable=True)
order = db.relationship("Order", foreign_keys=[order_id], lazy=True)
buyer = db.relationship("User", foreign_keys=[buyer_id], lazy=True)
seller = db.relationship("User", foreign_keys=[seller_id], lazy=True)
def calculate_fee(self):
"""Hesabu fee — returns 0 kama is_active=False (framework-ready)."""
if not self.is_active:
self.fee_amount = 0
self.waived_reason = "Escrow fees not yet active"
return 0
fee = int(self.order_amount * self.fee_rate)
self.fee_amount = fee
return fee
class Partnership(db.Model):
__tablename__ = "partnerships"
id = db.Column(db.Integer, primary_key=True)
organization_name = db.Column(db.String(150), nullable=False)
organization_type = db.Column(db.String(20), default="company", nullable=False) # institution/company/ngo/government/other
interest_type = db.Column(db.String(20), default="both", nullable=False) # institutional/commercial/both
contact_name = db.Column(db.String(100), nullable=False)
contact_email = db.Column(db.String(150), nullable=False)
contact_phone = db.Column(db.String(30), nullable=True)
website = db.Column(db.String(255), nullable=True)
message = db.Column(db.Text, nullable=False)
status = db.Column(db.String(20), default="pending", nullable=False) # pending/reviewing/contacted/approved/declined
admin_notes = db.Column(db.Text, nullable=True)
reviewed_by_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
reviewed_at = db.Column(db.DateTime, nullable=True)
reviewed_by = db.relationship("User", foreign_keys=[reviewed_by_id], lazy=True)
edited_at = db.Column(db.DateTime, nullable=True)
edited_by_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
edited_by = db.relationship("User", foreign_keys=[edited_by_id], lazy=True)
# ── Login Manager ─────────────────────────────────────────────────────────────
@login_manager.user_loader
def load_user(user_id):
user = User.query.get(int(user_id))
# SECURITY FIX: akaunti iliyosimamishwa haiingii hata na session hai
if user and not user.is_active:
return None
return user
# ── Trust Engine ──────────────────────────────────────────────────────────────
# Inahesabu trust level ya user automatically baada ya kila event muhimu
TRUST_THRESHOLDS = {
"gray": {"points": 0, "tx": 0, "rating": 0.0, "flags_max": 99},
"green": {"points": 10, "tx": 1, "rating": 0.0, "flags_max": 2},
"teal": {"points": 50, "tx": 5, "rating": 4.0, "flags_max": 1},
"gold": {"points": 120, "tx": 15, "rating": 4.5, "flags_max": 0},
}
def trust_engine(user_id):
"""
Recalculates trust level for a user based on:
- transaction_count (listings posted + inquiries made)
- avg_rating (from SellerRating)
- flag_count (from ListingReport against user)
- account age
Updates user in-place and commits.
"""
user = User.query.get(user_id)
if not user:
return
# 1. Hesabu avg rating kutoka SellerRating
ratings = SellerRating.query.filter_by(seller_id=user_id).all()
if ratings:
user.avg_rating = round(sum(r.stars for r in ratings) / len(ratings), 2)
else:
user.avg_rating = 0.0
# 2. Hesabu transaction_count (listings zake + conversations kama buyer)
listing_count = MarketListing.query.filter_by(
seller_id=user_id, is_available=True
).count()
conv_count = Conversation.query.filter_by(buyer_id=user_id).count()
user.transaction_count = listing_count + conv_count
# 3. Hesabu flag_count (reports zilizofanywa dhidi ya listings zake)
flagged = (
db.session.query(ListingReport)
.join(MarketListing, ListingReport.listing_id == MarketListing.id)
.filter(MarketListing.seller_id == user_id)
.count()
)
user.flag_count = flagged
# 4. Account age kwa siku
age_days = (datetime.utcnow() - user.created_at).days
# 5. Hesabu trust_points
points = 0
points += user.transaction_count * 5
points += int(user.avg_rating * 8)
points += max(0, min(age_days, 60)) # max 60 points kwa umri
points -= user.flag_count * 15 # adhabu kwa flags
user.trust_points = max(0, points)
# 6. Amua trust level
if user.flag_count >= 3:
new_level = "gray"
elif (
user.trust_points >= TRUST_THRESHOLDS["gold"]["points"]
and user.transaction_count >= TRUST_THRESHOLDS["gold"]["tx"]
and user.avg_rating >= TRUST_THRESHOLDS["gold"]["rating"]
and user.flag_count <= TRUST_THRESHOLDS["gold"]["flags_max"]
):
new_level = "gold"
elif (
user.trust_points >= TRUST_THRESHOLDS["teal"]["points"]
and user.transaction_count >= TRUST_THRESHOLDS["teal"]["tx"]
and user.avg_rating >= TRUST_THRESHOLDS["teal"]["rating"]
and user.flag_count <= TRUST_THRESHOLDS["teal"]["flags_max"]
):
new_level = "teal"
elif (
user.trust_points >= TRUST_THRESHOLDS["green"]["points"]
and user.transaction_count >= TRUST_THRESHOLDS["green"]["tx"]
and user.flag_count <= TRUST_THRESHOLDS["green"]["flags_max"]
):
new_level = "green"
else:
new_level = "gray"
user.trust_level = new_level
# 7. Fungua/funga uwezo kulingana na level
user.can_post_listing = new_level in ("green", "teal", "gold")
user.can_advise = new_level in ("teal", "gold")
user.can_b2b = new_level in ("green", "teal", "gold")
user.trust_updated_at = datetime.utcnow()
db.session.commit()
return new_level
def trust_badge_html(trust_level):
"""Returns badge HTML for templates (safe to use with |safe filter)"""
badges = {
"gray": ('<span class="trust-badge trust-gray">Mpya</span>', "●"),
"green": ('<span class="trust-badge trust-green">Mwanachama</span>', "●"),
"teal": ('<span class="trust-badge trust-teal">Mwaminifu</span>', "●"),
"gold": ('<span class="trust-badge trust-gold">Imara</span>', "●"),
}
return badges.get(trust_level, badges["gray"])
# ── Phone Masking Helper ──────────────────────────────────────────────────────
def mask_phone(phone):
"""Server-side masking — namba halisi haifiki browser ya guest kamwe"""
if not phone:
return "***"
p = str(phone).strip()
if len(p) <= 6:
return "***"
return p[:3] + "***" + p[-3:]
def get_display_phone(phone):
"""Returns masked or real phone based on login status"""
if current_user.is_authenticated:
return phone
return mask_phone(phone)
# ── Weather Service (unchanged logic) ────────────────────────────────────────
def get_weather(city="Mbeya"):
if not WEATHER_API_KEY:
return {"error": "API key haijawekwa", "city": city, "success": False}
cached = (
WeatherLog.query.filter_by(city=city)
.order_by(WeatherLog.fetched_at.desc())
.first()
)
if cached:
age = datetime.utcnow() - cached.fetched_at
if age < timedelta(minutes=30):
return {
"city": city,
"temperature": cached.temperature,
"humidity": cached.humidity,
"description": cached.description,
"wind_speed": cached.wind_speed,
"icon": cached.icon,
"success": True,
"cached": True,
"cache_age_mins": int(age.total_seconds() / 60),
}
tz_cities = {
"mbeya": {"lat": -8.9000, "lon": 33.4600},
"dar es salaam": {"lat": -6.7924, "lon": 39.2083},
"dodoma": {"lat": -6.1730, "lon": 35.7395},
"arusha": {"lat": -3.3869, "lon": 36.6830},
"mwanza": {"lat": -2.5164, "lon": 32.9175},
"tanga": {"lat": -5.0690, "lon": 39.0987},
"morogoro": {"lat": -6.8160, "lon": 37.6833},
"iringa": {"lat": -7.7700, "lon": 35.6930},
"kilimanjaro": {"lat": -3.0674, "lon": 37.3556},
"tabora": {"lat": -5.0167, "lon": 32.8000},
"kigoma": {"lat": -4.8771, "lon": 29.6278},
"singida": {"lat": -4.8185, "lon": 34.7500},
"songwe": {"lat": -9.3500, "lon": 33.2000},
"lindi": {"lat": -9.9970, "lon": 39.7140},
"mtwara": {"lat": -10.2667, "lon": 40.1833},
"kagera": {"lat": -1.2833, "lon": 31.7667},
"geita": {"lat": -2.8667, "lon": 32.1667},
"shinyanga": {"lat": -3.6600, "lon": 33.4200},
"rukwa": {"lat": -7.9000, "lon": 31.4167},
"ruvuma": {"lat": -10.6833, "lon": 35.6500},
}
city_key = city.lower().strip()
coords = tz_cities.get(city_key)
params = (
{
"lat": coords["lat"],
"lon": coords["lon"],
"appid": WEATHER_API_KEY,
"units": "metric",
"lang": "sw",
}
if coords
else {
"q": f"{city},TZ",
"appid": WEATHER_API_KEY,
"units": "metric",
"lang": "sw",
}
)
try:
resp = requests.get(WEATHER_BASE_URL, params=params, timeout=5)
resp.raise_for_status()
data = resp.json()
weather_data = {
"city": city,
"temperature": data["main"]["temp"],
"feels_like": data["main"]["feels_like"],
"humidity": data["main"]["humidity"],
"description": data["weather"][0]["description"],
"wind_speed": data["wind"]["speed"],
"icon": data["weather"][0]["icon"],
"success": True,
}
log = WeatherLog(
city=city,
temperature=weather_data["temperature"],
humidity=weather_data["humidity"],
description=weather_data["description"],
wind_speed=weather_data["wind_speed"],
icon=weather_data["icon"],
)
db.session.add(log)
db.session.commit()
return weather_data
except Exception as exc:
cached = (
WeatherLog.query.filter_by(city=city)
.order_by(WeatherLog.fetched_at.desc())
.first()
)
if cached:
return {
"city": cached.city,
"temperature": cached.temperature,
"humidity": cached.humidity,
"description": cached.description,
"wind_speed": cached.wind_speed,
"icon": cached.icon,
"success": True,
"cached": True,
}
return {"error": str(exc), "city": city, "success": False}
def get_forecast(city="Mbeya"):
if not WEATHER_API_KEY:
return []
params = {"q": f"{city},TZ", "appid": WEATHER_API_KEY, "units": "metric", "cnt": 5}
try:
resp = requests.get(FORECAST_BASE_URL, params=params, timeout=5)
resp.raise_for_status()
return [
{
"dt_txt": i["dt_txt"],
"temperature": i["main"]["temp"],
"description": i["weather"][0]["description"],
"icon": i["weather"][0]["icon"],
}
for i in resp.json().get("list", [])
]
except Exception as e:
print(f"Weather API error: {e}")
return []
# ── Routes ────────────────────────────────────────────────────────────────────
# ── Auth decorators ───────────────────────────────────────────────────────────
def require_phone_verified(f):
"""Zuia endpoint kama namba ya simu haijathibitishwa via OTP."""
@wraps(f)
def decorated(*args, **kwargs):
if not getattr(current_user, "phone_verified", False):
return jsonify({
"error": "Thibitisha namba yako ya simu kwanza.",
"code": "PHONE_NOT_VERIFIED",
"redirect": "/verify-phone"
}), 403
return f(*args, **kwargs)
return decorated
@app.route("/")
def index():
# Auth wall: guest anaona landing page tu
if not current_user.is_authenticated:
# Preview listings 6 tu — bila contact/phone
preview = (
MarketListing.query
.filter_by(is_available=True)
.order_by(MarketListing.posted_at.desc())
.limit(6)
.all()
)
return render_template("landing.html", preview_listings=preview)
crops = Crop.query.order_by(Crop.created_at.desc()).limit(6).all()
listings = (
MarketListing.query.filter_by(is_available=True)
.order_by(MarketListing.posted_at.desc())
.limit(6)
.all()
)
weather = get_weather("Mbeya")
# Platform stats — live kutoka DB
from sqlalchemy import func, distinct
stats = {
"users": db.session.query(func.count(User.id)).scalar() or 0,
"listings": db.session.query(func.count(MarketListing.id)).filter_by(is_available=True).scalar() or 0,
"regions": db.session.query(func.count(distinct(MarketListing.region))).filter_by(is_available=True).scalar() or 0,
"crops": db.session.query(func.count(distinct(MarketListing.crop_name))).filter_by(is_available=True).scalar() or 0,
}
return render_template(
"index.html", crops=crops, listings=listings, weather=weather, stats=stats
)
@app.route("/weather")
def weather_page():
city = sanitize(request.args.get("city", "Mbeya"), max_length=50)
weather = get_weather(city)
forecast = get_forecast(city)
return jsonify({"weather": weather, "forecast": forecast})
# ── AUTH ──────────────────────────────────────────────────────────────────────
@app.route("/login", methods=["GET", "POST"])
@limiter.limit("5 per minute")
def login():
if request.method == "POST":
data = request.get_json() or request.form
phone = sanitize(data.get("phone", ""), max_length=20)
password = data.get(
"password", ""
) # Usiisanitize nywila — chars special zinahitajika
# SECURITY FIX: generic error message — usitaje "phone" au "password" peke yake
user = User.query.filter_by(phone=phone).first()
if not user or not user.check_password(password):
return jsonify({"error": "Namba ya simu au nywila si sahihi."}), 401
# SECURITY FIX: angalia is_active KABLA ya kulogin
if not user.is_active:
return jsonify(
{
"error": "Akaunti yako imesimamishwa. Wasiliana na msimamizi kwa msaada."
}
), 403
login_user(user)
return jsonify({"message": "Umeingia.", "role": user.role})
return render_template("auth/login.html")
@app.route("/register/initiate", methods=["POST"])
@limiter.limit("5 per hour")
def register_initiate():
"""Hatua ya 1: Validate form data, tuma OTP, subiri uthibitisho."""
import json, secrets as _secrets
data = request.get_json() or request.form
# ── Sanitize ─────────────────────────────────────────────────────────────
full_name = sanitize(data.get("full_name", ""), max_length=120)
phone = sanitize(data.get("phone", ""), max_length=20)
email = sanitize(data.get("email", ""), max_length=120) or None
region = sanitize(data.get("region", ""), max_length=80)
role = sanitize(data.get("role", "farmer"), max_length=20)
password = data.get("password", "")
terms = data.get("terms_accepted", False)
# ── Validate ──────────────────────────────────────────────────────────────
if not terms or str(terms).lower() in ("false", "0", ""):
return jsonify({"error": "Lazima ukubali Masharti na Vigezo vya AgroLink."}), 400
if not full_name:
return jsonify({"error": "Jina kamili linahitajika."}), 400
if not validate_phone(phone):
return jsonify({"error": "Namba ya simu si sahihi. Tumia muundo: 0712345678."}), 400
if email and not validate_email(email):
return jsonify({"error": "Muundo wa email si sahihi."}), 400
pw_ok, pw_err = validate_password(password)
if not pw_ok:
return jsonify({"error": pw_err}), 400
# ── Check banned ──────────────────────────────────────────────────────────
if BannedEmail.query.filter_by(phone=phone).first():
return jsonify({"error": "Namba hii imefungwa. Wasiliana na msimamizi."}), 403
if email and BannedEmail.query.filter_by(email=email).first():
return jsonify({"error": "Email hii imefungwa. Wasiliana na msimamizi."}), 403
# ── Check duplicates ──────────────────────────────────────────────────────
if User.query.filter_by(phone=phone).first():
return jsonify({"error": "Namba ya simu tayari imetumika."}), 409
if email and User.query.filter_by(email=email).first():
return jsonify({"error": "Email tayari imetumika."}), 409
# ── Validate role ─────────────────────────────────────────────────────────
if role not in ("farmer", "agent", "buyer", "member"):
role = "farmer"
# ── Futa OTP za zamani za namba hii ──────────────────────────────────────
PhoneOTP.query.filter_by(phone=phone, verified=False).delete()
db.session.flush()
# ── Tengeneza OTP ─────────────────────────────────────────────────────────
otp_code = f"{_secrets.randbelow(900000) + 100000}"
form_payload = json.dumps({
"full_name": full_name, "phone": phone, "email": email,
"region": region, "role": role, "password": password,
})
otp_record = PhoneOTP(
phone=phone,
otp_code=otp_code,
form_data=form_payload,
expires_at=datetime.utcnow() + timedelta(minutes=10),
)
db.session.add(otp_record)
db.session.commit()
# ── Tuma SMS ──────────────────────────────────────────────────────────────
sent = send_otp_sms(phone, otp_code)
if not sent:
return jsonify({"error": "Imeshindwa kutuma SMS. Jaribu tena."}), 500
resp = {"message": "OTP imetumwa.", "phone": phone}
if OTP_MOCK:
resp["otp_dev"] = otp_code # Development only — ondoa production
return jsonify(resp), 200
@app.route("/register/verify", methods=["POST"])
@limiter.limit("10 per hour")
def register_verify():
"""Hatua ya 2: Thibitisha OTP na unda akaunti."""
import json
data = request.get_json() or request.form
phone = sanitize(data.get("phone", ""), max_length=20)
otp_code = sanitize(data.get("otp_code", ""), max_length=6)
if not phone or not otp_code:
return jsonify({"error": "Taarifa hazitoshi."}), 400