59 Commits

Author SHA1 Message Date
989e0d57d0 Fixed date formatting on consolidated sets 2025-10-01 21:17:44 +02:00
1097255dca Fixed consolidated price on card 2025-10-01 21:11:14 +02:00
7ffbc41f0a Updated changelog 2025-10-01 21:02:58 +02:00
11f9e5782f Added charts, env var for charts, fixed formatting and table columns 2025-10-01 20:52:29 +02:00
5f43e979f9 feat(statistics): Initial upload 2025-10-01 19:43:25 +02:00
4375f018a4 Merge pull request 'feature/consolidation' (#106) from feature/consolidation into release/1.3
Reviewed-on: #106
2025-10-01 19:28:49 +02:00
87472039be Changed border color 2025-10-01 19:22:57 +02:00
c1089c349f Fixed total minifigures for consolidated sets 2025-09-28 08:59:10 +02:00
3f6af51a43 Changed the look of consolidated cards when multiple statuses are used. 2025-09-28 08:42:33 +02:00
bc3cc176ef Fixed purchase information on consolidated cards 2025-09-27 23:43:27 +02:00
4a1a265fa8 Updated changelog 2025-09-27 23:32:45 +02:00
7c95583345 Changed the "Multiple Copies Available" view and fixed border formatting. 2025-09-27 23:30:13 +02:00
65f23c1f12 Fixed nested box formatting. 2025-09-27 23:06:53 +02:00
aa6c969a6b Fixed consolidating sets. 2025-09-27 23:06:06 +02:00
0bff20215c Merge pull request 'feature/checkbox' (#105) from feature/checkbox into release/1.3
Reviewed-on: #105
2025-09-27 16:26:04 +02:00
d0147b8061 Incremented version to 1.3.0 2025-09-27 16:17:05 +02:00
ca0de215ab Fixed damaged parts drawer showing on minifigures when no parts are damaged. 2025-09-26 12:46:31 +02:00
05b259e494 Removed checkboxes from minifigures details page 2025-09-26 12:28:49 +02:00
f03fd82be1 Feat(checkbox): Initial upload 2025-09-26 11:47:15 +02:00
a769e5464b Merge pull request 'feature/peeron' (#104) from feature/peeron into release/1.3
Reviewed-on: #104
2025-09-26 11:40:01 +02:00
40871a1c10 Changed download string 2025-09-26 11:37:49 +02:00
caac283905 Updated peeron download logic with proper socket. 2025-09-26 11:31:22 +02:00
4bc0ef5cc4 Peeron thumbnails cache, as peeron uses http and cant live link to https 2025-09-25 22:09:36 +02:00
ec4f44a3ab Removed unused import 2025-09-25 21:46:58 +02:00
0a29543939 Cleanup of peeron download 2025-09-25 21:42:15 +02:00
74fe14f09b Added rotation, moved select all, added link after download 2025-09-25 20:47:41 +02:00
787624c432 Added env variables and fixed socket for peeron 2025-09-24 21:59:10 +02:00
eddf4311d3 Feat(peeron): Initial upload 2025-09-24 21:59:10 +02:00
90c0c20d75 Merge pull request 'feature/pagination' (#101) from feature/pagination into release/1.3
Reviewed-on: #101
2025-09-24 21:49:05 +02:00
d2d388b142 Merge branch 'release/1.3' into feature/pagination 2025-09-24 21:47:54 +02:00
acf06e1955 Updated change log 2025-09-24 21:36:40 +02:00
c465e9814c Fixed duplicate color in parts dropdown 2025-09-24 21:24:51 +02:00
046493294f Moved sort/filter buttons 2025-09-24 20:44:50 +02:00
1096fbdef6 Fixed sorting icon on sets page 2025-09-24 20:40:46 +02:00
fc405e0832 Consolidated parts.js, problems.js and minifigures.js 2025-09-24 20:18:30 +02:00
cce96af09b Consolidate duplicate collapsible state management 2025-09-24 19:53:01 +02:00
f953a44593 Disabled table sort using headers, if server-side pagination is enabled. 2025-09-24 19:08:34 +02:00
e87cb90e20 Updated gitignore 2025-09-23 18:07:42 +02:00
064b79bf9e Merge remote-tracking branch 'origin/master' into feature/pagination 2025-09-23 17:24:58 +02:00
d1b79de411 Updated .env.sample with new variables 2025-09-23 16:41:38 +02:00
1e767537b9 fix(pagination): Fix #95. Switch from eventlet to gevent 2025-09-23 16:36:22 +02:00
8ee0d144be Updated gitignore 2025-09-23 15:16:51 +02:00
f7963b4723 Removed datatable-search field from minifigures page 2025-09-22 10:08:41 +02:00
52b6c94483 Fixed problems pagination 2025-09-22 10:01:16 +02:00
b5236fae51 Added filter/search/pagination to 'Problems' 2025-09-22 09:36:25 +02:00
9d0a48ee2a Fixed gitignore 2025-09-21 19:03:08 +02:00
5677d731e4 Updated gitignore 2025-09-21 18:56:56 +02:00
fcdcd12184 Updated .env sample file 2025-09-21 18:21:29 +02:00
e1891e8bd6 Added more pagination options 2025-09-21 18:18:26 +02:00
af53b29818 Removed print log spam 2025-09-21 17:32:11 +02:00
8a0a7837dc Fixed filtering on /sets page. 2025-09-21 17:26:57 +02:00
4b3aef577a Fixed sorting and filtering on /sets. 2025-09-21 15:58:32 +02:00
9a32a3f193 Merge remote-tracking branch 'origin/master' into feature/pagination 2025-09-17 18:32:53 +02:00
421d635dd3 Moved import and added ignore to BeautifulSoup type annotation issues 2025-09-17 17:03:24 +02:00
6bc406b70d Fixed broken wishlist page 2025-09-17 16:49:53 +02:00
5fa145a9d7 Fixed pagination button size 2025-09-17 16:34:29 +02:00
3bfd1c17dd Sets, Parts and Minifigures have pagination now 2025-09-17 07:06:34 +02:00
46dada312a Added page size option 2025-09-16 18:26:21 +02:00
c876e1e3a4 Added pagination to /parts page. 2025-09-16 15:30:54 +02:00
88 changed files with 6913 additions and 498 deletions

View File

@@ -122,6 +122,10 @@
# Default: false
# BK_HIDE_ALL_STORAGES=true
# Optional: Hide the 'Statistics' entry from the menu. Does not disable the route.
# Default: false
# BK_HIDE_STATISTICS=true
# Optional: Hide the 'Instructions' entry in a Set card
# Default: false
# BK_HIDE_SET_INSTRUCTIONS=true
@@ -134,6 +138,10 @@
# Default: false
# BK_HIDE_TABLE_MISSING_PARTS=true
# Optional: Hide the 'Checked' column from the parts table.
# Default: false
# BK_HIDE_TABLE_CHECKED_PARTS=true
# Optional: Hide the 'Wishlist' entry from the menu. Does not disable the route.
# Default: false
# BK_HIDE_WISHES=true
@@ -170,6 +178,47 @@
# Default: parts
# BK_PARTS_FOLDER=parts
# Optional: Enable server-side pagination for individual pages (recommended for large collections)
# When enabled, pages use server-side pagination with configurable page sizes
# When disabled, pages load all data at once with instant client-side search
# Default: false for all
# BK_SETS_SERVER_SIDE_PAGINATION=true
# BK_PARTS_SERVER_SIDE_PAGINATION=true
# BK_MINIFIGURES_SERVER_SIDE_PAGINATION=true
# BK_PROBLEMS_SERVER_SIDE_PAGINATION=true
# Optional: Number of parts to show per page on desktop devices (when server-side pagination is enabled)
# Default: 10
# BK_PARTS_PAGINATION_SIZE_DESKTOP=10
# Optional: Number of parts to show per page on mobile devices (when server-side pagination is enabled)
# Default: 5
# BK_PARTS_PAGINATION_SIZE_MOBILE=5
# Optional: Number of sets to show per page on desktop devices (when server-side pagination is enabled)
# Should be divisible by 4 for grid layout. Default: 12
# BK_SETS_PAGINATION_SIZE_DESKTOP=12
# Optional: Number of sets to show per page on mobile devices (when server-side pagination is enabled)
# Default: 4
# BK_SETS_PAGINATION_SIZE_MOBILE=4
# Optional: Number of minifigures to show per page on desktop devices (when server-side pagination is enabled)
# Default: 10
# BK_MINIFIGURES_PAGINATION_SIZE_DESKTOP=10
# Optional: Number of minifigures to show per page on mobile devices (when server-side pagination is enabled)
# Default: 5
# BK_MINIFIGURES_PAGINATION_SIZE_MOBILE=5
# Optional: Number of problems to show per page on desktop devices (when server-side pagination is enabled)
# Default: 10
# BK_PROBLEMS_PAGINATION_SIZE_DESKTOP=10
# Optional: Number of problems to show per page on mobile devices (when server-side pagination is enabled)
# Default: 5
# BK_PROBLEMS_PAGINATION_SIZE_MOBILE=5
# Optional: Port the server will listen on.
# Default: 3333
# BK_PORT=3333
@@ -221,9 +270,36 @@
# Default: https://rebrickable.com/instructions/{path}
# BK_REBRICKABLE_LINK_INSTRUCTIONS_PATTERN=
# Optional: User-Agent to use when querying Rebrickable outside of the Rebrick python library
# Default: 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
# BK_REBRICKABLE_USER_AGENT=
# Optional: User-Agent to use when querying Rebrickable and Peeron outside of the Rebrick python library
# Default: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
# BK_USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
# Legacy: User-Agent for Rebrickable (use BK_USER_AGENT instead)
# BK_REBRICKABLE_USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
# Optional: Delay in milliseconds between Peeron page downloads to avoid being potentially blocked
# Default: 1000
# BK_PEERON_DOWNLOAD_DELAY=1000
# Optional: Minimum image size (width/height) for valid Peeron instruction pages
# Images smaller than this are considered error placeholders and will be rejected
# Default: 100
# BK_PEERON_MIN_IMAGE_SIZE=100
# Optional: Pattern for Peeron instruction page URLs. Will be passed to Python .format()
# Supports {set_number} and {version_number} parameters
# Default: http://peeron.com/scans/{set_number}-{version_number}
# BK_PEERON_INSTRUCTION_PATTERN=
# Optional: Pattern for Peeron thumbnail URLs. Will be passed to Python .format()
# Supports {set_number} and {version_number} parameters
# Default: http://belay.peeron.com/thumbs/{set_number}-{version_number}/
# BK_PEERON_THUMBNAIL_PATTERN=
# Optional: Pattern for Peeron scan URLs. Will be passed to Python .format()
# Supports {set_number} and {version_number} parameters
# Default: http://belay.peeron.com/scans/{set_number}-{version_number}/
# BK_PEERON_SCAN_PATTERN=
# Optional: Display Rebrickable links wherever applicable
# Default: false
@@ -260,6 +336,12 @@
# Default: sets
# BK_SETS_FOLDER=sets
# Optional: Enable set consolidation/grouping on the main sets page
# When enabled, multiple copies of the same set are grouped together showing instance count
# When disabled, each set copy is displayed individually (original behavior)
# Default: false
# BK_SETS_CONSOLIDATION=true
# Optional: Make the grid filters displayed by default, rather than collapsed
# Default: false
# BK_SHOW_GRID_FILTERS=true
@@ -313,3 +395,12 @@
# - "bricktracker_wishes"."number_of_parts": set number of parts
# Default: "bricktracker_wishes"."rowid" DESC
# BK_WISHES_DEFAULT_ORDER="bricktracker_wishes"."set" DESC
# Optional: Show collection growth charts on the statistics page
# Default: true
# BK_STATISTICS_SHOW_CHARTS=false
# Optional: Default state of statistics page sections (expanded or collapsed)
# When true, all sections start expanded. When false, all sections start collapsed.
# Default: true
# BK_STATISTICS_DEFAULT_EXPANDED=false

View File

@@ -1,6 +1,67 @@
# Changelog
## Unreleased
## Unreleased
### 1.3
- Add individual pagination control system per entity type
- `BK_SETS_SERVER_SIDE_PAGINATION`: Enable/disable pagination for sets
- `BK_PARTS_SERVER_SIDE_PAGINATION`: Enable/disable pagination for parts
- `BK_MINIFIGURES_SERVER_SIDE_PAGINATION`: Enable/disable pagination for minifigures
- Device-specific pagination sizes (desktop/mobile) for each entity type
- Supports search, filtering, and sorting in both server-side and client-side modes
- Consolidated duplicate code across parts.js, problems.js, and minifigures.js
- Created shared functions in collapsible-state.js for common operations
- Fixed dynamic sort icons across all pages
- Sort icons now properly toggle between ascending/descending states
- Improved DataTable integration
- Disabled column header sorting when server-side pagination is enabled
- Prevents conflicting sort mechanisms between DataTable and server-side sorting
- Enhanced color dropdown functionality
- Automatic merging of duplicate color entries with same color_id
- Keeps entries with valid RGB data, removes entries with None/empty RGB
- Preserves selection state during dropdown consolidation
- Consistent search behavior (instant for client-side, Enter key for server-side)
- Mobile-friendly pagination navigation
- Add Peeron instructions integration
- Full image caching system with automatic thumbnail generation
- Optimized HTTP calls by downloading full images once and generating thumbnails locally
- Automatic cache cleanup after PDF generation to save disk space
- Add parts checking/inventory system
- New "Checked" column in parts tables for tracking inventory progress
- Checkboxes to mark parts as verified during set walkthrough
- `BK_HIDE_TABLE_CHECKED_PARTS`: Environment variable to hide checked column
- Add set consolidation/grouping functionality
- Automatic grouping of duplicate sets on main sets page
- Shows instance count with stack icon badge (e.g., "3 copies")
- Expandable drawer interface to view all set copies individually
- Full set cards for each instance with all badges, statuses, and functionality
- `BK_SETS_CONSOLIDATION`: Environment variable to enable/disable consolidation (default: false)
- Backwards compatible - when disabled, behaves exactly like original individual view
- Improved theme filtering: handles duplicate theme names correctly
- Fixed set number sorting: proper numeric sorting in both ascending and descending order
- Mixed status indicators for consolidated sets: three-state checkboxes (unchecked/partial/checked) with count badges
- Template logic handles three states: none (0/2), all (2/2), partial (1/2) with visual indicators
- Purple overlay styling for partial states, disabled checkboxes for read-only consolidated status display
- Individual sets maintain full interactive checkbox functionality
- Add comprehensive statistics system (#91)
- New Statistics page with collection analytics
- Financial overview: total cost, average price, price range, investment tracking
- Collection metrics: total sets, unique sets, parts count, minifigures count
- Theme distribution statistics with clickable drill-down to filtered sets
- Storage location statistics showing sets per location with value calculations
- Purchase location analytics with spending patterns and date ranges
- Problem tracking: missing and damaged parts statistics
- Clickable numbers throughout statistics that filter to relevant sets
- `BK_HIDE_STATISTICS`: Environment variable to hide statistics menu item
- Year-based analytics: Sets by release year and purchases by year
- Sets by Release Year: Shows collection distribution across LEGO release years
- Purchases by Year: Tracks spending patterns and acquisition timeline
- Year summary with peak collection/spending years and timeline insights
- Enhanced statistics interface and functionality
- Collapsible sections: All statistics sections have clickable headers to expand/collapse
- Collection growth charts: Line charts showing sets, parts, and minifigures over time
- Configuration options: `BK_STATISTICS_SHOW_CHARTS` and `BK_STATISTICS_DEFAULT_EXPANDED` environment variables
### 1.2.4

View File

@@ -10,6 +10,7 @@ from bricktracker.configuration_list import BrickConfigurationList
from bricktracker.login import LoginManager
from bricktracker.navbar import Navbar
from bricktracker.sql import close
from bricktracker.template_filters import replace_query_filter
from bricktracker.version import __version__
from bricktracker.views.add import add_page
from bricktracker.views.admin.admin import admin_page
@@ -31,6 +32,7 @@ from bricktracker.views.login import login_page
from bricktracker.views.minifigure import minifigure_page
from bricktracker.views.part import part_page
from bricktracker.views.set import set_page
from bricktracker.views.statistics import statistics_page
from bricktracker.views.storage import storage_page
from bricktracker.views.wish import wish_page
@@ -59,7 +61,8 @@ def setup_app(app: Flask) -> None:
# Setup the login manager
LoginManager(app)
# I don't know :-)
# Configure proxy header handling for reverse proxy deployments (nginx, Apache, etc.)
# This ensures proper client IP detection and HTTPS scheme recognition
app.wsgi_app = ProxyFix(
app.wsgi_app,
x_for=1,
@@ -80,6 +83,7 @@ def setup_app(app: Flask) -> None:
app.register_blueprint(minifigure_page)
app.register_blueprint(part_page)
app.register_blueprint(set_page)
app.register_blueprint(statistics_page)
app.register_blueprint(storage_page)
app.register_blueprint(wish_page)
@@ -121,6 +125,9 @@ def setup_app(app: Flask) -> None:
# Version
g.version = __version__
# Register custom Jinja2 filters
app.jinja_env.filters['replace_query'] = replace_query_filter
# Make sure all connections are closed at the end
@app.teardown_request
def teardown_request(_: BaseException | None) -> None:

View File

@@ -31,15 +31,29 @@ CONFIG: Final[list[dict[str, Any]]] = [
{'n': 'HIDE_ALL_PROBLEMS_PARTS', 'e': 'BK_HIDE_MISSING_PARTS', 'c': bool},
{'n': 'HIDE_ALL_SETS', 'c': bool},
{'n': 'HIDE_ALL_STORAGES', 'c': bool},
{'n': 'HIDE_STATISTICS', 'c': bool},
{'n': 'HIDE_SET_INSTRUCTIONS', 'c': bool},
{'n': 'HIDE_TABLE_DAMAGED_PARTS', 'c': bool},
{'n': 'HIDE_TABLE_MISSING_PARTS', 'c': bool},
{'n': 'HIDE_TABLE_CHECKED_PARTS', 'c': bool},
{'n': 'HIDE_WISHES', 'c': bool},
{'n': 'MINIFIGURES_DEFAULT_ORDER', 'd': '"rebrickable_minifigures"."name" ASC'}, # noqa: E501
{'n': 'MINIFIGURES_FOLDER', 'd': 'minifigs', 's': True},
{'n': 'MINIFIGURES_PAGINATION_SIZE_DESKTOP', 'd': 10, 'c': int},
{'n': 'MINIFIGURES_PAGINATION_SIZE_MOBILE', 'd': 5, 'c': int},
{'n': 'MINIFIGURES_SERVER_SIDE_PAGINATION', 'c': bool},
{'n': 'NO_THREADED_SOCKET', 'c': bool},
{'n': 'PARTS_SERVER_SIDE_PAGINATION', 'c': bool},
{'n': 'SETS_SERVER_SIDE_PAGINATION', 'c': bool},
{'n': 'PARTS_DEFAULT_ORDER', 'd': '"rebrickable_parts"."name" ASC, "rebrickable_parts"."color_name" ASC, "bricktracker_parts"."spare" ASC'}, # noqa: E501
{'n': 'PARTS_FOLDER', 'd': 'parts', 's': True},
{'n': 'PARTS_PAGINATION_SIZE_DESKTOP', 'd': 10, 'c': int},
{'n': 'PARTS_PAGINATION_SIZE_MOBILE', 'd': 5, 'c': int},
{'n': 'PROBLEMS_PAGINATION_SIZE_DESKTOP', 'd': 10, 'c': int},
{'n': 'PROBLEMS_PAGINATION_SIZE_MOBILE', 'd': 10, 'c': int},
{'n': 'PROBLEMS_SERVER_SIDE_PAGINATION', 'c': bool},
{'n': 'SETS_PAGINATION_SIZE_DESKTOP', 'd': 12, 'c': int},
{'n': 'SETS_PAGINATION_SIZE_MOBILE', 'd': 4, 'c': int},
{'n': 'PORT', 'd': 3333, 'c': int},
{'n': 'PURCHASE_DATE_FORMAT', 'd': '%d/%m/%Y'},
{'n': 'PURCHASE_CURRENCY', 'd': ''},
@@ -52,12 +66,19 @@ CONFIG: Final[list[dict[str, Any]]] = [
{'n': 'REBRICKABLE_LINK_PART_PATTERN', 'd': 'https://rebrickable.com/parts/{part}/_/{color}'}, # noqa: E501
{'n': 'REBRICKABLE_LINK_INSTRUCTIONS_PATTERN', 'd': 'https://rebrickable.com/instructions/{path}'}, # noqa: E501
{'n': 'REBRICKABLE_USER_AGENT', 'd': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}, # noqa: E501
{'n': 'USER_AGENT', 'd': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}, # noqa: E501
{'n': 'PEERON_DOWNLOAD_DELAY', 'd': 1000, 'c': int},
{'n': 'PEERON_INSTRUCTION_PATTERN', 'd': 'http://peeron.com/scans/{set_number}-{version_number}'},
{'n': 'PEERON_MIN_IMAGE_SIZE', 'd': 100, 'c': int},
{'n': 'PEERON_SCAN_PATTERN', 'd': 'http://belay.peeron.com/scans/{set_number}-{version_number}/'},
{'n': 'PEERON_THUMBNAIL_PATTERN', 'd': 'http://belay.peeron.com/thumbs/{set_number}-{version_number}/'},
{'n': 'REBRICKABLE_LINKS', 'e': 'LINKS', 'c': bool},
{'n': 'REBRICKABLE_PAGE_SIZE', 'd': 100, 'c': int},
{'n': 'RETIRED_SETS_FILE_URL', 'd': 'https://docs.google.com/spreadsheets/d/1rlYfEXtNKxUOZt2Mfv0H17DvK7bj6Pe0CuYwq6ay8WA/gviz/tq?tqx=out:csv&sheet=Sorted%20by%20Retirement%20Date'}, # noqa: E501
{'n': 'RETIRED_SETS_PATH', 'd': './retired_sets.csv'},
{'n': 'SETS_DEFAULT_ORDER', 'd': '"rebrickable_sets"."number" DESC, "rebrickable_sets"."version" ASC'}, # noqa: E501
{'n': 'SETS_FOLDER', 'd': 'sets', 's': True},
{'n': 'SETS_CONSOLIDATION', 'd': False, 'c': bool},
{'n': 'SHOW_GRID_FILTERS', 'c': bool},
{'n': 'SHOW_GRID_SORT', 'c': bool},
{'n': 'SKIP_SPARE_PARTS', 'c': bool},
@@ -69,4 +90,6 @@ CONFIG: Final[list[dict[str, Any]]] = [
{'n': 'TIMEZONE', 'd': 'Etc/UTC'},
{'n': 'USE_REMOTE_IMAGES', 'c': bool},
{'n': 'WISHES_DEFAULT_ORDER', 'd': '"bricktracker_wishes"."rowid" DESC'},
{'n': 'STATISTICS_SHOW_CHARTS', 'd': True, 'c': bool},
{'n': 'STATISTICS_DEFAULT_EXPANDED', 'd': True, 'c': bool},
]

View File

@@ -101,8 +101,9 @@ class BrickInstructions(object):
# Skip if we already have it
if os.path.isfile(target):
pdf_url = self.url()
return self.socket.complete(
message=f"File {self.filename} already exists, skipped"
message=f'File {self.filename} already exists, skipped - <a href="{pdf_url}" target="_blank" class="btn btn-sm btn-primary ms-2"><i class="ri-external-link-line"></i> Open PDF</a>'
)
# Fetch PDF via cloudscraper (to bypass Cloudflare)
@@ -141,8 +142,9 @@ class BrickInstructions(object):
# Done!
logger.info(f"Downloaded {self.filename}")
pdf_url = self.url()
self.socket.complete(
message=f"File {self.filename} downloaded ({self.human_size()})"
message=f'File {self.filename} downloaded ({self.human_size()}) - <a href="{pdf_url}" target="_blank" class="btn btn-sm btn-primary ms-2"><i class="ri-external-link-line"></i> Open PDF</a>'
)
except Exception as e:
@@ -253,16 +255,16 @@ class BrickInstructions(object):
raw: list[tuple[str, str]] = []
for a in soup.find_all('a', href=link_re):
img = a.find('img', alt=True)
if not img or set not in img['alt']:
img = a.find('img', alt=True) # type: ignore
if not img or set not in img['alt']: # type: ignore
continue
# Turn the alt text into a slug
alt_text = img['alt'].removeprefix('LEGO Building Instructions for ')
alt_text = img['alt'].removeprefix('LEGO Building Instructions for ') # type: ignore
slug = re.sub(r'[^A-Za-z0-9]+', '-', alt_text).strip('-')
# Build the absolute download URL
download_url = urljoin('https://rebrickable.com', a['href'])
download_url = urljoin('https://rebrickable.com', a['href']) # type: ignore
raw.append((slug, download_url))
if not raw:

View File

@@ -111,6 +111,16 @@ class BrickMetadataList(BrickRecordList[T]):
in new.filter(**kwargs)
])
# Return the items as a dictionary mapping column names to UUIDs
@classmethod
def as_column_mapping(cls, /, **kwargs) -> dict:
new = cls.new()
return {
record.as_column(): record.fields.id
for record in new.filter(**kwargs)
}
# Grab a specific status
@classmethod
def get(cls, id: str | None, /, *, allow_none: bool = False) -> T:

View File

@@ -53,6 +53,48 @@ class BrickMinifigureList(BrickRecordList[BrickMinifigure]):
return self
# Load minifigures with pagination support
def all_filtered_paginated(
self,
owner_id: str | None = None,
search_query: str | None = None,
page: int = 1,
per_page: int = 50,
sort_field: str | None = None,
sort_order: str = 'asc'
) -> tuple[Self, int]:
# Prepare filter context
filter_context = {}
if owner_id and owner_id != 'all':
filter_context['owner_id'] = owner_id
list_query = self.all_by_owner_query
else:
list_query = self.all_query
if search_query:
filter_context['search_query'] = search_query
# Field mapping for sorting
field_mapping = {
'name': '"rebrickable_minifigures"."name"',
'parts': '"rebrickable_minifigures"."number_of_parts"',
'quantity': '"total_quantity"',
'missing': '"total_missing"',
'damaged': '"total_damaged"',
'sets': '"total_sets"'
}
# Use the base pagination method
return self.paginate(
page=page,
per_page=per_page,
sort_field=sort_field,
sort_order=sort_order,
list_query=list_query,
field_mapping=field_mapping,
**filter_context
)
# Minifigures with a part damaged part
def damaged_part(self, part: str, color: int, /) -> Self:
# Save the parameters to the fields
@@ -95,16 +137,19 @@ class BrickMinifigureList(BrickRecordList[BrickMinifigure]):
brickset = None
# Prepare template context for owner filtering
context = {}
context_vars = {}
if hasattr(self.fields, 'owner_id') and self.fields.owner_id is not None:
context['owner_id'] = self.fields.owner_id
context_vars['owner_id'] = self.fields.owner_id
# Merge with any additional context passed in
context_vars.update(context)
# Load the sets from the database
for record in super().select(
override_query=override_query,
order=order,
limit=limit,
**context
**context_vars
):
minifigure = BrickMinifigure(brickset=brickset, record=record)

View File

@@ -15,6 +15,7 @@ NAVBAR: Final[list[dict[str, Any]]] = [
{'e': 'minifigure.list', 't': 'Minifigures', 'i': 'group-line', 'f': 'HIDE_ALL_MINIFIGURES'}, # noqa: E501
{'e': 'instructions.list', 't': 'Instructions', 'i': 'file-line', 'f': 'HIDE_ALL_INSTRUCTIONS'}, # noqa: E501
{'e': 'storage.list', 't': 'Storages', 'i': 'archive-2-line', 'f': 'HIDE_ALL_STORAGES'}, # noqa: E501
{'e': 'statistics.overview', 't': 'Statistics', 'i': 'bar-chart-line', 'f': 'HIDE_STATISTICS'}, # noqa: E501
{'e': 'wish.list', 't': 'Wishlist', 'i': 'gift-line', 'f': 'HIDE_WISHES'},
{'e': 'admin.admin', 't': 'Admin', 'i': 'settings-4-line', 'f': 'HIDE_ADMIN'}, # noqa: E501
]

View File

@@ -0,0 +1,52 @@
from flask import current_app, request
from typing import Any, Dict, Tuple
def get_pagination_config(entity_type: str) -> Tuple[int, bool]:
"""Get pagination configuration for an entity type (sets, parts, minifigures)"""
# Check if pagination is enabled for this specific entity type
pagination_key = f'{entity_type.upper()}_SERVER_SIDE_PAGINATION'
use_pagination = current_app.config.get(pagination_key, False)
if not use_pagination:
return 0, False
# Determine page size based on device type and entity
user_agent = request.headers.get('User-Agent', '').lower()
is_mobile = any(device in user_agent for device in ['mobile', 'android', 'iphone', 'ipad'])
# Get appropriate config keys based on entity type
entity_upper = entity_type.upper()
desktop_key = f'{entity_upper}_PAGINATION_SIZE_DESKTOP'
mobile_key = f'{entity_upper}_PAGINATION_SIZE_MOBILE'
per_page = current_app.config[mobile_key] if is_mobile else current_app.config[desktop_key]
return per_page, is_mobile
def build_pagination_context(page: int, per_page: int, total_count: int, is_mobile: bool) -> Dict[str, Any]:
"""Build pagination context for templates"""
total_pages = (total_count + per_page - 1) // per_page if total_count > 0 else 1
has_prev = page > 1
has_next = page < total_pages
return {
'page': page,
'per_page': per_page,
'total_count': total_count,
'total_pages': total_pages,
'has_prev': has_prev,
'has_next': has_next,
'is_mobile': is_mobile
}
def get_request_params() -> Tuple[str, str, str, int]:
"""Extract common request parameters for pagination"""
search_query = request.args.get('search', '').strip()
sort_field = request.args.get('sort', '')
sort_order = request.args.get('order', 'asc')
page = int(request.args.get('page', 1))
return search_query, sort_field, sort_order, page

View File

@@ -159,6 +159,43 @@ class BrickPart(RebrickablePart):
return self
# Update checked state for part walkthrough
def update_checked(self, json: Any | None, /) -> bool:
# Handle both direct 'checked' key and changer.js 'value' key format
if json:
checked = json.get('checked', json.get('value', False))
else:
checked = False
checked = bool(checked)
# Update the field
self.fields.checked = checked
BrickSQL().execute_and_commit(
'part/update/checked',
parameters=self.sql_parameters()
)
return checked
# Compute the url for updating checked state
def url_for_checked(self, /) -> str:
# Different URL for a minifigure part
if self.minifigure is not None:
figure = self.minifigure.fields.figure
else:
figure = None
return url_for(
'set.checked_part',
id=self.fields.id,
figure=figure,
part=self.fields.part,
color=self.fields.color,
spare=self.fields.spare,
)
# Update a problematic part
def update_problem(self, problem: str, json: Any | None, /) -> int:
amount: str | int = json.get('value', '') # type: ignore

View File

@@ -71,11 +71,64 @@ class BrickPartList(BrickRecordList[BrickPart]):
else:
query = self.all_query
# Prepare context for query
context = {}
if current_app.config.get('SKIP_SPARE_PARTS', False):
context['skip_spare_parts'] = True
# Load the parts from the database
self.list(override_query=query)
self.list(override_query=query, **context)
return self
# Load parts with pagination support
def all_filtered_paginated(
self,
owner_id: str | None = None,
color_id: str | None = None,
search_query: str | None = None,
page: int = 1,
per_page: int = 50,
sort_field: str | None = None,
sort_order: str = 'asc'
) -> tuple[Self, int]:
# Prepare filter context
filter_context = {}
if owner_id and owner_id != 'all':
filter_context['owner_id'] = owner_id
list_query = self.all_by_owner_query
else:
list_query = self.all_query
if color_id and color_id != 'all':
filter_context['color_id'] = color_id
if search_query:
filter_context['search_query'] = search_query
if current_app.config.get('SKIP_SPARE_PARTS', False):
filter_context['skip_spare_parts'] = True
# Field mapping for sorting
field_mapping = {
'name': '"rebrickable_parts"."name"',
'color': '"rebrickable_parts"."color_name"',
'quantity': '"total_quantity"',
'missing': '"total_missing"',
'damaged': '"total_damaged"',
'sets': '"total_sets"',
'minifigures': '"total_minifigures"'
}
# Use the base pagination method
return self.paginate(
page=page,
per_page=per_page,
sort_field=sort_field,
sort_order=sort_order,
list_query=list_query,
field_mapping=field_mapping,
**filter_context
)
# Base part list
def list(
self,
@@ -84,6 +137,7 @@ class BrickPartList(BrickRecordList[BrickPart]):
override_query: str | None = None,
order: str | None = None,
limit: int | None = None,
offset: int | None = None,
**context: Any,
) -> None:
if order is None:
@@ -105,12 +159,18 @@ class BrickPartList(BrickRecordList[BrickPart]):
context_vars['owner_id'] = self.fields.owner_id
if hasattr(self.fields, 'color_id') and self.fields.color_id is not None:
context_vars['color_id'] = self.fields.color_id
if hasattr(self.fields, 'search_query') and self.fields.search_query:
context_vars['search_query'] = self.fields.search_query
# Merge with any additional context passed in
context_vars.update(context)
# Load the sets from the database
for record in super().select(
override_query=override_query,
order=order,
limit=limit,
offset=offset,
**context_vars
):
part = BrickPart(
@@ -119,9 +179,6 @@ class BrickPartList(BrickRecordList[BrickPart]):
record=record,
)
if current_app.config['SKIP_SPARE_PARTS'] and part.fields.spare:
continue
self.records.append(part)
# List specific parts from a brickset or minifigure
@@ -181,6 +238,70 @@ class BrickPartList(BrickRecordList[BrickPart]):
return self
def problem_filtered(self, owner_id: str | None = None, color_id: str | None = None, /) -> Self:
# Save the filter parameters for client-side filtering
if owner_id is not None:
self.fields.owner_id = owner_id
if color_id is not None:
self.fields.color_id = color_id
# Prepare context for query
context = {}
if owner_id and owner_id != 'all':
context['owner_id'] = owner_id
if color_id and color_id != 'all':
context['color_id'] = color_id
if current_app.config.get('SKIP_SPARE_PARTS', False):
context['skip_spare_parts'] = True
# Load the problematic parts from the database
self.list(override_query=self.problem_query, **context)
return self
def problem_paginated(
self,
owner_id: str | None = None,
color_id: str | None = None,
search_query: str | None = None,
page: int = 1,
per_page: int = 50,
sort_field: str | None = None,
sort_order: str = 'asc'
) -> tuple[Self, int]:
# Prepare filter context
filter_context = {}
if owner_id and owner_id != 'all':
filter_context['owner_id'] = owner_id
if color_id and color_id != 'all':
filter_context['color_id'] = color_id
if search_query:
filter_context['search_query'] = search_query
if current_app.config.get('SKIP_SPARE_PARTS', False):
filter_context['skip_spare_parts'] = True
# Field mapping for sorting
field_mapping = {
'name': '"rebrickable_parts"."name"',
'color': '"rebrickable_parts"."color_name"',
'quantity': '"total_quantity"',
'missing': '"total_missing"',
'damaged': '"total_damaged"',
'sets': '"total_sets"',
'minifigures': '"total_minifigures"'
}
# Use the base pagination method with problem query
return self.paginate(
page=page,
per_page=per_page,
sort_field=sort_field,
sort_order=sort_order,
list_query=self.problem_query,
field_mapping=field_mapping,
**filter_context
)
# Return a dict with common SQL parameters for a parts list
def sql_parameters(self, /) -> dict[str, Any]:
parameters: dict[str, Any] = super().sql_parameters()

View File

@@ -0,0 +1,437 @@
import hashlib
import logging
import os
from pathlib import Path
import time
from typing import Any, NamedTuple, TYPE_CHECKING
from urllib.parse import urljoin
from bs4 import BeautifulSoup
import cloudscraper
from flask import current_app, url_for
import requests
from .exceptions import ErrorException
if TYPE_CHECKING:
from .socket import BrickSocket
logger = logging.getLogger(__name__)
def get_peeron_user_agent():
"""Get the User-Agent string for Peeron requests from config"""
return current_app.config.get('REBRICKABLE_USER_AGENT',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36')
def get_peeron_download_delay():
"""Get the delay in milliseconds between Peeron page downloads from config"""
return current_app.config.get('PEERON_DOWNLOAD_DELAY', 1000)
def get_min_image_size():
"""Get the minimum image size for valid Peeron instruction pages from config"""
return current_app.config.get('PEERON_MIN_IMAGE_SIZE', 100)
def get_peeron_instruction_url(set_number: str, version_number: str):
"""Get the Peeron instruction page URL using the configured pattern"""
pattern = current_app.config.get('PEERON_INSTRUCTION_PATTERN', 'http://peeron.com/scans/{set_number}-{version_number}')
return pattern.format(set_number=set_number, version_number=version_number)
def get_peeron_thumbnail_url(set_number: str, version_number: str):
"""Get the Peeron thumbnail base URL using the configured pattern"""
pattern = current_app.config.get('PEERON_THUMBNAIL_PATTERN', 'http://belay.peeron.com/thumbs/{set_number}-{version_number}/')
return pattern.format(set_number=set_number, version_number=version_number)
def get_peeron_scan_url(set_number: str, version_number: str):
"""Get the Peeron scan base URL using the configured pattern"""
pattern = current_app.config.get('PEERON_SCAN_PATTERN', 'http://belay.peeron.com/scans/{set_number}-{version_number}/')
return pattern.format(set_number=set_number, version_number=version_number)
def create_peeron_scraper():
"""Create a cloudscraper instance configured for Peeron"""
scraper = cloudscraper.create_scraper()
scraper.headers.update({
"User-Agent": get_peeron_user_agent()
})
return scraper
def get_peeron_cache_dir():
"""Get the base directory for Peeron caching"""
static_dir = Path(current_app.static_folder)
cache_dir = static_dir / 'images' / 'peeron_cache'
cache_dir.mkdir(parents=True, exist_ok=True)
return cache_dir
def get_set_cache_dir(set_number: str, version_number: str) -> tuple[Path, Path]:
"""Get cache directories for a specific set"""
base_cache_dir = get_peeron_cache_dir()
set_cache_key = f"{set_number}-{version_number}"
full_cache_dir = base_cache_dir / 'full' / set_cache_key
thumb_cache_dir = base_cache_dir / 'thumbs' / set_cache_key
full_cache_dir.mkdir(parents=True, exist_ok=True)
thumb_cache_dir.mkdir(parents=True, exist_ok=True)
return full_cache_dir, thumb_cache_dir
def cache_full_image_and_generate_thumbnail(image_url: str, page_number: str, set_number: str, version_number: str, session=None) -> tuple[str | None, str | None]:
"""
Download and cache full-size image, then generate a thumbnail preview.
Uses the full-size scan URLs from Peeron.
Returns (cached_image_path, thumbnail_url) or (None, None) if caching fails.
"""
try:
full_cache_dir, thumb_cache_dir = get_set_cache_dir(set_number, version_number)
full_filename = f"{page_number}.jpg"
thumb_filename = f"{page_number}.jpg"
full_cache_path = full_cache_dir / full_filename
thumb_cache_path = thumb_cache_dir / thumb_filename
# Return existing cached files if they exist
if full_cache_path.exists() and thumb_cache_path.exists():
set_cache_key = f"{set_number}-{version_number}"
thumbnail_url = url_for('static', filename=f'images/peeron_cache/thumbs/{set_cache_key}/{thumb_filename}')
return str(full_cache_path), thumbnail_url
# Download the full-size image using provided session or create new one
if session is None:
session = create_peeron_scraper()
response = session.get(image_url, timeout=30)
if response.status_code == 200 and len(response.content) > 0:
# Validate it's actually an image by checking minimum size
min_size = get_min_image_size()
if len(response.content) < min_size:
logger.warning(f"Image too small, skipping cache: {image_url}")
return None, None
# Write full-size image to cache
with open(full_cache_path, 'wb') as f:
f.write(response.content)
logger.debug(f"Cached full image: {image_url} -> {full_cache_path}")
# Generate thumbnail from the cached full image
try:
from PIL import Image
with Image.open(full_cache_path) as img:
# Create thumbnail (max 150px on longest side to match template)
img.thumbnail((150, 150), Image.Resampling.LANCZOS)
img.save(thumb_cache_path, 'JPEG', quality=85)
logger.debug(f"Generated thumbnail: {full_cache_path} -> {thumb_cache_path}")
set_cache_key = f"{set_number}-{version_number}"
thumbnail_url = url_for('static', filename=f'images/peeron_cache/thumbs/{set_cache_key}/{thumb_filename}')
return str(full_cache_path), thumbnail_url
except Exception as thumb_error:
logger.error(f"Failed to generate thumbnail for {page_number}: {thumb_error}")
# Clean up the full image if thumbnail generation failed
if full_cache_path.exists():
full_cache_path.unlink()
return None, None
else:
logger.warning(f"Failed to download full image: {image_url}")
return None, None
except Exception as e:
logger.error(f"Error caching full image {image_url}: {e}")
return None, None
def clear_set_cache(set_number: str, version_number: str) -> int:
"""
Clear all cached files for a specific set after PDF generation.
Returns the number of files deleted.
"""
try:
full_cache_dir, thumb_cache_dir = get_set_cache_dir(set_number, version_number)
deleted_count = 0
# Delete full images
if full_cache_dir.exists():
for cache_file in full_cache_dir.glob('*.jpg'):
try:
cache_file.unlink()
deleted_count += 1
logger.debug(f"Deleted cached full image: {cache_file}")
except OSError as e:
logger.warning(f"Failed to delete cache file {cache_file}: {e}")
# Remove directory if empty
try:
full_cache_dir.rmdir()
except OSError:
pass # Directory not empty or other error
# Delete thumbnails
if thumb_cache_dir.exists():
for cache_file in thumb_cache_dir.glob('*.jpg'):
try:
cache_file.unlink()
deleted_count += 1
logger.debug(f"Deleted cached thumbnail: {cache_file}")
except OSError as e:
logger.warning(f"Failed to delete cache file {cache_file}: {e}")
# Remove directory if empty
try:
thumb_cache_dir.rmdir()
except OSError:
pass # Directory not empty or other error
# Try to remove set directory if empty
try:
set_cache_key = f"{set_number}-{version_number}"
full_cache_dir.parent.rmdir() if full_cache_dir.parent.name == set_cache_key else None
thumb_cache_dir.parent.rmdir() if thumb_cache_dir.parent.name == set_cache_key else None
except OSError:
pass # Directory not empty or other error
logger.info(f"Set cache cleanup completed for {set_number}-{version_number}: {deleted_count} files deleted")
return deleted_count
except Exception as e:
logger.error(f"Error during set cache cleanup for {set_number}-{version_number}: {e}")
return 0
def clear_old_cache(max_age_days: int = 7) -> int:
"""
Clear old cache files across all sets.
Returns the number of files deleted.
"""
try:
base_cache_dir = get_peeron_cache_dir()
if not base_cache_dir.exists():
return 0
deleted_count = 0
max_age_seconds = max_age_days * 24 * 60 * 60
current_time = time.time()
# Clean both full and thumbs directories
for cache_type in ['full', 'thumbs']:
cache_type_dir = base_cache_dir / cache_type
if cache_type_dir.exists():
for set_dir in cache_type_dir.iterdir():
if set_dir.is_dir():
for cache_file in set_dir.glob('*.jpg'):
file_age = current_time - os.path.getmtime(cache_file)
if file_age > max_age_seconds:
try:
cache_file.unlink()
deleted_count += 1
logger.debug(f"Deleted old cache file: {cache_file}")
except OSError as e:
logger.warning(f"Failed to delete cache file {cache_file}: {e}")
# Remove empty directories
try:
if not any(set_dir.iterdir()):
set_dir.rmdir()
except OSError:
pass
logger.info(f"Old cache cleanup completed: {deleted_count} files deleted")
return deleted_count
except Exception as e:
logger.error(f"Error during old cache cleanup: {e}")
return 0
class PeeronPage(NamedTuple):
"""Represents a single instruction page from Peeron"""
page_number: str
original_image_url: str # Original Peeron full-size image URL
cached_full_image_path: str # Local full-size cached image path
cached_thumbnail_url: str # Local thumbnail URL for preview
alt_text: str
rotation: int = 0 # Rotation in degrees (0, 90, 180, 270)
# Peeron instruction scraper
class PeeronInstructions(object):
socket: 'BrickSocket | None'
set_number: str
version_number: str
pages: list[PeeronPage]
def __init__(
self,
set_number: str,
version_number: str = '1',
/,
*,
socket: 'BrickSocket | None' = None,
):
# Save the socket
self.socket = socket
# Parse set number (handle both "4011" and "4011-1" formats)
if '-' in set_number:
parts = set_number.split('-', 1)
self.set_number = parts[0]
self.version_number = parts[1] if len(parts) > 1 else '1'
else:
self.set_number = set_number
self.version_number = version_number
# Placeholder for pages
self.pages = []
# Check if instructions exist on Peeron (lightweight)
def exists(self, /) -> bool:
"""Check if the set exists on Peeron without caching thumbnails"""
try:
base_url = get_peeron_instruction_url(self.set_number, self.version_number)
scraper = create_peeron_scraper()
response = scraper.get(base_url)
if response.status_code != 200:
return False
soup = BeautifulSoup(response.text, 'html.parser')
# Check for "Browse instruction library" header (set not found)
if soup.find('h1', string="Browse instruction library"):
return False
# Look for thumbnail images to confirm instructions exist
thumbnails = soup.select('table[cellspacing="5"] a img[src^="http://belay.peeron.com/thumbs/"]')
return len(thumbnails) > 0
except Exception:
return False
# Find all available instruction pages on Peeron
def find_pages(self, /) -> list[PeeronPage]:
"""
Scrape Peeron's HTML and return a list of available instruction pages.
Similar to BrickInstructions.find_instructions() but for Peeron.
"""
base_url = get_peeron_instruction_url(self.set_number, self.version_number)
thumb_base_url = get_peeron_thumbnail_url(self.set_number, self.version_number)
scan_base_url = get_peeron_scan_url(self.set_number, self.version_number)
logger.debug(f"[find_pages] fetching HTML from {base_url!r}")
# Set up session with persistent cookies for Peeron (like working dl_peeron.py)
scraper = create_peeron_scraper()
# Download the main HTML page to establish session and cookies
try:
logger.debug(f"[find_pages] Establishing session by visiting: {base_url}")
response = scraper.get(base_url)
logger.debug(f"[find_pages] Main page visit: HTTP {response.status_code}")
if response.status_code != 200:
raise ErrorException(f'Failed to load Peeron page for {self.set_number}-{self.version_number}. HTTP {response.status_code}')
except requests.exceptions.RequestException as e:
raise ErrorException(f'Failed to connect to Peeron: {e}')
# Parse HTML to locate instruction pages
soup = BeautifulSoup(response.text, 'html.parser')
# Check for "Browse instruction library" header (set not found)
if soup.find('h1', string="Browse instruction library"):
raise ErrorException(f'Set {self.set_number}-{self.version_number} not found on Peeron')
# Locate all thumbnail images in the expected table structure
# Use the configured thumbnail pattern to build the expected URL prefix
thumb_base_url = get_peeron_thumbnail_url(self.set_number, self.version_number)
thumbnails = soup.select(f'table[cellspacing="5"] a img[src^="{thumb_base_url}"]')
if not thumbnails:
raise ErrorException(f'No instruction pages found for {self.set_number}-{self.version_number} on Peeron')
pages: list[PeeronPage] = []
total_thumbnails = len(thumbnails)
# Initialize progress if socket is available
if self.socket:
self.socket.progress_total = total_thumbnails
self.socket.progress_count = 0
self.socket.progress(message=f"Starting to cache {total_thumbnails} full images")
for idx, img in enumerate(thumbnails, 1):
thumb_url = img['src']
# Extract the page number from the thumbnail URL
page_number = thumb_url.split('/')[-2]
# Build the full-size scan URL using the page number
full_size_url = f"{scan_base_url}{page_number}/"
logger.debug(f"[find_pages] Page {page_number}: thumb={thumb_url}, full_size={full_size_url}")
# Create alt text for the page
alt_text = f"LEGO Instructions {self.set_number}-{self.version_number} Page {page_number}"
# Report progress if socket is available
if self.socket:
self.socket.progress_count = idx
self.socket.progress(message=f"Caching full image {idx} of {total_thumbnails}")
# Cache the full-size image and generate thumbnail preview using established session
cached_full_path, cached_thumb_url = cache_full_image_and_generate_thumbnail(
full_size_url, page_number, self.set_number, self.version_number, session=scraper
)
# Skip this page if caching failed
if not cached_full_path or not cached_thumb_url:
logger.warning(f"[find_pages] Skipping page {page_number} due to caching failure")
continue
page = PeeronPage(
page_number=page_number,
original_image_url=full_size_url,
cached_full_image_path=cached_full_path,
cached_thumbnail_url=cached_thumb_url,
alt_text=alt_text
)
pages.append(page)
# Cache the pages for later use
self.pages = pages
logger.debug(f"[find_pages] found {len(pages)} pages for {self.set_number}-{self.version_number}")
return pages
# Find instructions with fallback to Peeron
@staticmethod
def find_instructions_with_peeron_fallback(set: str, /) -> tuple[list[tuple[str, str]], list[PeeronPage] | None]:
"""
Enhanced version of BrickInstructions.find_instructions() that falls back to Peeron.
Returns (rebrickable_instructions, peeron_pages).
If rebrickable_instructions is empty, peeron_pages will contain Peeron data.
"""
from .instructions import BrickInstructions
# First try Rebrickable
try:
rebrickable_instructions = BrickInstructions.find_instructions(set)
return rebrickable_instructions, None
except ErrorException as e:
logger.info(f"Rebrickable failed for {set}: {e}. Trying Peeron fallback...")
# Fallback to Peeron
try:
peeron = PeeronInstructions(set)
peeron_pages = peeron.find_pages()
return [], peeron_pages
except ErrorException as peeron_error:
# Both failed, re-raise original Rebrickable error
logger.info(f"Peeron also failed for {set}: {peeron_error}")
raise e from peeron_error

200
bricktracker/peeron_pdf.py Normal file
View File

@@ -0,0 +1,200 @@
import logging
import os
import tempfile
import time
from typing import Any, TYPE_CHECKING
import cloudscraper
from flask import current_app
from PIL import Image
from .exceptions import DownloadException, ErrorException
from .instructions import BrickInstructions
from .peeron_instructions import PeeronPage, get_min_image_size, get_peeron_download_delay, get_peeron_instruction_url, create_peeron_scraper
if TYPE_CHECKING:
from .socket import BrickSocket
logger = logging.getLogger(__name__)
# PDF generator for Peeron instruction pages
class PeeronPDF(object):
socket: 'BrickSocket'
set_number: str
version_number: str
pages: list[PeeronPage]
filename: str
def __init__(
self,
set_number: str,
version_number: str,
pages: list[PeeronPage],
/,
*,
socket: 'BrickSocket',
):
# Save the socket
self.socket = socket
# Save set information
self.set_number = set_number
self.version_number = version_number
self.pages = pages
# Generate filename following BrickTracker conventions
self.filename = f"{set_number}-{version_number}_peeron.pdf"
# Download pages and create PDF
def create_pdf(self, /) -> None:
"""
Downloads selected Peeron pages and merges them into a PDF.
Uses progress updates via socket similar to BrickInstructions.download()
"""
try:
target_path = self._get_target_path()
# Skip if we already have it
if os.path.isfile(target_path):
# Create BrickInstructions instance to get PDF URL
instructions = BrickInstructions(self.filename)
pdf_url = instructions.url()
return self.socket.complete(
message=f'File {self.filename} already exists, skipped - <a href="{pdf_url}" target="_blank" class="btn btn-sm btn-primary ms-2"><i class="ri-external-link-line"></i> Open PDF</a>'
)
# Set up progress tracking
total_pages = len(self.pages)
self.socket.update_total(total_pages)
self.socket.progress_count = 0
self.socket.progress(message=f"Starting PDF creation from {total_pages} cached pages")
# Use cached images directly - no downloads needed!
cached_files_with_rotation = []
missing_pages = []
for i, page in enumerate(self.pages):
# Check if cached file exists
if os.path.isfile(page.cached_full_image_path):
cached_files_with_rotation.append((page.cached_full_image_path, page.rotation))
# Update progress
self.socket.progress_count += 1
self.socket.progress(
message=f"Processing cached page {page.page_number} ({i + 1}/{total_pages})"
)
else:
missing_pages.append(page.page_number)
logger.warning(f"Cached image missing for page {page.page_number}: {page.cached_full_image_path}")
if not cached_files_with_rotation:
raise DownloadException(f"No cached images available for set {self.set_number}-{self.version_number}. Cache may have been cleared.")
elif len(cached_files_with_rotation) < total_pages:
# Partial success
error_msg = f"Only found {len(cached_files_with_rotation)}/{total_pages} cached images."
if missing_pages:
error_msg += f" Missing pages: {', '.join(missing_pages)}."
logger.warning(error_msg)
# Create PDF from cached images with rotation
self._create_pdf_from_images(cached_files_with_rotation, target_path)
# Success
logger.info(f"Created PDF {self.filename} with {len(cached_files_with_rotation)} pages")
# Create BrickInstructions instance to get PDF URL
instructions = BrickInstructions(self.filename)
pdf_url = instructions.url()
self.socket.complete(
message=f'PDF {self.filename} created with {len(cached_files_with_rotation)} pages - <a href="{pdf_url}" target="_blank" class="btn btn-sm btn-primary ms-2"><i class="ri-external-link-line"></i> Open PDF</a>'
)
# Clean up set cache after successful PDF creation
try:
from .peeron_instructions import clear_set_cache
deleted_count = clear_set_cache(self.set_number, self.version_number)
if deleted_count > 0:
logger.info(f"[create_pdf] Cleaned up {deleted_count} cache files for set {self.set_number}-{self.version_number}")
except Exception as e:
logger.warning(f"[create_pdf] Failed to clean set cache: {e}")
except Exception as e:
logger.error(f"Error creating PDF {self.filename}: {e}")
self.socket.fail(
message=f"Error creating PDF {self.filename}: {e}"
)
# Create PDF from downloaded images
def _create_pdf_from_images(self, image_paths_and_rotations: list[tuple[str, int]], output_path: str, /) -> None:
"""Create a PDF from a list of image files with their rotations"""
try:
# Import FPDF (should be available from requirements)
from fpdf import FPDF
except ImportError:
raise ErrorException("FPDF library not available. Install with: pip install fpdf2")
pdf = FPDF()
for i, (img_path, rotation) in enumerate(image_paths_and_rotations):
try:
# Open image and apply rotation if needed
with Image.open(img_path) as image:
# Apply rotation if specified
if rotation != 0:
# PIL rotation is counter-clockwise, so we negate for clockwise rotation
image = image.rotate(-rotation, expand=True)
width, height = image.size
# Add page with image dimensions (convert pixels to mm)
# 1 pixel = 0.264583 mm (assuming 96 DPI)
page_width = width * 0.264583
page_height = height * 0.264583
pdf.add_page(format=(page_width, page_height))
# Save rotated image to temporary file for FPDF
temp_rotated_path = None
if rotation != 0:
import tempfile
temp_fd, temp_rotated_path = tempfile.mkstemp(suffix='.jpg', prefix=f'peeron_rotated_{i}_')
try:
os.close(temp_fd) # Close file descriptor, we'll use the path
image.save(temp_rotated_path, 'JPEG', quality=95)
pdf.image(temp_rotated_path, x=0, y=0, w=page_width, h=page_height)
finally:
# Clean up rotated temp file
if temp_rotated_path and os.path.exists(temp_rotated_path):
os.remove(temp_rotated_path)
else:
pdf.image(img_path, x=0, y=0, w=page_width, h=page_height)
# Update progress
progress_msg = f"Processing page {i + 1}/{len(image_paths_and_rotations)} into PDF"
if rotation != 0:
progress_msg += f" (rotated {rotation}°)"
self.socket.progress(message=progress_msg)
except Exception as e:
logger.warning(f"Failed to add image {img_path} to PDF: {e}")
continue
# Save the PDF
pdf.output(output_path)
# Get target file path
def _get_target_path(self, /) -> str:
"""Get the full path where the PDF should be saved"""
instructions_folder = os.path.join(
current_app.static_folder, # type: ignore
current_app.config['INSTRUCTIONS_FOLDER']
)
return os.path.join(instructions_folder, self.filename)
# Create BrickInstructions instance for the generated PDF
def get_instructions(self, /) -> BrickInstructions:
"""Return a BrickInstructions instance for the generated PDF"""
return BrickInstructions(self.filename)

View File

@@ -98,7 +98,7 @@ class RebrickablePart(BrickRecord):
# Use BrickLink color ID if available and not None, otherwise fall back to Rebrickable color
bricklink_color = getattr(self.fields, 'bricklink_color_id', None)
color_param = bricklink_color if bricklink_color is not None else self.fields.color
print(f'BrickLink URL parameters: part={part_param}, color={color_param}') # Debugging line, can be removed later
# print(f'BrickLink URL parameters: part={part_param}, color={color_param}') # Debugging line, can be removed later
return current_app.config['BRICKLINK_LINK_PART_PATTERN'].format( # noqa: E501
part=part_param,
color=color_param,

View File

@@ -11,24 +11,19 @@ class RebrickableSetList(BrickRecordList[RebrickableSet]):
select_query: str = 'rebrickable/set/list'
refresh_query: str = 'rebrickable/set/need_refresh'
# All the sets
def all(self, /) -> Self:
# Implementation of abstract list method
def list(self, /, *, override_query: str | None = None, **context) -> None:
# Load the sets from the database
for record in self.select():
for record in self.select(override_query=override_query, **context):
rebrickable_set = RebrickableSet(record=record)
self.records.append(rebrickable_set)
# All the sets
def all(self, /) -> Self:
self.list()
return self
# Sets needing refresh
def need_refresh(self, /) -> Self:
# Load the sets from the database
for record in self.select(
override_query=self.refresh_query
):
rebrickable_set = RebrickableSet(record=record)
self.records.append(rebrickable_set)
self.list(override_query=self.refresh_query)
return self

View File

@@ -1,5 +1,6 @@
import re
from sqlite3 import Row
from typing import Any, Generator, Generic, ItemsView, TypeVar, TYPE_CHECKING
from typing import Any, Generator, Generic, ItemsView, Self, TypeVar, TYPE_CHECKING
from .fields import BrickRecordFields
from .sql import BrickSQL
@@ -72,6 +73,90 @@ class BrickRecordList(Generic[T]):
**context
)
# Generic pagination method for all record lists
def paginate(
self,
page: int = 1,
per_page: int = 50,
sort_field: str | None = None,
sort_order: str = 'asc',
count_query: str | None = None,
list_query: str | None = None,
field_mapping: dict[str, str] | None = None,
**filter_context: Any
) -> tuple['Self', int]:
"""Generic pagination implementation for all record lists"""
from .sql import BrickSQL
# Use provided queries or fall back to defaults
list_query = list_query or getattr(self, 'all_query', None)
if not list_query:
raise NotImplementedError("Subclass must define all_query")
# Calculate offset
offset = (page - 1) * per_page
# Get total count by wrapping the main query
if count_query:
# Use provided count query
count_result = BrickSQL().fetchone(count_query, **filter_context)
total_count = count_result['total_count'] if count_result else 0
else:
# Generate count by wrapping the main query (without ORDER BY, LIMIT, OFFSET)
count_context = {k: v for k, v in filter_context.items()
if k not in ['order', 'limit', 'offset']}
# Get the main query SQL without pagination clauses
main_sql = BrickSQL().load_query(list_query, **count_context)
# Remove ORDER BY, LIMIT, OFFSET clauses for counting
# Remove ORDER BY clause and everything after it that's not part of subqueries
count_sql = re.sub(r'\s+ORDER\s+BY\s+[^)]*?(\s+LIMIT|\s+OFFSET|$)', r'\1', main_sql, flags=re.IGNORECASE)
# Remove LIMIT and OFFSET
count_sql = re.sub(r'\s+LIMIT\s+\d+', '', count_sql, flags=re.IGNORECASE)
count_sql = re.sub(r'\s+OFFSET\s+\d+', '', count_sql, flags=re.IGNORECASE)
# Wrap in COUNT(*)
wrapped_sql = f"SELECT COUNT(*) as total_count FROM ({count_sql.strip()})"
count_result = BrickSQL().raw_execute(wrapped_sql, {}).fetchone()
total_count = count_result['total_count'] if count_result else 0
# Prepare sort order
order_clause = None
if sort_field and field_mapping and sort_field in field_mapping:
sql_field = field_mapping[sort_field]
direction = 'DESC' if sort_order.lower() == 'desc' else 'ASC'
order_clause = f'{sql_field} {direction}'
# Build pagination context
pagination_context = {
'limit': per_page,
'offset': offset,
'order': order_clause or getattr(self, 'order', None),
**filter_context
}
# Load paginated results using the existing list() method
# Check if this is a set list that needs do_theme parameter
if hasattr(self, 'themes'): # Only BrickSetList has this attribute
self.list(override_query=list_query, do_theme=True, **pagination_context)
else:
self.list(override_query=list_query, **pagination_context)
return self, total_count
# Base method that subclasses can override
def list(
self,
/,
*,
override_query: str | None = None,
**context: Any,
) -> None:
"""Load records from database - should be implemented by subclasses that use pagination"""
raise NotImplementedError("Subclass must implement list() method")
# Generic SQL parameters from fields
def sql_parameters(self, /) -> dict[str, Any]:
parameters: dict[str, Any] = {}

View File

@@ -169,6 +169,20 @@ class BrickSet(RebrickableSet):
else:
return ''
# Purchase date max formatted for consolidated sets
def purchase_date_max_formatted(self, /, *, standard: bool = False) -> str:
if hasattr(self.fields, 'purchase_date_max') and self.fields.purchase_date_max is not None:
time = datetime.fromtimestamp(self.fields.purchase_date_max)
if standard:
return time.strftime('%Y/%m/%d')
else:
return time.strftime(
current_app.config['PURCHASE_DATE_FORMAT']
)
else:
return ''
# Purchase price with currency
def purchase_price(self, /) -> str:
if self.fields.purchase_price is not None:

View File

@@ -13,14 +13,19 @@ from .set_storage_list import BrickSetStorageList
from .set_tag import BrickSetTag
from .set_tag_list import BrickSetTagList
from .set import BrickSet
from .theme_list import BrickThemeList
from .instructions_list import BrickInstructionsList
# All the sets from the database
class BrickSetList(BrickRecordList[BrickSet]):
themes: list[str]
years: list[int]
order: str
# Queries
all_query: str = 'set/list/all'
consolidated_query: str = 'set/list/consolidated'
damaged_minifigure_query: str = 'set/list/damaged_minifigure'
damaged_part_query: str = 'set/list/damaged_part'
generic_query: str = 'set/list/generic'
@@ -37,17 +42,489 @@ class BrickSetList(BrickRecordList[BrickSet]):
# Placeholders
self.themes = []
self.years = []
# Store the order for this list
self.order = current_app.config['SETS_DEFAULT_ORDER']
# All the sets
def all(self, /) -> Self:
# Load the sets from the database
self.list(do_theme=True)
# Load the sets from the database with metadata context for filtering
filter_context = {
'owners': BrickSetOwnerList.as_columns(),
'statuses': BrickSetStatusList.as_columns(),
'tags': BrickSetTagList.as_columns(),
}
self.list(do_theme=True, **filter_context)
return self
# All sets in consolidated/grouped view
def all_consolidated(self, /) -> Self:
# Load the sets from the database using consolidated query with metadata context
filter_context = {
'owners_dict': BrickSetOwnerList.as_column_mapping(),
'statuses_dict': BrickSetStatusList.as_column_mapping(),
'tags_dict': BrickSetTagList.as_column_mapping(),
}
self.list(override_query=self.consolidated_query, do_theme=True, **filter_context)
return self
# All sets with pagination and filtering
def all_filtered_paginated(
self,
search_query: str | None = None,
page: int = 1,
per_page: int = 50,
sort_field: str | None = None,
sort_order: str = 'asc',
status_filter: str | None = None,
theme_filter: str | None = None,
owner_filter: str | None = None,
purchase_location_filter: str | None = None,
storage_filter: str | None = None,
tag_filter: str | None = None,
year_filter: str | None = None,
use_consolidated: bool = True
) -> tuple[Self, int]:
# Convert theme name to theme ID for filtering
theme_id_filter = None
if theme_filter:
theme_id_filter = self._theme_name_to_id(theme_filter)
# Check if any filters are applied
has_filters = any([status_filter, theme_id_filter, owner_filter, purchase_location_filter, storage_filter, tag_filter, year_filter])
# Prepare filter context
filter_context = {
'search_query': search_query,
'status_filter': status_filter,
'theme_filter': theme_id_filter, # Use converted theme ID
'owner_filter': owner_filter,
'purchase_location_filter': purchase_location_filter,
'storage_filter': storage_filter,
'tag_filter': tag_filter,
'year_filter': year_filter,
'owners': BrickSetOwnerList.as_columns(),
'statuses': BrickSetStatusList.as_columns(),
'tags': BrickSetTagList.as_columns(),
'owners_dict': BrickSetOwnerList.as_column_mapping(),
'statuses_dict': BrickSetStatusList.as_column_mapping(),
'tags_dict': BrickSetTagList.as_column_mapping(),
}
# Field mapping for sorting
if use_consolidated:
field_mapping = {
'set': '"rebrickable_sets"."number", "rebrickable_sets"."version"',
'name': '"rebrickable_sets"."name"',
'year': '"rebrickable_sets"."year"',
'parts': '"rebrickable_sets"."number_of_parts"',
'theme': '"rebrickable_sets"."theme_id"',
'minifigures': '"total_minifigures"',
'missing': '"total_missing"',
'damaged': '"total_damaged"',
'instances': '"instance_count"', # New field for consolidated view
'purchase-date': '"purchase_date"', # Use the MIN aggregated value
'purchase-price': '"purchase_price"' # Use the MIN aggregated value
}
else:
field_mapping = {
'set': '"rebrickable_sets"."number", "rebrickable_sets"."version"',
'name': '"rebrickable_sets"."name"',
'year': '"rebrickable_sets"."year"',
'parts': '"rebrickable_sets"."number_of_parts"',
'theme': '"rebrickable_sets"."theme_id"',
'minifigures': '"total_minifigures"', # Use the alias from the SQL query
'missing': '"total_missing"', # Use the alias from the SQL query
'damaged': '"total_damaged"', # Use the alias from the SQL query
'purchase-date': '"bricktracker_sets"."purchase_date"',
'purchase-price': '"bricktracker_sets"."purchase_price"'
}
# Choose query based on consolidation preference and filter complexity
# Owner/tag filters still need to fall back to non-consolidated for now
# due to complex aggregation requirements
complex_filters = [owner_filter, tag_filter]
if use_consolidated and not any(complex_filters):
query_to_use = self.consolidated_query
else:
# Use filtered query when consolidation is disabled or complex filters applied
query_to_use = 'set/list/all_filtered'
# Handle instructions filtering
if status_filter in ['has-missing-instructions', '-has-missing-instructions']:
# For instructions filter, we need to load all sets first, then filter and paginate
return self._all_filtered_paginated_with_instructions(
search_query, page, per_page, sort_field, sort_order,
status_filter, theme_id_filter, owner_filter,
purchase_location_filter, storage_filter, tag_filter
)
# Handle special case for set sorting with multiple columns
if sort_field == 'set' and field_mapping:
# Create custom order clause for set sorting
direction = 'DESC' if sort_order.lower() == 'desc' else 'ASC'
custom_order = f'"rebrickable_sets"."number" {direction}, "rebrickable_sets"."version" {direction}'
filter_context['order'] = custom_order
# Remove set from field mapping to avoid double-processing
field_mapping_copy = field_mapping.copy()
field_mapping_copy.pop('set', None)
field_mapping = field_mapping_copy
sort_field = None # Disable automatic ORDER BY construction
# Normal SQL-based filtering and pagination
result, total_count = self.paginate(
page=page,
per_page=per_page,
sort_field=sort_field,
sort_order=sort_order,
list_query=query_to_use,
field_mapping=field_mapping,
**filter_context
)
# Populate themes and years for filter dropdown from filtered dataset (not just current page)
result._populate_themes_from_filtered_dataset(
query_to_use,
**filter_context
)
result._populate_years_from_filtered_dataset(
query_to_use,
**filter_context
)
return result, total_count
def _populate_themes(self) -> None:
"""Populate themes list from the current records"""
themes = set()
for record in self.records:
if hasattr(record, 'theme') and hasattr(record.theme, 'name'):
themes.add(record.theme.name)
self.themes = list(themes)
self.themes.sort()
def _populate_years(self) -> None:
"""Populate years list from the current records"""
years = set()
for record in self.records:
if hasattr(record, 'fields') and hasattr(record.fields, 'year') and record.fields.year:
years.add(record.fields.year)
self.years = list(years)
self.years.sort(reverse=True) # Most recent years first
def _theme_name_to_id(self, theme_name_or_id: str) -> str | None:
"""Convert a theme name or ID to theme ID for filtering"""
try:
# Check if the input is already a numeric theme ID
if theme_name_or_id.isdigit():
# Input is already a theme ID, validate it exists
theme_list = BrickThemeList()
theme_id = int(theme_name_or_id)
if theme_id in theme_list.themes:
return str(theme_id)
else:
return None
# Input is a theme name, convert to ID
from .sql import BrickSQL
theme_list = BrickThemeList()
# Find all theme IDs that match the name
matching_theme_ids = []
for theme_id, theme in theme_list.themes.items():
if theme.name.lower() == theme_name_or_id.lower():
matching_theme_ids.append(str(theme_id))
if not matching_theme_ids:
return None
# If only one match, return it
if len(matching_theme_ids) == 1:
return matching_theme_ids[0]
# Multiple matches - check which theme ID actually has sets in the user's collection
sql = BrickSQL()
for theme_id in matching_theme_ids:
result = sql.fetchone(
'set/check_theme_exists',
theme_id=theme_id
)
count = result['count'] if result else 0
if count > 0:
return theme_id
# If none have sets, return the first match (fallback)
return matching_theme_ids[0]
except Exception:
# If themes can't be loaded, return None to disable theme filtering
return None
def _theme_id_to_name(self, theme_id: str) -> str | None:
"""Convert a theme ID to theme name (lowercase) for dropdown display"""
try:
if not theme_id or not theme_id.isdigit():
return None
from .theme_list import BrickThemeList
theme_list = BrickThemeList()
theme_id_int = int(theme_id)
if theme_id_int in theme_list.themes:
return theme_list.themes[theme_id_int].name.lower()
return None
except Exception as e:
# For debugging - log the exception
import logging
logger = logging.getLogger(__name__)
logger.warning(f"Failed to convert theme ID {theme_id} to name: {e}")
return None
def _all_filtered_paginated_with_instructions(
self,
search_query: str | None,
page: int,
per_page: int,
sort_field: str | None,
sort_order: str,
status_filter: str,
theme_id_filter: str | None,
owner_filter: str | None,
purchase_location_filter: str | None,
storage_filter: str | None,
tag_filter: str | None
) -> tuple[Self, int]:
"""Handle filtering when instructions filter is involved"""
try:
# Load all sets first (without pagination) with full metadata
all_sets = BrickSetList()
filter_context = {
'owners': BrickSetOwnerList.as_columns(),
'statuses': BrickSetStatusList.as_columns(),
'tags': BrickSetTagList.as_columns(),
}
all_sets.list(do_theme=True, **filter_context)
# Load instructions list
instructions_list = BrickInstructionsList()
instruction_sets = set(instructions_list.sets.keys())
# Apply all filters manually
filtered_records = []
for record in all_sets.records:
# Apply instructions filter
set_id = record.fields.set
has_instructions = set_id in instruction_sets
if status_filter == 'has-missing-instructions' and has_instructions:
continue # Skip sets that have instructions
elif status_filter == '-has-missing-instructions' and not has_instructions:
continue # Skip sets that don't have instructions
# Apply other filters manually
if search_query and not self._matches_search(record, search_query):
continue
if theme_id_filter and not self._matches_theme(record, theme_id_filter):
continue
if owner_filter and not self._matches_owner(record, owner_filter):
continue
if purchase_location_filter and not self._matches_purchase_location(record, purchase_location_filter):
continue
if storage_filter and not self._matches_storage(record, storage_filter):
continue
if tag_filter and not self._matches_tag(record, tag_filter):
continue
filtered_records.append(record)
# Apply sorting
if sort_field:
filtered_records = self._sort_records(filtered_records, sort_field, sort_order)
# Calculate pagination
total_count = len(filtered_records)
start_index = (page - 1) * per_page
end_index = start_index + per_page
paginated_records = filtered_records[start_index:end_index]
# Create result
result = BrickSetList()
result.records = paginated_records
# Copy themes and years from the source that has all sets
result.themes = all_sets.themes if hasattr(all_sets, 'themes') else []
result.years = all_sets.years if hasattr(all_sets, 'years') else []
# If themes or years weren't populated, populate them from current records
if not result.themes:
result._populate_themes()
if not result.years:
result._populate_years()
return result, total_count
except Exception:
# Fall back to normal pagination without instructions filter
return self.all_filtered_paginated(
search_query, page, per_page, sort_field, sort_order,
None, theme_id_filter, owner_filter,
purchase_location_filter, storage_filter, tag_filter
)
def _populate_years_from_filtered_dataset(self, query_name: str, **filter_context) -> None:
"""Populate years list from all available records in filtered dataset"""
try:
# Get all records matching the current filters (not just current page)
unlimited_context = filter_context.copy()
unlimited_context.pop('limit', None)
unlimited_context.pop('offset', None)
# Query all records for year extraction
all_sets = self._query_sets(query_name, **unlimited_context)
if all_sets.records:
years = set()
for record in all_sets.records:
if hasattr(record, 'fields') and hasattr(record.fields, 'year') and record.fields.year:
years.add(record.fields.year)
self.years = list(years)
self.years.sort(reverse=True) # Most recent years first
except Exception:
# Final fallback to current page years
self._populate_years()
def _populate_themes_from_filtered_dataset(self, query_name: str, **filter_context) -> None:
"""Populate themes list from filtered dataset (all pages, not just current page)"""
try:
from .theme_list import BrickThemeList
# Use a simplified query to get just distinct theme_ids
theme_context = dict(filter_context)
theme_context.pop('limit', None)
theme_context.pop('offset', None)
# Use a special lightweight query for themes
theme_records = super().select(
override_query='set/list/themes_only',
**theme_context
)
# Convert to theme names
theme_list = BrickThemeList()
themes = set()
for record in theme_records:
theme_id = record.get('theme_id')
if theme_id:
theme = theme_list.get(theme_id)
if theme and hasattr(theme, 'name'):
themes.add(theme.name)
self.themes = list(themes)
self.themes.sort()
except Exception:
# Fall back to simpler approach: get themes from ALL sets (ignoring filters)
# This is better than showing only current page themes
try:
from .theme_list import BrickThemeList
all_sets = BrickSetList()
all_sets.list(do_theme=True)
themes = set()
years = set()
for record in all_sets.records:
if hasattr(record, 'theme') and hasattr(record.theme, 'name'):
themes.add(record.theme.name)
if hasattr(record, 'fields') and hasattr(record.fields, 'year') and record.fields.year:
years.add(record.fields.year)
self.themes = list(themes)
self.themes.sort()
self.years = list(years)
self.years.sort(reverse=True)
except Exception:
# Final fallback to current page themes
self._populate_themes()
self._populate_years()
def _matches_search(self, record, search_query: str) -> bool:
"""Check if record matches search query"""
search_lower = search_query.lower()
return (search_lower in record.fields.name.lower() or
search_lower in record.fields.set.lower())
def _matches_theme(self, record, theme_id: str) -> bool:
"""Check if record matches theme filter"""
return str(record.fields.theme_id) == theme_id
def _matches_owner(self, record, owner_filter: str) -> bool:
"""Check if record matches owner filter"""
if not owner_filter.startswith('owner-'):
return True
# Convert owner-uuid format to owner_uuid column name
owner_column = owner_filter.replace('-', '_')
# Check if record has this owner attribute set to 1
return hasattr(record.fields, owner_column) and getattr(record.fields, owner_column) == 1
def _matches_purchase_location(self, record, location_filter: str) -> bool:
"""Check if record matches purchase location filter"""
return record.fields.purchase_location == location_filter
def _matches_storage(self, record, storage_filter: str) -> bool:
"""Check if record matches storage filter"""
return record.fields.storage == storage_filter
def _matches_tag(self, record, tag_filter: str) -> bool:
"""Check if record matches tag filter"""
if not tag_filter.startswith('tag-'):
return True
# Convert tag-uuid format to tag_uuid column name
tag_column = tag_filter.replace('-', '_')
# Check if record has this tag attribute set to 1
return hasattr(record.fields, tag_column) and getattr(record.fields, tag_column) == 1
def _sort_records(self, records, sort_field: str, sort_order: str):
"""Sort records manually"""
reverse = sort_order == 'desc'
if sort_field == 'set':
return sorted(records, key=lambda r: self._set_sort_key(r.fields.set), reverse=reverse)
elif sort_field == 'name':
return sorted(records, key=lambda r: r.fields.name, reverse=reverse)
elif sort_field == 'year':
return sorted(records, key=lambda r: r.fields.year, reverse=reverse)
elif sort_field == 'parts':
return sorted(records, key=lambda r: r.fields.number_of_parts, reverse=reverse)
# Add more sort fields as needed
return records
def _set_sort_key(self, set_number: str) -> tuple:
"""Generate sort key for set numbers like '10121-1' -> (10121, 1)"""
try:
if '-' in set_number:
main_part, version_part = set_number.split('-', 1)
return (int(main_part), int(version_part))
else:
return (int(set_number), 0)
except (ValueError, TypeError):
# Fallback to string sorting if parsing fails
return (float('inf'), set_number)
# Sets with a minifigure part damaged
def damaged_minifigure(self, figure: str, /) -> Self:
# Save the parameters to the fields
@@ -93,6 +570,7 @@ class BrickSetList(BrickRecordList[BrickSet]):
**context: Any,
) -> None:
themes = set()
years = set()
if order is None:
order = self.order
@@ -102,20 +580,22 @@ class BrickSetList(BrickRecordList[BrickSet]):
override_query=override_query,
order=order,
limit=limit,
owners=BrickSetOwnerList.as_columns(),
statuses=BrickSetStatusList.as_columns(),
tags=BrickSetTagList.as_columns(),
**context
):
brickset = BrickSet(record=record)
self.records.append(brickset)
if do_theme:
themes.add(brickset.theme.name)
if hasattr(brickset, 'fields') and hasattr(brickset.fields, 'year') and brickset.fields.year:
years.add(brickset.fields.year)
# Convert the set into a list and sort it
if do_theme:
self.themes = list(themes)
self.themes.sort()
self.years = list(years)
self.years.sort(reverse=True) # Most recent years first
# Sets missing a minifigure part
def missing_minifigure(self, figure: str, /) -> Self:

View File

@@ -6,6 +6,8 @@ from flask_socketio import SocketIO
from .instructions import BrickInstructions
from .instructions_list import BrickInstructionsList
from .peeron_instructions import PeeronInstructions, PeeronPage
from .peeron_pdf import PeeronPDF
from .set import BrickSet
from .socket_decorator import authenticated_socket, rebrickable_socket
from .sql import close as sql_close
@@ -18,8 +20,10 @@ MESSAGES: Final[dict[str, str]] = {
'CONNECT': 'connect',
'DISCONNECT': 'disconnect',
'DOWNLOAD_INSTRUCTIONS': 'download_instructions',
'DOWNLOAD_PEERON_PAGES': 'download_peeron_pages',
'FAIL': 'fail',
'IMPORT_SET': 'import_set',
'LOAD_PEERON_PAGES': 'load_peeron_pages',
'LOAD_SET': 'load_set',
'PROGRESS': 'progress',
'SET_LOADED': 'set_loaded',
@@ -106,6 +110,84 @@ class BrickSocket(object):
BrickInstructionsList(force=True)
@self.socket.on(MESSAGES['LOAD_PEERON_PAGES'], namespace=self.namespace) # noqa: E501
def load_peeron_pages(data: dict[str, Any], /) -> None:
logger.debug('Socket: LOAD_PEERON_PAGES={data} (from: {fr})'.format(
data=data, fr=request.remote_addr))
try:
set_number = data.get('set', '')
if not set_number:
self.fail(message="Set number is required")
return
# Create Peeron instructions instance with socket for progress reporting
peeron = PeeronInstructions(set_number, socket=self)
# Find pages (this will report progress for thumbnail caching)
pages = peeron.find_pages()
# Complete the operation (JavaScript will handle redirect)
self.complete(message=f"Found {len(pages)} instruction pages on Peeron")
except Exception as e:
logger.error(f"Error in load_peeron_pages: {e}")
self.fail(message=f"Error loading Peeron pages: {e}")
@self.socket.on(MESSAGES['DOWNLOAD_PEERON_PAGES'], namespace=self.namespace) # noqa: E501
@authenticated_socket(self)
def download_peeron_pages(data: dict[str, Any], /) -> None:
logger.debug('Socket: DOWNLOAD_PEERON_PAGES={data} (from: {fr})'.format(
data=data,
fr=request.sid, # type: ignore
))
try:
# Extract data from the request
set_number = data.get('set', '')
pages_data = data.get('pages', [])
if not set_number:
raise ValueError("Set number is required")
if not pages_data:
raise ValueError("No pages selected")
# Parse set number
if '-' in set_number:
parts = set_number.split('-', 1)
set_num = parts[0]
version_num = parts[1] if len(parts) > 1 else '1'
else:
set_num = set_number
version_num = '1'
# Convert page data to PeeronPage objects
pages = []
for page_data in pages_data:
page = PeeronPage(
page_number=page_data.get('page_number', ''),
original_image_url=page_data.get('original_image_url', ''),
cached_full_image_path=page_data.get('cached_full_image_path', ''),
cached_thumbnail_url='', # Not needed for PDF generation
alt_text=page_data.get('alt_text', ''),
rotation=page_data.get('rotation', 0)
)
pages.append(page)
# Create PDF generator and start download
pdf_generator = PeeronPDF(set_num, version_num, pages, socket=self)
pdf_generator.create_pdf()
# Note: Cache cleanup is handled automatically by pdf_generator.create_pdf()
# Refresh instructions list to include new PDF
BrickInstructionsList(force=True)
except Exception as e:
logger.error(f"Error in download_peeron_pages: {e}")
self.fail(message=f"Error downloading Peeron pages: {e}")
@self.socket.on(MESSAGES['IMPORT_SET'], namespace=self.namespace)
@rebrickable_socket(self)
def import_set(data: dict[str, Any], /) -> None:

View File

@@ -0,0 +1,9 @@
-- description: Add checked field to bricktracker_parts table for part walkthrough tracking
BEGIN TRANSACTION;
-- Add checked field to the bricktracker_parts table
-- This allows users to track which parts they have checked during walkthroughs
ALTER TABLE "bricktracker_parts" ADD COLUMN "checked" BOOLEAN DEFAULT 0;
COMMIT;

View File

@@ -35,3 +35,7 @@ ORDER BY {{ order }}
{% if limit %}
LIMIT {{ limit }}
{% endif %}
{% if offset %}
OFFSET {{ offset }}
{% endif %}

View File

@@ -34,6 +34,12 @@ ON "bricktracker_minifigures"."id" IS NOT DISTINCT FROM "problem_join"."id"
AND "rebrickable_minifigures"."figure" IS NOT DISTINCT FROM "problem_join"."figure"
{% endblock %}
{% block where %}
{% if search_query %}
WHERE (LOWER("rebrickable_minifigures"."name") LIKE LOWER('%{{ search_query }}%'))
{% endif %}
{% endblock %}
{% block group %}
GROUP BY
"rebrickable_minifigures"."figure"

View File

@@ -60,8 +60,15 @@ AND "rebrickable_minifigures"."figure" IS NOT DISTINCT FROM "problem_join"."figu
{% endblock %}
{% block where %}
{% set conditions = [] %}
{% if owner_id and owner_id != 'all' %}
WHERE "bricktracker_set_owners"."owner_{{ owner_id }}" = 1
{% set _ = conditions.append('"bricktracker_set_owners"."owner_' ~ owner_id ~ '" = 1') %}
{% endif %}
{% if search_query %}
{% set _ = conditions.append('(LOWER("rebrickable_minifigures"."name") LIKE LOWER(\'%' ~ search_query ~ '%\'))') %}
{% endif %}
{% if conditions %}
WHERE {{ conditions | join(' AND ') }}
{% endif %}
{% endblock %}

View File

@@ -9,6 +9,7 @@ SELECT
--"bricktracker_parts"."rebrickable_inventory",
"bricktracker_parts"."missing",
"bricktracker_parts"."damaged",
"bricktracker_parts"."checked",
--"rebrickable_parts"."part",
--"rebrickable_parts"."color_id",
"rebrickable_parts"."color_name",
@@ -60,3 +61,7 @@ ORDER BY {{ order }}
{% if limit %}
LIMIT {{ limit }}
{% endif %}
{% if offset %}
OFFSET {{ offset }}
{% endif %}

View File

@@ -0,0 +1,19 @@
SELECT DISTINCT
"rebrickable_parts"."color_id" AS "color_id",
"rebrickable_parts"."color_name" AS "color_name",
"rebrickable_parts"."color_rgb" AS "color_rgb"
FROM "rebrickable_parts"
INNER JOIN "bricktracker_parts"
ON "bricktracker_parts"."part" IS NOT DISTINCT FROM "rebrickable_parts"."part"
AND "bricktracker_parts"."color" IS NOT DISTINCT FROM "rebrickable_parts"."color_id"
{% if owner_id and owner_id != 'all' %}
INNER JOIN "bricktracker_sets"
ON "bricktracker_parts"."id" IS NOT DISTINCT FROM "bricktracker_sets"."id"
INNER JOIN "bricktracker_set_owners"
ON "bricktracker_sets"."id" IS NOT DISTINCT FROM "bricktracker_set_owners"."id"
{% endif %}
WHERE ("bricktracker_parts"."missing" > 0 OR "bricktracker_parts"."damaged" > 0)
{% if owner_id and owner_id != 'all' %}
AND "bricktracker_set_owners"."owner_{{ owner_id }}" = 1
{% endif %}
ORDER BY "rebrickable_parts"."color_name" ASC

View File

@@ -27,8 +27,19 @@ AND "bricktracker_parts"."figure" IS NOT DISTINCT FROM "bricktracker_minifigures
{% endblock %}
{% block where %}
{% set conditions = [] %}
{% if color_id and color_id != 'all' %}
WHERE "bricktracker_parts"."color" = {{ color_id }}
{% set _ = conditions.append('"bricktracker_parts"."color" = ' ~ color_id) %}
{% endif %}
{% if search_query %}
{% set search_condition = '(LOWER("rebrickable_parts"."name") LIKE LOWER(\'%' ~ search_query ~ '%\') OR LOWER("rebrickable_parts"."color_name") LIKE LOWER(\'%' ~ search_query ~ '%\') OR LOWER("bricktracker_parts"."part") LIKE LOWER(\'%' ~ search_query ~ '%\'))' %}
{% set _ = conditions.append(search_condition) %}
{% endif %}
{% if skip_spare_parts %}
{% set _ = conditions.append('"bricktracker_parts"."spare" = 0') %}
{% endif %}
{% if conditions %}
WHERE {{ conditions | join(' AND ') }}
{% endif %}
{% endblock %}

View File

@@ -56,17 +56,22 @@ AND "bricktracker_parts"."figure" IS NOT DISTINCT FROM "bricktracker_minifigures
{% endblock %}
{% block where %}
{% set has_where = false %}
{% set conditions = [] %}
{% if owner_id and owner_id != 'all' %}
WHERE "bricktracker_set_owners"."owner_{{ owner_id }}" = 1
{% set has_where = true %}
{% set _ = conditions.append('"bricktracker_set_owners"."owner_' ~ owner_id ~ '" = 1') %}
{% endif %}
{% if color_id and color_id != 'all' %}
{% if has_where %}
AND "bricktracker_parts"."color" = {{ color_id }}
{% else %}
WHERE "bricktracker_parts"."color" = {{ color_id }}
{% set _ = conditions.append('"bricktracker_parts"."color" = ' ~ color_id) %}
{% endif %}
{% if search_query %}
{% set search_condition = '(LOWER("rebrickable_parts"."name") LIKE LOWER(\'%' ~ search_query ~ '%\') OR LOWER("rebrickable_parts"."color_name") LIKE LOWER(\'%' ~ search_query ~ '%\') OR LOWER("bricktracker_parts"."part") LIKE LOWER(\'%' ~ search_query ~ '%\'))' %}
{% set _ = conditions.append(search_condition) %}
{% endif %}
{% if skip_spare_parts %}
{% set _ = conditions.append('"bricktracker_parts"."spare" = 0') %}
{% endif %}
{% if conditions %}
WHERE {{ conditions | join(' AND ') }}
{% endif %}
{% endblock %}

View File

@@ -1,30 +1,78 @@
{% extends 'part/base/base.sql' %}
{% block total_missing %}
{% if owner_id and owner_id != 'all' %}
SUM(CASE WHEN "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN "bricktracker_parts"."missing" ELSE 0 END) AS "total_missing",
{% else %}
SUM("bricktracker_parts"."missing") AS "total_missing",
{% endif %}
{% endblock %}
{% block total_damaged %}
{% if owner_id and owner_id != 'all' %}
SUM(CASE WHEN "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN "bricktracker_parts"."damaged" ELSE 0 END) AS "total_damaged",
{% else %}
SUM("bricktracker_parts"."damaged") AS "total_damaged",
{% endif %}
{% endblock %}
{% block total_quantity %}
{% if owner_id and owner_id != 'all' %}
SUM(CASE WHEN "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN "bricktracker_parts"."quantity" * IFNULL("bricktracker_minifigures"."quantity", 1) ELSE 0 END) AS "total_quantity",
{% else %}
SUM("bricktracker_parts"."quantity" * IFNULL("bricktracker_minifigures"."quantity", 1)) AS "total_quantity",
{% endif %}
{% endblock %}
{% block total_sets %}
IFNULL(COUNT("bricktracker_parts"."id"), 0) - IFNULL(COUNT("bricktracker_parts"."figure"), 0) AS "total_sets",
{% if owner_id and owner_id != 'all' %}
COUNT(DISTINCT CASE WHEN "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN "bricktracker_parts"."id" ELSE NULL END) AS "total_sets",
{% else %}
COUNT(DISTINCT "bricktracker_parts"."id") AS "total_sets",
{% endif %}
{% endblock %}
{% block total_minifigures %}
{% if owner_id and owner_id != 'all' %}
SUM(CASE WHEN "bricktracker_set_owners"."owner_{{ owner_id }}" = 1 THEN IFNULL("bricktracker_minifigures"."quantity", 0) ELSE 0 END) AS "total_minifigures"
{% else %}
SUM(IFNULL("bricktracker_minifigures"."quantity", 0)) AS "total_minifigures"
{% endif %}
{% endblock %}
{% block join %}
-- Join with sets to get owner information
INNER JOIN "bricktracker_sets"
ON "bricktracker_parts"."id" IS NOT DISTINCT FROM "bricktracker_sets"."id"
-- Left join with set owners (using dynamic columns)
LEFT JOIN "bricktracker_set_owners"
ON "bricktracker_sets"."id" IS NOT DISTINCT FROM "bricktracker_set_owners"."id"
-- Left join with minifigures
LEFT JOIN "bricktracker_minifigures"
ON "bricktracker_parts"."id" IS NOT DISTINCT FROM "bricktracker_minifigures"."id"
AND "bricktracker_parts"."figure" IS NOT DISTINCT FROM "bricktracker_minifigures"."figure"
{% endblock %}
{% block where %}
WHERE "bricktracker_parts"."missing" > 0
OR "bricktracker_parts"."damaged" > 0
{% set conditions = [] %}
-- Always filter for problematic parts
{% set _ = conditions.append('("bricktracker_parts"."missing" > 0 OR "bricktracker_parts"."damaged" > 0)') %}
{% if owner_id and owner_id != 'all' %}
{% set _ = conditions.append('"bricktracker_set_owners"."owner_' ~ owner_id ~ '" = 1') %}
{% endif %}
{% if color_id and color_id != 'all' %}
{% set _ = conditions.append('"bricktracker_parts"."color" = ' ~ color_id) %}
{% endif %}
{% if search_query %}
{% set search_condition = '(LOWER("rebrickable_parts"."name") LIKE LOWER(\'%' ~ search_query ~ '%\') OR LOWER("rebrickable_parts"."color_name") LIKE LOWER(\'%' ~ search_query ~ '%\') OR LOWER("bricktracker_parts"."part") LIKE LOWER(\'%' ~ search_query ~ '%\'))' %}
{% set _ = conditions.append(search_condition) %}
{% endif %}
{% if skip_spare_parts %}
{% set _ = conditions.append('"bricktracker_parts"."spare" = 0') %}
{% endif %}
WHERE {{ conditions | join(' AND ') }}
{% endblock %}
{% block group %}

View File

@@ -0,0 +1,7 @@
UPDATE "bricktracker_parts"
SET "checked" = :checked
WHERE "bricktracker_parts"."id" IS NOT DISTINCT FROM :id
AND "bricktracker_parts"."figure" IS NOT DISTINCT FROM :figure
AND "bricktracker_parts"."part" IS NOT DISTINCT FROM :part
AND "bricktracker_parts"."color" IS NOT DISTINCT FROM :color
AND "bricktracker_parts"."spare" IS NOT DISTINCT FROM :spare

View File

@@ -49,3 +49,7 @@ ORDER BY {{ order }}
{% if limit %}
LIMIT {{ limit }}
{% endif %}
{% if offset %}
OFFSET {{ offset }}
{% endif %}

View File

@@ -0,0 +1,4 @@
SELECT COUNT(*) as count
FROM "bricktracker_sets"
INNER JOIN "rebrickable_sets" ON "bricktracker_sets"."set" = "rebrickable_sets"."set"
WHERE "rebrickable_sets"."theme_id" = {{ theme_id }}

View File

@@ -1 +1,8 @@
{% extends 'set/base/full.sql' %}
{% block where %}
{% if search_query %}
WHERE (LOWER("rebrickable_sets"."name") LIKE LOWER('%{{ search_query }}%')
OR LOWER("rebrickable_sets"."set") LIKE LOWER('%{{ search_query }}%'))
{% endif %}
{% endblock %}

View File

@@ -0,0 +1,73 @@
{% extends 'set/base/full.sql' %}
{% block where %}
WHERE 1=1
{% if search_query %}
AND (LOWER("rebrickable_sets"."name") LIKE LOWER('%{{ search_query }}%')
OR LOWER("rebrickable_sets"."set") LIKE LOWER('%{{ search_query }}%'))
{% endif %}
{% if theme_filter %}
AND "rebrickable_sets"."theme_id" = {{ theme_filter }}
{% endif %}
{% if year_filter %}
AND "rebrickable_sets"."year" = {{ year_filter }}
{% endif %}
{% if storage_filter %}
AND "bricktracker_sets"."storage" = '{{ storage_filter }}'
{% endif %}
{% if purchase_location_filter %}
AND "bricktracker_sets"."purchase_location" = '{{ purchase_location_filter }}'
{% endif %}
{% if status_filter %}
{% if status_filter == 'has-missing' %}
AND IFNULL("problem_join"."total_missing", 0) > 0
{% elif status_filter == '-has-missing' %}
AND IFNULL("problem_join"."total_missing", 0) = 0
{% elif status_filter == 'has-damaged' %}
AND IFNULL("problem_join"."total_damaged", 0) > 0
{% elif status_filter == '-has-damaged' %}
AND IFNULL("problem_join"."total_damaged", 0) = 0
{% elif status_filter == 'has-storage' %}
AND "bricktracker_sets"."storage" IS NOT NULL AND "bricktracker_sets"."storage" != ''
{% elif status_filter == '-has-storage' %}
AND ("bricktracker_sets"."storage" IS NULL OR "bricktracker_sets"."storage" = '')
{% elif status_filter.startswith('status-') %}
AND EXISTS (
SELECT 1 FROM "bricktracker_set_statuses"
WHERE "bricktracker_set_statuses"."id" = "bricktracker_sets"."id"
AND "bricktracker_set_statuses"."{{ status_filter.replace('-', '_') }}" = 1
)
{% elif status_filter.startswith('-status-') %}
AND NOT EXISTS (
SELECT 1 FROM "bricktracker_set_statuses"
WHERE "bricktracker_set_statuses"."id" = "bricktracker_sets"."id"
AND "bricktracker_set_statuses"."{{ status_filter[1:].replace('-', '_') }}" = 1
)
{% endif %}
{% endif %}
{% if owner_filter %}
{% if owner_filter.startswith('owner-') %}
AND EXISTS (
SELECT 1 FROM "bricktracker_set_owners"
WHERE "bricktracker_set_owners"."id" = "bricktracker_sets"."id"
AND "bricktracker_set_owners"."{{ owner_filter.replace('-', '_') }}" = 1
)
{% endif %}
{% endif %}
{% if tag_filter %}
{% if tag_filter.startswith('tag-') %}
AND EXISTS (
SELECT 1 FROM "bricktracker_set_tags"
WHERE "bricktracker_set_tags"."id" = "bricktracker_sets"."id"
AND "bricktracker_set_tags"."{{ tag_filter.replace('-', '_') }}" = 1
)
{% endif %}
{% endif %}
{% endblock %}

View File

@@ -0,0 +1,172 @@
SELECT
(SELECT MIN("id") FROM "bricktracker_sets" WHERE "set" = "rebrickable_sets"."set") AS "id",
"rebrickable_sets"."set",
"rebrickable_sets"."number",
"rebrickable_sets"."version",
"rebrickable_sets"."name",
"rebrickable_sets"."year",
"rebrickable_sets"."theme_id",
"rebrickable_sets"."number_of_parts",
"rebrickable_sets"."image",
"rebrickable_sets"."url",
COUNT("bricktracker_sets"."id") AS "instance_count",
IFNULL(SUM("problem_join"."total_missing"), 0) AS "total_missing",
IFNULL(SUM("problem_join"."total_damaged"), 0) AS "total_damaged",
IFNULL(MAX("minifigures_join"."total"), 0) AS "total_minifigures",
-- Keep one representative instance for display purposes
GROUP_CONCAT("bricktracker_sets"."id", '|') AS "instance_ids",
REPLACE(GROUP_CONCAT(DISTINCT "bricktracker_sets"."storage"), ',', '|') AS "storage",
MIN("bricktracker_sets"."purchase_date") AS "purchase_date",
MAX("bricktracker_sets"."purchase_date") AS "purchase_date_max",
REPLACE(GROUP_CONCAT(DISTINCT "bricktracker_sets"."purchase_location"), ',', '|') AS "purchase_location",
ROUND(AVG("bricktracker_sets"."purchase_price"), 1) AS "purchase_price"
{% block owners %}
{% if owners_dict %}
{% for column, uuid in owners_dict.items() %}
, MAX("bricktracker_set_owners"."{{ column }}") AS "{{ column }}"
{% endfor %}
{% endif %}
{% endblock %}
{% block tags %}
{% if tags_dict %}
{% for column, uuid in tags_dict.items() %}
, MAX("bricktracker_set_tags"."{{ column }}") AS "{{ column }}"
{% endfor %}
{% endif %}
{% endblock %}
{% block statuses %}
{% if statuses_dict %}
{% for column, uuid in statuses_dict.items() %}
, MAX("bricktracker_set_statuses"."{{ column }}") AS "{{ column }}"
, IFNULL(SUM("bricktracker_set_statuses"."{{ column }}"), 0) AS "{{ column }}_count"
{% endfor %}
{% endif %}
{% endblock %}
FROM "bricktracker_sets"
INNER JOIN "rebrickable_sets"
ON "bricktracker_sets"."set" IS NOT DISTINCT FROM "rebrickable_sets"."set"
-- LEFT JOIN + SELECT to avoid messing the total
LEFT JOIN (
SELECT
"bricktracker_parts"."id",
SUM("bricktracker_parts"."missing") AS "total_missing",
SUM("bricktracker_parts"."damaged") AS "total_damaged"
FROM "bricktracker_parts"
GROUP BY "bricktracker_parts"."id"
) "problem_join"
ON "bricktracker_sets"."id" IS NOT DISTINCT FROM "problem_join"."id"
-- LEFT JOIN + SELECT to avoid messing the total
LEFT JOIN (
SELECT
"bricktracker_minifigures"."id",
SUM("bricktracker_minifigures"."quantity") AS "total"
FROM "bricktracker_minifigures"
GROUP BY "bricktracker_minifigures"."id"
) "minifigures_join"
ON "bricktracker_sets"."id" IS NOT DISTINCT FROM "minifigures_join"."id"
{% if owners_dict %}
LEFT JOIN "bricktracker_set_owners"
ON "bricktracker_sets"."id" IS NOT DISTINCT FROM "bricktracker_set_owners"."id"
{% endif %}
{% if statuses_dict %}
LEFT JOIN "bricktracker_set_statuses"
ON "bricktracker_sets"."id" IS NOT DISTINCT FROM "bricktracker_set_statuses"."id"
{% endif %}
{% if tags_dict %}
LEFT JOIN "bricktracker_set_tags"
ON "bricktracker_sets"."id" IS NOT DISTINCT FROM "bricktracker_set_tags"."id"
{% endif %}
{% block where %}
WHERE 1=1
{% if search_query %}
AND (LOWER("rebrickable_sets"."name") LIKE LOWER('%{{ search_query }}%')
OR LOWER("rebrickable_sets"."set") LIKE LOWER('%{{ search_query }}%'))
{% endif %}
{% if theme_filter %}
AND "rebrickable_sets"."theme_id" = {{ theme_filter }}
{% endif %}
{% if year_filter %}
AND "rebrickable_sets"."year" = {{ year_filter }}
{% endif %}
{% if storage_filter %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND bs_filter."storage" = '{{ storage_filter }}'
)
{% endif %}
{% if purchase_location_filter %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND bs_filter."purchase_location" = '{{ purchase_location_filter }}'
)
{% endif %}
{% if status_filter %}
{% if status_filter == 'has-storage' %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND bs_filter."storage" IS NOT NULL AND bs_filter."storage" != ''
)
{% elif status_filter == '-has-storage' %}
AND NOT EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND bs_filter."storage" IS NOT NULL AND bs_filter."storage" != ''
)
{% elif status_filter.startswith('status-') %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
JOIN "bricktracker_set_statuses" ON bs_filter."id" = "bricktracker_set_statuses"."id"
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND "bricktracker_set_statuses"."{{ status_filter.replace('-', '_') }}" = 1
)
{% elif status_filter.startswith('-status-') %}
AND NOT EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
JOIN "bricktracker_set_statuses" ON bs_filter."id" = "bricktracker_set_statuses"."id"
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND "bricktracker_set_statuses"."{{ status_filter[1:].replace('-', '_') }}" = 1
)
{% endif %}
{% endif %}
{% endblock %}
GROUP BY "rebrickable_sets"."set"
{% if status_filter %}
{% if status_filter == 'has-missing' %}
HAVING IFNULL(SUM("problem_join"."total_missing"), 0) > 0
{% elif status_filter == '-has-missing' %}
HAVING IFNULL(SUM("problem_join"."total_missing"), 0) = 0
{% elif status_filter == 'has-damaged' %}
HAVING IFNULL(SUM("problem_join"."total_damaged"), 0) > 0
{% elif status_filter == '-has-damaged' %}
HAVING IFNULL(SUM("problem_join"."total_damaged"), 0) = 0
{% endif %}
{% endif %}
{% if order %}
ORDER BY {{ order }}
{% endif %}
{% if limit %}
LIMIT {{ limit }}
{% endif %}
{% if offset %}
OFFSET {{ offset }}
{% endif %}

View File

@@ -5,7 +5,7 @@ WHERE "bricktracker_sets"."id" IN (
SELECT "bricktracker_parts"."id"
FROM "bricktracker_parts"
WHERE "bricktracker_parts"."figure" IS NOT DISTINCT FROM :figure
AND "bricktracker_parts"."missing" > 0
AND "bricktracker_parts"."damaged" > 0
GROUP BY "bricktracker_parts"."id"
)
{% endblock %}

View File

@@ -0,0 +1,87 @@
SELECT DISTINCT "rebrickable_sets"."theme_id"
FROM "bricktracker_sets"
INNER JOIN "rebrickable_sets"
ON "bricktracker_sets"."set" IS NOT DISTINCT FROM "rebrickable_sets"."set"
{% block where %}
WHERE 1=1
{% if search_query %}
AND (LOWER("rebrickable_sets"."name") LIKE LOWER('%{{ search_query }}%')
OR LOWER("rebrickable_sets"."set") LIKE LOWER('%{{ search_query }}%'))
{% endif %}
{% if storage_filter %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND bs_filter."storage" = '{{ storage_filter }}'
)
{% endif %}
{% if purchase_location_filter %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND bs_filter."purchase_location" = '{{ purchase_location_filter }}'
)
{% endif %}
{% if status_filter %}
{% if status_filter == 'has-storage' %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND bs_filter."storage" IS NOT NULL AND bs_filter."storage" != ''
)
{% elif status_filter == '-has-storage' %}
AND NOT EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND bs_filter."storage" IS NOT NULL AND bs_filter."storage" != ''
)
{% elif status_filter.startswith('status-') %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
JOIN "bricktracker_set_statuses" ON bs_filter."id" = "bricktracker_set_statuses"."id"
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND "bricktracker_set_statuses"."{{ status_filter.replace('-', '_') }}" = 1
)
{% elif status_filter.startswith('-status-') %}
AND NOT EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
JOIN "bricktracker_set_statuses" ON bs_filter."id" = "bricktracker_set_statuses"."id"
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND "bricktracker_set_statuses"."{{ status_filter[1:].replace('-', '_') }}" = 1
)
{% elif status_filter == 'has-missing' %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
JOIN "bricktracker_parts" ON bs_filter."id" = "bricktracker_parts"."id"
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND "bricktracker_parts"."missing" > 0
)
{% elif status_filter == '-has-missing' %}
AND NOT EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
JOIN "bricktracker_parts" ON bs_filter."id" = "bricktracker_parts"."id"
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND "bricktracker_parts"."missing" > 0
)
{% elif status_filter == 'has-damaged' %}
AND EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
JOIN "bricktracker_parts" ON bs_filter."id" = "bricktracker_parts"."id"
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND "bricktracker_parts"."damaged" > 0
)
{% elif status_filter == '-has-damaged' %}
AND NOT EXISTS (
SELECT 1 FROM "bricktracker_sets" bs_filter
JOIN "bricktracker_parts" ON bs_filter."id" = "bricktracker_parts"."id"
WHERE bs_filter."set" = "rebrickable_sets"."set"
AND "bricktracker_parts"."damaged" > 0
)
{% endif %}
{% endif %}
{% endblock %}

View File

@@ -0,0 +1,33 @@
-- Statistics Overview Query
-- Provides statistics for BrickTracker dashboard
SELECT
-- Basic counts
(SELECT COUNT(*) FROM "bricktracker_sets") AS "total_sets",
(SELECT COUNT(DISTINCT "bricktracker_sets"."set") FROM "bricktracker_sets") AS "unique_sets",
(SELECT COUNT(*) FROM "rebrickable_sets" WHERE "rebrickable_sets"."set" IN (SELECT DISTINCT "set" FROM "bricktracker_sets")) AS "unique_rebrickable_sets",
-- Parts statistics
(SELECT COUNT(*) FROM "bricktracker_parts") AS "total_part_instances",
(SELECT SUM("bricktracker_parts"."quantity") FROM "bricktracker_parts") AS "total_parts_count",
(SELECT COUNT(DISTINCT "bricktracker_parts"."part") FROM "bricktracker_parts") AS "unique_parts",
(SELECT SUM("bricktracker_parts"."missing") FROM "bricktracker_parts") AS "total_missing_parts",
(SELECT SUM("bricktracker_parts"."damaged") FROM "bricktracker_parts") AS "total_damaged_parts",
-- Minifigures statistics
(SELECT COUNT(*) FROM "bricktracker_minifigures") AS "total_minifigure_instances",
(SELECT SUM("bricktracker_minifigures"."quantity") FROM "bricktracker_minifigures") AS "total_minifigures_count",
(SELECT COUNT(DISTINCT "bricktracker_minifigures"."figure") FROM "bricktracker_minifigures") AS "unique_minifigures",
-- Financial statistics
(SELECT COUNT(*) FROM "bricktracker_sets" WHERE "purchase_price" IS NOT NULL) AS "sets_with_price",
(SELECT ROUND(SUM("purchase_price"), 2) FROM "bricktracker_sets" WHERE "purchase_price" IS NOT NULL) AS "total_cost",
(SELECT ROUND(AVG("purchase_price"), 2) FROM "bricktracker_sets" WHERE "purchase_price" IS NOT NULL) AS "average_cost",
(SELECT ROUND(MIN("purchase_price"), 2) FROM "bricktracker_sets" WHERE "purchase_price" IS NOT NULL) AS "minimum_cost",
(SELECT ROUND(MAX("purchase_price"), 2) FROM "bricktracker_sets" WHERE "purchase_price" IS NOT NULL) AS "maximum_cost",
-- Storage and location statistics
(SELECT COUNT(DISTINCT "storage") FROM "bricktracker_sets" WHERE "storage" IS NOT NULL) AS "storage_locations_used",
(SELECT COUNT(DISTINCT "purchase_location") FROM "bricktracker_sets" WHERE "purchase_location" IS NOT NULL) AS "purchase_locations_used",
(SELECT COUNT(*) FROM "bricktracker_sets" WHERE "storage" IS NOT NULL) AS "sets_with_storage",
(SELECT COUNT(*) FROM "bricktracker_sets" WHERE "purchase_location" IS NOT NULL) AS "sets_with_purchase_location"

View File

@@ -0,0 +1,45 @@
-- Purchase Location Statistics
-- Shows statistics grouped by purchase location
SELECT
"bricktracker_sets"."purchase_location" AS "location_id",
"bricktracker_metadata_purchase_locations"."name" AS "location_name",
COUNT("bricktracker_sets"."id") AS "set_count",
COUNT(DISTINCT "bricktracker_sets"."set") AS "unique_set_count",
SUM("rebrickable_sets"."number_of_parts") AS "total_parts",
ROUND(AVG("rebrickable_sets"."number_of_parts"), 0) AS "avg_parts_per_set",
-- Financial statistics per purchase location
COUNT(CASE WHEN "bricktracker_sets"."purchase_price" IS NOT NULL THEN 1 END) AS "sets_with_price",
ROUND(SUM("bricktracker_sets"."purchase_price"), 2) AS "total_spent",
ROUND(AVG("bricktracker_sets"."purchase_price"), 2) AS "avg_price",
ROUND(MIN("bricktracker_sets"."purchase_price"), 2) AS "min_price",
ROUND(MAX("bricktracker_sets"."purchase_price"), 2) AS "max_price",
-- Date range statistics
MIN("bricktracker_sets"."purchase_date") AS "first_purchase",
MAX("bricktracker_sets"."purchase_date") AS "latest_purchase",
-- Problem statistics per purchase location
COALESCE(SUM("problem_stats"."missing_parts"), 0) AS "missing_parts",
COALESCE(SUM("problem_stats"."damaged_parts"), 0) AS "damaged_parts",
-- Minifigure statistics per purchase location
COALESCE(SUM("minifigure_stats"."minifigure_count"), 0) AS "total_minifigures"
FROM "bricktracker_sets"
INNER JOIN "rebrickable_sets" ON "bricktracker_sets"."set" = "rebrickable_sets"."set"
LEFT JOIN "bricktracker_metadata_purchase_locations" ON "bricktracker_sets"."purchase_location" = "bricktracker_metadata_purchase_locations"."id"
LEFT JOIN (
SELECT
"bricktracker_parts"."id",
SUM("bricktracker_parts"."missing") AS "missing_parts",
SUM("bricktracker_parts"."damaged") AS "damaged_parts"
FROM "bricktracker_parts"
GROUP BY "bricktracker_parts"."id"
) "problem_stats" ON "bricktracker_sets"."id" = "problem_stats"."id"
LEFT JOIN (
SELECT
"bricktracker_minifigures"."id",
SUM("bricktracker_minifigures"."quantity") AS "minifigure_count"
FROM "bricktracker_minifigures"
GROUP BY "bricktracker_minifigures"."id"
) "minifigure_stats" ON "bricktracker_sets"."id" = "minifigure_stats"."id"
WHERE "bricktracker_sets"."purchase_location" IS NOT NULL
GROUP BY "bricktracker_sets"."purchase_location", "bricktracker_metadata_purchase_locations"."name"
ORDER BY "set_count" DESC, "location_name" ASC

View File

@@ -0,0 +1,49 @@
-- Purchases by Year Statistics
-- Shows statistics grouped by purchase year (when you bought the sets)
SELECT
strftime('%Y', datetime("bricktracker_sets"."purchase_date", 'unixepoch')) AS "purchase_year",
COUNT("bricktracker_sets"."id") AS "total_sets",
COUNT(DISTINCT "bricktracker_sets"."set") AS "unique_sets",
SUM("rebrickable_sets"."number_of_parts") AS "total_parts",
ROUND(AVG("rebrickable_sets"."number_of_parts"), 0) AS "avg_parts_per_set",
-- Financial statistics per purchase year
COUNT(CASE WHEN "bricktracker_sets"."purchase_price" IS NOT NULL THEN 1 END) AS "sets_with_price",
ROUND(SUM("bricktracker_sets"."purchase_price"), 2) AS "total_spent",
ROUND(AVG("bricktracker_sets"."purchase_price"), 2) AS "avg_price_per_set",
ROUND(MIN("bricktracker_sets"."purchase_price"), 2) AS "min_price",
ROUND(MAX("bricktracker_sets"."purchase_price"), 2) AS "max_price",
-- Release year statistics for sets purchased in this year
MIN("rebrickable_sets"."year") AS "oldest_set_year",
MAX("rebrickable_sets"."year") AS "newest_set_year",
ROUND(AVG("rebrickable_sets"."year"), 0) AS "avg_set_release_year",
-- Problem statistics per purchase year
COALESCE(SUM("problem_stats"."missing_parts"), 0) AS "missing_parts",
COALESCE(SUM("problem_stats"."damaged_parts"), 0) AS "damaged_parts",
-- Minifigure statistics per purchase year
COALESCE(SUM("minifigure_stats"."minifigure_count"), 0) AS "total_minifigures",
-- Diversity statistics per purchase year
COUNT(DISTINCT "rebrickable_sets"."theme_id") AS "unique_themes",
COUNT(DISTINCT "bricktracker_sets"."purchase_location") AS "unique_purchase_locations",
-- Monthly statistics within the year
COUNT(DISTINCT strftime('%m', datetime("bricktracker_sets"."purchase_date", 'unixepoch'))) AS "months_with_purchases"
FROM "bricktracker_sets"
INNER JOIN "rebrickable_sets" ON "bricktracker_sets"."set" = "rebrickable_sets"."set"
LEFT JOIN (
SELECT
"bricktracker_parts"."id",
SUM("bricktracker_parts"."missing") AS "missing_parts",
SUM("bricktracker_parts"."damaged") AS "damaged_parts"
FROM "bricktracker_parts"
GROUP BY "bricktracker_parts"."id"
) "problem_stats" ON "bricktracker_sets"."id" = "problem_stats"."id"
LEFT JOIN (
SELECT
"bricktracker_minifigures"."id",
SUM("bricktracker_minifigures"."quantity") AS "minifigure_count"
FROM "bricktracker_minifigures"
GROUP BY "bricktracker_minifigures"."id"
) "minifigure_stats" ON "bricktracker_sets"."id" = "minifigure_stats"."id"
WHERE "bricktracker_sets"."purchase_date" IS NOT NULL
GROUP BY strftime('%Y', datetime("bricktracker_sets"."purchase_date", 'unixepoch'))
ORDER BY "purchase_year" DESC

View File

@@ -0,0 +1,44 @@
-- Sets by Year Statistics
-- Shows statistics grouped by LEGO set release year
SELECT
"rebrickable_sets"."year",
COUNT("bricktracker_sets"."id") AS "total_sets",
COUNT(DISTINCT "bricktracker_sets"."set") AS "unique_sets",
SUM("rebrickable_sets"."number_of_parts") AS "total_parts",
ROUND(AVG("rebrickable_sets"."number_of_parts"), 0) AS "avg_parts_per_set",
MIN("rebrickable_sets"."number_of_parts") AS "min_parts",
MAX("rebrickable_sets"."number_of_parts") AS "max_parts",
-- Financial statistics per year (release year)
COUNT(CASE WHEN "bricktracker_sets"."purchase_price" IS NOT NULL THEN 1 END) AS "sets_with_price",
ROUND(SUM("bricktracker_sets"."purchase_price"), 2) AS "total_spent",
ROUND(AVG("bricktracker_sets"."purchase_price"), 2) AS "avg_price_per_set",
ROUND(MIN("bricktracker_sets"."purchase_price"), 2) AS "min_price",
ROUND(MAX("bricktracker_sets"."purchase_price"), 2) AS "max_price",
-- Problem statistics per year
COALESCE(SUM("problem_stats"."missing_parts"), 0) AS "missing_parts",
COALESCE(SUM("problem_stats"."damaged_parts"), 0) AS "damaged_parts",
-- Minifigure statistics per year
COALESCE(SUM("minifigure_stats"."minifigure_count"), 0) AS "total_minifigures",
-- Theme diversity per year
COUNT(DISTINCT "rebrickable_sets"."theme_id") AS "unique_themes"
FROM "bricktracker_sets"
INNER JOIN "rebrickable_sets" ON "bricktracker_sets"."set" = "rebrickable_sets"."set"
LEFT JOIN (
SELECT
"bricktracker_parts"."id",
SUM("bricktracker_parts"."missing") AS "missing_parts",
SUM("bricktracker_parts"."damaged") AS "damaged_parts"
FROM "bricktracker_parts"
GROUP BY "bricktracker_parts"."id"
) "problem_stats" ON "bricktracker_sets"."id" = "problem_stats"."id"
LEFT JOIN (
SELECT
"bricktracker_minifigures"."id",
SUM("bricktracker_minifigures"."quantity") AS "minifigure_count"
FROM "bricktracker_minifigures"
GROUP BY "bricktracker_minifigures"."id"
) "minifigure_stats" ON "bricktracker_sets"."id" = "minifigure_stats"."id"
WHERE "rebrickable_sets"."year" IS NOT NULL
GROUP BY "rebrickable_sets"."year"
ORDER BY "rebrickable_sets"."year" DESC

View File

@@ -0,0 +1,40 @@
-- Storage Location Statistics
-- Shows statistics grouped by storage location
SELECT
"bricktracker_sets"."storage" AS "storage_id",
"bricktracker_metadata_storages"."name" AS "storage_name",
COUNT("bricktracker_sets"."id") AS "set_count",
COUNT(DISTINCT "bricktracker_sets"."set") AS "unique_set_count",
SUM("rebrickable_sets"."number_of_parts") AS "total_parts",
ROUND(AVG("rebrickable_sets"."number_of_parts"), 0) AS "avg_parts_per_set",
-- Financial statistics per storage
COUNT(CASE WHEN "bricktracker_sets"."purchase_price" IS NOT NULL THEN 1 END) AS "sets_with_price",
ROUND(SUM("bricktracker_sets"."purchase_price"), 2) AS "total_value",
ROUND(AVG("bricktracker_sets"."purchase_price"), 2) AS "avg_price",
-- Problem statistics per storage
COALESCE(SUM("problem_stats"."missing_parts"), 0) AS "missing_parts",
COALESCE(SUM("problem_stats"."damaged_parts"), 0) AS "damaged_parts",
-- Minifigure statistics per storage
COALESCE(SUM("minifigure_stats"."minifigure_count"), 0) AS "total_minifigures"
FROM "bricktracker_sets"
INNER JOIN "rebrickable_sets" ON "bricktracker_sets"."set" = "rebrickable_sets"."set"
LEFT JOIN "bricktracker_metadata_storages" ON "bricktracker_sets"."storage" = "bricktracker_metadata_storages"."id"
LEFT JOIN (
SELECT
"bricktracker_parts"."id",
SUM("bricktracker_parts"."missing") AS "missing_parts",
SUM("bricktracker_parts"."damaged") AS "damaged_parts"
FROM "bricktracker_parts"
GROUP BY "bricktracker_parts"."id"
) "problem_stats" ON "bricktracker_sets"."id" = "problem_stats"."id"
LEFT JOIN (
SELECT
"bricktracker_minifigures"."id",
SUM("bricktracker_minifigures"."quantity") AS "minifigure_count"
FROM "bricktracker_minifigures"
GROUP BY "bricktracker_minifigures"."id"
) "minifigure_stats" ON "bricktracker_sets"."id" = "minifigure_stats"."id"
WHERE "bricktracker_sets"."storage" IS NOT NULL
GROUP BY "bricktracker_sets"."storage", "bricktracker_metadata_storages"."name"
ORDER BY "set_count" DESC, "storage_name" ASC

View File

@@ -0,0 +1,39 @@
-- Theme Distribution Statistics
-- Shows statistics grouped by theme
SELECT
"rebrickable_sets"."theme_id",
COUNT("bricktracker_sets"."id") AS "set_count",
COUNT(DISTINCT "bricktracker_sets"."set") AS "unique_set_count",
SUM("rebrickable_sets"."number_of_parts") AS "total_parts",
ROUND(AVG("rebrickable_sets"."number_of_parts"), 0) AS "avg_parts_per_set",
MIN("rebrickable_sets"."year") AS "earliest_year",
MAX("rebrickable_sets"."year") AS "latest_year",
-- Financial statistics per theme
COUNT(CASE WHEN "bricktracker_sets"."purchase_price" IS NOT NULL THEN 1 END) AS "sets_with_price",
ROUND(SUM("bricktracker_sets"."purchase_price"), 2) AS "total_spent",
ROUND(AVG("bricktracker_sets"."purchase_price"), 2) AS "avg_price",
-- Problem statistics per theme
COALESCE(SUM("problem_stats"."missing_parts"), 0) AS "missing_parts",
COALESCE(SUM("problem_stats"."damaged_parts"), 0) AS "damaged_parts",
-- Minifigure statistics per theme
COALESCE(SUM("minifigure_stats"."minifigure_count"), 0) AS "total_minifigures"
FROM "bricktracker_sets"
INNER JOIN "rebrickable_sets" ON "bricktracker_sets"."set" = "rebrickable_sets"."set"
LEFT JOIN (
SELECT
"bricktracker_parts"."id",
SUM("bricktracker_parts"."missing") AS "missing_parts",
SUM("bricktracker_parts"."damaged") AS "damaged_parts"
FROM "bricktracker_parts"
GROUP BY "bricktracker_parts"."id"
) "problem_stats" ON "bricktracker_sets"."id" = "problem_stats"."id"
LEFT JOIN (
SELECT
"bricktracker_minifigures"."id",
SUM("bricktracker_minifigures"."quantity") AS "minifigure_count"
FROM "bricktracker_minifigures"
GROUP BY "bricktracker_minifigures"."id"
) "minifigure_stats" ON "bricktracker_sets"."id" = "minifigure_stats"."id"
GROUP BY "rebrickable_sets"."theme_id"
ORDER BY "set_count" DESC, "rebrickable_sets"."theme_id" ASC

132
bricktracker/statistics.py Normal file
View File

@@ -0,0 +1,132 @@
"""
Statistics module for BrickTracker
Provides statistics and analytics functionality
"""
import logging
from typing import Any
from .sql import BrickSQL
from .theme_list import BrickThemeList
logger = logging.getLogger(__name__)
class BrickStatistics:
"""Main statistics class providing overview and detailed statistics"""
def __init__(self):
self.sql = BrickSQL()
def get_overview(self) -> dict[str, Any]:
"""Get overview statistics"""
result = self.sql.fetchone('statistics/overview')
if result:
return dict(result)
return {}
def get_theme_statistics(self) -> list[dict[str, Any]]:
"""Get statistics grouped by theme with theme names"""
results = self.sql.fetchall('statistics/themes')
# Load theme list to get theme names
theme_list = BrickThemeList()
statistics = []
for row in results:
stat = dict(row)
# Add theme name from theme list
theme = theme_list.get(stat['theme_id'])
stat['theme_name'] = theme.name if theme else f"Theme {stat['theme_id']}"
statistics.append(stat)
return statistics
def get_storage_statistics(self) -> list[dict[str, Any]]:
"""Get statistics grouped by storage location"""
results = self.sql.fetchall('statistics/storage')
return [dict(row) for row in results]
def get_purchase_location_statistics(self) -> list[dict[str, Any]]:
"""Get statistics grouped by purchase location"""
results = self.sql.fetchall('statistics/purchase_locations')
return [dict(row) for row in results]
def get_financial_summary(self) -> dict[str, Any]:
"""Get financial summary from overview statistics"""
overview = self.get_overview()
return {
'total_cost': overview.get('total_cost', 0),
'average_cost': overview.get('average_cost', 0),
'minimum_cost': overview.get('minimum_cost', 0),
'maximum_cost': overview.get('maximum_cost', 0),
'sets_with_price': overview.get('sets_with_price', 0),
'total_sets': overview.get('total_sets', 0),
'percentage_with_price': round(
(overview.get('sets_with_price', 0) / max(overview.get('total_sets', 1), 1)) * 100, 1
)
}
def get_collection_summary(self) -> dict[str, Any]:
"""Get collection summary from overview statistics"""
overview = self.get_overview()
return {
'total_sets': overview.get('total_sets', 0),
'unique_sets': overview.get('unique_sets', 0),
'total_parts_count': overview.get('total_parts_count', 0),
'unique_parts': overview.get('unique_parts', 0),
'total_minifigures_count': overview.get('total_minifigures_count', 0),
'unique_minifigures': overview.get('unique_minifigures', 0),
'total_missing_parts': overview.get('total_missing_parts', 0),
'total_damaged_parts': overview.get('total_damaged_parts', 0),
'storage_locations_used': overview.get('storage_locations_used', 0),
'purchase_locations_used': overview.get('purchase_locations_used', 0)
}
def get_sets_by_year_statistics(self) -> list[dict[str, Any]]:
"""Get statistics grouped by LEGO set release year"""
results = self.sql.fetchall('statistics/sets_by_year')
return [dict(row) for row in results]
def get_purchases_by_year_statistics(self) -> list[dict[str, Any]]:
"""Get statistics grouped by purchase year"""
results = self.sql.fetchall('statistics/purchases_by_year')
return [dict(row) for row in results]
def get_year_summary(self) -> dict[str, Any]:
"""Get year-based summary statistics"""
sets_by_year = self.get_sets_by_year_statistics()
purchases_by_year = self.get_purchases_by_year_statistics()
# Calculate summary metrics
years_represented = len(sets_by_year)
years_with_purchases = len(purchases_by_year)
# Find peak year for collection (by set count)
peak_collection_year = None
max_sets_in_year = 0
if sets_by_year:
peak_year_data = max(sets_by_year, key=lambda x: x['total_sets'])
peak_collection_year = peak_year_data['year']
max_sets_in_year = peak_year_data['total_sets']
# Find peak spending year
peak_spending_year = None
max_spending = 0
if purchases_by_year:
spending_years = [y for y in purchases_by_year if y.get('total_spent')]
if spending_years:
peak_spending_data = max(spending_years, key=lambda x: x['total_spent'] or 0)
peak_spending_year = peak_spending_data['purchase_year']
max_spending = peak_spending_data['total_spent']
return {
'years_represented': years_represented,
'years_with_purchases': years_with_purchases,
'peak_collection_year': peak_collection_year,
'max_sets_in_year': max_sets_in_year,
'peak_spending_year': peak_spending_year,
'max_spending': max_spending,
'oldest_set_year': min([y['year'] for y in sets_by_year]) if sets_by_year else None,
'newest_set_year': max([y['year'] for y in sets_by_year]) if sets_by_year else None
}

View File

@@ -0,0 +1,13 @@
"""Custom Jinja2 template filters for BrickTracker."""
from urllib.parse import urlparse, parse_qs, urlencode, urlunparse
def replace_query_filter(url, key, value):
"""Replace or add a query parameter in a URL"""
parsed = urlparse(url)
query_dict = parse_qs(parsed.query, keep_blank_values=True)
query_dict[key] = [str(value)]
new_query = urlencode(query_dict, doseq=True)
return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, new_query, parsed.fragment))

View File

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

View File

@@ -14,6 +14,7 @@ from .exceptions import exception_handler
from ..instructions import BrickInstructions
from ..instructions_list import BrickInstructionsList
from ..parser import parse_set
from ..peeron_instructions import PeeronInstructions
from ..socket import MESSAGES
from .upload import upload_helper
@@ -24,6 +25,22 @@ instructions_page = Blueprint(
)
def _render_peeron_select_page(set: str) -> str:
"""Helper function to render the Peeron page selection interface with cached thumbnails."""
peeron = PeeronInstructions(set)
peeron_pages = peeron.find_pages() # This will use the cached thumbnails
current_app.logger.debug(f"[peeron_loaded] Found {len(peeron_pages)} pages for {set}")
return render_template(
'peeron_select.html',
download=True,
pages=peeron_pages,
set=set,
path=current_app.config['SOCKET_PATH'],
namespace=current_app.config['SOCKET_NAMESPACE'],
messages=MESSAGES
)
# Index
@instructions_page.route('/', methods=['GET'])
@exception_handler(__file__)
@@ -141,6 +158,10 @@ def download() -> str:
except Exception:
set = ''
# Check if this is a redirect after Peeron pages were loaded
if request.args.get('peeron_loaded'):
return _render_peeron_select_page(set)
return render_template(
'instructions.html',
download=True,
@@ -160,12 +181,50 @@ def do_download() -> str:
except Exception:
set = ''
return render_template(
'instructions.html',
download=True,
instructions=BrickInstructions.find_instructions(set),
set=set,
path=current_app.config['SOCKET_PATH'],
namespace=current_app.config['SOCKET_NAMESPACE'],
messages=MESSAGES
)
# Check if this is a redirect after Peeron pages were loaded
if request.args.get('peeron_loaded'):
return _render_peeron_select_page(set)
# Try Rebrickable first
try:
from .instructions import BrickInstructions
rebrickable_instructions = BrickInstructions.find_instructions(set)
# Standard Rebrickable instructions found
return render_template(
'instructions.html',
download=True,
instructions=rebrickable_instructions,
set=set,
path=current_app.config['SOCKET_PATH'],
namespace=current_app.config['SOCKET_NAMESPACE'],
messages=MESSAGES
)
except Exception:
# Rebrickable failed, check if Peeron has instructions (without caching thumbnails yet)
try:
peeron = PeeronInstructions(set)
# Just check if pages exist, don't cache thumbnails yet
if peeron.exists():
# Peeron has instructions - show loading interface
return render_template(
'peeron_select.html',
download=True,
loading_peeron=True, # Flag to show loading state
set=set,
path=current_app.config['SOCKET_PATH'],
namespace=current_app.config['SOCKET_NAMESPACE'],
messages=MESSAGES
)
else:
raise Exception("Not found on Peeron either")
except Exception:
return render_template(
'instructions.html',
download=True,
instructions=[],
set=set,
error='No instructions found on Rebrickable or Peeron',
path=current_app.config['SOCKET_PATH'],
namespace=current_app.config['SOCKET_NAMESPACE'],
messages=MESSAGES
)

View File

@@ -1,8 +1,9 @@
from flask import Blueprint, render_template, request
from flask import Blueprint, current_app, render_template, request
from .exceptions import exception_handler
from ..minifigure import BrickMinifigure
from ..minifigure_list import BrickMinifigureList
from ..pagination_helper import get_pagination_config, build_pagination_context, get_request_params
from ..set_list import BrickSetList, set_metadata_lists
from ..set_owner_list import BrickSetOwnerList
@@ -13,24 +14,52 @@ minifigure_page = Blueprint('minifigure', __name__, url_prefix='/minifigures')
@minifigure_page.route('/', methods=['GET'])
@exception_handler(__file__)
def list() -> str:
# Get owner filter from request
# Get filter parameters from request
owner_id = request.args.get('owner', 'all')
search_query, sort_field, sort_order, page = get_request_params()
# Get minifigures filtered by owner
if owner_id == 'all' or owner_id is None or owner_id == '':
minifigures = BrickMinifigureList().all()
# Get pagination configuration
per_page, is_mobile = get_pagination_config('minifigures')
use_pagination = per_page > 0
if use_pagination:
# PAGINATION MODE - Server-side pagination with search
minifigures, total_count = BrickMinifigureList().all_filtered_paginated(
owner_id=owner_id,
search_query=search_query,
page=page,
per_page=per_page,
sort_field=sort_field,
sort_order=sort_order
)
pagination_context = build_pagination_context(page, per_page, total_count, is_mobile)
else:
minifigures = BrickMinifigureList().all_by_owner(owner_id)
# ORIGINAL MODE - Single page with all data for client-side search
if owner_id == 'all' or owner_id is None or owner_id == '':
minifigures = BrickMinifigureList().all()
else:
minifigures = BrickMinifigureList().all_by_owner(owner_id)
pagination_context = None
# Get list of owners for filter dropdown
owners = BrickSetOwnerList.list()
return render_template(
'minifigures.html',
table_collection=minifigures,
owners=owners,
selected_owner=owner_id,
)
template_context = {
'table_collection': minifigures,
'owners': owners,
'selected_owner': owner_id,
'search_query': search_query,
'use_pagination': use_pagination,
'current_sort': sort_field,
'current_order': sort_order
}
if pagination_context:
template_context['pagination'] = pagination_context
return render_template('minifigures.html', **template_context)
# Minifigure details

View File

@@ -2,6 +2,7 @@ from flask import Blueprint, render_template, request
from .exceptions import exception_handler
from ..minifigure_list import BrickMinifigureList
from ..pagination_helper import get_pagination_config, build_pagination_context, get_request_params
from ..part import BrickPart
from ..part_list import BrickPartList
from ..set_list import BrickSetList, set_metadata_lists
@@ -15,13 +16,32 @@ part_page = Blueprint('part', __name__, url_prefix='/parts')
@part_page.route('/', methods=['GET'])
@exception_handler(__file__)
def list() -> str:
# Get filter parameters from request
owner_id = request.args.get('owner', 'all')
color_id = request.args.get('color', 'all')
search_query, sort_field, sort_order, page = get_request_params()
# Get parts with filters applied
parts = BrickPartList().all_filtered(owner_id, color_id)
# Get pagination configuration
per_page, is_mobile = get_pagination_config('parts')
use_pagination = per_page > 0
if use_pagination:
# PAGINATION MODE - Server-side pagination with search
parts, total_count = BrickPartList().all_filtered_paginated(
owner_id=owner_id,
color_id=color_id,
search_query=search_query,
page=page,
per_page=per_page,
sort_field=sort_field,
sort_order=sort_order
)
pagination_context = build_pagination_context(page, per_page, total_count, is_mobile)
else:
# ORIGINAL MODE - Single page with all data for client-side search
parts = BrickPartList().all_filtered(owner_id, color_id)
pagination_context = None
# Get list of owners for filter dropdown
owners = BrickSetOwnerList.list()
@@ -34,23 +54,80 @@ def list() -> str:
colors = BrickSQL().fetchall('part/colors/list', **color_context)
return render_template(
'parts.html',
table_collection=parts,
owners=owners,
selected_owner=owner_id,
colors=colors,
selected_color=color_id,
)
template_context = {
'table_collection': parts,
'owners': owners,
'selected_owner': owner_id,
'colors': colors,
'selected_color': color_id,
'search_query': search_query,
'use_pagination': use_pagination,
'current_sort': sort_field,
'current_order': sort_order
}
if pagination_context:
template_context['pagination'] = pagination_context
return render_template('parts.html', **template_context)
# Problem
@part_page.route('/problem', methods=['GET'])
@exception_handler(__file__)
def problem() -> str:
# Get filter parameters from request
owner_id = request.args.get('owner', 'all')
color_id = request.args.get('color', 'all')
search_query, sort_field, sort_order, page = get_request_params()
# Get pagination configuration
per_page, is_mobile = get_pagination_config('problems')
use_pagination = per_page > 0
if use_pagination:
# PAGINATION MODE - Server-side pagination with search and filters
parts, total_count = BrickPartList().problem_paginated(
owner_id=owner_id,
color_id=color_id,
search_query=search_query,
page=page,
per_page=per_page,
sort_field=sort_field,
sort_order=sort_order
)
pagination_context = build_pagination_context(page, per_page, total_count, is_mobile)
else:
# ORIGINAL MODE - Single page with all data for client-side search
parts = BrickPartList().problem_filtered(owner_id, color_id)
pagination_context = None
# Get list of owners for filter dropdown
owners = BrickSetOwnerList.list()
# Get list of colors for filter dropdown
# Prepare context for color query (filter by owner if selected)
color_context = {}
if owner_id != 'all':
color_context['owner_id'] = owner_id
# Get colors from problem parts (following same pattern as parts page)
colors = BrickSQL().fetchall('part/colors/list_problem', **color_context)
return render_template(
'problem.html',
table_collection=BrickPartList().problem()
table_collection=parts,
pagination=pagination_context,
search_query=search_query,
sort_field=sort_field,
sort_order=sort_order,
use_pagination=use_pagination,
owners=owners,
colors=colors,
selected_owner=owner_id,
selected_color=color_id
)

View File

@@ -15,6 +15,7 @@ from werkzeug.wrappers.response import Response
from .exceptions import exception_handler
from ..exceptions import ErrorException
from ..minifigure import BrickMinifigure
from ..pagination_helper import get_pagination_config, build_pagination_context, get_request_params
from ..part import BrickPart
from ..rebrickable_set import RebrickableSet
from ..set import BrickSet
@@ -35,12 +36,80 @@ set_page = Blueprint('set', __name__, url_prefix='/sets')
@set_page.route('/', methods=['GET'])
@exception_handler(__file__)
def list() -> str:
return render_template(
'sets.html',
collection=BrickSetList().all(),
brickset_statuses=BrickSetStatusList.list(),
# Get filter parameters from request
search_query, sort_field, sort_order, page = get_request_params()
# Get filter parameters
status_filter = request.args.get('status')
theme_filter = request.args.get('theme')
owner_filter = request.args.get('owner')
purchase_location_filter = request.args.get('purchase_location')
storage_filter = request.args.get('storage')
tag_filter = request.args.get('tag')
year_filter = request.args.get('year')
# Get pagination configuration
per_page, is_mobile = get_pagination_config('sets')
use_pagination = per_page > 0
if use_pagination:
# PAGINATION MODE - Server-side pagination with search and filters
sets, total_count = BrickSetList().all_filtered_paginated(
search_query=search_query,
page=page,
per_page=per_page,
sort_field=sort_field,
sort_order=sort_order,
status_filter=status_filter,
theme_filter=theme_filter,
owner_filter=owner_filter,
purchase_location_filter=purchase_location_filter,
storage_filter=storage_filter,
tag_filter=tag_filter,
year_filter=year_filter,
use_consolidated=current_app.config['SETS_CONSOLIDATION']
)
pagination_context = build_pagination_context(page, per_page, total_count, is_mobile)
else:
# ORIGINAL MODE - Single page with all data for client-side search
if current_app.config['SETS_CONSOLIDATION']:
sets = BrickSetList().all_consolidated()
else:
sets = BrickSetList().all()
pagination_context = None
# Convert theme ID to theme name for dropdown display if needed
display_theme_filter = theme_filter
if theme_filter and theme_filter.isdigit():
# Theme filter is an ID, convert to name for dropdown
# Create a fresh BrickSetList instance for theme conversion
converter = BrickSetList()
theme_name = converter._theme_id_to_name(theme_filter)
if theme_name:
display_theme_filter = theme_name
template_context = {
'collection': sets,
'search_query': search_query,
'use_pagination': use_pagination,
'current_sort': sort_field,
'current_order': sort_order,
'current_status_filter': status_filter,
'current_theme_filter': display_theme_filter,
'current_owner_filter': owner_filter,
'current_purchase_location_filter': purchase_location_filter,
'current_storage_filter': storage_filter,
'current_tag_filter': tag_filter,
'current_year_filter': year_filter,
'brickset_statuses': BrickSetStatusList.list(),
**set_metadata_lists(as_class=True)
)
}
if pagination_context:
template_context['pagination'] = pagination_context
return render_template('sets.html', **template_context)
# Change the value of purchase date
@@ -187,13 +256,44 @@ def deleted(*, id: str) -> str:
@set_page.route('/<id>/details', methods=['GET'])
@exception_handler(__file__)
def details(*, id: str) -> str:
return render_template(
'set.html',
item=BrickSet().select_specific(id),
open_instructions=request.args.get('open_instructions'),
brickset_statuses=BrickSetStatusList.list(all=True),
**set_metadata_lists(as_class=True)
)
# Load the specific set
item = BrickSet().select_specific(id)
# Check if there are multiple instances of this set
all_instances = BrickSetList()
# Load all sets with metadata context for tags, owners, etc.
filter_context = {
'owners': BrickSetOwnerList.as_columns(),
'statuses': BrickSetStatusList.as_columns(),
'tags': BrickSetTagList.as_columns(),
}
all_instances.list(do_theme=True, **filter_context)
# Find all instances with the same set number
same_set_instances = [
record for record in all_instances.records
if record.fields.set == item.fields.set
]
# If consolidation is enabled and multiple instances exist, show consolidated view
if current_app.config['SETS_CONSOLIDATION'] and len(same_set_instances) > 1:
return render_template(
'set.html',
item=item,
all_instances=same_set_instances,
open_instructions=request.args.get('open_instructions'),
brickset_statuses=BrickSetStatusList.list(all=True),
**set_metadata_lists(as_class=True)
)
else:
# Single instance or consolidation disabled, show normal view
return render_template(
'set.html',
item=item,
open_instructions=request.args.get('open_instructions'),
brickset_statuses=BrickSetStatusList.list(all=True),
**set_metadata_lists(as_class=True)
)
# Update problematic pieces of a set
@@ -242,6 +342,50 @@ def problem_part(
return jsonify({problem: amount})
# Update checked state of parts during walkthrough
@set_page.route('/<id>/parts/<part>/<int:color>/<int:spare>/checked', defaults={'figure': None}, methods=['POST']) # noqa: E501
@set_page.route('/<id>/minifigures/<figure>/parts/<part>/<int:color>/<int:spare>/checked', methods=['POST']) # noqa: E501
@login_required
@exception_handler(__file__, json=True)
def checked_part(
*,
id: str,
figure: str | None,
part: str,
color: int,
spare: int,
) -> Response:
brickset = BrickSet().select_specific(id)
if figure is not None:
brickminifigure = BrickMinifigure().select_specific(brickset, figure)
else:
brickminifigure = None
brickpart = BrickPart().select_specific(
brickset,
part,
color,
spare,
minifigure=brickminifigure,
)
checked = brickpart.update_checked(request.json)
# Info
logger.info('Set {set} ({id}): updated part ({part} color: {color}, spare: {spare}, minifigure: {figure}) checked state to {checked}'.format( # noqa: E501
set=brickset.fields.set,
id=brickset.fields.id,
figure=figure,
part=brickpart.fields.part,
color=brickpart.fields.color,
spare=brickpart.fields.spare,
checked=checked
))
return jsonify({'checked': checked})
# Refresh a set
@set_page.route('/refresh/<set>/', methods=['GET'])
@set_page.route('/<id>/refresh', methods=['GET'])

View File

@@ -0,0 +1,189 @@
"""
Statistics views for BrickTracker
Provides statistics and analytics pages
"""
import logging
from flask import Blueprint, render_template, request, url_for, redirect, current_app
from werkzeug.wrappers.response import Response
from .exceptions import exception_handler
from ..statistics import BrickStatistics
logger = logging.getLogger(__name__)
statistics_page = Blueprint('statistics', __name__, url_prefix='/statistics')
@statistics_page.route('/', methods=['GET'])
@exception_handler(__file__)
def overview() -> str:
"""Statistics overview page with metrics"""
stats = BrickStatistics()
# Get all statistics data
overview_stats = stats.get_overview()
theme_stats = stats.get_theme_statistics()
storage_stats = stats.get_storage_statistics()
purchase_location_stats = stats.get_purchase_location_statistics()
financial_summary = stats.get_financial_summary()
collection_summary = stats.get_collection_summary()
sets_by_year_stats = stats.get_sets_by_year_statistics()
purchases_by_year_stats = stats.get_purchases_by_year_statistics()
year_summary = stats.get_year_summary()
# Prepare chart data for visualization (only if charts are enabled)
chart_data = {}
if current_app.config['STATISTICS_SHOW_CHARTS']:
chart_data = prepare_chart_data(sets_by_year_stats, purchases_by_year_stats)
# Get filter parameters for clickable statistics
filter_type = request.args.get('filter_type')
filter_value = request.args.get('filter_value')
# If a filter is applied, redirect to sets page with appropriate filters
if filter_type and filter_value:
return redirect_to_filtered_sets(filter_type, filter_value)
return render_template(
'statistics.html',
overview=overview_stats,
theme_statistics=theme_stats,
storage_statistics=storage_stats,
purchase_location_statistics=purchase_location_stats,
financial_summary=financial_summary,
collection_summary=collection_summary,
sets_by_year_statistics=sets_by_year_stats,
purchases_by_year_statistics=purchases_by_year_stats,
year_summary=year_summary,
chart_data=chart_data,
title="Statistics Overview"
)
def redirect_to_filtered_sets(filter_type: str, filter_value: str) -> Response:
"""Redirect to sets page with appropriate filters based on statistics click"""
# Map filter types to sets page parameters
filter_mapping = {
'theme': {'theme': filter_value},
'storage': {'storage': filter_value},
'purchase_location': {'purchase_location': filter_value},
'has_price': {'has_price': '1'} if filter_value == '1' else {},
'missing_parts': {'status': 'has-missing'},
'damaged_parts': {'status': 'has-damaged'},
'has_storage': {'status': 'has-storage'},
'no_storage': {'status': '-has-storage'},
}
# Get the appropriate filter parameters
filter_params = filter_mapping.get(filter_type, {})
if filter_params:
return redirect(url_for('set.list', **filter_params))
else:
# Default fallback to sets page
return redirect(url_for('set.list'))
@statistics_page.route('/themes', methods=['GET'])
@exception_handler(__file__)
def themes() -> str:
"""Detailed theme statistics page"""
stats = BrickStatistics()
theme_stats = stats.get_theme_statistics()
return render_template(
'statistics_themes.html',
theme_statistics=theme_stats,
title="Theme Statistics"
)
@statistics_page.route('/storage', methods=['GET'])
@exception_handler(__file__)
def storage() -> str:
"""Detailed storage statistics page"""
stats = BrickStatistics()
storage_stats = stats.get_storage_statistics()
return render_template(
'statistics_storage.html',
storage_statistics=storage_stats,
title="Storage Statistics"
)
@statistics_page.route('/purchase-locations', methods=['GET'])
@exception_handler(__file__)
def purchase_locations() -> str:
"""Detailed purchase location statistics page"""
stats = BrickStatistics()
purchase_stats = stats.get_purchase_location_statistics()
return render_template(
'statistics_purchase_locations.html',
purchase_location_statistics=purchase_stats,
title="Purchase Location Statistics"
)
def prepare_chart_data(sets_by_year_stats, purchases_by_year_stats):
"""Prepare data for Chart.js visualization"""
import json
# Get all years from both datasets
all_years = set()
# Add years from sets by year
if sets_by_year_stats:
for year_stat in sets_by_year_stats:
if 'year' in year_stat:
all_years.add(year_stat['year'])
# Add years from purchases by year
if purchases_by_year_stats:
for year_stat in purchases_by_year_stats:
if 'purchase_year' in year_stat:
all_years.add(int(year_stat['purchase_year']))
# Create sorted list of years
years = sorted(list(all_years))
# Initialize data arrays
sets_data = []
parts_data = []
minifigs_data = []
# Create lookup dictionaries for quick access
sets_by_year_lookup = {}
if sets_by_year_stats:
for year_stat in sets_by_year_stats:
if 'year' in year_stat:
sets_by_year_lookup[year_stat['year']] = year_stat
# Fill data arrays
for year in years:
# Get sets and parts data from sets_by_year
year_data = sets_by_year_lookup.get(year)
if year_data:
sets_data.append(year_data.get('total_sets', 0))
parts_data.append(year_data.get('total_parts', 0))
# Use actual minifigure count from the database
minifigs_data.append(year_data.get('total_minifigures', 0))
else:
sets_data.append(0)
parts_data.append(0)
minifigs_data.append(0)
return {
'years': json.dumps(years),
'sets_data': json.dumps(sets_data),
'parts_data': json.dumps(parts_data),
'minifigs_data': json.dumps(minifigs_data)
}

View File

@@ -19,17 +19,24 @@ class BrickWishList(BrickRecordList[BrickWish]):
# Queries
select_query: str = 'wish/list/all'
# All the wished sets
def all(self, /) -> Self:
# Implementation of abstract list method
def list(self, /, *, override_query: str | None = None, **context) -> None:
# Use provided order or default
order = context.pop('order', current_app.config['WISHES_DEFAULT_ORDER'])
# Load the wished sets from the database
for record in self.select(
order=current_app.config['WISHES_DEFAULT_ORDER'],
override_query=override_query,
order=order,
owners=BrickWishOwnerList.as_columns(),
**context
):
brickwish = BrickWish(record=record)
self.records.append(brickwish)
# All the wished sets
def all(self, /) -> Self:
self.list()
return self
# Add a set to the wishlist

View File

@@ -11,3 +11,5 @@ requests
tzdata
bs4
cloudscraper
fpdf2
pillow

View File

@@ -0,0 +1,442 @@
/**
* Shared collapsible state management for filters and sort sections
* Handles BK_SHOW_GRID_FILTERS and BK_SHOW_GRID_SORT configuration with user preferences
*/
// Generic state management for collapsible sections (filter and sort)
function initializeCollapsibleState(elementId, storageKey) {
const element = document.getElementById(elementId);
const toggleButton = document.querySelector(`[data-bs-target="#${elementId}"]`);
if (!element || !toggleButton) return;
// Restore state on page load
const savedState = sessionStorage.getItem(storageKey);
if (savedState === 'open') {
// User explicitly opened it
element.classList.add('show');
toggleButton.setAttribute('aria-expanded', 'true');
} else if (savedState === 'closed') {
// User explicitly closed it, override template state
element.classList.remove('show');
toggleButton.setAttribute('aria-expanded', 'false');
}
// If no saved state, keep the template state (respects BK_SHOW_GRID_FILTERS/BK_SHOW_GRID_SORT)
// Listen for toggle events
element.addEventListener('show.bs.collapse', () => {
sessionStorage.setItem(storageKey, 'open');
});
element.addEventListener('hide.bs.collapse', () => {
sessionStorage.setItem(storageKey, 'closed');
});
}
// Initialize filter and sort states for a specific page
function initializePageCollapsibleStates(pagePrefix, filterElementId = 'table-filter', sortElementId = 'table-sort') {
initializeCollapsibleState(filterElementId, `${pagePrefix}-filter-state`);
initializeCollapsibleState(sortElementId, `${pagePrefix}-sort-state`);
// Initialize sort icons based on current URL parameters (for all pages)
const urlParams = new URLSearchParams(window.location.search);
const currentSort = urlParams.get('sort');
const currentOrder = urlParams.get('order');
if (currentSort || currentOrder) {
updateSortIcon(currentOrder);
}
}
// Shared function to preserve filter state during filter changes
function preserveCollapsibleStateOnChange(elementId, storageKey) {
const element = document.getElementById(elementId);
const wasOpen = element && element.classList.contains('show');
// Store the state to restore after page reload
if (wasOpen) {
sessionStorage.setItem(storageKey, 'open');
}
}
// Setup color dropdown with visual indicators (shared implementation)
function setupColorDropdown() {
const colorSelect = document.getElementById('filter-color');
if (!colorSelect) return;
// Merge duplicate color options where one has color_rgb and the other is None
const colorMap = new Map();
const allOptions = colorSelect.querySelectorAll('option[data-color-id]');
// First pass: collect all options by color_id
allOptions.forEach(option => {
const colorId = option.dataset.colorId;
const colorRgb = option.dataset.colorRgb;
const colorName = option.textContent.trim();
if (!colorMap.has(colorId)) {
colorMap.set(colorId, []);
}
colorMap.get(colorId).push({
element: option,
colorRgb: colorRgb,
colorName: colorName,
selected: option.selected
});
});
// Second pass: merge duplicates, keeping the one with color_rgb
colorMap.forEach((options, colorId) => {
if (options.length > 1) {
// Find option with color_rgb (not empty/null/undefined)
const withRgb = options.find(opt => opt.colorRgb && opt.colorRgb !== 'None' && opt.colorRgb !== '');
const withoutRgb = options.find(opt => !opt.colorRgb || opt.colorRgb === 'None' || opt.colorRgb === '');
if (withRgb && withoutRgb) {
// Keep the selected state from either option
const wasSelected = withRgb.selected || withoutRgb.selected;
// Update the option with RGB to be selected if either was selected
if (wasSelected) {
withRgb.element.selected = true;
}
// Remove the option without RGB
withoutRgb.element.remove();
}
}
});
// Add color squares to remaining option text
const remainingOptions = colorSelect.querySelectorAll('option[data-color-rgb]');
remainingOptions.forEach(option => {
const colorRgb = option.dataset.colorRgb;
const colorId = option.dataset.colorId;
const colorName = option.textContent.trim();
if (colorRgb && colorRgb !== 'None' && colorRgb !== '' && colorId !== '9999') {
// Create a visual indicator (using Unicode square)
option.textContent = `${colorName}`; //■
//option.style.color = `#${colorRgb}`;
}
});
}
// Check if pagination mode is enabled for a specific table
function isPaginationModeForTable(tableId) {
const tableElement = document.querySelector(`#${tableId}`);
return tableElement && tableElement.getAttribute('data-table') === 'false';
}
// Update sort icon based on current sort direction
function updateSortIcon(sortDirection = null) {
// Find the main sort icon (could be in grid-sort or table-sort)
const sortIcon = document.querySelector('#grid-sort .ri-sort-asc, #grid-sort .ri-sort-desc, #table-sort .ri-sort-asc, #table-sort .ri-sort-desc');
if (!sortIcon) return;
// Remove existing sort classes
sortIcon.classList.remove('ri-sort-asc', 'ri-sort-desc');
// Add appropriate class based on sort direction
if (sortDirection === 'desc') {
sortIcon.classList.add('ri-sort-desc');
} else {
sortIcon.classList.add('ri-sort-asc');
}
}
// Initialize sort button states and icons for pagination mode
window.initializeSortButtonStates = function(currentSort, currentOrder) {
const sortButtons = document.querySelectorAll('[data-sort-attribute]');
// Update main sort icon
updateSortIcon(currentOrder);
if (currentSort) {
sortButtons.forEach(btn => {
// Clear all buttons first
btn.classList.remove('btn-primary');
btn.classList.add('btn-outline-primary');
btn.removeAttribute('data-current-direction');
// Set active state for current sort
if (btn.dataset.sortAttribute === currentSort) {
btn.classList.remove('btn-outline-primary');
btn.classList.add('btn-primary');
btn.dataset.currentDirection = currentOrder || 'asc';
}
});
}
};
// Shared sort button setup function
window.setupSharedSortButtons = function(tableId, tableInstanceGlobal, columnMap) {
const sortButtons = document.querySelectorAll('[data-sort-attribute]');
const clearButton = document.querySelector('[data-sort-clear]');
const isPaginationMode = isPaginationModeForTable(tableId);
sortButtons.forEach(button => {
button.addEventListener('click', () => {
const attribute = button.dataset.sortAttribute;
const isDesc = button.dataset.sortDesc === 'true';
if (isPaginationMode) {
// PAGINATION MODE - Server-side sorting via URL parameters
const currentUrl = new URL(window.location);
const currentSort = currentUrl.searchParams.get('sort');
const currentOrder = currentUrl.searchParams.get('order');
const isCurrentlyActive = currentSort === attribute;
let newDirection;
if (isCurrentlyActive) {
// Toggle direction if same attribute
newDirection = currentOrder === 'asc' ? 'desc' : 'asc';
} else {
// Use default direction for new attribute
newDirection = isDesc ? 'desc' : 'asc';
}
// Set sort parameters and reset to first page
currentUrl.searchParams.set('sort', attribute);
currentUrl.searchParams.set('order', newDirection);
currentUrl.searchParams.set('page', '1');
// Navigate to sorted results
window.location.href = currentUrl.toString();
} else {
// ORIGINAL MODE - Client-side sorting via Simple DataTables
const columnIndex = columnMap[attribute];
const tableInstance = window[tableInstanceGlobal];
if (columnIndex !== undefined && tableInstance) {
// Determine sort direction
const isCurrentlyActive = button.classList.contains('btn-primary');
const currentDirection = button.dataset.currentDirection || (isDesc ? 'desc' : 'asc');
const newDirection = isCurrentlyActive ?
(currentDirection === 'asc' ? 'desc' : 'asc') :
(isDesc ? 'desc' : 'asc');
// Clear other active buttons
sortButtons.forEach(btn => {
btn.classList.remove('btn-primary');
btn.classList.add('btn-outline-primary');
btn.removeAttribute('data-current-direction');
});
// Mark this button as active
button.classList.remove('btn-outline-primary');
button.classList.add('btn-primary');
button.dataset.currentDirection = newDirection;
// Apply sort using Simple DataTables API
tableInstance.table.columns.sort(columnIndex, newDirection);
// Update sort icon to reflect new direction
updateSortIcon(newDirection);
}
}
});
});
if (clearButton) {
clearButton.addEventListener('click', () => {
if (isPaginationMode) {
// PAGINATION MODE - Clear server-side sorting via URL parameters
const currentUrl = new URL(window.location);
currentUrl.searchParams.delete('sort');
currentUrl.searchParams.delete('order');
currentUrl.searchParams.set('page', '1');
window.location.href = currentUrl.toString();
} else {
// ORIGINAL MODE - Clear client-side sorting
// Clear all sort buttons
sortButtons.forEach(btn => {
btn.classList.remove('btn-primary');
btn.classList.add('btn-outline-primary');
btn.removeAttribute('data-current-direction');
});
// Reset sort icon to default ascending
updateSortIcon('asc');
// Reset table sort - remove all sorting
const tableInstance = window[tableInstanceGlobal];
if (tableInstance) {
const tableElement = document.querySelector(`#${tableId}`);
const currentPerPage = tableInstance.table.options.perPage;
tableInstance.table.destroy();
setTimeout(() => {
// Create new instance using the globally available BrickTable class
const newInstance = new window.BrickTable(tableElement, currentPerPage);
window[tableInstanceGlobal] = newInstance;
// Re-enable search functionality
newInstance.table.searchable = true;
}, 50);
}
}
});
}
};
// =================================================================
// SHARED FUNCTIONS FOR PAGE-SPECIFIC OPERATIONS
// =================================================================
// Shared pagination mode detection (works for any table/grid ID)
window.isPaginationModeForPage = function(elementId, attributeName = 'data-table') {
const element = document.querySelector(`#${elementId}`);
return element && element.getAttribute(attributeName) === 'false';
};
// Shared URL parameter update helper
window.updateUrlParams = function(params, resetPage = true) {
const currentUrl = new URL(window.location);
// Apply parameter updates
Object.entries(params).forEach(([key, value]) => {
if (value === null || value === undefined || value === '' || value === 'all') {
currentUrl.searchParams.delete(key);
} else {
currentUrl.searchParams.set(key, value);
}
});
// Reset to page 1 if requested
if (resetPage) {
currentUrl.searchParams.set('page', '1');
}
// Navigate to updated URL
window.location.href = currentUrl.toString();
};
// Shared filter application (supports owner and color filters)
window.applyPageFilters = function(tableId) {
const ownerSelect = document.getElementById('filter-owner');
const colorSelect = document.getElementById('filter-color');
const params = {};
// Handle owner filter
if (ownerSelect) {
params.owner = ownerSelect.value;
}
// Handle color filter
if (colorSelect) {
params.color = colorSelect.value;
}
// Update URL with new parameters
window.updateUrlParams(params, true);
};
// Shared search setup for both pagination and client-side modes
window.setupPageSearch = function(tableId, searchInputId, clearButtonId, tableInstanceGlobal) {
const searchInput = document.getElementById(searchInputId);
const searchClear = document.getElementById(clearButtonId);
if (!searchInput || !searchClear) return;
const isPaginationMode = window.isPaginationModeForPage(tableId);
if (isPaginationMode) {
// PAGINATION MODE - Server-side search with Enter key
searchInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const searchValue = e.target.value.trim();
window.updateUrlParams({ search: searchValue }, true);
}
});
// Clear search
searchClear.addEventListener('click', () => {
searchInput.value = '';
window.updateUrlParams({ search: null }, true);
});
} else {
// ORIGINAL MODE - Client-side instant search via Simple DataTables
const setupClientSearch = () => {
const tableElement = document.querySelector(`table[data-table="true"]#${tableId}`);
const tableInstance = window[tableInstanceGlobal];
if (tableElement && tableInstance) {
// Enable search functionality
tableInstance.table.searchable = true;
// Instant search as user types
searchInput.addEventListener('input', (e) => {
const searchValue = e.target.value.trim();
tableInstance.table.search(searchValue);
});
// Clear search
searchClear.addEventListener('click', () => {
searchInput.value = '';
tableInstance.table.search('');
});
} else {
// If table instance not ready, try again
setTimeout(setupClientSearch, 100);
}
};
setTimeout(setupClientSearch, 100);
}
};
// Shared function to preserve filter state and apply filters
window.applyFiltersAndKeepState = function(tableId, storageKey) {
const filterElement = document.getElementById('table-filter');
const wasOpen = filterElement && filterElement.classList.contains('show');
// Apply the filters
window.applyPageFilters(tableId);
// Store the state to restore after page reload
if (wasOpen) {
sessionStorage.setItem(storageKey, 'open');
}
};
// Shared initialization for table pages (parts, problems, minifigures)
window.initializeTablePage = function(config) {
const {
pagePrefix, // e.g., 'parts', 'problems', 'minifigures'
tableId, // e.g., 'parts', 'problems', 'minifigures'
searchInputId = 'table-search',
clearButtonId = 'table-search-clear',
tableInstanceGlobal, // e.g., 'partsTableInstance', 'problemsTableInstance'
sortColumnMap, // Column mapping for sort buttons
hasColorDropdown = true
} = config;
// Initialize collapsible states (filter and sort)
initializePageCollapsibleStates(pagePrefix);
// Setup search functionality
window.setupPageSearch(tableId, searchInputId, clearButtonId, tableInstanceGlobal);
// Setup color dropdown if needed
if (hasColorDropdown) {
setupColorDropdown();
}
// Setup sort buttons with shared functionality
if (sortColumnMap) {
window.setupSharedSortButtons(tableId, tableInstanceGlobal, sortColumnMap);
}
// Initialize sort button states and icons for pagination mode
if (window.isPaginationModeForPage(tableId)) {
const urlParams = new URLSearchParams(window.location.search);
const currentSort = urlParams.get('sort');
const currentOrder = urlParams.get('order');
window.initializeSortButtonStates(currentSort, currentOrder);
}
};

View File

@@ -91,7 +91,7 @@ class BrickGridFilter {
attribute: select.value,
bool: true,
value: "1"
})
});
}
break;
}
@@ -106,19 +106,48 @@ class BrickGridFilter {
const attribute = current.getAttribute(`data-${filter.attribute}`);
// Bool check
// Attribute not equal value, or undefined and value is truthy
// For boolean attributes (like owner/tag filtering)
if (filter.bool) {
if ((attribute != null && attribute != filter.value) || (attribute == null && filter.value == "1")) {
current.parentElement.classList.add("d-none");
return;
if (filter.value == "1") {
// Looking for sets WITH this attribute
// Hide if attribute is missing (null) or explicitly "0"
// For owner/tag attributes: missing = doesn't have this owner/tag
if (attribute == null || attribute == "0") {
current.parentElement.classList.add("d-none");
return;
}
} else if (filter.value == "0") {
// Looking for sets WITHOUT this attribute
// Hide if attribute is present and "1"
// For owner/tag attributes: present and "1" = has this owner/tag
if (attribute == "1") {
current.parentElement.classList.add("d-none");
return;
}
// Note: null (missing) is treated as "doesn't have" which is what we want for value="0"
}
}
// Value check
// Attribute not equal value, or attribute undefined
else if ((attribute != null && attribute != filter.value) || attribute == null) {
// For consolidated cards, attributes may be comma or pipe-separated (e.g., "storage1,storage2" or "storage1|storage2")
else if (attribute == null) {
// Hide if attribute is missing
current.parentElement.classList.add("d-none");
return;
} else if (attribute.includes(',') || attribute.includes('|')) {
// Handle comma or pipe-separated values (consolidated cards)
const separator = attribute.includes('|') ? '|' : ',';
const values = attribute.split(separator).map(v => v.trim());
if (!values.includes(filter.value)) {
current.parentElement.classList.add("d-none");
return;
}
} else {
// Handle single values (regular cards)
if (attribute != filter.value) {
current.parentElement.classList.add("d-none");
return;
}
}
}

View File

@@ -17,7 +17,13 @@ class BrickGrid {
}
}
// Global grid instances storage
window.gridInstances = {};
// Helper to setup the grids
const setup_grids = () => document.querySelectorAll('*[data-grid="true"]').forEach(
el => new BrickGrid(el)
el => {
const grid = new BrickGrid(el);
window.gridInstances[el.id] = grid;
}
);

View File

@@ -1,4 +1,11 @@
// Minifigures page functionality
// Check if we're in pagination mode (server-side) or original mode (client-side)
function isPaginationMode() {
const tableElement = document.querySelector('#minifigures');
return tableElement && tableElement.getAttribute('data-table') === 'false';
}
function filterByOwner() {
const select = document.getElementById('filter-owner');
const selectedOwner = select.value;
@@ -10,21 +17,23 @@ function filterByOwner() {
currentUrl.searchParams.set('owner', selectedOwner);
}
// Reset to page 1 when filtering
if (isPaginationMode()) {
currentUrl.searchParams.set('page', '1');
}
window.location.href = currentUrl.toString();
}
// Initialize filter and sort states for minifigures page
function initializeCollapsibleStates() {
initializePageCollapsibleStates('minifigures');
}
// Keep filters expanded after selection
function filterByOwnerAndKeepOpen() {
// Remember if filters were open
const filterSection = document.getElementById('table-filter');
const wasOpen = filterSection && filterSection.classList.contains('show');
preserveCollapsibleStateOnChange('table-filter', 'minifigures-filter-state');
filterByOwner();
// Store the state to restore after page reload
if (wasOpen) {
sessionStorage.setItem('keepFiltersOpen', 'true');
}
}
// Setup table search and sort functionality
@@ -32,117 +41,96 @@ document.addEventListener("DOMContentLoaded", () => {
const searchInput = document.getElementById('table-search');
const searchClear = document.getElementById('table-search-clear');
// Restore filter state after page load
if (sessionStorage.getItem('keepFiltersOpen') === 'true') {
const filterSection = document.getElementById('table-filter');
const filterButton = document.querySelector('[data-bs-target="#table-filter"]');
if (filterSection && filterButton) {
filterSection.classList.add('show');
filterButton.setAttribute('aria-expanded', 'true');
}
sessionStorage.removeItem('keepFiltersOpen');
}
// Initialize collapsible states (filter and sort)
initializeCollapsibleStates();
if (searchInput && searchClear) {
// Wait for table to be initialized by setup_tables
setTimeout(() => {
const tableElement = document.querySelector('table[data-table="true"]');
if (tableElement && window.brickTableInstance) {
// Enable custom search for minifigures table
window.brickTableInstance.table.searchable = true;
if (isPaginationMode()) {
// PAGINATION MODE - Server-side search
const searchForm = document.createElement('form');
searchForm.style.display = 'none';
searchInput.parentNode.appendChild(searchForm);
searchForm.appendChild(searchInput.cloneNode(true));
// Connect search input to table
searchInput.addEventListener('input', (e) => {
window.brickTableInstance.table.search(e.target.value);
});
// Handle Enter key for search
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
performServerSearch();
}
});
// Clear search
searchClear.addEventListener('click', () => {
searchInput.value = '';
window.brickTableInstance.table.search('');
});
// Setup sort buttons
setupSortButtons();
// Handle search button click (if exists)
const searchButton = document.querySelector('[data-search-trigger]');
if (searchButton) {
searchButton.addEventListener('click', performServerSearch);
}
}, 100);
// Clear search
searchClear.addEventListener('click', () => {
searchInput.value = '';
performServerSearch();
});
function performServerSearch() {
const currentUrl = new URL(window.location);
const searchQuery = searchInput.value.trim();
if (searchQuery) {
currentUrl.searchParams.set('search', searchQuery);
} else {
currentUrl.searchParams.delete('search');
}
// Reset to page 1 when searching
currentUrl.searchParams.set('page', '1');
window.location.href = currentUrl.toString();
}
} else {
// ORIGINAL MODE - Client-side search with Simple DataTables
setTimeout(() => {
const tableElement = document.querySelector('table[data-table="true"]');
if (tableElement && window.brickTableInstance) {
// Enable custom search for minifigures table
window.brickTableInstance.table.searchable = true;
// Connect search input to table
searchInput.addEventListener('input', (e) => {
window.brickTableInstance.table.search(e.target.value);
});
// Clear search
searchClear.addEventListener('click', () => {
searchInput.value = '';
window.brickTableInstance.table.search('');
});
}
}, 100);
}
}
// Setup sort buttons for both modes
setupSortButtons();
// Initialize sort button states and icons for pagination mode
if (isPaginationMode()) {
const urlParams = new URLSearchParams(window.location.search);
const currentSort = urlParams.get('sort');
const currentOrder = urlParams.get('order');
window.initializeSortButtonStates(currentSort, currentOrder);
}
});
function setupSortButtons() {
// Sort button functionality
const sortButtons = document.querySelectorAll('[data-sort-attribute]');
const clearButton = document.querySelector('[data-sort-clear]');
sortButtons.forEach(button => {
button.addEventListener('click', () => {
const attribute = button.dataset.sortAttribute;
const isDesc = button.dataset.sortDesc === 'true';
// Get column index based on attribute
const columnMap = {
'name': 1,
'parts': 2,
'quantity': 3,
'missing': 4,
'damaged': 5,
'sets': 6
};
const columnIndex = columnMap[attribute];
if (columnIndex !== undefined && window.brickTableInstance) {
// Determine sort direction
const isCurrentlyActive = button.classList.contains('btn-primary');
const currentDirection = button.dataset.currentDirection || (isDesc ? 'desc' : 'asc');
const newDirection = isCurrentlyActive ?
(currentDirection === 'asc' ? 'desc' : 'asc') :
(isDesc ? 'desc' : 'asc');
// Clear other active buttons
sortButtons.forEach(btn => {
btn.classList.remove('btn-primary');
btn.classList.add('btn-outline-primary');
btn.removeAttribute('data-current-direction');
});
// Mark this button as active
button.classList.remove('btn-outline-primary');
button.classList.add('btn-primary');
button.dataset.currentDirection = newDirection;
// Apply sort using Simple DataTables API
window.brickTableInstance.table.columns.sort(columnIndex, newDirection);
}
});
});
if (clearButton) {
clearButton.addEventListener('click', () => {
// Clear all sort buttons
sortButtons.forEach(btn => {
btn.classList.remove('btn-primary');
btn.classList.add('btn-outline-primary');
btn.removeAttribute('data-current-direction');
});
// Reset table sort - remove all sorting
if (window.brickTableInstance) {
// Destroy and recreate to clear sorting
const tableElement = document.querySelector('#minifigures');
const currentPerPage = window.brickTableInstance.table.options.perPage;
window.brickTableInstance.table.destroy();
setTimeout(() => {
// Create new instance using the globally available BrickTable class
const newInstance = new window.BrickTable(tableElement, currentPerPage);
window.brickTableInstance = newInstance;
// Re-enable search functionality
newInstance.table.searchable = true;
}, 50);
}
});
}
const columnMap = {
'name': 1,
'parts': 2,
'quantity': 3,
'missing': 4,
'damaged': 5,
'sets': 6
};
// Use shared sort buttons setup from collapsible-state.js
window.setupSharedSortButtons('minifigures', 'brickTableInstance', columnMap);
}

