Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 58

A

PROJECT
ON
DEVELOPMENT OF SOFTWARE APPLICATION FOR AN INTEGRATED E-
COMMERCE PLATFORM FOR AGRICULTURAL ENTERPRISES

(APP DESIGN)
Is submitted in partial fulfilment of the requirement

Of
DIPLOMA
In
ELECTRONICS & COMMUNICATION ENGINEERING
Of
STATE BOARD OF TECHNICAL EDUCATION AND TRAINING

SUBMITTED BY

21054-EC-033 S.THARAK SRIHARI


21054-EC-055 V.NITHIN REDDY
21054-EC-028 G.RANJITH
21054-EC-019 P.SAI KIRAN REDDY
21054-EC-045 D.VIKAS

DIPLOMA IN COMPUTER ENGINEERING

GOVERNMENT INSTITUTE OF ELECTRONICS

East Marredpally, Secunderabad

ACKNOWLEDGEMENT
We extend our sincere appreciation to the individuals and entities who
contributed to the realisation of this project. Their support and guidance
played a pivotal role in the project's success.

We would like to express our deepest gratitude to our whole group for
their unwavering support and expertise. Their contributions were instrumental
in overcoming challenges and ensuring the project's successful completion.

We are also indebted to SPR Human Capital Solutions for their valuable
insights and constructive feedback. Their guidance significantly enhanced the
quality of the project.

Thank you to all who played a role in the realisation of this project. Your
collective efforts are sincerely appreciated.

[ S.Tharak Srihari
V.Nithin Reddy
G.Ranjith
P.Sai Kiran Reddy
D.Vikas ]

DEVELOPMENT OF SOFTWARE APPLICATION FOR


AN INTEGRATED E-COMMERCE PLATFORM FOR
AGRICULTURAL ENTERPRISES
INDEX

CONTENT PAGE NO.

ABSTRACT

The demand for organic produce has witnessed a significant surge


in recent years, emphasising the need for efficient and transparent
channels between farmers and consumers. In response to this demand,
we present "TRUE FARMER," a comprehensive eCommerce platform
tailored for the organic farming sector.

Our software project aims to bridge the gap between organic


farmers and environmentally conscious consumers by providing a user-
friendly, secure, and sustainable online marketplace. The platform
facilitates the direct sale of organic products from farmers to
consumers, eliminating intermediaries and ensuring fair compensation
for farmers.

TRUE FARMER strives to empower organic farmers, promote


sustainable agriculture, and provide consumers with a reliable source for
high-quality organic products. By leveraging technology, we aim to
create a digital marketplace that not only facilitates transactions but
also builds a community dedicated to fostering sustainable and
environmentally friendly agricultural practices.

INTRODUCTION

● Begin by visiting the TRUE FARMER website and click on the "Sign Up" or
"Register" button.
● Upon successful registration, log in to your account to access the user
dashboard.
● Browse the platform to discover a diverse range of organic products offered
by local farmers.
● Click on a product to view the detailed vendor profile of the farmer or
producer.
● Select the desired quantity of the product and add it to your cart.
● Proceed to the checkout page, where you'll confirm your delivery address
and select a payment method.
● After completing the payment, you'll receive an order confirmation with
details of your purchase.
● The farmer receives the order and prepares the products for shipment.
● After receiving your order, you have the option to leave a review and
feedback for the farmer.
● Participate in forums and discussions on the platform to connect with other
users, farmers, and experts.

TRUE FARMER aims to simplify the process of connecting


consumers with organic farmers, ensuring a transparent and rewarding
experience for both parties. By following these steps, users can
seamlessly navigate the platform, support local farmers, and contribute
to the growth of sustainable agriculture.
START
PROGRAM

USER USER LOGIN


REGISTRATION

VIEW SEARCH
DASHBOARD PRODUCTS

DISPLAY
RESULTS

ADD TO CART ADD TO VIEW PRODUCT


WISHLIST(optional DETAILS

REVIEW CART PROCEED TO CONFIRM ORDER


CHECKOUT & PAYMENT

END PROGRAM
FRONTEND SOURCE CODE:

Main.dart:

// import "package:farmapp/pages/loginpage_.dart";
import "package:farmapp/pages/homepage_.dart";
// import "package:farmapp/pages/registration_.dart";
import "package:flutter/material.dart" ;
String? token;

void main () {
runApp(const FarmApp());
}

class FarmApp extends StatelessWidget {


const FarmApp ({super.key});

@override
Widget build (BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true
),
home : const HomePage(),
);
}
}

Constants.dart:

// const String farmurl = "http://192.168.0.104:8080";


const String farmurl = "http://192.168.3.207:8080";
const String productlistapi = "$farmurl/product";
const String categorylistapi = "$farmurl/category";
const String cartapi = "$farmurl/cart";
const String cartcountapi = "$farmurl/cartcount";
const String farmersinfoapi = "$farmurl/farmersinfo";
const String staticimg = "$farmurl/static/";
const String filterdproductsapi = "$farmurl/productfilter";
const String myordersapi = "$farmurl/myorders";

global_client.dart:

