Members
(constant) ACK_DISMISSED_KEY :string
LocalStorage key for acknowledgment dismissal
Type:
- string
- Source:
(constant) API_CACHE_KEY :string
LocalStorage key for cached API data
Type:
- string
- Source:
(constant) API_KEY_STORAGE_KEY :string
LocalStorage key for API provider information
Type:
- string
- Source:
(constant) API_PROVIDERS
API Provider configurations for metals pricing services
Each provider configuration contains:
Properties:
| Name | Type | Description |
|---|---|---|
name |
string | Display name for the provider |
baseUrl |
string | Base API endpoint URL |
endpoints |
Object | API endpoints for different metals |
parseResponse |
function | Function to parse API response into standard format |
documentation |
string | URL to provider's API documentation |
batchSupported |
boolean | Whether provider supports batch requests |
batchEndpoint |
string | Batch request endpoint pattern |
parseBatchResponse |
function | Function to parse batch API response |
- Source:
(constant) APP_VERSION :string
Application version Follows BRANCH.RELEASE.PATCH.state format State codes: a=alpha, b=beta, rc=release candidate Example: 3.03.02a → branch 3, release 03, patch 02, alpha Updated: 2026-02-12 - STACK-38/STACK-31: Responsive card view + mobile layout
Type:
- string
- Source:
(constant) APP_VERSION_KEY :string
LocalStorage key for current app version
Type:
- string
- Source:
(constant) AUTOCOMPLETE_CONFIG
Autocomplete system configuration
- Source:
(constant) BRANDING_DOMAIN_OPTIONS
Domain-based branding configuration
Properties:
| Name | Type | Description |
|---|---|---|
domainMap |
Object.<string, string> | Map of domain keywords to
custom display names. Keys are compared in lowercase and may omit the
domain extension when |
removeExtension |
boolean | When true, strips the domain extension (e.g. ".com") before lookup |
alwaysOverride |
boolean | When true, domain mapping overrides
|
- Source:
(constant) BRANDING_DOMAIN_OVERRIDE :string|null
Title detected from the current domain or null if no mapping found
Falls back to BRANDING_TITLE when running under file:// or no domain is
detected.
Type:
- string | null
- Source:
(constant) BRANDING_TITLE :string
Optional custom application title
Type:
- string
- Source:
(constant) CARD_STYLE_KEY :string
LocalStorage key for card view style (A/B/C/D) (STAK-118)
Type:
- string
- Source:
(constant) CATALOG_HISTORY_KEY :string
LocalStorage key for catalog API call history
Type:
- string
- Source:
(constant) CATALOG_MAP_KEY :string
LocalStorage key for S#/N# associations
Type:
- string
- Source:
(constant) CERT_LOOKUP_URLS :Object.<string, string>
Cert verification lookup URLs for grading authorities. {certNumber} is replaced with the actual certification number. URLs without {certNumber} open the generic verification page.
Type:
- Object.<string, string>
- Source:
(constant) CLOUD_PROVIDERS
Cloud provider configurations. Client IDs are placeholder — replace with real registered app IDs.
- Source:
(constant) DEBUG :boolean
Global debug flag, can be toggled via DEV_MODE or ?debug query parameter
Type:
- boolean
- Source:
(constant) DEFAULT_API_CACHE_DURATION :number
Default cache duration in milliseconds (24 hours)
Type:
- number
- Source:
(constant) DEFAULT_API_QUOTA :number
Default monthly API call quota
Type:
- number
- Source:
(constant) DEFAULT_CURRENCY :string
Default currency code for monetary formatting
Type:
- string
- Source:
(constant) DEFAULT_SORT_COL_KEY :string
LocalStorage key for default inventory sort column
Type:
- string
- Source:
(constant) DEFAULT_SORT_DIR_KEY :string
LocalStorage key for default inventory sort direction
Type:
- string
- Source:
(constant) DESKTOP_CARD_VIEW_KEY :string
LocalStorage key for desktop card view toggle (STAK-118)
Type:
- string
- Source:
(constant) DEV_MODE :boolean
Enables verbose debug logging when true
Type:
- boolean
- Source:
(constant) DISPLAY_CURRENCY_KEY :string
LocalStorage key for display currency preference (STACK-50)
Type:
- string
- Source:
(constant) EXCHANGE_RATES_KEY :string
LocalStorage key for cached exchange rates (STACK-50)
Type:
- string
- Source:
(constant) EXCHANGE_RATE_API_URL :string
Free exchange rate API (no key required)
Type:
- string
- Source:
(constant) FALLBACK_EXCHANGE_RATES :Object.<string, number>
Fallback exchange rates (USD-based) for offline/file:// use (STACK-50) Updated Feb 2026. Used only when API fetch fails and no cached rates exist.
Type:
- Object.<string, number>
- Source:
(constant) FEATURE_FLAGS
Feature flags configuration Controls experimental features and gradual rollouts
Each feature flag contains:
Properties:
| Name | Type | Description |
|---|---|---|
enabled |
boolean | Default enabled state |
urlOverride |
boolean | Allow URL parameter override |
userToggle |
boolean | Allow user preference toggle |
description |
string | Human-readable description |
phase |
string | Development phase (dev/testing/beta/stable) |
- Source:
(constant) FEATURE_FLAGS_KEY :string
LocalStorage key for feature flags
Type:
- string
- Source:
(constant) FIELD_COERCIONS
Coercion rules: fieldId → (rawValue) => coerced value
- Source:
(constant) FILTER_CHIP_CATEGORY_DEFAULTS :Array.<{id: string, label: string, enabled: boolean}>
Default filter chip category configuration. Order determines display order.
Type:
- Array.<{id: string, label: string, enabled: boolean}>
- Source:
(constant) GB_ESTIMATE_MODIFIER_KEY :string
LocalStorage key for user-configurable premium modifier
Type:
- string
- Source:
(constant) GB_ESTIMATE_PREMIUM :number
Default estimation premium multiplier (1.0 = no premium, pure 2x spot)
Type:
- number
- Source:
(constant) GB_TO_OZT :number
Conversion factor: 1 Goldback = 0.001 troy oz 24K gold
Type:
- number
- Source:
(constant) GITHUB_RELEASES_URL :string
Fallback link for static version badge
Type:
- string
- Source:
(constant) GOLDBACK_DENOMINATIONS :Array.<{weight: number, label: string, goldOz: number}>
Standard Goldback denominations with gold content. weight = denomination value (used as item.weight when weightUnit='gb') goldOz = troy oz of 24K gold per note
Type:
- Array.<{weight: number, label: string, goldOz: number}>
- Source:
(constant) GOLDBACK_ENABLED_KEY :string
LocalStorage key for Goldback pricing toggle (STACK-45)
Type:
- string
- Source:
(constant) GOLDBACK_ESTIMATE_ENABLED_KEY :string
LocalStorage key for Goldback estimation toggle (STACK-52)
Type:
- string
- Source:
(constant) GOLDBACK_PRICES_KEY :string
LocalStorage key for Goldback denomination prices (STACK-45)
Type:
- string
- Source:
(constant) GOLDBACK_PRICE_HISTORY_KEY :string
LocalStorage key for Goldback price history (STACK-45)
Type:
- string
- Source:
(constant) HEADER_SYNC_BTN_KEY :string
LocalStorage key for header sync button visibility
Type:
- string
- Source:
(constant) HEADER_TREND_BTN_KEY :string
LocalStorage key for header trend button visibility
Type:
- string
- Source:
(constant) IMAGE_MAX_BYTES :number
Max output size per image side in bytes (500 KB)
Type:
- number
- Source:
(constant) IMAGE_MAX_DIM :number
Max image dimension in px for resize
Type:
- number
- Source:
(constant) IMAGE_QUALITY :number
Default compression quality (0-1)
Type:
- number
- Source:
(constant) INLINE_CHIP_DEFAULTS :Array.<{id: string, label: string, enabled: boolean}>
Default inline chip configuration. Order determines display order.
Type:
- Array.<{id: string, label: string, enabled: boolean}>
- Source:
(constant) ITEMS_PER_PAGE_KEY :string
LocalStorage key for items per page setting
Type:
- string
- Source:
(constant) ITEM_PRICE_HISTORY_KEY :string
LocalStorage key for per-item price history (STACK-43)
Type:
- string
- Source:
(constant) ITEM_TAGS_KEY :string
LocalStorage key for item tags mapping (STAK-126)
Type:
- string
- Source:
(constant) LAST_API_SYNC_KEY :string
LocalStorage key for last API sync timestamp
Type:
- string
- Source:
(constant) LAST_CACHE_REFRESH_KEY :string
LocalStorage key for last cache refresh timestamp
Type:
- string
- Source:
(constant) LAST_VERSION_CHECK_KEY :string
LocalStorage key for last remote version check timestamp (STACK-67)
Type:
- string
- Source:
(constant) LATEST_REMOTE_URL_KEY :string
LocalStorage key for cached latest remote release URL (STACK-67)
Type:
- string
- Source:
(constant) LATEST_REMOTE_VERSION_KEY :string
LocalStorage key for cached latest remote version (STACK-67)
Type:
- string
- Source:
(constant) LAYOUT_SECTION_DEFAULTS :Array.<{id: string, label: string, enabled: boolean}>
Default layout section configuration. Order determines display order.
Type:
- Array.<{id: string, label: string, enabled: boolean}>
- Source:
(constant) LOG_TAB_RENDERERS
Dispatch map: log sub-tab key → window function name
- Source:
(constant) LS_KEY :string
LocalStorage key for inventory data
Type:
- string
- Source:
(constant) MAX_LOCAL_FILE_SIZE
Maximum upload size in bytes for local imports (2MB)
- Source:
(constant) MAX_TAGS_PER_ITEM :number
Maximum number of tags allowed per item (STAK-126)
Type:
- number
- Source:
(constant) MAX_TAG_LENGTH :number
Maximum characters per tag name (STAK-126)
Type:
- number
- Source:
(constant) METALS
Metal configuration object - Central registry for all metal-related information
This configuration drives the entire application's metal handling by defining:
- Display names for user interface elements
- Key identifiers for data structures and calculations
- DOM element ID patterns for dynamic element selection
- LocalStorage keys for persistent data storage
- CSS color variables for styling and theming
Each metal configuration contains:
Properties:
| Name | Type | Description |
|---|---|---|
name |
string | Display name used in UI elements and forms |
key |
string | Lowercase identifier for data objects and calculations |
spotKey |
string | DOM ID pattern for spot price input elements |
localStorageKey |
string | Key for storing spot prices in localStorage |
color |
string | CSS custom property name for metal-specific styling Adding a new metal type requires:
|
- Source:
(constant) METAL_COLORS
Renders the main inventory table with all current display settings
This is the primary display function that:
- Applies current search filters to inventory data
- Sorts data according to user-selected column and direction
- Implements pagination to show only current page items
- Generates HTML table rows with interactive elements
- Updates sort indicators in column headers
- Refreshes pagination controls and summary totals
- Re-establishes column resizing functionality
Called whenever inventory data changes or display settings update
- Source:
(constant) METAL_ORDER_KEY :string
LocalStorage key for metal order/visibility config
Type:
- string
- Source:
(constant) METAL_SYMBOLS
Symbol mapping for API requests (metal name → ISO 4217 precious metal code)
- Source:
(constant) NUMISTA_VIEW_FIELD_DEFAULTS :Object.<string, boolean>
Default Numista view field visibility. All enabled by default.
Type:
- Object.<string, boolean>
- Source:
(constant) NumistaLookup
Numista Search Lookup Module Pattern-based query rewriting for improved Numista search results. Matches user input against known coin naming patterns and rewrites queries to use Numista's canonical naming convention.
Follows the IIFE module pattern used by customMapping.js.
- Source:
(constant) PREBUILT_LOOKUP_DATA
Pre-built lookup database with common precious metals items Sourced from comprehensive industry data for enhanced autocomplete suggestions
- Source:
(constant) PRICE_HISTORY_COLS
Column keys for the price history table, matching
- Source:
(constant) Remote :string
base URL for historical data (file:// fallback)
Type:
- string
(constant) SEED_CUSTOM_RULES :Array.<{pattern: string, replacement: string, numistaId: (string|null), obverse: string, reverse: string}>
Seed custom rule definitions with embedded base64 WebP image data. Each entry becomes a custom pattern rule in NumistaLookup, visible in Settings > Images > Custom Pattern Rules with thumbnails.
Type:
- Array.<{pattern: string, replacement: string, numistaId: (string|null), obverse: string, reverse: string}>
- Source:
(constant) SEED_DATA_YEARS :Array.<number>
Years with available seed data. Updated by generate-seed-data.py.
Type:
- Array.<number>
- Source:
(constant) SEED_IMAGES_VERSION :string
Version string for seed images. Bump when images are updated so existing caches get refreshed. Stored in localStorage as 'seedImagesVer'.
Type:
- string
- Source:
(constant) SEED_INVENTORY_ITEMS
Sample inventory items for first-time users. Provides 8 items across 4 metals so new users see a populated table, learn the data model, and discover filter chips via grouped names.
3x American Silver Eagle (graded, Numista 298883) — triggers name chip 3x Canadian Gold Maple Leaf (Numista 75250) — triggers name chip 1x Platinum Round, 1x Palladium Bar
- Source:
(constant) SERIAL_KEY :string
LocalStorage key for inventory serial counter
Type:
- string
- Source:
(constant) SPOT_COMPARE_MODE_KEY :string
LocalStorage key for 24h % comparison mode (STACK-92)
Type:
- string
- Source:
(constant) SPOT_HISTORY_KEY :string
LocalStorage key for spot price history
Type:
- string
- Source:
(constant) SPOT_TREND_KEY :string
LocalStorage key for persisted spot trend period
Type:
- string
- Source:
(constant) SPOT_TREND_RANGE_KEY :string
LocalStorage key for sparkline trend range preferences
Type:
- string
- Source:
(constant) STORAGE_KEY_LABELS
Friendly display names for known localStorage keys
- Source:
(constant) STORAGE_TINY_THRESHOLD_KB
Keys under this KB threshold are considered "minor" and hidden by default
- Source:
(constant) SUPPORTED_CURRENCIES :Array.<{code: string, name: string}>
Supported display currencies for the currency selector (STACK-50)
Type:
- Array.<{code: string, name: string}>
- Source:
(constant) SYNC_FILE_PATH
Dropbox path for the rolling sync vault file
- Source:
(constant) SYNC_META_PATH
Dropbox path for the lightweight sync metadata pointer
- Source:
(constant) SYNC_POLL_INTERVAL
Poll interval for remote change detection (10 minutes in ms)
- Source:
(constant) SYNC_PUSH_DEBOUNCE
Debounce delay before pushing after a saveInventory() call (2 seconds)
- Source:
(constant) SYNC_SCOPE_KEYS
Keys included in a sync vault (excludes API keys, tokens, spot history). Only inventory data + display preferences that are meaningful across devices.
- Source:
(constant) THEME_KEY :string
LocalStorage key for theme preference
Type:
- string
- Source:
(constant) TIMEZONE_KEY :string
LocalStorage key for display timezone preference (STACK-63)
Type:
- string
- Source:
(constant) TREND_PRESETS
Trend period presets and labels for the header trend cycle button.
- Source:
(constant) TREND_PRESETS
Trend period presets and labels for the header trend cycle button.
- Source:
(constant) VALID_TYPES :Array.<string>
Allowed inventory item types
Type:
- Array.<string>
(constant) VAULT_FILE_EXTENSION :Array.<string>
List of recognized localStorage keys for cleanup validation
Type:
- Array.<string>
- Source:
(constant) VERSION_ACK_KEY :string
LocalStorage key for acknowledged app version
Type:
- string
- Source:
(constant) VERSION_CHECK_TTL :number
Cache TTL for remote version check in ms (24 hours)
Type:
- number
- Source:
(constant) VERSION_CHECK_URL :string
Remote endpoint for latest version info (STACK-67)
Type:
- string
- Source:
(constant) VIEW_METADATA_TTL :number
Numista metadata cache TTL: 30 days in milliseconds. Used by viewModal.js to skip re-fetching recently cached metadata.
Type:
- number
- Source:
(constant) VIEW_MODAL_SECTION_DEFAULTS :Array.<{id: string, label: string, enabled: boolean}>
Default view modal section configuration. Order determines display order.
Type:
- Array.<{id: string, label: string, enabled: boolean}>
- Source:
(constant) _VIEW_CHART_DEFAULT_RANGE :number
Default chart range in days (-1 = from purchase date, falls back to 30d)
Type:
- number
- Source:
(constant) _VIEW_CHART_RANGES :Array.<number>
Available chart range options (0 = all, -1 = from purchase date)
Type:
- Array.<number>
- Source:
(constant) _VIEW_CHART_RANGE_LABELS :Array.<string>
Display labels for chart range pills
Type:
- Array.<string>
- Source:
(constant) __ST_COMP_PREFIX
Storage compression helpers (Phase 1C)
_cardClickBound :boolean
Type:
- boolean
- Source:
_cardClickBound :boolean
Type:
- boolean
- Source:
_cardSortBarBound :boolean
Whether card sort bar event listeners have been bound
Type:
- boolean
- Source:
_cardSortBarBound :boolean
Whether card sort bar event listeners have been bound
Type:
- boolean
- Source:
_cloudContext :object|null
Cloud context for cloud-export/cloud-import modes
Type:
- object | null
_cvBlobUrls :Array.<string>
Blob URLs to revoke on next render
Type:
- Array.<string>
- Source:
_cvBlobUrls :Array.<string>
Blob URLs to revoke on next render
Type:
- Array.<string>
- Source:
_cvChartInstances :Array.<Chart>
Active card chart instances to destroy on re-render
Type:
- Array.<Chart>
- Source:
_cvChartInstances :Array.<Chart>
Active card chart instances to destroy on re-render
Type:
- Array.<Chart>
- Source:
_cvImageObserver :IntersectionObserver|null
Type:
- IntersectionObserver | null
- Source:
_cvImageObserver :IntersectionObserver|null
Type:
- IntersectionObserver | null
- Source:
_deleteObverseOnSave :boolean
User clicked Remove on obverse — delete on save
Type:
- boolean
_deleteReverseOnSave :boolean
User clicked Remove on reverse — delete on save
Type:
- boolean
_hScrollWired
Whether the custom H-scroll bar event listeners have been wired
- Source:
_hScrollWired
Whether the custom H-scroll bar event listeners have been wired
- Source:
_itemPriceModalFilterText :string
Filter text for the per-item modal table
Type:
- string
- Source:
_itemPriceModalUuid :string
UUID of the item currently displayed in the per-item modal
Type:
- string
- Source:
_patternMode
Settings modal listener binders (STAK-135)
Keeps listener wiring split by concern while preserving existing behavior.
- Source:
_pendingObverseBlob :Blob|null
Pending obverse upload blob — saved on item commit
Type:
- Blob | null
_pendingObversePreviewUrl :string|null
Preview object URL for obverse — revoked on modal close
Type:
- string | null
_pendingReverseBlob :Blob|null
Pending reverse upload blob — saved on item commit
Type:
- Blob | null
_pendingReversePreviewUrl :string|null
Preview object URL for reverse — revoked on modal close
Type:
- string | null
_statusCells :Map.<string, HTMLElement>
Status cells keyed by catalogId for live updates
Type:
- Map.<string, HTMLElement>
- Source:
_storageTinyVisible
True = show minor keys; toggled by the button in the panel
- Source:
(constant) _storedSortCol :Object
Sorting state tracking — initialized from user preference or factory default
Type:
- Object
_syncPollerTimer :number|null
setInterval handle for the polling loop
Type:
- number | null
- Source:
_syncProvider :string
Currently active sync provider
Type:
- string
- Source:
_syncPushInFlight :boolean
Whether a push is currently in progress
Type:
- boolean
- Source:
_syncRetryDelay :number
Retry backoff multiplier for 429 / network errors
Type:
- number
- Source:
_thumbBlobUrls
Blob URLs created by _enhanceTableThumbnails — revoked on each re-render
- Source:
_thumbObserver
IntersectionObserver instance for lazy-loading table thumbnails
- Source:
_vaultPendingFile :Uint8Array|null
Pending file bytes for import
Type:
- Uint8Array | null
_viewModalChartInstance :Chart|null
Price history chart instance — destroyed on modal close
Type:
- Chart | null
- Source:
_viewModalObjectUrls :Array.<string>
Active object URLs created for the current view modal session. Revoked on modal close to prevent memory leaks.
Type:
- Array.<string>
- Source:
(constant) _viewYearCache :Map.<number, Array>
Year-file cache shared with spot.js when available
Type:
- Map.<number, Array>
- Source:
(constant) _viewYearFetchPromises :Map.<number, Promise.<Array>>
In-flight fetch promises to deduplicate concurrent requests
Type:
- Map.<number, Promise.<Array>>
- Source:
activeFilters :Object.<string, FilterConfig>
Type:
- Object.<string, FilterConfig>
- Source:
apiCache :Object|null
Cached API data with timestamp
Type:
- Object | null
apiConfig :Object|null
Current Metals API configuration
Type:
- Object | null
apiHistoryEntries :Array.<Object>
In-memory buffer for API history log entries
Type:
- Array.<Object>
apiHistoryFilterText :string
Active filter text for searching API history
Type:
- string
apiHistorySortAsc :boolean
Sort direction for the API history table
Type:
- boolean
apiHistorySortColumn :string
Current sort column for the API history table
Type:
- string
brandingWarned
Gets the active branding name considering domain overrides
catalogHistory :Array
Catalog API call history records
Type:
- Array
catalogMap :Object
Backward compatibility for catalogMap - now managed by catalogManager
Type:
- Object
changeLog :Array
Change log entries
Type:
- Array
chartInstances :Object
Chart instances for proper cleanup
Type:
- Object
cloudBackupEnabled
Flag indicating whether cloud backup is enabled
- Source:
compositionOptions :Set.<string>
Available composition options
Type:
- Set.<string>
currentLookupTable :LookupTable|null
Current lookup table instance
Type:
- LookupTable | null
- Source:
detailsChartMetric :string
Current pie chart metric — purchase | melt | retail | gainLoss
Type:
- string
- Source:
detailsResizeObserver :ResizeObserver|null
Active ResizeObserver for chart resize handling
Type:
- ResizeObserver | null
- Source:
displayCurrency :string
User's selected display currency (ISO 4217), default USD (STACK-50)
Type:
- string
editingChangeLogIndex :number|null
Change log entry currently being edited
Type:
- number | null
editingIndex :number|null
Index of item being edited (null = no edit in progress)
Type:
- number | null
(constant) elements :Object
Cached DOM elements for performance
Type:
- Object
exchangeRates :Object.<string, number>
Cached exchange rates: 1 USD = rate × target currency (STACK-50)
Type:
- Object.<string, number>
(constant) featureFlags :FeatureFlags
Global feature flags instance
Type:
- Source:
gbHistoryFilterText :string
Current filter text for the history table
Type:
- string
- Source:
gbHistorySortAsc :boolean
Sort direction (true = ascending)
Type:
- boolean
- Source:
gbHistorySortColumn :string
Current sort column
Type:
- string
- Source:
goldbackEnabled :boolean
Whether Goldback denomination pricing is enabled (STACK-45)
Type:
- boolean
goldbackEstimateEnabled :boolean
Whether Goldback real-time price estimation is enabled (STACK-52)
Type:
- boolean
goldbackEstimateModifier :number
User-configurable premium modifier for Goldback estimation (STACK-52)
Type:
- number
goldbackPriceHistory :Object
Goldback price history keyed by weight string (STACK-45)
Type:
- Object
goldbackPrices :Object
Goldback denomination prices keyed by weight string (STACK-45)
Type:
- Object
(constant) historicalDataCache :Map.<number, Array>
Cached year-file entries keyed by year
Type:
- Map.<number, Array>
(constant) historicalFetchPromises :Map.<number, Promise.<Array>>
In-flight fetch promises to deduplicate concurrent requests
Type:
- Map.<number, Promise.<Array>>
inventory :Array
Main inventory data structure
Type:
- Array
itemPriceHistory :Object
Per-item price history keyed by UUID (STACK-43)
Type:
- Object
itemTags :Object
Item tags mapping: { [uuid]: string[] } (STAK-126)
Type:
- Object
itemsPerPage :number
Number of visible rows in the portal (scrollable table) view
Type:
- number
marketValueViewItems :Set.<number>
Items currently showing market value instead of purchase price
Type:
- Set.<number>
notesIndex :number|null
Index of item whose notes are being edited
Type:
- number | null
priceHistoryFilterText :string
Filter text for the settings price history table
Type:
- string
- Source:
scheduleSyncPush :function
Debounced version of pushSyncVault
Type:
- function
- Source:
searchQuery :string
Current search query
Type:
- string
settingsCatalogSortAsc :boolean
Sort ascending for settings catalog history table
Type:
- boolean
- Source:
settingsCatalogSortColumn :string
Sort column for settings catalog history table
Type:
- string
- Source:
settingsCloudSortAsc :boolean
Sort ascending for settings cloud activity table
Type:
- boolean
- Source:
settingsCloudSortColumn :string|null
Sort column for settings cloud activity table
Type:
- string | null
- Source:
settingsLbmaControlsBound :boolean
Prevent duplicate LBMA control binding
Type:
- boolean
settingsLbmaLoadPromise :Promise.<Array.<Object>>|null
In-flight LBMA load promise
Type:
- Promise.<Array.<Object>> | null
settingsLbmaReferenceCache :Array.<Object>|null
Cached LBMA reference entries
Type:
- Array.<Object> | null
settingsLbmaSortAsc :boolean
Sort ascending for settings LBMA reference table
Type:
- boolean
settingsLbmaSortColumn :string
Current sort column for settings LBMA reference table
Type:
- string
settingsPriceSortAsc :boolean
Sort ascending for settings price history table
Type:
- boolean
- Source:
settingsPriceSortColumn :string
Sort column for settings price history table
Type:
- string
- Source:
settingsSpotSortAsc :boolean
Sort ascending for settings spot history table
Type:
- boolean
settingsSpotSortColumn :string
Current sort column for settings spot history table
Type:
- string
sparklineInstances :Object
Sparkline Chart.js instances keyed by metal (for cleanup)
Type:
- Object
spotHistory :Array
Historical spot price records
Type:
- Array
spotPrices :Object
Current spot prices for all metals
Type:
- Object
Methods
_addDetail()
Add a detail item to a grid
- Source:
_applyTrend(val)
Applies a trend period value to all four metal sparkline selects and updates the header trend label.
Parameters:
| Name | Type | Description |
|---|---|---|
val |
string | The trend period value to apply. |
- Source:
_applyTrend(val)
Applies a trend period value to all four metal sparkline selects and updates the header trend label.
Parameters:
| Name | Type | Description |
|---|---|---|
val |
string | The trend period value to apply. |
- Source:
_cardChipsHTML(item, smallopt) → {string}
Builds chip HTML for card views.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
item |
object | |||
small |
boolean |
<optional> |
false |
- Source:
Returns:
- Type
- string
_cardChipsHTML(item, smallopt) → {string}
Builds chip HTML for card views.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
item |
object | |||
small |
boolean |
<optional> |
false |
- Source:
Returns:
- Type
- string
_cardFmt()
Format currency using app's formatCurrency or simple fallback.
- Source:
_cardFmt()
Format currency using app's formatCurrency or simple fallback.
- Source:
_cardImageHTML(item, extraClassopt, sideopt) → {string}
Returns coin image HTML. Renders an with data attributes for async
ImageCache resolution (same pattern as table thumbnails in inventory.js).
Falls back to a metal-initial placeholder via onerror.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
item |
object | |||
extraClass |
string |
<optional> |
'' | |
side |
string |
<optional> |
'obverse' | 'obverse' or 'reverse' |
- Source:
Returns:
- Type
- string
_cardImageHTML(item, extraClassopt, sideopt) → {string}
Returns coin image HTML. Renders an with data attributes for async
ImageCache resolution (same pattern as table thumbnails in inventory.js).
Falls back to a metal-initial placeholder via onerror.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
item |
object | |||
extraClass |
string |
<optional> |
'' | |
side |
string |
<optional> |
'obverse' | 'obverse' or 'reverse' |
- Source:
Returns:
- Type
- string
_cardMetalClass(metal) → {string}
Returns metal CSS class for card border/accent.
Parameters:
| Name | Type | Description |
|---|---|---|
metal |
string |
- Source:
Returns:
- Type
- string
_cardMetalClass(metal) → {string}
Returns metal CSS class for card border/accent.
Parameters:
| Name | Type | Description |
|---|---|---|
metal |
string |
- Source:
Returns:
- Type
- string
_cloudBackupWithCachedPw()
Perform a cached-password cloud backup (encrypt + upload, no vault modal).
- Source:
(async) _cloudBtnAction(btn, label, action, errorPrefix, finallyFnopt)
Run an async action while showing a loading state on a button. Saves innerHTML, disables the button, runs the action, then restores.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
btn |
HTMLElement | ||
label |
string | loading text to show (e.g. 'Uploading…') |
|
action |
function | async function to execute |
|
errorPrefix |
string | prefix for alert on failure |
|
finallyFn |
function |
<optional> |
optional cleanup in finally block |
- Source:
(async) _cloudRestoreWithCachedPw()
Perform a cached-password cloud restore (decrypt + restore, no vault modal).
- Source:
_computePortfolioSummary() → {Object}
Computes portfolio summary totals for currently filtered items.
- Source:
Returns:
- Type
- Object
_computePortfolioSummary() → {Object}
Computes portfolio summary totals for currently filtered items.
- Source:
Returns:
- Type
- Object
_createPriceHistoryChart(canvas, allSpotEntries, allRetailEntries, purchasePerUnit, meltFactor, daysopt, purchaseDateopt, currentRetailopt, fromTsopt, toTsopt)
Create a Chart.js line chart showing price history for the viewed item. Primary: melt value derived from spotHistory (dense daily data). Secondary: retail value anchored from purchase date/price to current market value, with sparse itemPriceHistory snapshots in between. Purchase price shown as a flat dashed reference line.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
canvas |
HTMLCanvasElement | |||
allSpotEntries |
Array.<{ts:number, spot:number}> | Daily spot prices for this metal |
||
allRetailEntries |
Array.<{ts:number, retail:number}> | Sparse retail value snapshots |
||
purchasePerUnit |
number | Original purchase price per unit |
||
meltFactor |
number | weightOz * qty * purity (melt = spot * meltFactor) |
||
days |
number |
<optional> |
0 | Number of days to show (0 = all) |
purchaseDate |
number |
<optional> |
0 | Purchase date timestamp (anchor start for retail line) |
currentRetail |
number |
<optional> |
0 | Current market/retail value (anchor end for retail line) |
fromTs |
number |
<optional> |
0 | Custom range start timestamp (0 = unbounded) |
toTs |
number |
<optional> |
0 | Custom range end timestamp (0 = unbounded) |
- Source:
_cvEscapeAttr(s) → {string}
Escapes HTML attribute values — fallback for card-view context. The main escapeAttribute lives in inventory.js (loaded before this file).
Parameters:
| Name | Type | Description |
|---|---|---|
s |
string |
- Source:
Returns:
- Type
- string
_cvEscapeAttr(s) → {string}
Escapes HTML attribute values — fallback for card-view context. The main escapeAttribute lives in inventory.js (loaded before this file).
Parameters:
| Name | Type | Description |
|---|---|---|
s |
string |
- Source:
Returns:
- Type
- string
_darkenColor(color, amount) → {string}
Darken a hex/rgb color by a factor (0–1). 0 = no change, 1 = black.
Parameters:
| Name | Type | Description |
|---|---|---|
color |
string | Hex or rgb() string |
amount |
number | Darkening factor |
- Source:
Returns:
Hex color
- Type
- string
_dataToPolylineScaled(data, w, h, globalMin, globalMax, padYopt) → {string}
Converts data to SVG polyline using a shared min/max scale.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
data |
Array.<number> | |||
w |
number | SVG width |
||
h |
number | SVG height |
||
globalMin |
number | |||
globalMax |
number | |||
padY |
number |
<optional> |
4 |
- Source:
Returns:
- Type
- string
_dataToPolylineScaled(data, w, h, globalMin, globalMax, padYopt) → {string}
Converts data to SVG polyline using a shared min/max scale.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
data |
Array.<number> | |||
w |
number | SVG width |
||
h |
number | SVG height |
||
globalMin |
number | |||
globalMax |
number | |||
padY |
number |
<optional> |
4 |
- Source:
Returns:
- Type
- string
_detailItem()
Create a label/value detail item element
- Source:
_el()
Create element with className
- Source:
(async) _enhanceCardImages(container)
Enhances card thumbnail images from IndexedDB ImageCache. Uses IntersectionObserver for lazy loading (same pattern as table thumbnails).
Parameters:
| Name | Type | Description |
|---|---|---|
container |
HTMLElement |
- Source:
(async) _enhanceCardImages(container)
Enhances card thumbnail images from IndexedDB ImageCache. Uses IntersectionObserver for lazy loading (same pattern as table thumbnails).
Parameters:
| Name | Type | Description |
|---|---|---|
container |
HTMLElement |
- Source:
(async) _enhanceTableThumbnails()
Upgrades table thumbnail src attributes from IDB blob URLs using IntersectionObserver for viewport-based lazy loading. Pre-loads 200px before viewport for smooth scrolling.
- Source:
_extractMetadata(result) → {Object}
Extract metadata fields from a Numista API result.
Parameters:
| Name | Type | Description |
|---|---|---|
result |
Object |
- Source:
Returns:
- Type
- Object
(async) _fetchHistoricalSpotData(metalName, days, fromTsopt, toTsopt) → {Promise.<Array.<{ts:number, spot:number}>>}
Fetch full historical spot data for a metal by loading year files. Merges fetched year-file data with live spotHistory, deduplicates by day (live data wins over seed). Returns sorted {ts, spot} entries.
For ranges <= 180 days, just returns the in-memory spotHistory slice (no fetch). For longer ranges (including "All"), async-fetches year files back to 1968.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
metalName |
string | Metal name ('Silver', 'Gold', etc.) |
||
days |
number | Number of days (0 = all available data) |
||
fromTs |
number |
<optional> |
0 | Custom range start (0 = unbounded) |
toTs |
number |
<optional> |
0 | Custom range end (0 = unbounded) |
- Source:
Returns:
Sorted daily spot entries
- Type
- Promise.<Array.<{ts:number, spot:number}>>
(async) _fetchNumistaResult(catalogId) → {Promise.<(Object|null)>}
Fetch a Numista item by catalogId. Returns the normalized result or null.
Parameters:
| Name | Type | Description |
|---|---|---|
catalogId |
string |
- Source:
Returns:
- Type
- Promise.<(Object|null)>
_fetchYearFile(year) → {Promise.<Array>}
Fetch a single year file with three-tier fallback (fetch → XHR → remote). Reuses spot.js cache/fetcher when available; falls back to own implementation. Deduplicates concurrent fetches for the same year.
Parameters:
| Name | Type | Description |
|---|---|---|
year |
number |
- Source:
Returns:
- Type
- Promise.<Array>
_getBulkImageSides() → {Object}
Reads tableImageSides setting and returns which sides to display.
- Source:
Returns:
- Type
- Object
_getOrCreateHScrollBar() → {Object|null}
Creates the scrollbar DOM node (once) and inserts it after .portal-scroll.
- Source:
Returns:
- Type
- Object | null
_getOrCreateHScrollBar() → {Object|null}
Creates the scrollbar DOM node (once) and inserts it after .portal-scroll.
- Source:
Returns:
- Type
- Object | null
_getThumbPlaceholder(metal, type) → {string}
Generate an inline SVG data URI for a metal-themed placeholder thumbnail. Uses the metal's brand color and an icon based on item type (coin vs bar).
Parameters:
| Name | Type | Description |
|---|---|---|
metal |
string | Metal name (Silver, Gold, Platinum, Palladium) |
type |
string | Item type (Coin, Bar, Round, etc.) |
- Source:
Returns:
data:image/svg+xml URI
- Type
- string
_getViewMetrics(item) → {Object}
Compute shared metrics used by all view modal section renderers.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Inventory item |
- Source:
Returns:
Metrics object with currentSpot, qty, weight, purity, isGb, weightOz, metalColor
- Type
- Object
_imageSlot()
Create an image slot with placeholder
- Source:
_initCardCharts(container)
Initializes Chart.js mini-charts on all .card-a-canvas elements. Reads spot history data from the canvas data attributes and builds the same 3-line chart as the view modal (purchase/melt/retail).
Parameters:
| Name | Type | Description |
|---|---|---|
container |
HTMLElement |
- Source:
_initCardCharts(container)
Initializes Chart.js mini-charts on all .card-a-canvas elements. Reads spot history data from the canvas data attributes and builds the same 3-line chart as the view modal (purchase/melt/retail).
Parameters:
| Name | Type | Description |
|---|---|---|
container |
HTMLElement |
- Source:
_initSpotControls()
Initialises spot controls: applies the persisted trend period on load.
The per-card
- Source:
_initSpotControls()
Initialises spot controls: applies the persisted trend period on load.
The per-card
- Source:
_interpolateNulls(arr) → {Array.<number>}
Interpolate null gaps in an array for SVG rendering (equivalent to Chart.js spanGaps).
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
Array.<(number|null)> |
- Source:
Returns:
- Type
- Array.<number>
_interpolateNulls(arr) → {Array.<number>}
Interpolate null gaps in an array for SVG rendering (equivalent to Chart.js spanGaps).
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
Array.<(number|null)> |
- Source:
Returns:
- Type
- Array.<number>
_isLightColor(color) → {boolean}
Check if a color is light based on relative luminance.
Parameters:
| Name | Type | Description |
|---|---|---|
color |
string | Hex or rgb() string |
- Source:
Returns:
True if light (needs dark text)
- Type
- boolean
(async) _loadBulkRowImages(tr, item)
Resolves IDB images for one item and injects elements into its
IMG cell, replacing the placeholder. Respects tableImageSides setting.
Blob URLs are tracked in _bulkBlobUrls for cleanup on modal close.
Parameters:
| Name | Type | Description |
|---|---|---|
tr |
HTMLTableRowElement | |
item |
Object |
- Source:
(async) _loadCardImage(img)
Resolves and sets blob URL for a single card thumbnail image.
Parameters:
| Name | Type | Description |
|---|---|---|
img |
HTMLImageElement |
- Source:
(async) _loadCardImage(img)
Resolves and sets blob URL for a single card thumbnail image.
Parameters:
| Name | Type | Description |
|---|---|---|
img |
HTMLImageElement |
- Source:
_loadSectionConfig(key, defaults, legacyKeyopt, migrateFnopt) → {Array.<{id: string, label: string, enabled: boolean}>}
Generic loader for section config arrays from localStorage. Merges saved user config with defaults so new sections are auto-appended.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
key |
string | localStorage key |
|
defaults |
Array.<{id: string, label: string, enabled: boolean}> | ||
legacyKey |
string |
<optional> |
Optional legacy key to migrate from |
migrateFn |
function |
<optional> |
Migration function for legacy data |
- Source:
Returns:
- Type
- Array.<{id: string, label: string, enabled: boolean}>
(async) _loadThumbImage(img)
Resolve and set blob URL for a single table thumbnail image. Checks IDB cache (user uploads → pattern images → Numista cache). Falls back to a metal-colored SVG placeholder when no image is available.
Parameters:
| Name | Type | Description |
|---|---|---|
img |
HTMLImageElement | Table thumbnail element with data attributes |
- Source:
_normalizePatterns(list) → {Array.<string>}
Normalizes a list of search patterns for comparison. Trims, lowercases, and sorts the patterns.
Parameters:
| Name | Type | Description |
|---|---|---|
list |
Array.<string> | The list of patterns to normalize |
Returns:
The normalized list
- Type
- Array.<string>
_openBulkImagePopover(imgTd, item)
Opens a small inline image-management popover anchored to the IMG cell. Lets the user upload obverse/reverse photos or remove existing ones for a single item. Saves directly to imageCache and refreshes that row.
Parameters:
| Name | Type | Description |
|---|---|---|
imgTd |
HTMLTableDataCellElement | |
item |
Object |
- Source:
_openExternalPopup(url, nameopt)
Open a URL in a 1250px popup window. Most external sites block iframe embedding (X-Frame-Options), so we use window.open().
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
url |
string | |||
name |
string |
<optional> |
'_blank' | Window name for reuse |
- Source:
_openThumbPopover(cell, item)
Opens a fixed-position popover anchored below (or above) the image cell. Shows a large preview of the resolved image for each visible side, with Upload, Camera (mobile/HTTPS only), and Remove buttons. Saves directly to imageCache and refreshes the row's thumbnails.
Parameters:
| Name | Type | Description |
|---|---|---|
cell |
HTMLTableDataCellElement | the td[data-column="image"] element |
item |
Object | the full inventory item object |
- Source:
_parseColor(color) → {Array.<number>}
Parse a color string (hex #rrggbb or rgb(r,g,b)) into [r, g, b].
Parameters:
| Name | Type | Description |
|---|---|---|
color |
string |
- Source:
Returns:
[r, g, b] in 0-255
- Type
- Array.<number>
_renderSectionConfigTable(opts)
Generic section-config table renderer. Builds a checkbox + arrow reorder table for any {id, label, enabled}[] config.
Parameters:
| Name | Type | Description | ||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
opts |
Object |
Properties
|
- Source:
_renderSortBarSummary()
Renders the portfolio summary strip in the sort bar.
- Source:
_renderSortBarSummary()
Renders the portfolio summary strip in the sort bar.
- Source:
(async) _restoreCdnFolderFromZip(zip)
Restores CDN images from an imported ZIP file.
Parameters:
| Name | Type | Description |
|---|---|---|
zip |
JSZip | The loaded ZIP object. |
- Source:
_saveSectionConfig(key, config)
Generic saver for section config arrays to localStorage.
Parameters:
| Name | Type | Description |
|---|---|---|
key |
string | localStorage key |
config |
Array.<{id: string, label: string, enabled: boolean}> |
- Source:
_schedulePoll()
Schedule the next poll using the current _syncRetryDelay (respects backoff).
- Source:
_section()
Create a data section with title
- Source:
_setSlotImage()
Replace placeholder with actual image in a slot
- Source:
_showCardImage(img, url)
Show a card image and hide its placeholder.
Parameters:
| Name | Type | Description |
|---|---|---|
img |
HTMLImageElement | |
url |
string |
- Source:
_showCardImage(img, url)
Show a card image and hide its placeholder.
Parameters:
| Name | Type | Description |
|---|---|---|
img |
HTMLImageElement | |
url |
string |
- Source:
_syncFallbackUUID()
Fallback UUID generator when generateUUID from utils.js is unavailable
- Source:
_syncHScrollBar(show)
Shows or hides the custom H-scroll bar and wires events (once).
Parameters:
| Name | Type | Description |
|---|---|---|
show |
boolean |
- Source:
_syncHScrollBar(show)
Shows or hides the custom H-scroll bar and wires events (once).
Parameters:
| Name | Type | Description |
|---|---|---|
show |
boolean |
- Source:
_syncRelativeTime()
Format a timestamp as a relative time string ("just now", "5 min ago", etc.)
- Source:
_syncSortBar()
Ensures the sort bar is always visible and syncs controls to the active view style. Called after every renderTable() — works around inventory.js hiding the bar in table mode.
- Source:
_syncSortBar()
Ensures the sort bar is always visible and syncs controls to the active view style. Called after every renderTable() — works around inventory.js hiding the bar in table mode.
- Source:
_updateHScrollThumb()
Recalculates thumb size and position from portal scroll state.
- Source:
_updateHScrollThumb()
Recalculates thumb size and position from portal scroll state.
- Source:
acceptAck()
Accepts the acknowledgment and hides the modal
addCompositionOption(value)
Adds a composition option and updates dropdowns
Parameters:
| Name | Type | Description |
|---|---|---|
value |
string | Composition to add |
addItemTag(uuid, tag, persistopt) → {boolean}
Add a tag to an item. Prevents duplicates and enforces limits.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
uuid |
string | Item UUID |
||
tag |
string | Tag name |
||
persist |
boolean |
<optional> |
true | Whether to save to localStorage immediately |
Returns:
True if tag was added
- Type
- boolean
analyzeStorageData()
Analyzes localStorage data and calculates memory usage
analyzeStorageItem()
Analyzes a storage item to determine its type and content
applyColumnFilter(field, value)
Legacy function for backward compatibility with table click handlers
Parameters:
| Name | Type | Description |
|---|---|---|
field |
string | The field to filter by |
value |
string | The value to filter for |
- Source:
applyHeaderToggleVisibility()
Shows/hides the header shortcut buttons based on stored preferences. Theme and Currency default hidden; Trend and Sync default visible.
- Source:
applyLayoutOrder()
Shows/hides and reorders major page sections based on layout section config. Reads from localStorage and applies both visibility and DOM order.
- Source:
applyMetalOrder()
Applies metal order config: reorders and shows/hides spot price cards and totals cards.
- Source:
applyMinCountThreshold(data, minCount) → {Object}
Applies a minimum count threshold to a category data object, filtering out entries below the threshold.
Parameters:
| Name | Type | Description |
|---|---|---|
data |
Object | Map of { key: count } |
minCount |
number | Minimum count to include |
- Source:
Returns:
Filtered map
- Type
- Object
applyNumistaTags(uuid, numistaTags, persistopt) → {number}
Apply Numista tags to an item from an API result. Capitalizes the first letter of each tag. Skips duplicates.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
uuid |
string | Item UUID |
||
numistaTags |
Array.<string> | Array of tag strings from Numista API |
||
persist |
boolean |
<optional> |
true | Whether to call saveItemTags() after applying. Pass false when calling in a loop; caller is responsible for a single saveItemTags() after. |
Returns:
Number of tags added
- Type
- number
applyQuickFilter(field, value, isGroupedopt, excludeopt)
Applies a quick filter for a specific field value (when clicking on table values) Supports 3-level deep filtering - clicking same filter removes it, clicking different filters stacks them
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
field |
string | The field to filter by |
||
value |
string | The value to filter for |
||
isGrouped |
boolean |
<optional> |
false | Whether this is a grouped/special filter (uses 'include' logic) |
exclude |
boolean |
<optional> |
false | Whether to apply the filter in exclusion mode |
- Source:
attachAutocomplete(inputEl, sourceType)
Attach autocomplete dropdown to an input element. Creates a dropdown that shows filtered suggestions from the lookup table.
Parameters:
| Name | Type | Description |
|---|---|---|
inputEl |
HTMLInputElement | The input element to attach to |
sourceType |
string | Key into currentLookupTable ('names', 'purchaseLocations', 'storageLocations') |
- Source:
attachPriceHistorySortHeaders(table)
Attaches click-to-sort handlers to price history table headers.
Parameters:
| Name | Type | Description |
|---|---|---|
table |
HTMLTableElement |
- Source:
autoSelectDefaultProvider()
Automatically selects the primary API provider based on priority and availability. The highest-priority provider that has a stored API key is selected as default.
(async) autoSyncSpotPrices() → {Promise.<void>}
Triggers an automatic background spot price synchronization. Only runs if API keys are configured and local data is stale.
Returns:
Resolves when background sync process ends
- Type
- Promise.<void>
(async) backfillStaktrakrHourly() → {Promise.<number>}
Backfills the last 24 hours of hourly spot data from StakTrakr into spotHistory. Only runs when STAKTRAKR is the primary provider (rank 1) and sync succeeded.
Returns:
Count of new entries added
- Type
- Promise.<number>
bindAppearanceAndHeaderListeners()
Binds listeners for appearance settings (theme, display currency, timezone, header toggles).
- Source:
bindCardAndTableImageListeners()
Binds listeners for card style and table image toggles.
- Source:
bindCardClickHandler(container)
Binds a delegated click handler on the card grid container.
Parameters:
| Name | Type | Description |
|---|---|---|
container |
HTMLElement |
- Source:
bindCardClickHandler(container)
Binds a delegated click handler on the card grid container.
Parameters:
| Name | Type | Description |
|---|---|---|
container |
HTMLElement |
- Source:
bindCloudCacheListeners()
Wires cloud storage connect/disconnect/backup/restore buttons.
- Source:
bindFilterAndNumistaListeners()
Binds listeners for filter settings and Numista integration options.
- Source:
bindGoldbackActionListeners()
Binds listeners for Goldback price entry and history actions.
- Source:
bindGoldbackToggleListeners()
Binds listeners for Goldback feature toggles and estimation settings.
- Source:
bindImageImportExportListeners()
Binds listeners for image import/export buttons.
- Source:
bindImageSettingsListeners()
Aggregates all image-related settings listeners.
- Source:
bindImageSyncListeners()
Binds listeners for image sync and cache clearing operations.
- Source:
bindLbmaHistoryControls()
Binds LBMA history filter controls once.
bindNumistaBulkSyncListeners()
Binds listeners for Numista bulk sync operations.
- Source:
bindPatternRuleModeListeners()
Binds listeners for pattern rule mode switching and creation.
- Source:
bindSettingsModalShellListeners()
Binds listeners for the settings modal shell (close button, background click).
- Source:
bindSettingsNavigationListeners()
Binds listeners for settings modal navigation (sidebar, provider tabs, log tabs).
- Source:
bindStorageListeners()
Wires up Storage section listeners (Refresh button, tiny-key toggle).
- Source:
blobToWebP(blob, qualityopt) → {Promise.<(Blob|null)>}
Converts a Blob to WebP format.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
blob |
Blob | The source image blob. |
||
quality |
number |
<optional> |
0.85 | WebP quality (0 to 1). |
- Source:
Returns:
WebP blob or null if failed.
- Type
- Promise.<(Blob|null)>
buildBulkItemRow(item, isPinned) → {HTMLTableRowElement}
Builds a table row element for a single inventory item in the bulk edit table.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | The inventory item |
isPinned |
boolean | Whether the row is in the pinned section |
- Source:
Returns:
The constructed row
- Type
- HTMLTableRowElement
(async) buildImageExportZip(options) → {Promise.<JSZip>}
Builds a ZIP archive of all exported images.
Parameters:
| Name | Type | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Export options. Properties
|
- Source:
Returns:
The generated ZIP object.
- Type
- Promise.<JSZip>
buildItemFields(f) → {Object}
Builds the common field object shared by both add and edit paths.
Parameters:
| Name | Type | Description |
|---|---|---|
f |
Object | Parsed fields from parseItemFormFields() |
Returns:
Common item fields
- Type
- Object
buildNumistaSearchQuery(nameVal, metalVal) → {Object}
Builds a Numista search query, optionally rewriting via NumistaLookup patterns.
Parameters:
| Name | Type | Description |
|---|---|---|
nameVal |
string | Item name input value |
metalVal |
string | Metal composition value |
Returns:
- Type
- Object
buildSearchIndices(lookupTable) → {Object}
Build searchable indices with variants for all lookup data
Parameters:
| Name | Type | Description |
|---|---|---|
lookupTable |
LookupTable | Base lookup table data |
- Source:
Returns:
Enhanced lookup table with search indices
- Type
- Object
buildTagSection(uuid, numistaTags, onChangedopt) → {HTMLElement|null}
Build the tag display section for the view modal. Returns a DOM fragment with Numista tags (read-only) and custom tags (editable).
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
uuid |
string | Item UUID |
|
numistaTags |
Array.<string> | Numista API tags (may be empty) |
|
onChanged |
function |
<optional> |
Callback when tags change (for re-render) |
Returns:
Tag section element, or null if no tags and no add capability
- Type
- HTMLElement | null
buildViewContent(item, index) → {DocumentFragment}
Build the full view modal body as a DocumentFragment. Sections are built eagerly then appended in user-configured order.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Inventory item |
index |
number | Item index for edit button |
- Source:
Returns:
- Type
- DocumentFragment
cacheLookupTable(lookupTable)
Cache lookup table to localStorage
Parameters:
| Name | Type | Description |
|---|---|---|
lookupTable |
LookupTable | Lookup table to cache |
- Source:
calculateApiUsage(selectedMetals, historyDaysopt, batchSupportedopt) → {Object}
Calculates the expected API usage (call count) for a given sync operation. Accounts for batch support and historical data backfill.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
selectedMetals |
Array.<string> | Array of metal keys to fetch |
||
historyDays |
number |
<optional> |
0 | Number of days of history to include |
batchSupported |
boolean |
<optional> |
false | Whether the provider supports batch calls |
Returns:
Usage breakdown including calls, type, and potential savings
- Type
- Object
calculateLevenshteinDistance(str1, str2) → {number}
Calculate Levenshtein distance between two strings
Parameters:
| Name | Type | Description |
|---|---|---|
str1 |
string | First string |
str2 |
string | Second string |
- Source:
Returns:
Edit distance
- Type
- number
calculateRetailPrice(item, currentSpot) → {Object}
Calculates qty-adjusted retail value using the portfolio hierarchy: Goldback denomination price → manual market value → melt value.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Inventory item |
currentSpot |
number | Current spot price for the item's metal |
Returns:
- Type
- Object
checkFileSize(file) → {boolean}
Checks if a file exceeds the local upload size limit
Parameters:
| Name | Type | Description |
|---|---|---|
file |
File | File to validate |
Returns:
True if file is within allowed size
- Type
- boolean
(async) checkRemoteVersion()
Checks for a newer version from the remote version.json endpoint (STACK-67) Skips fetch on file:// protocol (static badge still shown). Caches result for 24 hours.
- Source:
checkVersionChange()
Compares stored version with current and shows changelog modal if needed
- Source:
cleanOrphanedItemPriceHistory() → {number}
Removes history for UUIDs not present in the current inventory. Not called automatically — available for storage optimization.
- Source:
Returns:
Number of orphaned UUIDs removed
- Type
- number
cleanSearchTerm(term) → {string}
Strips search-operator characters from a search term for use in external URLs. Removes quotes, parentheses, and backslashes that act as search operators on eBay.
Parameters:
| Name | Type | Description |
|---|---|---|
term |
string | Raw search term (may contain user-entered punctuation) |
Returns:
Cleaned term safe for external search queries
- Type
- string
cleanString(str) → {string}
Cleans a string by stripping HTML tags and control characters while preserving punctuation. Normalizes whitespace and removes diacritics.
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string | Input string |
Returns:
Cleaned string
- Type
- string
cleanupStorage()
Removes unknown localStorage keys to maintain a clean storage state
Iterates over all localStorage entries and deletes any keys not present in ALLOWED_STORAGE_KEYS.
(async) clearAllCachedData()
Clears all cached images and metadata after confirmation.
- Source:
clearAllFilters()
Clears all active filters and resets search input and pagination.
- Source:
clearApiCache()
Clears only the API cache, keeping the configuration
clearApiConfig()
Clears Metals API configuration
clearApiHistory(silentopt)
Clears all stored spot price history from localStorage and re-renders UI.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
silent |
boolean |
<optional> |
false | If true, suppresses reopening the history modal |
clearApiKey(provider)
Removes the stored API key for a given provider from configuration. Also handles fallback to other available providers if necessary.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
clearCatalogHistory()
Clears all catalog API history after user confirmation.
- Source:
clearChangeLog()
Clears all change log entries after confirmation
- Source:
clearItemPriceHistory()
Clears all item price history after user confirmation.
- Source:
clearLookupCache()
Clear cached lookup table
- Source:
clearSpotHistory()
Clears all spot price history after user confirmation.
clearUploadState()
Clear the pending upload state and previews for both sides.
closeCurrencyDropdown()
Closes the currency dropdown and removes the outside-click listener.
- Source:
closeCurrencyDropdownOnOutside()
Click-outside handler for the currency dropdown.
- Source:
closeDetailsModal()
Closes the details modal and cleans up charts
- Source:
closeModalById(id)
Globally close a modal by id and clear body overflow safely.
Parameters:
| Name | Type | Description |
|---|---|---|
id |
string |
closeNumistaResultsModal()
Close Numista results modal and clean up state
- Source:
closePcgsFieldPicker()
Close the PCGS field picker modal.
- Source:
closeSpotLookupModal()
Closes the spot lookup modal.
- Source:
closeVaultModal()
Close the vault modal and reset state.
closeViewModal()
Close the view modal and clean up resources.
- Source:
coerceFieldValue(fieldId, value) → {*}
Coerces a bulk edit field value to the correct type based on field ID.
Parameters:
| Name | Type | Description |
|---|---|---|
fieldId |
string | The field identifier |
value |
string | The raw string value from the input |
- Source:
Returns:
The coerced value
- Type
- *
collectVaultData(scopeopt) → {object|null}
Collect localStorage data for vault export.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
scope |
string |
<optional> |
'full' | 'full' collects all ALLOWED_STORAGE_KEYS; 'sync' collects only SYNC_SCOPE_KEYS (inventory + display prefs, no API keys or tokens) |
Returns:
Payload object or null if empty
- Type
- object | null
commitItemToInventory(f, isEditing, editIdx)
Commits a parsed item to inventory (add or edit mode).
Parameters:
| Name | Type | Description |
|---|---|---|
f |
Object | Parsed fields from parseItemFormFields() |
isEditing |
boolean | Whether in edit mode |
editIdx |
number | null | Index being edited (null for add) |
compareVersions(a, b) → {number}
Compares two BRANCH.RELEASE.PATCH version strings
Parameters:
| Name | Type | Description |
|---|---|---|
a |
string | First version |
b |
string | Second version |
- Source:
Returns:
Negative if a < b, 0 if equal, positive if a > b
- Type
- number
computeGoldbackEstimatedRate(goldSpot) → {number}
Computes the estimated 1 Goldback exchange rate from gold spot price. Formula: 2 × (goldSpot / 1000) × modifier
Parameters:
| Name | Type | Description |
|---|---|---|
goldSpot |
number | Current gold spot price per troy oz |
- Source:
Returns:
Estimated 1 Goldback rate in USD
- Type
- number
computeItemValuation(item, currentSpot) → {Object}
Computes normalized valuation values for an inventory item. Centralizes purchase, melt, retail, and gain/loss calculations.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Inventory item |
currentSpot |
number | Current spot price for the item's metal |
Returns:
- Type
- Object
computeMeltValue(item, spot) → {number}
Computes the melt value for an inventory item. Centralises the formula: weight × qty × spot × purity.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Inventory item (needs weight, qty, purity) |
spot |
number | Current spot price for the item's metal |
Returns:
Qty-adjusted melt value
- Type
- number
convertToUsd(amount, currencyopt) → {number}
Converts amount from specified currency to USD using static rates
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
amount |
number | Monetary amount |
||
currency |
string |
<optional> |
"USD" | Currency code of amount |
Returns:
Amount converted to USD
- Type
- number
createBackupData() → {Object}
Exports backup data including Metals API configuration
Returns:
Complete backup data object
- Type
- Object
(async) createBackupZip() → {void}
Creates a comprehensive backup ZIP file containing all application data
This function generates a complete backup archive including:
- Current inventory data in JSON format
- All export formats (CSV, HTML)
- Application settings and configuration
- Spot price history
- README file explaining backup contents
The backup is packaged as a ZIP file for easy storage and portability. All data is exported in multiple formats to ensure compatibility and provide redundancy for data recovery scenarios.
- Source:
Returns:
Downloads a ZIP file containing complete backup
- Type
- void
Example
// Called to generate a complete backup archive
await createBackupZip();
createBreakdownElements(breakdown) → {DocumentFragment}
Creates breakdown DOM elements for display CHANGED from renderBreakdownHTML to use DOM methods instead of innerHTML
Parameters:
| Name | Type | Description |
|---|---|---|
breakdown |
Object | Breakdown data object |
- Source:
Returns:
DOM fragment containing the breakdown elements
- Type
- DocumentFragment
createDummyElement() → {Object}
Helper function to create dummy DOM elements to prevent null reference errors
Returns:
A dummy element object with basic properties
- Type
- Object
createEmptyLookupTable() → {LookupTable}
Create an empty lookup table structure with pre-built data
- Source:
Returns:
Empty lookup table with pre-built seed data
- Type
- LookupTable
createFieldInput(field) → {HTMLElement}
Creates the appropriate input element for a bulk edit field definition.
Parameters:
| Name | Type | Description |
|---|---|---|
field |
Object | Field definition from BULK_EDITABLE_FIELDS |
- Source:
Returns:
The input/select/textarea element
- Type
- HTMLElement
createPieChart(canvas, data, title) → {Chart}
Creates a pie chart with the given data
Parameters:
| Name | Type | Description |
|---|---|---|
canvas |
HTMLCanvasElement | Canvas element to render chart on |
data |
Object | Chart data with labels and values |
title |
string | Chart title |
Returns:
Chart.js instance
- Type
- Chart
createStorageItemModal()
Creates modal HTML for detailed item view
createThumbEl(src, alt) → {HTMLElement}
Create a thumbnail element (img or placeholder) for a given blob URL.
Parameters:
| Name | Type | Description |
|---|---|---|
src |
string | null | Object URL or null |
alt |
string | Alt text |
- Source:
Returns:
- Type
- HTMLElement
currentMonthKey() → {string}
Returns current month key in YYYY-MM format
Returns:
Current month identifier
- Type
- string
cycleSpotTrend()
Cycles through trend period presets, persists the selection, and applies it.
- Source:
cycleSpotTrend()
Cycles through trend period presets, persists the selection, and applies it.
- Source:
dataToPolyline(data, w, h, padYopt) → {string}
Converts an array of numeric values to SVG polyline coordinate string.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
data |
Array.<number> | Data points |
||
w |
number | SVG viewBox width |
||
h |
number | SVG viewBox height |
||
padY |
number |
<optional> |
4 | Vertical padding |
- Source:
Returns:
Space-separated "x,y" pairs
- Type
- string
dataToPolyline(data, w, h, padYopt) → {string}
Converts an array of numeric values to SVG polyline coordinate string.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
data |
Array.<number> | Data points |
||
w |
number | SVG viewBox width |
||
h |
number | SVG viewBox height |
||
padY |
number |
<optional> |
4 | Vertical padding |
- Source:
Returns:
Space-separated "x,y" pairs
- Type
- string
dataUriToBlob(dataUri) → {Blob}
Converts a data URI string to a Blob.
Parameters:
| Name | Type | Description |
|---|---|---|
dataUri |
string | Full data URI (e.g. "data:image/webp;base64,...") |
- Source:
Returns:
- Type
- Blob
debounce(func, wait) → {function}
Creates a debounced function that delays invoking func until after wait
milliseconds have elapsed since the last time the debounced function was
invoked. The debounced function comes with a cancel method to cancel
delayed func invocations and a flush method to immediately invoke them.
Parameters:
| Name | Type | Description |
|---|---|---|
func |
function | The function to debounce. |
wait |
number | The number of milliseconds to delay. |
Returns:
Returns the new debounced function.
- Type
- function
debugError(…args) → {void}
Logs an error debug entry.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
* |
<repeatable> |
- Source:
Returns:
- Type
- void
debugLog(…args) → {void}
Logs an informational debug entry.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
* |
<repeatable> |
- Source:
Returns:
- Type
- void
debugLog(…args)
Logs messages to console when DEBUG flag is enabled
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any |
<repeatable> |
Values to log when debugging |
debugWarn(…args) → {void}
Logs a warning debug entry.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
* |
<repeatable> |
- Source:
Returns:
- Type
- void
(async) deleteItem(idx)
Deletes inventory item at specified index after confirmation
Parameters:
| Name | Type | Description |
|---|---|---|
idx |
number | Index of item to delete |
- Source:
deleteItemPriceEntry(uuid, timestamp)
Deletes a single price history entry by UUID and timestamp. Logs the deletion to the change log for undo/redo support.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid |
string | Item UUID |
timestamp |
number | Entry timestamp to delete |
- Source:
deleteItemTags(uuid)
Delete all tags for an item (called on item deletion).
Parameters:
| Name | Type | Description |
|---|---|---|
uuid |
string | Item UUID |
deleteTagGlobal(tag) → {number}
Delete a tag from all items.
Parameters:
| Name | Type | Description |
|---|---|---|
tag |
string | Tag name to remove globally |
Returns:
Number of items affected
- Type
- number
deriveSearchLabel(patterns) → {string}
Derives a default display label for a set of search patterns.
Parameters:
| Name | Type | Description |
|---|---|---|
patterns |
Array.<string> | The patterns to derive a label from |
Returns:
The derived display label
- Type
- string
destroyCharts()
Destroys existing chart instances to prevent memory leaks
destroySparklines()
Destroys all sparkline Chart.js instances (cleanup)
detectCurrency(str) → {string|null}
Detects currency code from a value string containing symbols or codes
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string | Value containing currency information |
Returns:
Detected currency code or null if not found
- Type
- string | null
disableCloudSync()
Disable auto-sync: persist the disabled flag, stop the poller, and update UI.
- Source:
dismissAllAutocompletes()
Dismiss all open autocomplete dropdowns (e.g. when the modal closes).
- Source:
dismissNotesModal()
Closes the notes modal and resets the notes index.
(async) downloadCompleteBackup()
Downloads complete backup files including inventory and Metals API configuration
downloadFile(filename, content, mimeType)
Downloads a file with the specified content and filename
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
filename |
string | Name of the file to download |
|
content |
string | Content of the file |
|
mimeType |
string | text/plain | MIME type of the file (default: text/plain) |
downloadStorageReport()
Shows storage report options with view and download actions
duplicateItem(idx)
Duplicates an inventory item by opening the add modal pre-filled with the source item's fields. Date preserves the original purchase date, qty resets to 1.
Parameters:
| Name | Type | Description |
|---|---|---|
idx |
number | Index of item to duplicate |
- Source:
editItem(idx)
Prepares and displays edit modal for specified inventory item
Parameters:
| Name | Type | Description |
|---|---|---|
idx |
number | Index of item to edit |
- Source:
(async) enableCloudSync(provideropt)
Enable auto-sync: do an initial push, then start the poller.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
provider |
string |
<optional> |
'dropbox' |
- Source:
escapeAttribute(text) → {string}
Escapes special characters for safe inclusion in HTML attributes
Parameters:
| Name | Type | Description |
|---|---|---|
text |
string | Text to escape |
- Source:
Returns:
Escaped text safe for attribute usage
- Type
- string
escapeHtml(str) → {string}
Escape HTML special characters to prevent XSS when interpolating into innerHTML.
Parameters:
| Name | Type | Description |
|---|---|---|
str |
* | Value to escape (coerced to string) |
Returns:
Escaped HTML-safe string
- Type
- string
escapeHtmlCatalog(str) → {string}
Escape HTML for safe insertion into innerHTML
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string | Raw string |
- Source:
Returns:
Escaped string
- Type
- string
escapeHtmlPcgs()
Escape HTML for safe injection into innerHTML
- Source:
exportCsv()
Exports current inventory to CSV format
- Source:
(async) exportEncryptedBackup(password) → {Promise.<void>}
Export an encrypted vault backup.
Parameters:
| Name | Type | Description |
|---|---|---|
password |
string |
Returns:
- Type
- Promise.<void>
exportGoldbackHistory()
Exports Goldback price history as CSV.
- Source:
exportJson()
Exports current inventory to JSON format
- Source:
exportNumistaCsv()
Exports inventory using Numista-compatible column layout
- Source:
exportPdf()
Exports current inventory to PDF format
- Source:
exportSpotHistory()
Exports all spot history data as a CSV file
extractUniqueValues(inventory, field, optionsopt) → {Array.<string>}
Extract unique values from inventory for a specific field
Parameters:
| Name | Type | Attributes | Default | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
inventory |
Array | Current inventory data |
|||||||||||||||||
field |
string | Field name to extract |
|||||||||||||||||
options |
Object |
<optional> |
{} | Extraction options Properties
|
- Source:
Returns:
Array of unique values
- Type
- Array.<string>
(async) fetchBatchSpotPrices(provider, apiKey, selectedMetals, historyDaysopt, historyTimesopt) → {Promise.<Object.<string, number>>}
Executes a batch API request to retrieve spot prices for multiple metals simultaneously. Supports historical data range requests if provided by the underlying API.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
provider |
string | The unique key of the API provider |
||
apiKey |
string | The API key for the provider |
||
selectedMetals |
Array.<string> | Array of metal keys to fetch |
||
historyDays |
number |
<optional> |
0 | Number of days of history to include |
historyTimes |
Array.<string> |
<optional> |
[] | Array of HH:MM times for granular history |
Returns:
Map of metal keys to spot prices
- Type
- Promise.<Object.<string, number>>
(async) fetchExchangeRates() → {Promise.<boolean>}
Fetches latest exchange rates from the free API and caches them (STACK-50). Non-blocking — if fetch fails, existing cached/fallback rates are used.
Returns:
Whether the fetch succeeded
- Type
- Promise.<boolean>
(async) fetchHistoryBatched(provider, apiKey, selectedMetals, totalDays) → {Promise.<{totalEntries: number, callsMade: number}>}
Orchestrates a series of batched API requests to backfill historical spot price data. Automates the chunking process and parses results for multiple metals.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
apiKey |
string | The API key for the provider |
selectedMetals |
Array.<string> | Array of metal keys to fetch |
totalDays |
number | Total number of days of history to pull |
Returns:
Summary of the batch operation
- Type
- Promise.<{totalEntries: number, callsMade: number}>
(async) fetchLatestPrices(provider, apiKey, selectedMetals) → {Promise.<Object.<string, number>>}
Fetches the most recent spot prices for selected metals using individual endpoints. Optimized for low-cost, real-time updates without full history backfill.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
apiKey |
string | The API key for the provider |
selectedMetals |
Array.<string> | Array of metal keys to fetch |
Returns:
Map of metal keys to spot prices
- Type
- Promise.<Object.<string, number>>
(async) fetchMetalPriceApiHourly(apiKey, selectedMetals, totalDays) → {Promise.<{totalEntries: number, callsMade: number}>}
Specialized history fetcher for MetalPriceAPI's hourly endpoint. Requests granular hourly data for a specific date range.
Parameters:
| Name | Type | Description |
|---|---|---|
apiKey |
string | The API key for MetalPriceAPI |
selectedMetals |
Array.<string> | Array of metal keys to fetch |
totalDays |
number | Number of days of history to pull |
Returns:
Summary of the operation
- Type
- Promise.<{totalEntries: number, callsMade: number}>
(async) fetchSpotForDate(metalName, dateStr) → {Promise.<Array>}
Fetches spot price from the API for a specific date and metal. Records fetched entries into local spotHistory for future lookups.
Parameters:
| Name | Type | Description |
|---|---|---|
metalName |
string | Metal name ('Silver', 'Gold', etc.) |
dateStr |
string | Target date in YYYY-MM-DD format |
- Source:
Returns:
Fetched entries with dayOffset
- Type
- Promise.<Array>
fetchSpotPrice()
Fetches and displays current spot prices from localStorage or defaults
(async) fetchSpotPricesFromApi(provider, apiKey) → {Promise.<Object.<string, number>>}
Standard interface for fetching spot prices from any supported API provider. Automatically chooses between individual latest endpoints or batch calls.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
apiKey |
string | The API key for the provider |
Returns:
Map of metal keys to spot prices
- Type
- Promise.<Object.<string, number>>
(async) fetchStaktrakrHourlyRange(hoursBack) → {Promise.<{newCount: number, fetchCount: number}>}
Fetches hourly spot data from StakTrakr for a configurable number of hours. Skips hours already present in spotHistory to avoid duplicates.
Parameters:
| Name | Type | Description |
|---|---|---|
hoursBack |
number | Number of hours to look back |
Returns:
Counts of new entries and successful fetches
- Type
- Promise.<{newCount: number, fetchCount: number}>
(async) fetchStaktrakrPrices()
Fetch spot prices from StakTrakr hourly JSON files. Walks back up to 6 hours from the current UTC hour to find data.
fetchYearFile(year) → {Promise.<Array>}
Fetches a single year file from data/spot-history-{year}.json. Three-tier loading: local fetch → local XHR → remote staktrakr.com. Caches the result (or empty array on failure) to avoid retries. Deduplicates concurrent fetches for the same year.
Parameters:
| Name | Type | Description |
|---|---|---|
year |
number | Year to fetch |
Returns:
Array of spot history entries
- Type
- Promise.<Array>
fillFormFromNumistaResult()
Fill form fields from the editable picker inputs. Reads values from the numistaFieldValue_* text inputs (user may have edited them).
- Source:
fillFormFromPcgsResult()
Apply checked fields from the PCGS picker to the item form. Reads values from the pcgsFieldValue_* text inputs (user may have edited them).
- Source:
filterInventory() → {Array.<Object>}
Filters inventory based on the current search query and active column filters. Handles advanced multi-term, phrase, and series-specific logic for coins and metals.
Returns:
Filtered inventory items matching the search query and filters
- Type
- Array.<Object>
Example
filterInventory();
filterInventoryAdvanced() → {Array.<InventoryItem>}
Enhanced filter inventory function that includes advanced filters.
Applies all active filters in activeFilters to the inventory.
- Source:
Returns:
Filtered inventory items
- Type
- Array.<InventoryItem>
filterItemPriceHistoryTable()
Reads the filter input value and re-renders the price history table.
- Source:
flattenGoldbackHistory()
Flattens goldbackPriceHistory into a row array for table rendering. Each entry: { denomination, label, price, timestamp }
- Source:
formatCurrency(value, currencyopt) → {string}
Formats a number as a currency string using the default currency
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
value |
number | string | Number to format |
||
currency |
string |
<optional> |
DEFAULT_CURRENCY | ISO currency code |
Returns:
Formatted currency string (e.g., "$1,234.56")
- Type
- string
formatDateOnly(date) → {string}
Formats a date for display (date only, no time) using the user's timezone preference.
Parameters:
| Name | Type | Description |
|---|---|---|
date |
Date | string | number | Date object, ISO string, or epoch ms |
Returns:
Formatted date string
- Type
- string
formatDisplayDate(dateStr) → {string}
Formats a date string into compact MM/DD/YY format
Parameters:
| Name | Type | Description |
|---|---|---|
dateStr |
string | Date in YYYY-MM-DD format |
Returns:
Formatted date (e.g., "1/1/69")
- Type
- string
formatFileSize(bytes) → {string}
Format file size in human-readable form.
Parameters:
| Name | Type | Description |
|---|---|---|
bytes |
number |
Returns:
- Type
- string
formatLossProfit(value) → {string}
Formats a profit/loss value with color coding
Parameters:
| Name | Type | Description |
|---|---|---|
value |
number | Profit/loss value |
Returns:
HTML string with appropriate color styling
- Type
- string
formatOffsetLabel(offset) → {string}
Formats a day offset into a human-readable badge label.
Parameters:
| Name | Type | Description |
|---|---|---|
offset |
number | Day offset from target date |
- Source:
Returns:
Label like "Exact", "+1d", "-2d"
- Type
- string
formatPurchaseLocation(loc) → {string}
Formats Purchase Location for table display, wrapping URLs in hyperlinks while preserving filter behavior.
Parameters:
| Name | Type | Description |
|---|---|---|
loc |
string | Purchase location value |
- Source:
Returns:
HTML string for table cell
- Type
- string
formatStorageLocation(loc) → {string}
Formats Storage Location for table display with truncation
Parameters:
| Name | Type | Description |
|---|---|---|
loc |
string | Storage location value |
- Source:
Returns:
HTML string for table cell
- Type
- string
formatTimeOnly(date) → {string}
Formats a date for display (time only, no date) using the user's timezone preference.
Parameters:
| Name | Type | Description |
|---|---|---|
date |
Date | string | number | Date object, ISO string, or epoch ms |
Returns:
Formatted time string
- Type
- string
formatTimestamp(date, optionsopt) → {string}
Formats a date/timestamp for display using the user's timezone preference (STACK-63). When timezone is "auto" (default), uses the browser's local timezone — identical to previous behavior.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
date |
Date | string | number | Date object, ISO string, or epoch ms |
|
options |
Intl.DateTimeFormatOptions |
<optional> |
Override individual format options |
Returns:
Formatted date+time string
- Type
- string
formatWeight(ozt, weightUnitopt) → {string}
Formats a weight in troy ounces to either grams or ounces. If weightUnit is 'gb', displays as Goldback denomination (no gram auto-conversion).
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
ozt |
number | Weight in troy ounces (or Goldback denomination if weightUnit='gb') |
|
weightUnit |
string |
<optional> |
Optional weight unit: 'oz', 'g', or 'gb' |
Returns:
Formatted weight string with unit
- Type
- string
fuzzyMatch(query, target, optionsopt) → {number}
Calculates fuzzy similarity between query and target strings
Parameters:
| Name | Type | Attributes | Default | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
query |
string | User search input |
|||||||||||||||||
target |
string | Inventory item name to match against |
|||||||||||||||||
options |
Object |
<optional> |
{} | Configuration options Properties
|
- Source:
Returns:
Similarity score between 0 and 1
- Type
- number
Example
fuzzyMatch("Ame", "American Silver Eagle") // returns ~0.7
fuzzyMatch("Eagle Amer", "American Silver Eagle") // returns ~0.8
fuzzySearch(query, targets, optionsopt) → {Array.<{text: string, score: number}>}
Search through an array of targets and return fuzzy matches
Parameters:
| Name | Type | Attributes | Default | Description | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
query |
string | Search query |
||||||||||||||||||||||
targets |
Array.<string> | Array of strings to search |
||||||||||||||||||||||
options |
Object |
<optional> |
{} | Configuration options Properties
|
- Source:
Returns:
Array of results
- Type
- Array.<{text: string, score: number}>
generateBackupHtml(sortedInventory, timeFormatted) → {string}
Generates HTML content for backup export
Parameters:
| Name | Type | Description |
|---|---|---|
sortedInventory |
Array | Sorted inventory data |
timeFormatted |
string | Formatted timestamp |
- Source:
Returns:
HTML content
- Type
- string
generateCategorySummary(inventory) → {Object}
Generates category summary from filtered inventory. Returns summary of metals, types, and item counts above minimum threshold.
Parameters:
| Name | Type | Description |
|---|---|---|
inventory |
Array.<Object> | The filtered inventory |
- Source:
Returns:
Summary of metals, types, and counts
- Type
- Object
generateColors(count) → {Array}
Generates a color palette for pie chart segments
Parameters:
| Name | Type | Description |
|---|---|---|
count |
number | Number of colors needed |
Returns:
Array of color strings
- Type
- Array
generateItemDataTable()
Generates data table for storage item
generateLookupTable(inventoryopt, optionsopt) → {LookupTable}
Generate lookup table from current inventory data with pre-built seed data
Parameters:
| Name | Type | Attributes | Default | Description | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
inventory |
Array |
<optional> |
Inventory data (defaults to global inventory) |
|||||||||||||||||||||
options |
Object |
<optional> |
{} | Generation options Properties
|
- Source:
Returns:
Generated lookup table
- Type
- LookupTable
generateNGrams(str, nopt, caseSensitiveopt) → {Array.<string>}
Generate character n-grams from a string
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
str |
string | Input string |
||
n |
number |
<optional> |
2 | Length of n-gram |
caseSensitive |
boolean |
<optional> |
false | Preserve case if true |
- Source:
Returns:
Array of n-grams
- Type
- Array.<string>
generateReadmeContent(timeFormatted) → {string}
Generates README content for backup archive
Parameters:
| Name | Type | Description |
|---|---|---|
timeFormatted |
string | Formatted timestamp |
- Source:
Returns:
README content
- Type
- string
generateSparklineSVG(item, w, h, optsopt) → {string}
Generates a "since purchased" 3-line sparkline SVG matching the view modal pattern. Red dashed = purchase price (flat), Green = melt value over time, Blue = retail/market value. Uses real spot history with timestamps when available.
Parameters:
| Name | Type | Attributes | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
item |
object | Inventory item |
||||||||||||||||
w |
number | SVG viewBox width |
||||||||||||||||
h |
number | SVG viewBox height |
||||||||||||||||
opts |
object |
<optional> |
Options Properties
|
- Source:
Returns:
SVG markup string
- Type
- string
generateSparklineSVG(item, w, h, optsopt) → {string}
Generates a "since purchased" 3-line sparkline SVG matching the view modal pattern. Red dashed = purchase price (flat), Green = melt value over time, Blue = retail/market value. Uses real spot history with timestamps when available.
Parameters:
| Name | Type | Attributes | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
item |
object | Inventory item |
||||||||||||||||
w |
number | SVG viewBox width |
||||||||||||||||
h |
number | SVG viewBox height |
||||||||||||||||
opts |
object |
<optional> |
Options Properties
|
- Source:
Returns:
SVG markup string
- Type
- string
generateStorageReport()
Generates a storage utilization report
generateStorageReportHTML()
Generates comprehensive HTML storage report with theme support
(async) generateStorageReportTar()
Generates a comprehensive ZIP file with storage report and data
generateUUID() → {string}
Generates a UUID v4 string for stable item identification. Uses crypto.randomUUID() where available, with a Math.random() RFC 4122 v4 fallback for environments (e.g. file:// protocol) that lack crypto.randomUUID.
Returns:
A UUID v4 string (e.g. "550e8400-e29b-41d4-a716-446655440000")
- Type
- string
generateVariations(term) → {Array.<string>}
Generate searchable variations for a given term Includes common abbreviations, partial matches, and variations
Parameters:
| Name | Type | Description |
|---|---|---|
term |
string | Original term |
- Source:
Returns:
Array of searchable variations
- Type
- Array.<string>
get24hChange(metalName) → {Object}
Computes 24h % change using the user's selected comparison mode (STACK-92). Modes: close-close (default), open-open, open-close. Graceful degradation: when only 1 entry/day exists, first === last so all modes match.
Parameters:
| Name | Type | Description |
|---|---|---|
metalName |
string | 'Silver', 'Gold', etc. |
Returns:
- Type
- Object
getAllMetalsBreakdownData() → {Object}
Calculates breakdown data across all metals — by metal and by location Used when clicking the "All Metals" summary card
- Source:
Returns:
Breakdown data organized by metal and location
- Type
- Object
getAllUniqueTags() → {Array.<string>}
Get a sorted list of all unique tags across the entire inventory.
Returns:
Sorted array of unique tag strings
- Type
- Array.<string>
getApiAvailability(dateStr) → {Object}
Checks whether an API lookup is possible for a given date and returns availability info.
Parameters:
| Name | Type | Description |
|---|---|---|
dateStr |
string | Target date in YYYY-MM-DD format |
- Source:
Returns:
- Type
- Object
getAppTitle(baseTitleopt) → {string}
Returns full application title with version when no branding is configured
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
baseTitle |
string |
<optional> |
'StakTrakr' | Base application title |
Returns:
Full title with version or branding name
- Type
- string
getBreakdownData(metal) → {Object}
Calculates breakdown data for specified metal by type and location RENAMED from calculateBreakdownData to avoid 403 errors
Parameters:
| Name | Type | Description |
|---|---|---|
metal |
string | Metal type to calculate ('Silver', 'Gold', 'Platinum', or 'Palladium') |
- Source:
Returns:
Breakdown data organized by type and location
- Type
- Object
getCacheDurationMs() → {number}
Gets cache duration in milliseconds
Returns:
Cache duration
- Type
- number
getCachedLookupTable() → {LookupTable|null}
Get cached lookup table if valid
- Source:
Returns:
Cached lookup table or null if invalid/expired
- Type
- LookupTable | null
getCardStyle() → {'A'|'B'|'C'|'D'}
Returns the active card style from localStorage.
- Source:
Returns:
- Type
- 'A' | 'B' | 'C' | 'D'
getCardStyle() → {'A'|'B'|'C'|'D'}
Returns the active card style from localStorage.
- Source:
Returns:
- Type
- 'A' | 'B' | 'C' | 'D'
getChartBackgroundColor() → {string}
Gets appropriate background color for charts based on current theme
Returns:
Background color
- Type
- string
getChartColor()
Gets chart color for given index
getChartTextColor() → {string}
Gets appropriate text color for charts based on current theme
Returns:
Text color
- Type
- string
getChipColors(field, value, index) → {Object}
Returns chip color and text color for a given field/value combination.
Parameters:
| Name | Type | Description |
|---|---|---|
field |
string | Chip field type |
value |
string | Chip value |
index |
number | Chip index for fallback color cycling |
- Source:
Returns:
Background and optional text color
- Type
- Object
getCompositionFirstWords(composition) → {string}
Extracts up to the first two words from a composition string while removing parenthetical content and numeric values.
Parameters:
| Name | Type | Description |
|---|---|---|
composition |
string | Raw composition description |
Returns:
First two cleaned words joined by a space
- Type
- string
getContrastColor(bg) → {string}
Returns black or white contrast color for a given background. Supports hex strings and CSS variables.
Parameters:
| Name | Type | Description |
|---|---|---|
bg |
string | Background color in hex or CSS var format |
Returns:
'#000000' or '#ffffff'
- Type
- string
getCryptoBackend() → {'native'|'forge'|null}
Detect available crypto backend.
Returns:
- Type
- 'native' | 'forge' | null
getCurrencySymbol(currencyopt) → {string}
Extracts the currency symbol from Intl.NumberFormat for the given currency code (STACK-50)
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
currency |
string |
<optional> |
ISO 4217 code; defaults to displayCurrency |
Returns:
Currency symbol (e.g. "$", "€", "£", "₽")
- Type
- string
getDateChunks(totalDays, maxPerRequest) → {Array.<{start: Date, end: Date}>}
Splits a requested historical time range into smaller date chunks. Ensures each request stays within the provider's maximum allowed days per call.
Parameters:
| Name | Type | Description |
|---|---|---|
totalDays |
number | Total number of days to fetch |
maxPerRequest |
number | Maximum days allowed per API request |
Returns:
Array of date range objects, newest first
- Type
- Array.<{start: Date, end: Date}>
getDebugHistory() → {Array.<string>}
Returns a copy of debug log history entries.
- Source:
Returns:
- Type
- Array.<string>
getDefaultSyncMode(provider) → {"always"|"backup"}
Determines the default synchronization behavior for a provider. Higher priority providers default to 'always', others to 'backup'.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
Returns:
Recommended sync mode
- Type
- "always" | "backup"
getDisplayComposition(composition) → {string}
Determines display-friendly composition text.
Returns "Alloy" when the first word isn't one of the primary metals (Gold, Silver, Platinum, Palladium).
Parameters:
| Name | Type | Description |
|---|---|---|
composition |
string | Raw composition description |
Returns:
Display text for the composition
- Type
- string
getEmbeddedRoadmap() → {string}
Provides embedded roadmap data as fallback when file fetch fails
Returns:
HTML string of development roadmap
- Type
- string
getEmbeddedSeedData() → {Array.<{spot:number, metal:string, source:string, provider:string, timestamp:string}>}
Embedded seed data fallback for file:// protocol where fetch() cannot load local JSON files. Auto-generated — do not edit by hand.
- Source:
Returns:
- Type
- Array.<{spot:number, metal:string, source:string, provider:string, timestamp:string}>
getEmbeddedWhatsNew() → {string}
Provides embedded "What's New" data as fallback when file fetch fails
Returns:
HTML string of recent announcements
- Type
- string
getExchangeRate(targetCurrencyopt) → {number}
Returns the exchange rate for a target currency (STACK-50). 1 USD = getExchangeRate(code) × target currency. Falls back: cached exchangeRates → FALLBACK_EXCHANGE_RATES → 1.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
targetCurrency |
string |
<optional> |
ISO 4217 code; defaults to displayCurrency |
Returns:
Exchange rate multiplier
- Type
- number
getExistingElement(id) → {HTMLElement|null}
Helper to safely get an element by ID, returning null if not found.
Parameters:
| Name | Type | Description |
|---|---|---|
id |
string | The DOM element ID |
- Source:
Returns:
The element or null
- Type
- HTMLElement | null
getFilterChipCategoryConfig() → {Array.<{id: string, label: string, enabled: boolean}>}
Loads the filter chip category config from localStorage, merging with defaults so new categories added in future versions appear automatically.
- Source:
Returns:
- Type
- Array.<{id: string, label: string, enabled: boolean}>
getFooterDomain() → {string}
Determines active domain for footer copyright
Returns:
Domain name to display
- Type
- string
getGoldbackDenominationPrice(weightGb) → {number|null}
Returns the denomination price for a given Goldback weight, or null.
Parameters:
| Name | Type | Description |
|---|---|---|
weightGb |
number | Weight in Goldback denomination units (e.g. 1, 5, 10) |
- Source:
Returns:
Per-unit denomination price, or null if not set
- Type
- number | null
getGoldbackRetailPrice(item) → {number|null}
Returns the per-unit Goldback denomination retail price, or null. Checks: weightUnit is 'gb', Goldback pricing is enabled, and a price exists.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Inventory item |
Returns:
Per-unit denomination price, or null
- Type
- number | null
(async) getHistoricalSparklineData(metalName, days) → {Promise.<{labels: Array.<string>, data: Array.<number>}>}
Fetches needed year files, merges with live spotHistory, filters to metal + range, deduplicates by day (live data wins over seed).
Parameters:
| Name | Type | Description |
|---|---|---|
metalName |
string | Metal name ('Silver', 'Gold', etc.) |
days |
number | Number of days to look back |
Returns:
Arrays for Chart.js
- Type
- Promise.<{labels: Array.<string>, data: Array.<number>}>
getInlineChipConfig() → {Array.<{id: string, label: string, enabled: boolean}>}
Loads the inline chip config from localStorage, merging with defaults so new chip types added in future versions appear automatically.
- Source:
Returns:
- Type
- Array.<{id: string, label: string, enabled: boolean}>
getItemTags(uuid) → {Array.<string>}
Get all tags for an item.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid |
string | Item UUID |
Returns:
Array of tag strings (never null)
- Type
- Array.<string>
getLastProviderSyncTime(provider) → {number|null}
Scans the spot history log to find the most recent successful sync for a provider.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
Returns:
Millisecond timestamp of last sync, or null
- Type
- number | null
getLastUpdateTime(metalName, modeopt) → {string}
Builds two-line HTML showing source and last cache refresh or API sync info for a metal
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
metalName |
string | Metal name ('Silver', 'Gold', 'Platinum', 'Palladium') |
||
mode |
string |
<optional> |
"cache" | "cache" or "api" to select timestamp |
Returns:
HTML string with source line and time line
- Type
- string
getLayoutSectionConfig()
Loads the layout section config, with migration from old layoutVisibility format.
- Source:
getLbmaReferenceYears() → {Array.<number>}
Returns the seed years configured for bundled LBMA reference data. Falls back to current year when the seed config is unavailable.
Returns:
Sorted list of years
- Type
- Array.<number>
getLookupStats() → {Object}
Get current lookup table stats
- Source:
Returns:
Lookup table statistics
- Type
- Object
getMetalColor(metalKey) → {string}
Returns the theme-aware color for a metal sparkline by reading the CSS custom property (--silver, --gold, etc.) from the active theme. Falls back to hardcoded defaults if getComputedStyle is unavailable.
Parameters:
| Name | Type | Description |
|---|---|---|
metalKey |
string | 'silver', 'gold', 'platinum', 'palladium' |
Returns:
CSS color string
- Type
- string
getMetalOrderConfig() → {Array.<{id:string, label:string, enabled:boolean}>}
Returns the current metal order config, merging stored data with defaults. New metals added to defaults will be appended to existing stored configs.
- Source:
Returns:
- Type
- Array.<{id:string, label:string, enabled:boolean}>
getNumistaViewFieldConfig() → {Object.<string, boolean>}
Load Numista view field config from localStorage, merged with defaults.
- Source:
Returns:
- Type
- Object.<string, boolean>
getPasswordStrength(password) → {Object}
Evaluate password strength.
Parameters:
| Name | Type | Description |
|---|---|---|
password |
string |
Returns:
- Type
- Object
getPopularNumistaItems() → {Array.<{id: string, name: string, metal: string}>}
Curated list of popular bullion items for quick-pick in the no-results modal. Focused on items silver/gold stackers commonly own.
- Source:
Returns:
- Type
- Array.<{id: string, name: string, metal: string}>
getProviderOrder() → {Array.<string>}
Returns the effective priority order for API providers. Merges user-defined priority with legacy order and hardcoded defaults.
Returns:
Ordered list of provider keys
- Type
- Array.<string>
getRequiredYears(days) → {Array.<number>}
Calculates which year files are needed for a given lookback period.
Parameters:
| Name | Type | Description |
|---|---|---|
days |
number | Number of days to look back |
Returns:
Array of year numbers to fetch
- Type
- Array.<number>
getSparklineData(metalName, days, intradayopt) → {Object}
Extracts sparkline data from spotHistory for a given metal and date range
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
metalName |
string | Metal name ('Silver', 'Gold', etc.) |
||
days |
number | Number of days to look back |
||
intraday |
boolean |
<optional> |
false | If true, keep all entries (no per-day dedup) and use midnight cutoff instead of current-time offset (STACK-66) |
Returns:
Arrays for Chart.js
- Type
- Object
getSpotHistoryForMetal(metal, pointsopt, withTimestampsopt) → {Array.<number>|Array.<{ts:number, spot:number}>|null}
Returns recent spot prices for a given metal from spotHistory. Used by card-view sparklines (STAK-118).
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
metal |
string | Metal key ('silver', 'gold', etc.) |
||
points |
number |
<optional> |
30 | Number of data points to return |
withTimestamps |
boolean |
<optional> |
false | If true, returns {ts, spot} objects |
Returns:
Array of spot prices, or null if insufficient data
- Type
- Array.<number> | Array.<{ts:number, spot:number}> | null
getStorageItemDescription()
Gets description for storage items
getStorageItemDisplayName()
Gets display name for storage keys
getStorageReportCSS()
Gets enhanced CSS styles for the storage report with theme support
getStorageReportJS()
Gets enhanced JavaScript for the storage report with theme and chart support
getSyncDeviceId() → {string}
Get or create a stable per-device UUID, persisted in localStorage.
- Source:
Returns:
- Type
- string
getSyncPassword() → {Promise.<(string|null)>}
Get the session-cached sync password, or open the sync password modal. Returns a Promise that resolves with the password string, or null if cancelled.
- Source:
Returns:
- Type
- Promise.<(string|null)>
getTemplateVariables()
Template replacement functions for documentation Used by build process to replace {{TEMPLATE}} variables
- Source:
getUserFriendlyMessage(errorMessage) → {string}
Converts technical error messages to user-friendly ones
Parameters:
| Name | Type | Description |
|---|---|---|
errorMessage |
string | Technical error message |
Returns:
User-friendly error message
- Type
- string
getVersionString(prefixopt) → {string}
Returns formatted version string
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
prefix |
string |
<optional> |
"v" | Prefix to add before version |
- Source:
Returns:
Formatted version string (e.g., "v3.03.07b")
- Type
- string
getViewModalSectionConfig()
Loads the view modal section config from localStorage, merged with defaults.
- Source:
gramsToOzt(grams) → {number}
Converts grams to troy ounces
Parameters:
| Name | Type | Description |
|---|---|---|
grams |
number | Weight in grams |
Returns:
Weight in troy ounces
- Type
- number
handleError(error, context)
Handles errors with user-friendly messaging
Parameters:
| Name | Type | Description |
|---|---|---|
error |
Error | string | Error to handle |
context |
string | Context where error occurred |
(async) handleHistoryPull(provider)
UI entry point for initiating a historical data pull for a provider. Validates requirements, shows cost/quota confirmation, and executes pull.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
(async) handleImageDeletion(uuid) → {Promise.<void>}
Handle image deletion based on deletion flags. Supports partial deletion (one side only) or full deletion (both sides).
Parameters:
| Name | Type | Description |
|---|---|---|
uuid |
string | Item UUID |
Returns:
- Type
- Promise.<void>
handleProviderSave(provider)
Saves provider settings (key, cache timeout, history days) without testing or fetching
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | Provider key |
(async) handleProviderSync(provider) → {Promise.<void>}
Handles the UI-triggered synchronization of a single specific provider. Useful for per-provider settings cards and troubleshooting.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
Returns:
Resolves when the provider sync attempt completes
- Type
- Promise.<void>
(async) handleRemoteChange(remoteMeta)
Handle a detected remote change. If no local changes → show update-available modal, then pull on Accept. If both sides changed → show conflict modal.
Parameters:
| Name | Type | Description |
|---|---|---|
remoteMeta |
object | The parsed staktrakr-sync.json content |
- Source:
(async) handleSaveSearchPattern()
Handles the "Save Search" button click event. Prompts the user for a label and creates a new custom group.
(async) handleStaktrakrHistoryPull()
Handles user-initiated hourly history pull for STAKTRAKR. Reads days from dropdown, confirms, fetches, and updates UI.
(async) handleVaultAction()
Handle the vault modal action button (export or import).
hideAboutModal()
Hides the About modal
hideAckModal()
Hides the acknowledgment modal
hideApiHistoryModal()
Closes the API history modal.
hideApiModal()
Legacy hideApiModal — redirects to hideSettingsModal
hideApiProvidersModal()
Closes the API providers modal (legacy wrapper for hideSettingsModal).
hideCatalogHistoryModal()
Hides catalog history modal
- Source:
hideDebugModal() → {void}
Hides the debug modal and restores body scrolling.
- Source:
Returns:
- Type
- void
hideEmptyColumns()
Hides table columns that contain no data after filtering.
- Source:
hideFilesModal()
Legacy hideFilesModal — redirects to hideSettingsModal
hideGoldbackHistoryModal()
Hides the Goldback price history modal.
- Source:
hideManualInput(metal)
Hides manual price input for a specific metal
Parameters:
| Name | Type | Description |
|---|---|---|
metal |
string | Metal name (Silver, Gold, etc.) |
hideProviderInfo()
Hides provider information modal
hideSettingsModal()
Closes the Settings modal.
- Source:
importCsv(file, overrideopt)
Imports inventory data from CSV file with comprehensive validation and error handling
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
file |
File | CSV file selected by user through file input |
||
override |
boolean |
<optional> |
false | Replace existing inventory instead of merging |
- Source:
(async) importEncryptedBackup(fileBytes, password) → {Promise.<void>}
Import and decrypt a vault backup.
Parameters:
| Name | Type | Description |
|---|---|---|
fileBytes |
Uint8Array | |
password |
string |
Returns:
- Type
- Promise.<void>
importJson(file, overrideopt)
Imports inventory data from JSON file
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
file |
File | JSON file to import |
||
override |
boolean |
<optional> |
false | Replace existing inventory instead of merging |
- Source:
importNumistaCsv(file, overrideopt)
Imports inventory data from a Numista CSV export
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
file |
File | CSV file from Numista |
||
override |
boolean |
<optional> |
false | Replace existing inventory instead of merging |
- Source:
importSpotHistory(file)
Imports spot history data from a CSV or JSON file
Parameters:
| Name | Type | Description |
|---|---|---|
file |
File | File to import |
initCardSortBar()
Binds event listeners on the card sort bar (once). Also sets up the MutationObserver that keeps the bar visible in D (table) mode.
- Source:
initCardSortBar()
Binds event listeners on the card sort bar (once). Also sets up the MutationObserver that keeps the bar visible in D (table) mode.
- Source:
initCloudSync()
Initialize the cloud sync module. Creates the debounced push function and starts the poller if sync was enabled.
- Source:
initSpotHistoryButtons()
Wires up spot history export/import button event listeners. Called during populateApiSection() or init.
initTheme()
Initializes theme based on user preference and system settings
initializeAutocomplete(inventoryopt)
Initialize autocomplete system Should be called when inventory is loaded or changed
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
inventory |
Array |
<optional> |
Current inventory data |
- Source:
injectVersionString(elementId, prefixopt)
Inserts formatted version string into a target element
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
elementId |
string | ID of the element to update |
||
prefix |
string |
<optional> |
"v" | Prefix to add before version |
- Source:
isCardViewActive() → {boolean}
Returns true when the card view (A/B/C) should be rendered instead of the table. Style D = table view. When D is selected, returns false so inventory.js renders the table.
- Source:
Returns:
- Type
- boolean
isCardViewActive() → {boolean}
Returns true when the card view (A/B/C) should be rendered instead of the table. Style D = table view. When D is selected, returns false so inventory.js renders the table.
- Source:
Returns:
- Type
- boolean
isFeatureEnabled()
Convenience functions for common feature flag operations
- Source:
isGoldbackPricingActive() → {boolean}
Returns true if Goldback pricing is active (enabled + has at least one price).
- Source:
Returns:
- Type
- boolean
isValidSelectOption(selectId, value) → {boolean}
Check if a value matches a valid
Parameters:
| Name | Type | Description |
|---|---|---|
selectId |
string | DOM id of the select element |
value |
string | Value to check |
- Source:
Returns:
- Type
- boolean
(async) loadAnnouncements()
Loads announcements and populates changelog and roadmap sections
loadApiCache() → {Object|null}
Retrieves valid cached API response data from localStorage. Checks against the provider's specific cache duration before returning.
Returns:
Cached response or null if expired/not found
- Type
- Object | null
loadApiConfig() → {Object|null}
Loads Metals API configuration from localStorage
Returns:
Metals API configuration or null if not set
- Type
- Object | null
loadCatalogHistory()
Load catalog history from localStorage
- Source:
(async) loadData(key, defaultValueopt) → {any}
Load data from localStorage with optional decompression
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
key |
string | Storage key |
||
defaultValue |
any |
<optional> |
[] | Default value if no data found |
Returns:
Parsed data or default value
- Type
- any
loadDisplayCurrency()
Loads the display currency preference from localStorage (STACK-50)
loadExchangeRates()
Loads cached exchange rates from localStorage (STACK-50). Called on startup before any rendering.
loadGoldbackEnabled()
Loads the Goldback pricing enabled toggle from localStorage.
- Source:
loadGoldbackEstimateEnabled()
Loads the Goldback estimation enabled toggle from localStorage.
- Source:
loadGoldbackEstimateModifier()
Loads the user-configurable premium modifier from localStorage.
- Source:
loadGoldbackPriceHistory()
Loads Goldback price history from localStorage into global state.
- Source:
loadGoldbackPrices()
Loads Goldback denomination prices from localStorage into global state.
- Source:
loadInventory() → {void}
Loads inventory from localStorage with comprehensive data migration
This function handles backwards compatibility by:
- Loading existing inventory data from localStorage
- Migrating legacy records that may be missing newer fields
- Calculating premiums for older records that lack this data
- Ensuring all records have required fields with sensible defaults
- Preserving existing user data while adding new functionality
- Source:
Throws:
-
Logs errors to console if localStorage access fails
- Type
- Error
Returns:
Updates the global inventory array with migrated data
- Type
- void
loadItemPriceHistory()
Loads item price history from localStorage into the global state variable.
- Source:
loadItemTags()
Load item tags from localStorage into the global itemTags object.
(async) loadLbmaReferenceEntries() → {Promise.<Array.<Object>>}
Loads and caches LBMA reference entries from yearly seed files. Uses fetchYearFile() for file:// and HTTP compatibility.
Returns:
Flattened LBMA reference entries
- Type
- Promise.<Array.<Object>>
loadLookupTable(inventoryopt, forceRefreshopt) → {LookupTable}
Load lookup table from cache or generate new one
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
inventory |
Array |
<optional> |
Current inventory data |
|
forceRefresh |
boolean |
<optional> |
false | Force regeneration regardless of cache |
- Source:
Returns:
Lookup table data
- Type
- LookupTable
loadProviderPriorities() → {Object}
Loads provider priority map from localStorage. Falls back to migration if not found.
- Source:
Returns:
Priority map { METALS_DEV: 1, METALS_API: 2, ... }
- Type
- Object
(async) loadSeedImages()
Loads seed pattern images as custom rules into NumistaLookup + IndexedDB. Creates two demo custom pattern rules with real coin photos for first-time users. Skips if already loaded at current version.
- Source:
loadSeedInventory()
Loads sample inventory items for first-time users.
Guard: skips if inventory already has entries (existing user). Assigns a unique serial to each sample item via getNextSerial(), pushes them into the inventory array, and persists with a single saveInventory() call.
- Source:
(async) loadSeedSpotHistory() → {Promise.<void>}
Loads seed spot history for first-time users.
Guard: skips if spotHistory already has entries (existing user). Tries fetch() for each year's JSON file; falls back to embedded data for file:// protocol. Validates entries, bulk-assigns to spotHistory, and persists with a single saveSpotHistory() call.
Also sets the latest seed price per metal in localStorage so price cards display seed prices instead of hardcoded defaults.
- Source:
Returns:
- Type
- Promise.<void>
loadSpotHistory()
Loads spot history from localStorage
loadTrendRanges() → {Object}
Loads saved trend range preferences from localStorage
Returns:
Map of metal key → days (default 30)
- Type
- Object
(async) loadViewImages(item, container) → {Promise.<{loaded: boolean, source: (string|null)}>}
Load coin images from IndexedDB cache → CDN URL fallback.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | |
container |
HTMLElement |
- Source:
Returns:
- Type
- Promise.<{loaded: boolean, source: (string|null)}>
(async) loadViewNumistaData(item, container, apiResult)
Load Numista metadata from IndexedDB cache or pre-fetched API result, render enrichment section.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | |
container |
HTMLElement | |
apiResult |
Object | null | Pre-fetched Numista API result (avoids duplicate call) |
- Source:
logChange(itemName, field, oldValue, newValue, idx)
Records a change to the change log and persists it
Parameters:
| Name | Type | Description |
|---|---|---|
itemName |
string | Name of the inventory item |
field |
string | Field that was changed |
oldValue |
any | Previous value |
newValue |
any | New value |
idx |
number | Index of item in inventory array |
- Source:
logItemChanges(oldItem, newItem)
Compares two item objects and logs any differences
Parameters:
| Name | Type | Description |
|---|---|---|
oldItem |
Object | Original item values |
newItem |
Object | Updated item values |
- Source:
logSyncActivity(message, typeopt)
Appends a timestamped line to the activity log and auto-scrolls.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
message |
string | |||
type |
'info' | 'success' | 'warn' | 'error' |
<optional> |
'info' |
- Source:
(async) lookupPcgsByNumber(pcgsNumber, gradeNumberopt) → {Promise.<Object>}
Look up a coin by PCGS catalog number via the PCGS Public API.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
pcgsNumber |
string | PCGS catalog number (e.g. "786060") |
|
gradeNumber |
string |
<optional> |
Optional grade number for specific grade lookup |
- Source:
Returns:
Lookup result with coin details
- Type
- Promise.<Object>
(async) lookupPcgsFromForm() → {Promise.<Object>}
Smart PCGS lookup — tries Cert# first, then PCGS#. Reads values from the item form fields.
- Source:
Returns:
Lookup result with coin details
- Type
- Promise.<Object>
mapNumistaType(type) → {string}
Maps Numista type strings to internal StakTrakr categories
Parameters:
| Name | Type | Description |
|---|---|---|
type |
string | Numista type string |
Returns:
Mapped internal type
- Type
- string
matchCoinSeries(searchMetal, coinType, itemText, exactPhrase) → {boolean|null}
Checks whether a two-word search like "Silver Eagle" should match an item, preventing cross-metal false positives (e.g. "Silver Eagle" matching "American Gold Eagle").
Parameters:
| Name | Type | Description |
|---|---|---|
searchMetal |
string | First word of the two-word search (lowercase) |
coinType |
string | Second word of the two-word search (lowercase) |
itemText |
string | Concatenated item fields (lowercase) |
exactPhrase |
string | Full two-word search string (lowercase) |
- Source:
Returns:
true/false for definitive match result, null to fall through to default logic
- Type
- boolean | null
mergeItemPriceHistory(importedHistory)
Merges imported item price history with existing data. Union by UUID + timestamp — deduplicates, sorts ascending. Used during ZIP restore (unlike spot history which does full replace).
Parameters:
| Name | Type | Description |
|---|---|---|
importedHistory |
Object | Object keyed by UUID with arrays of entries |
- Source:
migrateHourlySource()
One-time migration: re-tag old StakTrakr hourly backfill entries. Before v3.30.02, backfill entries were stored with source:"api" (same as live syncs). Identifies them by the heuristic: provider is "StakTrakr", source is "api", and timestamp lands exactly on the hour (:00:00). Regular syncs never produce on-the-hour timestamps.
migrateLayoutVisibility(obj) → {Array.<{id: string, label: string, enabled: boolean}>}
Migrates old layoutVisibility object to new ordered array format.
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
Object | Old format: { spotPrices: bool, totals: bool, ... } |
- Source:
Returns:
- Type
- Array.<{id: string, label: string, enabled: boolean}>
migrateProviderPriority() → {Object}
One-time migration from legacy apiProviderOrder + syncMode to priority numbers (STACK-90). Maps first "always" provider → 1, remaining providers → 2,3 in order, disabled → 0.
- Source:
Returns:
Priority map { METALS_DEV: 1, METALS_API: 2, ... }
- Type
- Object
monitorPerformance(fn, name, …args) → {any}
Performance monitoring utility
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
fn |
function | Function to monitor |
|
name |
string | Name for logging |
|
args |
any |
<repeatable> |
Arguments to pass to function |
Returns:
Result of function execution
- Type
- any
normalizeItemName(fullName) → {string}
Normalize item name to base form for grouping (e.g., filter chips). Uses precise starts-with matching against PREBUILT_LOOKUP_DATA — longest match wins. Falls back to suffix stripping for items not in the lookup.
Parameters:
| Name | Type | Description |
|---|---|---|
fullName |
string | Full item name (e.g., "2024 American Silver Eagle PCGS MS70") |
- Source:
Returns:
Base name (e.g., "American Silver Eagle")
- Type
- string
normalizeString(str, caseSensitiveopt) → {string}
Normalize a string by stripping special characters and optionally lowercasing
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
str |
string | Input string |
||
caseSensitive |
boolean |
<optional> |
false | Preserve case if true |
- Source:
Returns:
Normalized string
- Type
- string
normalizeType(typeopt) → {string}
Normalizes item type to one of the predefined options
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
type |
string |
<optional> |
"" | Raw type string |
Returns:
Normalized type value
- Type
- string
onGoldSpotPriceChanged()
Hook called whenever the gold spot price changes (API sync, manual, cache). If estimation is ON + Goldback pricing is ON + valid gold spot: calculates all denomination prices, saves them, records history, refreshes UI.
- Source:
openEbaySearch(searchTerm)
Opens eBay sold listings search for the given item name and metal
Parameters:
| Name | Type | Description |
|---|---|---|
searchTerm |
string | The item name and metal to search for |
openItemPriceHistoryModal(uuid, itemName)
Opens the per-item price history modal for a specific inventory item.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid |
string | Item UUID |
itemName |
string | Item name for the modal title |
- Source:
openModalById(id)
Opens a modal by id and sets body overflow to hidden. Also initializes a click-outside-to-close handler once.
Parameters:
| Name | Type | Description |
|---|---|---|
id |
string |
openNumistaModal(numistaId, coinName)
Opens the Numista page for the specified coin in a popup window.
Parameters:
| Name | Type | Description |
|---|---|---|
numistaId |
string | The Numista catalog ID |
coinName |
string | The name of the coin (used for window title) |
- Source:
(async) openSpotLookupModal()
Opens the spot lookup modal, searching local history and historical seed data for the date and metal currently selected in the add/edit form.
- Source:
(async) openStorageReportPopup()
Displays the storage report HTML inside a modal iframe
openVaultModal(mode, fileOrOptsopt)
Open the vault modal in export, import, cloud-export, or cloud-import mode.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
mode |
'export' | 'import' | 'cloud-export' | 'cloud-import' | ||
fileOrOpts |
File | object |
<optional> |
File for import, or { provider, fileBytes, filename, size } for cloud-import |
optimizeStoragePhase1C()
Phase 1C: Storage optimization and housekeeping
- Source:
optionalListener(el, event, handler, label)
Attaches a listener only if the element exists; silent no-op otherwise. Avoids console.warn spam for intentionally optional UI elements.
Parameters:
| Name | Type | Description |
|---|---|---|
el |
HTMLElement | null | Element (may be null) |
event |
string | Event type |
handler |
function | Event handler |
label |
string | Description for logging |
oztToGrams(ozt) → {number}
Converts troy ounces to grams
Parameters:
| Name | Type | Description |
|---|---|---|
ozt |
number | Weight in troy ounces |
Returns:
Weight in grams
- Type
- number
pad2(n) → {string}
Pads a number with leading zeros to ensure two-digit format
Parameters:
| Name | Type | Description |
|---|---|---|
n |
number | Number to pad |
Returns:
Two-digit string representation
- Type
- string
Example
pad2(5) returns "05", pad2(12) returns "12"
parseDate(dateStr) → {string}
Parses various date formats into standard YYYY-MM-DD format
Handles:
- ISO format (YYYY-MM-DD)
- US format (MM/DD/YYYY)
- European format (DD/MM/YYYY)
- Year-first format (YYYY/MM/DD)
Uses intelligent parsing to distinguish between US and European formats based on date values and context clues.
Parameters:
| Name | Type | Description |
|---|---|---|
dateStr |
string | Date string in any supported format |
Returns:
Date in YYYY-MM-DD format, or 'Unknown' if parsing fails
- Type
- string
parseFraction(str) → {number}
Parses a weight string that may contain fractions Supports: "0.5", "1/1000", "1 1/2" (mixed numbers)
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string | Weight string to parse |
Returns:
Parsed decimal value, or NaN if invalid
- Type
- number
parseItemFormFields(isEditing, existingItem) → {Object}
Reads all form fields and returns a parsed fields object.
Parameters:
| Name | Type | Description |
|---|---|---|
isEditing |
boolean | Whether in edit mode |
existingItem |
Object | Existing item (edit mode) |
Returns:
Parsed field values
- Type
- Object
parseNumistaMetal(composition) → {string}
Determines metal type from Numista composition string
Parameters:
| Name | Type | Description |
|---|---|---|
composition |
string | Composition description |
Returns:
Recognized metal or 'Alloy' if not silver/gold/platinum/palladium
- Type
- string
parsePcgsResponse(data) → {Object}
Parse a PCGS API coin detail response into a standardized result object.
Parameters:
| Name | Type | Description |
|---|---|---|
data |
Object | Raw PCGS API response |
- Source:
Returns:
Parsed coin details
- Type
- Object
parsePriceToUSD(rawValue, fxRate, isEditing, existingValue) → {number}
Converts a user-entered price from display currency to USD.
Parameters:
| Name | Type | Description |
|---|---|---|
rawValue |
string | Raw price input value |
fxRate |
number | Exchange rate (display currency per 1 USD) |
isEditing |
boolean | Whether in edit mode |
existingValue |
number | Existing price (edit mode) |
Returns:
Price in USD
- Type
- number
parsePurity(isEditing, existingItem) → {number}
Reads purity from the select/custom input pair.
Parameters:
| Name | Type | Description |
|---|---|---|
isEditing |
boolean | Whether in edit mode |
existingItem |
Object | Existing item (edit mode) |
Returns:
Purity value (0–1)
- Type
- number
parseSearchPatterns(query) → {Array.<string>}
Parses a comma-separated search query into individual patterns.
Parameters:
| Name | Type | Description |
|---|---|---|
query |
string | The search query string |
Returns:
Array of individual search patterns
- Type
- Array.<string>
parseVaultFile(fileBytes) → {Object}
Parse a .stvault binary file into its components.
Parameters:
| Name | Type | Description |
|---|---|---|
fileBytes |
Uint8Array |
Throws:
-
On invalid format
- Type
- Error
Returns:
- Type
- Object
parseWeight(weightRaw, weightUnit, isEditing, existingItem) → {number}
Parses weight from form input, handling Goldback denominations, fractions, and gram-to-troy-oz conversion.
Parameters:
| Name | Type | Description |
|---|---|---|
weightRaw |
string | Raw weight input value |
weightUnit |
string | Unit: 'oz', 'g', or 'gb' |
isEditing |
boolean | Whether in edit mode |
existingItem |
Object | Existing item (edit mode) |
Returns:
Weight in troy ounces (or denomination value for gb)
- Type
- number
(async) pcgsFetch(url) → {Promise.<Object>}
Shared fetch wrapper for PCGS API calls.
Parameters:
| Name | Type | Description |
|---|---|---|
url |
string | Full API URL |
- Source:
Returns:
Parsed JSON or error result
- Type
- Promise.<Object>
pcgsPreflightCheck() → {Object|null}
Shared pre-flight checks for all PCGS API calls.
- Source:
Returns:
Error result if checks fail, null if OK
- Type
- Object | null
persistInventoryAndRefresh()
Saves inventory and refreshes table display
- Source:
(async) pollForRemoteChanges()
Download staktrakr-sync.json and compare syncId with last pull. If different, hand off to handleRemoteChange(). Skips silently if not connected or sync is disabled.
- Source:
populateAboutModal()
Populates the about modal with current version and changelog information
populateAckModal()
Populates the acknowledgment modal with version information
populateApiSection()
Populates the API section fields with current configuration. Called when switching to the API section in the Settings modal.
populateImagesSection()
Populate all sub-sections of the Images settings tab.
- Source:
populateVersionModal(version)
Populates and shows the version modal Content is loaded by loadAnnouncements() into the versionChanges element
Parameters:
| Name | Type | Description |
|---|---|---|
version |
string | Current application version |
- Source:
preparePriceHistoryRows(filterUuidopt) → {Array.<Object>}
Flattens, filters, and sorts item price history into renderable rows.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
filterUuid |
string |
<optional> |
If provided, only return rows for this UUID |
- Source:
Returns:
Sorted row objects (includes uuid for delete support)
- Type
- Array.<Object>
(async) processUploadedImage(file, sideopt)
Process a user-selected image file and show preview for a specific side.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
file |
File | |||
side |
'obverse' | 'reverse' |
<optional> |
'obverse' |
providerRequiresKey()
Check whether a provider requires an API key
(async) pullSyncVault(remoteMeta)
Download staktrakr-sync.stvault, decrypt, and restore inventory.
Parameters:
| Name | Type | Description |
|---|---|---|
remoteMeta |
object | Remote sync metadata (from pollForRemoteChanges) |
- Source:
purgeCatalogHistory(days)
Purge catalog history entries older than given number of days
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
days |
number | 180 | Maximum age in days (default 180) |
- Source:
purgeItemPriceHistory(days)
Removes item price history entries older than the specified number of days. Not called automatically — available for future settings UI.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
days |
number | 365 | Number of days to retain (default: 365) |
- Source:
purgeSpotHistory(days)
Removes spot history entries older than the specified number of days
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
days |
number | 180 | Number of days to retain |
(async) pushSyncVault()
Encrypt the sync-scoped inventory and upload to Dropbox. Also updates the lightweight staktrakr-sync.json metadata pointer. Skips silently if not connected or sync is disabled.
- Source:
recalcItem(item)
Recalculates premium values for an inventory item Legacy premiums are no longer displayed — this is now a no-op stub kept to prevent runtime errors from stale references.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Inventory item (unused) |
- Source:
recordAllItemPriceSnapshots()
Snapshots all inventory items after a spot price change. Applies spot-sync dedup rules (24h throttle, 1% delta). Called after API sync, manual spot update, or spot reset.
- Source:
recordCatalogHistory(entry)
Record a catalog API call to history
Parameters:
| Name | Type | Description |
|---|---|---|
entry |
Object | History entry data |
- Source:
recordGoldbackPrices()
Appends current denomination prices as timestamped history entries. Called after user saves updated prices in the settings panel.
- Source:
recordItemPrice(item, trigger) → {boolean}
Records a single price data point for an inventory item. Applies deduplication rules:
- add/edit/bulk: skip exact duplicates only (same retail + spot + melt)
- spot-sync: 24h throttle if retail unchanged; beyond 24h, require >1% delta
Does NOT save to localStorage — caller must batch saves.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
item |
Object | Inventory item (must have uuid, metal, weight, qty, purity, marketValue) |
|
trigger |
string | spot-sync | Recording trigger: 'add' | 'edit' | 'bulk' | 'spot-sync' |
- Source:
Returns:
True if a data point was recorded
- Type
- boolean
recordSingleItemPrice(item, trigger)
Records a price data point for a single item and saves immediately. Used after item add, edit, or inline edit.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
item |
Object | Inventory item |
|
trigger |
string | edit | 'add' | 'edit' | 'bulk' |
- Source:
recordSpot(newSpot, source, metal, provider, timestamp)
Records a new spot price entry in history
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
newSpot |
number | New spot price value |
|
source |
string | Source of spot price ('manual', 'api', etc.) |
|
metal |
string | Metal type ('Silver', 'Gold', 'Platinum', or 'Palladium') |
|
provider |
string | null | null | Provider name if source is API-based |
timestamp |
string | null | null | Optional ISO timestamp for historical entries |
refreshCompositionOptions()
Refreshes composition dropdown options in add/edit modals
refreshFromCache() → {boolean}
Force-refreshes all spot price displays using the most recent cached data. Does not make external network requests.
Returns:
True if display was successfully updated from cache
- Type
- boolean
refreshLookupTable(inventoryopt) → {LookupTable}
Refresh lookup table from current inventory
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
inventory |
Array |
<optional> |
Current inventory data |
- Source:
Returns:
Refreshed lookup table
- Type
- LookupTable
refreshProviderStatuses()
Periodically refreshes connection status icons based on key presence and cache age. Determines if a provider is fully connected, cached (needs sync), or disconnected.
refreshSyncUI()
Refresh the "Last synced" text and toggle state in the cloud card. Called by syncCloudUI() when switching to the Cloud settings panel.
- Source:
refreshTotalsDots()
Rebuilds totals carousel dots after metal order/visibility changes. Safe to call multiple times — does not re-wire scroll or nav listeners.
- Source:
refreshTotalsDots()
Rebuilds totals carousel dots after metal order/visibility changes. Safe to call multiple times — does not re-wire scroll or nav listeners.
- Source:
registerName(name)
Register a new item name into the current lookup table. Called automatically when items are added or imported.
Parameters:
| Name | Type | Description |
|---|---|---|
name |
string | Item name to register |
- Source:
removeFilter(field, value)
Removes a specific filter from active filters or search.
Parameters:
| Name | Type | Description |
|---|---|---|
field |
string | The field to remove filter from |
value |
string | The value to remove from filter |
- Source:
removeItemTag(uuid, tag) → {boolean}
Remove a tag from an item.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid |
string | Item UUID |
tag |
string | Tag name |
Returns:
True if tag was removed
- Type
- boolean
renameTag(oldName, newName) → {number}
Rename a tag across all items.
Parameters:
| Name | Type | Description |
|---|---|---|
oldName |
string | Current tag name |
newName |
string | New tag name |
Returns:
Number of items affected
- Type
- number
renderActiveFilters()
Renders active filter chips beneath the search bar. Updates the filter chip container based on current filters and inventory.
- Source:
renderApiHistoryTable()
Renders API history table with filtering, sorting and pagination
renderApiStatusSummary()
Renders a status summary row in the header for all configured API providers. Displays connection status (connected/disconnected/cached) and last sync time.
renderBulkTable()
Full render — toolbar + table body. Called on open and after bulk actions.
- Source:
renderBulkTableBody()
Renders the table body (rows) — called on search, selection, and data changes. Does NOT touch the toolbar, preserving search input focus.
- Source:
renderBulkToolbar()
Renders the toolbar (search, buttons, badge) — called once on open. The toolbar persists across search/selection updates.
- Source:
renderCardA(item, idx, computed) → {string}
Renders Card Style A: Sparkline Header with stacked images.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
object | Inventory item |
idx |
number | Original inventory index |
computed |
object | Pre-computed financial values |
- Source:
Returns:
- Type
- string
renderCardA(item, idx, computed) → {string}
Renders Card Style A: Sparkline Header with stacked images.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
object | Inventory item |
idx |
number | Original inventory index |
computed |
object | Pre-computed financial values |
- Source:
Returns:
- Type
- string
renderCardB()
Renders Card Style B: Full-Bleed Overlay with hero gain number.
- Source:
renderCardB()
Renders Card Style B: Full-Bleed Overlay with hero gain number.
- Source:
renderCardC()
Renders Card Style C: Split Card (image left, data right).
- Source:
renderCardC()
Renders Card Style C: Split Card (image left, data right).
- Source:
renderCardView(sortedItems, container)
Renders all items as cards into the given container.
Parameters:
| Name | Type | Description |
|---|---|---|
sortedItems |
Array.<object> | Sorted/filtered inventory items |
container |
HTMLElement | Target container element |
- Source:
renderCardView(sortedItems, container)
Renders all items as cards into the given container.
Parameters:
| Name | Type | Description |
|---|---|---|
sortedItems |
Array.<object> | Sorted/filtered inventory items |
container |
HTMLElement | Target container element |
- Source:
renderCatalogHistoryForSettings()
Renders the catalog history table in the Settings > Activity Log > Catalogs sub-tab. Reads from global catalogHistory, sorts by timestamp descending by default.
- Source:
renderCatalogHistoryTable()
Renders catalog history table with filtering and sorting Mirrors renderApiHistoryTable() in api.js
- Source:
renderChangeLog()
Renders the change log table with all entries
- Source:
renderCloudBackupList()
Render the backup list for a cloud provider.
- Source:
(async) renderCustomPatternRules()
Render user-created pattern image rules with dual thumbnails, edit, and delete.
- Source:
renderCustomRuleTable()
Renders the custom Numista lookup rules table with delete buttons.
- Source:
(async) renderEligibleItemsTable()
Renders the table of all inventory items that have Numista catalog IDs. Each row shows: N#, item name, cache status, and action buttons. Status cells are tracked in _statusCells for live updates during bulk sync.
- Source:
renderFilterChipCategoryTable()
Renders the filter chip category config table in Settings > Chips. Each row has a checkbox (enable/disable) and up/down arrows for reordering.
- Source:
renderGoldbackHistoryTable()
Renders the Goldback history table with filtering and sorting.
- Source:
(async) renderImageStorageStats()
Render storage statistics for the image system.
- Source:
renderInlineChipConfigTable()
Renders the inline chip config table in Settings > Grouping. Delegates to the generic _renderSectionConfigTable helper.
- Source:
renderItemPriceHistoryModalTable()
Renders the per-item price history modal table. Shows entries only for _itemPriceModalUuid, newest first.
- Source:
renderItemPriceHistoryTable()
Renders the item price history table in the Settings > Activity Log > Price History sub-tab.
- Source:
renderLayoutSectionConfigTable()
Renders the main page layout section config table in Settings > Layout.
- Source:
(async) renderLbmaHistoryTable()
Renders the Settings > Activity Log > LBMA History reference table. Data source is bundled year files (seed reference data), not user spotHistory.
renderLogTab(key)
Dispatches to the appropriate render function for a log sub-tab.
Parameters:
| Name | Type | Description |
|---|---|---|
key |
string | Sub-tab key |
- Source:
renderMetalOrderConfigTable()
Renders the metal order config table in Settings > Chips.
- Source:
renderNumistaFieldCheckboxes(result)
Render field checkboxes with editable input fields for the selected result. Each row: [checkbox] [label] [editable text input] User can tweak values before hitting "Fill Fields".
Parameters:
| Name | Type | Description |
|---|---|---|
result |
Object | Normalized Numista item data |
- Source:
renderNumistaResultCard(result, index) → {string}
Render a single result card HTML string
Parameters:
| Name | Type | Description |
|---|---|---|
result |
Object | Normalized Numista item data |
index |
number | Index in results array |
- Source:
Returns:
HTML string
- Type
- string
renderNumistaSelectedItem(result) → {string}
Render the selected item preview in field picker
Parameters:
| Name | Type | Description |
|---|---|---|
result |
Object | Normalized Numista item data |
- Source:
Returns:
HTML string
- Type
- string
(async) renderNumistaSyncUI()
Renders the Numista Bulk Sync inline UI: stats, eligible items table. Called when the Numista provider tab is shown and conditions are met.
- Source:
renderNumistaUsageBar()
Renders Numista API usage progress bar into #numistaUsageBar Reuses the same .api-usage / .usage-bar / .usage-text CSS as metals providers
- Source:
renderPcgsFieldCheckboxes(result)
Render field checkboxes with editable inputs for the PCGS result. Each row: [checkbox] [label] [editable text input] [optional current hint]
Parameters:
| Name | Type | Description |
|---|---|---|
result |
Object | Parsed PCGS response |
- Source:
renderPcgsSelectedItem(result) → {string}
Render the selected item preview card with images + metadata.
Parameters:
| Name | Type | Description |
|---|---|---|
result |
Object | Parsed PCGS response |
- Source:
Returns:
HTML string
- Type
- string
renderPcgsUsageBar()
Renders PCGS API usage progress bar into #pcgsUsageBar Clones the Numista pattern but uses daily granularity (1,000/day)
- Source:
renderSeedRuleTable()
Renders the built-in (seed) Numista lookup rules table with enable/disable toggles.
- Source:
renderSpotHistoryTable()
Renders the spot price history table in the Settings > Activity Log > Metals sub-tab. Reads from the global spotHistory array and sorts by timestamp descending by default.
renderSpotLookupEmpty(container, metalName, dateStr)
Renders the empty state when no local history matches. Shows "Fetch from API" button if a provider is available.
Parameters:
| Name | Type | Description |
|---|---|---|
container |
HTMLElement | The modal body element |
metalName |
string | Metal name |
dateStr |
string | Target date |
- Source:
renderSpotLookupResults(container, results, metalName, dateStr)
Renders spot lookup results into the modal body.
Parameters:
| Name | Type | Description |
|---|---|---|
container |
HTMLElement | The modal body element |
results |
Array | Search results with dayOffset |
metalName |
string | Metal name for API fallback context |
dateStr |
string | Target date for API fallback context |
- Source:
(async) renderStorageSection(silentopt)
Populates the Storage settings panel with live LS and IDB data.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
silent |
boolean |
<optional> |
false | If true, skip the loading spinner on refresh |
- Source:
renderSyncHistorySection()
Render the Sync History section in Settings → Cloud. Shows metadata for the pre-pull local snapshot (if any) and a restore button.
- Source:
(async) renderSyncStats()
Renders the cache statistics bar: count, total size, quota percentage.
- Source:
(async) renderUserImageGrid()
Render user-uploaded images as rows with dual thumbnails, edit link, and delete.
- Source:
renderVersionBadge(badge, remoteVersion, releaseUrl)
Renders the version badge in the footer
Parameters:
| Name | Type | Description |
|---|---|---|
badge |
HTMLElement | The badge element |
remoteVersion |
string | Latest remote version |
releaseUrl |
string | URL to latest release |
- Source:
renderViewModalSectionConfigTable()
Renders the view modal section config table in Settings > Layout.
- Source:
replaceTemplateVariables(text) → {string}
Replaces template variables in text
Parameters:
| Name | Type | Description |
|---|---|---|
text |
string | Text containing {{VARIABLE}} placeholders |
- Source:
Returns:
Text with variables replaced
- Type
- string
resetSpot(metalKey)
Resets spot price for specified metal to default or API cached value
Parameters:
| Name | Type | Description |
|---|---|---|
metalKey |
string | Key of metal to reset ('silver', 'gold', 'platinum', 'palladium') |
resetSpotByName(metalName)
Alternative reset function that works with metal name instead of key This provides compatibility with the API.js resetSpotPrice function
Parameters:
| Name | Type | Description |
|---|---|---|
metalName |
string | Name of metal to reset ('Silver', 'Gold', etc.) |
resetSpotPrice(metal)
Resets spot price to default or API cached value
Parameters:
| Name | Type | Description |
|---|---|---|
metal |
string | Metal name (Silver, Gold, etc.) |
resolveElement(id) → {HTMLElement|null}
Safely retrieves a DOM element by ID, using safeGetElement if available.
Parameters:
| Name | Type | Description |
|---|---|---|
id |
string | The ID of the element to retrieve |
Returns:
The DOM element or null
- Type
- HTMLElement | null
(async) restoreBackupZip(file)
Restores application data from a backup ZIP file
Parameters:
| Name | Type | Description |
|---|---|---|
file |
File | ZIP file created by createBackupZip |
- Source:
restoreVaultData(payload)
Restore vault data into localStorage and refresh UI.
Parameters:
| Name | Type | Description |
|---|---|---|
payload |
object | Decrypted vault payload |
(async) resyncCachedEntry(catalogId)
Re-syncs a single cached entry: deletes metadata then re-fetches from Numista API. Image caching is handled on-demand by the view modal.
Parameters:
| Name | Type | Description |
|---|---|---|
catalogId |
string |
- Source:
safeAttachListener(element, event, handler, descriptionopt) → {boolean}
Safely attaches event listener with fallback methods
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
element |
HTMLElement | Window | Document | Element to attach listener to |
||
event |
string | Event type |
||
handler |
function | Event handler function |
||
description |
string |
<optional> |
"" | Description for logging |
Returns:
Success status
- Type
- boolean
safeDebug(…args) → {void}
Logs debug output with the app logger when available.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
* |
<repeatable> |
- Source:
Returns:
- Type
- void
safeGetElement(id, required) → {HTMLElement|Object}
Safely retrieves a DOM element by ID with fallback to dummy element
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
id |
string | Element ID |
|
required |
boolean | false | Whether to log warning if element missing |
Returns:
Element or dummy element
- Type
- HTMLElement | Object
sanitizeHtml(text) → {string}
Sanitizes text input for safe HTML display Prevents XSS attacks by encoding HTML special characters
Parameters:
| Name | Type | Description |
|---|---|---|
text |
string | Text to sanitize |
Returns:
Sanitized text safe for HTML insertion
- Type
- string
sanitizeImportedItem(item) → {Object}
Sanitizes imported inventory data, coercing invalid fields to safe defaults.
String fields default to an empty string and numeric fields become null when parsing fails. This allows imports to proceed even when some fields are malformed.
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Raw item data from an import process |
Returns:
Sanitized item
- Type
- Object
sanitizeObjectFields(obj) → {Object}
Sanitizes all string properties of an object by stripping non-alphanumeric characters.
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
Object | Object whose string fields will be sanitized |
Returns:
New object with sanitized string fields
- Type
- Object
sanitizeTablesOnLoad() → {void}
Removes non-alphanumeric characters from inventory records.
- Source:
Returns:
- Type
- void
saveApiCache(data, provider)
Persists API response data to the local browser cache. Uses provider-specific cache duration settings.
Parameters:
| Name | Type | Description |
|---|---|---|
data |
Object | Standardized price data object |
provider |
string | Key of the data provider |
saveApiConfig(config)
Saves Metals API configuration to localStorage
Parameters:
| Name | Type | Description |
|---|---|---|
config |
Object | Metals API configuration object |
saveCatalogHistory()
Save catalog history to localStorage
- Source:
(async) saveData(key, data)
Save data to localStorage with optional compression
Parameters:
| Name | Type | Description |
|---|---|---|
key |
string | Storage key |
data |
any | Data to store |
saveDisplayCurrency(code)
Saves the display currency preference to localStorage (STACK-50)
Parameters:
| Name | Type | Description |
|---|---|---|
code |
string | ISO 4217 currency code |
saveExchangeRates(rates)
Saves exchange rates to localStorage (STACK-50).
Parameters:
| Name | Type | Description |
|---|---|---|
rates |
Object.<string, number> | Exchange rates keyed by currency code |
saveFilterChipCategoryConfig(config)
Saves the filter chip category config to localStorage.
Parameters:
| Name | Type | Description |
|---|---|---|
config |
Array.<{id: string, label: string, enabled: boolean}> |
- Source:
saveGoldbackEnabled(val)
Saves the Goldback pricing enabled toggle to localStorage.
Parameters:
| Name | Type | Description |
|---|---|---|
val |
boolean | Whether Goldback pricing is enabled |
- Source:
saveGoldbackEstimateEnabled(val)
Saves the Goldback estimation enabled toggle to localStorage.
Parameters:
| Name | Type | Description |
|---|---|---|
val |
boolean | Whether estimation is enabled |
- Source:
saveGoldbackEstimateModifier(val)
Saves the user-configurable premium modifier to localStorage.
Parameters:
| Name | Type | Description |
|---|---|---|
val |
number | Modifier value (e.g. 1.0, 1.03) |
- Source:
saveGoldbackPriceHistory()
Saves Goldback price history to localStorage.
- Source:
saveGoldbackPrices()
Saves current Goldback denomination prices to localStorage.
- Source:
saveInlineChipConfig(config)
Saves the inline chip config to localStorage.
Parameters:
| Name | Type | Description |
|---|---|---|
config |
Array.<{id: string, label: string, enabled: boolean}> |
- Source:
saveInventory()
Saves current inventory to localStorage
- Source:
saveItemPriceHistory()
Saves item price history to localStorage.
- Source:
saveItemTags()
Save the global itemTags object to localStorage.
saveLayoutSectionConfig()
Saves the layout section config to localStorage.
- Source:
saveNumistaViewFieldConfig(config)
Save Numista view field config to localStorage.
Parameters:
| Name | Type | Description |
|---|---|---|
config |
Object.<string, boolean> |
- Source:
saveProviderPriorities(priorities)
Saves provider priority map and writes backward-compatible apiProviderOrder (STACK-90).
Parameters:
| Name | Type | Description |
|---|---|---|
priorities |
Object | { METALS_DEV: 1, METALS_API: 2, ... } |
- Source:
saveSpotHistory() → {void}
Saves spot history to localStorage.
Writes the content of spotHistory to the SPOT_HISTORY_KEY.
Returns:
- Type
- void
saveTrendRange(metalKey, days)
Saves a single metal's trend range preference
Parameters:
| Name | Type | Description |
|---|---|---|
metalKey |
string | Metal key |
days |
number | Number of days |
(async) saveUserImageForItem(uuid) → {Promise.<boolean>}
Save the pending upload blob(s) to IndexedDB for the given item UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid |
string |
Returns:
- Type
- Promise.<boolean>
saveViewModalSectionConfig()
Saves the view modal section config to localStorage.
- Source:
(async) searchHistoricalByDate(metalName, dateStr) → {Promise.<Array.<Object>>}
Searches historical year files for prices near a given date for a specific metal. Uses the same progressive widening as searchSpotByDate: exact → ±1d → ±3d → ±7d. Requires fetchYearFile() from spot.js (STACK-69).
Parameters:
| Name | Type | Description |
|---|---|---|
metalName |
string | Metal name ('Silver', 'Gold', 'Platinum', 'Palladium') |
dateStr |
string | Target date in YYYY-MM-DD format |
- Source:
Returns:
Matching entries with dayOffset appended, sorted by proximity
- Type
- Promise.<Array.<Object>>
searchPatternExistsInCustomGroups(patterns) → {boolean}
Checks if a set of search patterns already exists as a custom group.
Parameters:
| Name | Type | Description |
|---|---|---|
patterns |
Array.<string> | The patterns to check |
Returns:
True if a matching custom group exists
- Type
- boolean
searchPatternMatchesAutoChip(patterns) → {boolean}
Checks if a set of search patterns matches any auto-generated chips.
Parameters:
| Name | Type | Description |
|---|---|---|
patterns |
Array.<string> | The patterns to check |
Returns:
True if any pattern matches an auto-chip
- Type
- boolean
searchSpotByDate(metalName, dateStr) → {Array.<Object>}
Searches local spot history for prices near a given date for a specific metal. Uses progressive widening: exact → ±1d → ±3d → ±7d.
Parameters:
| Name | Type | Description |
|---|---|---|
metalName |
string | Metal name ('Silver', 'Gold', 'Platinum', 'Palladium') |
dateStr |
string | Target date in YYYY-MM-DD format |
- Source:
Returns:
Matching entries with dayOffset appended, sorted by proximity
- Type
- Array.<Object>
serializeVaultFile(salt, iv, iterations, ciphertext) → {Uint8Array}
Serialize vault header + ciphertext into a single binary blob.
Parameters:
| Name | Type | Description |
|---|---|---|
salt |
Uint8Array | 32 bytes |
iv |
Uint8Array | 12 bytes |
iterations |
number | |
ciphertext |
Uint8Array |
Returns:
- Type
- Uint8Array
setDefaultProvider(provider)
Updates the active API provider in configuration. Validates that the provider has a key (if required) before switching.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
setEditPreviewUrl(url, sideopt)
Track an externally-created preview object URL so it gets revoked when clearUploadState() runs (prevents memory leaks in editItem preview).
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
url |
string | Object URL to track |
||
side |
'obverse' | 'reverse' |
<optional> |
'obverse' |
setProviderStatus(provider, status)
Sets connection status for a provider in the settings UI
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | |
status |
"connected" | "disconnected" | "error" | "cached" |
setTheme(theme)
Sets application theme and updates localStorage
Parameters:
| Name | Type | Description |
|---|---|---|
theme |
string | 'dark', 'light', or 'sepia' |
setupAboutModalEvents()
Sets up event listeners for about modal elements
setupAckModalEvents()
Sets up event listeners for acknowledgment modal elements
setupApiEvents()
Sets up API-related event listeners
setupBasicEventListeners()
Basic event listener setup as fallback
setupBulkEditControls()
Sets up bulk edit control panel event listeners
setupColumnResizing()
Implements dynamic column resizing for the inventory table
setupDataManagementListeners()
Sets up data-destructive action listeners (remove data, boating accident).
setupEventListeners()
Sets up all primary event listeners for the application
setupFormatImport(overrideBtn, mergeBtn, fileInput, importFn, formatName)
Sets up the override/merge/file-input triad for a single import format.
Parameters:
| Name | Type | Description |
|---|---|---|
overrideBtn |
HTMLElement | null | "Override" button element |
mergeBtn |
HTMLElement | null | "Merge" button element |
fileInput |
HTMLElement | null | Hidden file input element |
importFn |
function | Import function (file, isOverride) => void |
formatName |
string | Human label (e.g. "CSV", "JSON", "Numista CSV") |
setupHeaderButtonListeners()
Sets up header button listeners (logo, settings, about, details)
setupImportExportListeners()
Sets up import/export event listeners (CSV, JSON, Numista, PDF, Vault, etc.)
setupItemFormListeners()
Sets up item form submission and related button listeners
setupNoteAndModalListeners()
Sets up notes modal, debug modal, bulk edit, changelog, and settings clear button listeners
setupPagination()
Sets up visible-rows (portal view) event listener
setupProviderPriority()
Sets up change listeners on provider priority selects (STACK-90). Auto-shifts: setting provider X to priority N bumps any existing N holder to N+1 (cascade).
- Source:
setupProviderSettingsListeners(provider)
Attaches DOM event listeners to the settings controls for a specific provider. Handles cache changes, history pull parameters, and metal selection checkboxes.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
setupResponsiveColumns()
Sets up responsive column visibility handling
setupSearch()
Sets up search event listeners
setupSearchAndChipListeners()
Sets up search input and chip-related listeners
setupSettingsEventListeners()
Wires up all Settings modal event listeners. Called once during initialization.
- Source:
setupSpotPriceListeners()
Sets up spot price sync icons, range dropdowns, and inline editing
setupSystemThemeListener()
Sets up system theme change listener
setupTableSortListeners()
Sets up table header sorting and Goldback denomination picker
setupThemeToggle()
Sets up the theme toggle logic and listeners. Initializes the theme based on saved preference or system settings.
setupVaultListeners()
Sets up vault backup/restore listeners and password strength UI.
setupVersionModalEvents(version)
Sets up modal event handlers for version acknowledgment
Parameters:
| Name | Type | Description |
|---|---|---|
version |
string | Current application version |
- Source:
shouldShowSearchSaveButton(query, fuzzyUsed) → {boolean}
Determines whether the "Save Search" button should be displayed.
Parameters:
| Name | Type | Description |
|---|---|---|
query |
string | The current search query |
fuzzyUsed |
boolean | Whether fuzzy matching was used for this query |
Returns:
True if the save button should be shown
- Type
- boolean
showAboutModal()
Shows the About modal and populates it with current data
showAckModal()
Shows the acknowledgment modal on load
showApiHistoryModal()
Opens the API history modal and populates it with filtered spot history data. Displays only 'api', 'api-hourly', and 'seed' entries in the log.
showApiModal()
Legacy showApiModal — redirects to Settings modal API section
showApiProvidersModal()
Opens the API provider selection modal (redirects to the API section of Settings).
showAppAlert(message, titleopt) → {Promise.<void>}
Displays an application-styled alert dialog.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
message |
string | ||
title |
string |
<optional> |
- Source:
Returns:
- Type
- Promise.<void>
showAppConfirm(message, titleopt) → {Promise.<boolean>}
Displays an application-styled confirmation dialog.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
message |
string | ||
title |
string |
<optional> |
- Source:
Returns:
- Type
- Promise.<boolean>
showAppPrompt(message, defaultValueopt, titleopt) → {Promise.<?string>}
Displays an application-styled prompt dialog.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
message |
string | ||
defaultValue |
string |
<optional> |
|
title |
string |
<optional> |
- Source:
Returns:
- Type
- Promise.<?string>
showBulkConfirm(message) → {Promise.<boolean>}
Show an inline confirmation modal and return a Promise
Parameters:
| Name | Type | Description |
|---|---|---|
message |
string |
- Source:
Returns:
- Type
- Promise.<boolean>
showCatalogHistoryModal()
Shows catalog history modal
- Source:
showDebugModal() → {void}
Displays the debug modal and renders buffered debug history text.
- Source:
Returns:
- Type
- void
showDetailsModal(metal)
Shows the details modal for specified metal with pie charts
Parameters:
| Name | Type | Description |
|---|---|---|
metal |
string | Metal type to show details for |
- Source:
showFaqModal() → {void}
Opens the Settings modal on the FAQ tab.
Returns:
- Type
- void
showFilesModal()
Legacy showFilesModal — redirects to Settings modal Files section
showFullChangelog()
Shows full changelog in a new window or navigates to documentation
showGoldbackHistoryModal()
Shows the Goldback price history modal.
- Source:
showManualInput(metal)
Shows manual price input for a specific metal
Parameters:
| Name | Type | Description |
|---|---|---|
metal |
string | Metal name (Silver, Gold, etc.) |
showNotes(idx)
Opens modal to view and edit an item's notes
Parameters:
| Name | Type | Description |
|---|---|---|
idx |
number | Index of item whose notes to view/edit |
- Source:
showNotesView(idx)
Opens a read-only notes viewer for the given inventory index.
Parameters:
| Name | Type | Description |
|---|---|---|
idx |
number | Inventory array index |
- Source:
showNumistaResults(results, directLookup, originalQuery)
Show Numista results modal with search results
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
results |
Array | Array of normalized Numista item data |
|
directLookup |
boolean | false | If true and single result, skip list and show field picker |
originalQuery |
string | The search query used (for retry pre-fill) |
- Source:
showPcgsFieldPicker(result)
Open the PCGS field picker modal with the given lookup result.
Parameters:
| Name | Type | Description |
|---|---|---|
result |
Object | Parsed PCGS response |
- Source:
showProviderInfo(providerKey)
Shows provider information modal
Parameters:
| Name | Type | Description |
|---|---|---|
providerKey |
string |
showSettingsModal(sectionopt)
Opens the unified Settings modal, optionally navigating to a section.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
section |
string |
<optional> |
'site' | Section to display: 'site', 'system', 'table', 'grouping', 'api', 'cloud', 'images', 'storage', 'goldback', 'changelog' |
- Source:
showStaticVersionBadge()
Shows a static version badge linking to GitHub releases. Used as the default state; upgraded by checkRemoteVersion() when possible.
- Source:
showSyncConflictModal(opts)
Show the sync conflict modal with local vs. remote comparison.
Parameters:
| Name | Type | Description |
|---|---|---|
opts |
Object |
- Source:
showSyncUpdateModal(remoteMeta) → {Promise.<boolean>}
Show the "Update available" modal and return a Promise that resolves true (user accepted) or false (user dismissed / closed).
Parameters:
| Name | Type | Description |
|---|---|---|
remoteMeta |
object | The parsed staktrakr-sync.json content |
- Source:
Returns:
- Type
- Promise.<boolean>
showTagInput(container, uuid, numistaTags, renderTags, onChangedopt)
Show an inline input for adding a new tag.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
container |
HTMLElement | Parent container |
|
uuid |
string | Item UUID |
|
numistaTags |
Array.<string> | Numista tags for autocomplete |
|
renderTags |
function | Re-render callback |
|
onChanged |
function |
<optional> |
External change callback |
showVaultStatus(type, message)
Show status message in the vault modal.
Parameters:
| Name | Type | Description |
|---|---|---|
type |
'success' | 'error' | 'info' | 'warning' | |
message |
string |
(async) showViewModal(index)
Open the view modal for a specific inventory item.
Parameters:
| Name | Type | Description |
|---|---|---|
index |
number | Index into the global |
- Source:
simpleHash(str) → {string}
Simple hash for integrity check (not cryptographic — just detects corruption).
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string |
Returns:
- Type
- string
simplifyChipValue(value, field) → {string}
Returns the display value for a filter chip. Passes through the value as-is — hardcoded name simplifications have been removed in favour of user-configurable custom grouping rules in Settings.
Parameters:
| Name | Type | Description |
|---|---|---|
value |
string | The original value |
field |
string | The field type (e.g., 'name', 'type', etc.) |
- Source:
Returns:
Display value
- Type
- string
sortInventory(dataopt) → {Array.<InventoryItem>}
Sorts inventory based on the current sort column and direction. Handles special cases for date, numeric, boolean, and string columns.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
data |
Array.<InventoryItem> |
<optional> |
inventory | Array of inventory items to sort (defaults to main inventory) |
- Source:
Returns:
Sorted inventory data
- Type
- Array.<InventoryItem>
Example
sortInventory([{name: 'A'}, {name: 'B'}]);
sortInventoryByDateNewestFirst(dataopt) → {Array}
Sorts inventory by date (newest first)
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
data |
Array |
<optional> |
inventory | Data to sort |
Returns:
Sorted inventory data
- Type
- Array
startBulkSync()
Starts the bulk sync operation from the inline Numista card. Updates per-row status cells in real time as items are processed.
- Source:
startCellEdit(idx, field, element)
Enhanced inline editing for table cells with support for multiple field types
Parameters:
| Name | Type | Description |
|---|---|---|
idx |
number | Index of item to edit |
field |
string | Field name to update |
element |
HTMLElement | The td cell or a child element within it |
- Source:
startSpotInlineEdit(valueEl, metalKey)
Opens an inline input on a spot card price for manual editing (shift+click)
Parameters:
| Name | Type | Description |
|---|---|---|
valueEl |
HTMLElement | The .spot-card-value element that was clicked |
metalKey |
string | Metal key ('silver', 'gold', etc.) |
startSyncPoller()
Start the background polling loop. Uses setTimeout so backoff delay is honoured.
- Source:
stopSyncPoller()
Stop the background polling loop.
- Source:
stripNonAlphanumeric(str) → {string}
Removes all non-alphanumeric characters from a string, preserving spaces.
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string | Input string |
Returns:
Cleaned string containing only letters, numbers, and spaces
- Type
- string
switchLogTab(key)
Switches the visible log sub-tab in the Activity Log panel. Re-renders the tab content on every switch to ensure fresh data.
Parameters:
| Name | Type | Description |
|---|---|---|
key |
string | Sub-tab key: 'changelog', 'metals', 'catalogs', 'pricehistory' |
- Source:
switchProviderTab(key)
Switches the visible provider tab in the API section.
Parameters:
| Name | Type | Description |
|---|---|---|
key |
string | Provider key: 'NUMISTA', 'METALS_DEV', 'METALS_API', 'METAL_PRICE_API', 'CUSTOM' |
- Source:
switchSettingsSection(name)
Switches the visible section panel in the Settings modal.
Parameters:
| Name | Type | Description |
|---|---|---|
name |
string | Section key: 'site', 'system', 'table', 'grouping', 'api', 'cloud', 'images', 'storage', 'goldback', 'changelog' |
- Source:
(async) syncAllProviders() → {Promise.<number>}
Triggers a background sync across all providers.
Returns:
Total number of prices updated
- Type
- Promise.<number>
syncChipToggle(elementId, isOn)
Syncs a chip-sort-toggle's active state from a boolean value.
Parameters:
| Name | Type | Description |
|---|---|---|
elementId |
string | DOM id of the .chip-sort-toggle container |
isOn |
boolean | Whether the 'yes' button should be active |
- Source:
syncCurrencySettingsUI()
Syncs the display currency dropdown with current state (STACK-50). Populates options from SUPPORTED_CURRENCIES on first call.
- Source:
syncGoldbackSettingsUI()
Syncs the Goldback settings panel UI with current state. Renders denomination price rows and updates enabled toggle.
- Source:
syncHasLocalChanges() → {boolean}
Determine whether we have local unpushed changes. We consider local "dirty" if our last push was more recent than our last pull (meaning we've pushed something that predates the remote change, so both sides have diverged independently).
- Source:
Returns:
- Type
- boolean
syncHeaderToggleUI()
Syncs the header shortcut checkboxes in Settings with stored state.
- Source:
syncLayoutVisibilityUI()
Syncs layout section config table in Settings and applies layout order.
- Source:
(async) syncProviderChain(options) → {Promise.<{results: Object, updatedCount: number, anySucceeded: boolean}>}
Core engine that iterates through configured API providers in priority order. Respects sync modes ('always' vs 'backup') and handles cascading failover.
Parameters:
| Name | Type | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Properties
|
Returns:
Sync operation summary
- Type
- Promise.<{results: Object, updatedCount: number, anySucceeded: boolean}>
syncProviderPriorityUI(priorities)
Sets all priority
Parameters:
| Name | Type | Description |
|---|---|---|
priorities |
Object | { METALS_DEV: 1, ... } |
- Source:
(async) syncRestoreOverrideBackup()
Restore the pre-pull local snapshot saved by syncSaveOverrideBackup(). Prompts for confirmation, writes raw strings back, and refreshes the UI.
- Source:
syncSaveOverrideBackup()
Snapshot all SYNC_SCOPE_KEYS raw localStorage strings into a single JSON blob. Called immediately before vaultDecryptAndRestore() in pullSyncVault().
- Source:
syncSettingsUI()
Syncs all Settings UI controls with current application state. Called each time the modal opens to ensure controls reflect live values.
- Source:
(async) syncSpotPricesFromApi(showProgressopt, forceSyncopt) → {Promise.<boolean>}
Initiates the spot price synchronization process across all configured providers. Handles user interaction, cache validation prompts, and UI status updates.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
showProgress |
boolean |
<optional> |
true | Whether to display alerts and progress UI |
forceSync |
boolean |
<optional> |
false | If true, ignores the local cache and forces API calls |
Returns:
True if at least one provider successfully synced prices
- Type
- Promise.<boolean>
(async) testApiConnection(provider, apiKey) → {Promise.<boolean>}
Validates an API provider's connectivity by making a lightweight test request. Usually attempts to fetch a single metal's price (e.g., silver) to verify the key.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
apiKey |
string | The API key to be tested |
Returns:
True if the connection test was successful
- Type
- Promise.<boolean>
todayStr() → {string}
Returns current date as ISO string (YYYY-MM-DD)
Returns:
Current date in ISO format
- Type
- string
toggleChange(logIdx)
Toggles a logged change between undone and redone states
Parameters:
| Name | Type | Description |
|---|---|---|
logIdx |
number | Index of change entry in changeLog array |
- Source:
toggleCurrencyDropdown()
Toggles the floating currency picker dropdown anchored to the header button. Creates the dropdown lazily on first use; subsequent calls toggle visibility.
- Source:
toggleGlobalPriceView()
Legacy function kept for compatibility - no longer used
Market value now has its own dedicated column
- Source:
togglePriceView()
Legacy function kept for compatibility - no longer used Market value now has its own dedicated column
- Source:
toggleTheme()
Cycles through available themes: dark → light → sepia → dark
toggleVaultPasswordVisibility(inputId, toggleBtn)
Toggle password visibility for a field.
Parameters:
| Name | Type | Description |
|---|---|---|
inputId |
string | |
toggleBtn |
HTMLElement |
tokenizeWords(str, caseSensitiveopt) → {Array.<string>}
Tokenize a string into individual words
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
str |
string | Input string |
||
caseSensitive |
boolean |
<optional> |
false | Preserve case if true |
- Source:
Returns:
Array of words
- Type
- Array.<string>
(async) updateAllSparklines()
Refreshes sparklines on all 4 metal cards concurrently
updateCardSortBar()
Updates the card sort bar UI to reflect current sort state and card style. Called from renderTable() whenever card view (A/B/C) is active. For D mode, _syncSortBar handles everything via MutationObserver.
- Source:
updateCardSortBar()
Updates the card sort bar UI to reflect current sort state and card style. Called from renderTable() whenever card view (A/B/C) is active. For D mode, _syncSortBar handles everything via MutationObserver.
- Source:
updateColumnVisibility()
Updates column visibility based on current viewport width
updateFuzzyIndicator(query, show)
Show or hide the fuzzy search indicator banner. Displayed when exact search returns 0 results but fuzzy returns > 0.
Parameters:
| Name | Type | Description |
|---|---|---|
query |
string | The search query that triggered fuzzy matching |
show |
boolean | Whether to show or hide the indicator |
updateHistoryPullCost(provider)
Updates the visual cost indicator for a history pull from a given provider. Displays total API calls or file fetches expected based on current settings.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
updateItemCount(filteredCount, totalCount)
Updates the displayed inventory item count based on active filters
Parameters:
| Name | Type | Description |
|---|---|---|
filteredCount |
number | Items matching current filters |
totalCount |
number | Total items in inventory |
- Source:
updateLastTimestamps(source, provider, timestamp)
Stores last cache refresh and API sync timestamps
Parameters:
| Name | Type | Description |
|---|---|---|
source |
string | Source of spot price ('api' or 'cached') |
provider |
string | null | Provider name if available |
timestamp |
string | ISO timestamp of the event |
updateManualSpot(metalKey)
Updates spot price for specified metal from user input
Parameters:
| Name | Type | Description |
|---|---|---|
metalKey |
string | Key of metal to update ('silver', 'gold', 'platinum', 'palladium') |
updateMatchIndicator(password, confirm)
Update the password match indicator.
Parameters:
| Name | Type | Description |
|---|---|---|
password |
string | |
confirm |
string |
updateModalCurrencyUI()
Updates the add/edit modal's currency symbols and placeholders (STACK-50) Sets the CSS custom property --currency-symbol on .currency-input wrappers and updates input placeholders with the current currency code.
updatePortalHeight()
Updates the max-height of .table-section to show exactly itemsPerPage rows.
Measures actual rendered heights (thead + first row) so it adapts to font
scaling, browser zoom, and responsive breakpoints.
If all rows fit within the computed height, max-height is removed to avoid an unnecessary scrollbar.
Called by renderTable() after rows are inserted into the DOM.
- Source:
updateProviderHistoryTables()
Renders the API usage/quota visualization (progress bars) for each provider. Displays usage vs quota and handles clicks for quota adjustment modals.
updateProviderSettings(provider)
Updates persistent provider settings (like cache duration) from form inputs. Persists the updated configuration to localStorage.
Parameters:
| Name | Type | Description |
|---|---|---|
provider |
string | The unique key of the API provider |
updateSaveSearchButton(query, fuzzyUsedopt)
Updates the visibility of the "Save Search" button based on the query.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
query |
string | The search query string |
||
fuzzyUsed |
boolean |
<optional> |
false | Whether fuzzy matching was active |
(async) updateSettingsFooter()
Updates the storage + version footer bar at the bottom of the Settings modal.
- Source:
(async) updateSparkline(metalKey)
Renders or updates a sparkline chart for a single metal card. For ranges >180 days, fetches historical year files asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
metalKey |
string | Metal key ('silver', 'gold', etc.) |
updateSpotCardColor(metalKey, newPrice)
Updates spot card color based on price movement compared to last history entry
Parameters:
| Name | Type | Description |
|---|---|---|
metalKey |
string | Metal key ('silver', 'gold', etc.) |
newPrice |
number | Newly set spot price |
updateSpotChangePercent(metalKey, precomputedDataopt)
Computes and displays % change on a spot card based on the selected sparkline period. Compares oldest vs newest data point in the selected range.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
metalKey |
string | Metal key ('silver', 'gold', etc.) |
||
precomputedData |
Array.<number> | null |
<optional> |
null | Pre-fetched data array from updateSparkline (avoids redundant re-fetch for historical ranges). When null, uses sync getSparklineData(). |
updateSpotTimestamp(metalName)
Updates spot timestamp element with toggle between cache refresh and API sync times
Parameters:
| Name | Type | Description |
|---|---|---|
metalName |
string | Metal name ('Silver', 'Gold', 'Platinum', 'Palladium') |
updateStatusCell(catalogId, text, color)
Updates a status cell in the eligible items table for live feedback.
Parameters:
| Name | Type | Description |
|---|---|---|
catalogId |
string | |
text |
string | |
color |
string | CSS color value |
- Source:
(async) updateStorageStats()
Updates footer with localStorage usage statistics and visual usage indicator
updateStrengthBar(password)
Update the password strength bar.
Parameters:
| Name | Type | Description |
|---|---|---|
password |
string |
updateSummary()
Calculates and updates all financial summary displays across the application
- Source:
updateSyncButtonStates(syncing)
Updates sync button states based on API availability
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
syncing |
boolean | false | Whether sync is in progress |
updateSyncStatusIndicator(state, detailopt)
Update the auto-sync status indicator in the Settings UI.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
state |
'idle' | 'syncing' | 'error' | 'disabled' | ||
detail |
string |
<optional> |
optional status text (e.g. "Just now", error message) |
- Source:
updateThemeButton()
Sets up theme toggle event listeners
useSpotPrice(spotPrice, timestamp)
Uses a selected spot price from the lookup modal. Sets the hidden itemSpotPrice field and closes the modal.
Parameters:
| Name | Type | Description |
|---|---|---|
spotPrice |
number | The selected spot price |
timestamp |
string | Timestamp of the selected entry (for reference) |
- Source:
validateFieldValue(field, value) → {boolean}
Enhanced validation for inline edits with comprehensive field support
Parameters:
| Name | Type | Description |
|---|---|---|
field |
string | Field being edited |
value |
string | Proposed value |
- Source:
Returns:
Whether value is valid
- Type
- boolean
validateInventoryItem(item) → {Object}
Validates inventory item data
Parameters:
| Name | Type | Description |
|---|---|---|
item |
Object | Inventory item to validate |
Returns:
Validation result with isValid flag and errors array
- Type
- Object
validateItemFields(f) → {string|null}
Validates mandatory item fields.
Parameters:
| Name | Type | Description |
|---|---|---|
f |
Object | Parsed fields from parseItemFormFields() |
Returns:
Error message or null if valid
- Type
- string | null
(async) vaultDecrypt(ciphertext, key, iv) → {Promise.<Uint8Array>}
Decrypt ciphertext with AES-256-GCM.
Parameters:
| Name | Type | Description |
|---|---|---|
ciphertext |
Uint8Array | ciphertext + 16-byte auth tag |
key |
CryptoKey | string | |
iv |
Uint8Array | 12-byte nonce |
Throws:
-
On wrong password or corrupted data (GCM auth tag mismatch)
- Type
- Error
Returns:
plaintext
- Type
- Promise.<Uint8Array>
(async) vaultDecryptAndRestore(fileBytes, password) → {Promise.<void>}
Decrypt raw vault bytes with the given password and restore data.
Parameters:
| Name | Type | Description |
|---|---|---|
fileBytes |
Uint8Array | ArrayBuffer | |
password |
string |
Returns:
- Type
- Promise.<void>
(async) vaultDeriveKey(password, salt, iterations) → {Promise.<(CryptoKey|string)>}
Derive AES-256 key from password using PBKDF2.
Parameters:
| Name | Type | Description |
|---|---|---|
password |
string | |
salt |
Uint8Array | 32-byte salt |
iterations |
number |
Returns:
Native CryptoKey or forge key bytes
- Type
- Promise.<(CryptoKey|string)>
(async) vaultEncrypt(plaintext, key, iv) → {Promise.<Uint8Array>}
Encrypt plaintext with AES-256-GCM.
Parameters:
| Name | Type | Description |
|---|---|---|
plaintext |
Uint8Array | |
key |
CryptoKey | string | |
iv |
Uint8Array | 12-byte nonce |
Returns:
ciphertext + 16-byte auth tag
- Type
- Promise.<Uint8Array>
(async) vaultEncryptToBytes(password) → {Promise.<Uint8Array>}
Encrypt inventory data with the given password and return raw vault bytes.
Parameters:
| Name | Type | Description |
|---|---|---|
password |
string |
Returns:
serialized vault file bytes
- Type
- Promise.<Uint8Array>
(async) vaultEncryptToBytesScoped(password) → {Promise.<Uint8Array>}
Encrypt sync-scoped data (inventory + display prefs only) and return raw vault bytes. Used by cloud auto-sync to avoid pushing API keys or cloud tokens to remote storage.
Parameters:
| Name | Type | Description |
|---|---|---|
password |
string |
Returns:
serialized vault file bytes
- Type
- Promise.<Uint8Array>
vaultRandomBytes(length) → {Uint8Array}
Generate cryptographically random bytes.
Parameters:
| Name | Type | Description |
|---|---|---|
length |
number |
Returns:
- Type
- Uint8Array
(async) verifyPcgsCert(certNumber) → {Promise.<Object>}
Verify a PCGS certification number via the PCGS Public API.
Parameters:
| Name | Type | Description |
|---|---|---|
certNumber |
string | PCGS certification number to verify |
- Source:
Returns:
Verification result with coin details
- Type
- Promise.<Object>
wireChipSortToggle(elementId, syncIdopt)
Wires a chip sort order toggle (alpha/count) with bidirectional sync.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
elementId |
string | DOM id of the toggle container |
|
syncId |
string |
<optional> |
DOM id of a mirror toggle to keep in sync |
- Source:
wireFeatureFlagToggle(elementId, flagName, optsopt)
Wires a yes/no chip toggle to a feature flag. Handles click delegation, flag enable/disable, active-class sync, optional mirror element sync, and optional callback.
Parameters:
| Name | Type | Attributes | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
elementId |
string | DOM id of the toggle container |
|||||||||||||
flagName |
string | Feature flag key (e.g. 'GROUPED_NAME_CHIPS') |
|||||||||||||
opts |
Object |
<optional> |
Properties
|
- Source:
wireStorageToggle(elementId, storageKey, optsopt)
Wires a yes/no chip toggle to a raw localStorage key (not a feature flag). Handles click delegation, localStorage read/write, active-class sync, and optional callback.
Parameters:
| Name | Type | Attributes | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
elementId |
string | DOM id of the toggle container |
||||||||||||||||
storageKey |
string | localStorage key to read/write ('true'/'false') |
||||||||||||||||
opts |
Object |
<optional> |
Properties
|
- Source:
xhrLoadJSON(url) → {Promise.<any>}
Loads a local JSON file via XMLHttpRequest (sync-free). Broader file:// compatibility than fetch() — works in Firefox/Safari and Chrome with --allow-file-access-from-files.
Parameters:
| Name | Type | Description |
|---|---|---|
url |
string | Relative or absolute URL to JSON file |
Returns:
Parsed JSON
- Type
- Promise.<any>
Type Definitions
ApiConfig
Type:
- Object
Properties:
| Name | Type | Attributes | Description |
|---|---|---|---|
provider |
string | Currently selected provider key |
|
keys |
Object.<string, string> | API keys for different providers |
|
usage |
Object |
<optional> |
Usage tracking |
ApiProviderConfig
Type:
- Object
Properties:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
string | Display name for the provider |
|
baseUrl |
string | Base API endpoint URL |
|
endpoints |
Object.<string, string> | API endpoints for different metals |
|
parseResponse |
function | Function to parse API response into standard format |
|
documentation |
string | URL to provider's API documentation |
|
batchSupported |
boolean | Whether provider supports batch requests |
|
batchEndpoint |
string |
<optional> |
Batch request endpoint pattern |
parseBatchResponse |
function |
<optional> |
Function to parse batch API response |
requiresKey |
boolean |
<optional> |
Whether an API key is required |
CsvMappingRules
Type:
- Object
Properties:
| Name | Type | Attributes | Description |
|---|---|---|---|
columnMap |
Object.<string, string> | Mapping of CSV columns to internal item properties |
|
ignoredColumns |
Array.<string> |
<optional> |
Columns to ignore during import |
DomElements
Type:
- Object
Properties:
| Name | Type | Description |
|---|---|---|
spotPriceDisplay |
Object | Spot price display elements |
spotSyncIcon |
Object | Spot sync icon elements |
inventoryForm |
HTMLElement | Main inventory form |
inventoryTable |
HTMLElement | Main inventory table |
itemMetal |
HTMLElement | Metal select field |
itemName |
HTMLElement | Name input field |
itemQty |
HTMLElement | Quantity input field |
itemType |
HTMLElement | Type input field |
itemWeight |
HTMLElement | Weight input field |
itemWeightUnit |
HTMLElement | Weight unit select field |
itemPrice |
HTMLElement | Price input field |
itemDate |
HTMLElement | Date input field |
searchInput |
HTMLElement | Search input field |
typeFilter |
HTMLElement | Type filter select field |
metalFilter |
HTMLElement | Metal filter select field |
totals |
Object | Totals display elements organized by metal |
FilterConfig
Type:
- Object
Properties:
| Name | Type | Attributes | Description |
|---|---|---|---|
metal |
string |
<optional> |
Metal filter |
type |
string |
<optional> |
Type filter |
search |
string |
<optional> |
Search query |
InventoryItem
Type:
- Object
Properties:
| Name | Type | Attributes | Description |
|---|---|---|---|
metal |
string | Metal type (Silver, Gold, Platinum, Palladium) |
|
composition |
string |
<optional> |
Composition (Gold, Silver, Platinum, Palladium, Alloy) |
name |
string | Display name of the item |
|
qty |
number | Quantity of items |
|
type |
string | Item type (Coin, Round, Bar, etc.) |
|
weight |
number | Weight per item |
|
weightUnit |
string |
<optional> |
Weight unit (oz, g, kg, etc.) |
purity |
number |
<optional> |
Purity (0.0 to 1.0) |
price |
number | Purchase price per item |
|
date |
string | Purchase date (YYYY-MM-DD) |
|
purchaseLocation |
string |
<optional> |
Where the item was purchased |
storageLocation |
string |
<optional> |
Where the item is stored |
notes |
string |
<optional> |
User notes |
spotPriceAtPurchase |
number |
<optional> |
Spot price at time of purchase |
premiumPerOz |
number |
<optional> |
Premium paid per ounce |
totalPremium |
number |
<optional> |
Total premium paid for all units |
marketValue |
number |
<optional> |
Current market value (calculated or manual override) |
numistaId |
string |
<optional> |
Numista ID for lookup |
year |
string |
<optional> |
Year of issue |
grade |
string |
<optional> |
Item grade |
gradingAuthority |
string |
<optional> |
Grading authority (PCGS, NGC, etc.) |
certNumber |
string |
<optional> |
Certification number |
serialNumber |
string |
<optional> |
Serial number |
pcgsNumber |
string |
<optional> |
PCGS number for lookup |
pcgsVerified |
boolean |
<optional> |
Whether PCGS data has been verified |
serial |
string |
<optional> |
Original serial number string from import |
uuid |
string | Unique identifier for the item |
|
obverseImageUrl |
string |
<optional> |
URL for obverse image |
reverseImageUrl |
string |
<optional> |
URL for reverse image |
collectable |
boolean |
<optional> |
Whether item is marked as collectable |
LookupTable
Lookup table data structure for autocomplete suggestions
Type:
- Object
Properties:
| Name | Type | Description |
|---|---|---|
names |
Array.<string> | Unique item names from inventory |
purchaseLocations |
Array.<string> | Unique purchase locations |
storageLocations |
Array.<string> | Unique storage locations |
types |
Array.<string> | Unique item types |
abbreviations |
Object | Common abbreviations and expansions |
lastUpdated |
number | Timestamp of last update |
itemCount |
number | Number of inventory items used to generate table |
- Source:
MappingRule
Type:
- Object
Properties:
| Name | Type | Description |
|---|---|---|
regex |
RegExp | Pattern to match against field names |
field |
string | Target field identifier |
- Source:
SpotHistoryEntry
Type:
- Object
Properties:
| Name | Type | Description |
|---|---|---|
spot |
number | Spot price |
metal |
string | Metal name (Gold, Silver, Platinum, Palladium) |
source |
string | Data source (e.g., 'seed', 'api') |
provider |
string | Data provider (e.g., 'LBMA', 'Metals.dev') |
timestamp |
string | UTC timestamp (YYYY-MM-DD HH:mm:ss or ISO) |