View File

@@ -0,0 +1,182 @@
// Bulk operations for parts in set details page
class PartsBulkOperations {
constructor(accordionId) {
this.accordionId = accordionId;
this.setupModal();
this.setupEventListeners();
}
setupModal() {
// Create Bootstrap modal if it doesn't exist
if (!document.getElementById('partsConfirmModal')) {
const modalHTML = `
<div class="modal fade" id="partsConfirmModal" tabindex="-1" aria-labelledby="partsConfirmModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="partsConfirmModalLabel">Confirm Action</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p id="partsConfirmModalMessage"></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-primary" id="partsConfirmModalConfirm">Confirm</button>
</div>
</div>
</div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', modalHTML);
}
}
setupEventListeners() {
// Mark all as missing (only if missing parts are not hidden)
const markAllMissingBtn = document.getElementById(`mark-all-missing-${this.accordionId}`);
if (markAllMissingBtn) {
markAllMissingBtn.addEventListener('click', (e) => {
e.preventDefault();
this.confirmAndExecute(
'Mark all parts as missing?',
'This will set the missing count to the maximum quantity for all parts in this section.',
() => this.markAllMissing()
);
});
}
// Clear all missing (only if missing parts are not hidden)
const clearAllMissingBtn = document.getElementById(`clear-all-missing-${this.accordionId}`);
if (clearAllMissingBtn) {
clearAllMissingBtn.addEventListener('click', (e) => {
e.preventDefault();
this.confirmAndExecute(
'Clear all missing parts?',
'This will clear the missing field for all parts in this section.',
() => this.clearAllMissing()
);
});
}
// Check all checkboxes (only if checked parts are not hidden)
const checkAllBtn = document.getElementById(`check-all-${this.accordionId}`);
if (checkAllBtn) {
checkAllBtn.addEventListener('click', (e) => {
e.preventDefault();
this.checkAll();
});
}
// Uncheck all checkboxes (only if checked parts are not hidden)
const uncheckAllBtn = document.getElementById(`uncheck-all-${this.accordionId}`);
if (uncheckAllBtn) {
uncheckAllBtn.addEventListener('click', (e) => {
e.preventDefault();
this.uncheckAll();
});
}
}
confirmAndExecute(title, message, callback) {
const modal = document.getElementById('partsConfirmModal');
const modalTitle = document.getElementById('partsConfirmModalLabel');
const modalMessage = document.getElementById('partsConfirmModalMessage');
const confirmBtn = document.getElementById('partsConfirmModalConfirm');
// Set modal content
modalTitle.textContent = title;
modalMessage.textContent = message;
// Remove any existing event listeners and add new one
const newConfirmBtn = confirmBtn.cloneNode(true);
confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
newConfirmBtn.addEventListener('click', () => {
const modalInstance = bootstrap.Modal.getInstance(modal);
modalInstance.hide();
callback();
});
// Show modal
const modalInstance = new bootstrap.Modal(modal);
modalInstance.show();
}
markAllMissing() {
const accordionElement = document.getElementById(this.accordionId);
if (!accordionElement) return;
// Find all rows in this accordion
const rows = accordionElement.querySelectorAll('tbody tr');
rows.forEach(row => {
// Find the quantity cell (usually 4th column)
const quantityCell = row.cells[3]; // Index 3 for quantity column
const missingInput = row.querySelector('input[id*="-missing-"]');
if (quantityCell && missingInput) {
// Extract quantity from cell text content
const quantityText = quantityCell.textContent.trim();
const quantity = parseInt(quantityText) || 1; // Default to 1 if can't parse
if (missingInput.value !== quantity.toString()) {
missingInput.value = quantity.toString();
// Trigger change event to activate BrickChanger
missingInput.dispatchEvent(new Event('change', { bubbles: true }));
}
}
});
}
clearAllMissing() {
const accordionElement = document.getElementById(this.accordionId);
if (!accordionElement) return;
const missingInputs = accordionElement.querySelectorAll('input[id*="-missing-"]');
missingInputs.forEach(input => {
if (input.value !== '') {
input.value = '';
// Trigger change event to activate BrickChanger
input.dispatchEvent(new Event('change', { bubbles: true }));
}
});
}
checkAll() {
const accordionElement = document.getElementById(this.accordionId);
if (!accordionElement) return;
const checkboxes = accordionElement.querySelectorAll('input[id*="-checked-"][type="checkbox"]');
checkboxes.forEach(checkbox => {
if (!checkbox.checked) {
checkbox.checked = true;
// Trigger change event to activate BrickChanger
checkbox.dispatchEvent(new Event('change', { bubbles: true }));
}
});
}
uncheckAll() {
const accordionElement = document.getElementById(this.accordionId);
if (!accordionElement) return;
const checkboxes = accordionElement.querySelectorAll('input[id*="-checked-"][type="checkbox"]');
checkboxes.forEach(checkbox => {
if (checkbox.checked) {
checkbox.checked = false;
// Trigger change event to activate BrickChanger
checkbox.dispatchEvent(new Event('change', { bubbles: true }));
}
});
}
}
// Initialize bulk operations for all part accordions when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
// Find all hamburger menus and initialize bulk operations
const hamburgerMenus = document.querySelectorAll('button[id^="hamburger-"]');
hamburgerMenus.forEach(button => {
const accordionId = button.id.replace('hamburger-', '');
new PartsBulkOperations(accordionId);
});
});

View File

@@ -1,190 +1,27 @@
// Parts page functionality
function applyFilters() {
const ownerSelect = document.getElementById('filter-owner');
const colorSelect = document.getElementById('filter-color');
const currentUrl = new URL(window.location);
// Handle owner filter
if (ownerSelect) {
const selectedOwner = ownerSelect.value;
if (selectedOwner === 'all') {
currentUrl.searchParams.delete('owner');
} else {
currentUrl.searchParams.set('owner', selectedOwner);
}
}
// Handle color filter
if (colorSelect) {
const selectedColor = colorSelect.value;
if (selectedColor === 'all') {
currentUrl.searchParams.delete('color');
} else {
currentUrl.searchParams.set('color', selectedColor);
}
}
window.location.href = currentUrl.toString();
}
function setupColorDropdown() {
const colorSelect = document.getElementById('filter-color');
if (!colorSelect) return;
// Add color squares to option text
const options = colorSelect.querySelectorAll('option[data-color-rgb]');
options.forEach(option => {
const colorRgb = option.dataset.colorRgb;
const colorId = option.dataset.colorId;
const colorName = option.textContent.trim();
if (colorRgb && colorId !== '9999') {
// Create a visual indicator (using Unicode square)
option.textContent = `${colorName}`; //■
//option.style.color = `#${colorRgb}`;
}
});
}
// Parts page functionality - now uses shared functions
// Keep filters expanded after selection
function applyFiltersAndKeepOpen() {
// Remember if filters were open
const filterSection = document.getElementById('table-filter');
const wasOpen = filterSection && filterSection.classList.contains('show');
applyFilters();
// Store the state to restore after page reload
if (wasOpen) {
sessionStorage.setItem('keepFiltersOpen', 'true');
}
window.applyFiltersAndKeepState('parts', 'parts-filter-state');
}
function setupSortButtons() {
// Sort button functionality
const sortButtons = document.querySelectorAll('[data-sort-attribute]');
const clearButton = document.querySelector('[data-sort-clear]');
sortButtons.forEach(button => {
button.addEventListener('click', () => {
const attribute = button.dataset.sortAttribute;
const isDesc = button.dataset.sortDesc === 'true';
// Get column index based on attribute
const columnMap = {
'name': 1,
'color': 2,
'quantity': 3,
'missing': 4,
'damaged': 5,
'sets': 6,
'minifigures': 7
};
const columnIndex = columnMap[attribute];
if (columnIndex !== undefined && window.partsTableInstance) {
// Determine sort direction
const isCurrentlyActive = button.classList.contains('btn-primary');
const currentDirection = button.dataset.currentDirection || (isDesc ? 'desc' : 'asc');
const newDirection = isCurrentlyActive ?
(currentDirection === 'asc' ? 'desc' : 'asc') :
(isDesc ? 'desc' : 'asc');
// Clear other active buttons
sortButtons.forEach(btn => {
btn.classList.remove('btn-primary');
btn.classList.add('btn-outline-primary');
btn.removeAttribute('data-current-direction');
});
// Mark this button as active
button.classList.remove('btn-outline-primary');
button.classList.add('btn-primary');
button.dataset.currentDirection = newDirection;
// Apply sort using Simple DataTables API
window.partsTableInstance.table.columns.sort(columnIndex, newDirection);
}
});
});
if (clearButton) {
clearButton.addEventListener('click', () => {
// Clear all sort buttons
sortButtons.forEach(btn => {
btn.classList.remove('btn-primary');
btn.classList.add('btn-outline-primary');
btn.removeAttribute('data-current-direction');
});
// Reset table sort - remove all sorting
if (window.partsTableInstance) {
// Destroy and recreate to clear sorting
const tableElement = document.querySelector('#parts');
const currentPerPage = window.partsTableInstance.table.options.perPage;
window.partsTableInstance.table.destroy();
setTimeout(() => {
// Create new instance using the globally available BrickTable class
const newInstance = new window.BrickTable(tableElement, currentPerPage);
window.partsTableInstance = newInstance;
// Re-enable search functionality
newInstance.table.searchable = true;
}, 50);
}
});
}
}
// Setup table search and sort functionality
// Initialize parts page
document.addEventListener("DOMContentLoaded", () => {
const searchInput = document.getElementById('table-search');
const searchClear = document.getElementById('table-search-clear');
// Use shared table page initialization
window.initializeTablePage({
pagePrefix: 'parts',
tableId: 'parts',
tableInstanceGlobal: 'partsTableInstance',
sortColumnMap: {
'name': 1,
'color': 2,
'quantity': 3,
'missing': 4,
'damaged': 5,
'sets': 6,
'minifigures': 7
},
hasColorDropdown: true
});
});
// Setup color dropdown with color squares
setupColorDropdown();
// Restore filter state after page load
if (sessionStorage.getItem('keepFiltersOpen') === 'true') {
const filterSection = document.getElementById('table-filter');
const filterButton = document.querySelector('[data-bs-target="#table-filter"]');
if (filterSection && filterButton) {
filterSection.classList.add('show');
filterButton.setAttribute('aria-expanded', 'true');
}
sessionStorage.removeItem('keepFiltersOpen');
}
if (searchInput && searchClear) {
// Wait for table to be initialized by setup_tables
const setupSearch = () => {
const tableElement = document.querySelector('table[data-table="true"]');
if (tableElement && window.partsTableInstance) {
// Enable custom search for parts table
window.partsTableInstance.table.searchable = true;
// Connect search input to table
searchInput.addEventListener('input', (e) => {
window.partsTableInstance.table.search(e.target.value);
});
// Clear search
searchClear.addEventListener('click', () => {
searchInput.value = '';
window.partsTableInstance.table.search('');
});
// Setup sort buttons
setupSortButtons();
} else {
// If table instance not ready, try again
setTimeout(setupSearch, 100);
}
};
setTimeout(setupSearch, 100);
}
});

