Massive update for individual parts and part-lots

This commit is contained in:
2025-11-06 08:24:42 +01:00
parent 21d104280c
commit 8d00569798
72 changed files with 3744 additions and 99 deletions

View File

@@ -129,6 +129,13 @@
# Default: false
# BK_DISABLE_INDIVIDUAL_MINIFIGURES=false
# Optional: Disable the individual/loose parts system. This hides all individual part UI
# elements and prevents adding new individual parts (parts not associated with any set).
# The routes remain accessible so existing individual parts can still be viewed. Users who
# only track set-based parts can use this to simplify the interface. Does not disable the route.
# Default: false
# BK_DISABLE_INDIVIDUAL_PARTS=false
# Optional: Hide the 'Parts' entry from the menu. Does not disable the route.
# Default: false
# BK_HIDE_ALL_PARTS=true

1
.gitignore vendored
View File

@@ -36,3 +36,4 @@ offline/
TODO.md
run-local.sh
test-server.sh
data/

View File

@@ -30,6 +30,7 @@ from bricktracker.views.index import index_page
from bricktracker.views.instructions import instructions_page
from bricktracker.views.login import login_page
from bricktracker.views.individual_minifigure import individual_minifigure_page
from bricktracker.views.individual_part import individual_part_page
from bricktracker.views.minifigure import minifigure_page
from bricktracker.views.part import part_page
from bricktracker.views.set import set_page
@@ -37,11 +38,42 @@ from bricktracker.views.statistics import statistics_page
from bricktracker.views.storage import storage_page
from bricktracker.views.wish import wish_page
logger = logging.getLogger(__name__)
def _validate_config(app: Flask) -> None:
"""
Validate application configuration and log warnings for potential issues.
"""
# Check if both individual features are disabled
if app.config.get('DISABLE_INDIVIDUAL_PARTS') and app.config.get('DISABLE_INDIVIDUAL_MINIFIGURES'):
logger.warning(
'Both DISABLE_INDIVIDUAL_PARTS and DISABLE_INDIVIDUAL_MINIFIGURES are enabled. '
'Users will not be able to track standalone parts or minifigures.'
)
# Check if Rebrickable API key is missing
if not app.config.get('REBRICKABLE_API_KEY'):
logger.warning(
'REBRICKABLE_API_KEY is not set. You will not be able to fetch data from Rebrickable API. '
'Please set this in your .env file or environment variables.'
)
# Check authentication configuration
if not app.config.get('AUTHENTICATION_PASSWORD') and not app.config.get('AUTHENTICATION_KEY'):
logger.info(
'No authentication configured (AUTHENTICATION_PASSWORD or AUTHENTICATION_KEY). '
'Admin features will be accessible without login.'
)
def setup_app(app: Flask) -> None:
# Load the configuration
BrickConfigurationList(app)
# Validate configuration
_validate_config(app)
# Set the logging level
if app.config['DEBUG']:
logging.basicConfig(
@@ -82,6 +114,7 @@ def setup_app(app: Flask) -> None:
app.register_blueprint(instructions_page)
app.register_blueprint(login_page)
app.register_blueprint(individual_minifigure_page)
app.register_blueprint(individual_part_page)
app.register_blueprint(minifigure_page)
app.register_blueprint(part_page)
app.register_blueprint(set_page)

View File

@@ -19,6 +19,7 @@ CONFIG: Final[list[dict[str, Any]]] = [
{'n': 'DEFAULT_TABLE_PER_PAGE', 'd': 25, 'c': int},
{'n': 'DESCRIPTION_BADGE_MAX_LENGTH', 'd': 15, 'c': int},
{'n': 'DISABLE_INDIVIDUAL_MINIFIGURES', 'c': bool},
{'n': 'DISABLE_INDIVIDUAL_PARTS', 'c': bool},
{'n': 'DOMAIN_NAME', 'e': 'DOMAIN_NAME', 'd': ''},
{'n': 'FILE_DATETIME_FORMAT', 'd': '%d/%m/%Y, %H:%M:%S'},
{'n': 'HOST', 'd': '0.0.0.0'},

View File

@@ -85,6 +85,7 @@ RESTART_REQUIRED_VARS: Final[List[str]] = [
'BK_DATABASE_PATH',
'BK_DEBUG',
'BK_DISABLE_INDIVIDUAL_MINIFIGURES',
'BK_DISABLE_INDIVIDUAL_PARTS',
'BK_DOMAIN_NAME',
'BK_HOST',
'BK_PORT',

View File

@@ -464,6 +464,14 @@ class IndividualMinifigure(RebrickableMinifigure):
def url(self, /) -> str:
return url_for('individual_minifigure.details', id=self.fields.id)
# String representation for debugging
def __repr__(self, /) -> str:
"""String representation for debugging"""
figure = getattr(self.fields, 'figure', 'unknown')
name = getattr(self.fields, 'name', 'Unknown')
qty = getattr(self.fields, 'quantity', 0)
return f'<IndividualMinifigure {figure} "{name}" qty:{qty}>'
# URL for updating quantity
def url_for_quantity(self, /) -> str:
return url_for('individual_minifigure.update_quantity', id=self.fields.id)

View File

@@ -0,0 +1,700 @@
import logging
import os
import traceback
from typing import Any, Self, TYPE_CHECKING
from urllib.parse import urlparse
from uuid import uuid4
from flask import current_app, url_for
import requests
from shutil import copyfileobj
from .exceptions import NotFoundException, DatabaseException, ErrorException
from .record import BrickRecord
from .set_owner_list import BrickSetOwnerList
from .set_purchase_location_list import BrickSetPurchaseLocationList
from .set_storage_list import BrickSetStorageList
from .set_tag_list import BrickSetTagList
from .sql import BrickSQL
if TYPE_CHECKING:
from .socket import BrickSocket
logger = logging.getLogger(__name__)
# Individual part (standalone, not associated with a set or minifigure)
class IndividualPart(BrickRecord):
# Queries
select_query: str = 'individual_part/select/by_id'
insert_query: str = 'individual_part/insert'
update_query: str = 'individual_part/update'
def __init__(
self,
/,
*,
record: Any | None = None
):
super().__init__()
# Ingest the record if it has one
if record is not None:
self.ingest(record)
# Select a specific individual part by UUID
def select_by_id(self, id: str, /) -> Self:
self.fields.id = id
if not self.select(override_query=self.select_query):
raise NotFoundException(
'Individual part with id "{id}" not found'.format(id=id)
)
return self
# Delete an individual part
def delete(self, /) -> None:
sql = BrickSQL()
sql.executescript(
'individual_part/delete',
id=self.fields.id
)
sql.commit()
# Generate HTML ID for form elements
def html_id(self, prefix: str | None = None, /) -> str:
"""Generate HTML ID for form elements"""
components: list[str] = ['individual-part']
if prefix is not None:
components.append(prefix)
components.append(self.fields.part)
components.append(str(self.fields.color))
components.append(self.fields.id)
return '-'.join(components)
# URL for quantity update
def url_for_quantity(self, /) -> str:
"""URL for updating quantity"""
return url_for('individual_part.update_quantity', id=self.fields.id)
# URL for description update
def url_for_description(self, /) -> str:
"""URL for updating description"""
return url_for('individual_part.update_description', id=self.fields.id)
# URL for problem (missing/damaged) update
def url_for_problem(self, problem_type: str, /) -> str:
"""URL for updating problem counts (missing/damaged)"""
if problem_type == 'missing':
return url_for('individual_part.update_missing', id=self.fields.id)
elif problem_type == 'damaged':
return url_for('individual_part.update_damaged', id=self.fields.id)
else:
raise ValueError(f'Invalid problem type: {problem_type}')
# URL for checked status update
def url_for_checked(self, /) -> str:
"""URL for updating checked status"""
return url_for('individual_part.update_checked', id=self.fields.id)
# URL for this part's detail page
def url(self, /) -> str:
"""URL for this part's detail page"""
return url_for('individual_part.details', id=self.fields.id)
# String representation for debugging
def __repr__(self, /) -> str:
"""String representation for debugging"""
part_id = getattr(self.fields, 'part', 'unknown')
color_id = getattr(self.fields, 'color', 'unknown')
qty = getattr(self.fields, 'quantity', 0)
return f'<IndividualPart {part_id} color:{color_id} qty:{qty}>'
# Get or fetch color information from rebrickable_colors table
@staticmethod
def get_or_fetch_color(color_id: int, /) -> dict[str, Any] | None:
"""
Get color information from cache table, or fetch from API if not cached.
Returns dict with: name, rgb, is_trans, bricklink_color_id, bricklink_color_name
"""
sql = BrickSQL()
# Check if color exists in cache
check_query = """
SELECT "color_id", "name", "rgb", "is_trans",
"bricklink_color_id", "bricklink_color_name"
FROM "rebrickable_colors"
WHERE "color_id" = :color_id
"""
sql.cursor.execute(check_query, {'color_id': color_id})
result = sql.cursor.fetchone()
if result:
# Color found in cache
return {
'color_id': result[0],
'name': result[1],
'rgb': result[2],
'is_trans': result[3],
'bricklink_color_id': result[4],
'bricklink_color_name': result[5]
}
# Color not in cache, fetch from API
try:
import rebrick
import json
rebrick.init(current_app.config['REBRICKABLE_API_KEY'])
color_response = rebrick.lego.get_color(color_id)
color_data = json.loads(color_response.read())
# Extract BrickLink color info
bricklink_color_id = None
bricklink_color_name = None
if 'external_ids' in color_data and 'BrickLink' in color_data['external_ids']:
bricklink_info = color_data['external_ids']['BrickLink']
if 'ext_ids' in bricklink_info and bricklink_info['ext_ids']:
bricklink_color_id = bricklink_info['ext_ids'][0]
if 'ext_descrs' in bricklink_info and bricklink_info['ext_descrs']:
bricklink_color_name = bricklink_info['ext_descrs'][0][0] if bricklink_info['ext_descrs'][0] else None
# Store in cache
insert_query = """
INSERT OR REPLACE INTO "rebrickable_colors" (
"color_id", "name", "rgb", "is_trans",
"bricklink_color_id", "bricklink_color_name"
) VALUES (
:color_id, :name, :rgb, :is_trans,
:bricklink_color_id, :bricklink_color_name
)
"""
sql.cursor.execute(insert_query, {
'color_id': color_data['id'],
'name': color_data['name'],
'rgb': color_data.get('rgb'),
'is_trans': color_data.get('is_trans', False),
'bricklink_color_id': bricklink_color_id,
'bricklink_color_name': bricklink_color_name
})
sql.connection.commit()
logger.info(f'Cached color {color_id} ({color_data["name"]}) with BrickLink ID {bricklink_color_id}')
return {
'color_id': color_data['id'],
'name': color_data['name'],
'rgb': color_data.get('rgb'),
'is_trans': color_data.get('is_trans', False),
'bricklink_color_id': bricklink_color_id,
'bricklink_color_name': bricklink_color_name
}
except Exception as e:
logger.warning(f'Could not fetch color {color_id} from API: {e}')
return None
# Download image for this part
def download_image(self, image_url: str, /) -> None:
if not image_url:
return
# Create image_id from URL
image_id, _ = os.path.splitext(os.path.basename(urlparse(image_url).path))
if not image_id:
return
# Build path
parts_folder = current_app.config['PARTS_FOLDER']
extension = 'jpg' # Everything is saved as jpg
path = os.path.join(
current_app.static_folder, # type: ignore
parts_folder,
f'{image_id}.{extension}'
)
# Avoid downloading if file exists
if os.path.exists(path):
return
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(path), exist_ok=True)
# Download the image
try:
response = requests.get(image_url, stream=True)
if response.ok:
with open(path, 'wb') as f:
copyfileobj(response.raw, f)
logger.info(f'Downloaded image for part {self.fields.part} color {self.fields.color} to {path}')
except Exception as e:
logger.warning(f'Could not download image for part {self.fields.part} color {self.fields.color}: {e}')
# Load available colors for a part
def load_colors(self, socket: 'BrickSocket', data: dict[str, Any], /) -> bool:
# Check if individual parts are disabled
if current_app.config.get('DISABLE_INDIVIDUAL_PARTS', False):
socket.fail(message='Individual parts system is disabled.')
return False
try:
# Extract part number
part_num = str(data.get('part', '')).strip()
if not part_num:
raise ErrorException('Part number is required')
# Fetch available colors from Rebrickable
import rebrick
import json
rebrick.init(current_app.config['REBRICKABLE_API_KEY'])
# Setup progress tracking
socket.progress_count = 0
socket.progress_total = 2 # Fetch part info + fetch colors
try:
# Get part information for the name
socket.auto_progress(message='Fetching part information')
part_response = rebrick.lego.get_part(part_num)
part_data = json.loads(part_response.read())
part_name = part_data.get('name', part_num)
# Get all available colors for this part
socket.auto_progress(message='Fetching available colors')
colors_response = rebrick.lego.get_part_colors(part_num)
colors_data = json.loads(colors_response.read())
# Extract the results
colors = colors_data.get('results', [])
if not colors:
raise ErrorException(f'No colors found for part {part_num}')
# Download images locally if USE_REMOTE_IMAGES is False
if not current_app.config.get('USE_REMOTE_IMAGES', False):
# Add image downloads to progress
socket.progress_total += len(colors)
for color in colors:
image_url = color.get('part_img_url', '')
if image_url:
socket.auto_progress(message=f'Downloading image for {color.get("color_name", "color")}')
try:
self.download_image(image_url)
except Exception as e:
logger.warning(f'Could not download image for part {part_num} color {color.get("color_id")}: {e}')
# Emit the part colors loaded event
logger.info(f'Emitting {len(colors)} colors for part {part_num} ({part_name})')
socket.emit(
'PART_COLORS_LOADED',
{
'part': part_num,
'part_name': part_name,
'colors': colors,
'count': len(colors)
}
)
logger.info(f'Successfully loaded {len(colors)} colors for part {part_num}')
return True
except Exception as e:
error_msg = str(e)
# Provide helpful error message for printed/decorated parts
if '404' in error_msg or 'Not Found' in error_msg:
# Check if this might be a printed part (has letters/pattern code)
base_part = ''.join(c for c in part_num if c.isdigit())
if base_part and base_part != part_num:
raise ErrorException(
f'Part {part_num} not found in Rebrickable. This appears to be a printed/decorated part. '
f'Try searching for the base part number: {base_part}'
)
else:
raise ErrorException(
f'Part {part_num} not found in Rebrickable. '
f'Please verify the part number is correct.'
)
else:
raise ErrorException(
f'Could not fetch colors for part {part_num}: {error_msg}'
)
except Exception as e:
error_msg = str(e)
socket.fail(message=f'Could not load part colors: {error_msg}')
if not isinstance(e, (NotFoundException, ErrorException)):
logger.debug(traceback.format_exc())
return False
# Add a new individual part
def add(self, socket: 'BrickSocket', data: dict[str, Any], /) -> bool:
# Check if individual parts are disabled
if current_app.config.get('DISABLE_INDIVIDUAL_PARTS', False):
socket.fail(message='Individual parts system is disabled.')
return False
try:
# Reset progress
socket.progress_count = 0
socket.progress_total = 3
socket.auto_progress(message='Validating part and color')
# Extract data
part_num = str(data.get('part', '')).strip()
color_id = int(data.get('color', 0))
quantity = int(data.get('quantity', 1))
if not part_num:
raise ErrorException('Part number is required')
if color_id <= 0:
raise ErrorException('Valid color ID is required')
if quantity <= 0:
raise ErrorException('Quantity must be greater than 0')
# Check if color info was pre-loaded (from load_colors)
color_data = data.get('color_info', None)
part_name = data.get('part_name', None)
# Validate part+color exists in rebrickable_parts
# If not, fetch from Rebrickable or use pre-loaded data and insert
sql = BrickSQL()
check_query = """
SELECT COUNT(*) FROM "rebrickable_parts"
WHERE "part" = :part AND "color_id" = :color_id
"""
sql.cursor.execute(check_query, {'part': part_num, 'color_id': color_id})
exists = sql.cursor.fetchone()[0] > 0
# Store image URL for downloading later
image_url = None
if not exists:
# Fetch full color information (with BrickLink mapping)
socket.auto_progress(message='Fetching color information')
full_color_info = IndividualPart.get_or_fetch_color(color_id)
# If we have pre-loaded color data, use it; otherwise fetch from Rebrickable
if color_data and part_name:
# Use pre-loaded data from get_part_colors() response
socket.auto_progress(message='Using cached part info')
image_url = color_data.get('part_img_url', '')
# Insert into rebrickable_parts using the pre-loaded data
insert_part_query = """
INSERT OR IGNORE INTO "rebrickable_parts" (
"part", "color_id", "color_name", "color_rgb", "color_transparent",
"bricklink_color_id", "bricklink_color_name",
"name", "image", "url"
) VALUES (
:part, :color_id, :color_name, :color_rgb, :color_transparent,
:bricklink_color_id, :bricklink_color_name,
:name, :image, :url
)
"""
sql.cursor.execute(insert_part_query, {
'part': part_num,
'color_id': color_id,
'color_name': color_data.get('color_name', ''),
'color_rgb': full_color_info.get('rgb') if full_color_info else None,
'color_transparent': full_color_info.get('is_trans') if full_color_info else None,
'bricklink_color_id': full_color_info.get('bricklink_color_id') if full_color_info else None,
'bricklink_color_name': full_color_info.get('bricklink_color_name') if full_color_info else None,
'name': part_name,
'image': image_url,
'url': f'https://rebrickable.com/parts/{part_num}/'
})
else:
# Fetch from Rebrickable (fallback for old workflow)
socket.auto_progress(message='Fetching part info from Rebrickable')
import rebrick
import json
# Initialize rebrick with API key
rebrick.init(current_app.config['REBRICKABLE_API_KEY'])
try:
# Get part information
part_info = json.loads(rebrick.lego.get_part(part_num).read())
# Get color information (this also caches it in rebrickable_colors)
# full_color_info already fetched above, but get again to be sure
if not full_color_info:
full_color_info = IndividualPart.get_or_fetch_color(color_id)
# Get part+color specific info (for the image)
part_color_info = json.loads(rebrick.lego.get_part_color(part_num, color_id).read())
# Get image URL
image_url = part_color_info.get('part_img_url', part_info.get('part_img_url', ''))
# Insert into rebrickable_parts with BrickLink color info
insert_part_query = """
INSERT OR IGNORE INTO "rebrickable_parts" (
"part", "color_id", "color_name", "color_rgb", "color_transparent",
"bricklink_color_id", "bricklink_color_name",
"name", "image", "url"
) VALUES (
:part, :color_id, :color_name, :color_rgb, :color_transparent,
:bricklink_color_id, :bricklink_color_name,
:name, :image, :url
)
"""
sql.cursor.execute(insert_part_query, {
'part': part_info['part_num'],
'color_id': full_color_info['color_id'] if full_color_info else color_id,
'color_name': full_color_info['name'] if full_color_info else '',
'color_rgb': full_color_info['rgb'] if full_color_info else None,
'color_transparent': full_color_info['is_trans'] if full_color_info else None,
'bricklink_color_id': full_color_info.get('bricklink_color_id') if full_color_info else None,
'bricklink_color_name': full_color_info.get('bricklink_color_name') if full_color_info else None,
'name': part_info['name'],
'image': image_url,
'url': part_info['part_url']
})
except Exception as e:
error_msg = str(e)
# Provide helpful error message for printed/decorated parts
if '404' in error_msg or 'Not Found' in error_msg:
base_part = ''.join(c for c in part_num if c.isdigit())
if base_part and base_part != part_num:
raise ErrorException(
f'Part {part_num} with color {color_id} not found in Rebrickable. '
f'This appears to be a printed/decorated part. '
f'Try using the base part number: {base_part}'
)
else:
raise ErrorException(
f'Part {part_num} with color {color_id} not found in Rebrickable. '
f'Please verify the part number is correct.'
)
else:
raise ErrorException(
f'Part {part_num} with color {color_id} not found in Rebrickable: {error_msg}'
)
else:
# Part already exists in rebrickable_parts, get the image URL
sql.cursor.execute(
'SELECT "image" FROM "rebrickable_parts" WHERE "part" = :part AND "color_id" = :color_id',
{'part': part_num, 'color_id': color_id}
)
result = sql.cursor.fetchone()
if result and result[0]:
image_url = result[0]
# Generate UUID and insert individual part
socket.auto_progress(message='Adding part to collection')
part_id = str(uuid4())
# Get storage and purchase location
storage = BrickSetStorageList.get(
data.get('storage', ''),
allow_none=True
)
purchase_location = BrickSetPurchaseLocationList.get(
data.get('purchase_location', ''),
allow_none=True
)
# Set fields
self.fields.id = part_id
self.fields.part = part_num
self.fields.color = color_id
self.fields.quantity = quantity
self.fields.missing = 0
self.fields.damaged = 0
self.fields.checked = 0
self.fields.description = data.get('description', '')
self.fields.storage = storage.fields.id if storage else None
self.fields.purchase_location = purchase_location.fields.id if purchase_location else None
self.fields.purchase_date = data.get('purchase_date', None)
self.fields.purchase_price = data.get('purchase_price', None)
# Insert into database
self.insert(commit=False, no_defer=True)
# Save owners
owners: list[str] = list(data.get('owners', []))
for owner_id in owners:
owner = BrickSetOwnerList.get(owner_id)
owner.update_individual_part_state(self, state=True)
# Save tags
tags: list[str] = list(data.get('tags', []))
for tag_id in tags:
tag = BrickSetTagList.get(tag_id)
tag.update_individual_part_state(self, state=True)
# Commit
sql.connection.commit()
# Download image if we have a URL
if image_url:
try:
self.download_image(image_url)
except Exception as e:
# Don't fail the whole operation if image download fails
logger.warning(f'Could not download image for part {part_num} color {color_id}: {e}')
# Get color name for success message
color_name = 'Unknown'
if color_data and color_data.get('color_name'):
color_name = color_data.get('color_name')
elif full_color_info and full_color_info.get('name'):
color_name = full_color_info.get('name')
# Generate link to part details page
part_url = url_for('part.details', part=part_num, color=color_id)
socket.complete(
message=f'Successfully added part {part_num} in {color_name} (<a href="{part_url}">View details</a>)'
)
return True
except Exception as e:
error_msg = str(e)
if 'Individual parts system is disabled' in error_msg:
socket.fail(message=error_msg)
else:
socket.fail(
message=f'Could not add individual part: {error_msg}'
)
if not isinstance(e, (NotFoundException, ErrorException)):
logger.debug(traceback.format_exc())
return False
# Update a field
def update_field(self, field: str, value: Any, /) -> Self:
setattr(self.fields, field, value)
# Use a specific update query for each field
sql = BrickSQL()
update_query = f"""
UPDATE "bricktracker_individual_parts"
SET "{field}" = :value
WHERE "id" = :id
"""
sql.cursor.execute(update_query, {
'id': self.fields.id,
'value': value
})
sql.commit()
return self
# Update problem count (missing/damaged)
def update_problem(self, problem: str, data: dict[str, Any], /) -> int:
# Handle both 'value' key and 'amount' key
amount: str | int = data.get('value', data.get('amount', '')) # type: ignore
# We need a positive integer
try:
if amount == '':
amount = 0
amount = int(amount)
if amount < 0:
amount = 0
except Exception:
raise ErrorException(f'"{amount}" is not a valid integer')
if amount < 0:
raise ErrorException('Cannot set a negative amount')
setattr(self.fields, problem, amount)
BrickSQL().execute_and_commit(
f'individual_part/update/{problem}',
parameters={
'id': self.fields.id,
problem: amount
}
)
return amount
# Update checked status
def update_checked(self, data: dict[str, Any], /) -> bool:
# Handle both direct 'checked' key and changer.js 'value' key format
if data:
checked = data.get('checked', data.get('value', False))
else:
checked = False
checked = bool(checked)
self.fields.checked = 1 if checked else 0
BrickSQL().execute_and_commit(
'individual_part/update/checked',
parameters={
'id': self.fields.id,
'checked': self.fields.checked
}
)
return checked
# URL methods
def url(self, /) -> str:
return url_for('individual_part.details', id=self.fields.id)
def url_for_quantity(self, /) -> str:
return url_for('individual_part.update_quantity', id=self.fields.id)
def url_for_description(self, /) -> str:
return url_for('individual_part.update_description', id=self.fields.id)
def url_for_problem(self, problem: str, /) -> str:
if problem == 'missing':
return url_for('individual_part.update_missing', id=self.fields.id)
elif problem == 'damaged':
return url_for('individual_part.update_damaged', id=self.fields.id)
return ''
def url_for_checked(self, /) -> str:
return url_for('individual_part.update_checked', id=self.fields.id)
def url_for_delete(self, /) -> str:
return url_for('individual_part.delete_part', id=self.fields.id)
def url_for_image(self, /) -> str:
# Check if we should use remote images
if current_app.config.get('USE_REMOTE_IMAGES', False):
# Return remote URL directly
if hasattr(self.fields, 'image') and self.fields.image:
return self.fields.image
else:
return current_app.config.get('REBRICKABLE_IMAGE_NIL', '')
else:
# Use local images
from .rebrickable_image import RebrickableImage
if hasattr(self.fields, 'image') and self.fields.image:
# Extract image_id from URL
image_id, _ = os.path.splitext(os.path.basename(urlparse(self.fields.image).path))
if image_id:
# Return local static URL using RebrickableImage helper
return RebrickableImage.static_url(image_id, 'PARTS_FOLDER')
# Fallback to nil image
return RebrickableImage.static_url(RebrickableImage.nil_name(), 'PARTS_FOLDER')

View File

@@ -0,0 +1,93 @@
import logging
from typing import Self, TYPE_CHECKING
from .record_list import BrickRecordList
from .individual_part import IndividualPart
if TYPE_CHECKING:
from .set_storage import BrickSetStorage
logger = logging.getLogger(__name__)
# List of individual parts
class IndividualPartList(BrickRecordList):
# Queries
list_query: str = 'individual_part/list/all'
by_part_query: str = 'individual_part/list/by_part'
by_color_query: str = 'individual_part/list/by_color'
by_part_and_color_query: str = 'individual_part/list/by_part_and_color'
by_storage_query: str = 'individual_part/list/by_storage'
using_storage_query: str = 'individual_part/list/using_storage'
without_storage_query: str = 'individual_part/list/without_storage'
problem_query: str = 'individual_part/list/problem'
# Get all individual parts
def all(self, /) -> Self:
self.list(override_query=self.list_query)
return self
# Get individual parts by part number
def by_part(self, part: str, /) -> Self:
self.fields.part = part
self.list(override_query=self.by_part_query)
return self
# Get individual parts by color
def by_color(self, color_id: int, /) -> Self:
self.fields.color = color_id
self.list(override_query=self.by_color_query)
return self
# Get individual parts by part number and color
def by_part_and_color(self, part: str, color_id: int, /) -> Self:
self.fields.part = part
self.fields.color = color_id
self.list(override_query=self.by_part_and_color_query)
return self
# Get individual parts by storage location
def by_storage(self, storage: 'BrickSetStorage', /) -> Self:
self.fields.storage = storage.fields.id
self.list(override_query=self.by_storage_query)
return self
# Get individual parts using a specific storage location
def using_storage(self, storage: 'BrickSetStorage', /) -> Self:
self.fields.storage = storage.fields.id
self.list(override_query=self.using_storage_query)
return self
# Get individual parts without storage
def without_storage(self, /) -> Self:
self.list(override_query=self.without_storage_query)
return self
# Get individual parts with problems (missing or damaged)
def with_problems(self, /) -> Self:
self.list(override_query=self.problem_query)
return self
# Base individual part list
def list(
self,
/,
*,
override_query: str | None = None,
order: str | None = None,
limit: int | None = None,
**context,
) -> None:
# Load the individual parts from the database
for record in super().select(
override_query=override_query,
order=order,
limit=limit,
**context
):
individual_part = IndividualPart(record=record)
self.records.append(individual_part)
# Set the record class
def set_record_class(self, /) -> None:
self.record_class = IndividualPart

View File

@@ -0,0 +1,340 @@
import logging
import traceback
from typing import Any, Self, TYPE_CHECKING
from uuid import uuid4
from flask import url_for
from .exceptions import NotFoundException, DatabaseException, ErrorException
from .individual_part import IndividualPart
from .record import BrickRecord, format_timestamp
from .set_owner_list import BrickSetOwnerList
from .set_purchase_location_list import BrickSetPurchaseLocationList
from .set_storage_list import BrickSetStorageList
from .set_tag_list import BrickSetTagList
from .sql import BrickSQL
if TYPE_CHECKING:
from .socket import BrickSocket
logger = logging.getLogger(__name__)
# Individual part lot (collection/batch of individual parts added together)
class IndividualPartLot(BrickRecord):
# Queries
select_query: str = 'individual_part_lot/select/by_id'
insert_query: str = 'individual_part_lot/insert'
def __init__(
self,
/,
*,
record: Any | None = None
):
super().__init__()
# Ingest the record if it has one
if record is not None:
self.ingest(record)
# Select a specific lot by UUID
def select_by_id(self, id: str, /) -> Self:
self.fields.id = id
if not self.select(override_query=self.select_query):
raise NotFoundException(
'Individual part lot with id "{id}" not found'.format(id=id)
)
return self
# Delete a lot and all its parts
def delete(self, /) -> None:
BrickSQL().executescript(
'individual_part_lot/delete',
id=self.fields.id
)
# Get the URL for this lot
def url(self, /) -> str:
return url_for('individual_part.lot_details', lot_id=self.fields.id)
# String representation for debugging
def __repr__(self, /) -> str:
"""String representation for debugging"""
name = getattr(self.fields, 'name', 'Unnamed') or 'Unnamed'
lot_id = getattr(self.fields, 'id', 'unknown')
# Try to get part_count if available (from optimized query)
part_count = getattr(self.fields, 'part_count', '?')
return f'<IndividualPartLot "{name}" ({part_count} parts) id:{lot_id[:8]}...>'
# Format created date
def created_date_formatted(self, /) -> str:
"""Format the created date for display"""
return format_timestamp(self.fields.created_date)
# Format purchase date
def purchase_date_formatted(self, /) -> str:
"""Format the purchase date for display"""
return format_timestamp(self.fields.purchase_date)
# Get all parts in this lot
def parts(self, /) -> list['IndividualPart']:
"""Get all individual parts that belong to this lot"""
sql = BrickSQL()
parts_data = sql.fetchall('individual_part_lot/list/parts', lot_id=self.fields.id)
# Convert to list of IndividualPart objects using ingest()
return [IndividualPart(record=record) for record in parts_data]
# Create a new lot with parts from cart
def create(self, socket: 'BrickSocket', data: dict[str, Any], /) -> bool:
"""
Create a new individual part lot with multiple parts.
Expected data format:
{
'cart': [
{
'part': '3001',
'part_name': 'Brick 2 x 4',
'color_id': 1,
'color_name': 'White',
'quantity': 10,
'color_info': {...}
},
...
],
'name': 'Optional lot name',
'description': 'Optional lot description',
'storage': 'storage_id',
'purchase_location': 'purchase_location_id',
'purchase_date': timestamp,
'purchase_price': 0.0,
'owners': ['owner_id1', ...],
'tags': ['tag_id1', ...]
}
"""
try:
# Validate cart data
cart = data.get('cart', [])
if not cart or not isinstance(cart, list):
raise ErrorException('Cart is empty or invalid')
socket.auto_progress(
message=f'Creating lot with {len(cart)} parts',
increment_total=True
)
# Generate UUID for the lot
lot_id = str(uuid4())
self.fields.id = lot_id
# Set lot metadata
self.fields.name = data.get('name', None)
self.fields.description = data.get('description', None)
self.fields.created_date = datetime.now().timestamp()
# Get storage
storage = BrickSetStorageList.get(
data.get('storage', ''),
allow_none=True
)
self.fields.storage = storage.fields.id if storage else None
# Get purchase location
purchase_location = BrickSetPurchaseLocationList.get(
data.get('purchase_location', ''),
allow_none=True
)
self.fields.purchase_location = purchase_location.fields.id if purchase_location else None
# Set purchase info
self.fields.purchase_date = data.get('purchase_date', None)
self.fields.purchase_price = data.get('purchase_price', None)
# Insert the lot record
socket.auto_progress(
message='Inserting lot into database',
increment_total=True
)
self.insert(commit=False)
# Save owners
owners: list[str] = list(data.get('owners', []))
for owner_id in owners:
owner = BrickSetOwnerList.get(owner_id)
# Insert into junction table
sql = BrickSQL()
sql.cursor.execute(
'INSERT INTO "bricktracker_individual_part_lot_owners" ("id") VALUES (:id)',
{'id': lot_id}
)
# Save tags
tags: list[str] = list(data.get('tags', []))
for tag_id in tags:
tag = BrickSetTagList.get(tag_id)
# Insert into junction table
sql = BrickSQL()
sql.cursor.execute(
'INSERT INTO "bricktracker_individual_part_lot_tags" ("id") VALUES (:id)',
{'id': lot_id}
)
# Add all parts from cart
socket.auto_progress(
message=f'Adding {len(cart)} parts to lot',
increment_total=True
)
for idx, cart_item in enumerate(cart):
part_num = cart_item.get('part')
color_id = cart_item.get('color_id')
quantity = cart_item.get('quantity', 1)
color_info = cart_item.get('color_info', {})
socket.auto_progress(
message=f'Adding part {idx + 1}/{len(cart)}: {part_num} in {cart_item.get("color_name", "unknown color")}',
increment_total=True
)
# Create individual part with lot_id
part_uuid = str(uuid4())
# Use the add method but with lot_id
# We need to insert the part with the lot_id
sql = BrickSQL()
# First ensure the part exists in rebrickable_parts
IndividualPart.get_or_fetch_color(color_id)
# Insert the part with lot_id (NO individual metadata - inherited from lot)
insert_query = """
INSERT INTO "bricktracker_individual_parts" (
"id",
"part",
"color",
"quantity",
"missing",
"damaged",
"checked",
"description",
"storage",
"purchase_location",
"purchase_date",
"purchase_price",
"lot_id"
) VALUES (
:id,
:part,
:color,
:quantity,
0,
0,
0,
NULL,
NULL,
NULL,
NULL,
NULL,
:lot_id
)
"""
sql.cursor.execute(insert_query, {
'id': part_uuid,
'part': part_num,
'color': color_id,
'quantity': quantity,
'lot_id': lot_id
})
# Ensure part data is in rebrickable_parts
try:
# Check if part exists
check_query = """
SELECT COUNT(*) FROM "rebrickable_parts"
WHERE "part" = :part AND "color_id" = :color_id
"""
sql.cursor.execute(check_query, {'part': part_num, 'color_id': color_id})
exists = sql.cursor.fetchone()[0] > 0
if not exists:
# Insert part data
part_name = cart_item.get('part_name', '')
color_name = cart_item.get('color_name', '')
insert_part_query = """
INSERT OR IGNORE INTO "rebrickable_parts" (
"part",
"name",
"color_id",
"color_name",
"color_rgb",
"color_transparent",
"image",
"url",
"bricklink_color_id",
"bricklink_color_name"
) VALUES (
:part,
:name,
:color_id,
:color_name,
:color_rgb,
:color_transparent,
:image,
:url,
:bricklink_color_id,
:bricklink_color_name
)
"""
sql.cursor.execute(insert_part_query, {
'part': part_num,
'name': part_name,
'color_id': color_id,
'color_name': color_name,
'color_rgb': color_info.get('rgb', ''),
'color_transparent': color_info.get('is_trans', False),
'image': color_info.get('part_img_url', ''),
'url': f'https://rebrickable.com/parts/{part_num}/',
'bricklink_color_id': color_info.get('bricklink_color_id', None),
'bricklink_color_name': color_info.get('bricklink_color_name', None)
})
except Exception as e:
logger.warning(f'Could not ensure part data for {part_num}/{color_id}: {e}')
# Commit all changes
socket.auto_progress(
message='Committing changes to database',
increment_total=True
)
sql.commit()
socket.auto_progress(
message=f'Lot created successfully with {len(cart)} parts',
increment_total=True
)
# Complete with success message and lot URL
lot_url = self.url()
socket.complete(
message=f'Successfully created lot with {len(cart)} parts. <a href="{lot_url}">View lot</a>',
data={
'lot_id': lot_id,
'lot_url': lot_url
}
)
return True
except ErrorException as e:
socket.fail(message=str(e))
logger.error(f'Error creating lot: {e}')
return False
except Exception as e:
socket.fail(message=f'Unexpected error creating lot: {str(e)}')
logger.error(f'Unexpected error creating lot: {e}')
logger.error(traceback.format_exc())
return False

View File

@@ -0,0 +1,45 @@
import logging
from typing import Self, TYPE_CHECKING
from .record_list import BrickRecordList
from .individual_part_lot import IndividualPartLot
if TYPE_CHECKING:
from .set_storage import BrickSetStorage
logger = logging.getLogger(__name__)
# List of individual part lots
class IndividualPartLotList(BrickRecordList):
# Queries
list_query: str = 'individual_part_lot/list/all'
# Get all individual part lots
def all(self, /) -> Self:
self.list(override_query=self.list_query)
return self
# Base individual part lot list
def list(
self,
/,
*,
override_query: str | None = None,
order: str | None = None,
limit: int | None = None,
**context,
) -> None:
# Load the individual part lots from the database
for record in super().select(
override_query=override_query,
order=order,
limit=limit,
**context
):
lot = IndividualPartLot(record=record)
self.records.append(lot)
# Set the record class
def set_record_class(self, /) -> None:
self.record_class = IndividualPartLot

View File

@@ -10,6 +10,7 @@ from .record import BrickRecord
from .sql import BrickSQL
if TYPE_CHECKING:
from .individual_minifigure import IndividualMinifigure
from .individual_part import IndividualPart
from .set import BrickSet
logger = logging.getLogger(__name__)
@@ -23,6 +24,8 @@ class BrickMetadata(BrickRecord):
set_state_endpoint: str = ''
individual_minifigure_state_endpoint: str = ''
individual_minifigure_value_endpoint: str = ''
individual_part_state_endpoint: str = ''
individual_part_value_endpoint: str = ''
# Queries
delete_query: str
@@ -33,6 +36,8 @@ class BrickMetadata(BrickRecord):
update_set_value_query: str = ''
update_individual_minifigure_state_query: str = ''
update_individual_minifigure_value_query: str = ''
update_individual_part_state_query: str = ''
update_individual_part_value_query: str = ''
def __init__(
self,
@@ -126,6 +131,21 @@ class BrickMetadata(BrickRecord):
id=id
)
# URL to change the selected state of this metadata item for an individual part
def url_for_individual_part_state(self, id: str, /) -> str:
return url_for(
self.individual_part_state_endpoint,
id=id,
metadata_id=self.fields.id
)
# URL to change the value for an individual part
def url_for_individual_part_value(self, id: str, /) -> str:
return url_for(
self.individual_part_value_endpoint,
id=id
)
# Select a specific metadata (with an id)
def select_specific(self, id: str, /) -> Self:
# Save the parameters to the fields
@@ -195,6 +215,40 @@ class BrickMetadata(BrickRecord):
return value
# Generic method to update state for any entity type
def _update_entity_state(
self,
entity_type: str,
entity_id: str,
entity_name: str,
query: str,
/,
*,
json: Any | None = None,
state: Any | None = None
) -> Any:
"""Generic state update logic for sets, minifigures, and parts"""
if state is None and json is not None:
state = json.get('value', False)
parameters = self.sql_parameters()
parameters['id'] = entity_id
parameters['state'] = state
rows, _ = BrickSQL().execute_and_commit(
query,
parameters=parameters,
name=self.as_column(),
)
if rows != 1:
raise DatabaseException(f'Could not update the {self.kind} "{self.fields.name}" state for {entity_type} {entity_name} ({entity_id})')
# Info
logger.info(f'{self.kind.capitalize()} "{self.fields.name}" state changed to "{state}" for {entity_type} {entity_name} ({entity_id})')
return state
# Update the selected state of this metadata item for a set
def update_set_state(
self,
@@ -204,38 +258,15 @@ class BrickMetadata(BrickRecord):
json: Any | None = None,
state: Any | None = None
) -> Any:
if state is None and json is not None:
state = json.get('value', False)
parameters = self.sql_parameters()
parameters['set_id'] = brickset.fields.id
parameters['state'] = state
rows, _ = BrickSQL().execute_and_commit(
return self._update_entity_state(
'set',
brickset.fields.id,
brickset.fields.set,
self.update_set_state_query,
parameters=parameters,
name=self.as_column(),
json=json,
state=state
)
if rows != 1:
raise DatabaseException('Could not update the {kind} "{name}" state for set {set} ({id})'.format( # noqa: E501
kind=self.kind,
name=self.fields.name,
set=brickset.fields.set,
id=brickset.fields.id,
))
# Info
logger.info('{kind} "{name}" state changed to "{state}" for set {set} ({id})'.format( # noqa: E501
kind=self.kind,
name=self.fields.name,
state=state,
set=brickset.fields.set,
id=brickset.fields.id,
))
return state
# Check if this metadata has a specific individual minifigure
def has_individual_minifigure(
self,
@@ -263,37 +294,50 @@ class BrickMetadata(BrickRecord):
json: Any | None = None,
state: Any | None = None
) -> Any:
if state is None and json is not None:
state = json.get('value', False)
parameters = self.sql_parameters()
parameters['id'] = individual_minifigure.fields.id
parameters['state'] = state
rows, _ = BrickSQL().execute_and_commit(
return self._update_entity_state(
'individual minifigure',
individual_minifigure.fields.id,
individual_minifigure.fields.figure,
self.update_individual_minifigure_state_query,
parameters=parameters,
name=self.as_column(),
json=json,
state=state
)
if rows != 1:
raise DatabaseException('Could not update the {kind} "{name}" state for individual minifigure {figure} ({id})'.format(
kind=self.kind,
name=self.fields.name,
figure=individual_minifigure.fields.figure,
id=individual_minifigure.fields.id,
))
# Check if this metadata has a specific individual part
def has_individual_part(
self,
individual_part: 'IndividualPart',
/,
) -> bool:
"""Check if this owner/tag/status is assigned to an individual part"""
# Determine the table name based on metadata type
table_name = f'bricktracker_individual_part_{self.kind}s'
column_name = f'{self.kind}_{self.fields.id}'
# Info
logger.info('{kind} "{name}" state changed to "{state}" for individual minifigure {figure} ({id})'.format(
kind=self.kind,
name=self.fields.name,
state=state,
figure=individual_minifigure.fields.figure,
id=individual_minifigure.fields.id,
))
# Query to check if the relationship exists using raw SQL
sql = BrickSQL()
query = f'SELECT COUNT(*) as count FROM "{table_name}" WHERE "id" = ? AND "{column_name}" = 1'
result = sql.cursor.execute(query, (individual_part.fields.id,)).fetchone()
return state
return result and result['count'] > 0
# Update the selected state of this metadata item for an individual part
def update_individual_part_state(
self,
individual_part: 'IndividualPart',
/,
*,
json: Any | None = None,
state: Any | None = None
) -> Any:
return self._update_entity_state(
'individual part',
individual_part.fields.id,
f'{individual_part.fields.part} color {individual_part.fields.color}',
self.update_individual_part_state_query,
json=json,
state=state
)
# Update the selected value of this metadata item for a set
def update_set_value(

View File

@@ -114,7 +114,19 @@ class RebrickablePart(BrickRecord):
if self.fields.image is None:
file = RebrickableImage.nil_name()
else:
file = self.fields.image_id
# Use image_id if available, otherwise extract from image URL
if hasattr(self.fields, 'image_id') and self.fields.image_id:
file = self.fields.image_id
else:
# Extract image_id from URL on-the-fly
from urllib.parse import urlparse
import os
image_id, _ = os.path.splitext(
os.path.basename(
urlparse(self.fields.image).path
)
)
file = image_id if image_id else RebrickableImage.nil_name()
return RebrickableImage.static_url(file, 'PARTS_FOLDER')
else:
@@ -204,6 +216,48 @@ class RebrickablePart(BrickRecord):
if len(bricklink_data['ext_descrs']) > 0 and len(bricklink_data['ext_descrs'][0]) > 0:
record['bricklink_color_name'] = bricklink_data['ext_descrs'][0][0]
# Cache color information in rebrickable_colors table for future lookups
# This builds the translation table automatically as sets are imported
if 'color' in data:
try:
from .sql import BrickSQL
sql = BrickSQL()
# Check if color already exists in cache
check_query = """
SELECT COUNT(*) FROM "rebrickable_colors"
WHERE "color_id" = :color_id
"""
sql.cursor.execute(check_query, {'color_id': record['color_id']})
exists = sql.cursor.fetchone()[0] > 0
if not exists:
# Insert color into cache
insert_query = """
INSERT OR IGNORE INTO "rebrickable_colors" (
"color_id", "name", "rgb", "is_trans",
"bricklink_color_id", "bricklink_color_name"
) VALUES (
:color_id, :name, :rgb, :is_trans,
:bricklink_color_id, :bricklink_color_name
)
"""
sql.cursor.execute(insert_query, {
'color_id': record['color_id'],
'name': record['color_name'],
'rgb': record['color_rgb'],
'is_trans': record['color_transparent'],
'bricklink_color_id': record['bricklink_color_id'],
'bricklink_color_name': record['bricklink_color_name']
})
# Commit is handled by parent transaction
except Exception as e:
# Don't fail part import if color caching fails
import logging
logger = logging.getLogger(__name__)
logger.debug(f'Could not cache color {record["color_id"]}: {e}')
# Extract BrickLink part number if available
if 'part' in data and 'external_ids' in data['part']:
part_external_ids = data['part']['external_ids']
@@ -226,7 +280,7 @@ class RebrickablePart(BrickRecord):
)
)
if image_id is not None or image_id != '':
if image_id is not None and image_id != '':
record['image_id'] = image_id
return record

View File

@@ -1,3 +1,4 @@
from datetime import datetime
from sqlite3 import Row
from typing import Any, ItemsView
@@ -5,6 +6,24 @@ from .fields import BrickRecordFields
from .sql import BrickSQL
def format_timestamp(timestamp: float | None, format_key: str = 'PURCHASE_DATE_FORMAT') -> str:
"""
Format a timestamp for display.
Args:
timestamp: Unix timestamp (float) or None
format_key: Config key for date format string
Returns:
Formatted date string or empty string if timestamp is None
"""
if timestamp is not None:
from flask import current_app
time = datetime.fromtimestamp(timestamp)
return time.strftime(current_app.config.get(format_key, '%Y/%m/%d'))
return ''
# SQLite record
class BrickRecord(object):
select_query: str

View File

@@ -8,6 +8,7 @@ class BrickSetOwner(BrickMetadata):
# Endpoints
set_state_endpoint: str = 'set.update_owner'
individual_minifigure_state_endpoint: str = 'individual_minifigure.update_owner'
individual_part_state_endpoint: str = 'individual_part.update_owner'
# Queries
delete_query: str = 'set/metadata/owner/delete'
@@ -16,3 +17,4 @@ class BrickSetOwner(BrickMetadata):
update_field_query: str = 'set/metadata/owner/update/field'
update_set_state_query: str = 'set/metadata/owner/update/state'
update_individual_minifigure_state_query: str = 'individual_minifigure/metadata/owner/update/state'
update_individual_part_state_query: str = 'individual_part/metadata/owner/update/state'

View File

@@ -10,6 +10,7 @@ class BrickSetStatus(BrickMetadata):
# Endpoints
set_state_endpoint: str = 'set.update_status'
individual_minifigure_state_endpoint: str = 'individual_minifigure.update_status'
individual_part_state_endpoint: str = 'individual_part.update_status'
# Queries
delete_query: str = 'set/metadata/status/delete'
@@ -18,6 +19,7 @@ class BrickSetStatus(BrickMetadata):
update_field_query: str = 'set/metadata/status/update/field'
update_set_state_query: str = 'set/metadata/status/update/state'
update_individual_minifigure_state_query: str = 'individual_minifigure/metadata/status/update/state'
update_individual_part_state_query: str = 'individual_part/metadata/status/update/state'
# Grab data from a form
def from_form(self, form: dict[str, str], /) -> Self:

View File

@@ -8,6 +8,7 @@ class BrickSetTag(BrickMetadata):
# Endpoints
set_state_endpoint: str = 'set.update_tag'
individual_minifigure_state_endpoint: str = 'individual_minifigure.update_tag'
individual_part_state_endpoint: str = 'individual_part.update_tag'
# Queries
delete_query: str = 'set/metadata/tag/delete'
@@ -16,3 +17,4 @@ class BrickSetTag(BrickMetadata):
update_field_query: str = 'set/metadata/tag/update/field'
update_set_state_query: str = 'set/metadata/tag/update/state'
update_individual_minifigure_state_query: str = 'individual_minifigure/metadata/tag/update/state'
update_individual_part_state_query: str = 'individual_part/metadata/tag/update/state'

View File

@@ -18,6 +18,7 @@ logger = logging.getLogger(__name__)
MESSAGES: Final[dict[str, str]] = {
'COMPLETE': 'complete',
'CONNECT': 'connect',
'CREATE_LOT': 'create_lot',
'DISCONNECT': 'disconnect',
'DOWNLOAD_INSTRUCTIONS': 'download_instructions',
'DOWNLOAD_PEERON_PAGES': 'download_peeron_pages',
@@ -25,9 +26,13 @@ MESSAGES: Final[dict[str, str]] = {
'IMPORT_MINIFIGURE': 'import_minifigure',
'IMPORT_SET': 'import_set',
'LOAD_MINIFIGURE': 'load_minifigure',
'LOAD_PART': 'load_part',
'LOAD_PART_COLORS': 'load_part_colors',
'LOAD_PEERON_PAGES': 'load_peeron_pages',
'LOAD_SET': 'load_set',
'MINIFIGURE_LOADED': 'minifigure_loaded',
'PART_COLORS_LOADED': 'part_colors_loaded',
'PART_LOADED': 'part_loaded',
'PROGRESS': 'progress',
'SET_LOADED': 'set_loaded',
}
@@ -231,6 +236,36 @@ class BrickSocket(object):
from .individual_minifigure import IndividualMinifigure
IndividualMinifigure().load(self, data)
@self.socket.on(MESSAGES['LOAD_PART'], namespace=self.namespace)
def load_part(data: dict[str, Any], /) -> None:
logger.debug('Socket: LOAD_PART={data} (from: {fr})'.format(
data=data,
fr=request.sid, # type: ignore
))
from .individual_part import IndividualPart
IndividualPart().add(self, data)
@self.socket.on(MESSAGES['LOAD_PART_COLORS'], namespace=self.namespace)
def load_part_colors(data: dict[str, Any], /) -> None:
logger.debug('Socket: LOAD_PART_COLORS={data} (from: {fr})'.format(
data=data,
fr=request.sid, # type: ignore
))
from .individual_part import IndividualPart
IndividualPart().load_colors(self, data)
@self.socket.on(MESSAGES['CREATE_LOT'], namespace=self.namespace)
@rebrickable_socket(self)
def create_lot(data: dict[str, Any], /) -> None:
logger.debug('Socket: CREATE_LOT (from: {fr})'.format(
fr=request.sid, # type: ignore
))
from .individual_part_lot import IndividualPartLot
IndividualPartLot().create(self, data)
# Update the progress auto-incrementing
def auto_progress(
self,

View File

@@ -0,0 +1,13 @@
-- Delete metadata first (foreign keys with CASCADE will handle this, but being explicit)
DELETE FROM "bricktracker_individual_part_owners"
WHERE "id" = '{{ id }}';
DELETE FROM "bricktracker_individual_part_tags"
WHERE "id" = '{{ id }}';
DELETE FROM "bricktracker_individual_part_statuses"
WHERE "id" = '{{ id }}';
-- Delete the individual part itself
DELETE FROM "bricktracker_individual_parts"
WHERE "id" = '{{ id }}';

View File

@@ -0,0 +1,27 @@
INSERT INTO "bricktracker_individual_parts" (
"id",
"part",
"color",
"quantity",
"missing",
"damaged",
"checked",
"description",
"storage",
"purchase_location",
"purchase_date",
"purchase_price"
) VALUES (
:id,
:part,
:color,
:quantity,
:missing,
:damaged,
:checked,
:description,
:storage,
:purchase_location,
:purchase_date,
:purchase_price
)

View File

@@ -0,0 +1,30 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
ORDER BY "bricktracker_individual_parts"."part", "bricktracker_individual_parts"."color"

View File

@@ -0,0 +1,31 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_parts"."color" = :color
ORDER BY "bricktracker_individual_parts"."part"

View File

@@ -0,0 +1,31 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_parts"."part" = :part
ORDER BY "bricktracker_individual_parts"."color"

View File

@@ -0,0 +1,32 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_parts"."part" = :part
AND "bricktracker_individual_parts"."color" = :color
ORDER BY "bricktracker_individual_parts"."id"

View File

@@ -0,0 +1,31 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_parts"."storage" = :storage
ORDER BY "bricktracker_individual_parts"."part", "bricktracker_individual_parts"."color"

View File

@@ -0,0 +1,32 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_parts"."missing" > 0
OR "bricktracker_individual_parts"."damaged" > 0
ORDER BY "bricktracker_individual_parts"."part", "bricktracker_individual_parts"."color"

View File

@@ -0,0 +1,31 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM :storage
ORDER BY "bricktracker_individual_parts"."part", "bricktracker_individual_parts"."color"

View File

@@ -0,0 +1,31 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_parts"."storage" IS NULL
ORDER BY "bricktracker_individual_parts"."part", "bricktracker_individual_parts"."color"

View File

@@ -0,0 +1,10 @@
INSERT INTO "bricktracker_individual_part_owners" (
"id",
"{{name}}"
) VALUES (
:id,
:state
)
ON CONFLICT("id")
DO UPDATE SET "{{name}}" = :state
WHERE "bricktracker_individual_part_owners"."id" IS NOT DISTINCT FROM :id

View File

@@ -0,0 +1,10 @@
INSERT INTO "bricktracker_individual_part_statuses" (
"id",
"{{name}}"
) VALUES (
:id,
:state
)
ON CONFLICT("id")
DO UPDATE SET "{{name}}" = :state
WHERE "bricktracker_individual_part_statuses"."id" IS NOT DISTINCT FROM :id

View File

@@ -0,0 +1,10 @@
INSERT INTO "bricktracker_individual_part_tags" (
"id",
"{{name}}"
) VALUES (
:id,
:state
)
ON CONFLICT("id")
DO UPDATE SET "{{name}}" = :state
WHERE "bricktracker_individual_part_tags"."id" IS NOT DISTINCT FROM :id

View File

@@ -0,0 +1,31 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"bricktracker_individual_parts"."lot_id",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_parts"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_parts"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_parts"."id" = :id

View File

@@ -0,0 +1,3 @@
UPDATE "bricktracker_individual_parts"
SET "{{ field }}" = :value
WHERE "id" = :id

View File

@@ -0,0 +1,3 @@
UPDATE "bricktracker_individual_parts"
SET "checked" = :checked
WHERE "id" = :id

View File

@@ -0,0 +1,3 @@
UPDATE "bricktracker_individual_parts"
SET "damaged" = :damaged
WHERE "id" = :id

View File

@@ -0,0 +1,3 @@
UPDATE "bricktracker_individual_parts"
SET "missing" = :missing
WHERE "id" = :id

View File

@@ -0,0 +1,9 @@
UPDATE "bricktracker_individual_parts"
SET
"quantity" = :quantity,
"description" = :description,
"storage" = :storage,
"purchase_location" = :purchase_location,
"purchase_date" = :purchase_date,
"purchase_price" = :purchase_price
WHERE "id" = :id

View File

@@ -0,0 +1,15 @@
-- Delete all individual parts associated with this lot
DELETE FROM "bricktracker_individual_parts"
WHERE "lot_id" = :id;
-- Delete lot owners
DELETE FROM "bricktracker_individual_part_lot_owners"
WHERE "id" = :id;
-- Delete lot tags
DELETE FROM "bricktracker_individual_part_lot_tags"
WHERE "id" = :id;
-- Delete the lot itself
DELETE FROM "bricktracker_individual_part_lots"
WHERE "id" = :id;

View File

@@ -0,0 +1,19 @@
INSERT INTO "bricktracker_individual_part_lots" (
"id",
"name",
"description",
"created_date",
"storage",
"purchase_location",
"purchase_date",
"purchase_price"
) VALUES (
:id,
:name,
:description,
:created_date,
:storage,
:purchase_location,
:purchase_date,
:purchase_price
)

View File

@@ -0,0 +1,21 @@
SELECT
"bricktracker_individual_part_lots"."id",
"bricktracker_individual_part_lots"."name",
"bricktracker_individual_part_lots"."description",
"bricktracker_individual_part_lots"."created_date",
"bricktracker_individual_part_lots"."storage",
"bricktracker_individual_part_lots"."purchase_location",
"bricktracker_individual_part_lots"."purchase_date",
"bricktracker_individual_part_lots"."purchase_price",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name",
COUNT("bricktracker_individual_parts"."id") AS "part_count"
FROM "bricktracker_individual_part_lots"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_part_lots"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_part_lots"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
LEFT JOIN "bricktracker_individual_parts"
ON "bricktracker_individual_part_lots"."id" = "bricktracker_individual_parts"."lot_id"
GROUP BY "bricktracker_individual_part_lots"."id"
ORDER BY "bricktracker_individual_part_lots"."created_date" DESC

View File

@@ -0,0 +1,26 @@
SELECT
"bricktracker_individual_parts"."id",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
"bricktracker_individual_parts"."quantity",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
"bricktracker_individual_parts"."description",
"bricktracker_individual_parts"."storage",
"bricktracker_individual_parts"."purchase_location",
"bricktracker_individual_parts"."purchase_date",
"bricktracker_individual_parts"."purchase_price",
"bricktracker_individual_parts"."lot_id",
"rebrickable_parts"."name",
"rebrickable_parts"."color_name",
"rebrickable_parts"."color_rgb",
"rebrickable_parts"."color_transparent",
"rebrickable_parts"."image",
"rebrickable_parts"."url"
FROM "bricktracker_individual_parts"
INNER JOIN "rebrickable_parts"
ON "bricktracker_individual_parts"."part" = "rebrickable_parts"."part"
AND "bricktracker_individual_parts"."color" = "rebrickable_parts"."color_id"
WHERE "bricktracker_individual_parts"."lot_id" = :lot_id
ORDER BY "rebrickable_parts"."name" ASC, "bricktracker_individual_parts"."color" ASC

View File

@@ -0,0 +1,17 @@
SELECT
"bricktracker_individual_part_lots"."id",
"bricktracker_individual_part_lots"."name",
"bricktracker_individual_part_lots"."description",
"bricktracker_individual_part_lots"."created_date",
"bricktracker_individual_part_lots"."storage",
"bricktracker_individual_part_lots"."purchase_location",
"bricktracker_individual_part_lots"."purchase_date",
"bricktracker_individual_part_lots"."purchase_price",
"bricktracker_metadata_storages"."name" AS "storage_name",
"bricktracker_metadata_purchase_locations"."name" AS "purchase_location_name"
FROM "bricktracker_individual_part_lots"
LEFT JOIN "bricktracker_metadata_storages"
ON "bricktracker_individual_part_lots"."storage" IS NOT DISTINCT FROM "bricktracker_metadata_storages"."id"
LEFT JOIN "bricktracker_metadata_purchase_locations"
ON "bricktracker_individual_part_lots"."purchase_location" IS NOT DISTINCT FROM "bricktracker_metadata_purchase_locations"."id"
WHERE "bricktracker_individual_part_lots"."id" = :id

View File

@@ -1,4 +1,4 @@
-- Migration 0020: Add individual minifigures and individual parts tables
-- description: Add individual minifigures and individual parts tables
-- Individual minifigures table - tracks individual minifigures not associated with sets
CREATE TABLE IF NOT EXISTS "bricktracker_individual_minifigures" (

View File

@@ -1,23 +1,15 @@
-- Migration 0021: Add existing owner/tag columns to individual minifigure and individual part metadata tables
-- description: Populate missing image_id values in rebrickable_parts from image URLs
-- Extract image_id from image URL for records with 'elements/' path
-- Note: The url_for_image() method now handles extraction on-the-fly for missing values,
-- so this migration only needs to handle the common case to improve performance
-- Add owner columns to individual minifigure owners table
ALTER TABLE "bricktracker_individual_minifigure_owners"
ADD COLUMN "owner_32479d0a_cd3c_43c6_aa16_b3f378915b13" BOOLEAN NOT NULL DEFAULT 0;
ALTER TABLE "bricktracker_individual_minifigure_owners"
ADD COLUMN "owner_2f07518d_40e1_4279_b0d0_aa339f195cbf" BOOLEAN NOT NULL DEFAULT 0;
-- Add tag columns to individual minifigure tags table
ALTER TABLE "bricktracker_individual_minifigure_tags"
ADD COLUMN "tag_b1b5c316_5caf_4b82_a085_ac4c7ab9b8db" BOOLEAN NOT NULL DEFAULT 0;
-- Add owner columns to individual part owners table
ALTER TABLE "bricktracker_individual_part_owners"
ADD COLUMN "owner_32479d0a_cd3c_43c6_aa16_b3f378915b13" BOOLEAN NOT NULL DEFAULT 0;
ALTER TABLE "bricktracker_individual_part_owners"
ADD COLUMN "owner_2f07518d_40e1_4279_b0d0_aa339f195cbf" BOOLEAN NOT NULL DEFAULT 0;
-- Add tag columns to individual part tags table
ALTER TABLE "bricktracker_individual_part_tags"
ADD COLUMN "tag_b1b5c316_5caf_4b82_a085_ac4c7ab9b8db" BOOLEAN NOT NULL DEFAULT 0;
-- For images with 'elements/' in the path, extract the element ID (e.g., 300126 from .../elements/300126.jpg)
UPDATE "rebrickable_parts"
SET "image_id" = SUBSTR(
"image",
INSTR("image", 'elements/') + 9,
INSTR(SUBSTR("image", INSTR("image", 'elements/') + 9), '.') - 1
)
WHERE "image" IS NOT NULL
AND ("image_id" IS NULL OR "image_id" = '')
AND "image" LIKE '%elements/%';

View File

@@ -0,0 +1,16 @@
-- description: Create rebrickable_colors translation table for BrickLink color ID mapping
-- This table caches color information from Rebrickable API to avoid repeated API calls
-- and provides mapping between Rebrickable and BrickLink color IDs
CREATE TABLE IF NOT EXISTS "rebrickable_colors" (
"color_id" INTEGER PRIMARY KEY,
"name" TEXT NOT NULL,
"rgb" TEXT,
"is_trans" BOOLEAN,
"bricklink_color_id" INTEGER,
"bricklink_color_name" TEXT
);
-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS "idx_rebrickable_colors_bricklink"
ON "rebrickable_colors"("bricklink_color_id");

View File

@@ -0,0 +1,54 @@
-- description: Add individual part lots system for bulk/cart adding of parts
BEGIN TRANSACTION;
-- Create individual part lots table
CREATE TABLE IF NOT EXISTS "bricktracker_individual_part_lots" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT,
"description" TEXT,
"created_date" REAL NOT NULL,
"storage" TEXT,
"purchase_location" TEXT,
"purchase_date" REAL,
"purchase_price" REAL,
FOREIGN KEY("storage") REFERENCES "bricktracker_metadata_storages"("id") ON DELETE SET NULL,
FOREIGN KEY("purchase_location") REFERENCES "bricktracker_metadata_purchase_locations"("id") ON DELETE SET NULL
);
-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS "idx_individual_part_lots_created_date"
ON "bricktracker_individual_part_lots"("created_date");
-- Add missing/damaged/checked fields to individual parts table
ALTER TABLE "bricktracker_individual_parts"
ADD COLUMN "missing" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "bricktracker_individual_parts"
ADD COLUMN "damaged" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "bricktracker_individual_parts"
ADD COLUMN "checked" BOOLEAN NOT NULL DEFAULT 0;
-- Add lot_id column to individual parts table
ALTER TABLE "bricktracker_individual_parts"
ADD COLUMN "lot_id" TEXT;
CREATE INDEX IF NOT EXISTS "idx_individual_parts_lot_id"
ON "bricktracker_individual_parts"("lot_id");
-- Create lot owners junction table
CREATE TABLE IF NOT EXISTS "bricktracker_individual_part_lot_owners" (
"id" TEXT NOT NULL,
PRIMARY KEY("id"),
FOREIGN KEY("id") REFERENCES "bricktracker_individual_part_lots"("id") ON DELETE CASCADE
);
-- Create lot tags junction table
CREATE TABLE IF NOT EXISTS "bricktracker_individual_part_lot_tags" (
"id" TEXT NOT NULL,
PRIMARY KEY("id"),
FOREIGN KEY("id") REFERENCES "bricktracker_individual_part_lots"("id") ON DELETE CASCADE
);
COMMIT;

View File

@@ -0,0 +1,13 @@
-- description: Add missing indexes for individual part lots optimization
BEGIN TRANSACTION;
-- Add storage index for lots table (for filtering by storage)
CREATE INDEX IF NOT EXISTS "idx_individual_part_lots_storage"
ON "bricktracker_individual_part_lots"("storage");
-- Add purchase location index for lots table (for filtering by purchase location)
CREATE INDEX IF NOT EXISTS "idx_individual_part_lots_purchase_location"
ON "bricktracker_individual_part_lots"("purchase_location");
COMMIT;

View File

@@ -68,10 +68,27 @@ FROM (
"bricktracker_individual_minifigure_parts"."missing",
"bricktracker_individual_minifigure_parts"."damaged",
"bricktracker_individual_minifigure_parts"."checked",
'individual' AS "source_type"
'individual_minifigure' AS "source_type"
FROM "bricktracker_individual_minifigure_parts"
INNER JOIN "bricktracker_individual_minifigures"
ON "bricktracker_individual_minifigure_parts"."id" = "bricktracker_individual_minifigures"."id"
UNION ALL
-- Individual/standalone parts (not from any set or minifigure)
SELECT
"bricktracker_individual_parts"."id",
NULL AS "figure",
"bricktracker_individual_parts"."part",
"bricktracker_individual_parts"."color",
0 AS "spare",
"bricktracker_individual_parts"."quantity",
NULL AS "element",
"bricktracker_individual_parts"."missing",
"bricktracker_individual_parts"."damaged",
"bricktracker_individual_parts"."checked",
'individual_part' AS "source_type"
FROM "bricktracker_individual_parts"
) AS "combined"
INNER JOIN "rebrickable_parts"

View File

@@ -4,7 +4,8 @@
{% if owner_id and owner_id != 'all' %}
SUM(CASE
WHEN "combined"."source_type" = 'set' AND "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."missing"
WHEN "combined"."source_type" = 'individual' AND "bricktracker_individual_minifigure_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."missing"
WHEN "combined"."source_type" = 'individual_minifigure' AND "bricktracker_individual_minifigure_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."missing"
WHEN "combined"."source_type" = 'individual_part' AND "bricktracker_individual_part_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."missing"
ELSE 0
END) AS "total_missing",
{% else %}
@@ -16,7 +17,8 @@ SUM("combined"."missing") AS "total_missing",
{% if owner_id and owner_id != 'all' %}
SUM(CASE
WHEN "combined"."source_type" = 'set' AND "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."damaged"
WHEN "combined"."source_type" = 'individual' AND "bricktracker_individual_minifigure_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."damaged"
WHEN "combined"."source_type" = 'individual_minifigure' AND "bricktracker_individual_minifigure_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."damaged"
WHEN "combined"."source_type" = 'individual_part' AND "bricktracker_individual_part_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."damaged"
ELSE 0
END) AS "total_damaged",
{% else %}
@@ -28,7 +30,8 @@ SUM("combined"."damaged") AS "total_damaged",
{% if owner_id and owner_id != 'all' %}
SUM(CASE
WHEN "combined"."source_type" = 'set' AND "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."quantity" * IFNULL("bricktracker_minifigures"."quantity", 1)
WHEN "combined"."source_type" = 'individual' AND "bricktracker_individual_minifigure_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."quantity"
WHEN "combined"."source_type" = 'individual_minifigure' AND "bricktracker_individual_minifigure_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."quantity"
WHEN "combined"."source_type" = 'individual_part' AND "bricktracker_individual_part_owners"."owner_{{ owner_id }}" = 1 THEN "combined"."quantity"
ELSE 0
END) AS "total_quantity",
{% else %}
@@ -54,13 +57,13 @@ COUNT(DISTINCT CASE WHEN "combined"."source_type" = 'set' THEN "combined"."id" E
{% if owner_id and owner_id != 'all' %}
SUM(CASE
WHEN "combined"."source_type" = 'set' AND "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN IFNULL("bricktracker_minifigures"."quantity", 0)
WHEN "combined"."source_type" = 'individual' AND "bricktracker_individual_minifigure_owners"."owner_{{ owner_id }}" = 1 THEN 1
WHEN "combined"."source_type" = 'individual_minifigure' AND "bricktracker_individual_minifigure_owners"."owner_{{ owner_id }}" = 1 THEN 1
ELSE 0
END) AS "total_minifigures"
{% else %}
SUM(CASE
WHEN "combined"."source_type" = 'set' THEN IFNULL("bricktracker_minifigures"."quantity", 0)
WHEN "combined"."source_type" = 'individual' THEN 1
WHEN "combined"."source_type" = 'individual_minifigure' THEN 1
ELSE 0
END) AS "total_minifigures"
{% endif %}
@@ -83,21 +86,31 @@ ON "combined"."source_type" = 'set'
AND "combined"."id" IS NOT DISTINCT FROM "bricktracker_minifigures"."id"
AND "combined"."figure" IS NOT DISTINCT FROM "bricktracker_minifigures"."figure"
-- Left join with individual minifigures (for individual parts)
-- Left join with individual minifigures (for individual minifigure parts)
LEFT JOIN "bricktracker_individual_minifigures"
ON "combined"."source_type" = 'individual'
ON "combined"."source_type" = 'individual_minifigure'
AND "combined"."id" IS NOT DISTINCT FROM "bricktracker_individual_minifigures"."id"
-- Left join with individual minifigure owners (using dynamic columns)
LEFT JOIN "bricktracker_individual_minifigure_owners"
ON "combined"."source_type" = 'individual'
ON "combined"."source_type" = 'individual_minifigure'
AND "bricktracker_individual_minifigures"."id" IS NOT DISTINCT FROM "bricktracker_individual_minifigure_owners"."id"
-- Left join with individual parts (for standalone parts)
LEFT JOIN "bricktracker_individual_parts"
ON "combined"."source_type" = 'individual_part'
AND "combined"."id" IS NOT DISTINCT FROM "bricktracker_individual_parts"."id"
-- Left join with individual part owners (using dynamic columns)
LEFT JOIN "bricktracker_individual_part_owners"
ON "combined"."source_type" = 'individual_part'
AND "bricktracker_individual_parts"."id" IS NOT DISTINCT FROM "bricktracker_individual_part_owners"."id"
{% endblock %}
{% block where %}
{% set conditions = [] %}
{% if owner_id and owner_id != 'all' %}
{% set owner_condition = '(("combined"."source_type" = \'set\' AND "bricktracker_set_owners"."owner_' ~ owner_id ~ '" = 1) OR ("combined"."source_type" = \'individual\' AND "bricktracker_individual_minifigure_owners"."owner_' ~ owner_id ~ '" = 1))' %}
{% set owner_condition = '(("combined"."source_type" = \'set\' AND "bricktracker_set_owners"."owner_' ~ owner_id ~ '" = 1) OR ("combined"."source_type" = \'individual_minifigure\' AND "bricktracker_individual_minifigure_owners"."owner_' ~ owner_id ~ '" = 1) OR ("combined"."source_type" = \'individual_part\' AND "bricktracker_individual_part_owners"."owner_' ~ owner_id ~ '" = 1))' %}
{% set _ = conditions.append(owner_condition) %}
{% endif %}
{% if color_id and color_id != 'all' %}

View File

@@ -7,6 +7,18 @@ DROP COLUMN "owner_{{ id }}";
ALTER TABLE "bricktracker_wish_owners"
DROP COLUMN "owner_{{ id }}";
-- Also drop from individual minifigures
ALTER TABLE "bricktracker_individual_minifigure_owners"
DROP COLUMN "owner_{{ id }}";
-- Also drop from individual parts
ALTER TABLE "bricktracker_individual_part_owners"
DROP COLUMN "owner_{{ id }}";
-- Also drop from individual part lots
ALTER TABLE "bricktracker_individual_part_lot_owners"
DROP COLUMN "owner_{{ id }}";
DELETE FROM "bricktracker_metadata_owners"
WHERE "bricktracker_metadata_owners"."id" IS NOT DISTINCT FROM '{{ id }}';

View File

@@ -15,6 +15,10 @@ ADD COLUMN "owner_{{ id }}" BOOLEAN NOT NULL DEFAULT 0;
ALTER TABLE "bricktracker_individual_part_owners"
ADD COLUMN "owner_{{ id }}" BOOLEAN NOT NULL DEFAULT 0;
-- Also inject into individual part lots
ALTER TABLE "bricktracker_individual_part_lot_owners"
ADD COLUMN "owner_{{ id }}" BOOLEAN NOT NULL DEFAULT 0;
INSERT INTO "bricktracker_metadata_owners" (
"id",
"name"

View File

@@ -2,7 +2,8 @@
{% block total_sets %}
IFNULL(COUNT(DISTINCT "bricktracker_sets"."id"), 0) AS "total_sets",
IFNULL(COUNT(DISTINCT "bricktracker_individual_minifigures"."id"), 0) AS "total_individual_minifigures"
IFNULL(COUNT(DISTINCT "bricktracker_individual_minifigures"."id"), 0) AS "total_individual_minifigures",
IFNULL(COUNT(DISTINCT "bricktracker_individual_parts"."id"), 0) AS "total_individual_parts"
{% endblock %}
{% block join %}
@@ -11,6 +12,9 @@ ON "bricktracker_metadata_storages"."id" IS NOT DISTINCT FROM "bricktracker_sets
LEFT JOIN "bricktracker_individual_minifigures"
ON "bricktracker_metadata_storages"."id" IS NOT DISTINCT FROM "bricktracker_individual_minifigures"."storage"
LEFT JOIN "bricktracker_individual_parts"
ON "bricktracker_metadata_storages"."id" IS NOT DISTINCT FROM "bricktracker_individual_parts"."storage"
{% endblock %}
{% block group %}

View File

@@ -3,6 +3,18 @@ BEGIN TRANSACTION;
ALTER TABLE "bricktracker_set_tags"
DROP COLUMN "tag_{{ id }}";
-- Also drop from individual minifigures
ALTER TABLE "bricktracker_individual_minifigure_tags"
DROP COLUMN "tag_{{ id }}";
-- Also drop from individual parts
ALTER TABLE "bricktracker_individual_part_tags"
DROP COLUMN "tag_{{ id }}";
-- Also drop from individual part lots
ALTER TABLE "bricktracker_individual_part_lot_tags"
DROP COLUMN "tag_{{ id }}";
DELETE FROM "bricktracker_metadata_tags"
WHERE "bricktracker_metadata_tags"."id" IS NOT DISTINCT FROM '{{ id }}';

View File

@@ -11,6 +11,10 @@ ADD COLUMN "tag_{{ id }}" BOOLEAN NOT NULL DEFAULT 0;
ALTER TABLE "bricktracker_individual_part_tags"
ADD COLUMN "tag_{{ id }}" BOOLEAN NOT NULL DEFAULT 0;
-- Also inject into individual part lots
ALTER TABLE "bricktracker_individual_part_lot_tags"
ADD COLUMN "tag_{{ id }}" BOOLEAN NOT NULL DEFAULT 0;
INSERT INTO "bricktracker_metadata_tags" (
"id",
"name"

View File

@@ -1,4 +1,4 @@
from typing import Final
__version__: Final[str] = '1.3.0'
__database_version__: Final[int] = 21
__database_version__: Final[int] = 24

View File

@@ -40,3 +40,19 @@ def bulk() -> str:
bulk=True,
**set_metadata_lists()
)
# Add individual parts
@add_page.route('/parts', methods=['GET'])
@login_required
@exception_handler(__file__)
def parts() -> str:
BrickConfigurationList.error_unless_is_set('REBRICKABLE_API_KEY')
return render_template(
'add_parts.html',
path=current_app.config['SOCKET_PATH'],
namespace=current_app.config['SOCKET_NAMESPACE'],
messages=MESSAGES,
**set_metadata_lists()
)

View File

@@ -0,0 +1,332 @@
import logging
from flask import Blueprint, jsonify, redirect, render_template, request, url_for, Response
from flask_login import login_required
from .exceptions import exception_handler
from ..individual_part import IndividualPart
from ..individual_part_list import IndividualPartList
from ..individual_part_lot import IndividualPartLot
from ..individual_part_lot_list import IndividualPartLotList
from ..set_list import set_metadata_lists
from ..set_owner_list import BrickSetOwnerList
from ..set_tag_list import BrickSetTagList
from ..set_storage_list import BrickSetStorageList
from ..set_purchase_location_list import BrickSetPurchaseLocationList
from ..sql import BrickSQL
logger = logging.getLogger(__name__)
individual_part_page = Blueprint('individual_part', __name__, url_prefix='/individual-parts')
# List all individual parts
@individual_part_page.route('/')
@exception_handler(__file__)
def list_all() -> str:
parts = IndividualPartList().all()
return render_template(
'individual_parts.html',
parts=parts,
**set_metadata_lists(as_class=True)
)
# Individual part instance details/edit
@individual_part_page.route('/<id>')
@exception_handler(__file__)
def details(*, id: str) -> str:
item = IndividualPart().select_by_id(id)
# Check if this part belongs to a lot
lot = None
if hasattr(item.fields, 'lot_id') and item.fields.lot_id:
try:
lot = IndividualPartLot().select_by_id(item.fields.lot_id)
except Exception as e:
logger.warning(f'Could not load lot {item.fields.lot_id} for part {id}: {e}')
return render_template(
'individual_part/details.html',
item=item,
lot=lot,
**set_metadata_lists(as_class=True)
)
# Update individual part instance
@individual_part_page.route('/<id>/update', methods=['POST'])
@exception_handler(__file__)
def update(*, id: str):
item = IndividualPart().select_by_id(id)
# Update basic fields
item.fields.quantity = int(request.form.get('quantity', 1))
item.fields.description = request.form.get('description', '')
item.fields.storage = request.form.get('storage') or None
item.fields.purchase_location = request.form.get('purchase_location') or None
item.fields.purchase_date = request.form.get('purchase_date') or None
item.fields.purchase_price = request.form.get('purchase_price') or None
# Update the individual part
BrickSQL().execute(
'individual_part/update_full',
parameters={
'id': item.fields.id,
'quantity': item.fields.quantity,
'description': item.fields.description,
'storage': item.fields.storage,
'purchase_location': item.fields.purchase_location,
'purchase_date': item.fields.purchase_date,
'purchase_price': item.fields.purchase_price,
},
commit=False,
)
# Update owners
owners = request.form.getlist('owners')
for owner in BrickSetOwnerList.list():
owner.update_individual_part_state(item, state=(owner.fields.id in owners))
# Update tags
tags = request.form.getlist('tags')
for tag in BrickSetTagList.list():
tag.update_individual_part_state(item, state=(tag.fields.id in tags))
BrickSQL().commit()
return redirect(url_for('individual_part.details', id=id))
# Update quantity
@individual_part_page.route('/<id>/update/quantity', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_quantity(*, id: str):
item = IndividualPart().select_by_id(id)
value = request.json.get('value', '1')
# Handle empty string or 0 - don't allow it
if value == '' or value == '0' or value == 0:
return jsonify({'success': False, 'error': 'Quantity cannot be 0. Use the delete button in the menu to remove this part from the lot.'})
try:
quantity = int(value)
if quantity < 1:
return jsonify({'success': False, 'error': 'Quantity must be at least 1'})
except ValueError:
return jsonify({'success': False, 'error': 'Invalid quantity value'})
item.update_field('quantity', quantity)
return jsonify({'success': True})
# Update description
@individual_part_page.route('/<id>/update/description', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_description(*, id: str):
item = IndividualPart().select_by_id(id)
description = request.json.get('value', '')
item.update_field('description', description)
return jsonify({'success': True})
# Update owner
@individual_part_page.route('/<id>/update/owner/<metadata_id>', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_owner(*, id: str, metadata_id: str):
item = IndividualPart().select_by_id(id)
owner = BrickSetOwnerList.get(metadata_id)
owner.update_individual_part_state(item, json=request.json)
return jsonify({'success': True})
# Update tag
@individual_part_page.route('/<id>/update/tag/<metadata_id>', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_tag(*, id: str, metadata_id: str):
item = IndividualPart().select_by_id(id)
tag = BrickSetTagList.get(metadata_id)
tag.update_individual_part_state(item, json=request.json)
return jsonify({'success': True})
# Update status
@individual_part_page.route('/<id>/update/status/<metadata_id>', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_status(*, id: str, metadata_id: str):
item = IndividualPart().select_by_id(id)
from ..set_status_list import BrickSetStatusList
status = BrickSetStatusList.get(metadata_id)
status.update_individual_part_state(item, json=request.json)
return jsonify({'success': True})
# Update storage
@individual_part_page.route('/<id>/update/storage', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_storage(*, id: str):
item = IndividualPart().select_by_id(id)
storage_id = request.json.get('value')
item.update_field('storage', storage_id if storage_id else None)
return jsonify({'success': True})
# Update purchase location
@individual_part_page.route('/<id>/update/purchase_location', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_purchase_location(*, id: str):
item = IndividualPart().select_by_id(id)
location_id = request.json.get('value')
item.update_field('purchase_location', location_id if location_id else None)
return jsonify({'success': True})
# Update missing count
@individual_part_page.route('/<id>/update/missing', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_missing(*, id: str):
item = IndividualPart().select_by_id(id)
amount = item.update_problem('missing', request.json)
logger.info(f'Individual part {item.fields.part} (color: {item.fields.color}, id: {item.fields.id}): updated missing count to {amount}')
return jsonify({'missing': amount})
# Update damaged count
@individual_part_page.route('/<id>/update/damaged', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_damaged(*, id: str):
item = IndividualPart().select_by_id(id)
amount = item.update_problem('damaged', request.json)
logger.info(f'Individual part {item.fields.part} (color: {item.fields.color}, id: {item.fields.id}): updated damaged count to {amount}')
return jsonify({'damaged': amount})
# Update checked state
@individual_part_page.route('/<id>/update/checked', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_checked(*, id: str):
item = IndividualPart().select_by_id(id)
checked = item.update_checked(request.json)
logger.info(f'Individual part {item.fields.part} (color: {item.fields.color}, id: {item.fields.id}): updated checked state to {checked}')
return jsonify({'checked': checked})
# Delete individual part instance
@individual_part_page.route('/<id>/delete', methods=['POST'])
@login_required
@exception_handler(__file__)
def delete_part(*, id: str):
item = IndividualPart().select_by_id(id)
lot_id = item.fields.lot_id if hasattr(item.fields, 'lot_id') else None
item.delete()
logger.info(f'Deleted individual part {item.fields.part} (color: {item.fields.color}, id: {id})')
# If part was in a lot, redirect back to the lot
if lot_id:
return redirect(url_for('individual_part.lot_details', lot_id=lot_id))
else:
return redirect(url_for('individual_part.list_all'))
# List all lots
@individual_part_page.route('/lot/')
@exception_handler(__file__)
def list_lots() -> str:
"""List all individual part lots"""
# Use optimized query that includes part_count
lots = IndividualPartLotList().all()
return render_template(
'individual_part/lots.html',
lots=lots,
**set_metadata_lists(as_class=True)
)
# Lot detail page
@individual_part_page.route('/lot/<lot_id>')
@exception_handler(__file__)
def lot_details(*, lot_id: str) -> str:
"""Display details for an individual part lot (behaves like a set)"""
lot = IndividualPartLot().select_by_id(lot_id)
return render_template(
'individual_part/lot_details.html',
item=lot, # Pass as 'item' like sets do
solo=True,
**set_metadata_lists(as_class=True)
)
# Update lot name
@individual_part_page.route('/lot/<lot_id>/update/name', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_lot_name(*, lot_id: str):
lot = IndividualPartLot().select_by_id(lot_id)
name = request.json.get('value', '')
from ..sql import BrickSQL
sql = BrickSQL()
sql.cursor.execute(
'UPDATE "bricktracker_individual_part_lots" SET "name" = ? WHERE "id" = ?',
(name, lot_id)
)
sql.commit()
logger.info(f'Updated lot {lot_id} name to: {name}')
return jsonify({'success': True})
# Update lot description
@individual_part_page.route('/lot/<lot_id>/update/description', methods=['POST'])
@login_required
@exception_handler(__file__)
def update_lot_description(*, lot_id: str):
lot = IndividualPartLot().select_by_id(lot_id)
description = request.json.get('value', '')
from ..sql import BrickSQL
sql = BrickSQL()
sql.cursor.execute(
'UPDATE "bricktracker_individual_part_lots" SET "description" = ? WHERE "id" = ?',
(description, lot_id)
)
sql.commit()
logger.info(f'Updated lot {lot_id} description')
return jsonify({'success': True})
# Delete lot
@individual_part_page.route('/lot/<lot_id>/delete', methods=['POST'])
@login_required
@exception_handler(__file__)
def delete_lot(*, lot_id: str):
lot = IndividualPartLot().select_by_id(lot_id)
lot.delete()
logger.info(f'Deleted individual part lot {lot_id}')
return redirect(url_for('individual_part.list_lots'))

View File

@@ -1,6 +1,7 @@
from flask import Blueprint, render_template, request
from flask import Blueprint, render_template, request, current_app
from .exceptions import exception_handler
from ..individual_part_list import IndividualPartList
from ..minifigure_list import BrickMinifigureList
from ..pagination_helper import get_pagination_config, build_pagination_context, get_request_params
from ..part import BrickPart
@@ -137,6 +138,11 @@ def problem() -> str:
def details(*, part: str, color: int) -> str:
brickpart = BrickPart().select_generic(part, color)
# Get individual parts if not disabled
individual_parts = None
if not current_app.config.get('DISABLE_INDIVIDUAL_PARTS', False):
individual_parts = IndividualPartList().by_part_and_color(part, color)
return render_template(
'part.html',
item=brickpart,
@@ -166,5 +172,6 @@ def details(*, part: str, color: int) -> str:
),
different_color=BrickPartList().with_different_color(brickpart),
similar_prints=BrickPartList().from_print(brickpart),
individual_parts=individual_parts,
**set_metadata_lists(as_class=True)
)

View File

@@ -2,6 +2,7 @@ from flask import Blueprint, render_template
from .exceptions import exception_handler
from ..individual_minifigure_list import IndividualMinifigureList
from ..individual_part_list import IndividualPartList
from ..set_list import BrickSetList, set_metadata_lists
from ..set_storage import BrickSetStorage
from ..set_storage_list import BrickSetStorageList
@@ -27,11 +28,17 @@ def list() -> str:
sql.cursor.execute(minifigs_no_storage_query)
minifigs_no_storage = sql.cursor.fetchone()[0]
# Count individual parts with no storage
parts_no_storage_query = 'SELECT COUNT(*) FROM "bricktracker_individual_parts" WHERE "storage" IS NULL'
sql.cursor.execute(parts_no_storage_query)
parts_no_storage = sql.cursor.fetchone()[0]
return render_template(
'storages.html',
table_collection=BrickSetStorageList.all(),
sets_no_storage=sets_no_storage,
minifigs_no_storage=minifigs_no_storage,
parts_no_storage=parts_no_storage,
)
@@ -46,15 +53,17 @@ def no_storage_details() -> str:
no_storage.fields.id = None
no_storage.fields.name = 'Not in a storage location'
# Get sets and individual minifigures with no storage
# Get sets, individual minifigures, and individual parts with no storage
sets = BrickSetList().without_storage()
individual_minifigures = IndividualMinifigureList().without_storage()
individual_parts = IndividualPartList().without_storage()
return render_template(
'storage.html',
item=no_storage,
sets=sets,
individual_minifigures=individual_minifigures,
individual_parts=individual_parts,
**set_metadata_lists(as_class=True)
)
@@ -70,5 +79,6 @@ def details(*, id: str) -> str:
item=storage,
sets=BrickSetList().using_storage(storage),
individual_minifigures=IndividualMinifigureList().using_storage(storage),
individual_parts=IndividualPartList().using_storage(storage),
**set_metadata_lists(as_class=True)
)

View File

@@ -12,6 +12,12 @@
<p class="mb-0">You can import multiple sets at once with <a href="{{ url_for('add.bulk') }}" class="btn btn-primary"><i class="ri-function-add-line"></i> Bulk add</a>.</p>
</div>
{% endif %}
{% if not bulk and not config['DISABLE_INDIVIDUAL_PARTS'] %}
<div class="alert alert-info" role="alert">
<h4 class="alert-heading">Adding individual parts?</h4>
<p class="mb-0">You can add standalone parts (not from a set) with <a href="{{ url_for('add.parts') }}" class="btn btn-info"><i class="ri-hammer-line"></i> Add parts</a>.</p>
</div>
{% endif %}
<div class="row">
<div class="col-12">
<div class="card mb-3">

675
templates/add_parts.html Normal file
View File

@@ -0,0 +1,675 @@
{% import 'macro/accordion.html' as accordion %}
{% extends 'base.html' %}
{% block title %} - Add individual parts{% endblock %}
{% block main %}
<div class="container">
<div class="row">
<div class="col-12">
<div class="card mb-3">
<div class="card-header">
<h5 class="mb-0"><i class="ri-hammer-line"></i> Add individual parts</h5>
</div>
<div class="card-body">
<div id="add-part-fail" class="alert alert-danger d-none" role="alert"></div>
<div id="add-part-complete" class="alert alert-success d-none" role="alert"></div>
<div class="mb-3">
<label for="add-part-input" class="form-label">Part number</label>
<input type="text" class="form-control" id="add-part-input" placeholder="3001" required>
<div class="form-text">Enter the Rebrickable part number (e.g., 3001, 3622, etc.)</div>
</div>
<div class="form-check mb-3">
<input type="checkbox" class="form-check-input" id="add-part-lot-mode">
<label class="form-check-label" for="add-part-lot-mode">
<strong>Lot/Bulk Mode</strong> - Add multiple parts to a cart before saving
</label>
<div class="form-text">When enabled, parts are added to a cart and saved together as a lot</div>
</div>
<!-- Cart section (only visible in lot mode) -->
<div id="add-part-cart-section" class="d-none mb-3">
<h6 class="border-bottom">
<i class="ri-shopping-cart-line"></i> Cart
<span class="badge bg-primary" id="add-part-cart-count">0</span>
</h6>
<div id="add-part-cart-items" class="mb-2">
<!-- Cart items will be inserted here -->
</div>
<div class="d-grid gap-2">
<button id="add-part-complete-lot" type="button" class="btn btn-success" disabled>
<i class="ri-check-line"></i> Complete Lot & Add All Parts
</button>
<button id="add-part-clear-cart" type="button" class="btn btn-outline-danger btn-sm">
<i class="ri-delete-bin-line"></i> Clear Cart
</button>
</div>
</div>
<hr>
<div class="mb-3">
<p>
Progress <span id="add-part-count"></span>
<span id="add-part-spinner" class="d-none">
<span class="spinner-border spinner-border-sm" aria-hidden="true"></span>
<span class="visually-hidden" role="status">Loading...</span>
</span>
</p>
<div id="add-part-progress" class="progress" role="progressbar" aria-label="Add part progress" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
<div id="add-part-progress-bar" class="progress-bar" style="width: 0%"></div>
</div>
<p id="add-part-progress-message" class="text-center d-none"></p>
</div>
<!-- Color selection section (hidden until part is loaded) -->
<div id="add-part-colors-section" class="d-none">
<h6 class="border-bottom mt-3 mb-3">Select Color</h6>
<div id="add-part-colors-grid" class="row row-cols-2 row-cols-md-3 row-cols-lg-4 g-3">
<!-- Color cards will be inserted here dynamically -->
</div>
</div>
<!-- Metadata section (initially hidden, shown after selecting part) -->
<div id="add-part-metadata-section" class="d-none">
<h6 class="border-bottom mt-3">Metadata</h6>
<div class="accordion accordion" id="metadata">
{% if not (brickset_owners | length) and not (brickset_purchase_locations | length) and not (brickset_storages | length) and not (brickset_tags | length) %}
<div class="alert alert-warning" role="alert">
You have no metadata configured.
You can add entries in the <a href="{{ url_for('admin.admin', open_metadata=true) }}\" class="btn btn-warning" role="button"><i class="ri-profile-line"></i> Set metadata management</a> section of the Admin panel.
</div>
{% else %}
{% if brickset_owners | length %}
{{ accordion.header('Owners', 'owners', 'metadata', icon='user-line') }}
<div id="add-part-owners">
{% for owner in brickset_owners %}
{% with id=owner.as_dataset() %}
<div class="form-check">
<input class="form-check-input" type="checkbox" value="{{ owner.fields.id }}" id="part-{{ id }}" autocomplete="off">
<label class="form-check-label" for="part-{{ id }}">{{ owner.fields.name }}</label>
</div>
{% endwith %}
{% endfor %}
</div>
{{ accordion.footer() }}
{% endif %}
{% if brickset_purchase_locations | length %}
{{ accordion.header('Purchase location', 'purchase-location', 'metadata', icon='building-line') }}
<label class="visually-hidden" for="add-part-purchase-location">Purchase location</label>
<div class="input-group">
<select id="add-part-purchase-location" class="form-select" autocomplete="off">
<option value="" selected><i>None</i></option>
{% for purchase_location in brickset_purchase_locations %}
<option value="{{ purchase_location.fields.id }}">{{ purchase_location.fields.name }}</option>
{% endfor %}
</select>
</div>
{{ accordion.footer() }}
{% endif %}
{% if brickset_storages | length %}
{{ accordion.header('Storage', 'storage', 'metadata', icon='archive-line') }}
<label class="visually-hidden" for="add-part-storage">Storage</label>
<div class="input-group">
<select id="add-part-storage" class="form-select" autocomplete="off">
<option value="" selected><i>None</i></option>
{% for storage in brickset_storages %}
<option value="{{ storage.fields.id }}">{{ storage.fields.name }}</option>
{% endfor %}
</select>
</div>
{{ accordion.footer() }}
{% endif %}
{% if brickset_tags | length %}
{{ accordion.header('Tags', 'tags', 'metadata', icon='price-tag-3-line') }}
<div id="add-part-tags">
{% for tag in brickset_tags %}
{% with id=tag.as_dataset() %}
<div class="form-check">
<input class="form-check-input" type="checkbox" value="{{ tag.fields.id }}" id="part-{{ id }}" autocomplete="off">
<label class="form-check-label" for="part-{{ id }}">{{ tag.fields.name }}</label>
</div>
{% endwith %}
{% endfor %}
</div>
{{ accordion.footer() }}
{% endif %}
{% if brickset_purchase_locations | length %}
{{ accordion.header('Purchase details', 'purchase', 'metadata', icon='money-dollar-circle-line') }}
<div class="mb-3">
<label for="add-part-purchase-date" class="form-label">Purchase date</label>
<input type="date" class="form-control" id="add-part-purchase-date">
</div>
<div class="mb-3">
<label for="add-part-purchase-price" class="form-label">Purchase price</label>
<input type="number" class="form-control" id="add-part-purchase-price" placeholder="0.00" step="0.01" min="0">
</div>
{{ accordion.footer() }}
{% endif %}
{% endif %}
</div>
</div>
</div>
<div class="card-footer text-end">
<span id="add-part-status-icon" class="me-1"></span><span id="add-part-status" class="me-1"></span>
<button id="add-part-lookup" type="button" class="btn btn-primary"><i class="ri-search-line"></i> Look up part</button>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
// Individual Part Color Selection Socket class
class BrickPartColorSocket extends BrickSocket {
constructor(id, path, namespace, messages) {
super(id, path, namespace, messages, false);
// Form elements
this.html_button = document.getElementById(id + '-lookup');
this.html_input = document.getElementById(`${id}-input`);
this.html_owners = document.getElementById(`${id}-owners`);
this.html_purchase_location = document.getElementById(`${id}-purchase-location`);
this.html_purchase_date = document.getElementById(`${id}-purchase-date`);
this.html_purchase_price = document.getElementById(`${id}-purchase-price`);
this.html_storage = document.getElementById(`${id}-storage`);
this.html_tags = document.getElementById(`${id}-tags`);
// Color selection elements
this.html_colors_section = document.getElementById(`${id}-colors-section`);
this.html_colors_grid = document.getElementById(`${id}-colors-grid`);
this.html_metadata_section = document.getElementById(`${id}-metadata-section`);
// Lot mode elements
this.html_lot_mode = document.getElementById(`${id}-lot-mode`);
this.html_cart_section = document.getElementById(`${id}-cart-section`);
this.html_cart_items = document.getElementById(`${id}-cart-items`);
this.html_cart_count = document.getElementById(`${id}-cart-count`);
this.html_complete_lot = document.getElementById(`${id}-complete-lot`);
this.html_clear_cart = document.getElementById(`${id}-clear-cart`);
// State
this.current_part = null;
this.current_part_name = null;
this.current_colors = null;
this.selected_color = null;
// Cart state
this.lot_mode = false;
this.cart = []; // Array of {part, part_name, color_id, color_name, quantity, color_info}
if (this.html_button) {
this.html_button.addEventListener("click", ((bricksocket) => (e) => {
bricksocket.lookup_part();
})(this));
}
if (this.html_input) {
this.html_input.addEventListener("keyup", ((bricksocket) => (e) => {
if (e.key === 'Enter') {
bricksocket.lookup_part();
}
})(this));
}
// Lot mode checkbox
if (this.html_lot_mode) {
this.html_lot_mode.addEventListener("change", ((bricksocket) => (e) => {
bricksocket.toggle_lot_mode(e.target.checked);
})(this));
}
// Clear cart button
if (this.html_clear_cart) {
this.html_clear_cart.addEventListener("click", ((bricksocket) => (e) => {
bricksocket.clear_cart();
})(this));
}
// Complete lot button
if (this.html_complete_lot) {
this.html_complete_lot.addEventListener("click", ((bricksocket) => (e) => {
bricksocket.complete_lot();
})(this));
}
// Setup the socket
this.setup();
}
// Clear form
clear() {
super.clear();
if (this.html_colors_section) {
this.html_colors_section.classList.add("d-none");
}
if (this.html_colors_grid) {
this.html_colors_grid.innerHTML = '';
}
if (this.html_metadata_section) {
this.html_metadata_section.classList.add("d-none");
}
this.current_part = null;
this.current_part_name = null;
this.current_colors = null;
this.selected_color = null;
}
// Look up part and load available colors
lookup_part() {
if (this.disabled) {
return;
}
const part = this.html_input.value.trim();
if (!part) {
this.fail({ message: 'Please enter a part number' });
return;
}
// Clear previous results
this.clear();
this.clear_status();
this.toggle(false);
this.spinner(true);
console.log('Emitting LOAD_PART_COLORS event with part:', part);
this.socket.emit(this.messages.LOAD_PART_COLORS, { part: part });
}
// Handle part colors loaded
part_colors_loaded(data) {
console.log('Received part colors:', data);
this.current_part = data.part;
this.current_part_name = data.part_name;
this.current_colors = data.colors;
// Show the colors section
if (this.html_colors_section) {
this.html_colors_section.classList.remove("d-none");
}
// Render color cards
if (this.html_colors_grid && this.current_colors) {
this.html_colors_grid.innerHTML = '';
this.current_colors.forEach((color) => {
const card = this.create_color_card(color);
this.html_colors_grid.appendChild(card);
});
}
// Show metadata section
if (this.html_metadata_section) {
this.html_metadata_section.classList.remove("d-none");
}
this.spinner(false);
this.toggle(true);
this.status(`Found ${data.count} colors for ${this.current_part_name} (${this.current_part})`);
}
// Create a color card element
create_color_card(color) {
const col = document.createElement('div');
col.className = 'col';
const card = document.createElement('div');
card.className = 'card h-100';
// Card image
const imgContainer = document.createElement('div');
imgContainer.className = 'card-img-top';
imgContainer.style.height = '150px';
imgContainer.style.backgroundImage = `url(${color.part_img_url || ''})`;
imgContainer.style.backgroundSize = 'contain';
imgContainer.style.backgroundRepeat = 'no-repeat';
imgContainer.style.backgroundPosition = 'center';
const img = document.createElement('img');
img.src = color.part_img_url || '';
img.alt = color.color_name;
img.className = 'd-none';
img.loading = 'lazy';
imgContainer.appendChild(img);
// Card body
const cardBody = document.createElement('div');
cardBody.className = 'card-body p-2';
const colorName = document.createElement('h6');
colorName.className = 'card-title mb-1';
colorName.textContent = color.color_name;
const colorId = document.createElement('small');
colorId.className = 'text-muted';
colorId.textContent = `ID: ${color.color_id}`;
cardBody.appendChild(colorName);
cardBody.appendChild(colorId);
// Card footer with quantity input and add button
const cardFooter = document.createElement('div');
cardFooter.className = 'card-footer p-2';
const inputGroup = document.createElement('div');
inputGroup.className = 'input-group input-group-sm';
const quantityInput = document.createElement('input');
quantityInput.type = 'number';
quantityInput.className = 'form-control';
quantityInput.placeholder = 'Qty';
quantityInput.value = '1';
quantityInput.min = '1';
quantityInput.id = `qty-${color.color_id}`;
const addButton = document.createElement('button');
addButton.className = 'btn btn-primary';
addButton.innerHTML = '<i class="ri-add-line"></i> Add';
addButton.onclick = ((bricksocket, colorData, qtyInput) => () => {
bricksocket.add_part_with_color(colorData, parseInt(qtyInput.value) || 1);
})(this, color, quantityInput);
inputGroup.appendChild(quantityInput);
inputGroup.appendChild(addButton);
cardFooter.appendChild(inputGroup);
// Assemble card
card.appendChild(imgContainer);
card.appendChild(cardBody);
card.appendChild(cardFooter);
col.appendChild(card);
return col;
}
// Add part with selected color
add_part_with_color(color, quantity) {
if (this.disabled) {
return;
}
console.log('Adding part with color:', color, 'quantity:', quantity);
// Clear previous status messages
this.clear_status();
// If in lot mode, add to cart instead of adding immediately
if (this.lot_mode) {
this.add_to_cart(color, quantity);
return;
}
// Collect owners
const owners = [];
if (this.html_owners) {
this.html_owners.querySelectorAll('input[type="checkbox"]:checked').forEach(cb => {
owners.push(cb.value);
});
}
// Collect tags
const tags = [];
if (this.html_tags) {
this.html_tags.querySelectorAll('input[type="checkbox"]:checked').forEach(cb => {
tags.push(cb.value);
});
}
const data = {
part: this.current_part,
part_name: this.current_part_name,
color: color.color_id,
color_info: color,
quantity: quantity,
description: '', // No description field in this UI
owners: owners,
tags: tags,
storage: this.html_storage ? this.html_storage.value : null,
purchase_location: this.html_purchase_location ? this.html_purchase_location.value : null,
purchase_date: this.html_purchase_date ? this.html_purchase_date.value : null,
purchase_price: this.html_purchase_price ? parseFloat(this.html_purchase_price.value) : null
};
this.clear_status();
this.toggle(false);
this.spinner(true);
console.log('Emitting LOAD_PART event with data:', data);
this.socket.emit(this.messages.LOAD_PART, data);
}
// Toggle lot/bulk mode
toggle_lot_mode(enabled) {
this.lot_mode = enabled;
if (this.html_cart_section) {
if (enabled) {
this.html_cart_section.classList.remove("d-none");
} else {
this.html_cart_section.classList.add("d-none");
// Clear cart when disabling lot mode
this.clear_cart();
}
}
}
// Add part to cart
add_to_cart(color, quantity) {
const cart_item = {
part: this.current_part,
part_name: this.current_part_name,
color_id: color.color_id,
color_name: color.color_name,
quantity: quantity,
color_info: color
};
this.cart.push(cart_item);
this.render_cart();
this.status(`Added ${this.current_part} in ${color.color_name} to cart (${this.cart.length} items)`);
}
// Remove item from cart
remove_from_cart(index) {
this.cart.splice(index, 1);
this.render_cart();
}
// Clear entire cart
clear_cart() {
this.cart = [];
this.render_cart();
this.clear_status();
}
// Render cart items
render_cart() {
if (!this.html_cart_items) return;
this.html_cart_items.innerHTML = '';
if (this.cart.length === 0) {
this.html_cart_items.innerHTML = '<p class="text-muted text-center">Cart is empty</p>';
if (this.html_complete_lot) {
this.html_complete_lot.disabled = true;
}
} else {
this.cart.forEach((item, index) => {
const cartItem = document.createElement('div');
cartItem.className = 'card mb-2';
const cardBody = document.createElement('div');
cardBody.className = 'card-body p-2 d-flex justify-content-between align-items-center';
const info = document.createElement('div');
info.innerHTML = `
<strong>${item.part}</strong> - ${item.part_name}<br>
<small class="text-muted">Color: ${item.color_name}, Qty: ${item.quantity}</small>
`;
const removeBtn = document.createElement('button');
removeBtn.className = 'btn btn-sm btn-outline-danger';
removeBtn.innerHTML = '<i class="ri-delete-bin-line"></i>';
removeBtn.onclick = () => this.remove_from_cart(index);
cardBody.appendChild(info);
cardBody.appendChild(removeBtn);
cartItem.appendChild(cardBody);
this.html_cart_items.appendChild(cartItem);
});
if (this.html_complete_lot) {
this.html_complete_lot.disabled = false;
}
}
// Update cart count badge
if (this.html_cart_count) {
this.html_cart_count.textContent = this.cart.length;
}
}
// Complete lot and add all parts
complete_lot() {
if (this.cart.length === 0) {
this.fail({message: 'Cart is empty. Add parts before completing the lot.'});
return;
}
this.clear_status();
this.toggle(false);
this.spinner(true);
// Prepare cart data - convert to format expected by backend
const cart_data = this.cart.map(item => ({
part: item.part,
part_name: item.part_name,
color_id: item.color_id,
color_name: item.color_name,
quantity: item.quantity,
color_info: item.color_info
}));
// Gather metadata from form
const lot_data = {
cart: cart_data,
name: null, // Could add optional lot name field
description: null, // Could add optional lot description field
storage: this.html_storage ? (this.html_storage.value || '') : '',
purchase_location: this.html_purchase_location ? (this.html_purchase_location.value || '') : '',
purchase_date: this.html_purchase_date && this.html_purchase_date.value ? new Date(this.html_purchase_date.value).getTime() / 1000 : null,
purchase_price: this.html_purchase_price && this.html_purchase_price.value ? parseFloat(this.html_purchase_price.value) : null,
owners: this.html_owners ? Array.from(this.html_owners.querySelectorAll('input[type="checkbox"]:checked')).map(cb => cb.value) : [],
tags: this.html_tags ? Array.from(this.html_tags.querySelectorAll('input[type="checkbox"]:checked')).map(cb => cb.value) : []
};
// Emit CREATE_LOT socket event
this.socket.emit(this.messages.CREATE_LOT, lot_data);
}
// Setup socket listeners
setup() {
super.setup();
if (this.socket) {
// Listen for part colors loaded
this.socket.on(this.messages.PART_COLORS_LOADED, ((bricksocket) => (data) => {
bricksocket.part_colors_loaded(data);
})(this));
}
}
// Override complete to clear the form but keep success message
complete(data) {
super.complete(data);
// If lot was created, clear the cart
if (data && data.lot_id) {
this.clear_cart();
// Optionally disable lot mode after successful lot creation
if (this.html_lot_mode) {
this.html_lot_mode.checked = false;
this.toggle_lot_mode(false);
}
}
// Clear the form after successful add (but don't call this.clear() as it clears status)
if (this.html_input) {
this.html_input.value = '';
}
// Hide color selection section without clearing status
if (this.html_colors_section) {
this.html_colors_section.classList.add("d-none");
}
if (this.html_colors_grid) {
this.html_colors_grid.innerHTML = '';
}
if (this.html_metadata_section) {
this.html_metadata_section.classList.add("d-none");
}
// Clear state
this.current_part = null;
this.current_part_name = null;
this.current_colors = null;
this.selected_color = null;
// Uncheck all metadata
if (this.html_owners) {
this.html_owners.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
}
if (this.html_tags) {
this.html_tags.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
}
if (this.html_storage) {
this.html_storage.value = '';
}
if (this.html_purchase_location) {
this.html_purchase_location.value = '';
}
if (this.html_purchase_date) {
this.html_purchase_date.value = '';
}
if (this.html_purchase_price) {
this.html_purchase_price.value = '';
}
}
}
// Initialize the socket
const partSocket = new BrickPartColorSocket(
'add-part',
'{{ path }}',
'{{ namespace }}',
{
COMPLETE: '{{ messages["COMPLETE"] }}',
CREATE_LOT: '{{ messages["CREATE_LOT"] }}',
FAIL: '{{ messages["FAIL"] }}',
LOAD_PART: '{{ messages["LOAD_PART"] }}',
LOAD_PART_COLORS: '{{ messages["LOAD_PART_COLORS"] }}',
PART_COLORS_LOADED: '{{ messages["PART_COLORS_LOADED"] }}',
PROGRESS: '{{ messages["PROGRESS"] }}',
PART_LOADED: '{{ messages["PART_LOADED"] }}'
}
);
});
</script>
{% endblock %}

View File

@@ -761,7 +761,16 @@
<input class="form-check-input config-static-toggle" type="checkbox" id="static-BK_DISABLE_INDIVIDUAL_MINIFIGURES" data-var="BK_DISABLE_INDIVIDUAL_MINIFIGURES">
<label class="form-check-label" for="static-BK_DISABLE_INDIVIDUAL_MINIFIGURES">
BK_DISABLE_INDIVIDUAL_MINIFIGURES {{ config_badges('BK_DISABLE_INDIVIDUAL_MINIFIGURES') }}
<div class="text-muted small">Completely disable individual/loose minifigures system</div>
<div class="text-muted small">Disable individual/loose minifigures system</div>
</label>
</div>
</div>
<div class="col-md-6">
<div class="form-check form-switch">
<input class="form-check-input config-static-toggle" type="checkbox" id="static-BK_DISABLE_INDIVIDUAL_PARTS" data-var="BK_DISABLE_INDIVIDUAL_PARTS">
<label class="form-check-label" for="static-BK_DISABLE_INDIVIDUAL_PARTS">
BK_DISABLE_INDIVIDUAL_PARTS {{ config_badges('BK_DISABLE_INDIVIDUAL_PARTS') }}
<div class="text-muted small">Disable individual/loose parts system</div>
</label>
</div>
</div>

View File

@@ -0,0 +1,40 @@
{% import 'macro/badge.html' as badge %}
{% import 'macro/card.html' as card %}
{% import 'macro/form.html' as form %}
<div class="card mb-3 flex-fill">
<div class="card-header">
<h5 class="mb-0">
<a href="{{ item.url() }}" class="text-decoration-none">
<i class="ri-hammer-line"></i>
{{ item.fields.name }} ({{ item.fields.color_name }})
</a>
</h5>
</div>
<div class="card-body border-bottom p-1">
{{ badge.quantity(item.fields.quantity, solo=false, last=false) }}
{% if item.fields.missing > 0 %}
{{ badge.total_missing(item.fields.missing, solo=false, last=false) }}
{% endif %}
{% if item.fields.damaged > 0 %}
{{ badge.total_damaged(item.fields.damaged, solo=false, last=false) }}
{% endif %}
{% for owner in brickset_owners %}
{{ badge.owner(item, owner, solo=false, last=false) }}
{% endfor %}
{% for tag in brickset_tags %}
{{ badge.tag(item, tag, solo=false, last=false) }}
{% endfor %}
{% if item.fields.storage %}
{{ badge.storage(item, brickset_storages, solo=false, last=false) }}
{% endif %}
{% if item.fields.purchase_location %}
{{ badge.purchase_location(item, brickset_purchase_locations, solo=false, last=false) }}
{% endif %}
{% if item.fields.description %}
<span class="badge text-bg-light text-dark text-wrap" data-bs-toggle="tooltip" title="{{ item.fields.description }}">
<i class="ri-file-text-line"></i> {{ item.fields.description[:config['DESCRIPTION_BADGE_MAX_LENGTH']] }}{% if item.fields.description | length > config['DESCRIPTION_BADGE_MAX_LENGTH'] %}...{% endif %}
</span>
{% endif %}
</div>
</div>

View File

@@ -0,0 +1,92 @@
{% extends 'base.html' %}
{% import 'macro/accordion.html' as accordion %}
{% import 'macro/form.html' as form %}
{% block title %} - Individual Part {{ item.fields.name }}{% endblock %}
{% block main %}
<div class="container">
<div class="row">
<div class="col-12">
<div class="card mb-3">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">
<i class="ri-hammer-line"></i> {{ item.fields.name }}
<span class="badge text-bg-secondary fw-normal"><i class="ri-hashtag"></i> {{ item.fields.part }} / Color {{ item.fields.color }}</span>
</h5>
<div>
<a href="{{ url_for('part.details', part=item.fields.part, color=item.fields.color) }}" class="btn btn-sm btn-secondary">
<i class="ri-arrow-left-line"></i> Back to {{ item.fields.part }}
</a>
</div>
</div>
{% if item.fields.image %}
<div class="card-img border-bottom" style="background-image: url({{ item.url_for_image() }})">
<a data-lightbox data-caption="{{ item.fields.name }}" href="{{ item.url_for_image() }}" target="_blank">
<img class="card-medium-img" src="{{ item.url_for_image() }}" alt="{{ item.fields.part }}" loading="lazy">
</a>
</div>
{% endif %}
<div class="accordion accordion-flush border-top" id="individual-part-details-{{ item.fields.id }}">
{{ accordion.header('Quantity', 'accordion-quantity-' ~ item.fields.id, 'individual-part-details-' ~ item.fields.id, icon='functions') }}
{{ form.input('Quantity', item.fields.id, 'quantity', item.url_for_quantity(), item.fields.quantity, icon='functions', type='number') }}
{{ accordion.footer() }}
{{ accordion.header('Description', 'accordion-description-' ~ item.fields.id, 'individual-part-details-' ~ item.fields.id, icon='file-text-line') }}
{{ form.input('Description', item.fields.id, 'description', item.url_for_description(), item.fields.description or '', icon='file-text-line', textarea=true) }}
{{ accordion.footer() }}
{{ accordion.header('Problems', 'accordion-problems-' ~ item.fields.id, 'individual-part-details-' ~ item.fields.id, icon='error-warning-line') }}
{{ form.input('Missing', item.fields.id, 'missing', item.url_for_problem('missing'), item.fields.missing, icon='question-line', type='number') }}
{{ form.input('Damaged', item.fields.id, 'damaged', item.url_for_problem('damaged'), item.fields.damaged, icon='error-warning-line', type='number') }}
{{ accordion.footer() }}
{% if lot %}
{{ accordion.header('Lot', 'accordion-lot-' ~ item.fields.id, 'individual-part-details-' ~ item.fields.id, icon='shopping-cart-line') }}
<div class="alert alert-info" role="alert">
<i class="ri-information-line"></i> This part belongs to a lot
{% if lot.fields.name %}<strong>"{{ lot.fields.name }}"</strong>{% endif %}
with {{ lot.parts()|length }} total parts.
</div>
<p class="mb-3">
All metadata (storage, purchase information, owners, tags) is managed at the lot level.
View the full lot to see all metadata and other parts.
</p>
<a href="{{ lot.url() }}" class="btn btn-primary">
<i class="ri-eye-line"></i> View Full Lot
</a>
{{ accordion.footer() }}
{% else %}
{# Only show management accordion if NOT part of a lot #}
{% include 'individual_part/management.html' %}
{% endif %}
{% if g.login.is_authenticated() %}
{{ accordion.header('Danger zone', 'accordion-danger-zone-' ~ item.fields.id, 'individual-part-details-' ~ item.fields.id, danger=true, class='text-end') }}
<a href="{{ url_for('individual_part.delete_part', id=item.fields.id) }}" class="btn btn-danger" role="button" data-bs-toggle="modal" data-bs-target="#deleteModal"><i class="ri-close-line"></i> Delete this individual part instance</a>
{{ accordion.footer() }}
{% endif %}
</div>
<div class="card-footer"></div>
</div>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Confirm Delete</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Are you sure you want to delete this individual part instance? This action cannot be undone.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<form method="POST" action="{{ url_for('individual_part.delete_part', id=item.fields.id) }}">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,82 @@
{% import 'macro/accordion.html' as accordion %}
{% import 'macro/badge.html' as badge %}
{% import 'macro/card.html' as card %}
{% import 'macro/form.html' as form %}
<div class="card mb-3 flex-fill {% if solo %}card-solo{% endif %}">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">
<i class="ri-shopping-cart-line"></i>
{% if item.fields.name %}
{{ item.fields.name }}
{% else %}
Individual Part Lot
{% endif %}
<span class="badge text-bg-secondary fw-normal">{{ item.parts()|length }} parts</span>
</h5>
{% if not solo %}
<a href="{{ item.url() }}" class="btn btn-sm btn-primary">
<i class="ri-eye-line"></i> View
</a>
{% else %}
<a href="{{ url_for('individual_part.list_lots') }}" class="btn btn-sm btn-secondary">
<i class="ri-arrow-left-line"></i> Back
</a>
{% endif %}
</div>
<div class="card-body border-bottom-0 {% if not solo %}p-1{% endif %}">
{{ badge.parts(item.parts()|length, solo=solo, last=false) }}
{% for owner in brickset_owners %}
{{ badge.owner(item, owner, solo=solo, last=false) }}
{% endfor %}
{% for tag in brickset_tags %}
{{ badge.tag(item, tag, solo=solo, last=false) }}
{% endfor %}
{{ badge.storage(item, brickset_storages, solo=solo, last=false) }}
{{ badge.purchase_date(item.purchase_date_formatted(), solo=solo, last=false) }}
{{ badge.purchase_location(item, brickset_purchase_locations, solo=solo, last=false) }}
{% if item.fields.purchase_price %}
<span class="badge text-bg-light text-dark"><i class="ri-money-dollar-circle-line"></i> ${{ "%.2f"|format(item.fields.purchase_price) }}</span>
{% endif %}
</div>
{% if solo %}
<div class="accordion accordion-flush border-top" id="lot-details">
{{ accordion.table(item.parts(), 'Parts', 'parts-inventory', 'lot-details', 'part/lot_table.html', icon='shapes-line', hamburger_menu=g.login.is_authenticated())}}
{% include 'individual_part/management.html' %}
{% if g.login.is_authenticated() %}
{{ accordion.header('Danger zone', 'danger-zone', 'lot-details', danger=true, class='text-end') }}
<a href="{{ url_for('individual_part.delete_lot', lot_id=item.fields.id) }}" class="btn btn-danger" role="button" data-bs-toggle="modal" data-bs-target="#deleteModal">
<i class="ri-delete-bin-line"></i> Delete entire lot and all parts
</a>
{{ accordion.footer() }}
{% endif %}
</div>
{% endif %}
<div class="card-footer"></div>
</div>
{% if solo and g.login.is_authenticated() %}
<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Confirm Delete</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Are you sure you want to delete this entire lot and all {{ item.parts()|length }} parts in it? This action cannot be undone.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<form method="POST" action="{{ url_for('individual_part.delete_lot', lot_id=item.fields.id) }}">
<button type="submit" class="btn btn-danger">Delete Lot</button>
</form>
</div>
</div>
</div>
</div>
{% endif %}

View File

@@ -0,0 +1,15 @@
{% extends 'base.html' %}
{% block title %} - {% if item.fields.name %}{{ item.fields.name }}{% else %}Individual Part Lot{% endif %}{% endblock %}
{% block main %}
<div class="container">
<div class="row">
<div class="col-12">
{% with solo=true %}
{% include 'individual_part/lot_card.html' %}
{% endwith %}
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,37 @@
{% extends 'base.html' %}
{% block title %} - Individual Part Lots{% endblock %}
{% block main %}
<div class="container-fluid">
<div class="row mb-3">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center">
<h2><i class="ri-shopping-cart-line"></i> Individual Part Lots</h2>
<a href="{{ url_for('add.parts') }}" class="btn btn-primary">
<i class="ri-add-line"></i> Add Parts
</a>
</div>
</div>
</div>
{% if lots | length %}
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-4">
{% for item in lots %}
<div class="col">
{% include 'individual_part/lot_card.html' with context %}
</div>
{% endfor %}
</div>
{% else %}
<div class="row">
<div class="col-12">
<div class="alert alert-info" role="alert">
<i class="ri-information-line"></i> No lots found.
<a href="{{ url_for('add.parts') }}" class="alert-link">Add some parts</a> to get started!
</div>
</div>
</div>
{% endif %}
</div>
{% endblock %}

View File

@@ -0,0 +1,83 @@
{% import 'macro/accordion.html' as accordion %}
{% import 'macro/form.html' as form %}
{% if g.login.is_authenticated() %}
{{ accordion.header('Management', 'accordion-management-' ~ item.fields.id, 'individual-part-details-' ~ item.fields.id, icon='settings-4-line', class='p-0') }}
{% if item.__class__.__name__ == 'IndividualPartLot' %}
{{ accordion.header('Details', 'accordion-details-' ~ item.fields.id, 'accordion-management-' ~ item.fields.id, icon='file-text-line') }}
<div class="row g-2">
<div class="col-12">
{{ form.input('Name', item.fields.id, 'lot-name-' ~ item.fields.id, url_for('individual_part.update_lot_name', lot_id=item.fields.id), item.fields.name) }}
</div>
<div class="col-12">
{{ form.input('Description', item.fields.id, 'lot-description-' ~ item.fields.id, url_for('individual_part.update_lot_description', lot_id=item.fields.id), item.fields.description, textarea=true) }}
</div>
</div>
{{ accordion.footer() }}
{% endif %}
{{ accordion.header('Owners', 'accordion-owners-' ~ item.fields.id, 'accordion-management-' ~ item.fields.id, icon='group-line', class='p-0') }}
<ul class="list-group list-group-flush">
{% if brickset_owners | length %}
{% for owner in brickset_owners %}
<li class="d-flex list-group-item list-group-item-action text-nowrap">{{ form.checkbox(owner.fields.name, item.fields.id, owner.as_dataset(), owner.url_for_individual_part_state(item.fields.id), item.fields[owner.as_column()]) }}</li>
{% endfor %}
{% else %}
<li class="list-group-item list-group-item-action text-center"><i class="ri-error-warning-line"></i> No owner found.</li>
{% endif %}
</ul>
<div class="list-group list-group-flush border-top">
<a class="list-group-item list-group-item-action" href="{{ url_for('admin.admin', open_owner=true) }}"><i class="ri-settings-4-line"></i> Manage the part owners</a>
</div>
{{ accordion.footer() }}
{{ accordion.header('Storage', 'accordion-storage-' ~ item.fields.id, 'accordion-management-' ~ item.fields.id, icon='archive-2-line') }}
{% if brickset_storages | length %}
{{ form.select('Storage', item.fields.id, brickset_storages.as_prefix(), brickset_storages.url_for_individual_part_value(item.fields.id), item.fields.storage, brickset_storages, icon='building-line') }}
{% else %}
<p class="text-center"><i class="ri-error-warning-line"></i> No storage found.</p>
{% endif %}
<hr>
<a href="{{ url_for('admin.admin', open_storage=true) }}" class="btn btn-primary" role="button"><i class="ri-settings-4-line"></i> Manage the storages</a>
{{ accordion.footer() }}
{{ accordion.header('Purchase', 'accordion-purchase-' ~ item.fields.id, 'accordion-management-' ~ item.fields.id, icon='wallet-3-line') }}
<div class="row row-cols-lg-auto g-1 justify-content-start align-items-center pb-2">
<div class="col-12 flex-grow-1">
{% if brickset_purchase_locations | length %}
{{ form.select('Location', item.fields.id, brickset_purchase_locations.as_prefix(), brickset_purchase_locations.url_for_individual_part_value(item.fields.id), item.fields.purchase_location, brickset_purchase_locations, icon='building-line') }}
{% else %}
<i class="ri-error-warning-line"></i> No purchase location found.
{% endif %}
</div>
</div>
<hr>
<a href="{{ url_for('admin.admin', open_purchase_location=true) }}" class="btn btn-primary" role="button"><i class="ri-settings-4-line"></i> Manage the purchase locations</a>
{{ accordion.footer() }}
{{ accordion.header('Statuses', 'accordion-statuses-' ~ item.fields.id, 'accordion-management-' ~ item.fields.id, icon='checkbox-line', class='p-0') }}
<ul class="list-group list-group-flush">
{% if brickset_statuses | length %}
{% for status in brickset_statuses %}
<li class="d-flex list-group-item list-group-item-action text-nowrap">{{ form.checkbox(status.fields.name, item.fields.id, status.as_dataset(), status.url_for_individual_part_state(item.fields.id), item.fields[status.as_column()]) }}</li>
{% endfor %}
{% else %}
<li class="list-group-item list-group-item-action text-center"><i class="ri-error-warning-line"></i> No status found.</li>
{% endif %}
</ul>
<div class="list-group list-group-flush border-top">
<a class="list-group-item list-group-item-action" href="{{ url_for('admin.admin', open_status=true) }}"><i class="ri-settings-4-line"></i> Manage the statuses</a>
</div>
{{ accordion.footer() }}
{{ accordion.header('Tags', 'accordion-tags-' ~ item.fields.id, 'accordion-management-' ~ item.fields.id, icon='price-tag-2-line', class='p-0') }}
<ul class="list-group list-group-flush">
{% if brickset_tags | length %}
{% for tag in brickset_tags %}
<li class="d-flex list-group-item list-group-item-action text-nowrap">{{ form.checkbox(tag.fields.name, item.fields.id, tag.as_dataset(), tag.url_for_individual_part_state(item.fields.id), item.fields[tag.as_column()]) }}</li>
{% endfor %}
{% else %}
<li class="list-group-item list-group-item-action text-center"><i class="ri-error-warning-line"></i> No tag found.</li>
{% endif %}
</ul>
<div class="list-group list-group-flush border-top">
<a class="list-group-item list-group-item-action" href="{{ url_for('admin.admin', open_tag=true) }}"><i class="ri-settings-4-line"></i> Manage the tags</a>
</div>
{{ accordion.footer() }}
{{ accordion.footer() }}
{% endif %}

View File

@@ -0,0 +1,38 @@
{% extends 'base.html' %}
{% import 'macro/form.html' as form %}
{% block title %} - Individual Parts{% endblock %}
{% block main %}
<div class="container-fluid">
<div class="row mb-3">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center">
<h2><i class="ri-hammer-line"></i> Individual Parts</h2>
<a href="{{ url_for('add.parts') }}" class="btn btn-primary">
<i class="ri-add-line"></i> Add Parts
</a>
</div>
</div>
</div>
{% if parts | length %}
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-4">
{% for item in parts %}
<div class="col">
{% include 'individual_part/card.html' with context %}
</div>
{% endfor %}
</div>
{% else %}
<div class="row">
<div class="col-12">
<div class="alert alert-info" role="alert">
<i class="ri-information-line"></i> No individual parts found.
<a href="{{ url_for('add.parts') }}" class="alert-link">Add some parts</a> to get started!
</div>
</div>
</div>
{% endif %}
</div>
{% endblock %}

View File

@@ -16,7 +16,7 @@
{% endif %}
{% endmacro %}
{% macro input(name, id, prefix, url, value, all=none, read_only=none, icon=none, suffix=none, date=false, type=none, textarea=false) %}
{% macro input(name, id, prefix, url, value, all=none, read_only=none, icon=none, suffix=none, date=false, type=none, textarea=false, no_clear=false) %}
{% if all or read_only %}
{{ value }}
{% else %}
@@ -44,7 +44,9 @@
{% if suffix %}<span class="input-group-text d-none d-md-inline px-1">{{ suffix }}</span>{% endif %}
{% if g.login.is_authenticated() %}
<span id="status-{{ prefix }}-{{ id }}" class="input-group-text ri-save-line px-1"></span>
{% if not no_clear %}
<button id="clear-{{ prefix }}-{{ id }}" type="button" class="btn btn-sm btn-light btn-outline-danger border px-1"><i class="ri-eraser-line"></i></button>
{% endif %}
{% else %}
<span class="input-group-text ri-prohibited-line px-1"></span>
{% endif %}

View File

@@ -29,6 +29,11 @@
{{ accordion.cards(minifigures_using, 'Minifigures using this part', 'minifigures-using-inventory', 'part-details', 'minifigure/card.html', icon='group-line') }}
{{ accordion.cards(minifigures_missing, 'Minifigures missing this part', 'minifigures-missing-inventory', 'part-details', 'minifigure/card.html', icon='question-line') }}
{{ accordion.cards(minifigures_damaged, 'Minifigures with this part damaged', 'minifigures-damaged-inventory', 'part-details', 'minifigure/card.html', icon='error-warning-line') }}
{% if not config['DISABLE_INDIVIDUAL_PARTS'] %}
{% if individual_parts is defined and individual_parts | length > 0 %}
{{ accordion.cards(individual_parts, 'Individual part instances', 'individual-parts', 'part-details', 'individual_part/card.html', icon='package-line') }}
{% endif %}
{% endif %}
{{ accordion.cards(different_color, 'Same part with a different color', 'different-color', 'part-details', 'part/card.html', icon='palette-line') }}
{{ accordion.cards(similar_prints, 'Prints using the same base', 'similar-prints', 'part-details', 'part/card.html', icon='paint-brush-line') }}
</div>

View File

@@ -0,0 +1,193 @@
{% import 'macro/form.html' as form %}
{% import 'macro/table.html' as table %}
<div class="table-responsive-sm">
<table class="table table-striped align-middle sortable mb-0">
{{ table.header(color=true, quantity=true, checked=true, hamburger_menu=g.login.is_authenticated(), accordion_id=accordion_id|default('')) }}
<tbody>
{% for item in table_collection %}
<tr>
{{ table.image(item.url_for_image(), caption=item.fields.name, alt=item.fields.part, accordion=false) }}
<td data-sort="{{ item.fields.name }}">
<a class="text-reset" href="{{ item.url() }}">{{ item.fields.name }}</a>
</td>
<td data-sort="{{ item.fields.color_name }}">
{% if item.fields.color_rgb %}<span class="color-rgb color-rgb-table {% if item.fields.color == 9999 %}color-any{% endif %} align-middle border border-black" {% if item.fields.color != 9999 %}style="background-color: #{{ item.fields.color_rgb }};"{% endif %}></span>{% endif %}
<span class="align-middle">{{ item.fields.color_name }}</span>
</td>
<td data-sort="{{ item.fields.quantity }}" class="table-td-input">
{{ form.input('Quantity', item.fields.id, item.html_id('quantity'), item.url_for_quantity(), item.fields.quantity, read_only=false, no_clear=true) }}
</td>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<td data-sort="{{ item.fields.missing }}" class="table-td-input">
{{ form.input('Missing', item.fields.id, item.html_id('missing'), item.url_for_problem('missing'), item.fields.missing, read_only=false) }}
</td>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<td data-sort="{{ item.fields.damaged }}" class="table-td-input">
{{ form.input('Damaged', item.fields.id, item.html_id('damaged'), item.url_for_problem('damaged'), item.fields.damaged, read_only=false) }}
</td>
{% endif %}
{% if not config['HIDE_TABLE_CHECKED_PARTS'] %}
<td class="table-td-input">
<center>{{ form.checkbox('', item.fields.id, item.html_id('checked'), item.url_for_checked(), item.fields.checked | default(false), parent='part', delete=false) }}</center>
</td>
{% endif %}
{% if g.login.is_authenticated() %}
<td>
<div class="dropdown">
<button type="button" class="btn btn-sm btn-outline-primary border-0" data-bs-toggle="dropdown" aria-expanded="false">
<i class="ri-more-fill"></i>
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li><a class="dropdown-item" href="{{ item.url() }}"><i class="ri-eye-line"></i> View details</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item text-danger delete-part-btn" href="#" data-part-id="{{ item.fields.id }}" data-part-name="{{ item.fields.name }}" data-part-color="{{ item.fields.color_name }}"><i class="ri-delete-bin-line"></i> Delete from lot</a></li>
</ul>
</div>
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- Remove Part from Lot Confirmation Modal -->
<div class="modal fade" id="removePartModal" tabindex="-1" aria-labelledby="removePartModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="removePartModalLabel">Remove Part from Lot</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Are you sure you want to remove <strong id="removePartName"></strong> (<span id="removePartColor"></span>) from this lot?</p>
<p class="text-muted">This action cannot be undone. The part will be permanently deleted.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" id="confirmRemovePart">Remove Part</button>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const removeModal = document.getElementById('removePartModal');
const removeModalBS = new bootstrap.Modal(removeModal);
const confirmBtn = document.getElementById('confirmRemovePart');
const partNameEl = document.getElementById('removePartName');
const partColorEl = document.getElementById('removePartColor');
let partToRemove = null;
// Handle delete button clicks
document.addEventListener('click', function(e) {
if (e.target.closest('.delete-part-btn')) {
e.preventDefault();
const btn = e.target.closest('.delete-part-btn');
const partId = btn.dataset.partId;
const partName = btn.dataset.partName;
const partColor = btn.dataset.partColor;
// Store part info
partToRemove = partId;
// Update modal text
partNameEl.textContent = partName;
partColorEl.textContent = partColor;
// Show modal
removeModalBS.show();
}
});
// Handle quantity input validation
document.addEventListener('change', function(e) {
const input = e.target;
if (input.id && input.id.includes('quantity')) {
const value = input.value.trim();
if (value === '0' || value === '') {
// Get the status icon element
const statusId = 'status-' + input.id;
const statusEl = document.getElementById(statusId);
if (statusEl) {
// Clear any existing classes
statusEl.className = '';
// Add error styling
statusEl.classList.add('input-group-text', 'ri-alert-line', 'text-danger', 'px-1');
// Create tooltip with error message
const tooltip = new bootstrap.Tooltip(statusEl, {
title: 'Quantity cannot be 0. Use the delete button in the menu to remove this part from the lot.',
trigger: 'manual',
placement: 'top'
});
tooltip.show();
// Hide tooltip after 5 seconds
setTimeout(function() {
tooltip.hide();
setTimeout(function() {
tooltip.dispose();
// Restore status icon
statusEl.className = '';
statusEl.classList.add('input-group-text', 'ri-save-line', 'px-1');
}, 200);
}, 5000);
}
// Prevent the change from going through
e.preventDefault();
e.stopPropagation();
// Restore to 1 (minimum value)
input.value = '1';
return false;
}
}
}, true);
// Handle confirmation
confirmBtn.addEventListener('click', function() {
if (partToRemove) {
const uuid = partToRemove;
// Call delete endpoint
fetch(`/individual-parts/${uuid}/delete`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => {
if (response.redirected || response.ok) {
window.location.reload();
} else {
return response.json();
}
})
.then(data => {
if (data && data.error) {
alert('Error removing part: ' + data.error);
}
})
.catch(error => {
console.error('Error removing part:', error);
alert('Error removing part from lot');
});
removeModalBS.hide();
partToRemove = null;
}
});
// Reset when modal is hidden
removeModal.addEventListener('hidden.bs.modal', function() {
partToRemove = null;
});
});
</script>

View File

@@ -3,7 +3,7 @@
<div class="table-responsive-sm">
<table data-table="true" class="table table-striped align-middle" id="storage">
{{ table.header(image=false, missing=false, damaged=false, sets=true, individual=(not config['DISABLE_INDIVIDUAL_MINIFIGURES'])) }}
{{ table.header(image=false, missing=false, damaged=false, sets=true, individual=(not config['DISABLE_INDIVIDUAL_MINIFIGURES']), parts=(not config['DISABLE_INDIVIDUAL_PARTS'])) }}
<tbody>
{% for item in table_collection %}
<tr>
@@ -12,16 +12,22 @@
{% if not config['DISABLE_INDIVIDUAL_MINIFIGURES'] %}
<td>{{ item.fields.total_individual_minifigures }}</td>
{% endif %}
{% if not config['DISABLE_INDIVIDUAL_PARTS'] %}
<td>{{ item.fields.total_individual_parts }}</td>
{% endif %}
</tr>
{% endfor %}
{% if sets_no_storage is defined and minifigs_no_storage is defined %}
{% if sets_no_storage > 0 or minifigs_no_storage > 0 %}
{% if sets_no_storage is defined and minifigs_no_storage is defined and parts_no_storage is defined %}
{% if sets_no_storage > 0 or minifigs_no_storage > 0 or parts_no_storage > 0 %}
<tr class="table-warning">
<td data-sort="zzz-not-in-storage"><a class="text-reset" href="{{ url_for('storage.no_storage_details') }}"><em>Not in a storage location</em></a></td>
<td>{{ sets_no_storage }}</td>
{% if not config['DISABLE_INDIVIDUAL_MINIFIGURES'] %}
<td>{{ minifigs_no_storage }}</td>
{% endif %}
{% if not config['DISABLE_INDIVIDUAL_PARTS'] %}
<td>{{ parts_no_storage }}</td>
{% endif %}
</tr>
{% endif %}
{% endif %}