mirror of
				https://github.com/StefBuwalda/cal_counter.git
				synced 2025-10-30 03:10:00 +00:00 
			
		
		
		
	Compare commits
	
		
			12 Commits
		
	
	
		
			v0.9.0
			...
			cef3d63ca2
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | cef3d63ca2 | ||
| b379b59eec | |||
| 24a1757166 | |||
| 5373d373ca | |||
|   | dca3ff7efe | ||
| 7cedd8f74d | |||
|   | faff1a60b8 | ||
| 73985b9b6d | |||
|   | 7b84ab980e | ||
| 4aca63671b | |||
| bd0468a600 | |||
| c1f46357f0 | 
							
								
								
									
										23
									
								
								app.py
									
									
									
									
									
								
							
							
						
						
									
										23
									
								
								app.py
									
									
									
									
									
								
							| @@ -1,8 +1,4 @@ | ||||
| from flask import ( | ||||
|     redirect, | ||||
|     url_for, | ||||
|     send_from_directory, | ||||
| ) | ||||
| from flask import redirect, url_for, send_from_directory, render_template | ||||
| from flask_login import ( | ||||
|     login_required, | ||||
|     current_user, | ||||
| @@ -12,7 +8,7 @@ from application import db, app, login_manager | ||||
| from application.admin.routes import admin_bp | ||||
| from application.user.routes import user_bp | ||||
| from application.auth.routes import bp as auth_bp | ||||
| from application.add_meal_v2.routes import bp as add_meal_v2_bp | ||||
| from application.add_meal.routes import bp as add_meal_bp | ||||
| from typing import Optional | ||||
|  | ||||
| # Config | ||||
| @@ -30,12 +26,17 @@ def load_user(user_id: int): | ||||
| app.register_blueprint(admin_bp) | ||||
| app.register_blueprint(user_bp) | ||||
| app.register_blueprint(auth_bp) | ||||
| app.register_blueprint(add_meal_v2_bp) | ||||
| app.register_blueprint(add_meal_bp) | ||||
|  | ||||
|  | ||||
| # @app.errorhandler(404) | ||||
| # def page_not_found(e): | ||||
| #    return redirect("/") | ||||
|  | ||||
|  | ||||
| # Routes | ||||
| def default_return(next_page: Optional[str] = None): | ||||
|     return redirect(url_for("user.daily_log2")) | ||||
|     return redirect(url_for("user.daily_log")) | ||||
|     if next_page: | ||||
|         return redirect(next_page) | ||||
|     if current_user.is_admin: | ||||
| @@ -49,6 +50,12 @@ def index(): | ||||
|     return redirect(url_for("auth.login")) | ||||
|  | ||||
|  | ||||
| @app.route("/test") | ||||
| @login_required | ||||
| def text(): | ||||
|     return render_template("newBase.html") | ||||
|  | ||||
|  | ||||
| @app.route("/favicon.ico") | ||||
| def favicon(): | ||||
|     return send_from_directory("static", "favicon.ico") | ||||
|   | ||||
| @@ -17,9 +17,9 @@ from sqlalchemy.sql.elements import BinaryExpression | ||||
| from typing import cast | ||||
| 
 | ||||
| bp = Blueprint( | ||||
|     "add_meal_v2", | ||||
|     "add_meal", | ||||
|     __name__, | ||||
|     url_prefix="/add_meal_v2", | ||||
|     url_prefix="/add_meal", | ||||
|     template_folder="templates", | ||||
| ) | ||||
| 
 | ||||
| @@ -27,14 +27,14 @@ bp = Blueprint( | ||||
| def date_present(func): | ||||
|     def check_date(): | ||||
|         if "selected_date" not in session: | ||||
|             return redirect(url_for("user.daily_log2")) | ||||
|             return redirect(url_for("user.daily_log")) | ||||
| 
 | ||||
| 
 | ||||
| def item_selected(func): | ||||
|     def check_item(): | ||||
|         if check_item(): | ||||
|             if "item_id" not in session: | ||||
|                 return redirect(url_for("add_meal_v2.get_barcode")) | ||||
|                 return redirect(url_for("add_meal.find_item")) | ||||
| 
 | ||||
| 
 | ||||
| @bp.before_request | ||||
| @@ -44,14 +44,14 @@ def login_required(): | ||||
| 
 | ||||
| 
 | ||||
| @date_present | ||||
| @bp.route("/get_barcode", methods=["GET"]) | ||||
| def get_barcode(): | ||||
|     return render_template("scan_barcode_v2.html") | ||||
| @bp.route("/find_item", methods=["GET"]) | ||||
| def find_item(): | ||||
|     return render_template("find_item.html") | ||||
| 
 | ||||
| 
 | ||||
| @date_present | ||||
| @bp.route("/add_existing/<string:input>", methods=["GET"]) | ||||
| def add_existing(input: str): | ||||
| @bp.route("/select_item/<string:input>", methods=["GET"]) | ||||
| def select_item(input: str): | ||||
|     # Check if input is a barcode | ||||
|     if input.isdigit(): | ||||
|         item = current_user.food_items.filter_by(barcode=input).first() | ||||
| @@ -61,28 +61,28 @@ def add_existing(input: str): | ||||
| 
 | ||||
|     if item is None: | ||||
|         # Does not exist, add item | ||||
|         return redirect(url_for("add_meal_v2.add_new", input=input)) | ||||
|         return redirect(url_for("add_meal.add_new_item", input=input)) | ||||
| 
 | ||||
|     # Track item to add and continue to next step | ||||
|     session["item_id"] = item.id | ||||
|     return redirect(url_for("add_meal_v2.step4")) | ||||
|     return redirect(url_for("add_meal.step4")) | ||||
| 
 | ||||
| 
 | ||||
| @date_present | ||||
| @bp.route("/add_new/<string:input>", methods=["GET"]) | ||||
| def add_new(input: str): | ||||
| @bp.route("/add_new_item/<string:input>", methods=["GET"]) | ||||
| def add_new_item(input: str): | ||||
|     form = FoodItemForm() | ||||
| 
 | ||||
|     if input.isdigit(): | ||||
|         form.barcode.data = input | ||||
|     else: | ||||
|         form.name.data = input | ||||
|     return render_template("add_item.html", form=form) | ||||
|     return render_template("add_new_item.html", form=form) | ||||
| 
 | ||||
| 
 | ||||
| @date_present | ||||
| @bp.route("/add_new/<string:input>", methods=["POST"]) | ||||
| def add_new_post(input: str): | ||||
| @bp.route("/add_new_item/<string:input>", methods=["POST"]) | ||||
| def post_new_item(input: str): | ||||
|     form = FoodItemForm() | ||||
| 
 | ||||
|     if form.validate_on_submit(): | ||||
| @@ -126,10 +126,10 @@ def add_new_post(input: str): | ||||
|             print(f"Item exists: {item.barcode} {item.name}") | ||||
| 
 | ||||
|         # Item added or already present, return to step 3. | ||||
|         return redirect(url_for("add_meal_v2.add_existing", input=input)) | ||||
|         return redirect(url_for("add_meal.select_item", input=input)) | ||||
|     else: | ||||
|         print("[DEBUG] Form Invalid") | ||||
|         return redirect(url_for("add_meal_v2.add_new", input=input)) | ||||
|         return redirect(url_for("add_meal.add_new_item", input=input)) | ||||
| 
 | ||||
| 
 | ||||
| @date_present | ||||
| @@ -139,7 +139,7 @@ def step4(): | ||||
|     form = FoodLogForm() | ||||
|     item = db.session.get(FoodItem, session["item_id"]) | ||||
|     if not item: | ||||
|         return redirect(url_for("add_meal_v2.get_barcode")) | ||||
|         return redirect(url_for("add_meal.find_item")) | ||||
| 
 | ||||
|     if form.validate_on_submit(): | ||||
|         assert form.amount.data | ||||
| @@ -156,9 +156,9 @@ def step4(): | ||||
|         db.session.commit() | ||||
|         session.pop("item_id") | ||||
|         session.pop("selected_date") | ||||
|         return redirect(url_for("user.daily_log2")) | ||||
|         return redirect(url_for("user.daily_log")) | ||||
| 
 | ||||
|     return render_template("step4.html", tod="idk", item=item, form=form) | ||||
|     return render_template("step4.html", item=item, form=form) | ||||
| 
 | ||||
| 
 | ||||
| @date_present | ||||
							
								
								
									
										126
									
								
								application/add_meal/templates/find_item.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										126
									
								
								application/add_meal/templates/find_item.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,126 @@ | ||||
| {% extends "base.html" %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="container d-flex flex-column justify-content-start align-items-center py-4" style="min-height: 100vh;"> | ||||
|     <div class="card shadow-sm w-100"> | ||||
|         <div class="card-body d-flex flex-column"> | ||||
|             <h5 class="card-title text-center mb-4">Item Scanner</h5> | ||||
|             <video id="camera" autoplay class="w-100 mb-3" muted></video> | ||||
|  | ||||
|             <div class="mb-3"> | ||||
|                 <label for="manualSearch" class="form-label">Or search manually</label> | ||||
|                 <input type="text" class="form-control" id="manualSearch" placeholder="Enter item name"> | ||||
|             </div> | ||||
|  | ||||
|             <ul class="list-group mb-3" id="searchResults"></ul> | ||||
|  | ||||
|             <button class="btn btn-primary w-100" id="createItemBtn">Create New Item</button> | ||||
|         </div> | ||||
|     </div> | ||||
| </div> | ||||
| {% endblock%} | ||||
|  | ||||
| {% block scripts %} | ||||
| <script> | ||||
|     const baseURL = "{{url_for('add_meal.select_item', input='!')}}"; | ||||
|     const baseURL2 = "{{url_for('add_meal.add_new_item', input='!')}}"; | ||||
| </script> | ||||
| <script type="module"> | ||||
|     // Import barcode scanner | ||||
|     import { BrowserMultiFormatReader } from 'https://cdn.jsdelivr.net/npm/@zxing/library@0.21.3/+esm'; | ||||
|  | ||||
|     // constants | ||||
|     const codeReader = new BrowserMultiFormatReader(); | ||||
|     const videoElement = document.getElementById('camera'); | ||||
|  | ||||
|     // Start async camera thingymibob | ||||
|     document.addEventListener('DOMContentLoaded', async () => { | ||||
|         console.log('[DEBUG] Page loaded, starting barcode scan'); | ||||
|  | ||||
|         try { | ||||
|             await navigator.mediaDevices.getUserMedia({ video: true }); | ||||
|         } catch (err) { | ||||
|             alert("No camera found or no camera permission"); | ||||
|             console.error("Could not access the camera:", err); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         console.log('[DEBUG] Permission given and at least one device present'); | ||||
|         const devices = await codeReader.listVideoInputDevices(); | ||||
|         console.log('[DEBUG] Cameras found:', devices); | ||||
|  | ||||
|         const rearCamera = devices.find(device => device.label.toLowerCase().includes('back')) | ||||
|             || devices.find(device => device.label.toLowerCase().includes('rear')) | ||||
|             || devices[0]; // fallback | ||||
|  | ||||
|         const selectedDeviceId = rearCamera?.deviceId; | ||||
|         await codeReader.decodeFromVideoDevice(selectedDeviceId, videoElement, async (result, err) => { | ||||
|             if (result) { | ||||
|                 // Result found, redirect to the URL | ||||
|                 console.log(result) | ||||
|                 const codeText = result.getText(); | ||||
|                 window.location.href = baseURL.replace("!", encodeURIComponent(codeText)); | ||||
|             } | ||||
|         }); | ||||
|     }); | ||||
| </script> | ||||
|  | ||||
| <script> | ||||
|     const searchInput = document.getElementById('manualSearch'); | ||||
|     const resultsList = document.getElementById('searchResults'); | ||||
|     const createBtn = document.getElementById('createItemBtn'); | ||||
|  | ||||
|     let controller; // keeps track of the current fetch | ||||
|  | ||||
|     // TODO: Debounce input, wait for user to stop typing (f.e. 300ms)  | ||||
|     searchInput.addEventListener('input', () => { | ||||
|         const query = searchInput.value.toLowerCase(); | ||||
|  | ||||
|         // Check if there is enough input to fetch | ||||
|         if (query.length < 2) { | ||||
|             resultsList.innerHTML = ''; | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         if (controller) controller.abort(); // Abort previous fetch if still running | ||||
|         controller = new AbortController(); // new controller for this fetch | ||||
|         const signal = controller.signal;   // Signal to fetch to listen for aborts | ||||
|  | ||||
|         fetch(`{{url_for("add_meal.query")}}?q=${encodeURIComponent(query)}`, { signal }) | ||||
|             .then(response => response.json()) | ||||
|             .then(data => { | ||||
|                 resultsList.innerHTML = ''; // clear before appending | ||||
|                 data.forEach(item => { | ||||
|                     // Create list item with button inside that changes the hidden form and submits it | ||||
|                     const li = document.createElement('li'); | ||||
|                     li.className = 'list-group-item p-0'; | ||||
|                     const btn = document.createElement('button'); | ||||
|                     btn.className = 'list-group-item list-group-item-action m-0 border-0'; | ||||
|                     btn.style.width = '100%'; // make it fill the li | ||||
|                     btn.textContent = item; | ||||
|  | ||||
|                     btn.addEventListener('click', () => { | ||||
|                         window.location.href = baseURL.replace("!", encodeURIComponent(item)); | ||||
|                     }); | ||||
|  | ||||
|                     li.appendChild(btn); | ||||
|                     resultsList.appendChild(li); | ||||
|                 }); | ||||
|             }).catch(err => { | ||||
|                 if (err.name == 'AbortError') { | ||||
|                     console.log("Fetch aborted"); | ||||
|                 } | ||||
|                 if (err.name !== 'AbortError') { | ||||
|                     console.error('Fetch error:', err); | ||||
|                 } | ||||
|             }); | ||||
|     }); | ||||
| </script> | ||||
| <script> | ||||
|     createBtn.addEventListener('click', () => { | ||||
|         const newItem = searchInput.value.trim() | ||||
|         window.location.href = newItem ? baseURL2.replace("!", encodeURIComponent(newItem)) : baseURL2; | ||||
|     }); | ||||
| </script> | ||||
|  | ||||
| {% endblock %} | ||||
| @@ -1,7 +1,6 @@ | ||||
| {% extends "base.html" %} | ||||
| 
 | ||||
| {% block content %} | ||||
| <p>{{ tod }}</p> | ||||
| <p>{{ item.name }}</p> | ||||
| 
 | ||||
| <form method="POST"> | ||||
| @@ -1,134 +0,0 @@ | ||||
| {% extends "base.html" %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="container py-5"> | ||||
|     <!-- Header --> | ||||
|     <div class="text-center mb-4"> | ||||
|         <h1 class="fw-bold">Barcode Scanner</h1> | ||||
|         <p class="text-muted">Use your camera to scan barcodes</p> | ||||
|     </div> | ||||
|  | ||||
|     <!-- Video preview --> | ||||
|     <div class="d-flex justify-content-center mb-4"> | ||||
|         <video id="video" class="border rounded shadow-sm" style="width: 100%; max-width: 500px;" autoplay | ||||
|             muted></video> | ||||
|     </div> | ||||
|  | ||||
|     <!-- Start/Stop buttons --> | ||||
|     <div class="d-flex justify-content-center gap-3 mb-4"> | ||||
|         <button id="startButton" class="btn btn-primary px-4">Start Scanning</button> | ||||
|         <button id="stopButton" class="btn btn-danger px-4">Stop</button> | ||||
|     </div> | ||||
|  | ||||
|     <!-- Search box and suggestions --> | ||||
|     <div class="d-flex justify-content-center mt-4"> | ||||
|         <div class="w-100 position-relative" style="max-width: 500px;"> | ||||
|             <!-- Input group (search + go button) --> | ||||
|             <div class="input-group"> | ||||
|                 <input type="text" id="search-box" class="form-control" placeholder="Search..." autocomplete="off"> | ||||
|                 <button id="go-button" class="btn btn-success">Go</button> | ||||
|             </div> | ||||
|  | ||||
|             <!-- Suggestions --> | ||||
|             <ul id="suggestions" class="list-group position-absolute w-100 mt-1" style="z-index: 1000;"></ul> | ||||
|         </div> | ||||
|     </div> | ||||
|  | ||||
|  | ||||
|     <!-- Suggestions list --> | ||||
|     <div class="d-flex justify-content-center"> | ||||
|         <ul id="suggestions" class="list-group position-absolute mt-1 w-100" style="max-width: 500px; z-index: 1000;"> | ||||
|         </ul> | ||||
|     </div> | ||||
| </div> | ||||
|  | ||||
|  | ||||
|  | ||||
|  | ||||
|  | ||||
| <script> | ||||
|     const searchBox = document.getElementById('search-box'); | ||||
|     const suggestionsBox = document.getElementById('suggestions'); | ||||
|     const goButton = document.getElementById('go-button'); | ||||
|  | ||||
|     searchBox.addEventListener('input', function () { | ||||
|         const query = searchBox.value; | ||||
|         if (query.length < 2) { | ||||
|             suggestionsBox.innerHTML = ''; | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         fetch(`{{url_for("add_meal.query")}}?q=${encodeURIComponent(query)}`) | ||||
|             .then(response => response.json()) | ||||
|             .then(data => { | ||||
|                 suggestionsBox.innerHTML = ''; | ||||
|                 data.forEach(item => { | ||||
|                     const li = document.createElement('li'); | ||||
|                     li.textContent = item; | ||||
|  | ||||
|                     // Apply Bootstrap classes | ||||
|                     li.classList.add('list-group-item', 'list-group-item-action', 'cursor-pointer'); | ||||
|  | ||||
|                     // Add click behavior | ||||
|                     li.addEventListener('click', () => { | ||||
|                         searchBox.value = item; | ||||
|                         suggestionsBox.innerHTML = ''; | ||||
|                     }); | ||||
|  | ||||
|                     // Add to suggestions box | ||||
|                     suggestionsBox.appendChild(li); | ||||
|                 }); | ||||
|             }); | ||||
|     }); | ||||
|  | ||||
|     // ✅ Redirect when the "Go" button is clicked | ||||
|     goButton.addEventListener('click', () => { | ||||
|         const value = searchBox.value.trim(); | ||||
|         if (value) { | ||||
|             const baseURL = "{{url_for('add_meal_v2.add_existing', input='!')}}"; | ||||
|             window.location.href = baseURL.replace("!", encodeURIComponent(value)); | ||||
|         } | ||||
|     }); | ||||
| </script> | ||||
|  | ||||
| <script type="module"> | ||||
|     import { BrowserMultiFormatReader } from 'https://cdn.jsdelivr.net/npm/@zxing/library@0.21.3/+esm'; | ||||
|  | ||||
|     // constants | ||||
|     const codeReader = new BrowserMultiFormatReader(); | ||||
|     const videoElement = document.getElementById('video'); | ||||
|  | ||||
|  | ||||
|     // Start scanning for barcode | ||||
|     document.getElementById('startButton').addEventListener('click', async () => { | ||||
|         console.log('[DEBUG] Start button clicked') | ||||
|         try { | ||||
|             await navigator.mediaDevices.getUserMedia({ video: true }); | ||||
|         } catch (err) { | ||||
|             alert("No camera found or no camera permission"); | ||||
|             console.error("Could not access the camera:", err); | ||||
|             return; | ||||
|         } | ||||
|         console.log('[DEBUG] Permission given and at least one device present'); | ||||
|         const devices = await codeReader.listVideoInputDevices(); | ||||
|         console.log('[DEBUG] Cameras found:', devices); | ||||
|         const rearCamera = devices.find(device => device.label.toLowerCase().includes('back')) | ||||
|             || devices.find(device => device.label.toLowerCase().includes('rear')) | ||||
|             || devices[0]; // fallback | ||||
|  | ||||
|         const selectedDeviceId = rearCamera?.deviceId; | ||||
|         await codeReader.decodeFromVideoDevice(selectedDeviceId, videoElement, async (result, err) => { | ||||
|             if (result) { | ||||
|                 // Result found, this should post the barcode | ||||
|                 const codeText = result.getText(); | ||||
|                 const baseURL = "{{url_for('add_meal_v2.add_existing', input='!')}}"; | ||||
|                 window.location.href = baseURL.replace("!", encodeURIComponent(codeText)); | ||||
|             } | ||||
|         }) | ||||
|     }) | ||||
|  | ||||
|     document.getElementById('stopButton').addEventListener('click', () => { | ||||
|         codeReader.reset(); | ||||
|     }); | ||||
| </script> | ||||
| {% endblock %} | ||||
| @@ -35,8 +35,8 @@ def login(): | ||||
|     return render_template("login.html", form=form) | ||||
|  | ||||
|  | ||||
| @bp.route("/change_password", methods=["GET", "POST"]) | ||||
| def change_password(): | ||||
| @bp.route("/change_pass", methods=["GET", "POST"]) | ||||
| def change_pass(): | ||||
|     if not current_user.is_authenticated: | ||||
|         return redirect(url_for("auth.login")) | ||||
|  | ||||
| @@ -50,8 +50,9 @@ def change_password(): | ||||
|             current_user.change_password(form.new_password.data) | ||||
|             current_user.set_pw_change(False) | ||||
|             db.session.commit() | ||||
|             logout_user() | ||||
|             return default_return() | ||||
|     return render_template("change_password.html", form=form) | ||||
|     return render_template("new_change_password.html", form=form) | ||||
|  | ||||
|  | ||||
| @bp.route("/logout") | ||||
|   | ||||
							
								
								
									
										52
									
								
								application/auth/templates/new_change_password.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										52
									
								
								application/auth/templates/new_change_password.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,52 @@ | ||||
| {% extends "base.html" %} | ||||
|  | ||||
| {% block title %}Change Password{%endblock%} | ||||
|  | ||||
| {% block content %} | ||||
| <style> | ||||
|     .card { | ||||
|         border-radius: 16px; | ||||
|         box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1); | ||||
|     } | ||||
| </style> | ||||
|  | ||||
| <div class="d-flex justify-content-center align-items-center"> | ||||
|     <div class="card p-4" style="max-width: 400px; width: 90%"> | ||||
|         <h1 class="text-center mb-4" style="font-size: 2rem;">Change Your Password</h1> | ||||
|         <form method="POST"> | ||||
|             {{ form.hidden_tag() }} | ||||
|             <div class="mb-3"> | ||||
|                 <label for="current-password" class="form-label">Current Password</label> | ||||
|                 {{ form.current_password(class="form-control", placeholder="") }} | ||||
|                 {% if form.current_password.errors %} | ||||
|                 <div class="text-danger small"> | ||||
|                     {{ form.current_password.errors[0] }} | ||||
|                 </div> | ||||
|                 {% endif %} | ||||
|             </div> | ||||
|             <div class="mb-3"> | ||||
|                 <label for="new-password" class="form-label">New Password</label> | ||||
|                 {{ form.new_password(class="form-control", placeholder="Enter password") }} | ||||
|                 {% if form.new_password.errors %} | ||||
|                 <div class="text-danger small"> | ||||
|                     {{ form.new_password.errors[0] }} | ||||
|                 </div> | ||||
|                 {% endif %} | ||||
|             </div> | ||||
|             <div class="mb-3"> | ||||
|                 <label for="confirm-password" class="form-label">Confirm New Password</label> | ||||
|                 {{ form.confirm_password(class="form-control", placeholder="Enter password") }} | ||||
|                 {% if form.confirm_password.errors %} | ||||
|                 <div class="text-danger small"> | ||||
|                     {{ form.confirm_password.errors[0] }} | ||||
|                 </div> | ||||
|                 {% endif %} | ||||
|             </div> | ||||
|             {{ form.submit(class="btn btn-primary w-100", label="Update Password") }} | ||||
|         </form> | ||||
|         <p class="text-center text-muted mt-3" style="font-size: 0.85rem;"> | ||||
|             Make sure your password is at least 8 characters long and includes a mix of letters and numbers. | ||||
|         </p> | ||||
|     </div> | ||||
| </div> | ||||
| {% endblock %} | ||||
| @@ -10,74 +10,16 @@ | ||||
|     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> | ||||
| </head> | ||||
|  | ||||
| <body class="bg-body-secondary"> | ||||
|     <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4"> | ||||
|         <div class="container-fluid"> | ||||
|             <a class="navbar-brand" href="{{ url_for('index') }}">CalCounter</a> | ||||
|             <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" | ||||
|                 aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> | ||||
|                 <span class="navbar-toggler-icon"></span> | ||||
|             </button> | ||||
| <body class="bg-body-secondary" style="max-width: calc(100vh*9/16); margin: 0 auto;"> | ||||
|     {% include "new_navbar.html" %} | ||||
|  | ||||
|             <div class="collapse navbar-collapse" id="navbarNav"> | ||||
|                 <div class="d-flex w-100"> | ||||
|                     <ul class="navbar-nav flex-grow-1"> | ||||
|                         <li class="nav-item"> | ||||
|                             <a class="nav-link" href="{{ url_for('user.daily_log2') }}">Daily Log (new)</a> | ||||
|                         </li> | ||||
|                         <li class="nav-item"> | ||||
|                             <a class="nav-link" href="{{ url_for('user.dashboard') }}">Dashboard</a> | ||||
|                         </li> | ||||
|                     </ul> | ||||
|                     <ul class="navbar-nav"> | ||||
|                         {% if current_user.is_authenticated %} | ||||
|                         <li class="nav-item"> | ||||
|                             <a class="nav-link" href="{{ url_for('auth.logout') }}">Logout</a> | ||||
|                         </li> | ||||
|                         {% else %} | ||||
|                         <li class="nav-item"> | ||||
|                             <a class="nav-link" href="{{ url_for('auth.login') }}">Login</a> | ||||
|                         </li> | ||||
|                         {% endif %} | ||||
|                         <li class="nav-item"> | ||||
|                             <button id="toggleTheme" class="btn btn-outline-light">Toggle Theme</button> | ||||
|                         </li> | ||||
|                     </ul> | ||||
|                 </div> | ||||
|             </div> | ||||
|         </div> | ||||
|     </nav> | ||||
|  | ||||
|  | ||||
|     <div class="container"> | ||||
|         {% with messages = get_flashed_messages() %} | ||||
|         {% if messages %} | ||||
|         <div class="alert alert-info"> | ||||
|             {% for message in messages %} | ||||
|             <p>{{ message }}</p> | ||||
|             {% endfor %} | ||||
|         </div> | ||||
|         {% endif %} | ||||
|         {% endwith %} | ||||
|     {% include "flash.html" %} | ||||
|  | ||||
|     {% block content %} | ||||
|     {% endblock %} | ||||
|     </div> | ||||
|  | ||||
|     <script> | ||||
|         const html = document.documentElement; | ||||
|         const savedTheme = localStorage.getItem("theme"); | ||||
|         if (savedTheme) { | ||||
|             html.setAttribute("data-bs-theme", savedTheme); | ||||
|         } | ||||
|  | ||||
|         document.getElementById("toggleTheme").addEventListener("click", () => { | ||||
|             const current = html.getAttribute("data-bs-theme"); | ||||
|             const next = current === "dark" ? "light" : "dark"; | ||||
|             html.setAttribute("data-bs-theme", next); | ||||
|             localStorage.setItem("theme", next); | ||||
|         }); | ||||
|     </script> | ||||
|     {% block footer %} | ||||
|     {% endblock %} | ||||
|  | ||||
|     <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> | ||||
|  | ||||
|   | ||||
							
								
								
									
										9
									
								
								application/templates/flash.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								application/templates/flash.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,9 @@ | ||||
| {% with messages = get_flashed_messages() %} | ||||
| {% if messages %} | ||||
| <div class="alert alert-info"> | ||||
|     {% for message in messages %} | ||||
|     <p>{{ message }}</p> | ||||
|     {% endfor %} | ||||
| </div> | ||||
| {% endif %} | ||||
| {% endwith %} | ||||
							
								
								
									
										51
									
								
								application/templates/navbar.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										51
									
								
								application/templates/navbar.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,51 @@ | ||||
| <nav class="navbar navbar-dark bg-dark mb-4"> | ||||
|     <div class="container-fluid"> | ||||
|         <a class="navbar-brand" href="{{ url_for('index') }}">CalCounter</a> | ||||
|         <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" | ||||
|             aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> | ||||
|             <span class="navbar-toggler-icon"></span> | ||||
|         </button> | ||||
|  | ||||
|         <div class="collapse navbar-collapse" id="navbarNav"> | ||||
|             <div class="d-flex w-100"> | ||||
|                 <ul class="navbar-nav flex-grow-1"> | ||||
|                     <li class="nav-item"> | ||||
|                         <a class="nav-link" href="{{ url_for('user.daily_log') }}">Daily Log (new)</a> | ||||
|                     </li> | ||||
|                     <li class="nav-item"> | ||||
|                         <a class="nav-link" href="{{ url_for('user.dashboard') }}">Dashboard</a> | ||||
|                     </li> | ||||
|                 </ul> | ||||
|                 <ul class="navbar-nav"> | ||||
|                     {% if current_user.is_authenticated %} | ||||
|                     <li class="nav-item"> | ||||
|                         <a class="nav-link" href="{{ url_for('auth.logout') }}">Logout</a> | ||||
|                     </li> | ||||
|                     {% else %} | ||||
|                     <li class="nav-item"> | ||||
|                         <a class="nav-link" href="{{ url_for('auth.login') }}">Login</a> | ||||
|                     </li> | ||||
|                     {% endif %} | ||||
|                     <li class="nav-item"> | ||||
|                         <button id="toggleTheme" class="btn btn-outline-light">Toggle Theme</button> | ||||
|                     </li> | ||||
|                 </ul> | ||||
|             </div> | ||||
|         </div> | ||||
|     </div> | ||||
| </nav> | ||||
|  | ||||
| <script> | ||||
|     const html = document.documentElement; | ||||
|     const savedTheme = localStorage.getItem("theme"); | ||||
|     if (savedTheme) { | ||||
|         html.setAttribute("data-bs-theme", savedTheme); | ||||
|     } | ||||
|  | ||||
|     document.getElementById("toggleTheme").addEventListener("click", () => { | ||||
|         const current = html.getAttribute("data-bs-theme"); | ||||
|         const next = current === "dark" ? "light" : "dark"; | ||||
|         html.setAttribute("data-bs-theme", next); | ||||
|         localStorage.setItem("theme", next); | ||||
|     }); | ||||
| </script> | ||||
							
								
								
									
										60
									
								
								application/templates/new_navbar.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										60
									
								
								application/templates/new_navbar.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,60 @@ | ||||
| <!-- Navbar --> | ||||
| <nav class="navbar bg-body shadow-sm mb-2"> | ||||
|     <div class="container"> | ||||
|         <a class="navbar-brand" href="#">TaskManager</a> | ||||
|         <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" | ||||
|             aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> | ||||
|             <span class="navbar-toggler-icon"></span> | ||||
|         </button> | ||||
|         <div class="collapse navbar-collapse" id="navbarNav"> | ||||
|             <ul class="navbar-nav me-auto"> | ||||
|                 <li class="nav-item"> | ||||
|                     <a class="nav-link" href="{{ url_for('user.daily_log') }}">Daily Overview</a> | ||||
|                 </li> | ||||
|                 <li class="nav-item"> | ||||
|                     <a class="nav-link" href="{{ url_for('user.dashboard') }}">Dashboard</a> | ||||
|                 </li> | ||||
|             </ul> | ||||
|             <ul class="navbar-nav ms-auto"> | ||||
|                 {% if current_user.is_authenticated %} | ||||
|                 <li class="nav-item dropdown"> | ||||
|                     <a class="nav-link dropdown-toggle" href="#" id="accountDropdown" role="button" | ||||
|                         data-bs-toggle="dropdown" aria-expanded="false"> | ||||
|                         Account | ||||
|                     </a> | ||||
|                     <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="accountDropdown"> | ||||
|                         <li><a class="dropdown-item" href='{{ url_for("auth.change_pass") }}'>Change Password</a></li> | ||||
|                         <li><a class="dropdown-item" href="#">Profile</a></li> | ||||
|                         <li> | ||||
|                             <hr class="dropdown-divider"> | ||||
|                         </li> | ||||
|                         <li><a class="dropdown-item" href='{{ url_for("auth.logout") }}'>Logout</a></li> | ||||
|                     </ul> | ||||
|                 </li> | ||||
|                 {% else %} | ||||
|                 <li class="nav-item"> | ||||
|                     <a class="nav-link" href="#">Login</a> | ||||
|                 </li> | ||||
|                 {% endif %} | ||||
|                 <li class="nav-item"> | ||||
|                     <button id="toggleTheme" class="btn btn-body-secondary bg-dark-subtle">Toggle Theme</button> | ||||
|                 </li> | ||||
|             </ul> | ||||
|         </div> | ||||
|     </div> | ||||
| </nav> | ||||
|  | ||||
| <script> | ||||
|     const html = document.documentElement; | ||||
|     const savedTheme = localStorage.getItem("theme"); | ||||
|     if (savedTheme) { | ||||
|         html.setAttribute("data-bs-theme", savedTheme); | ||||
|     } | ||||
|  | ||||
|     document.getElementById("toggleTheme").addEventListener("click", () => { | ||||
|         const current = html.getAttribute("data-bs-theme"); | ||||
|         const next = current === "dark" ? "light" : "dark"; | ||||
|         html.setAttribute("data-bs-theme", next); | ||||
|         localStorage.setItem("theme", next); | ||||
|     }); | ||||
| </script> | ||||
| @@ -12,7 +12,7 @@ from application import db | ||||
| from forms import FoodItemForm | ||||
| from models import FoodItem, FoodLog | ||||
| from datetime import datetime | ||||
| from application.utils import login_required | ||||
| from application.utils import login_required, macro_arr_to_json | ||||
| from numpy import array | ||||
| from zoneinfo import ZoneInfo | ||||
|  | ||||
| @@ -22,58 +22,6 @@ user_bp = Blueprint( | ||||
|     template_folder="templates", | ||||
| ) | ||||
|  | ||||
|  | ||||
| def macro_arr_to_json(data: list[float]): | ||||
|     assert len(data) == 4 | ||||
|     cal = data[0] | ||||
|     pro = data[3] | ||||
|     car = data[2] | ||||
|     fat = data[1] | ||||
|     macros = [ | ||||
|         { | ||||
|             "name": "Calories", | ||||
|             "current": cal, | ||||
|             "target": 2000, | ||||
|             "bar_width": 100 - abs(cal / 20 - 100), | ||||
|             "bar_width_overflow": max(0, cal / 20 - 100), | ||||
|             "unit": " kcal", | ||||
|             "color": "bg-calories", | ||||
|             "overflow_color": "bg-calories-dark", | ||||
|         }, | ||||
|         { | ||||
|             "name": "Protein", | ||||
|             "current": pro, | ||||
|             "target": 150, | ||||
|             "bar_width": 100 - abs(pro / 1.5 - 100), | ||||
|             "bar_width_overflow": max(0, pro / 1.5 - 100), | ||||
|             "unit": "g", | ||||
|             "color": "bg-protein", | ||||
|             "overflow_color": "bg-protein-dark", | ||||
|         }, | ||||
|         { | ||||
|             "name": "Carbs", | ||||
|             "current": car, | ||||
|             "target": 250, | ||||
|             "bar_width": 100 - abs(car / 2.5 - 100), | ||||
|             "bar_width_overflow": max(0, car / 2.5 - 100), | ||||
|             "unit": "g", | ||||
|             "color": "bg-carbs", | ||||
|             "overflow_color": "bg-carbs-dark", | ||||
|         }, | ||||
|         { | ||||
|             "name": "Fat", | ||||
|             "current": fat, | ||||
|             "target": 70, | ||||
|             "bar_width": 100 - abs(fat / 0.7 - 100), | ||||
|             "bar_width_overflow": max(0, fat / 0.7 - 100), | ||||
|             "unit": "g", | ||||
|             "color": "bg-fat", | ||||
|             "overflow_color": "bg-fat-dark", | ||||
|         }, | ||||
|     ] | ||||
|     return macros | ||||
|  | ||||
|  | ||||
| user_bp.before_request(login_required) | ||||
|  | ||||
|  | ||||
| @@ -83,6 +31,35 @@ def dashboard(): | ||||
|     return render_template("dashboard.html", items=items) | ||||
|  | ||||
|  | ||||
| @user_bp.route("/daily_log", methods=["GET"]) | ||||
| def daily_log(): | ||||
|     # Get today's date according to user's timezone | ||||
|     today = datetime.now(ZoneInfo(current_user.timezone)).date() | ||||
|  | ||||
|     # Save date in session | ||||
|     session["selected_date"] = today.isoformat() | ||||
|  | ||||
|     # Get logs from today | ||||
|     logs_today = current_user.food_logs.filter_by( | ||||
|         date_=today.isoformat() | ||||
|     ).all() | ||||
|  | ||||
|     # calculate macros | ||||
|     macros = array((0.0, 0.0, 0.0, 0.0)) | ||||
|     for log in logs_today: | ||||
|         macros += array(log.food_item.macros()) / 100 * log.amount | ||||
|     macros = macro_arr_to_json(macros.tolist()) | ||||
|  | ||||
|     # Render HTML | ||||
|     return render_template( | ||||
|         "daily_log.html", | ||||
|         macros=macros, | ||||
|         logs=logs_today, | ||||
|         today=today.strftime("%d/%m/%Y"), | ||||
|         min=min, | ||||
|     ) | ||||
|  | ||||
|  | ||||
| @user_bp.route("/delete_food_item/<int:id>", methods=["POST"]) | ||||
| def delete_food_item(id: int): | ||||
|     item = FoodItem.query.get(id) | ||||
| @@ -119,35 +96,6 @@ def edit_food_item(id: int): | ||||
|     return redirect(url_for("user.dashboard")) | ||||
|  | ||||
|  | ||||
| @user_bp.route("/daily_log2", methods=["GET"]) | ||||
| def daily_log2(): | ||||
|     # Get today's date according to user's timezone | ||||
|     today = datetime.now(ZoneInfo(current_user.timezone)).date() | ||||
|  | ||||
|     # Save date in session | ||||
|     session["selected_date"] = today.isoformat() | ||||
|  | ||||
|     # Get logs from today | ||||
|     logs_today = current_user.food_logs.filter_by( | ||||
|         date_=today.isoformat() | ||||
|     ).all() | ||||
|  | ||||
|     # calculate macros | ||||
|     macros = array((0.0, 0.0, 0.0, 0.0)) | ||||
|     for log in logs_today: | ||||
|         macros += array(log.food_item.macros()) / 100 * log.amount | ||||
|     macros = macro_arr_to_json(macros.tolist()) | ||||
|  | ||||
|     # Render HTML | ||||
|     return render_template( | ||||
|         "daily_log2.html", | ||||
|         macros=macros, | ||||
|         logs=logs_today, | ||||
|         today=today.strftime("%d/%m/%Y"), | ||||
|         min=min, | ||||
|     ) | ||||
|  | ||||
|  | ||||
| @user_bp.route("/remove_log/<int:id>", methods=["POST"]) | ||||
| def remove_log(id: int): | ||||
|     log = db.session.get(FoodLog, id) | ||||
| @@ -158,4 +106,4 @@ def remove_log(id: int): | ||||
|     # Delete log | ||||
|     db.session.delete(log) | ||||
|     db.session.commit() | ||||
|     return redirect(url_for("user.daily_log2")) | ||||
|     return redirect(url_for("user.daily_log")) | ||||
|   | ||||
| @@ -3,8 +3,6 @@ | ||||
| {% block title %}Daily Calorie Dashboard{% endblock %} | ||||
| 
 | ||||
| {% block content %} | ||||
| <link rel="stylesheet" href="{{ url_for('static', filename='css/macros.css') }}"> | ||||
| 
 | ||||
| <div class="container my-4"> | ||||
|     <h2 class="mb-3">Daily Calorie Dashboard ({{ today }})</h2> | ||||
| 
 | ||||
| @@ -13,14 +11,14 @@ | ||||
|         <h5>Macros</h5> | ||||
|         {% for macro in macros %} | ||||
|         <div class="mb-2"> | ||||
|             <span class="macro-text">{{ macro.name }}: {{ macro.current }} / {{ macro.target }}</span> | ||||
|             <span class="macro-text">{{ macro.name }}: {{ macro.current | int }} / {{ macro.target }}</span> | ||||
|             <div class="progress rounded" style="height: 24px;"> | ||||
|                 <div class="progress-bar bg-danger macro-bar" role="progressbar" | ||||
|                     style="width: {{ macro.bar_width_overflow }}%"> | ||||
|                     {{ (macro.current - macro.target) }}{{ macro.unit }} | ||||
|                     {{ (macro.current - macro.target) | int}}{{ macro.unit }} | ||||
|                 </div> | ||||
|                 <div class="progress-bar bg-success macro-bar" role="progressbar" style="width: {{ macro.bar_width }}%"> | ||||
|                     {{ min(macro.current, macro.target) }}{{ macro.unit }} | ||||
|                     {{ min(macro.current, macro.target) | int }}{{ macro.unit }} | ||||
|                 </div> | ||||
|             </div> | ||||
|         </div> | ||||
| @@ -32,15 +30,31 @@ | ||||
|         <h5>Items Eaten Today</h5> | ||||
|         <div class="list-group list-group-flush"> | ||||
|             {% for log in logs %} | ||||
|             <div class="list-group-item item-row d-flex justify-content-between align-items-center"> | ||||
|                 <span>({{ log.amount }}g) {{ log.food_item.name }}</span> | ||||
|                 <span>{{ log.food_item.energy_100 * log.amount / 100 }} kcal</span> | ||||
|             <div class="list-group-item d-flex align-items-center"> | ||||
|                 <!-- Weight: fixed width, right-aligned --> | ||||
|                 <span class="text-end" style="width: 6ch; flex-shrink: 0;"> | ||||
|                     ({{ log.amount | int }}g) | ||||
|                 </span> | ||||
| 
 | ||||
|                 <!-- Food name: flexible, truncates if too long --> | ||||
|                 <span class="text-truncate flex-grow-1" | ||||
|                     style="min-width: 0; margin-left: 0.5rem; margin-right: 0.5rem;"> | ||||
|                     {{ log.food_item.name }} | ||||
|                 </span> | ||||
| 
 | ||||
|                 <!-- kcal: fixed width, right-aligned, pushed to the right --> | ||||
|                 <span class="d-inline-block text-end ms-auto" style="width: 9ch; flex-shrink: 0;"> | ||||
|                     {{ (log.food_item.energy_100 * log.amount / 100) | int }} kcal | ||||
|                 </span> | ||||
|             </div> | ||||
|             {% endfor %} | ||||
|         </div> | ||||
|     </div> | ||||
| 
 | ||||
| 
 | ||||
| 
 | ||||
| 
 | ||||
| 
 | ||||
| </div> | ||||
| 
 | ||||
| <!-- Bottom Navigation Buttons --> | ||||
| @@ -52,7 +66,7 @@ | ||||
|         </a> | ||||
| 
 | ||||
|         <!-- Center Button (highlighted) --> | ||||
|         <a id="set_link_date" href="{{ url_for('add_meal_v2.get_barcode') }}" | ||||
|         <a id="set_link_date" href="{{ url_for('add_meal.find_item') }}" | ||||
|             class="btn btn-success flex-fill mx-2 fw-bold rounded-pill"> | ||||
|             + Add Item | ||||
|         </a> | ||||
| @@ -14,7 +14,7 @@ def login_required(): | ||||
|  | ||||
|  | ||||
| def default_return(next_page: Optional[str] = None): | ||||
|     return redirect(url_for("user.daily_log2")) | ||||
|     return redirect(url_for("user.daily_log")) | ||||
|     if next_page: | ||||
|         return redirect(next_page) | ||||
|     if current_user.is_admin: | ||||
| @@ -29,3 +29,54 @@ def is_valid_timezone(tz: str) -> bool: | ||||
|         print(Exception) | ||||
|         return False | ||||
|     return True | ||||
|  | ||||
|  | ||||
| def macro_arr_to_json(data: list[float]): | ||||
|     assert len(data) == 4 | ||||
|     cal = data[0] | ||||
|     pro = data[3] | ||||
|     car = data[2] | ||||
|     fat = data[1] | ||||
|     macros = [ | ||||
|         { | ||||
|             "name": "Calories", | ||||
|             "current": cal, | ||||
|             "target": 2000, | ||||
|             "bar_width": 100 - abs(cal / 20 - 100), | ||||
|             "bar_width_overflow": max(0, cal / 20 - 100), | ||||
|             "unit": " kcal", | ||||
|             "color": "bg-calories", | ||||
|             "overflow_color": "bg-calories-dark", | ||||
|         }, | ||||
|         { | ||||
|             "name": "Protein", | ||||
|             "current": pro, | ||||
|             "target": 150, | ||||
|             "bar_width": 100 - abs(pro / 1.5 - 100), | ||||
|             "bar_width_overflow": max(0, pro / 1.5 - 100), | ||||
|             "unit": "g", | ||||
|             "color": "bg-protein", | ||||
|             "overflow_color": "bg-protein-dark", | ||||
|         }, | ||||
|         { | ||||
|             "name": "Carbs", | ||||
|             "current": car, | ||||
|             "target": 250, | ||||
|             "bar_width": 100 - abs(car / 2.5 - 100), | ||||
|             "bar_width_overflow": max(0, car / 2.5 - 100), | ||||
|             "unit": "g", | ||||
|             "color": "bg-carbs", | ||||
|             "overflow_color": "bg-carbs-dark", | ||||
|         }, | ||||
|         { | ||||
|             "name": "Fat", | ||||
|             "current": fat, | ||||
|             "target": 70, | ||||
|             "bar_width": 100 - abs(fat / 0.7 - 100), | ||||
|             "bar_width_overflow": max(0, fat / 0.7 - 100), | ||||
|             "unit": "g", | ||||
|             "color": "bg-fat", | ||||
|             "overflow_color": "bg-fat-dark", | ||||
|         }, | ||||
|     ] | ||||
|     return macros | ||||
|   | ||||
| @@ -1,3 +1,7 @@ | ||||
| # For Python >=3.8, importlib-metadata backport is not needed | ||||
| python_version >= "3.12.10" | ||||
|  | ||||
| # Package requirements | ||||
| alembic==1.16.4 | ||||
| blinker==1.9.0 | ||||
| click==8.2.1 | ||||
|   | ||||
		Reference in New Issue
	
	Block a user