View File

@@ -0,0 +1,26 @@
// Problems page functionality - now uses shared functions
// Keep filters expanded after selection
function applyFiltersAndKeepOpen() {
window.applyFiltersAndKeepState('problems', 'problems-filter-state');
}
// Initialize problems page
document.addEventListener("DOMContentLoaded", () => {
// Use shared table page initialization
window.initializeTablePage({
pagePrefix: 'problems',
tableId: 'problems',
tableInstanceGlobal: 'problemsTableInstance',
sortColumnMap: {
'name': 1,
'color': 2,
'quantity': 3,
'missing': 4,
'damaged': 5,
'sets': 6,
'minifigures': 7
},
hasColorDropdown: true
});
});

View File

@@ -0,0 +1,15 @@
// Set details page functionality
document.addEventListener('DOMContentLoaded', function() {
const collapseElement = document.getElementById('all-instances');
const toggleIcon = document.getElementById('copies-toggle-icon');
if (collapseElement && toggleIcon) {
collapseElement.addEventListener('shown.bs.collapse', function() {
toggleIcon.className = 'ri-arrow-up-s-line fs-4';
});
collapseElement.addEventListener('hidden.bs.collapse', function() {
toggleIcon.className = 'ri-arrow-down-s-line fs-4';
});
}
});

