Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Tags fixed

sassanixd54ed49429c6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc62dc0..47649d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,18 @@
# Changelog
+# [0.9.9.0] - 2025-04-06
+
+### Fixed
+- **Tag Management:** Resolved issues with adding and deleting tags.
+ - **Backend:** Added the missing `DELETE /api/tags/<tag_id>` API endpoint (`backend/app.py`) to handle tag deletion requests, including removing associations from the `warranty_tags` table.
+ - **Frontend:** Corrected the `deleteTag` function (`frontend/script.js`) to use the `DELETE` method and the correct API endpoint.
+ - **Frontend:** Improved UI feedback for tag operations:
+ - The tag list in the "Manage Tags" modal now updates immediately after adding or deleting a tag (`renderExistingTags`).
+ - The tag input fields in the modal are cleared after successfully adding a tag.
+ - The tag filter dropdown on the main page updates after adding or deleting tags (`populateTagFilter`).
+ - Selected tags display in the add/edit warranty forms update correctly after a tag is deleted (`renderSelectedTags`, `renderEditSelectedTags`).
+ - Added loading spinners and improved toast notifications/error messages for tag creation and deletion.
+
## [0.9.8.9] - 2025-04-03
### Added
diff --git a/backend/app.py b/backend/app.py
index 4dc1c87..0a45be8 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -2848,61 +2848,83 @@ def create_tag():
@token_required
def update_tag(tag_id):
"""Update an existing tag"""
- conn = None
- try:
- data = request.json
-
- if not data:
- return jsonify({"error": "No data provided"}), 400
-
- name = data.get('name')
- color = data.get('color')
+ data = request.get_json()
+ new_name = data.get('name')
+ new_color = data.get('color')
+
+ if not new_name:
+ return jsonify({"error": "Tag name cannot be empty"}), 400
- if not name and not color:
- return jsonify({"error": "At least one field (name or color) is required"}), 400
-
- # Validate color format if provided
- if color and not re.match(r'^#[0-9A-Fa-f]{6}$', color):
- return jsonify({"error": "Invalid color format. Use hex format (e.g., #FF5733)"}), 400
+ # Validate color format (basic check)
+ if new_color and not re.match(r'^#[0-9a-fA-F]{6}$', new_color):
+ return jsonify({"error": "Invalid color format. Use hex (e.g., #RRGGBB)"}), 400
+ conn = None
+ try:
conn = get_db_connection()
with conn.cursor() as cur:
# Check if tag exists
cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
- if cur.fetchone() is None:
+ tag = cur.fetchone()
+ if not tag:
return jsonify({"error": "Tag not found"}), 404
+
+ # Check if new name conflicts with another tag
+ cur.execute('SELECT id FROM tags WHERE name = %s AND id != %s', (new_name, tag_id))
+ existing = cur.fetchone()
+ if existing:
+ return jsonify({"error": "A tag with this name already exists"}), 409
+
+ # Update the tag
+ cur.execute('UPDATE tags SET name = %s, color = %s, updated_at = NOW() WHERE id = %s RETURNING id, name, color',
+ (new_name, new_color, tag_id))
+ updated_tag = cur.fetchone()
- # Check if new name already exists (if name is being updated)
- if name:
- cur.execute('SELECT id FROM tags WHERE name = %s AND id != %s', (name, tag_id))
- if cur.fetchone():
- return jsonify({"error": "A tag with this name already exists"}), 409
-
- # Build update query
- update_fields = []
- values = []
+ conn.commit()
- if name:
- update_fields.append("name = %s")
- values.append(name)
+ return jsonify({"id": updated_tag[0], "name": updated_tag[1], "color": updated_tag[2]}), 200
- if color:
- update_fields.append("color = %s")
- values.append(color)
+ except Exception as e:
+ logger.error(f"Error updating tag {tag_id}: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to update tag"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/tags/<int:tag_id>', methods=['DELETE'])
+@token_required # Or @admin_required if only admins should delete tags
+def delete_tag_endpoint(tag_id):
+ """Delete a tag and its associations"""
+ conn = None
+ try:
+ # Check if the user has permission (you might want admin_required here)
+ # For now, just check if logged in using token_required
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if tag exists
+ cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ tag = cur.fetchone()
+ if not tag:
+ return jsonify({"error": "Tag not found"}), 404
+
+ # Delete associations from warranty_tags first
+ cur.execute('DELETE FROM warranty_tags WHERE tag_id = %s', (tag_id,))
- values.append(tag_id)
+ # Delete the tag itself
+ cur.execute('DELETE FROM tags WHERE id = %s', (tag_id,))
- # Update tag
- query = f"UPDATE tags SET {', '.join(update_fields)} WHERE id = %s"
- cur.execute(query, values)
conn.commit()
- return jsonify({"message": "Tag updated successfully"}), 200
+ return jsonify({"message": "Tag deleted successfully"}), 200
+
except Exception as e:
- logger.error(f"Error updating tag {tag_id}: {e}")
+ logger.error(f"Error deleting tag {tag_id}: {e}")
if conn:
conn.rollback()
- return jsonify({"error": "Failed to update tag"}), 500
+ return jsonify({"error": "Failed to delete tag"}), 500
finally:
if conn:
release_db_connection(conn)
@@ -2910,7 +2932,7 @@ def update_tag(tag_id):
@app.route('/api/warranties/<int:warranty_id>/tags', methods=['GET'])
@token_required
def get_warranty_tags(warranty_id):
- """Get all tags for a specific warranty"""
+ """Get all tags associated with a specific warranty"""
conn = None
try:
user_id = request.user['id']
diff --git a/frontend/script.js b/frontend/script.js
index 83acb5a..ee6ac02 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -2183,18 +2183,29 @@ function deleteTag(id) {
const token = localStorage.getItem('auth_token');
if (!token) {
console.error('No authentication token found');
+ showToast('Authentication required', 'error'); // Added toast for better feedback
return;
}
- fetch(`/api/tags/${id}`, {
- method: 'DELETE',
+ showLoadingSpinner(); // Show loading indicator
+
+ fetch(`/api/tags/${id}`, { // Use the correct URL with tag ID
+ method: 'DELETE', // Use DELETE method
headers: {
'Authorization': 'Bearer ' + token
}
})
.then(response => {
if (!response.ok) {
- throw new Error('Failed to delete tag');
+ // Log the status for debugging the 405 error
+ console.error(`Failed to delete tag. Status: ${response.status} ${response.statusText}`);
+ // Try to get error message from response body
+ return response.json().then(errData => {
+ throw new Error(errData.error || errData.message || 'Failed to delete tag');
+ }).catch(() => {
+ // If response body is not JSON or empty
+ throw new Error(`Failed to delete tag. Status: ${response.status}`);
+ });
}
return response.json();
})
@@ -2202,23 +2213,25 @@ function deleteTag(id) {
// Remove tag from allTags array
allTags = allTags.filter(tag => tag.id !== id);
- // Remove tag from selectedTags if present
+ // Remove tag from selectedTags if present (in both add and edit modes)
selectedTags = selectedTags.filter(tag => tag.id !== id);
+ editSelectedTags = editSelectedTags.filter(tag => tag.id !== id);
- // Rerender existing tags and selected tags
- renderExistingTags();
- renderSelectedTags();
-
- // Update summary if needed
- if (document.getElementById('summary-tags')) {
- updateSummary();
- }
+ // --- FIX: Re-render UI elements ---
+ renderExistingTags(); // Update the list in the modal
+ renderSelectedTags(); // Update selected tags in the add form
+ renderEditSelectedTags(); // Update selected tags in the edit form
+ populateTagFilter(); // Update the filter dropdown on the main page
+ // --- END FIX ---
showToast('Tag deleted successfully', 'success');
})
.catch(error => {
console.error('Error deleting tag:', error);
- showToast('Failed to delete tag', 'error');
+ showToast(error.message || 'Failed to delete tag', 'error'); // Show specific error message
+ })
+ .finally(() => {
+ hideLoadingSpinner(); // Hide loading indicator
});
}
@@ -2663,4 +2676,78 @@ function renderEditSelectedTags() {
placeholder.textContent = 'No tags selected';
editSelectedTagsContainer.appendChild(placeholder);
}
+}
+
+// Create a new tag via the management modal form
+function createNewTag() {
+ const tagNameInput = document.getElementById('newTagName');
+ const tagColorInput = document.getElementById('newTagColor');
+
+ const name = tagNameInput ? tagNameInput.value.trim() : '';
+ const color = tagColorInput ? tagColorInput.value : '#808080'; // Default color if input not found
+
+ if (!name) {
+ showToast('Tag name cannot be empty', 'error');
+ return;
+ }
+
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('No authentication token found');
+ showToast('Authentication required', 'error');
+ return;
+ }
+
+ showLoadingSpinner(); // Show loading indicator
+
+ fetch('/api/tags', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer ' + token
+ },
+ body: JSON.stringify({
+ name: name,
+ color: color
+ })
+ })
+ .then(response => {
+ if (!response.ok) {
+ if (response.status === 409) {
+ throw new Error('A tag with this name already exists');
+ }
+ // Try to get error message from response body
+ return response.json().then(errData => {
+ throw new Error(errData.error || errData.message || 'Failed to create tag');
+ }).catch(() => {
+ // If response body is not JSON or empty
+ throw new Error(`Failed to create tag. Status: ${response.status}`);
+ });
+ }
+ return response.json();
+ })
+ .then(data => {
+ // Add new tag to allTags array
+ allTags.push({
+ id: data.id,
+ name: data.name,
+ color: data.color
+ });
+
+ // --- FIX: Clear input fields and re-render existing tags ---
+ if (tagNameInput) tagNameInput.value = '';
+ if (tagColorInput) tagColorInput.value = '#808080'; // Reset color picker
+ renderExistingTags(); // Update the list in the modal
+ populateTagFilter(); // Update the filter dropdown on the main page
+ // --- END FIX ---
+
+ showToast('Tag created successfully', 'success');
+ })
+ .catch(error => {
+ console.error('Error creating tag:', error);
+ showToast(error.message || 'Failed to create tag', 'error');
+ })
+ .finally(() => {
+ hideLoadingSpinner(); // Hide loading indicator
+ });
}
\ No newline at end of file