import "dart:convert";
import "package:farmapp/constants.dart";
import "package:farmapp/models/farmersinfo_model.dart";
import "package:farmapp/models/productslist_model.dart";
import 'package:farmapp/models/category_model.dart';
import 'package:farmapp/models/myorders_model.dart';
import "package:http/http.dart" as http;

class CustomClient {

// Products Future

Future<List<Product>> getOurProducts () async {


http.Response response = await http.get(Uri.parse(productlistapi));
final data = jsonDecode(response.body);
if (response.statusCode != 200) {
throw "Error";
}
List<Product> products = [];
for (Map<String,dynamic> product in data) {
var prd = Product.fromJson(product);
products.add(prd);
await prd.getCartCount();
}
return products;
}

List<Product> prodlist = [];


Future<List<Product>> getProductsSearch () async {
http.Response response = await http.get(Uri.parse(productlistapi));
final data = jsonDecode(response.body);
if (response.statusCode != 200) {
throw "Error";
}
List<Product> products = [];
prodlist = [];
for (Map<String,dynamic> product in data) {
var prd = Product.fromJson(product);
products.add(prd);
prodlist.add(prd);
}
return products;
}

// Catergories Future
Future<List<Category>> getOurCategories() async {
http.Response response = await
http.get(Uri.parse(categorylistapi));
final data = jsonDecode(response.body);
if (response.statusCode != 200) {
throw "Error";
}
List<Category> categories = [];
for (Map<String,dynamic> category in data) {
categories.add(Category.fromJson(category));
}
return categories;
}

// Cart futures
Future<Iterable<Product>> getCart() async {
http.Response response = await http.get(Uri.parse(cartapi));
final data = jsonDecode(response.body);
if (response.statusCode != 200) {
throw "Errors";
}
// print(data);
Map<int, Product> products = {};
for(Map<String, dynamic> prd in data) {
if(prd.containsKey("id") == false) continue;
if(products.containsKey(prd["id"]) == false) {
products[prd["id"]] = Product.fromJson(prd);
}
products[prd["id"]]!.incr();
}
return products.values;
}

Future<int> addtocart(Product prod) async{


http.Response response = await http.post(
Uri.parse(cartapi),
body: jsonEncode(<String,int>{
'product' : prod.id
}),
headers: <String,String> {
'Content-type' : 'application/json'
}
);
final data = jsonDecode(response.body);
if (response.statusCode != 201) {
throw "failed to add";
}
else {
// print("before await ${prod.count}");
await prod.getCartCount();
// print("after await ${prod.count}");
// print("In addtocart fn ${data["count"]}");
return data["count"];
// return prod.count;
}
}

Future<int> deletefromcart(Product prod) async {


http.Response response = await http.delete(
Uri.parse(cartapi),
body: jsonEncode(<String,int>{
"product" : prod.id
}),
headers: <String,String> {
'Content-type' : 'application/json'
}
);
final data = jsonDecode(response.body);
if (response.statusCode != 200) {
return 0;
} else {
await prod.getCartCount();
return data["count"];
}
}

Future<int> getCartCount(int id) async {


http.Response response = await
http.get(Uri.parse('$cartcountapi/$id'));
final data = jsonDecode(response.body);
return data["count"];
}

Future<List<Product>> getProductsFilterByCat(int id) async {


http.Response response = await
http.get(Uri.parse('$filterdproductsapi/$id'));
if (response.statusCode != 200) {
throw "Errors";
}
final data = jsonDecode(response.body);
List<Product> products = [];
for (Map<String,dynamic> product in data) {
var prd = Product.fromJson(product);
products.add(prd);
await prd.getCartCount();
}
return products;
}

// FarmersInfo future
Future<List<FarmersInfo>> getFarmersInfo() async {
http.Response response = await http.get(Uri.parse(farmersinfoapi));
final data = jsonDecode(response.body);
if (response.statusCode != 200) {
throw "error";
}
List<FarmersInfo> farmers = [];
for (Map<String,dynamic> element in data) {
farmers.add(FarmersInfo.fromJson(element));
}
return farmers;
}

Future<List<MyOrders>> getmyOrders() async {


http.Response response = await http.get(Uri.parse(myordersapi));
final data = jsonDecode(response.body);
if (response.statusCode != 200) {
throw "error";
}
List<MyOrders> myorders = [];
for (Map<String,dynamic> element in data) {
myorders.add(MyOrders.fromJson(element));
}
return myorders;
}

Future postmyOrders(Product prod,String quantity) async {


http.Response response = await http.post(
Uri.parse(myordersapi),
body: jsonEncode({
'product' : prod.id,
'quantity' : quantity
}),
headers: <String,String> {
'Content-type' : 'application/json'
}
);
if (response.statusCode != 200) {
throw 'error';
}
return response.body;
}

Future<List<MyOrders>> getMyOrders () async {


http.Response response = await http.get(Uri.parse(myordersapi));
final data = jsonDecode(response.body);
if (response.statusCode != 200) {
throw 'error';
}
List<MyOrders> myorders = [];
for (Map<String,dynamic> element in data) {
myorders.add(MyOrders.fromJson(element));
}
return myorders;
}

deleteCart (Product prod) async{


http.Response response = await http.put(
Uri.parse(cartapi),
body: jsonEncode({
'product' : prod.id,
}),
headers: <String,String> {
'Content-type' : 'application/json'
}
);
if(response.statusCode != 200) {
throw 'error';
}
return response.body;
}

CustomClient client = CustomClient();

Category_model.dart:

import
'package:farmapp/elements/Categoriespage/category_elements.dar
t';

class Category {
final int id ;
final String category;
final String subcategory;
const Category ({
required this.id,
required this.category,
required this.subcategory
});

factory Category.fromJson(Map<String,dynamic> json) {


return Category(
id: json["cat_id"],
category: json["category"],
subcategory: json ["sub_category"]
);
}

CategoryCard getcategory() {
return CategoryCard(label: category,id : id,inst:this);
}

Productslist_model.dart:

import 'package:farmapp/elements/Homepage/productcard.dart';
import 'package:farmapp/globals/global_client.dart';

class Product {
final int id;
final String name;
final String desc;
final String variety;
final int category;
final String image;
int _cartcount = 0;
Product ({
required this.id,
required this.name,
required this.desc,
required this.variety,
required this.category,
required this.image
});

factory Product.fromJson(Map<String, dynamic> json) {


Product prd = Product(
id: json['id'],
name: json['name'],
desc: json['desc'],
variety: json['variety'],
category: json['category'],
image : json['image']
);
// prd.count = json['count'];
return prd;
}

ProductCard getProductCard() {
return ProductCard(
image: image, productname: name,
productdesp: desc, productid : id,
prodinst: this,
);
}

void incr() {
_cartcount += 1;
}

void decr() {
_cartcount -= 1;
}

set count(int value) {


_cartcount = value;
}
int get count {
return _cartcount;
}

Future<int> getCartCount() async {


await client.getCartCount(id).then((value) {
_cartcount=value;
});
return _cartcount;
}
}

Farmersinfo_model.dart:

import
'package:farmapp/elements/MenuPage/farmersinfocard.dart';

class FarmersInfo {
final int id;
final String name;
final String image;
final String acres;
final String crop;
final String location;
final String contact;
final String address;
const FarmersInfo ({
required this.id,
required this.name,
required this.image,
required this.acres,
required this.crop,
required this.location,
required this.contact,
required this.address
});
factory FarmersInfo.fromJson(Map<String,dynamic> json){
return FarmersInfo(
id: json["id"],
name: json["name"],
image: json["image"],
acres: json["acres"],
crop: json["crop"],
location: json["location"],
contact: json["mobilenumber"],
address : json["address"]
);
}

FarmersInfoCard getfarmers() {
return FarmersInfoCard(
name: name,
image: image,
acres: acres,
crop: crop,
location: location,
contact: contact,
address: address
);
}
}

Myorders_model.dart:

// import 'package:farmapp/models/productslist_model.dart';
import
'package:farmapp/pages/profile_page/yourorderspage_.dart';

class MyOrders {
final int id;
final String dateTime;
final String qty;
MyOrders ({
required this.id,
required this.dateTime,
required this.qty
});

factory MyOrders.fromJson(Map<String,dynamic> json) {


return MyOrders(
id: json['id'],
dateTime: json['delivery_date'],
qty: json['quantity']
);
}

YourOrdersCard getCard() {
return YourOrdersCard(
prod: id,
quantity: qty,
datetime: dateTime
);
}
}

Categorpage.dart:

import
'package:farmapp/elements/Categoriespage/category_elements.dar
t';
import 'package:farmapp/elements/Homepage/searchbar.dart';
import 'package:farmapp/pages/searchpage_.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../models/category_model.dart';
import 'package:farmapp/globals/global_client.dart';

class CategoryPage extends StatefulWidget {


const CategoryPage ({super.key});
@override
State<CategoryPage> createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {

@override
Widget build (BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap:() {

Navigator.of(context).push(CupertinoPageRoute(builder:
(context) => const SearchPage()));
},
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: Searchbar(),
)
),
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.symmetric(horizontal:
15,vertical: 10),
child: const Text(
"Our Categories",
style: TextStyle(
fontSize :28,
fontWeight : FontWeight.bold,
fontFamily : "Poppins"
)
),
),
// const SizedBox(height: 10,),
Column(
children: [
FutureBuilder(
future: client.getOurCategories(),
builder: (context,snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting) {
return const Center(child:
CircularProgressIndicator(),);
}
List<CategoryCard> ret = [];
if (snapshot.hasData) {
for (Category element in snapshot.data!)
{
ret.add(
element.getcategory()
);
}
return Column(children: ret,);
}
if (snapshot.hasError) {
throw const Text("Something went
Wrong");
}
return const Column();
}
)
],
)
],
),
),
);
}
}