562
static/scripts/sets.js Normal file
View File

@@ -0,0 +1,562 @@
// Sets page functionality
// Check if we're in pagination mode (server-side) or original mode (client-side)
function isPaginationMode() {
const gridElement = document.querySelector('#grid');
return gridElement && gridElement.getAttribute('data-grid') === 'false';
}
// Initialize filter and sort states for sets page
function initializeCollapsibleStates() {
initializePageCollapsibleStates('sets', 'grid-filter', 'grid-sort');
}
// Setup page functionality
document.addEventListener("DOMContentLoaded", () => {
// Initialize collapsible states (filter and sort)
initializeCollapsibleStates();
const searchInput = document.getElementById('grid-search');
const searchClear = document.getElementById('grid-search-clear');
if (searchInput && searchClear) {
if (isPaginationMode()) {
// PAGINATION MODE - Server-side search
const searchForm = document.createElement('form');
searchForm.style.display = 'none';
searchInput.parentNode.appendChild(searchForm);
searchForm.appendChild(searchInput.cloneNode(true));
// Handle Enter key for search
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
performServerSearch();
}
});
// Handle search button click (if exists)
const searchButton = document.querySelector('[data-search-trigger]');
if (searchButton) {
searchButton.addEventListener('click', performServerSearch);
}
// Clear search
searchClear.addEventListener('click', () => {
searchInput.value = '';
performServerSearch();
});
function performServerSearch() {
const currentUrl = new URL(window.location);
const searchQuery = searchInput.value.trim();
if (searchQuery) {
currentUrl.searchParams.set('search', searchQuery);
} else {
currentUrl.searchParams.delete('search');
}
// Reset to page 1 when searching
currentUrl.searchParams.set('page', '1');
window.location.href = currentUrl.toString();
}
// Setup sort buttons for pagination mode
setupPaginationSortButtons();
// Setup filter dropdowns for pagination mode
setupPaginationFilterDropdowns();
// Initialize filter dropdowns from URL parameters
initializeFilterDropdowns();
// Initialize sort button states and icons for pagination mode
const urlParams = new URLSearchParams(window.location.search);
const currentSort = urlParams.get('sort');
const currentOrder = urlParams.get('order');
window.initializeSortButtonStates(currentSort, currentOrder);
} else {
// ORIGINAL MODE - Client-side filtering with grid scripts
// Initialize filter dropdowns from URL parameters for client-side mode too
initializeClientSideFilterDropdowns();
}
}
});
function setupPaginationSortButtons() {
// Sort button functionality for pagination mode
const sortButtons = document.querySelectorAll('[data-sort-attribute]');
const clearButton = document.querySelector('[data-sort-clear]');
sortButtons.forEach(button => {
button.addEventListener('click', () => {
const attribute = button.dataset.sortAttribute;
const isDesc = button.dataset.sortDesc === 'true';
// PAGINATION MODE - Server-side sorting
const currentUrl = new URL(window.location);
const currentSort = currentUrl.searchParams.get('sort');
const currentOrder = currentUrl.searchParams.get('order');
// Determine new sort direction
let newOrder = isDesc ? 'desc' : 'asc';
if (currentSort === attribute) {
// Toggle direction if clicking the same column
newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
}
currentUrl.searchParams.set('sort', attribute);
currentUrl.searchParams.set('order', newOrder);
// Update sort icon immediately before navigation
updateSortIcon(newOrder);
// Reset to page 1 when sorting
currentUrl.searchParams.set('page', '1');
window.location.href = currentUrl.toString();
});
});
if (clearButton) {
clearButton.addEventListener('click', () => {
// PAGINATION MODE - Clear server-side sorting
const currentUrl = new URL(window.location);
currentUrl.searchParams.delete('sort');
currentUrl.searchParams.delete('order');
// Reset sort icon to default ascending
updateSortIcon('asc');
currentUrl.searchParams.set('page', '1');
window.location.href = currentUrl.toString();
});
}
}
function initializeFilterDropdowns() {
// Set filter dropdown values from URL parameters
const urlParams = new URLSearchParams(window.location.search);
// Set each filter dropdown value if the parameter exists
const yearParam = urlParams.get('year');
if (yearParam) {
const yearDropdown = document.getElementById('grid-year');
if (yearDropdown) {
yearDropdown.value = yearParam;
}
}
const themeParam = urlParams.get('theme');
if (themeParam) {
const themeDropdown = document.getElementById('grid-theme');
if (themeDropdown) {
// Try to set the theme value directly first (for theme names)
themeDropdown.value = themeParam;
// If that didn't work and the param is numeric (theme ID),
// try to find the corresponding theme name by looking at cards
if (themeDropdown.value !== themeParam && /^\d+$/.test(themeParam)) {
// Look for a card with this theme ID and get its theme name
const cardWithTheme = document.querySelector(`[data-theme-id="${themeParam}"]`);
if (cardWithTheme) {
const themeName = cardWithTheme.getAttribute('data-theme');
if (themeName) {
themeDropdown.value = themeName;
}
}
}
}
}
const statusParam = urlParams.get('status');
if (statusParam) {
const statusDropdown = document.getElementById('grid-status');
if (statusDropdown) {
statusDropdown.value = statusParam;
}
}
const ownerParam = urlParams.get('owner');
if (ownerParam) {
const ownerDropdown = document.getElementById('grid-owner');
if (ownerDropdown) {
ownerDropdown.value = ownerParam;
}
}
const purchaseLocationParam = urlParams.get('purchase_location');
if (purchaseLocationParam) {
const purchaseLocationDropdown = document.getElementById('grid-purchase-location');
if (purchaseLocationDropdown) {
purchaseLocationDropdown.value = purchaseLocationParam;
}
}
const storageParam = urlParams.get('storage');
if (storageParam) {
const storageDropdown = document.getElementById('grid-storage');
if (storageDropdown) {
storageDropdown.value = storageParam;
}
}
const tagParam = urlParams.get('tag');
if (tagParam) {
const tagDropdown = document.getElementById('grid-tag');
if (tagDropdown) {
tagDropdown.value = tagParam;
}
}
}
function initializeClientSideFilterDropdowns() {
// Set filter dropdown values from URL parameters and trigger filtering for client-side mode
const urlParams = new URLSearchParams(window.location.search);
let needsFiltering = false;
// Check if we have any filter parameters to avoid flash of all content
const hasFilterParams = urlParams.has('year') || urlParams.has('theme') || urlParams.has('storage') || urlParams.has('purchase_location');
// If we have filter parameters, temporarily hide the grid to prevent flash
if (hasFilterParams) {
const gridElement = document.querySelector('#grid');
if (gridElement && gridElement.getAttribute('data-grid') === 'true') {
gridElement.style.opacity = '0';
}
}
// Set year filter if parameter exists
const yearParam = urlParams.get('year');
if (yearParam) {
const yearDropdown = document.getElementById('grid-year');
if (yearDropdown) {
yearDropdown.value = yearParam;
needsFiltering = true;
}
}
// Set theme filter - handle both theme names and theme IDs
const themeParam = urlParams.get('theme');
if (themeParam) {
const themeDropdown = document.getElementById('grid-theme');
if (themeDropdown) {
if (/^\d+$/.test(themeParam)) {
// Theme parameter is an ID, need to convert to theme name by looking at cards
const themeNameFromId = findThemeNameById(themeParam);
if (themeNameFromId) {
themeDropdown.value = themeNameFromId;
needsFiltering = true;
}
} else {
// Theme parameter is already a name
themeDropdown.value = themeParam.toLowerCase();
needsFiltering = true;
}
}
}
// Set storage filter if parameter exists
const storageParam = urlParams.get('storage');
if (storageParam) {
const storageDropdown = document.getElementById('grid-storage');
if (storageDropdown) {
storageDropdown.value = storageParam;
needsFiltering = true;
}
}
// Set purchase location filter if parameter exists
const purchaseLocationParam = urlParams.get('purchase_location');
if (purchaseLocationParam) {
const purchaseLocationDropdown = document.getElementById('grid-purchase-location');
if (purchaseLocationDropdown) {
purchaseLocationDropdown.value = purchaseLocationParam;
needsFiltering = true;
}
}
// Trigger filtering if any parameters were set
if (needsFiltering) {
// Try to trigger filtering immediately
const tryToFilter = () => {
const gridElement = document.querySelector('#grid');
if (gridElement && gridElement.getAttribute('data-grid') === 'true' && window.gridInstances) {
const gridInstance = window.gridInstances[gridElement.id];
if (gridInstance && gridInstance.filter) {
// This is client-side mode, trigger the filter directly
gridInstance.filter.filter();
// Show the grid again after filtering
if (hasFilterParams) {
gridElement.style.opacity = '1';
gridElement.style.transition = 'opacity 0.2s ease-in-out';
}
return true;
}
}
return false;
};
// Try filtering immediately
if (!tryToFilter()) {
// If not ready, try again with a shorter delay
setTimeout(() => {
if (!tryToFilter()) {
// Final attempt with longer delay
setTimeout(tryToFilter, 100);
}
}, 50);
}
}
}
function findThemeNameById(themeId) {
// Look through all cards to find the theme name for this theme ID
const cards = document.querySelectorAll('.card[data-theme-id]');
for (const card of cards) {
if (card.getAttribute('data-theme-id') === themeId) {
return card.getAttribute('data-theme');
}
}
return null;
}
function setupPaginationFilterDropdowns() {
// Filter dropdown functionality for pagination mode
const filterDropdowns = document.querySelectorAll('#grid-filter select');
filterDropdowns.forEach(dropdown => {
dropdown.addEventListener('change', () => {
performServerFilter();
});
});
function performServerFilter() {
const currentUrl = new URL(window.location);
// Get all filter values
const statusFilter = document.getElementById('grid-status')?.value || '';
const themeFilter = document.getElementById('grid-theme')?.value || '';
const yearFilter = document.getElementById('grid-year')?.value || '';
const ownerFilter = document.getElementById('grid-owner')?.value || '';
const purchaseLocationFilter = document.getElementById('grid-purchase-location')?.value || '';
const storageFilter = document.getElementById('grid-storage')?.value || '';
const tagFilter = document.getElementById('grid-tag')?.value || '';
// Update URL parameters
if (statusFilter) {
currentUrl.searchParams.set('status', statusFilter);
} else {
currentUrl.searchParams.delete('status');
}
if (themeFilter) {
currentUrl.searchParams.set('theme', themeFilter);
} else {
currentUrl.searchParams.delete('theme');
}
if (yearFilter) {
currentUrl.searchParams.set('year', yearFilter);
} else {
currentUrl.searchParams.delete('year');
}
if (ownerFilter) {
currentUrl.searchParams.set('owner', ownerFilter);
} else {
currentUrl.searchParams.delete('owner');
}
if (purchaseLocationFilter) {
currentUrl.searchParams.set('purchase_location', purchaseLocationFilter);
} else {
currentUrl.searchParams.delete('purchase_location');
}
if (storageFilter) {
currentUrl.searchParams.set('storage', storageFilter);
} else {
currentUrl.searchParams.delete('storage');
}
if (tagFilter) {
currentUrl.searchParams.set('tag', tagFilter);
} else {
currentUrl.searchParams.delete('tag');
}
// Reset to page 1 when filtering
currentUrl.searchParams.set('page', '1');
window.location.href = currentUrl.toString();
}
}
// Set grouping functionality
function initializeSetGrouping() {
const groupToggle = document.getElementById('group-identical-sets');
if (!groupToggle) return;
// Load saved state from localStorage
const savedState = localStorage.getItem('groupIdenticalSets') === 'true';
groupToggle.checked = savedState;
// Apply grouping on page load if enabled
if (savedState) {
applySetGrouping();
}
// Listen for toggle changes
groupToggle.addEventListener('change', function() {
// Save state to localStorage
localStorage.setItem('groupIdenticalSets', this.checked);
if (this.checked) {
applySetGrouping();
} else {
removeSetGrouping();
}
});
}
function applySetGrouping() {
const grid = document.getElementById('grid');
if (!grid) return;
const setCards = Array.from(grid.children);
const groupedSets = {};
// Group sets by rebrickable_set_id
setCards.forEach(cardCol => {
const setCard = cardCol.querySelector('.card[data-set-id]');
if (!setCard) return;
const setId = setCard.getAttribute('data-set-id');
const rebrickableId = setCard.getAttribute('data-rebrickable-id');
if (!rebrickableId) return;
if (!groupedSets[rebrickableId]) {
groupedSets[rebrickableId] = [];
}
groupedSets[rebrickableId].push({
cardCol: cardCol,
setId: setId,
rebrickableId: rebrickableId
});
});
// Process each group
Object.keys(groupedSets).forEach(rebrickableId => {
const group = groupedSets[rebrickableId];
if (group.length > 1) {
createGroupedSetDisplay(group);
}
});
}
function createGroupedSetDisplay(setGroup) {
const firstSet = setGroup[0];
const firstCard = firstSet.cardCol.querySelector('.card');
if (!firstCard) return;
// Calculate aggregate stats
let totalMissing = 0;
let totalDamaged = 0;
let allSetIds = [];
setGroup.forEach(set => {
const card = set.cardCol.querySelector('.card');
// Get missing and damaged counts from existing data attributes
const missingCount = parseInt(card.getAttribute('data-missing') || '0');
const damagedCount = parseInt(card.getAttribute('data-damaged') || '0');
totalMissing += missingCount;
totalDamaged += damagedCount;
allSetIds.push(set.setId);
});
// Create grouped card container
const groupContainer = document.createElement('div');
groupContainer.className = firstSet.cardCol.className + ' set-group-container';
groupContainer.innerHTML = `
<div class="card set-group-card">
<div class="card-header d-flex justify-content-between align-items-center">
<div class="d-flex align-items-center">
<button class="btn btn-sm btn-outline-primary me-2 group-toggle-btn"
type="button" data-bs-toggle="collapse"
data-bs-target="#group-${setGroup[0].rebrickableId}"
aria-expanded="false">
<i class="ri-arrow-right-line"></i>
</button>
<span class="fw-bold">${firstCard.querySelector('.card-title')?.textContent || 'Set'}</span>
<span class="badge bg-secondary ms-2">${setGroup.length} sets</span>
</div>
<div class="d-flex gap-1">
${totalMissing > 0 ? `<span class="badge bg-warning text-dark">${totalMissing} missing</span>` : ''}
${totalDamaged > 0 ? `<span class="badge bg-danger">${totalDamaged} damaged</span>` : ''}
</div>
</div>
<div class="collapse" id="group-${setGroup[0].rebrickableId}">
<div class="card-body">
<div class="row set-group-items"></div>
</div>
</div>
</div>
`;
// Add individual set cards to the group
const groupItems = groupContainer.querySelector('.set-group-items');
setGroup.forEach(set => {
const itemContainer = document.createElement('div');
itemContainer.className = 'col-12 mb-2';
// Clone the original card but make it smaller
const clonedCard = set.cardCol.querySelector('.card').cloneNode(true);
clonedCard.classList.add('set-group-item');
itemContainer.appendChild(clonedCard);
groupItems.appendChild(itemContainer);
// Hide the original card
set.cardCol.style.display = 'none';
set.cardCol.classList.add('grouped-set-hidden');
});
// Insert the grouped container before the first hidden set
firstSet.cardCol.parentNode.insertBefore(groupContainer, firstSet.cardCol);
// Add event listener to toggle arrow icon
const toggleBtn = groupContainer.querySelector('.group-toggle-btn');
const collapseElement = groupContainer.querySelector('.collapse');
collapseElement.addEventListener('shown.bs.collapse', () => {
toggleBtn.querySelector('i').className = 'ri-arrow-down-line';
});
collapseElement.addEventListener('hidden.bs.collapse', () => {
toggleBtn.querySelector('i').className = 'ri-arrow-right-line';
});
}
function removeSetGrouping() {
// Show all hidden sets
const hiddenSets = document.querySelectorAll('.grouped-set-hidden');
hiddenSets.forEach(setCol => {
setCol.style.display = '';
setCol.classList.remove('grouped-set-hidden');
});
// Remove all group containers
const groupContainers = document.querySelectorAll('.set-group-container');
groupContainers.forEach(container => {
container.remove();
});
}

