def register(request): if request.method == 'POST': #if POST request username = request.POST.get('username') email = request.POST.get( 'email') #collect data from respective input fields password = request.POST.get('password') user = None if not (username and email and password ): #if any field is empty redirect to register page again return render(request, 'authentication/register.html') try: user = auth.create_user( email=email, password=password) #create user using firebase-admin.auth() except: messages.error(request, "User Already exists!" ) # If user exists then, error is thrown. return render(request, 'authentication/register.html' ) #redirect to register page again data = {"username": username, "email": email, 'isAdmin': False} db.collection('users').document(user.uid).set( data) #add user data to cloud firestore database return redirect( 'home' ) #After successfully creating user and adding user's credentials to the database redirect to home page return render(request, 'authentication/register.html' ) #If no POST request, then redirect to register page again
def adminhome(request): if 'uid' in request.session: # if user is authenticated user = db.collection('users').document(request.session['uid']).get( ).to_dict() # retreive current user details if user['isAdmin']: # check if user is Admin movies = db.collection('movies').get() # retreive movie details moviesdata = [] for movie in movies: moviesdata.append(movie.to_dict( )) # convert document references to dictionary return render(request, 'admin/home.html', context={ "moviesdata": moviesdata, 'uid': request.session['uid'] }) # render admin's home page return render( request, 'users/home.html', context={'uid': request.session['uid']} ) # if user is not an admin then redirect him/her to user home page return redirect( 'login') # if user isnt authenticated redirect him/her to login page
def fix_hours(): all_hours = db.collection(u'restaurants').document( res_public_id).collection(u'hours').stream() for hour in all_hours: hour_ref = db.collection(u'restaurants').document( res_public_id).collection(u'hours').document(hour.id) hour_ref.update({"is_active": True})
def run_nightly(): all_restaurants = db.collection(u'restaurants').where( u'is_active', u'==', True).stream() for restaurant in all_restaurants: print("Working on restaurant: " + str(restaurant.id)) # res_public_data = restaurant.to_dict() all_hours = db.collection(u'restaurants').document( restaurant.id).collection("hours").stream() for hour in all_hours: print("Working on hour: " + str(hour.id)) hour_data = hour.to_dict() all_discounts = hour_data["discounts"] new_discounts = {} for discount in sorted(all_discounts): if discount == "0_00": new_discounts[discount] = { "is_active": True, "current_contributed": 0, } else: new_discounts[discount] = { "is_active": False, "current_contributed": 0, } hour_ref = db.collection(u'restaurants').document( restaurant.id).collection("hours").document(hour.id) hour_ref.update({u'discounts': new_discounts})
def init_algorithm(res_public_id): algo_foods = [] all_foods = db.collection(u'foods').where(u'restaurant_id', u'==', res_public_id).stream() MAX_DISCOUNT = 100 for food in all_foods: # print(u'{} => {}'.format(food.id, food.to_dict())) food_data = food.to_dict() sales_price = food_data["sales_price"] private_info = db.collection(u'foods').document( food.id).collection(u'private').stream() for info in private_info: # print(u'{} => {}'.format(info.id, info.to_dict())) res_private_id = info.id info_data = info.to_dict() ingredients_cost = info_data["ingredients_cost"] profit_margin = info_data["profit_margin"] res_private_ref = db.collection(u'restaurants').document( res_public_id).collection(u'private').document(res_private_id) res_private_data = res_private_ref.get().to_dict() credit_card_percentage = res_private_data["credit_card_percentage"] credit_card_constant = res_private_data["credit_card_constant"] # For food.id # Got sales_price, ingredients_cost, and profit_margin # Trofi Algorithm initialization credit_card_fee = (sales_price * credit_card_percentage) + credit_card_constant # TESTING: credit_card_fee = 0 initial_expense_contribution = sales_price - \ (profit_margin + ingredients_cost + credit_card_fee) print(initial_expense_contribution) max_food_discount = initial_expense_contribution / sales_price print(max_food_discount) food = { "id": food.id, "sales_price": sales_price, "credit_card_fee": credit_card_fee, "initial_expense_contribution": initial_expense_contribution, "max_discount": max_food_discount, } if max_food_discount < MAX_DISCOUNT: MAX_DISCOUNT = round(max_food_discount, 2) algo_foods.append(food) return algo_foods, MAX_DISCOUNT
def deletemovies(request, id): if 'uid' in request.session: # if user is authenticated user = db.collection('users').document(request.session['uid']).get( ).to_dict() # retreive current user details if user['isAdmin']: # check if user is Admin movie = db.collection('movies').document(id).delete( ) # retreive movie document for particular id and delete it from database return redirect('adminhome') # redirect to admin home page return redirect( 'home') # if user is not admin then return to user's home page return redirect( 'login') # if user is not authenticated then redirect to home page
def updatedone(request, id): if 'uid' in request.session: # if user is authenticated user = db.collection('users').document(request.session['uid']).get( ).to_dict() # retreive current user details if user['isAdmin']: # check if user is Admin if request.method == 'POST': # if POST request name = request.POST.get('name') genre = request.POST.get('genre') contentrating = request.POST.get( 'contentrating' ) # retreive updated movie details from input fields contentURL = request.POST.get('contentURL') releasedate = request.POST.get('releasedate') if name and genre and contentrating and contentURL and releasedate: # if all fields are non empty if 'poster' in request.FILES: # if new poster image exits poster = request.FILES['poster'] storage.child('images/posters/' + name).put( poster) # store the new image in firebase storage posterURL = storage.child( 'images/posters/' + name).get_url( None) # retreive new url for new image movie = { 'name': name, 'genre': genre, 'contentrating': contentrating, 'contentURL': contentURL, 'poster': posterURL, 'releasedate': releasedate } else: movie = { 'name': name, 'genre': genre, 'contentrating': contentrating, # if no new poster exists 'contentURL': contentURL, 'releasedate': releasedate } db.collection('movies').document(id).update( movie) # update details in the database return redirect( 'adminhome' ) # After successfully updating movie details return return redirect('updatemovie', id=id) return redirect('home') return render(request, 'authentication/login.html')
def login(request): if request.method == 'POST': #if POST request email = request.POST.get('email') password = request.POST.get( 'password') #retreive details from input fields user = None if (email and password): #if details retreived are non-empty try: user = pyfirebase.auth().sign_in_with_email_and_password( email, password ) #using firebase authentication to authenticate user via pyrebase except: messages.error(request, "Invalid Credentials" ) #error is occured if details are invalid return render(request, 'authentication/login.html' ) # in that case redirect to login page again session_id = user['localId'] request.session[ 'uid'] = session_id #store uid in session variable for future authentication user = db.collection('users').document(request.session['uid']).get( ).to_dict() # retreive current user details if user['isAdmin']: # check if user is Admin return redirect('adminhome') #if user is admin return redirect('home') #redirect to home page return render( request, 'authentication/login.html') #else redirect to login page again
def comment(request, id): if 'uid' in request.session: #if user is authenticated let him/her in if request.method == 'POST': #if POST request comment = request.POST.get( 'comment') #retreive comment in textarea if comment: #if comment is not empty curruser = db.collection('users').document( request.session['uid']).get( ) #retrieve current user details db.collection('movies').document(id).collection('comments').add( #add the comment to comments part of that particular movie {"uid": request.session['uid'], "comment": comment, "username": curruser.to_dict()['username']}) return redirect( 'movie', id=id) #if no POST request then redirect to the same page return redirect( 'login') #if user isnt authenticated redirect him/her to login page
def updatemovie(request, id): if 'uid' in request.session: # if user is authenticated user = db.collection('users').document(request.session['uid']).get( ).to_dict() # retreive current user details if user['isAdmin']: # check if user is Admin movie = db.collection('movies').document(id).get().to_dict( ) # retreive that particular movie with given id return render( request, 'admin/updatemovie.html', context={ "movie": movie }) # pass movie details for further updating movie details return redirect( 'home') # if user is not admin, redirect to user's home page return redirect( 'login') # if user is not authenticated, then redirect to login page
def addmovies(request): if 'uid' in request.session: # if user is authenticated user = db.collection('users').document(request.session['uid']).get( ).to_dict() # retreive current user details if user['isAdmin']: # check if user is Admin if request.method == 'POST': # if POST request name = request.POST.get('name') genre = request.POST.get('genre') contentrating = request.POST.get( 'contentrating') # retreive details from input fields contentURL = request.POST.get('contentURL') poster = request.FILES['poster'] releasedate = request.POST.get('releasedate') description = request.POST.get('description') if (name and genre and contentrating and contentURL and releasedate and description): # if all fields are non empty if 'poster' in request.FILES: # if poster(image) exists storage.child('movies/posters/' + name).put( poster) # add image to firebase storage posterURL = storage.child( "movies/posters/" + name).get_url( None) # generate url for that image movie = { 'name': name, 'genre': genre, 'contentrating': contentrating, 'contentURL': contentURL, 'poster': posterURL, 'releasedate': releasedate, 'description': description } doc = db.collection( 'movies').document() # create a document doc_id = doc.id # generate unique id movie['id'] = doc_id doc.set(movie) # add all details to firebase return redirect('adminhome') # redirect to admin home return render(request, 'admin/addmovies.html' ) # if no POST request, then redirect to same page return redirect( 'home') # if user is not admin, redirect to user's home page return redirect( 'login') # if user is not authenticated, then redirect to login page
def start(update, context): number_of_noodles = 0 username = update.message.from_user.username # get username user_id = update.message.from_user.id today = str(date.today()) datetime = str(time.asctime(time.localtime(time.time()))) welcome_text = f"Welcome {username}! I am here to check on your health! Please remember to enter your details BEFORE you consume your food to check whether you are allowed to eat!" update.message.reply_text(welcome_text) today = str(date.today()) db = firestore.client() doc_ref = db.collection(u'data').document(username) # new users if db.collection(u'data').document(username).get().to_dict() is None: doc_ref.set({ u'Username': str(username), u'ID': str(user_id), u'LastEnteredDate': today, u'TotalNoodleConsumedThisMonth': number_of_noodles }) # current users else: pass current_month = str(date.today()).split('-')[1] # get month from last entry in firebase month = db.collection(u'data').document( username).get().to_dict()['LastEnteredDate'].split('-')[1] print('month is ', month) if month != current_month: number_of_noodles = 0 doc_ref.update({ u'LastEnteredDate': today, u'TotalNoodleConsumedThisMonth': number_of_noodles }) else: doc_ref.update({ u'LastEnteredDate': today })
def upload_food_item(food_item): try: new_food_ref = db.collection(u'foods').document() new_food_ref.set(food_item["public"]) private_ref = new_food_ref.collection(u'private').document() private_ref.set(food_item["private"]) except: print("DB Error!")
def fix_menu(): all_foods = db.collection(u'foods').where(u'restaurant_id', u'==', res_public_id).stream() for food in all_foods: # print(u'{} => {}'.format(food.id, food.to_dict())) # food_data = food.to_dict() private_info = db.collection(u'foods').document( food.id).collection(u'private').stream() for info in private_info: # print(u'{} => {}'.format(info.id, info.to_dict())) food_ref = db.collection(u'foods').document( food.id).collection(u'private').document(info.id) food_ref.update({ "credit_card_fee": 0.01, "ingredients_cost": 0.01, "profit_margin": 0.01 })
def home(request): if 'uid' in request.session: # if user is authenticated user = db.collection('users').document(request.session['uid']).get( ).to_dict() # retreive current user details if user['isAdmin']: # check if user is Admin return redirect('adminhome') #redirect him/her to adminhome movies = db.collection( 'movies').get() #retreive movies from cloud firestore moviesdata = [] for movie in movies: moviesdata.append( movie.to_dict()) #convert document references to dictionary return render(request, 'users/home.html', context={ "moviesdata": moviesdata }) #render home template with movies data in context return redirect( 'login') #if user isnt authenticated redirect him/her to login page
def adminregister(request): if 'uid' in request.session: # if user is authenticated user = db.collection('users').document(request.session['uid']).get( ).to_dict() # retreive current user details if user['isAdmin']: # check if user is Admin if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') user = None if not ( username and email and password ): # if any field is empty redirect to the same page again return render(request, 'admin/adminregister.html') try: user = auth.create_user( email=email, password=password ) # create user using firebase-admin.auth() except: messages.error(request, "Admin Already exists!" ) # If user exists then, error is thrown. return render(request, 'admin/adminregister.html' ) # redirect to register page again data = { "username": username, "email": email, 'isAdmin': True } # Setting 'isAdmin'= True depicting admin functionality db.collection('users').document(user.uid).set( data) # add user data to cloud firestore database messages.success(request, "Admin Registration Successful!") return redirect( 'adminhome' ) # After successfully creating new admin and adding his/her credentials to the database redirect to home page return render( request, 'admin/adminregister.html' ) # If no POST request, then redirect to register page again
def tweetFromFirestore(): documentId = None document = None try: results = db.collection(u'toTweets').where( u'isDone', u'==', False).limit(1).get() snap = list(results)[0] documentId = snap.id document = snap.to_dict() print(document) except IndexError as err: print("No tweets to be tweeted!") return except: print("Something went wrong. Try Again") return try: resTwitter = twitterApi.PostUpdate(document[u'message']) db.collection(u'toTweets').document( documentId).update({u'isDone': True}) except TwitterError as err: print(err.message)
def movie(request, id): if 'uid' in request.session: #if user is authenticated let him/her in movie = db.collection('movies').document(id).get( ) #retreive the particular movie details on which the user clicked from cloud firestore comments = db.collection('movies').document(id).collection( 'comments' ).get( ) #retreive comments of the particular movie on which the user clicked from cloud firestore commentsdata = [] for comment in comments: commentsdata.append(comment.to_dict( )) #convert comments data from document references to dictionary print(commentsdata) return render( request, 'users/movie.html', context={ "movie": movie.to_dict(), "comments": commentsdata } ) #render movie template with movie details and comments data in context return redirect( 'login') #if user isnt authenticated redirect him/her to login page
def set_noodle(update, context): username = update.message.from_user.username db = firestore.client() try: noodle_command = context.args[0].lower() doc_ref = db.collection(u'data').document(username) doc_ref.update({ u'TotalNoodle': noodle_command }) message = f'You have set {noodle_command} packet(s) of noodles per month!' update.message.reply_text(message) except: update.message.reply_text( 'Please only enter - numerical (1,2,3...) commands')
from config import db users = db.collection(u'users') folders = db.collection(u'folders') files = db.collection(u'files') news = db.collection(u'news') notifications = db.collection(u'notifications')
def check_number_noodle(update, context): db = firestore.client() username = update.message.from_user.username today = str(date.today()) datetime = str(time.asctime(time.localtime(time.time()))) total_noodles = int(db.collection(u'data').document( username).get().to_dict()['TotalNoodle']) noodle_today = 0 number_of_noodles = db.collection(u'data').document( username).get().to_dict()['TotalNoodleConsumedThisMonth'] try: command = context.args[0].lower() current_month = str(date.today()).split('-')[1] doc_ref = db.collection(u'data').document(username) # get month from last entry in firebase month = db.collection(u'data').document( username).get().to_dict()['LastEnteredDate'].split('-')[1] print('month is ', month) if month != current_month: number_of_noodles = 0 doc_ref.update({ u'LastEnteredDate': today, u'TotalNoodleConsumedThisMonth': number_of_noodles }) else: doc_ref.update({ u'LastEnteredDate': today }) if (command == "oops"): noodle_today += 1 number_of_noodles += 1 number_left = total_noodles - number_of_noodles if (number_left >= 0): text = f'You have eaten {number_of_noodles} packets of noodle(s), {number_left} left for the month.' update.message.reply_text(text) # get username and id username = update.message.from_user.username # update firebase try: doc_ref = db.collection(u'data').document(username) doc_ref.update({ u'TotalNoodleConsumedThisMonth': number_of_noodles, }) doc_ref_date = db.collection(u'data').document( username).collection(today) doc_ref_date.add({ u'Date': datetime, u'Noodle': noodle_today }) except Exception as e: print(e) else: text = f'WANNA BE FAT ISIT? STOP EATING!!!' update.message.reply_text(text) elif (command == "check"): number_left = total_noodles - number_of_noodles print('number left ', number_left) text = f'You have eaten {number_of_noodles} packets of noodle(s), {number_left} left for the month.' update.message.reply_text(text) else: update.message.reply_text( 'Please only enter - check/oops commands') except: update.message.reply_text( 'STH WRONG Please only enter - check/oops commands')
def run_algorithm(res_public_id, algo_foods, MAX_DISCOUNT): all_hours = db.collection(u'restaurants').document( res_public_id).collection("hours").stream() batch = db.batch() for hour in all_hours: all_hour_discounts = {} all_food_contributions = {} # print(u'{} => {}'.format(hour.id, hour.to_dict())) hour_data = hour.to_dict() needed_contribution = hour_data["payroll"] + hour_data["overhead_cost"] initial_discount = hour_data["initial_discount"] print("FOR HOUR: " + hour.id) percent_discount = 0.0 while percent_discount < MAX_DISCOUNT: active = True if (initial_discount == 0 and percent_discount == 0 ) or (initial_discount > 0 and percent_discount == initial_discount) else False hour_discount = { "is_active": active, "current_contributed": 0, } format_discount = "{:.2f}".format(percent_discount).replace( '.', '_') all_hour_discounts[format_discount] = hour_discount percent_discount += DISCOUNT_INCREMENT percent_discount = round(percent_discount, 2) for food in algo_foods: print("\n--------------------------------\n") food_contributions = {} # do not show breakeven percent_discount = 0.0 + DISCOUNT_INCREMENT print("FOR FOOD: " + food["id"]) print(MAX_DISCOUNT) while percent_discount < MAX_DISCOUNT: discount = food["sales_price"] * percent_discount expense_contribution = food[ "initial_expense_contribution"] - discount print("To unlock a discount of: ", percent_discount) print("Item will contribute: ", expense_contribution) format_discount = "{:.2f}".format(percent_discount - DISCOUNT_INCREMENT).replace( '.', '_') food_contributions[format_discount] = expense_contribution percent_discount += DISCOUNT_INCREMENT percent_discount = round(percent_discount, 2) all_food_contributions[str(food["id"])] = food_contributions print(all_food_contributions) # print(all_hour_discounts) hour_ref = db.collection(u'restaurants').document( res_public_id).collection("hours").document(hour.id) batch.update(hour_ref, {u'needed_contribution': needed_contribution}) batch.update(hour_ref, {u'contributions': all_food_contributions}) batch.update(hour_ref, {u'discounts': all_hour_discounts}) batch.update(hour_ref, {u'max_discount': 0.95}) # print("\n--------------------------------\n") print("Writing to database...") batch.commit()
def reset_hours(public_id): res_ref = db.collection(u'restaurants').document(public_id) init_hours_ref = res_ref.collection(u'hours') init_0_hours_ref = init_hours_ref.document("0") init_1_hours_ref = init_hours_ref.document("1") init_2_hours_ref = init_hours_ref.document("2") init_3_hours_ref = init_hours_ref.document("3") init_4_hours_ref = init_hours_ref.document("4") init_5_hours_ref = init_hours_ref.document("5") init_6_hours_ref = init_hours_ref.document("6") init_7_hours_ref = init_hours_ref.document("7") init_8_hours_ref = init_hours_ref.document("8") init_9_hours_ref = init_hours_ref.document("9") init_10_hours_ref = init_hours_ref.document("10") init_11_hours_ref = init_hours_ref.document("11") init_12_hours_ref = init_hours_ref.document("12") init_13_hours_ref = init_hours_ref.document("13") init_14_hours_ref = init_hours_ref.document("14") init_15_hours_ref = init_hours_ref.document("15") init_16_hours_ref = init_hours_ref.document("16") init_17_hours_ref = init_hours_ref.document("17") init_18_hours_ref = init_hours_ref.document("18") init_19_hours_ref = init_hours_ref.document("19") init_20_hours_ref = init_hours_ref.document("20") init_21_hours_ref = init_hours_ref.document("21") init_22_hours_ref = init_hours_ref.document("22") init_23_hours_ref = init_hours_ref.document("23") batch = db.batch() batch.set( init_0_hours_ref, { "start_id": 0, "payroll": 0, "overhead_cost": 0, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "contributions": {}, "foods_active": [] }) batch.set( init_1_hours_ref, { "start_id": 1, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_2_hours_ref, { "start_id": 2, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_3_hours_ref, { "start_id": 3, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_4_hours_ref, { "start_id": 4, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_5_hours_ref, { "start_id": 5, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_6_hours_ref, { "start_id": 6, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_7_hours_ref, { "start_id": 7, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_8_hours_ref, { "start_id": 8, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_9_hours_ref, { "start_id": 9, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_10_hours_ref, { "start_id": 10, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_11_hours_ref, { "start_id": 11, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_12_hours_ref, { "start_id": 12, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_13_hours_ref, { "start_id": 13, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_14_hours_ref, { "start_id": 14, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_15_hours_ref, { "start_id": 15, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_16_hours_ref, { "start_id": 16, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_17_hours_ref, { "start_id": 17, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_18_hours_ref, { "start_id": 18, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_19_hours_ref, { "start_id": 19, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_20_hours_ref, { "start_id": 20, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_21_hours_ref, { "start_id": 21, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_22_hours_ref, { "start_id": 22, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.set( init_23_hours_ref, { "start_id": 23, "payroll": 0, "overhead_cost": 0, "contributions": {}, "is_active": False, "initial_discount": 0, "discounts": {}, "max_discount": 0, "foods_active": [] }) batch.commit()
import json import pytz from datetime import datetime, timedelta from firebase_admin import firestore from config import db # Insert into 'sections' with open('./assets/seller_sections_fake_data_foobarify.json') as json_file: fake_sections = json.load(json_file) batch = db.batch() for index, section in enumerate(fake_sections): docRef = db.collection( f'sellers/{section["seller_id"]}/sections').document() delivery_location = { 'address': section['delivery_location']['address'], 'address_zh': section['delivery_location']['address_zh'], 'geopoint': firestore.GeoPoint( section['delivery_location']['geopoint']['lat'], section['delivery_location']['geopoint']['long']) } now_time = datetime.now( pytz.timezone('Asia/Hong_Kong')) + timedelta(days=index) cutoff_time = datetime.strptime(section["cutoff_time"], '%H:%M') delivery_time = datetime.strptime(section["delivery_time"], '%H:%M')