Searchpage_.dart:
import 'package:farmapp/elements/Homepage/productcard.dart';
import 'package:farmapp/globals/global_client.dart';
import 'package:flutter/material.dart';

// import '../models/productslist_model.dart';

class SearchPage extends StatefulWidget {


const SearchPage ({super.key});

@override
State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {

List<dynamic> displaylist = List.from(client.prodlist);


List<dynamic>? newlist =[];
String determine = "";

search (String value) {


setState(() {
determine = value;
displaylist = client.prodlist.where((element) {
if
(element.name.toLowerCase().contains(value.toLowerCase()) ==
true ) {
return
element.name.toLowerCase().contains(value.toLowerCase());
} else {
return
element.desc.toLowerCase().contains(value.toLowerCase());
}
}).toList();
});
}

var cont =const Expanded(


child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.search),
Text(" Search!")
],
),
),
);

@override
void initState() {
super.initState();
client.getProductsSearch();
}

@override
Widget build (BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
const SizedBox(height: 10,),
Padding(
padding: const EdgeInsets.symmetric(horizontal:
10),
child: SizedBox(
height: MediaQuery.of(context).size.height *
0.070,
child: TextField(
onChanged: (value) => search(value),
decoration: InputDecoration(
hintText: "Search",
hintStyle: const TextStyle(
color: Colors.black54,
fontSize : 16,
fontWeight: FontWeight.w500
),
prefixIcon: const Icon(Icons.search),
prefixIconColor: Colors.black,
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color : Color.fromRGBO(217, 217, 217,
1),
)
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide : const BorderSide(
color : Color.fromRGBO(217,217,217,1)
)
),
suffixIcon: GestureDetector(
onTap: () {
Navigator.of(context).pop();
setState(() {
client.prodlist.clear();
});
},
child: const Icon(Icons.close)
),
filled: true,
fillColor : const Color.fromRGBO(217, 217,
217, 1)
),
),
),
),
determine.isEmpty == true ? cont : Expanded(
child: ListView.builder(
itemCount: displaylist.length,
itemBuilder: (context,index) {
return ProductCard(
productname: displaylist[index].name,
productdesp: displaylist[index].desc,
image: displaylist[index].image,
productid: displaylist[index].id,
prodinst: displaylist[index]
);
}
)
)
],
),
),
);
}

