Skip to content

Commit

Permalink
Add some refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
cherriae committed Feb 10, 2025
1 parent 920fcad commit d4ba7fb
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 44 deletions.
41 changes: 20 additions & 21 deletions app/scout/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,27 +31,26 @@ def on_blueprint_init(state):
@limiter.limit("10 per minute")
@handle_route_errors
def add():
if request.method == "POST":
data = request.get_json() if request.is_json else request.form.to_dict()

# Convert the drawing coordinates from string to JSON if present
if "auto_path_coords" in data and isinstance(data["auto_path_coords"], str):
try:
json.loads(data["auto_path_coords"]) # Validate JSON
except json.JSONDecodeError:
flash("Invalid path coordinates format", "error")
return redirect(url_for("scouting.home"))

success, message = scouting_manager.add_scouting_data(data, current_user.get_id())

if success:
flash("Team data added successfully", "success")
else:
flash(f"Error adding data: {message}", "error")

return redirect(url_for("scouting.home"))

return render_template("scouting/add.html")
if request.method != "POST":
return render_template("scouting/add.html")
data = request.get_json() if request.is_json else request.form.to_dict()

# Convert the drawing coordinates from string to JSON if present
if "auto_path_coords" in data and isinstance(data["auto_path_coords"], str):
try:
json.loads(data["auto_path_coords"]) # Validate JSON
except json.JSONDecodeError:
flash("Invalid path coordinates format", "error")
return redirect(url_for("scouting.home"))

success, message = scouting_manager.add_scouting_data(data, current_user.get_id())

if success:
flash("Team data added successfully", "success")
else:
flash(f"Error adding data: {message}", "error")

return redirect(url_for("scouting.home"))


@scouting_bp.route("/scouting/list")
Expand Down
18 changes: 8 additions & 10 deletions app/scout/scouting_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,7 @@ def __init__(self, mongo_uri):
def _ensure_collections(self):
"""Ensure required collections exist"""
if "team_data" not in self.db.list_collection_names():
self.db.create_collection("team_data")
# Create indexes
self.db.team_data.create_index([("team_number", 1)])
self.db.team_data.create_index([("scouter_id", 1)])
logger.info("Created team_data collection and indexes")
self._create_team_data_collection()

def connect(self):
"""Establish connection to MongoDB with basic error handling"""
Expand All @@ -38,15 +34,17 @@ def connect(self):

# Ensure team_data collection exists
if "team_data" not in self.db.list_collection_names():
self.db.create_collection("team_data")
# Create indexes
self.db.team_data.create_index([("team_number", 1)])
self.db.team_data.create_index([("scouter_id", 1)])
logger.info("Created team_data collection and indexes")
self._create_team_data_collection()
except Exception as e:
logger.error(f"Failed to connect to MongoDB: {str(e)}")
raise

def _create_team_data_collection(self):
self.db.create_collection("team_data")
self.db.team_data.create_index([("team_number", 1)])
self.db.team_data.create_index([("scouter_id", 1)])
logger.info("Created team_data collection and indexes")

def ensure_connected(self):
"""Ensure we have a valid connection, reconnect if necessary"""
try:
Expand Down
12 changes: 9 additions & 3 deletions app/static/js/scout.add.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,9 @@ function loadImages() {
}

function drawBackground() {
if (!bgImage.complete) return;
if (!bgImage.complete) {
return;
}

const canvasWidth = canvas.width / window.devicePixelRatio;
const canvasHeight = canvas.height / window.devicePixelRatio;
Expand All @@ -164,7 +166,9 @@ function drawBackground() {
if (isMobile) {
// Use the pre-split field images for mobile
const mobileImage = isRedAlliance ? mobileRedImage : mobileBlueImage;
if (!mobileImage.complete) return;
if (!mobileImage.complete) {
return;
}

imageScale = Math.min(
canvasWidth / mobileImage.width,
Expand Down Expand Up @@ -224,7 +228,9 @@ function startDrawing(e) {

function draw(e) {
e.preventDefault();
if (!isDrawing) return;
if (!isDrawing) {
return;
}

const pos = getPointerPosition(e);

Expand Down
16 changes: 12 additions & 4 deletions app/static/js/scout.edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,9 @@ function resizeCanvas() {
}

function drawBackground() {
if (!bgImage.complete) return;
if (!bgImage.complete) {
return;
}

const canvasWidth = canvas.width / window.devicePixelRatio;
const canvasHeight = canvas.height / window.devicePixelRatio;
Expand All @@ -121,7 +123,9 @@ function drawBackground() {
if (isMobile) {
// Use the pre-split field images for mobile
const mobileImage = isRedAlliance ? mobileRedImage : mobileBlueImage;
if (!mobileImage.complete) return;
if (!mobileImage.complete) {
return;
}

imageScale = Math.min(
canvasWidth / mobileImage.width,
Expand Down Expand Up @@ -198,7 +202,9 @@ function startDrawing(e) {

function draw(e) {
e.preventDefault();
if (!isDrawing) return;
if (!isDrawing) {
return;
}

const pos = getPointerPosition(e);

Expand Down Expand Up @@ -291,7 +297,9 @@ function loadExistingPath(pathData) {
// Set alliance if it exists in the data
if (data.alliance) {
const allianceInput = document.querySelector(`input[name="alliance"][value="${data.alliance}"]`);
if (allianceInput) allianceInput.checked = true;
if (allianceInput) {
allianceInput.checked = true;
}
}

redrawPaths();
Expand Down
19 changes: 13 additions & 6 deletions app/static/js/scout.list.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,18 @@ document.addEventListener('DOMContentLoaded', function() {

function initializeCanvas() {
canvas = document.getElementById('modalAutoPath');
if (!canvas) return;
if (!canvas) {
return;
}

ctx = canvas.getContext('2d');
resizeCanvas();
}

function resizeCanvas() {
if (!canvas || !ctx) return;
if (!canvas || !ctx) {
return;
}

const container = canvas.parentElement;
const containerWidth = container.clientWidth;
Expand All @@ -85,7 +89,9 @@ function resizeCanvas() {
}

function drawPath(pathData, deviceType) {
if (!canvas || !ctx) return;
if (!canvas || !ctx) {
return;
}

const currentIsMobile = window.innerWidth < 768;
const alliance = pathData.alliance || 'red';
Expand Down Expand Up @@ -149,9 +155,10 @@ function drawPath(pathData, deviceType) {

function showAutoPath(pathData, autoNotes, deviceType) {
// Ensure pathData is an object
let pathObj = pathData;
if (typeof pathData === 'string') {
try {
pathData = JSON.parse(pathData);
pathObj = JSON.parse(pathData);
} catch (error) {
console.error('Failed to parse path data:', error);
return;
Expand All @@ -175,13 +182,13 @@ function showAutoPath(pathData, autoNotes, deviceType) {
resizeCanvas();

// Ensure pathData has the expected structure
if (!pathData || !pathData.points) {
if (!pathObj || !pathObj.points) {
console.error('Invalid path data structure');
return;
}

// Draw the path
drawPath(pathData, deviceType);
drawPath(pathObj, deviceType);
}

function closeAutoPathModal() {
Expand Down

0 comments on commit d4ba7fb

Please sign in to comment.