Skip to content

Commit

Permalink
Add message functionality, placing order, and add to cart in firebase…
Browse files Browse the repository at this point in the history
… database
  • Loading branch information
codewith-usama committed Nov 18, 2023
1 parent 0a32043 commit f5c697a
Show file tree
Hide file tree
Showing 17 changed files with 618 additions and 86 deletions.
3 changes: 3 additions & 0 deletions lib/consts/firebase_consts.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ User? currentUser = auth.currentUser;
const usersCollection = "users";
const productsCollection = "products";
const cartCollection = "cart";
const chatsCollection = "chats";
const messagesCollection = "messages";
const ordersCollection = "orders";
3 changes: 3 additions & 0 deletions lib/consts/list.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,6 @@ const itemDetailsButtonsList = [

const profileButtonList = [wishlist, orders, messages];
const profileButtonIconsList = [icOrder, icOrder, icMessages];

const paymentMethodsImgList = [imgCod, imgStripe, imgPaypal];
const paymentMethhodsList = [cod, stripe, paypal];
11 changes: 11 additions & 0 deletions lib/consts/strings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const signup = "Sign up";
const loggedin = "Logged in successfully";
const loggedout = "Logged ou successfully";
const updated = "Updated";
const typeMessage = "Type a message...";

const createNewAccount = "or, create new account";
const loginWith = "Log in with";
Expand Down Expand Up @@ -74,3 +75,13 @@ const wishlist = "Wish List",
oldPass = "Old Password",
newPass = "New Password",
wrongOldPass = "Wrong Old Password";

// shipping screen string
const address = "Address",
city = "City",
state = "State",
postalCode = "Postal Code",
phone = "Phone";

// payment methods string
const paypal = "Paypal", stripe = "Stripe", cod = "Cash of Delivery";
60 changes: 60 additions & 0 deletions lib/controllers/cart_controller.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:emart/consts/consts.dart';
import 'package:emart/controllers/home_controller.dart';
import 'package:get/get.dart';

class CartCotroller extends GetxController {
var totalPrice = 0.obs;

// text editing controller
TextEditingController addressController = TextEditingController();
TextEditingController cityController = TextEditingController();
TextEditingController stateController = TextEditingController();
TextEditingController postalCodeController = TextEditingController();
TextEditingController phoneController = TextEditingController();

// payment index
var paymentIndex = 0.obs;

late dynamic productSnapshot;
var products = [];

// calculate total price of item present in cart
calculateTotalPrice(data) {
totalPrice.value = 0;
Expand All @@ -11,4 +27,48 @@ class CartCotroller extends GetxController {
totalPrice.value + int.parse(data[price]['total_price'].toString());
}
}

// change payment index
changePaymentIndex(index) {
paymentIndex.value = index;
}

// order placing
placeMyOrder({required orderPaymentMethod, required totalAmount}) async {
await getProductDetails();

await firestore.collection(ordersCollection).doc().set({
'order_code': "223322",
'order_date': FieldValue.serverTimestamp(),
'order_by': currentUser!.uid,
'order_by_name': Get.find<HomeController>().userName,
'order_by_email': currentUser!.email,
'order_by_address': addressController.text,
'order_by_city': cityController.text,
'order_by_state': stateController.text,
'order_by_phone': phoneController.text,
'order_by_postal_code': postalCodeController.text,
'shipping_method': "Home Delivery",
'payment_method': orderPaymentMethod,
'order_placed': true,
'order_confirmed': false,
'order_delivered': false,
'order_on_delivery': false,
'total_amount': totalAmount,
'orders': FieldValue.arrayUnion(products),
});
}

// product details
getProductDetails() {
products.clear();
for (var i = 0; i < productSnapshot.length; i++) {
products.add({
'color': productSnapshot[i]['color'],
'image': productSnapshot[i]['image'],
'quantity': productSnapshot[i]['quantity'],
'title': productSnapshot[i]['title'],
});
}
}
}
70 changes: 70 additions & 0 deletions lib/controllers/chat_controller.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// ignore_for_file: curly_braces_in_flow_control_structures

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:emart/controllers/home_controller.dart';
import 'package:get/get.dart';
import 'package:emart/consts/consts.dart';

class ChatController extends GetxController {
@override
void onInit() {
getChatId();
super.onInit();
}

var chats = firestore.collection(chatsCollection);

var friendName = Get.arguments[0];
var friendId = Get.arguments[1];

var senderName = Get.find<HomeController>().userName;
var currentId = currentUser!.uid;

TextEditingController msgController = TextEditingController();

dynamic chatDocId;

var isLoading = false.obs;

getChatId() async {
isLoading(true);
await chats
.where('users', isEqualTo: {friendId: null, currentId: null})
.limit(1)
.get()
.then((QuerySnapshot snapshot) {
if (snapshot.docs.isNotEmpty)
chatDocId = snapshot.docs.single.id;
else
chats.add({
'created_on': null,
'last_message': '',
'users': {friendId: null, currentId: null},
'toId': '',
'fromId': '',
'friend_name': friendName,
'sender_name': senderName,
}).then((value) {
chatDocId = value.id;
});
});
isLoading(false);
}

sendMessage(String msg) async {
if (msg.trim().isNotEmpty) {
chats.doc(chatDocId).update({
'created_on': FieldValue.serverTimestamp(),
'last_message': msg,
'toId': friendId,
'fromId': currentId,
});

chats.doc(chatDocId).collection(messagesCollection).doc().set({
'created_on': FieldValue.serverTimestamp(),
'message': msg,
'uid': currentId,
});
}
}
}
21 changes: 21 additions & 0 deletions lib/controllers/home_controller.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import 'package:emart/consts/consts.dart';
import 'package:get/get.dart';

class HomeController extends GetxController {
var currentNavIndex = 0.obs;

var userName = '';

@override
void onInit() {
getUserName();
super.onInit();
}

getUserName() async {
var n = await firestore
.collection(usersCollection)
.where('id', isEqualTo: currentUser!.uid)
.get()
.then((value) {
if (value.docs.isNotEmpty) return value.docs.single['name'];
});

userName = n;
}
}
27 changes: 27 additions & 0 deletions lib/controllers/product_controller.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// ignore_for_file: curly_braces_in_flow_control_structures

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:emart/consts/consts.dart';
import 'package:emart/models/category_model.dart';
import 'package:flutter/services.dart';
Expand All @@ -8,6 +11,7 @@ class ProductController extends GetxController {
var quantity = 0.obs;
var colorIndex = 0.obs;
var totalPrice = 0.obs;
var isFav = false.obs;

getSubCategories(title) async {
subCat.clear();
Expand Down Expand Up @@ -61,4 +65,27 @@ class ProductController extends GetxController {
totalPrice.value = 0;
colorIndex.value = 0;
}

addToWishList(docId, context) async {
firestore.collection(productsCollection).doc(docId).set({
'p_wishlist': FieldValue.arrayUnion([currentUser!.uid])
}, SetOptions(merge: true));
isFav(true);
VxToast.show(context, msg: "Added to Wishlist");
}

removeFromWishList(docId, context) async {
firestore.collection(productsCollection).doc(docId).set({
'p_wishlist': FieldValue.arrayRemove([currentUser!.uid])
}, SetOptions(merge: true));
isFav(false);
VxToast.show(context, msg: "Remove from Wishlist");
}

checkIsFav(data) async {
if (data['p_wishlist'].contains(currentUser!.uid))
isFav(true);
else
isFav(false);
}
}
8 changes: 8 additions & 0 deletions lib/services/firestore_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,12 @@ class FirestoreService {
// delete cart document from databse
static deleteCartDocument(docId) =>
firestore.collection(cartCollection).doc(docId).delete();

// gett all chat messages
static getChatMessages(docId) => firestore
.collection(chatsCollection)
.doc(docId)
.collection(messagesCollection)
.orderBy('created_on', descending: false)
.snapshots();
}
Loading

0 comments on commit f5c697a

Please sign in to comment.