@override
void dispose() {
super.dispose();
setState(() {
client.prodlist.clear();
});
}
}

Cartpage_.dart:

import 'package:farmapp/constants.dart';
import 'package:farmapp/globals/global_client.dart';
// import 'package:farmapp/pages/ordersuccess.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:farmapp/models/productslist_model.dart';
import 'package:lottie/lottie.dart';

class CartPage extends StatefulWidget {


const CartPage ({super.key});
static GlobalKey cartkey = GlobalKey<_CartPageState>();

@override
State<CartPage> createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {

void refresh() {
setState(() {});
}

Future<List<CartCard>> getCartList() async {


List<CartCard> cartcard = [];
for (Product product in await client.getCart()) {
cartcard.add(CartCard(prod: product, notify: refresh,));
}
return cartcard;
}

@override
Widget build (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Cart"),
titleTextStyle: GoogleFonts.poppins(fontSize:
28,fontWeight: FontWeight.w600,color: Colors.black),
actions: [
Padding(
padding: const EdgeInsets.symmetric(horizontal:
10),
child: GestureDetector(
onTap: refresh,
child : const Icon(Icons.refresh)
),
)
],
),
body: SafeArea(
child: SingleChildScrollView(
child: FutureBuilder(
future: client.getCart(),
builder: ((context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting) {
return const Center(child:
CircularProgressIndicator(),);
}
if (snapshot.hasError) {
throw const Text("Something went Wrong");
}
if (snapshot.data!.isEmpty) {
return Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
SizedBox(
height :
MediaQuery.of(context).size.height * 0.35,
),
const Text(
'No item here!!'
),
]
),
);
}
List<CartCard> ret = [];
for (Product element in snapshot.data!) {
ret.add(CartCard(prod: element, notify:
refresh));
}
return Column(
children: ret,
);
}),
)
),
),
bottomNavigationBar: FutureBuilder(
future: client.getCart(),
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting) {
return const Center(child:
CircularProgressIndicator(),);
}
if (snapshot.data!.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
height : MediaQuery.of(context).size.height *
0.15,
),
const Text(
'No item here!!'
),
]
),
);
}
List<Product> prodlist = [];
for (Product element in snapshot.data!) {
prodlist.add(element);
}
return CartBottomBar(prod:prodlist[0],quantity:
prodlist[0].count,);
},
),
);
}
}

class CartBottomBar extends StatefulWidget {


final Product prod;
final int quantity;
const CartBottomBar({
super.key,
required this.prod,
required this.quantity
});

@override
State<CartBottomBar> createState() => _CartBottomBarState();
}

class _CartBottomBarState extends State<CartBottomBar> {

@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: BottomAppBar(
height: MediaQuery.of(context).size.height * 0.08,
elevation: 10,
padding: EdgeInsets.zero,
child: Container(
width: MediaQuery.of(context).size.width * 0.8,
alignment: Alignment.center,
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) {
return Dialog(
child: SizedBox(
height:
MediaQuery.of(context).size.height*0.50,
width:
MediaQuery.of(context).size.width * 0.50,
child: FutureBuilder(
future:
client.postmyOrders(widget.prod, widget.quantity.toString()),
builder: (context, snapshot) {
if (snapshot.connectionState
== ConnectionState.waiting) {
return const Center(child:
CircularProgressIndicator(),);
}
if (snapshot.hasData) {
return FutureBuilder(
future:
client.deleteCart(widget.prod),
builder: (context,
snapshot) {
if (snapshot.hasData) {
return
Lottie.asset('assests/images/Animation - 1701334508536.json');
}
return const Column();
},
);

}
return const Column();
},
),
)
);
}
);
},
child: Container(
// height:
MediaQuery.of(context).size.height * 0.05,
// width:
MediaQuery.of(context).size.width * 0.4,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.yellow,
),
alignment: Alignment.center,
child: Text(
"Place Order",
style: GoogleFonts.poppins(fontSize:
20),
),
),
)
),
),
),
);
}
}