View File

@@ -0,0 +1,206 @@
// Peeron Socket class
class BrickPeeronSocket extends BrickSocket {
constructor(id, path, namespace, messages) {
super(id, path, namespace, messages, true);
// Form elements (built based on the initial id)
this.html_button = document.getElementById(id);
this.html_files = document.getElementById(`${id}-files`);
if (this.html_button) {
this.html_button.addEventListener("click", (e) => {
this.execute();
});
}
// Setup select all button
this.setup_select_all_button();
// Setup rotation buttons
this.setup_rotation_buttons();
// Setup the socket
this.setup();
}
setup_select_all_button() {
const selectAllButton = document.getElementById('peeron-select-all');
if (selectAllButton) {
selectAllButton.addEventListener('click', () => {
const checkboxes = this.get_files();
const allChecked = checkboxes.every(cb => cb.checked);
checkboxes.forEach(cb => cb.checked = !allChecked);
// Update button text and icon
if (allChecked) {
selectAllButton.innerHTML = '<i class="ri-checkbox-multiple-line"></i> Select All';
} else {
selectAllButton.innerHTML = '<i class="ri-checkbox-blank-line"></i> Deselect All';
}
});
}
}
setup_rotation_buttons() {
document.querySelectorAll('.peeron-rotate-btn').forEach(button => {
button.addEventListener('click', (e) => {
e.preventDefault(); // Prevent label click
e.stopPropagation(); // Stop event bubbling
const targetId = button.getAttribute('data-target');
const checkboxId = button.getAttribute('data-checkbox');
const targetImg = document.getElementById(targetId);
const checkbox = document.getElementById(checkboxId);
if (targetImg && checkbox) {
let currentRotation = parseInt(button.getAttribute('data-rotation') || '0');
currentRotation = (currentRotation + 90) % 360;
// Update image rotation
targetImg.style.transform = `rotate(${currentRotation}deg)`;
button.setAttribute('data-rotation', currentRotation.toString());
// Store rotation in checkbox data for later use
checkbox.setAttribute('data-rotation', currentRotation.toString());
// Update the rotation icon to indicate current state
const icon = button.querySelector('i');
if (icon) {
// Rotate the icon to match the image rotation
icon.style.transform = `rotate(${currentRotation}deg)`;
}
}
});
});
}
// Upon receiving a complete message
complete(data) {
super.complete(data);
// Clear progress display after completion
if (this.html_progress_message) {
this.html_progress_message.classList.add("d-none");
this.html_progress_message.textContent = "";
}
if (this.html_count) {
this.html_count.classList.add("d-none");
this.html_count.textContent = "";
}
// Ensure spinner is hidden
this.spinner(false);
this.toggle(true);
}
// Execute the action
execute() {
if (!this.disabled && this.socket !== undefined && this.socket.connected) {
this.toggle(false);
this.download_peeron_pages();
}
}
// Get the list of checkboxes describing files
get_files(checked=false) {
let files = [];
if (this.html_files) {
files = [...this.html_files.querySelectorAll('input[type="checkbox"]')];
if (checked) {
files = files.filter(file => file.checked);
}
}
return files;
}
// Download Peeron pages
download_peeron_pages() {
if (this.html_files) {
const selectedFiles = this.get_files(true);
if (selectedFiles.length === 0) {
this.fail({message: "Please select at least one page to download."});
this.toggle(true);
return;
}
const pages = selectedFiles.map(checkbox => ({
page_number: checkbox.getAttribute('data-page-number'),
original_image_url: checkbox.getAttribute('data-original-image-url'),
cached_full_image_path: checkbox.getAttribute('data-cached-full-image-path'),
alt_text: checkbox.getAttribute('data-alt-text'),
rotation: parseInt(checkbox.getAttribute('data-rotation') || '0')
}));
this.clear();
this.spinner(true);
const setElement = document.querySelector('input[name="download-set"]');
const set = setElement ? setElement.value : '';
this.socket.emit(this.messages.DOWNLOAD_PEERON_PAGES, {
set: set,
pages: pages,
total: pages.length,
current: 0
});
} else {
this.fail({message: "Could not find the list of pages to download"});
}
}
// Toggle clicking on the button, or sending events
toggle(enabled) {
super.toggle(enabled);
if (this.html_files) {
this.get_files().forEach(el => el.disabled = !enabled);
}
if (this.html_button) {
this.html_button.disabled = !enabled;
}
}
}
// Simple Peeron page loader using standard socket pattern
class BrickPeeronPageLoader extends BrickSocket {
constructor(set, path, namespace, messages) {
// Use 'peeron-loader' as the ID for socket elements
super('peeron-loader', path, namespace, messages, false);
this.set = set;
this.setup();
// Auto-start loading when connected
setTimeout(() => {
if (this.socket && this.socket.connected) {
this.loadPages();
} else {
this.socket.on('connect', () => this.loadPages());
}
}, 100);
}
loadPages() {
this.socket.emit(this.messages.LOAD_PEERON_PAGES, {
set: this.set
});
}
// Override complete to redirect when done
complete(data) {
super.complete(data);
// Redirect to show the pages selection interface
const params = new URLSearchParams();
params.set('set', this.set);
params.set('peeron_loaded', '1');
window.location.href = `${window.location.pathname}?${params.toString()}`;
}
}