class CartCard extends StatelessWidget {


final Product prod;
final Function() notify;
const CartCard ({
super.key,
required this.prod,
required this.notify
});

@override
Widget build (BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(10, 4, 10, 4),
child:Container(
padding: const EdgeInsets.all(10),
height: 180,
width: double.infinity,
decoration: BoxDecoration(
color: const Color.fromRGBO(217, 217, 217, 1),
borderRadius: BorderRadius.circular(15)
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
width: 154,
height: 155,
clipBehavior: Clip.hardEdge,
decoration: BoxDecoration(
color: const Color.fromRGBO(217, 217, 217, 1),
borderRadius: BorderRadius.circular(15)
),
child: Image.network(
staticimg + prod.image,
fit: BoxFit.fill,
),
),
const SizedBox(width: 10,),
SizedBox(
// color: Colors.red,
width: 155,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 10,),
SizedBox(
// color: Colors.grey,
width: 160,
child: Text(
prod.name,
style:
GoogleFonts.poppins(fontSize:20 ),
overflow: TextOverflow.visible,
),
),
const SizedBox(height: 10,),
SizedBox(
width: 160,
// color: Colors.grey,
child: Text(
"quantity : 1kg",
style: GoogleFonts.poppins(fontSize:
18),
),
),
const SizedBox(height: 10,),
CartAddtoCart(prod : prod ,notify:notify),
],
),
),
// Checkbox(
// value: _isactive,
// onChanged: (newbool) {
// setState(() {
// _isactive = newbool;
// });
// },
// )
],
),
),
);
}
}

class CartAddtoCart extends StatefulWidget {


final Product prod;
final Function() notify;
const CartAddtoCart ({super.key,required this.prod,required
this.notify});

@override
State<CartAddtoCart> createState() => _CartAddtoCartState();
}
class _CartAddtoCartState extends State<CartAddtoCart> {
// bool? _isactive = true;
Future<int>? _method;
bool? refresh = false;

void _incrementcounter () {
setState(() {
_method = client.addtocart(widget.prod);
});
}

void _decrementcounter() {
_method = client.deletefromcart(widget.prod);
_method!.whenComplete(() {
_method!.then((value) {
if (value == 0) {
widget.notify();
}
});
});
setState(() {});
}

Container getRow() {
var future = FutureBuilder(
future:_method,
builder: (context, snapshot) {
if(snapshot.connectionState ==
ConnectionState.waiting) {
return const SizedBox(
width: 10,
height:10,
child: CircularProgressIndicator());
}
widget.prod.count = snapshot.data as int;
return Text("${widget.prod.count}");
},
initialData: widget.prod.count,
);
return Container(
height: MediaQuery.of(context).size.height * 0.04,
width: MediaQuery.of(context).size.width * 0.25,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.yellow
),
child: Row(
children: [
const SizedBox(width: 8,),
GestureDetector(
onTap: _decrementcounter,
child: const Icon(Icons.remove)
),
const SizedBox(width: 10,),
future,
const SizedBox(width: 10,),
GestureDetector(
onTap: _incrementcounter,
child: const Icon(Icons.add)
)
],
),
);
}

@override
Widget build (BuildContext context) {
return getRow();
}
}

BACKEND SOURCE CODE:

Product_model.py:

from django.db import models

class ProductCategory(models.Model):
# example vegitables, Groceries, Meat and etc
cat_id = models.BigAutoField(primary_key=True)
category = models.CharField(max_length=250, unique=True,
blank=False, null=False)
sub_category = models.CharField(
max_length=250, blank=False, null=False,
default="nosub"
)

class Meta:
unique_together = ("category", "sub_category")

def __str__(self):
return self.category

@staticmethod
def get_categories():
return [c for c in ProductCategory.objects.all()]

@staticmethod
def create_product_category(category,
sub_category="nosub"):
pc = ProductCategory(
category=category.lower(),
sub_category=sub_category.lower()
)
pc.save()
return pc

def update_category(self, category):


self.category = category
self.save()

def user_directory_path(instance, filename):


# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return "images/{name}".format(name=filename)

class Brand(models.Model):
# product brand
name = models.CharField(max_length=250, unique=True,
null=False, blank=False)
# set upload_to variable
logo = models.ImageField(upload_to=user_directory_path,
blank=True)
def user_path_products(instance,filename) :
return "images/products/{name}".format(name=filename)

class Product(models.Model):
# product registery
name = models.CharField(max_length=250, blank=False,
null=False)
desc =
models.CharField(max_length=250,blank=False ,null=False)
variety = models.CharField(
max_length=250, blank=False, null=False,
default="novariety"
)
category = models.ForeignKey(ProductCategory,
on_delete=models.CASCADE)
# product_id = models.IntegerField()
image =
models.ImageField(upload_to=user_path_products,blank=False)