View File

@@ -0,0 +1,153 @@
/**
* Statistics page chart functionality
*/
document.addEventListener('DOMContentLoaded', function() {
// Check if charts are enabled and chart data exists
if (typeof window.chartData === 'undefined') {
return;
}
// Debug: Log chart data to console
console.log('Chart Data:', window.chartData);
// Common chart configuration
const commonConfig = {
type: 'line',
options: {
responsive: true,
maintainAspectRatio: false,
interaction: {
intersect: false,
mode: 'index'
},
scales: {
x: {
title: {
display: true,
text: 'Release Year'
},
grid: {
display: false
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Count'
},
ticks: {
precision: 0
}
}
},
plugins: {
legend: {
display: false
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleColor: 'white',
bodyColor: 'white',
cornerRadius: 4
}
},
elements: {
point: {
radius: 3,
hoverRadius: 5
},
line: {
borderWidth: 2
}
}
}
};
// Sets Chart
const setsCanvas = document.getElementById('setsChart');
if (setsCanvas) {
const setsCtx = setsCanvas.getContext('2d');
new Chart(setsCtx, {
...commonConfig,
data: {
labels: window.chartData.years,
datasets: [{
label: 'Sets',
data: window.chartData.sets,
borderColor: '#0d6efd',
backgroundColor: 'rgba(13, 110, 253, 0.1)',
fill: true,
tension: 0.3
}]
}
});
}
// Parts Chart
const partsCanvas = document.getElementById('partsChart');
if (partsCanvas) {
const partsCtx = partsCanvas.getContext('2d');
new Chart(partsCtx, {
...commonConfig,
data: {
labels: window.chartData.years,
datasets: [{
label: 'Parts',
data: window.chartData.parts,
borderColor: '#198754',
backgroundColor: 'rgba(25, 135, 84, 0.1)',
fill: true,
tension: 0.3
}]
},
options: {
...commonConfig.options,
scales: {
...commonConfig.options.scales,
y: {
...commonConfig.options.scales.y,
title: {
display: true,
text: 'Parts Count'
}
}
}
}
});
}
// Minifigures Chart
const minifigsCanvas = document.getElementById('minifigsChart');
if (minifigsCanvas) {
const minifigsCtx = minifigsCanvas.getContext('2d');
new Chart(minifigsCtx, {
...commonConfig,
data: {
labels: window.chartData.years,
datasets: [{
label: 'Minifigures',
data: window.chartData.minifigs,
borderColor: '#fd7e14',
backgroundColor: 'rgba(253, 126, 20, 0.1)',
fill: true,
tension: 0.3
}]
},
options: {
...commonConfig.options,
scales: {
...commonConfig.options.scales,
y: {
...commonConfig.options.scales.y,
title: {
display: true,
text: 'Minifigures Count'
}
}
}
}
});
}
});

View File

@@ -36,14 +36,19 @@ window.BrickTable = class BrickTable {
// Special configuration for tables with custom search/sort
const isMinifiguresTable = table.id === 'minifigures';
const isPartsTable = table.id === 'parts';
const hasCustomInterface = isMinifiguresTable || isPartsTable;
const isProblemsTable = table.id === 'problems';
const isPartsTablePaginationMode = isPartsTable && table.getAttribute('data-table') === 'false';
const isProblemsTablePaginationMode = isProblemsTable && table.getAttribute('data-table') === 'false';
const hasCustomInterface = isMinifiguresTable || isPartsTablePaginationMode || isProblemsTablePaginationMode;
const hasCustomSearch = isPartsTable || isProblemsTable || isMinifiguresTable; // Parts, problems, and minifigures always have custom search
this.table = new simpleDatatables.DataTable(`#${table.id}`, {
columns: columns,
paging: !(isPartsTablePaginationMode || isProblemsTablePaginationMode), // Disable built-in pagination for tables in pagination mode
pagerDelta: 1,
perPage: per_page,
perPageSelect: [10, 25, 50, 100, 500, 1000],
searchable: !hasCustomInterface, // Disable built-in search for tables with custom interface
searchable: !hasCustomSearch, // Disable built-in search for tables with custom search
searchMethod: (table => (terms, cell, row, column, source) => table.search(terms, cell, row, column, source))(this),
searchQuerySeparator: "",
tableRender: () => {
@@ -105,6 +110,8 @@ const setup_tables = (per_page) => document.querySelectorAll('table[data-table="
window.brickTableInstance = brickTable;
} else if (el.id === 'parts') {
window.partsTableInstance = brickTable;
} else if (el.id === 'problems') {
window.problemsTableInstance = brickTable;
}
}
);

View File

@@ -50,6 +50,67 @@
max-width: 150px;
}
/* Checkbox column width constraint */
.table-td-input:has(.form-check-input[type="checkbox"]) {
width: 120px;
max-width: 120px;
min-width: 120px;
}
/* Reserve space for status icon to prevent layout shift */
.form-check-label i[id^="status-"] {
display: inline-block;
width: 1.2em;
text-align: center;
margin-left: 0.25rem;
}
/* Hamburger menu styling */
.table th .dropdown {
position: relative;
}
.table th .dropdown-toggle {
border-radius: 0.375rem;
padding: 0.25rem 0.5rem;
font-size: 0.875rem;
line-height: 1.25rem;
border-color: #6c757d;
}
.table th .dropdown-toggle:focus {
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
.table th .dropdown-toggle:hover {
background-color: #f8f9fa;
border-color: #6c757d;
}
/* Style dropdown items */
.dropdown-menu .dropdown-header {
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
color: #6c757d;
padding: 0.25rem 1rem;
}
.dropdown-menu .dropdown-item {
font-size: 0.875rem;
padding: 0.5rem 1rem;
}
.dropdown-menu .dropdown-item:hover {
background-color: #f8f9fa;
color: #212529;
}
.dropdown-menu .dropdown-item i {
width: 1.25rem;
text-align: center;
}
/* Fixes for sortable.js */
.sortable {
--th-color: #000 !important;
@@ -77,4 +138,44 @@
linear-gradient(127deg, rgb(0 255 0 / 80%), rgb(0 255 0 / 0%) 70.71%),
linear-gradient(336deg, rgb(0 0 255 / 80%), rgb(0 0 255 / 0%) 70.71%)
;
}
/* Mobile Pagination Fixes */
.mobile-pagination {
display: flex !important;
width: 100% !important;
gap: 2px;
}
.mobile-pagination .btn:first-child,
.mobile-pagination .btn:last-child {
flex: 0 0 auto;
min-width: 90px;
max-width: 120px;
}
.mobile-pagination .btn:nth-child(2) {
flex: 1 1 auto;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
}
/* Partial Status Checkbox Styling */
.partial-status {
position: relative;
}
.partial-status::after {
content: '';
position: absolute;
top: 2px;
left: 2px;
right: 2px;
bottom: 2px;
background: #6f42c1;
border-radius: 2px;
opacity: 0.8;
pointer-events: none;
}

View File

@@ -12,6 +12,7 @@
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanillajs-datepicker@1.3.4/dist/css/datepicker-bs5.min.css">
<link href="{{ url_for('static', filename='styles.css') }}" rel="stylesheet">
<link rel="icon" type="image/png" sizes="48x48" href="{{ url_for('static', filename='brick.png') }}">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.5.0/dist/chart.umd.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
@@ -81,6 +82,7 @@
<script src="https://cdn.jsdelivr.net/npm/simple-datatables@9.2.1/dist/umd/simple-datatables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vanillajs-datepicker@1.3.4/dist/js/datepicker-full.min.js"></script>
<!-- BrickTracker scripts -->
<script src="{{ url_for('static', filename='scripts/collapsible-state.js') }}"></script>
<script src="{{ url_for('static', filename='scripts/changer.js') }}"></script>
<script src="{{ url_for('static', filename='scripts/grid/filter.js') }}"></script>
<script src="{{ url_for('static', filename='scripts/grid/grid.js') }}"></script>
@@ -97,6 +99,23 @@
{% if request.endpoint == 'part.list' %}
<script src="{{ url_for('static', filename='scripts/parts.js') }}"></script>
{% endif %}
{% if request.endpoint == 'part.problem' %}
<script src="{{ url_for('static', filename='scripts/parts.js') }}"></script>
<script src="{{ url_for('static', filename='scripts/problems.js') }}"></script>
{% endif %}
{% if request.endpoint == 'set.list' %}
<script src="{{ url_for('static', filename='scripts/sets.js') }}"></script>
{% endif %}
{% if request.endpoint == 'set.details' %}
<script src="{{ url_for('static', filename='scripts/parts-bulk-operations.js') }}"></script>
<script src="{{ url_for('static', filename='scripts/set-details.js') }}"></script>
{% endif %}
{% if request.endpoint == 'statistics.overview' %}
<script src="{{ url_for('static', filename='scripts/statistics.js') }}"></script>
{% endif %}
{% if request.endpoint == 'instructions.download' or request.endpoint == 'instructions.do_download' %}
<script src="{{ url_for('static', filename='scripts/socket/peeron.js') }}"></script>
{% endif %}
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", () => {
setup_grids();

View File

@@ -16,7 +16,7 @@
{% if g.login.is_authenticated() %}
<p class="border-bottom pb-2 px-2 text-center">
<a class="btn btn-primary" href="{{ url_for('instructions.upload') }}"><i class="ri-upload-line"></i> Upload an instructions file</a>
<a class="btn btn-primary" href="{{ url_for('instructions.download') }}"><i class="ri-download-line"></i> Download instructions from Rebrickable</a>
<a class="btn btn-primary" href="{{ url_for('instructions.download') }}"><i class="ri-download-line"></i> Download instructions</a>
<a href="{{ url_for('admin.admin', open_instructions=true) }}" class="btn btn-light border" role="button"><i class="ri-refresh-line"></i> Refresh the instructions cache</a>
</p>
{% endif %}

View File

@@ -5,7 +5,7 @@
<form method="POST" action="{{ url_for('instructions.do_download') }}">
<div class="card mb-3">
<div class="card-header">
<h5 class="mb-0"><i class="ri-download-line"></i> Download instructions from Rebrickable</h5>
<h5 class="mb-0"><i class="ri-download-line"></i> Download instructions</h5>
</div>
<div class="card-body">
<div class="mb-3">

View File

@@ -0,0 +1,15 @@
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", () => {
new BrickPeeronPageLoader(
'{{ set }}',
'{{ path }}',
'{{ namespace }}',
{
COMPLETE: '{{ messages['COMPLETE'] }}',
FAIL: '{{ messages['FAIL'] }}',
LOAD_PEERON_PAGES: '{{ messages['LOAD_PEERON_PAGES'] }}',
PROGRESS: '{{ messages['PROGRESS'] }}',
}
);
});
</script>

View File

@@ -0,0 +1,10 @@
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", () => {
new BrickPeeronSocket('peeron-download', '{{ path }}', '{{ namespace }}', {
COMPLETE: '{{ messages['COMPLETE'] }}',
DOWNLOAD_PEERON_PAGES: 'download_peeron_pages',
FAIL: '{{ messages['FAIL'] }}',
PROGRESS: '{{ messages['PROGRESS'] }}',
});
});
</script>

View File

@@ -1,4 +1,4 @@
{% macro header(title, id, parent, quantity=none, expanded=false, icon=none, class=none, danger=none, image=none, alt=none) %}
{% macro header(title, id, parent, quantity=none, expanded=false, icon=none, class=none, danger=none, image=none, alt=none, hamburger_menu=none) %}
{% if danger %}
{% set icon='alert-fill' %}
{% endif %}
@@ -43,10 +43,10 @@
{% endif %}
{% endmacro %}
{% macro table(table_collection, title, id, parent, target, quantity=none, icon=none, image=none, alt=none, details=none, read_only=none) %}
{% macro table(table_collection, title, id, parent, target, quantity=none, icon=none, image=none, alt=none, details=none, read_only=none, hamburger_menu=none) %}
{% set size=table_collection | length %}
{% if size %}
{{ header(title, id, parent, quantity=quantity, icon=icon, class='p-0', image=image, alt=alt) }}
{{ header(title, id, parent, quantity=quantity, icon=icon, class='p-0', image=image, alt=alt, hamburger_menu=hamburger_menu) }}
{% if details %}
<p class="border-top border-bottom p-2 text-center">
{% if image %}
@@ -57,7 +57,7 @@
<a class="btn border bg-secondary-text" href="{{ details }}">{% if icon %}<i class="ri-{{ icon }}"></i>{% endif %} Details</a>
</p>
{% endif %}
{% with solo=true, all=false %}
{% with solo=true, all=false, accordion_id=id %}
{% include target %}
{% endwith %}
{{ footer() }}

View File

@@ -65,24 +65,55 @@
{% endif %}
{% endmacro %}
{% macro purchase_date(date, solo=false, last=false) %}
{% if last %}
{% set tooltip=date %}
{% macro purchase_date(date, solo=false, last=false, date_max_formatted=none) %}
{% if date_max_formatted and date_max_formatted != date %}
{# Date range for consolidated sets #}
{% set date_range = date ~ ' - ' ~ date_max_formatted %}
{% if last %}
{% set tooltip=date_range %}
{% else %}
{% set text=date_range %}
{% endif %}
{% else %}
{% set text=date %}
{# Single date #}
{% if last %}
{% set tooltip=date %}
{% else %}
{% set text=date %}
{% endif %}
{% endif %}
{{ badge(check=date, solo=solo, last=last, color='light border', icon='calendar-line', text=text, tooltip=tooltip, collapsible='Date:') }}
{% endmacro %}
{% macro purchase_location(item, purchase_locations, solo=false, last=false) %}
{% if purchase_locations and item.fields.purchase_location in purchase_locations.mapping %}
{% set purchase_location = purchase_locations.mapping[item.fields.purchase_location] %}
{% if last %}
{% set tooltip=purchase_location.fields.name %}
{% if purchase_locations and item.fields.purchase_location %}
{% if '|' in item.fields.purchase_location or ',' in item.fields.purchase_location %}
{# Consolidated mode - multiple purchase locations #}
{% set separator = '|' if '|' in item.fields.purchase_location else ',' %}
{% set location_list = item.fields.purchase_location.split(separator) %}
{% for location_id in location_list %}
{% if location_id and location_id.strip() and location_id.strip() in purchase_locations.mapping %}
{% set purchase_location = purchase_locations.mapping[location_id.strip()] %}
{% if last %}
{% set tooltip=purchase_location.fields.name %}
{% else %}
{% set text=purchase_location.fields.name %}
{% endif %}
{{ badge(check=purchase_location, solo=solo, last=last, color='light border', icon='building-line', text=text, tooltip=tooltip, collapsible='Location:') }}
{% endif %}
{% endfor %}
{% else %}
{% set text=purchase_location.fields.name %}
{# Single purchase location #}
{% if item.fields.purchase_location.strip() and item.fields.purchase_location.strip() in purchase_locations.mapping %}
{% set purchase_location = purchase_locations.mapping[item.fields.purchase_location.strip()] %}
{% if last %}
{% set tooltip=purchase_location.fields.name %}
{% else %}
{% set text=purchase_location.fields.name %}
{% endif %}
{{ badge(check=purchase_location, solo=solo, last=last, color='light border', icon='building-line', text=text, tooltip=tooltip, collapsible='Location:') }}
{% endif %}
{% endif %}
{{ badge(check=purchase_location, solo=solo, last=last, color='light border', icon='building-line', text=text, tooltip=tooltip, collapsible='Location:') }}
{% endif %}
{% endmacro %}
@@ -103,14 +134,34 @@
{% endmacro %}
{% macro storage(item, storages, solo=false, last=false) %}
{% if storages and item.fields.storage in storages.mapping %}
{% set storage = storages.mapping[item.fields.storage] %}
{% if last %}
{% set tooltip=storage.fields.name %}
{% if storages and item.fields.storage %}
{% if '|' in item.fields.storage or ',' in item.fields.storage %}
{# Consolidated mode - multiple storage locations #}
{% set separator = '|' if '|' in item.fields.storage else ',' %}
{% set storage_list = item.fields.storage.split(separator) %}
{% for storage_id in storage_list %}
{% if storage_id and storage_id.strip() and storage_id.strip() in storages.mapping %}
{% set storage = storages.mapping[storage_id.strip()] %}
{% if last %}
{% set tooltip=storage.fields.name %}
{% else %}
{% set text=storage.fields.name %}
{% endif %}
{{ badge(url=storage.url(), solo=solo, last=last, color='light text-warning-emphasis bg-warning-subtle border border-warning-subtle', icon='archive-2-line', text=text, alt='Storage', tooltip=tooltip) }}
{% endif %}
{% endfor %}
{% else %}
{% set text=storage.fields.name %}
{# Single storage location #}
{% if item.fields.storage.strip() and item.fields.storage.strip() in storages.mapping %}
{% set storage = storages.mapping[item.fields.storage.strip()] %}
{% if last %}
{% set tooltip=storage.fields.name %}
{% else %}
{% set text=storage.fields.name %}
{% endif %}
{{ badge(url=storage.url(), solo=solo, last=last, color='light text-warning-emphasis bg-warning-subtle border border-warning-subtle', icon='archive-2-line', text=text, alt='Storage', tooltip=tooltip) }}
{% endif %}
{% endif %}
{{ badge(url=item.url_for_storage(), solo=solo, last=last, color='light text-warning-emphasis bg-warning-subtle border border-warning-subtle', icon='archive-2-line', text=text, alt='Storage', tooltip=tooltip) }}
{% endif %}
{% endmacro %}

View File

@@ -1,4 +1,4 @@
{% macro header(image=true, color=false, parts=false, quantity=false, missing=true, missing_parts=false, damaged=true, damaged_parts=false, sets=false, minifigures=false) %}
{% macro header(image=true, color=false, parts=false, quantity=false, missing=true, missing_parts=false, damaged=true, damaged_parts=false, sets=false, minifigures=false, checked=false, hamburger_menu=false, accordion_id='') %}
<thead>
<tr>
{% if image %}
@@ -26,6 +26,37 @@
{% if minifigures %}
<th data-table-number="true" scope="col"><i class="ri-group-line fw-normal"></i> Minifigures</th>
{% endif %}
{% if checked and not config['HIDE_TABLE_CHECKED_PARTS'] %}
<th data-table-no-sort-and-search="true" class="no-sort" scope="col"><i class="ri-checkbox-line fw-normal"></i> Checked</th>
{% endif %}
{% if hamburger_menu and g.login.is_authenticated() %}
{% set show_missing_menu = not config['HIDE_TABLE_MISSING_PARTS'] %}
{% set show_checked_menu = not config['HIDE_TABLE_CHECKED_PARTS'] %}
{% if show_missing_menu or show_checked_menu %}
<th data-table-no-sort-and-search="true" class="no-sort text-end" scope="col">
<div class="dropdown">
<button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="hamburger-{{ accordion_id }}" data-bs-toggle="dropdown" aria-expanded="false">
<i class="ri-menu-line"></i>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="hamburger-{{ accordion_id }}">
{% if show_missing_menu %}
<li><h6 class="dropdown-header">Missing Parts</h6></li>
<li><a class="dropdown-item" href="#" id="mark-all-missing-{{ accordion_id }}"><i class="ri-question-line me-2"></i>Mark all as missing</a></li>
<li><a class="dropdown-item" href="#" id="clear-all-missing-{{ accordion_id }}"><i class="ri-close-circle-line me-2"></i>Clear all missing</a></li>
{% endif %}
{% if show_missing_menu and show_checked_menu %}
<li><hr class="dropdown-divider"></li>
{% endif %}
{% if show_checked_menu %}
<li><h6 class="dropdown-header">Checked Status</h6></li>
<li><a class="dropdown-item" href="#" id="check-all-{{ accordion_id }}"><i class="ri-checkbox-line me-2"></i>Check all</a></li>
<li><a class="dropdown-item" href="#" id="uncheck-all-{{ accordion_id }}"><i class="ri-checkbox-blank-line me-2"></i>Uncheck all</a></li>
{% endif %}
</ul>
</div>
</th>
{% endif %}
{% endif %}
</tr>
</thead>
{% endmacro %}

View File

@@ -0,0 +1,22 @@
{% import 'macro/table.html' as table %}
<tbody>
{% for minifigure in table_collection %}
<tr>
{{ table.image(minifigure.url_for_image(), caption=minifigure.fields.name, alt=minifigure.fields.figure) }}
<td data-sort="{{ minifigure.fields.name }}">
<a class="text-reset" href="{{ minifigure.url() }}">{{ minifigure.fields.name }}</a>
{{ table.rebrickable(minifigure) }}
</td>
<td data-sort="{{ minifigure.fields.number_of_parts }}">{{ minifigure.fields.number_of_parts }}</td>
<td data-sort="{{ minifigure.fields.total_quantity }}">{{ minifigure.fields.total_quantity }}</td>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<td data-sort="{{ minifigure.fields.total_missing }}">{{ minifigure.fields.total_missing }}</td>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<td data-sort="{{ minifigure.fields.total_damaged }}">{{ minifigure.fields.total_damaged }}</td>
{% endif %}
<td data-sort="{{ minifigure.fields.total_sets }}">{{ minifigure.fields.total_sets }}</td>
</tr>
{% endfor %}
</tbody>

View File

@@ -1,4 +1,5 @@
{% extends 'base.html' %}
{% import 'macro/table.html' as table %}
{% block title %} - All minifigures{% endblock %}
@@ -10,7 +11,7 @@
<label class="visually-hidden" for="table-search">Search</label>
<div class="input-group">
<span class="input-group-text"><i class="ri-search-line"></i><span class="ms-1 d-none d-md-inline"> Search</span></span>
<input id="table-search" class="form-control form-control-sm px-1" type="text" placeholder="Figure name, parts count, sets" value="">
<input id="table-search" class="form-control form-control-sm px-1" type="text" placeholder="Figure name, parts count, sets" value="{{ search_query or '' }}">
<button id="table-search-clear" type="button" class="btn btn-light btn-outline-danger border"><i class="ri-eraser-line"></i></button>
</div>
</div>
@@ -19,24 +20,159 @@
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#table-sort" aria-expanded="{% if config['SHOW_GRID_SORT'] %}true{% else %}false{% endif %}" aria-controls="table-sort">
<i class="ri-sort-asc"></i> Sort
</button>
</div>
</div>
{% if owners | length > 1 %}
<div class="col-12">
<div class="input-group">
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#table-filter" aria-expanded="{% if config['SHOW_GRID_FILTERS'] %}true{% else %}false{% endif %}" aria-controls="table-filter">
<i class="ri-filter-line"></i> Filters
</button>
</div>
</div>
{% endif %}
</div>
{% include 'minifigure/sort.html' %}
{% include 'minifigure/filter.html' %}
{% with all=true %}
{% include 'minifigure/table.html' %}
{% endwith %}
{% if use_pagination %}
<!-- PAGINATION MODE -->
<div class="table-responsive-sm">
<table data-table="false" class="table table-striped align-middle mb-0" id="minifigures">
{{ table.header(parts=true, quantity=true, missing=true, damaged=true, sets=true, minifigures=false) }}
{% include 'minifigure/table_body.html' %}
</table>
</div>
<!-- Pagination -->
<div>
{% if pagination and pagination.total_pages > 1 %}
<div class="row mt-4">
<div class="col-12">
<!-- Desktop Pagination -->
<div class="d-none d-md-block">
<nav aria-label="Minifigures pagination">
<ul class="pagination justify-content-center">
{% if pagination.has_prev %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.page - 1) }}">
<i class="ri-arrow-left-line"></i> Previous
</a>
</li>
{% endif %}
<!-- Show page numbers (with smart truncation) -->
{% set start_page = [1, pagination.page - 2] | max %}
{% set end_page = [pagination.total_pages, pagination.page + 2] | min %}
{% if start_page > 1 %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', 1) }}">1</a>
</li>
{% if start_page > 2 %}
<li class="page-item disabled"><span class="page-link">...</span></li>
{% endif %}
{% endif %}
{% for page_num in range(start_page, end_page + 1) %}
{% if page_num == pagination.page %}
<li class="page-item active">
<span class="page-link">{{ page_num }}</span>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', page_num) }}">{{ page_num }}</a>
</li>
{% endif %}
{% endfor %}
{% if end_page < pagination.total_pages %}
{% if end_page < pagination.total_pages - 1 %}
<li class="page-item disabled"><span class="page-link">...</span></li>
{% endif %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.total_pages) }}">{{ pagination.total_pages }}</a>
</li>
{% endif %}
{% if pagination.has_next %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.page + 1) }}">
Next <i class="ri-arrow-right-line"></i>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
<!-- Mobile Pagination -->
<div class="d-md-none">
<div class="mobile-pagination" role="group" aria-label="Mobile pagination">
{% if pagination.has_prev %}
<a href="{{ request.url | replace_query('page', pagination.page - 1) }}"
class="btn btn-outline-primary">
<i class="ri-arrow-left-line"></i> Previous
</a>
{% else %}
<button class="btn btn-outline-secondary" disabled>
<i class="ri-arrow-left-line"></i> Previous
</button>
{% endif %}
<span class="btn btn-light">
Page {{ pagination.page }} of {{ pagination.total_pages }}
</span>
{% if pagination.has_next %}
<a href="{{ request.url | replace_query('page', pagination.page + 1) }}"
class="btn btn-outline-primary">
Next <i class="ri-arrow-right-line"></i>
</a>
{% else %}
<button class="btn btn-outline-secondary" disabled>
Next <i class="ri-arrow-right-line"></i>
</button>
{% endif %}
</div>
</div>
<!-- Results Info -->
<div class="text-center mt-3">
<small class="text-muted">
Showing {{ ((pagination.page - 1) * pagination.per_page + 1) }} to
{{ [pagination.page * pagination.per_page, pagination.total_count] | min }}
of {{ pagination.total_count }} minifigures
</small>
</div>
</div>
</div>
{% endif %}
</div>
{% else %}
<!-- ORIGINAL MODE - Single page with client-side search -->
<div class="table-responsive-sm">
<table data-table="true" class="table table-striped align-middle {% if not all %}sortable mb-0{% endif %}" id="minifigures">
{{ table.header(parts=true, quantity=true, missing=true, damaged=true, sets=true, minifigures=false) }}
<tbody>
{% for minifigure in table_collection %}
<tr>
{{ table.image(minifigure.url_for_image(), caption=minifigure.fields.name, alt=minifigure.fields.figure) }}
<td data-sort="{{ minifigure.fields.name }}">
<a class="text-reset" href="{{ minifigure.url() }}">{{ minifigure.fields.name }}</a>
{{ table.rebrickable(minifigure) }}
</td>
<td data-sort="{{ minifigure.fields.number_of_parts }}">{{ minifigure.fields.number_of_parts }}</td>
<td data-sort="{{ minifigure.fields.total_quantity }}">{{ minifigure.fields.total_quantity }}</td>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<td data-sort="{{ minifigure.fields.total_missing }}">{{ minifigure.fields.total_missing }}</td>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<td data-sort="{{ minifigure.fields.total_damaged }}">{{ minifigure.fields.total_damaged }}</td>
{% endif %}
<td data-sort="{{ minifigure.fields.total_sets }}">{{ minifigure.fields.total_sets }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</div>
{% else %}
<div class="container-fluid">
@@ -52,4 +188,4 @@
</div>
{% endif %}
{% endblock %}
{% endblock %}

View File

@@ -3,7 +3,7 @@
<div class="table-responsive-sm">
<table data-table="{% if all %}true{% endif %}" class="table table-striped align-middle {% if not all %}sortable mb-0{% endif %}" {% if all %}id="parts"{% endif %}>
{{ table.header(color=true, quantity=not no_quantity, sets=all, minifigures=all) }}
{{ table.header(color=true, quantity=not no_quantity, sets=all, minifigures=all, checked=not all and not read_only, hamburger_menu=not all and not read_only, accordion_id=accordion_id|default('')) }}
<tbody>
{% for item in table_collection %}
<tr>
@@ -40,6 +40,19 @@
{% if all %}
<td>{{ item.fields.total_sets }}</td>
<td>{{ item.fields.total_minifigures }}</td>
{% else %}
{% if not config['HIDE_TABLE_CHECKED_PARTS'] and not read_only %}
<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=read_only) }}</center>
</td>
{% endif %}
{% if g.login.is_authenticated() and not read_only %}
{% set show_missing_menu = not config['HIDE_TABLE_MISSING_PARTS'] %}
{% set show_checked_menu = not config['HIDE_TABLE_CHECKED_PARTS'] %}
{% if show_missing_menu or show_checked_menu %}
<td></td>
{% endif %}
{% endif %}
{% endif %}
</tr>
{% endfor %}

View File

@@ -0,0 +1,35 @@
{% import 'macro/form.html' as form %}
{% import 'macro/table.html' as table %}
<tbody>
{% for item in table_collection %}
<tr>
{{ table.image(item.url_for_image(), caption=item.fields.name, alt=item.fields.part, accordion=solo) }}
<td data-sort="{{ item.fields.name }}">
<a class="text-reset" href="{{ item.url() }}">{{ item.fields.name }}</a>
{% if item.fields.spare %}<span class="badge rounded-pill text-bg-warning fw-normal"><i class="ri-loop-left-line"></i> Spare</span>{% endif %}
{% if all %}
{{ table.rebrickable(item) }}
{{ table.bricklink(item) }}
{% endif %}
</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>{{ item.fields.total_quantity }}</td>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<td data-sort="{{ item.fields.total_missing }}" class="table-td-input">
{{ form.input('Missing', item.fields.id, item.html_id('missing'), item.url_for_problem('missing'), item.fields.total_missing, all=all, read_only=read_only) }}
</td>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<td data-sort="{{ item.fields.total_damaged }}" class="table-td-input">
{{ form.input('Damaged', item.fields.id, item.html_id('damaged'), item.url_for_problem('damaged'), item.fields.total_damaged, all=all, read_only=read_only) }}
</td>
{% endif %}
<td>{{ item.fields.total_sets }}</td>
<td>{{ item.fields.total_minifigures }}</td>
</tr>
{% endfor %}
</tbody>

View File

@@ -1,4 +1,6 @@
{% extends 'base.html' %}
{% import 'macro/form.html' as form %}
{% import 'macro/table.html' as table %}
{% block title %} - All parts{% endblock %}
@@ -10,7 +12,7 @@
<label class="visually-hidden" for="table-search">Search</label>
<div class="input-group">
<span class="input-group-text"><i class="ri-search-line"></i><span class="ms-1 d-none d-md-inline"> Search</span></span>
<input id="table-search" class="form-control form-control-sm px-1" type="text" placeholder="Part name, color, quantity, sets" value="">
<input id="table-search" class="form-control form-control-sm px-1" type="text" placeholder="Part name, color, quantity, sets" value="{{ search_query or '' }}">
<button id="table-search-clear" type="button" class="btn btn-light btn-outline-danger border"><i class="ri-eraser-line"></i></button>
</div>
</div>
@@ -19,10 +21,6 @@
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#table-sort" aria-expanded="{% if config['SHOW_GRID_SORT'] %}true{% else %}false{% endif %}" aria-controls="table-sort">
<i class="ri-sort-asc"></i> Sort
</button>
</div>
</div>
<div class="col-12">
<div class="input-group">
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#table-filter" aria-expanded="{% if config['SHOW_GRID_FILTERS'] %}true{% else %}false{% endif %}" aria-controls="table-filter">
<i class="ri-filter-line"></i> Filters
</button>
@@ -32,9 +30,162 @@
{% include 'part/sort.html' %}
{% include 'part/filter.html' %}
{% with all=true %}
{% include 'part/table.html' %}
{% endwith %}
{% if use_pagination %}
<!-- PAGINATION MODE -->
<div class="table-responsive-sm">
<table data-table="false" class="table table-striped align-middle mb-0" id="parts">
{{ table.header(color=true, quantity=not no_quantity, sets=true, minifigures=true) }}
{% with all=true %}
{% include 'part/table_body.html' %}
{% endwith %}
</table>
</div>
<!-- Pagination -->
<div>
{% if pagination and pagination.total_pages > 1 %}
<div class="row mt-4">
<div class="col-12">
<!-- Desktop Pagination -->
<div class="d-none d-md-block">
<nav aria-label="Parts pagination">
<ul class="pagination justify-content-center">
{% if pagination.has_prev %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.page - 1) }}">
<i class="ri-arrow-left-line"></i> Previous
</a>
</li>
{% endif %}
<!-- Show page numbers (with smart truncation) -->
{% set start_page = [1, pagination.page - 2] | max %}
{% set end_page = [pagination.total_pages, pagination.page + 2] | min %}
{% if start_page > 1 %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', 1) }}">1</a>
</li>
{% if start_page > 2 %}
<li class="page-item disabled"><span class="page-link">...</span></li>
{% endif %}
{% endif %}
{% for page_num in range(start_page, end_page + 1) %}
{% if page_num == pagination.page %}
<li class="page-item active">
<span class="page-link">{{ page_num }}</span>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', page_num) }}">{{ page_num }}</a>
</li>
{% endif %}
{% endfor %}
{% if end_page < pagination.total_pages %}
{% if end_page < pagination.total_pages - 1 %}
<li class="page-item disabled"><span class="page-link">...</span></li>
{% endif %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.total_pages) }}">{{ pagination.total_pages }}</a>
</li>
{% endif %}
{% if pagination.has_next %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.page + 1) }}">
Next <i class="ri-arrow-right-line"></i>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
<!-- Mobile Pagination -->
<div class="d-md-none">
<div class="mobile-pagination" role="group" aria-label="Mobile pagination">
{% if pagination.has_prev %}
<a href="{{ request.url | replace_query('page', pagination.page - 1) }}"
class="btn btn-outline-primary">
<i class="ri-arrow-left-line"></i> Previous
</a>
{% else %}
<button class="btn btn-outline-secondary" disabled>
<i class="ri-arrow-left-line"></i> Previous
</button>
{% endif %}
<span class="btn btn-light">
Page {{ pagination.page }} of {{ pagination.total_pages }}
</span>
{% if pagination.has_next %}
<a href="{{ request.url | replace_query('page', pagination.page + 1) }}"
class="btn btn-outline-primary">
Next <i class="ri-arrow-right-line"></i>
</a>
{% else %}
<button class="btn btn-outline-secondary" disabled>
Next <i class="ri-arrow-right-line"></i>
</button>
{% endif %}
</div>
</div>
<!-- Results Info -->
<div class="text-center mt-3">
<small class="text-muted">
Showing {{ ((pagination.page - 1) * pagination.per_page + 1) }} to
{{ [pagination.page * pagination.per_page, pagination.total_count] | min }}
of {{ pagination.total_count }} parts
</small>
</div>
</div>
</div>
{% endif %}
</div>
{% else %}
<!-- ORIGINAL MODE - Single page with client-side search -->
<div class="table-responsive-sm">
<table data-table="true" class="table table-striped align-middle {% if not all %}sortable mb-0{% endif %}" id="parts">
{{ table.header(color=true, quantity=not no_quantity, sets=true, minifigures=true) }}
<tbody>
{% for item in table_collection %}
<tr>
{{ table.image(item.url_for_image(), caption=item.fields.name, alt=item.fields.part, accordion=solo) }}
<td data-sort="{{ item.fields.name }}">
<a class="text-reset" href="{{ item.url() }}">{{ item.fields.name }}</a>
{% if item.fields.spare %}<span class="badge rounded-pill text-bg-warning fw-normal"><i class="ri-loop-left-line"></i> Spare</span>{% endif %}
{{ table.rebrickable(item) }}
{{ table.bricklink(item) }}
</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>{{ item.fields.total_quantity }}</td>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<td data-sort="{{ item.fields.total_missing }}" class="table-td-input">
{{ form.input('Missing', item.fields.id, item.html_id('missing'), item.url_for_problem('missing'), item.fields.total_missing, all=true, read_only=read_only) }}
</td>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<td data-sort="{{ item.fields.total_damaged }}" class="table-td-input">
{{ form.input('Damaged', item.fields.id, item.html_id('damaged'), item.url_for_problem('damaged'), item.fields.total_damaged, all=true, read_only=read_only) }}
</td>
{% endif %}
<td>{{ item.fields.total_sets }}</td>
<td>{{ item.fields.total_minifigures }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</div>
{% else %}
<div class="container-fluid">
@@ -50,4 +201,4 @@
</div>
{% endif %}
{% endblock %}
{% endblock %}

View File

@@ -0,0 +1,144 @@
{% extends 'base.html' %}
{% block title %} - Download instructions from Peeron{% endblock %}
{% block main %}
<div class="container">
{% if error %}<div class="alert alert-danger" role="alert"><strong>Error:</strong> {{ error }}.</div>{% endif %}
<div class="row">
<div class="col-12">
<form method="POST" action="{{ url_for('instructions.do_download') }}">
<div class="card mb-3">
<div class="card-header">
<h5 class="mb-0"><i class="ri-download-line"></i> Download instructions from Rebrickable</h5>
</div>
<div class="card-body">
<div class="mb-3">
<label for="download-set" class="form-label">Set number (only one)</label>
<input type="text" class="form-control" id="download-set" name="download-set" placeholder="107-1 or 1642-1 or ..." value="{{ set }}">
</div>
</div>
<div class="card-footer text-end">
<button type="submit" class="btn btn-primary"><i class="ri-search-line"></i> Search</button>
</div>
</div>
</form>
{% if loading_peeron %}
<div class="alert alert-info" role="alert">
<i class="ri-information-line"></i> <strong>Found on Peeron:</strong> {{ set }} was not available on Rebrickable, loading instruction pages from Peeron...
</div>
<!-- Socket elements for peeron-loader -->
<div id="peeron-loader-fail" class="alert alert-danger d-none" role="alert"></div>
<div id="peeron-loader-complete" class="alert alert-success d-none" role="alert"></div>
<div class="mb-3">
<p>
Progress <span id="peeron-loader-count"></span>
<span id="peeron-loader-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="peeron-loader-progress" class="progress" role="progressbar" aria-label="Loading Peeron pages" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
<div id="peeron-loader-progress-bar" class="progress-bar" style="width: 0%"></div>
</div>
<p id="peeron-loader-progress-message" class="text-center d-none"></p>
</div>
{% endif %}
{% if loading_peeron %}
<!-- Include socket for automatic loading -->
{% with set=set, path=path, namespace=namespace, messages=messages %}
{% include 'instructions/peeron_loader_socket.html' %}
{% endwith %}
{% endif %}
{% if pages %}
<div id="peeron-loading-alert" class="alert alert-info" role="alert">
<i class="ri-information-line"></i> <strong>Instructions found on Peeron:</strong> {{ set }} was not available on Rebrickable, but {{ pages|length }} instruction pages were found on Peeron.
<div id="peeron-cache-progress" class="mt-2 d-none">
<div class="progress" role="progressbar" aria-label="Caching thumbnails" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
<div id="peeron-cache-progress-bar" class="progress-bar" style="width: 0%"></div>
</div>
<small id="peeron-cache-message" class="text-muted">Caching thumbnails...</small>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5 class="mb-0"><i class="ri-checkbox-line"></i> Select instructions to download</h5>
</div>
<div class="card-body">
<div class="mb-3">
<div id="peeron-download-fail" class="alert alert-danger d-none" role="alert"></div>
<div id="peeron-download-complete"></div>
<div class="d-flex justify-content-between align-items-center border-bottom mb-3">
<h5 class="mb-0">Available Instructions</h5>
<button id="peeron-select-all" type="button" class="btn btn-sm btn-outline-secondary">
<i class="ri-checkbox-multiple-line"></i> Select All
</button>
</div>
<div id="peeron-download-files" class="row g-2">
{% for page in pages %}
<div class="col-12 col-md-6 col-lg-4">
<div class="card border-0 shadow-sm">
<div class="card-body p-2">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="peeron-page-{{ loop.index }}"
data-page-number="{{ page.page_number }}"
data-original-image-url="{{ page.original_image_url }}"
data-cached-full-image-path="{{ page.cached_full_image_path }}"
data-alt-text="{{ page.alt_text }}"
data-rotation="0"
autocomplete="off">
<label class="form-check-label w-100" for="peeron-page-{{ loop.index }}">
<div class="text-center position-relative">
<div class="position-relative d-inline-block">
<img id="peeron-img-{{ loop.index }}" src="{{ page.cached_thumbnail_url }}" alt="{{ page.alt_text }}"
class="img-fluid mb-2 border rounded peeron-thumbnail" style="max-height: 150px; transform: rotate(0deg); transition: transform 0.3s ease;"
data-index="{{ loop.index }}" data-total="{{ pages|length }}">
<button type="button" class="btn btn-sm btn-light position-absolute top-0 end-0 p-1 me-1 mt-1 peeron-rotate-btn"
data-target="peeron-img-{{ loop.index }}" data-checkbox="peeron-page-{{ loop.index }}" data-rotation="0"
title="Rotate page" style="font-size: 0.7rem; line-height: 1;">
<i class="ri-refresh-line"></i>
</button>
</div>
<div class="small fw-bold">Page {{ page.page_number }}</div>
</div>
</label>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
<hr>
<div class="mb-3">
<p>
Progress <span id="peeron-download-count"></span>
<span id="peeron-download-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="peeron-download-progress" class="progress" role="progressbar" aria-label="Download Peeron instructions progress" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
<div id="peeron-download-progress-bar" class="progress-bar" style="width: 0%"></div>
</div>
<p id="peeron-download-progress-message" class="text-center d-none"></p>
</div>
</div>
<div class="card-footer text-end">
<span id="peeron-download-status-icon" class="me-1"></span><span id="peeron-download-status" class="me-1"></span><button id="peeron-download" type="button" class="btn btn-primary"><i class="ri-download-line"></i> Download selected files</button>
</div>
</div>
{% if not loading_peeron %}
<!-- Include normal socket for downloading -->
{% include 'instructions/peeron_socket.html' %}
{% endif %}
{% endif %}
</div>
</div>
</div>
{% endblock %}

View File

@@ -1,11 +1,229 @@
{% extends 'base.html' %}
{% import 'macro/form.html' as form %}
{% import 'macro/table.html' as table %}
{% block title %} - Problematic parts{% endblock %}
{% block main %}
<div class="container-fluid px-0">
{% with all=true, no_quantity=true %}
{% include 'part/table.html' %}
{% endwith %}
{% if table_collection | length %}
<div class="container-fluid">
<div class="row row-cols-lg-auto g-1 justify-content-center align-items-center pb-2">
<div class="col-12 flex-grow-1">
<label class="visually-hidden" for="table-search">Search</label>
<div class="input-group">
<span class="input-group-text"><i class="ri-search-line"></i><span class="ms-1 d-none d-md-inline"> Search</span></span>
<input id="table-search" class="form-control form-control-sm px-1" type="text" placeholder="Part name, color" value="{{ search_query or '' }}">
<button id="table-search-clear" type="button" class="btn btn-light btn-outline-danger border"><i class="ri-eraser-line"></i></button>
</div>
</div>
<div class="col-12">
<div class="input-group">
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#table-sort" aria-expanded="{% if config['SHOW_GRID_SORT'] %}true{% else %}false{% endif %}" aria-controls="table-sort">
<i class="ri-sort-asc"></i> Sort
</button>
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#table-filter" aria-expanded="{% if config['SHOW_GRID_FILTERS'] %}true{% else %}false{% endif %}" aria-controls="table-filter">
<i class="ri-filter-line"></i> Filters
</button>
</div>
</div>
</div>
{% include 'problem/sort.html' %}
{% include 'problem/filter.html' %}
{% if use_pagination %}
<!-- PAGINATION MODE -->
<div class="table-responsive-sm">
<table data-table="false" class="table table-striped align-middle mb-0" id="problems">
{{ table.header(color=true, quantity=false, sets=true, minifigures=true) }}
<tbody>
{% for item in table_collection %}
<tr>
{{ table.image(item.url_for_image(), caption=item.fields.name, alt=item.fields.part) }}
<td data-sort="{{ item.fields.name }}">
<a class="text-reset" href="{{ item.url() }}">{{ item.fields.name }}</a>
{% if item.fields.spare %}<span class="badge rounded-pill text-bg-warning fw-normal"><i class="ri-loop-left-line"></i> Spare</span>{% endif %}
{{ table.rebrickable(item) }}
{{ table.bricklink(item) }}
</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>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<td data-sort="{{ item.fields.total_missing }}" class="table-td-input">
{{ form.input('Missing', item.fields.id, item.html_id('missing'), item.url_for_problem('missing'), item.fields.total_missing, all=true, read_only=read_only) }}
</td>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<td data-sort="{{ item.fields.total_damaged }}" class="table-td-input">
{{ form.input('Damaged', item.fields.id, item.html_id('damaged'), item.url_for_problem('damaged'), item.fields.total_damaged, all=true, read_only=read_only) }}
</td>
{% endif %}
<td>{{ item.fields.total_sets }}</td>
<td>{{ item.fields.total_minifigures }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- Pagination -->
<div>
{% if pagination and pagination.total_pages > 1 %}
<div class="row mt-4">
<div class="col-12">
<!-- Desktop Pagination -->
<div class="d-none d-md-block">
<nav aria-label="Problems pagination">
<ul class="pagination justify-content-center">
{% if pagination.has_prev %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.page - 1) }}">
<i class="ri-arrow-left-line"></i> Previous
</a>
</li>
{% endif %}
<!-- Show page numbers (with smart truncation) -->
{% set start_page = [1, pagination.page - 2] | max %}
{% set end_page = [pagination.total_pages, pagination.page + 2] | min %}
{% if start_page > 1 %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', 1) }}">1</a>
</li>
{% if start_page > 2 %}
<li class="page-item disabled"><span class="page-link">...</span></li>
{% endif %}
{% endif %}
{% for page_num in range(start_page, end_page + 1) %}
{% if page_num == pagination.page %}
<li class="page-item active">
<span class="page-link">{{ page_num }}</span>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', page_num) }}">{{ page_num }}</a>
</li>
{% endif %}
{% endfor %}
{% if end_page < pagination.total_pages %}
{% if end_page < pagination.total_pages - 1 %}
<li class="page-item disabled"><span class="page-link">...</span></li>
{% endif %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.total_pages) }}">{{ pagination.total_pages }}</a>
</li>
{% endif %}
{% if pagination.has_next %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.page + 1) }}">
Next <i class="ri-arrow-right-line"></i>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
<!-- Mobile Pagination -->
<div class="d-md-none">
<div class="mobile-pagination" role="group" aria-label="Mobile pagination">
{% if pagination.has_prev %}
<a href="{{ request.url | replace_query('page', pagination.page - 1) }}"
class="btn btn-outline-primary">
<i class="ri-arrow-left-line"></i> Previous
</a>
{% else %}
<button class="btn btn-outline-secondary" disabled>
<i class="ri-arrow-left-line"></i> Previous
</button>
{% endif %}
<span class="btn btn-light">
Page {{ pagination.page }} of {{ pagination.total_pages }}
</span>
{% if pagination.has_next %}
<a href="{{ request.url | replace_query('page', pagination.page + 1) }}"
class="btn btn-outline-primary">
Next <i class="ri-arrow-right-line"></i>
</a>
{% else %}
<button class="btn btn-outline-secondary" disabled>
Next <i class="ri-arrow-right-line"></i>
</button>
{% endif %}
</div>
</div>
<!-- Results Info -->
<div class="text-center mt-3">
<small class="text-muted">
Showing {{ ((pagination.page - 1) * pagination.per_page + 1) }} to
{{ [pagination.page * pagination.per_page, pagination.total_count] | min }}
of {{ pagination.total_count }} problematic parts
</small>
</div>
</div>
</div>
{% endif %}
</div>
{% else %}
<!-- ORIGINAL MODE - Single page with client-side search -->
<div class="table-responsive-sm">
<table data-table="true" class="table table-striped align-middle sortable mb-0" id="problems">
{{ table.header(color=true, quantity=false, sets=true, minifigures=true) }}
<tbody>
{% for item in table_collection %}
<tr>
{{ table.image(item.url_for_image(), caption=item.fields.name, alt=item.fields.part) }}
<td data-sort="{{ item.fields.name }}">
<a class="text-reset" href="{{ item.url() }}">{{ item.fields.name }}</a>
{% if item.fields.spare %}<span class="badge rounded-pill text-bg-warning fw-normal"><i class="ri-loop-left-line"></i> Spare</span>{% endif %}
{{ table.rebrickable(item) }}
{{ table.bricklink(item) }}
</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>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<td data-sort="{{ item.fields.total_missing }}" class="table-td-input">
{{ form.input('Missing', item.fields.id, item.html_id('missing'), item.url_for_problem('missing'), item.fields.total_missing, all=true, read_only=read_only) }}
</td>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<td data-sort="{{ item.fields.total_damaged }}" class="table-td-input">
{{ form.input('Damaged', item.fields.id, item.html_id('damaged'), item.url_for_problem('damaged'), item.fields.total_damaged, all=true, read_only=read_only) }}
</td>
{% endif %}
<td>{{ item.fields.total_sets }}</td>
<td>{{ item.fields.total_minifigures }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</div>
{% else %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="text-center">
<i class="ri-error-warning-line" style="font-size: 4rem; color: #6c757d;"></i>
<h3 class="mt-3">No problematic parts found</h3>
<p class="text-muted">Great! All your parts are in perfect condition.</p>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}

View File

@@ -0,0 +1,30 @@
<div id="table-filter" class="collapse {% if config['SHOW_GRID_FILTERS'] %}show{% endif %} row row-cols-lg-auto g-1 justify-content-center align-items-center">
{% if owners | length %}
<div class="col-12 col-md-6 flex-grow-1">
<div class="input-group">
<span class="input-group-text"><i class="ri-user-line"></i><span class="ms-1 d-none d-md-inline"> Owner</span></span>
<select id="filter-owner" class="form-select" onchange="applyFiltersAndKeepOpen()" autocomplete="off">
<option value="all" {% if selected_owner == 'all' %}selected{% endif %}>All owners</option>
{% for owner in owners %}
<option value="{{ owner.fields.id }}" {% if selected_owner == owner.fields.id %}selected{% endif %}>{{ owner.fields.name }}</option>
{% endfor %}
</select>
</div>
</div>
{% endif %}
{% if colors | length %}
<div class="col-12 col-md-6 flex-grow-1">
<div class="input-group">
<span class="input-group-text"><i class="ri-palette-line"></i><span class="ms-1 d-none d-md-inline"> Color</span></span>
<select id="filter-color" class="form-select" onchange="applyFiltersAndKeepOpen()" autocomplete="off">
<option value="all" {% if selected_color == 'all' %}selected{% endif %}>All colors</option>
{% for color in colors %}
<option value="{{ color.color_id }}" {% if selected_color == color.color_id|string %}selected{% endif %} data-color-rgb="{{ color.color_rgb }}" data-color-id="{{ color.color_id }}">
{{ color.color_name }}
</option>
{% endfor %}
</select>
</div>
</div>
{% endif %}
</div>

View File

@@ -0,0 +1,25 @@
<div id="table-sort" class="collapse {% if config['SHOW_GRID_SORT'] %}show{% endif %} row row-cols-lg-auto g-1 justify-content-center align-items-center">
<div class="col-12 flex-grow-1">
<div class="input-group">
<span class="input-group-text mb-2"><i class="ri-sort-asc"></i><span class="ms-1 d-none d-md-inline"> Sort</span></span>
<button id="sort-name" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="name"><i class="ri-pencil-line"></i><span class="d-none d-md-inline"> Name</span></button>
<button id="sort-color" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="color"><i class="ri-palette-line"></i><span class="d-none d-xl-inline"> Color</span></button>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<button id="sort-missing" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="missing" data-sort-desc="true"><i class="ri-question-line"></i><span class="d-none d-xl-inline"> Missing</span></button>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<button id="sort-damaged" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="damaged" data-sort-desc="true"><i class="ri-error-warning-line"></i><span class="d-none d-xl-inline"> Damaged</span></button>
{% endif %}
<button id="sort-sets" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="sets" data-sort-desc="true"><i class="ri-hashtag"></i><span class="d-none d-xl-inline"> Sets</span></button>
<button id="sort-minifigures" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="minifigures" data-sort-desc="true"><i class="ri-group-line"></i><span class="d-none d-xl-inline"> Figures</span></button>
<button id="sort-clear" type="button" class="btn btn-outline-dark mb-2"
data-sort-clear="true"><i class="ri-close-circle-line"></i><span class="d-none d-xl-inline"> Clear</span></button>
</div>
</div>
</div>

View File

@@ -6,9 +6,51 @@
<div class="container">
<div class="row">
<div class="col-12">
{% with solo=true, delete=delete %}
{% include 'set/card.html' %}
{% endwith %}
{% if all_instances and all_instances | length > 1 %}
<!-- Multiple instances view with drawer-style header -->
<div class="alert alert-info mb-3">
<!-- Clickable drawer header -->
<div class="d-flex justify-content-between align-items-center" style="cursor: pointer;" data-bs-toggle="collapse"
data-bs-target="#all-instances" aria-expanded="false" aria-controls="all-instances">
<div>
<h4 class="mb-1">
<i class="ri-stack-line me-2"></i>Multiple Copies Available
<span class="badge bg-primary ms-2">{{ all_instances | length }}</span>
</h4>
<p class="mb-0">This set has {{ all_instances | length }} copies in your collection. Click to view all copies individually.</p>
</div>
<i class="ri-arrow-down-s-line fs-4" id="copies-toggle-icon"></i>
</div>
<!-- Collapsible instances section -->
<div class="collapse mt-3" id="all-instances">
<div class="border-top pt-3">
<div class="row">
{% set current_item_id = item.fields.id %}
{% for instance in all_instances %}
<div class="col-md-6 col-xl-4 d-flex align-items-stretch mb-3">
{% with item=instance, index=loop.index0, tiny=false, current_viewing=(instance.fields.id == current_item_id) %}
<div class="position-relative w-100">
{% include 'set/card.html' %}
</div>
{% endwith %}
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% with solo=true, delete=delete %}
{% include 'set/card.html' %}
{% endwith %}
{% else %}
<!-- Single instance view -->
{% with solo=true, delete=delete %}
{% include 'set/card.html' %}
{% endwith %}
{% endif %}
</div>
</div>
</div>

View File