@staticmethod
def filter_by_category(cat_id):
return Product.objects.filter(category=cat_id)

class QRandBarCode(models.Model):
identifier = models.BigAutoField(primary_key=True)
code = models.CharField(max_length=250, unique=True,
null=False, blank=False)
code_choices = [
("BAR", "BAR"),
("QR", "QR"),
] # edited CodeTypes to Code Types and models.TextChoices
code_type = models.CharField(choices=code_choices,
max_length=3)
product = models.ForeignKey(Product,
on_delete=models.CASCADE)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
unit = models.CharField(max_length=50)
@staticmethod
def get_product_by_id(prod_id):
return QRandBarCode.objects.filter(product=prod_id)

class Stock(models.Model):
qr_or_bar_code = models.ForeignKey(QRandBarCode,
on_delete=models.CASCADE)
num_of_units = models.PositiveIntegerField()
price = models.IntegerField()
batch_date = models.DateTimeField()
batch_code = models.CharField(null=True, blank=True,
max_length=250)

import datetime

now = str(datetime.datetime.now())

# for just
class MyOrders(models.Model):
product =
models.ForeignKey(Product,on_delete=models.DO_NOTHING)
delivery_date =
models.DateTimeField(auto_created=True,auto_now_add=now)
quantity = models.CharField(max_length=2)

Product_serializer.py:

from rest_framework import serializers


from datamodeling.models.product import *

class ProductCategorySerializer(serializers.ModelSerializer):
class Meta:
model = ProductCategory
fields = "__all__"

class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = "__all__"

class BrandSerializer(serializers.ModelSerializer):
class Meta:
model = Brand
fields = ("id", "name", "logo")

class QRandBarCodeSerializer(serializers.ModelSerializer):
class Meta:
model = QRandBarCode
fields = "__all__"

class StockSerializer(serializers.ModelSerializer):
class Meta:
model = Stock
fields = "__all__"

class MyOrdersSerializer(serializers.ModelSerializer):
class Meta:
model = MyOrders
fields = "__all__"

Commonser serializer.py:

from rest_framework import serializers


from datamodeling.models import Product, Cart
from loguru import logger
import traceback

class CommonSerializer(serializers.ModelSerializer):

def to_representation(self, instance):


prod_id = instance.product_id
ret = {}
try:
data = Product.objects.get(id=prod_id)
ret.update({
"cart_id" : instance.id,
"id" : data.id,
"name" : data.name,
"desc" : data.desc,
"variety" : data.variety,
"category" : data.category.cat_id,
"image" : data.image.url,
# "count" :
len(Cart.objects.filter(product=prod_id))
})
except Exception as e:
logger.error(str(e))
logger.debug(traceback.format_exc())
return ret

Product_view.py:

from rest_framework.views import APIView


from datamodeling.models.product import *
from datamodeling.serializers.product import *
from rest_framework.response import Response
from rest_framework import status
"""APIView of ProductCategory"""

class ProductCategoryList(APIView):
def get(self, request):
category = ProductCategory.objects.all()
serializer = ProductCategorySerializer(category,
many=True)
return Response(data=serializer.data,
status=status.HTTP_200_OK)

def post(self, request):


data = request.data
serializer = ProductCategorySerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_201_CREATED)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def patch(self, request):


data = request.data
id = data.get("cat_id")
if id is None or isinstance(id, int) is False:
return Response(
data={"errors": ["id should be a integer"]},
status=status.HTTP_418_IM_A_TEAPOT,
)
try:
pc_id =
ProductCategory.objects.get(cat_id=data["cat_id"])
except ProductCategory.DoesNotExist:
return Response(
data={"errors": ["id does not exists"]},
status=status.HTTP_400_BAD_REQUEST,
)
serializer = ProductCategorySerializer(pc_id,
data=data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_200_OK)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def delete(self, request):


data = request.data
obj = data.get('cat_id')
category = ProductCategory.objects.filter(cat_id=obj)
category.delete()
return Response(
{"messsage": "object deleted"},
status=status.HTTP_204_NO_CONTENT
)

"""APIView of Products"""

class ProductList(APIView):
def get(self, request):
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(data=serializer.data)

def post(self, request):


data = request.data
serializer = ProductSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_201_CREATED)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def patch(self, request):