@@ -3,10 +3,12 @@
{% import 'macro/card.html' as card %}
{% import 'macro/form.html' as form %}
<div {% if not solo %}id="set-{{ item.fields.id }}"{% endif %} class="card mb-3 flex-fill {% if solo %}card-solo{% endif %}"
<div {% if not solo %}id="set-{{ item.fields.consolidated_id or item.fields.id }}"{% endif %} class="card mb-3 flex-fill {% if solo %}card-solo{% endif %}{% if current_viewing %} border-secondary{% endif %}"{% if current_viewing %} style="border-width: 3px !important;"{% endif %}
data-set-id="{{ item.fields.consolidated_id or item.fields.id }}" data-rebrickable-id="{{ item.fields.set }}"
{% if item.fields.instance_count is defined %}data-instance-count="{{ item.fields.instance_count }}" data-instance-ids="{{ item.fields.instance_ids }}"{% endif %}
{% if not solo and not tiny %}
data-index="{{ index }}" data-number="{{ item.fields.set }}" data-name="{{ item.fields.name | lower }}" data-parts="{{ item.fields.number_of_parts }}"
data-year="{{ item.fields.year }}" data-theme="{{ item.theme.name | lower }}"
data-index="{{ index }}" data-number="{{ item.fields.set }}" data-set="{{ item.fields.set.split('-')[0] | int }}{{ '%05d' | format(item.fields.set.split('-')[1] | int) }}" data-name="{{ item.fields.name | lower }}" data-parts="{{ item.fields.number_of_parts }}"
data-year="{{ item.fields.year }}" data-theme="{{ item.theme.name | lower }}" data-theme-id="{{ item.theme.id }}"
{% if not config['HIDE_SET_INSTRUCTIONS'] %}
data-has-missing-instructions="{{ (item.instructions | length == 0) | int }}"
{% endif %}
@@ -54,7 +56,7 @@
>
{{ card.header(item, item.fields.name, solo=solo, identifier=item.fields.set) }}
{{ card.image(item, solo=solo, last=last, caption=item.fields.name, alt=item.fields.set) }}
<div class="card-body border-bottom-0 {% if not solo %}p-1{% endif %}">
<div class="card-body border-bottom-0 {% if not solo %}p-1{% endif %}"{% if current_viewing %} style="border-color: var(--bs-border-color) !important; border-width: 1px !important;"{% endif %}>
{{ badge.theme(item.theme.name, solo=solo, last=last) }}
{% for tag in brickset_tags %}
{{ badge.tag(item, tag, solo=solo, last=last) }}
@@ -63,6 +65,9 @@
{{ badge.year(item.fields.year, solo=solo, last=last) }}
{% endif %}
{{ badge.parts(item.fields.number_of_parts, solo=solo, last=last) }}
{% if item.fields.instance_count is defined and item.fields.instance_count > 1 %}
<span class="badge bg-primary"><i class="ri-stack-line"></i> {{ item.fields.instance_count }} copies</span>
{% endif %}
{{ badge.total_minifigures(item.fields.total_minifigures, solo=solo, last=last) }}
{{ badge.total_missing(item.fields.total_missing, solo=solo, last=last) }}
{{ badge.total_damaged(item.fields.total_damaged, solo=solo, last=last) }}
@@ -71,7 +76,7 @@
{% endfor %}
{{ badge.storage(item, brickset_storages, solo=solo, last=last) }}
{% if not last %}
{{ badge.purchase_date(item.purchase_date(), solo=solo, last=last) }}
{{ badge.purchase_date(item.purchase_date(), solo=solo, last=last, date_max_formatted=item.purchase_date_max_formatted()) }}
{{ badge.purchase_location(item, brickset_purchase_locations, solo=solo, last=last) }}
{{ badge.purchase_price(item.purchase_price(), solo=solo, last=last) }}
{% if not solo %}
@@ -81,14 +86,45 @@
{% endif %}
</div>
{% if not tiny and brickset_statuses | length %}
<ul class="list-group list-group-flush card-check border-bottom-0">
<ul class="list-group list-group-flush card-check border-bottom-0"{% if current_viewing %} style="border-color: var(--bs-border-color) !important; border-width: 1px !important;"{% endif %}>
{% for status in brickset_statuses %}
<li class="d-flex list-group-item {% if not solo %}p-1{% endif %} text-nowrap">{{ form.checkbox(status.fields.name, item.fields.id, status.as_dataset(), status.url_for_set_state(item.fields.id), item.fields[status.as_column()], parent='set', delete=delete) }}</li>
<li class="d-flex list-group-item {% if not solo %}p-1{% endif %} text-nowrap">
{% if item.fields.instance_count is defined and item.fields.instance_count > 1 %}
{# Consolidated set - show mixed status indicator #}
{% set status_count = item.fields[status.as_column() + '_count'] %}
{% set total_count = item.fields.instance_count %}
{% if status_count == 0 %}
{# None checked #}
<input class="form-check-input px-1" type="checkbox" disabled>
<label class="form-check-label">
{{ status.fields.name }}
<small class="text-muted ms-1">(0/{{ total_count }})</small>
</label>
{% elif status_count == total_count %}
{# All checked #}
<input class="form-check-input px-1" type="checkbox" checked disabled>
<label class="form-check-label">
{{ status.fields.name }}
<small class="text-muted ms-1">({{ total_count }}/{{ total_count }})</small>
</label>
{% else %}
{# Partial - some checked #}
<input class="form-check-input px-1 partial-status" type="checkbox" disabled>
<label class="form-check-label">
{{ status.fields.name }}
<small class="text-muted ms-1">({{ status_count }}/{{ total_count }})</small>
</label>
{% endif %}
{% else %}
{# Individual set - use normal checkbox #}
{{ form.checkbox(status.fields.name, item.fields.id, status.as_dataset(), status.url_for_set_state(item.fields.id), item.fields[status.as_column()], parent='set', delete=delete) }}
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% if solo %}
<div class="accordion accordion-flush border-top" id="set-details">
<div class="accordion accordion-flush border-top" id="set-details"{% if current_viewing %} style="border-color: var(--bs-border-color) !important; border-width: 1px !important;"{% endif %}>
{% if not delete %}
{% if not config['HIDE_SET_INSTRUCTIONS'] %}
{{ accordion.header('Instructions', 'instructions', 'set-details', expanded=open_instructions, quantity=item.instructions | length, icon='file-line', class='p-0') }}
@@ -104,14 +140,14 @@
{% endif %}
{% endif %}
{% if g.login.is_authenticated() %}
<a class="list-group-item list-group-item-action" href="{{ url_for('instructions.download', set=item.fields.set) }}"><i class="ri-download-line"></i> Download instructions from Rebrickable</a>
<a class="list-group-item list-group-item-action" href="{{ url_for('instructions.download', set=item.fields.set) }}"><i class="ri-download-line"></i> Download instructions</a>
{% endif %}
</div>
{{ accordion.footer() }}
{% endif %}
{{ accordion.table(item.parts(), 'Parts', 'parts-inventory', 'set-details', 'part/table.html', icon='shapes-line')}}
{{ accordion.table(item.parts(), 'Parts', 'parts-inventory', 'set-details', 'part/table.html', icon='shapes-line', hamburger_menu=g.login.is_authenticated())}}
{% for minifigure in item.minifigures() %}
{{ accordion.table(minifigure.parts(), minifigure.fields.name, minifigure.fields.figure, 'set-details', 'part/table.html', quantity=minifigure.fields.quantity, icon='group-line', image=minifigure.url_for_image(), alt=minifigure.fields.figure, details=minifigure.url())}}
{{ accordion.table(minifigure.parts(), minifigure.fields.name, minifigure.fields.figure, 'set-details', 'part/table.html', quantity=minifigure.fields.quantity, icon='group-line', image=minifigure.url_for_image(), alt=minifigure.fields.figure, details=minifigure.url(), hamburger_menu=g.login.is_authenticated())}}
{% endfor %}
{% include 'set/management.html' %}
{% endif %}

View File

@@ -6,26 +6,26 @@
<select id="grid-status" class="form-select"
data-filter="metadata"
autocomplete="off">
<option value="" selected>All</option>
<option value="" {% if not current_status_filter %}selected{% endif %}>All</option>
{% if not config['HIDE_TABLE_MISSING_PARTS'] %}
<option value="has-missing">Has missing pieces</option>
<option value="-has-missing">Has NO missing pieces</option>
<option value="has-missing" {% if current_status_filter == 'has-missing' %}selected{% endif %}>Has missing pieces</option>
<option value="-has-missing" {% if current_status_filter == '-has-missing' %}selected{% endif %}>Has NO missing pieces</option>
{% endif %}
{% if not config['HIDE_TABLE_DAMAGED_PARTS'] %}
<option value="has-damaged">Has damaged pieces</option>
<option value="-has-damaged">Has NO damaged pieces</option>
<option value="has-damaged" {% if current_status_filter == 'has-damaged' %}selected{% endif %}>Has damaged pieces</option>
<option value="-has-damaged" {% if current_status_filter == '-has-damaged' %}selected{% endif %}>Has NO damaged pieces</option>
{% endif %}
{% if not config['HIDE_SET_INSTRUCTIONS'] %}
<option value="-has-missing-instructions">Has instructions</option>
<option value="has-missing-instructions">Is MISSING instructions</option>
<option value="-has-missing-instructions" {% if current_status_filter == '-has-missing-instructions' %}selected{% endif %}>Has instructions</option>
<option value="has-missing-instructions" {% if current_status_filter == 'has-missing-instructions' %}selected{% endif %}>Is MISSING instructions</option>
{% endif %}
{% if brickset_storages | length %}
<option value="has-storage">Is in storage</option>
<option value="-has-storage">Is NOT in storage</option>
<option value="has-storage" {% if current_status_filter == 'has-storage' %}selected{% endif %}>Is in storage</option>
<option value="-has-storage" {% if current_status_filter == '-has-storage' %}selected{% endif %}>Is NOT in storage</option>
{% endif %}
{% for status in brickset_statuses %}
<option value="{{ status.as_dataset() }}">{{ status.fields.name }}</option>
<option value="-{{ status.as_dataset() }}">NOT: {{ status.fields.name }}</option>
<option value="{{ status.as_dataset() }}" {% if current_status_filter == status.as_dataset() %}selected{% endif %}>{{ status.fields.name }}</option>
<option value="-{{ status.as_dataset() }}" {% if current_status_filter == ('-' + status.as_dataset()) %}selected{% endif %}>NOT: {{ status.fields.name }}</option>
{% endfor %}
</select>
</div>
@@ -37,9 +37,9 @@
<select id="grid-theme" class="form-select"
data-filter="value" data-filter-attribute="theme"
autocomplete="off">
<option value="" selected>All</option>
<option value="" {% if not current_theme_filter %}selected{% endif %}>All</option>
{% for theme in collection.themes %}
<option value="{{ theme | lower }}">{{ theme }}</option>
<option value="{{ theme | lower }}" {% if current_theme_filter == (theme | lower) %}selected{% endif %}>{{ theme }}</option>
{% endfor %}
</select>
</div>
@@ -52,9 +52,9 @@
<select id="grid-owner" class="form-select"
data-filter="metadata"
autocomplete="off">
<option value="" selected>All</option>
<option value="" {% if not current_owner_filter %}selected{% endif %}>All</option>
{% for owner in brickset_owners %}
<option value="{{ owner.as_dataset() }}">{{ owner.fields.name }}</option>
<option value="{{ owner.as_dataset() }}" {% if current_owner_filter == owner.as_dataset() %}selected{% endif %}>{{ owner.fields.name }}</option>
{% endfor %}
</select>
</div>
@@ -68,9 +68,9 @@
<select id="grid-purchase-location" class="form-select"
data-filter="value" data-filter-attribute="purchase-location"
autocomplete="off">
<option value="" selected>All</option>
<option value="" {% if not current_purchase_location_filter %}selected{% endif %}>All</option>
{% for purchase_location in brickset_purchase_locations %}
<option value="{{ purchase_location.fields.id }}">{{ purchase_location.fields.name }}</option>
<option value="{{ purchase_location.fields.id }}" {% if current_purchase_location_filter == purchase_location.fields.id %}selected{% endif %}>{{ purchase_location.fields.name }}</option>
{% endfor %}
</select>
</div>
@@ -84,9 +84,9 @@
<select id="grid-storage" class="form-select"
data-filter="value" data-filter-attribute="storage"
autocomplete="off">
<option value="" selected>All</option>
<option value="" {% if not current_storage_filter %}selected{% endif %}>All</option>
{% for storage in brickset_storages %}
<option value="{{ storage.fields.id }}">{{ storage.fields.name }}</option>
<option value="{{ storage.fields.id }}" {% if current_storage_filter == storage.fields.id %}selected{% endif %}>{{ storage.fields.name }}</option>
{% endfor %}
</select>
</div>
@@ -100,12 +100,26 @@
<select id="grid-tag" class="form-select"
data-filter="metadata"
autocomplete="off">
<option value="" selected>All</option>
<option value="" {% if not current_tag_filter %}selected{% endif %}>All</option>
{% for tag in brickset_tags %}
<option value="{{ tag.as_dataset() }}">{{ tag.fields.name }}</option>
<option value="{{ tag.as_dataset() }}" {% if current_tag_filter == tag.as_dataset() %}selected{% endif %}>{{ tag.fields.name }}</option>
{% endfor %}
</select>
</div>
</div>
{% endif %}
<div class="col-12 flex-grow-1">
<label class="visually-hidden" for="grid-year">Year</label>
<div class="input-group">
<span class="input-group-text"><i class="ri-calendar-line"></i><span class="ms-1 d-none d-md-inline"> Year</span></span>
<select id="grid-year" class="form-select"
data-filter="value" data-filter-attribute="year"
autocomplete="off">
<option value="" {% if not current_year_filter %}selected{% endif %}>All</option>
{% for year in collection.years %}
<option value="{{ year }}" {% if current_year_filter == year %}selected{% endif %}>{{ year }}</option>
{% endfor %}
</select>
</div>
</div>
</div>

View File

@@ -2,8 +2,8 @@
<div class="col-12 flex-grow-1">
<div class="input-group">
<span class="input-group-text mb-2"><i class="ri-sort-asc"></i><span class="ms-1 d-none d-md-inline"> Sort</span></span>
<button id="sort-number" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="number" data-sort-natural="true"><i class="ri-hashtag"></i><span class="d-none d-md-inline"> Set</span></button>
<button id="sort-set" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="set" data-sort-natural="true"><i class="ri-hashtag"></i><span class="d-none d-md-inline"> Set</span></button>
<button id="sort-name" type="button" class="btn btn-outline-primary mb-2"
data-sort-attribute="name"><i class="ri-pencil-line"></i><span class="d-none d-md-inline"> Name</span></button>
<button id="sort-theme" type="button" class="btn btn-outline-primary mb-2"

View File

@@ -3,14 +3,14 @@
{% block title %} - All sets{% endblock %}
{% block main %}
{% if collection | length %}
{% if collection | length or use_pagination %}
<div class="container-fluid">
<div class="row row-cols-lg-auto g-1 justify-content-center align-items-center pb-2">
<div class="col-12 flex-grow-1">
<label class="visually-hidden" for="grid-search">Search</label>
<div class="input-group">
<span class="input-group-text"><i class="ri-search-line"></i><span class="ms-1 d-none d-md-inline"> Search</span></span>
<input id="grid-search" data-search-exact="name,number,parts,searchPurchaseLocation,searchStorage,theme,year" data-search-list="searchOwner,searchTag" class="form-control form-control-sm px-1" type="text" placeholder="Set, name, number of parts, theme, year, owner, purchase location, storage, tag" value="">
<input id="grid-search" {% if not use_pagination %}data-search-exact="name,number,parts,searchPurchaseLocation,searchStorage,theme,year" data-search-list="searchOwner,searchTag"{% endif %} class="form-control form-control-sm px-1" type="text" placeholder="Set, name, number of parts, theme, year{% if not use_pagination %}, owner, purchase location, storage, tag{% endif %}" value="{{ search_query or '' }}">
<button id="grid-search-clear" type="button" class="btn btn-light btn-outline-danger border"><i class="ri-eraser-line"></i></button>
</div>
</div>
@@ -19,10 +19,6 @@
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#grid-sort" aria-expanded="{% if config['SHOW_GRID_SORT'] %}true{% else %}false{% endif %}" aria-controls="grid-sort">
<i class="ri-sort-asc"></i> Sort
</button>
</div>
</div>
<div class="col-12">
<div class="input-group">
<button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#grid-filter" aria-expanded="{% if config['SHOW_GRID_FILTERS'] %}true{% else %}false{% endif %}" aria-controls="grid-filter">
<i class="ri-filter-line"></i> Filters
</button>
@@ -31,6 +27,131 @@
</div>
{% include 'set/sort.html' %}
{% include 'set/filter.html' %}
{% if use_pagination %}
<!-- PAGINATION MODE -->
<div class="row" data-grid="false" id="grid">
{% for item in collection %}
<div class="col-md-6 col-xl-3 d-flex align-items-stretch">
{% with index=loop.index0 %}
{% include 'set/card.html' %}
{% endwith %}
</div>
{% endfor %}
</div>
<!-- Pagination -->
<div>
{% if pagination and pagination.total_pages > 1 %}
<div class="row mt-4">
<div class="col-12">
<!-- Desktop Pagination -->
<div class="d-none d-md-block">
<nav aria-label="Sets pagination">
<ul class="pagination justify-content-center">
{% if pagination.has_prev %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.page - 1) }}">
<i class="ri-arrow-left-line"></i> Previous
</a>
</li>
{% endif %}
<!-- Show page numbers (with smart truncation) -->
{% set start_page = [1, pagination.page - 2] | max %}
{% set end_page = [pagination.total_pages, pagination.page + 2] | min %}
{% if start_page > 1 %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', 1) }}">1</a>
</li>
{% if start_page > 2 %}
<li class="page-item disabled"><span class="page-link">...</span></li>
{% endif %}
{% endif %}
{% for page_num in range(start_page, end_page + 1) %}
{% if page_num == pagination.page %}
<li class="page-item active">
<span class="page-link">{{ page_num }}</span>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', page_num) }}">{{ page_num }}</a>
</li>
{% endif %}
{% endfor %}
{% if end_page < pagination.total_pages %}
{% if end_page < pagination.total_pages - 1 %}
<li class="page-item disabled"><span class="page-link">...</span></li>
{% endif %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.total_pages) }}">{{ pagination.total_pages }}</a>
</li>
{% endif %}
{% if pagination.has_next %}
<li class="page-item">
<a class="page-link" href="{{ request.url | replace_query('page', pagination.page + 1) }}">
Next <i class="ri-arrow-right-line"></i>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
<!-- Mobile Pagination -->
<div class="d-md-none">
<div class="mobile-pagination" role="group" aria-label="Mobile pagination">
{% if pagination.has_prev %}
<a href="{{ request.url | replace_query('page', pagination.page - 1) }}"
class="btn btn-outline-primary">
<i class="ri-arrow-left-line"></i> Previous
</a>
{% else %}
<button class="btn btn-outline-secondary" disabled>
<i class="ri-arrow-left-line"></i> Previous
</button>
{% endif %}
<span class="btn btn-light">
Page {{ pagination.page }} of {{ pagination.total_pages }}
</span>
{% if pagination.has_next %}
<a href="{{ request.url | replace_query('page', pagination.page + 1) }}"
class="btn btn-outline-primary">
Next <i class="ri-arrow-right-line"></i>
</a>
{% else %}
<button class="btn btn-outline-secondary" disabled>
Next <i class="ri-arrow-right-line"></i>
</button>
{% endif %}
</div>
</div>
<!-- Results Info -->
<div class="text-center mt-3">
<small class="text-muted">
{% if pagination.total_count > 0 %}
Showing {{ ((pagination.page - 1) * pagination.per_page + 1) }} to
{{ [pagination.page * pagination.per_page, pagination.total_count] | min }}
of {{ pagination.total_count }} sets
{% else %}
No sets found
{% endif %}
</small>
</div>
</div>
</div>
{% endif %}
</div>
{% else %}
<!-- ORIGINAL MODE - Single page with client-side search and filters -->
<div class="row" data-grid="true" id="grid">
{% for item in collection %}
<div class="col-md-6 col-xl-3 d-flex align-items-stretch">
@@ -40,6 +161,8 @@
</div>
{% endfor %}
</div>
{% endif %}
</div>
{% else %}
{% include 'set/empty.html' %}

633
templates/statistics.html Normal file
View File

@@ -0,0 +1,633 @@
{% extends 'base.html' %}
{% block title %} - Statistics{% endblock %}
{% block main %}
<div class="container-fluid">
<!-- Overview Cards Row -->
<div class="row g-3 mb-4">
<!-- Collection Summary -->
<div class="col-lg-4 col-md-6">
<div class="card h-100">
<div class="card-header bg-primary text-white">
<h5 class="card-title mb-0">
<i class="ri-grid-line"></i> Collection Overview
</h5>
</div>
<div class="card-body">
<div class="row g-2">
<div class="col-6">
<div class="text-center">
<a href="{{ url_for('set.list') }}" class="text-decoration-none">
<div class="h4 text-primary mb-0">{{ collection_summary.total_sets }}</div>
<small class="text-dark">Total Sets</small>
</a>
</div>
</div>
<div class="col-6">
<div class="text-center">
<div class="h4 text-dark mb-0">{{ collection_summary.unique_sets }}</div>
<small class="text-dark">Unique Sets</small>
</div>
</div>
<div class="col-6">
<div class="text-center">
<a href="{{ url_for('part.list') }}" class="text-decoration-none">
<div class="h4 text-primary mb-0">{{ "{:,}".format(collection_summary.total_parts_count) }}</div>
<small class="text-dark">Total Parts</small>
</a>
</div>
</div>
<div class="col-6">
<div class="text-center">
<div class="h4 text-dark mb-0">{{ collection_summary.unique_parts }}</div>
<small class="text-dark">Unique Parts</small>
</div>
</div>
<div class="col-6">
<div class="text-center">
<a href="{{ url_for('minifigure.list') }}" class="text-decoration-none">
<div class="h4 text-primary mb-0">{{ collection_summary.total_minifigures_count }}</div>
<small class="text-dark">Minifigures</small>
</a>
</div>
</div>
<div class="col-6">
<div class="text-center">
<div class="h4 text-dark mb-0">{{ collection_summary.unique_minifigures }}</div>
<small class="text-dark">Unique Figs</small>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Financial Summary -->
<div class="col-lg-4 col-md-6">
<div class="card h-100">
<div class="card-header bg-success text-white">
<h5 class="card-title mb-0">
<i class="ri-money-dollar-circle-line"></i> Financial Summary
</h5>
</div>
<div class="card-body">
<div class="text-center mb-3">
<div class="h3 text-success mb-0">{{ config['PURCHASE_CURRENCY'] }}{{ "%.2f"|format(financial_summary.total_cost) }}</div>
<small class="text-dark">Total Investment</small>
</div>
<div class="row g-2">
<div class="col-6">
<div class="text-center">
<div class="h5 text-dark mb-0">{{ financial_summary.sets_with_price }}</div>
<small class="text-dark">Sets with Price</small>
</div>
</div>
<div class="col-6">
<div class="text-center">
<div class="h5 text-dark mb-0">{{ financial_summary.percentage_with_price }}%</div>
<small class="text-dark">Price Coverage</small>
</div>
</div>
<div class="col-6">
<div class="text-center">
<div class="text-dark small">Average</div>
<div class="fw-bold">{{ config['PURCHASE_CURRENCY'] }}{{ "%.2f"|format(financial_summary.average_cost) }}</div>
</div>
</div>
<div class="col-6">
<div class="text-center">
<div class="text-dark small">Range</div>
<div class="fw-bold">{{ config['PURCHASE_CURRENCY'] }}{{ "%.2f"|format(financial_summary.minimum_cost) }} - {{ config['PURCHASE_CURRENCY'] }}{{ "%.2f"|format(financial_summary.maximum_cost) }}</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Problems & Storage -->
<div class="col-lg-4 col-md-12">
<div class="card h-100">
<div class="card-header bg-warning text-dark">
<h5 class="card-title mb-0">
<i class="ri-error-warning-line"></i> Issues & Storage
</h5>
</div>
<div class="card-body">
<div class="row g-2">
<div class="col-6">
<div class="text-center">
<a href="{{ url_for('part.problem') }}" class="text-decoration-none">
<div class="h4 text-danger mb-0">{{ collection_summary.total_missing_parts }}</div>
<small class="text-dark">Missing Parts</small>
</a>
</div>
</div>
<div class="col-6">
<div class="text-center">
<a href="{{ url_for('part.problem') }}" class="text-decoration-none">
<div class="h4 text-danger mb-0">{{ collection_summary.total_damaged_parts }}</div>
<small class="text-dark">Damaged Parts</small>
</a>
</div>
</div>
<div class="col-6">
<div class="text-center">
{% if config['HIDE_ALL_STORAGES'] %}
<div class="h4 text-dark mb-0">{{ collection_summary.storage_locations_used }}</div>
{% else %}
<a href="{{ url_for('storage.list') }}" class="text-decoration-none">
<div class="h4 text-primary mb-0">{{ collection_summary.storage_locations_used }}</div>
</a>
{% endif %}
<small class="text-dark">Storage Locations</small>
</div>
</div>
<div class="col-6">
<div class="text-center">
<div class="h4 text-dark mb-0">{{ collection_summary.purchase_locations_used }}</div>
<small class="text-dark">Purchase Locations</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Collection Growth Charts -->
{% if config['STATISTICS_SHOW_CHARTS'] %}
<div class="row g-3 mb-4">
<div class="col-12">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">
<a class="text-decoration-none text-dark" data-bs-toggle="collapse" href="#collapseCharts" role="button" aria-expanded="{{ 'true' if config['STATISTICS_DEFAULT_EXPANDED'] else 'false' }}" aria-controls="collapseCharts">
<i class="ri-line-chart-line"></i> Collection Growth Over Time
<i class="ri-arrow-down-s-line float-end"></i>
</a>
</h5>
</div>
<div class="collapse {{ 'show' if config['STATISTICS_DEFAULT_EXPANDED'] else '' }}" id="collapseCharts">
<div class="card-body">
<div class="row">
<div class="col-lg-4 mb-3">
<h6 class="text-center text-dark">Sets by Release Year</h6>
<div style="position: relative; height: 250px;">
<canvas id="setsChart"></canvas>
</div>
</div>
<div class="col-lg-4 mb-3">
<h6 class="text-center text-dark">Parts by Release Year</h6>
<div style="position: relative; height: 250px;">
<canvas id="partsChart"></canvas>
</div>
</div>
<div class="col-lg-4 mb-3">
<h6 class="text-center text-dark">Minifigures by Release Year</h6>
<div style="position: relative; height: 250px;">
<canvas id="minifigsChart"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endif %}
<!-- Detailed Statistics Tables -->
<div class="row g-3">
<!-- Theme Statistics -->
{% if theme_statistics %}
<div class="col-lg-6">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">
<a class="text-decoration-none text-dark" data-bs-toggle="collapse" href="#collapseThemes" role="button" aria-expanded="{{ 'true' if config['STATISTICS_DEFAULT_EXPANDED'] else 'false' }}" aria-controls="collapseThemes">
<i class="ri-palette-line"></i> Sets by Theme
<i class="ri-arrow-down-s-line float-end"></i>
</a>
</h5>
</div>
<div class="collapse {{ 'show' if config['STATISTICS_DEFAULT_EXPANDED'] else '' }}" id="collapseThemes">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th>Theme</th>
<th class="text-center">Sets</th>
<th class="text-center">Parts</th>
<th class="text-center">Minifigures</th>
<th class="text-center">Spent</th>
</tr>
</thead>
<tbody>
{% for theme in theme_statistics[:10] %}
<tr>
<td>
<a href="{{ url_for('set.list', theme=theme.theme_id) }}" class="text-decoration-none">
{{ theme.theme_name }}
</a>
</td>
<td class="text-center">
<small class="text-dark">{{ theme.set_count }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ "{:,}".format(theme.total_parts) }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ theme.total_minifigures }}</small>
</td>
<td class="text-center">
{% if theme.total_spent %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.0f"|format(theme.total_spent) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if theme_statistics|length > 10 %}
<div class="card-footer text-center">
<small class="text-dark">Showing top 10 themes</small>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endif %}
<!-- Storage Statistics -->
{% if storage_statistics %}
<div class="col-lg-6">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">
<a class="text-decoration-none text-dark" data-bs-toggle="collapse" href="#collapseStorage" role="button" aria-expanded="{{ 'true' if config['STATISTICS_DEFAULT_EXPANDED'] else 'false' }}" aria-controls="collapseStorage">
<i class="ri-archive-2-line"></i> Sets by Storage
<i class="ri-arrow-down-s-line float-end"></i>
</a>
</h5>
</div>
<div class="collapse {{ 'show' if config['STATISTICS_DEFAULT_EXPANDED'] else '' }}" id="collapseStorage">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th>Storage Location</th>
<th class="text-center">Sets</th>
<th class="text-center">Parts</th>
<th class="text-center">Minifigures</th>
<th class="text-center">Value</th>
</tr>
</thead>
<tbody>
{% for storage in storage_statistics %}
<tr>
<td>
<a href="{{ url_for('set.list', storage=storage.storage_id) }}" class="text-decoration-none">
{{ storage.storage_name or 'Unknown' }}
</a>
</td>
<td class="text-center">
<small class="text-dark">{{ storage.set_count }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ "{:,}".format(storage.total_parts) }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ storage.total_minifigures }}</small>
</td>
<td class="text-center">
{% if storage.total_value %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.0f"|format(storage.total_value) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
{% endif %}
</div>
<!-- Purchase Location Statistics -->
{% if purchase_location_statistics %}
<div class="row g-3 mt-2">
<div class="col-12">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">
<a class="text-decoration-none text-dark" data-bs-toggle="collapse" href="#collapsePurchase" role="button" aria-expanded="{{ 'true' if config['STATISTICS_DEFAULT_EXPANDED'] else 'false' }}" aria-controls="collapsePurchase">
<i class="ri-shopping-cart-line"></i> Sets by Purchase Location
<i class="ri-arrow-down-s-line float-end"></i>
</a>
</h5>
</div>
<div class="collapse {{ 'show' if config['STATISTICS_DEFAULT_EXPANDED'] else '' }}" id="collapsePurchase">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th>Purchase Location</th>
<th class="text-center">Sets</th>
<th class="text-center">Parts</th>
<th class="text-center">Minifigures</th>
<th class="text-center">Total Spent</th>
<th class="text-center">Avg. Price</th>
<th class="text-center">Price Range</th>
</tr>
</thead>
<tbody>
{% for location in purchase_location_statistics %}
<tr>
<td>
<a href="{{ url_for('set.list', purchase_location=location.location_id) }}" class="text-decoration-none">
{{ location.location_name or 'Unknown' }}
</a>
</td>
<td class="text-center">
<small class="text-dark">{{ location.set_count }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ "{:,}".format(location.total_parts) }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ location.total_minifigures }}</small>
</td>
<td class="text-center">
{% if location.total_spent %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.2f"|format(location.total_spent) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
<td class="text-center">
{% if location.avg_price %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.2f"|format(location.avg_price) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
<td class="text-center">
{% if location.min_price and location.max_price %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.0f"|format(location.min_price) }}-{{ "%.0f"|format(location.max_price) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
{% endif %}
<!-- Year-based Statistics -->
<div class="row g-3 mt-2">
<!-- Sets by Year (Release Year) -->
{% if sets_by_year_statistics %}
<div class="col-lg-6">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">
<a class="text-decoration-none text-dark" data-bs-toggle="collapse" href="#collapseReleaseYear" role="button" aria-expanded="{{ 'true' if config['STATISTICS_DEFAULT_EXPANDED'] else 'false' }}" aria-controls="collapseReleaseYear">
<i class="ri-calendar-line"></i> Sets by Release Year
<i class="ri-arrow-down-s-line float-end"></i>
</a>
</h5>
<small class="text-dark">Statistics grouped by when LEGO released the sets</small>
</div>
<div class="collapse {{ 'show' if config['STATISTICS_DEFAULT_EXPANDED'] else '' }}" id="collapseReleaseYear">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0 table-sm">
<thead class="table-light">
<tr>
<th>Year</th>
<th class="text-center">Unique</th>
<th class="text-center">Total</th>
<th class="text-center">Parts</th>
<th class="text-center">Minifigures</th>
<th class="text-center">Spent</th>
<th class="text-center">Avg/Set</th>
</tr>
</thead>
<tbody>
{% for year in sets_by_year_statistics[:15] %}
<tr>
<td>
<a href="{{ url_for('set.list', year=year.year) }}" class="year-filter-link text-decoration-none" data-year="{{ year.year }}">
<strong>{{ year.year }}</strong>
</a>
{% if year.unique_themes > 1 %}
<small class="text-dark d-block">{{ year.unique_themes }} themes</small>
{% endif %}
</td>
<td class="text-center">
<small class="text-dark">{{ year.unique_sets }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ year.total_sets }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ "{:,}".format(year.total_parts) }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ year.total_minifigures }}</small>
</td>
<td class="text-center">
{% if year.total_spent %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.0f"|format(year.total_spent) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
<td class="text-center">
{% if year.avg_price_per_set %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.0f"|format(year.avg_price_per_set) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if sets_by_year_statistics|length > 15 %}
<div class="card-footer text-center">
<small class="text-dark">Showing last 15 years</small>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endif %}
<!-- Purchases by Year -->
{% if purchases_by_year_statistics %}
<div class="col-lg-6">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">
<a class="text-decoration-none text-dark" data-bs-toggle="collapse" href="#collapsePurchaseYear" role="button" aria-expanded="{{ 'true' if config['STATISTICS_DEFAULT_EXPANDED'] else 'false' }}" aria-controls="collapsePurchaseYear">
<i class="ri-shopping-cart-line"></i> Purchases by Year
<i class="ri-arrow-down-s-line float-end"></i>
</a>
</h5>
<small class="text-dark">Statistics grouped by when you purchased the sets</small>
</div>
<div class="collapse {{ 'show' if config['STATISTICS_DEFAULT_EXPANDED'] else '' }}" id="collapsePurchaseYear">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0 table-sm">
<thead class="table-light">
<tr>
<th>Year</th>
<th class="text-center">Unique</th>
<th class="text-center">Total</th>
<th class="text-center">Parts</th>
<th class="text-center">Minifigures</th>
<th class="text-center">Spent</th>
<th class="text-center">Avg/Set</th>
</tr>
</thead>
<tbody>
{% for year in purchases_by_year_statistics %}
<tr>
<td>
<strong>{{ year.purchase_year }}</strong>
</td>
<td class="text-center">
<small class="text-dark">{{ year.unique_sets }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ year.total_sets }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ "{:,}".format(year.total_parts) }}</small>
</td>
<td class="text-center">
<small class="text-dark">{{ year.total_minifigures }}</small>
</td>
<td class="text-center">
{% if year.total_spent %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.2f"|format(year.total_spent) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
<td class="text-center">
{% if year.avg_price_per_set %}
<small class="text-dark">{{ config['PURCHASE_CURRENCY'] }}{{ "%.0f"|format(year.avg_price_per_set) }}</small>
{% else %}
<small class="text-dark">-</small>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if year_summary %}
<div class="card-footer">
<div class="row text-center">
<div class="col-6">
<small class="text-dark">Peak Year</small><br>
{% if year_summary.peak_spending_year %}
<strong>{{ year_summary.peak_spending_year }}</strong>
<small class="text-success d-block">{{ config['PURCHASE_CURRENCY'] }}{{ "%.0f"|format(year_summary.max_spending) }}</small>
{% else %}
<small class="text-dark">N/A</small>
{% endif %}
</div>
<div class="col-6">
<small class="text-dark">Active Years</small><br>
<strong>{{ year_summary.years_with_purchases }}</strong>
<small class="text-dark d-block">years</small>
</div>
</div>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endif %}
</div>
<!-- Year Summary Banner -->
{% if year_summary and (year_summary.peak_collection_year or year_summary.oldest_set_year) %}
<div class="row g-3 mt-2">
<div class="col-12">
<div class="alert alert-info">
<div class="row text-center">
{% if year_summary.oldest_set_year and year_summary.newest_set_year %}
<div class="col-md-3">
<strong>{{ year_summary.oldest_set_year }} - {{ year_summary.newest_set_year }}</strong><br>
<small class="text-dark">Set Year Range</small>
</div>
{% endif %}
{% if year_summary.peak_collection_year %}
<div class="col-md-3">
<strong>{{ year_summary.peak_collection_year }}</strong><br>
<small class="text-dark">Most Sets from Year ({{ year_summary.max_sets_in_year }} sets)</small>
</div>
{% endif %}
{% if year_summary.years_represented %}
<div class="col-md-3">
<strong>{{ year_summary.years_represented }}</strong><br>
<small class="text-dark">Years Represented</small>
</div>
{% endif %}
{% if year_summary.years_with_purchases %}
<div class="col-md-3">
<strong>{{ year_summary.years_with_purchases }}</strong><br>
<small class="text-dark">Years with Purchases</small>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endif %}
</div>
{% if config['STATISTICS_SHOW_CHARTS'] %}
<script type="text/javascript">
// Initialize chart data for statistics.js
window.chartData = {
years: {{ chart_data.years|safe }},
sets: {{ chart_data.sets_data|safe }},
parts: {{ chart_data.parts_data|safe }},
minifigs: {{ chart_data.minifigs_data|safe }}
};
</script>
{% endif %}
{% endblock %}