data = request.data
id = data.get("id")
if id is None is False:
return Response(
data={"errors": ["id shall be a valid
integer"]},
status=status.HTTP_400_BAD_REQUEST,
)
try:
product_id = Product.objects.get(id=data["id"])
except Product.DoesNotExist:
return Response(
data={"errors": ["id is not valid"]},
status=status.HTTP_400_BAD_REQUEST
)
serializer = ProductSerializer(product_id, data=data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_200_OK)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def delete(self, request):


data = request.data
obj = data.get("id")
product = Product.objects.filter(id=obj)
product.delete()
return Response(
{"message": "object deleted"},
status=status.HTTP_204_NO_CONTENT
)
"""APIView of Brand"""

class BrandList(APIView):
def get(self, request):
brands = Brand.objects.all()
serializer = BrandSerializer(brands, many=True)
return Response(data=serializer.data)

def post(self, request):


data = request.data
serializer = BrandSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_201_CREATED)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def patch(self, request):


data = request.data
id = data.get("id")
if id is None or isinstance(id, int) is False:
return Response(data={"errors": ["id should be a
integer"]})
try:
brand_id = Brand.objects.get(id=data["id"])
except Brand.DoesNotExist:
return Response(
data={"errors": ["id does not exists"]},
status=status.HTTP_400_BAD_REQUEST,
)
serializer = BrandSerializer(brand_id, data=data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_200_OK)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def delete(self, request):


data = request.data
obj = data.get("id")
brand = Brand.objects.filter(id=obj)
brand.delete()
return Response(
{"message": "object deleted"},
status=status.HTTP_204_NO_CONTENT
)

"""APIView of ORandBarCode"""

class QRandBarCodeList(APIView):
def get(self, request):
qr = QRandBarCode.objects.all()
serializer = QRandBarCodeSerializer(qr, many=True)
return Response(data=serializer.data,
status=status.HTTP_200_OK)

def post(self, request):


data = request.data
serializer = QRandBarCodeSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_201_CREATED)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def patch(self, request):


data = request.data
id = data.get("identifier")
if id is None or isinstance(id, int) is False: #
id.type == int is False
return Response(
data={"errors": ["id should be a integer"]},
status=status.HTTP_400_BAD_REQUEST,
)
try:
qr_id =
QRandBarCode.objects.get(identifier=data["identifier"])
except QRandBarCode.DoesNotExist:
return Response(
data={"errors": ["id does not exists"]},
status=status.HTTP_400_BAD_REQUEST,
)
serializer = QRandBarCodeSerializer(qr_id, data=data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_200_OK)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def delete(self, request):


data = request.data
obj = data.get("identifier")
qr = QRandBarCode.objects.filter(identifier=obj)
qr.delete()
return Response(
{"meassage": "object delted"},
status=status.HTTP_204_NO_CONTENT
)

"""APIView of Stock"""
class StockList(APIView):
def get(self, request):
stock = Stock.objects.all()
serializer = StockSerializer(stock, many=True)
return Response(data=serializer.data,
status=status.HTTP_200_OK)

def post(self, request):


data = request.data
serializer = StockSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_201_CREATED)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def patch(self, request):


data = request.data
id = data.get("id")
if id is None or isinstance(id, int) is False:
return Response(
data={"errors": ["id should be a integer"]},
status=status.HTTP_400_BAD_REQUEST,
)
try:
stock_id = Stock.objects.get(id=data["id"])
except:
return Response(
data={"errors": "id does not exists"},
status=status.HTTP_400_BAD_REQUEST,
)
serializer = StockSerializer(stock_id, data=data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data,
status=status.HTTP_200_OK)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def delete(self, request):


data = request.data
obj = data.get("id")
stock = Stock.objects.filter(id=obj)
stock.delete()
return Response(
{"message": "object deleted"},
status=status.HTTP_204_NO_CONTENT
)

class FilterdProducts(APIView):

def get(self,request,*args,**kwargs):
id = kwargs.get("id")
data = Product.filter_by_category(id)
ser = ProductSerializer(data,many=True)
return Response(data =
ser.data,status=status.HTTP_200_OK)

class MyOrdersView(APIView):
def get(self,request):
data = MyOrders.objects.all()
serializer = MyOrdersSerializer(data,many=True)
return
Response(data=serializer.data,status=status.HTTP_200_OK)

def post(self,request):
data = request.data
serializer = MyOrdersSerializer(data=data)
if serializer.is_valid():
serializer.save()
return
Response(data=serializer.data,status=status.HTTP_200_OK)
print(serializer.errors)
return
Response(data=serializer.errors,status=status.HTTP_400_BAD_REQ
UEST)

URLS:

from django.urls import path


from datamodeling.views import product
from datamodeling.views import infra
# from dbrestapi.jwtauth import authenticate

urlpatterns = [
path("category/", product.ProductCategoryList.as_view(),
name="productcategory"),
path("product", product.ProductList.as_view(),
name="productview"),
path("brand", product.BrandList.as_view(),
name="brandview"),
path("QRandBAR", product.QRandBarCodeList.as_view(),
name="qrandbarview"),
path("stock", product.StockList.as_view(),
name="stockview"),
path("cart",infra.CartList.as_view(), name="cartview"),

path("cartcount/<int:id>",infra.CartCount.as_view(),name="cart
countview"),

path("productfilter/<int:id>",product.FilterdProducts.as_view(
),name="productfilterview"),

path("farmersinfo",infra.FarmersInfoList.as_view(),name="farme
rsinfoview"),
path("myorders",product.MyOrdersView.as_view(),name='myordersv
iew')
# path("signup", authenticate.UserRegistration.as_view(),
name="signupview"),
# path("login", authenticate.Login.as_view(),
name="loginview"),
]

RESOURCES :

DART OVERVIEW

Dart provides a powerful and versatile environment for developers, enabling


them to build applications ranging from web interfaces to mobile and desktop
applications. Its simplicity, coupled with the Flutter framework, makes it an excellent
choice for those looking to create visually appealing and performant cross-platform
applications.
With a growing community and strong backing from Google, Dart continues
to evolve, making it an exciting language for modern development projects.

PYTHON OVERVIEW

Python stands out as a versatile language for app development, offering a


range of frameworks and features that cater to different needs. For web
applications, Flask and Django are prominent choices, providing robust and scalable
solutions.
Python's adaptability extends to mobile app development with frameworks
like Kivy and BeeWare, allowing developers to create cross-platform applications
efficiently. What sets Python apart is its rapid prototyping capabilities, thanks to its
concise syntax and readability, making it an ideal language for quickly turning app
ideas into functional prototypes.
The extensive Python developer community further enhances the app
development experience, providing support, resources, and a wealth of libraries.
Whether you're building web applications, mobile apps, or prototypes, Python's
ecosystem, documentation, and community support contribute to a seamless and
efficient app development process.
FLUTTER OVERVIEW :

Flutter is a UI toolkit developed by Google for building natively compiled


applications for mobile, web, and desktop from a single codebase. It allows
developers to use a single programming language, Dart, to create high-performance
apps that can run on different platforms.

One of Flutter's key features is its hot reload capability, enabling developers to see
the results of their code changes instantly without restarting the app. This makes the
development process faster and more interactive.

Flutter uses a widget-based architecture, where everything in the user interface is a


widget. Widgets are combined to create the overall app layout and design. Flutter's
rich set of customizable widgets allows developers to create visually appealing and
responsive interfaces.

The framework is known for its flexibility, speed, and ability to provide a native-like
experience on both Android and iOS platforms. It has gained popularity for its cross-
platform development capabilities and is widely used by developers for creating
mobile applications.

DJANGO OVERVIEW :
Django Rest Framework (DRF) is like the Django of the API world—it's a
powerful and flexible toolkit for building Web APIs in Django applications. If Django
is the framework for building web applications, DRF is the toolkit for adding API
functionality to those applications.

DRF makes it easier to develop RESTful APIs by providing a set of tools and
conventions for common tasks. It includes features like serialization, authentication,
permissions, and viewsets, making it efficient to build APIs that follow best
practices.

Here's a quick breakdown of some key components:


Serialization: DRF allows you to convert complex data types, such as Django
models, into Python data types that can be easily rendered into JSON or other
content types.
Viewsets and Routers: DRF introduces the concept of viewsets, which are
classes that define the CRUD (Create, Read, Update, Delete) operations for
your API. Routers help you automatically wire up the URLs for your API.
Authentication and Permissions: DRF provides various authentication classes
(token-based, session-based, etc.) and permission classes to control access
to your API.
Browsable API: DRF comes with a browsable and interactive API, making it easy
for developers to understand, test, and interact with the API directly from the
browser.

In a nutshell, if you're building a web application with Django and you need to expose
data through APIs, Django Rest Framework is your go-to companion for creating
robust and feature-rich RESTful APIs.

INFERENCE:

1. Empowering Organic Farmers:


- The platform connects organic farmers directly with consumers, reducing
dependence on intermediaries.

2. Transparency and Trust:


- The software promotes transparency in transactions by providing detailed
information about the source of each product, cultivation practices, and
certifications..

3. User-Friendly Interface:
- The user interface is designed to be user-friendly, making it easy for both farmers
and consumers to navigate the platform.

4. Sustainable Agriculture Awareness:


- Educational resources on organic farming practices contribute to consumer
awareness and promote sustainable agriculture.

5. Community Building:
- Forums and community engagement features encourage users, including
farmers and consumers, to connect, share experiences, and discuss sustainable
farming practices.

6. Secure Transactions:
- The integrated payment gateways ensure secure transactions, fostering
confidence among users in making online purchases.

7. Logistics Integration:
- Integrated logistics ensure a smooth and timely delivery process, enhancing the
end-to-end user experience.

8. Database Management:
- The system architecture includes a well-designed database structure to securely
store user data and product information.

9. Iterative Design Process:


- The design process involves iterations based on feedback, ensuring that the
software meets user requirements and expectations.

10. Efficient Order Fulfilment:


- The order fulfilment process involves farmers receiving and processing orders
efficiently, ensuring timely delivery to consumers.

11. Wishlist Feature (Optional):


- The optional wishlist feature allows users to save desired products for future
consideration, contributing to a personalised shopping experience.

12. Scalability:
- The modular design and well-defined architecture suggest scalability, enabling the
platform to accommodate future enhancements and features.

In conclusion, the TRUE FARMER software project appears to


be a comprehensive and user-centric solution that addresses the
specific needs of organic farmers and environmentally conscious
consumers.
The platform not only facilitates e-commerce transactions but
also promotes a sense of community and awareness around
sustainable agriculture.

FUTURE IMPROVEMENTS:

In order to advance the TRUE FARMER software project,


several key improvements can be considered for future
development. Firstly, the creation of a mobile application for
Android and iOS platforms could significantly broaden the
platform's reach, allowing users to access the marketplace
conveniently from their mobile devices.

Integration with agricultural data sources could provide real-


time information on crop yields and weather conditions, aiding
farmers in decision-making. Implementing machine learning
algorithms to offer smart product recommendations based on user
behaviour and preferences could personalise the shopping
experience.

Multi-language support, collaboration with certification bodies,


and the incorporation of blockchain technology for supply chain
transparency are crucial features to consider for enhancing the
platform's credibility and global accessibility.

You might also like