Author: Mark

  • Fulfillment – Daily Changelog – October 29, 2025

    Fulfillment – Daily Changelog – October 29, 2025

    Changelog – October 29, 2025

    🚀 New Features & Improvements

    Raffle Sticker Batch Page Enhancements

    • Visual Order Grouping: Split domestic orders into two distinct sections on raffle sticker batch page
    • “Single Sticker Orders” section for orders with exactly 1 sticker
    • “Multiple Sticker Orders” section for orders with 2+ stickers
    • Each section shows order count and total sticker count for easy packing workflow
    • Color-Coded Quantity Badges: Added brand-approved color-coded badges to quantity display
    • Single sticker (1): Gray – subtle, low priority
    • 2-5 stickers: Green – moderate attention
    • 6-10 stickers: Blue – higher attention
    • 11+ stickers: Primary gold – highest attention
    • Section-Specific Selection: Each order group has its own “Select All” checkbox while maintaining global selection functionality
    • Packing Workflow Optimization: Visual grouping makes it easier to prepare packages by quantity, improving packing efficiency

    4×6 Packing Label Enhancements

    • Multiple Quantity Badge: Added prominent visual indicator on 4×6 packing labels for orders with more than 1 sticker
    • Black badge displaying “X STICKERS” appears in header area next to order number
    • Only shows when quantity > 1 to draw attention to multi-sticker orders
    • Prevents packing errors by making quantity immediately apparent
    • Label Generation Updates: Modified both production and debug label routes to calculate and display total quantity
    • Updated label header layout to accommodate badge
    • Bold, high-contrast styling ensures visibility during physical packing

    Avery Packing Label Enhancements (5160 & 5167)

    • Quantity Badge on Sticky Labels: Added visual quantity badges to Avery label formats for multi-item orders
    • Displays total item quantity (e.g., “3”) in a bold black badge next to order number
    • Works on both Avery 5160 (30 labels/sheet) and Avery 5167 (80 labels/sheet) formats
    • Compact sizing optimized for small label dimensions
    • Only appears when order has more than 1 item
    • Order Picking Optimization: Helps employees quickly identify orders requiring multiple items during pick/pack operations
    • High-contrast black badge with white text for instant visibility
    • Positioned next to order number in flexible layout
    • Scales appropriately for compact (5167) vs standard (5160) label sizes

    🔧 Technical Improvements

    Frontend Components

    • src/app/(authenticated)/batches/[id]/raffle-page.tsx:
    • Added useMemo hook to group domestic orders by quantity
    • Created getQuantityBadgeColor helper function for color-coded badges
    • Created renderOrderRow helper function to DRY up order table rendering
    • Split single orders table into two sections with independent selection logic
    • Updated selection handlers to work across both order groups

    API Route Updates

    • src/app/api/orders/labels-4x6/route.ts: Added quantity badge logic to production 4×6 label generation
    • src/app/api/orders/labels-4x6/debug/route.ts: Added quantity badge logic to debug 4×6 label generation
    • Calculate total quantity across all line items
    • Conditionally render badge HTML when quantity > 1
    • Updated CSS to style badge with high visibility
    • src/app/api/orders/labels/route.ts: Added quantity badge support for Avery label formats (5160 & 5167)
    • Added .order-with-badge and .qty-badge CSS classes
    • Implemented flexible layout to accommodate badge next to order number
    • Responsive sizing for both compact (5167) and standard (5160) formats
    • Uses existing itemCount field which contains total quantity sum

    Styling Updates

    • Added .order-info CSS class for flexible layout of order number and badge
    • Added .qty-badge CSS class with bold styling (black background, white text, increased letter-spacing)
    • Updated header alignment from align-items: baseline to align-items: flex-start for proper badge positioning

    🎯 User Experience Improvements

    • Packing Efficiency: Visual separation of single vs. multiple sticker orders streamlines the physical packing process
    • Error Prevention: Prominent quantity badges on labels reduce risk of packing incorrect number of stickers
    • Quick Identification: Color-coded badges allow instant recognition of order complexity at a glance
    • Workflow Preservation: All existing functionality (send to ShippingEasy, bulk operations) remains unchanged

    Files Modified: 4
    Major Features Added: Order quantity grouping, visual quantity badges on all label types (4×6 packing lists & Avery sticky labels)
    Focus: Packing workflow optimization and error prevention for physical fulfillment operations

    🖨️ Packing Lists Overhaul (Batches)

    • Fixed print layout to hide all app UI (nav, sidebar, submenus) and only render packing lists
    • Ensured one page per order with reliable page breaks and no blank pages
    • Added manual Print button plus auto-print after data load
    • Added professional header:
    • Mama Tried logo and business address (4188 S. Kinnickinnic Ave., St Francis, WI 53235)
    • Moved order number and date to top-right; removed duplicate “#” prefix
    • Removed unused icon import to satisfy lint and unblock deploy

    Files:

    • src/app/(authenticated)/batches/[id]/packing-lists/page.tsx
    • src/app/api/batches/[id]/bulk-packing-lists/route.ts
    • src/app/api/batches/[id]/packing-list/route.ts

    🧰 Database Transaction Leak Remediation (Critical)

    • Audited and fixed transaction handling across 24+ API routes (29 transactions)
    • Replaced db.query('BEGIN'|'COMMIT'|'ROLLBACK') with per-request client via db.connect()
    • Added finally { client.release() } and 10s statement timeout on transactions
    • Resolved pool exhaustion that previously froze the app under load

    Representative routes fixed (subset):

    • orders/[id]/create-reprint, orders/fix-line-items
    • products/* (tags, files, production-files, display-files, toggle-pod, placement-preview)
    • warehouse-items/*, warehouse-inventory/* (transfer, move, reserve, import, pod)
    • navbar/*, available-pages, settings/batch-stages, price-*, roles/*, users/public-pages, art-file-previews

    📦 Warehouse & POD Inventory Improvements

    • Added POD inventory endpoints and UI dialogs
    • Introduced migration for POD blank inventory
    • Fixed lint in inventory dialogs to allow deployment

    Files:

    • database_migrations/add_pod_blank_inventory.sql
    • src/app/api/warehouse-inventory/pod/route.ts
    • src/components/warehouse-inventory/{pod-inventory-view,adjust-pod-inventory-dialog,pod-blank-item-dialog}.tsx

    🛍️ Shopify Product Metadata Sync in Order Processing

    • Added metadata sync from Shopify during order import to improve product classification
    • Order processing now continues even if metadata sync fails (better resilience)

    Files:

    • src/lib/orderUtils.ts
    • ORDER_TYPE_FIX.md

    🔤 New Supporting APIs

    • Added sizes API route to support inventory/product flows

    Files:

    • src/app/api/sizes/route.ts
  • Fulfillment – Daily Changelog – October 28, 2025

    Fulfillment – Daily Changelog – October 28, 2025

    Changelog – October 28, 2025

    POD Category Inventory System Implementation

    Overview

    Implemented a comprehensive Print on Demand (POD) inventory system that tracks blank garments by category or specific style. This allows for flexible inventory management where POD inventory is separate from regular blank inventory, enabling better tracking for print-on-demand orders.

    Database Changes

    1. New Migration: add_pod_blank_inventory.sql

    • Added blank_category_id column to warehouse_items table
    • Added new item type 'pod_blank' to warehouse items
    • Created database views:
    • v_pod_category_inventory – Aggregated POD inventory by category
    • v_pod_style_inventory – POD inventory for style-specific items
    • Added indexes for performance optimization
    • Warehouse items can now have either garment_id (specific style) OR blank_category_id (category-based)

    TypeScript Type Updates

    Updated src/types/warehouse-inventory.ts

    • Added 'pod_blank' to WarehouseItemType enum
    • Added blank_category_id field to WarehouseItem interface
    • Added category relation type for warehouse items
    • Created new POD-specific types:
    • PODCategoryInventory – Category-based inventory with size aggregation
    • PODStyleInventory – Style-specific inventory with size breakdown
    • PODInventoryResponse – API response structure for POD inventory

    Backend API Changes

    1. Updated src/app/api/warehouse-inventory/route.ts

    • Modified queries to include blank_category_id field
    • Added joins with blank_categories table
    • Updated response mapping to include category information
    • All warehouse inventory queries now return category data when applicable

    2. New API Endpoint: src/app/api/warehouse-inventory/pod/route.ts

    • GET /api/warehouse-inventory/pod – Fetches POD blanks with category aggregation
    • Returns separate arrays for category-based and style-specific inventory
    • Aggregates quantities by size across all styles in a category
    • Supports filtering by storage location

    3. Updated src/app/api/products/[id]/route.ts

    • Modified GET endpoint to join with blank_categories table
    • Returns category information in product data
    • Updated both initial fetch and PATCH update queries
    • Category data now available at product level

    Frontend Components

    1. Updated Product Cards

    Files: src/components/products/product-card.tsx, src/components/products/product-wide-card-view.tsx

    • Products using categories now display:
    • “Category” badge
    • Category name instead of individual styles
    • Category color information
    • Falls back to showing individual styles if no category is set

    2. Product Details Section

    File: src/components/products/product-sections/product-details.tsx

    • Already had category selection UI
    • Now properly displays selected category
    • Shows styles within the category with preference ranking

    3. New POD Inventory Page

    File: src/components/warehouse-inventory/pod-inventory-view.tsx

    • Dedicated view for POD inventory
    • Features:
    • Sub-tabs for “Blanks” and “Transfers”
    • Two separate inventory tables:
      • Category Inventory Table: Aggregates quantities across all styles in each category
      • Style-Specific Inventory Table: Shows POD items with specific style assignments
    • Size-based matrix view
    • Expandable rows to see contributing warehouse items
    • “Add POD Item” button

    4. New POD Blank Item Dialog

    File: src/components/warehouse-inventory/pod-blank-item-dialog.tsx

    • Create POD blank inventory items with full size/quantity support
    • Two selection modes:
    • Category Mode: Select a blank category (any style from category can be used)
    • Style Mode: Select specific style + color
    • Auto-generates item names based on selection
    • Size & Quantity Selector:
    • Automatically filters sizes based on category/style size category
    • Checkbox interface for selecting sizes
    • Quantity input for each selected size
    • Creates warehouse_item_variants and warehouse_variant_inventory records
    • Supports:
    • Category or style selection
    • Multiple sizes with quantities
    • Storage location assignment (required)
    • Description and notes
    • Name customization

    5. Updated Warehouse Inventory Page

    File: src/app/(authenticated)/warehouse-inventory/page.tsx

    • Added new “Print on Demand” tab between “Blank Garment Inventory” and “Staging Inventory”
    • Loads PODInventoryView component

    Features Implemented

    1. Category-Based Inventory Tracking
    • Warehouse items can be linked to blank categories instead of specific styles
    • System aggregates quantities across all styles in a category
    • Flexible for situations where any style from a category can fulfill an order
    1. Style-Specific POD Inventory
    • Still supports tracking specific style+color combinations
    • Useful for POD items that must use a particular garment
    1. Product Category Display
    • Products using categories show this clearly on product cards
    • Category name and color displayed prominently
    • No longer shows confusing “No styles assigned” when category is set
    1. Dedicated POD Tab
    • Separate inventory view specifically for POD items
    • Clean separation from regular blank inventory
    • Easy to see what’s available for POD orders
    1. Add POD Items
    • Comprehensive dialog for adding new POD inventory
    • Choose between category or style-specific
    • Select multiple sizes and enter quantities
    • Auto-naming for consistency
    • One-step process to create item with inventory

    Database Schema Summary

    -- New column
    ALTER TABLE warehouse_items 
    ADD COLUMN blank_category_id INTEGER REFERENCES blank_categories(id);
    
    -- New item type
    warehouse_items.item_type: 'pod_blank'
    
    -- New views
    v_pod_category_inventory
    v_pod_style_inventory

    Next Steps (Not Implemented Yet)

    1. Work Order Integration
    • Automatic inventory deduction when work orders are created
    • Style selection based on preference rank and availability
    1. Transfers Integration
    • Link transfers to POD inventory
    • Show POD transfers in the Transfers sub-tab
    1. Inventory Import
    • Update warehouse import dialog to support pod_blank type
    • CSV import with category references
    1. Bulk Adjustment
    • Allow editing quantities for existing POD items
    • Support transferring between storage locations
    1. Testing
    • Create test POD inventory items
    • Verify category display on product cards
    • Test POD inventory views and aggregation

    Recent Update: Size & Quantity Selector

    Enhanced the POD Blank Item Dialog to include a comprehensive size and quantity selector:

    • Smart Size Filtering: Automatically shows only relevant sizes based on the selected category or style’s size category
    • Checkbox Selection: Clean interface for selecting which sizes to add
    • Inline Quantity Entry: Enter quantities directly for each selected size
    • Multi-Size Creation: Creates all warehouse variants and inventory records in one transaction
    • Validation: Requires at least one size to be selected and a storage location
    • Smart Defaults: Storage location automatically defaults to “Print on Demand Supply” location

    Bug Fixes:

    1. Created missing /api/sizes endpoint that was preventing the size selector from loading. The endpoint fetches all sizes from the database, ordered by size category and display order.
    2. Updated /api/warehouse-items POST endpoint to include blank_category_id in the INSERT statement, fixing the “INSERT has more target columns than expressions” error.
    3. Enhanced /api/warehouse-items POST endpoint to handle multiple sizes at once – when a sizes array is provided, it creates warehouse_item_variants and warehouse_variant_inventory records for each size in a single transaction.
    4. Updated POD blank item dialog mutation to send sizes array to the API instead of trying to call non-existent variant/inventory endpoints.
    5. Fixed duplicate key constraint violation by appending size name to variant_name (e.g., “POD – 50/50 Medium Black T-Shirt – S”) to ensure uniqueness across multiple size variants.

    This completes the POD item creation workflow – you can now add fully-functional POD inventory items with sizes and quantities in one step!

    POD Inventory Management Features

    Incremental Inventory Addition:

    • POD items now work like real inventory – you can add stock incrementally to the same item
    • When adding inventory for a category/style that already exists, the system:
    1. Finds the existing warehouse item for that category/style+color
    2. Adds new sizes as variants if they don’t exist
    3. Updates quantities for existing sizes (adds to current stock)
    • Example workflow:
    • First time: Add 3 Small → creates “POD – 50/50 Medium Black T-Shirt” with 3 S
    • Later: Add 6 Large → adds to the same item, now has 3 S and 6 L
    • Later: Add 2 more Small → updates to 5 S and 6 L
    • No more duplicate warehouse items for the same category!

    Adjust Inventory & Delete POD Items:

    • Added Edit and Delete buttons to each warehouse item in the POD inventory view
    • Click the chevron next to a category row to expand and see contributing warehouse items
    • Each item shows an Edit button (pencil icon) and Delete button (trash icon)

    Edit/Adjust Inventory:

    • Opens a visual inventory adjustment dialog
    • Shows current quantities for all sizes in a grid layout
    • Adjust quantities with:
    • + / – buttons for quick adjustments
    • Direct input to set exact adjustment amounts
    • Visual preview showing: Current → Adjustment → New Total
    • Supports adding new sizes (enter positive number for sizes with 0 qty)
    • Supports reducing quantities (enter negative numbers, can’t go below 0)
    • Batch apply all changes at once
    • Real-time validation prevents negative quantities
    • Changes are highlighted in green (additions) or red (reductions)

    Delete Items:

    • Delete button performs force deletion – removes the warehouse item AND all associated inventory:
    • Deletes all warehouse_item_variants
    • Deletes all warehouse_variant_inventory records
    • Deletes warehouse_inventory aggregates
    • Shows detailed confirmation dialog before deletion
    • Perfect for cleaning up duplicate items or removing discontinued POD items
    • API supports ?force=true parameter to cascade delete all related records

    Notes

    • Regular blank inventory remains unchanged and separate
    • Work order inventory deduction will be implemented in a future phase
    • POD items are fully functional with complete size/quantity management
    • Color is determined by the category (for category-based items) or the selected style color (for style-specific items)
  • Fulfillment – Daily Changelog – October 27, 2025

    Fulfillment – Daily Changelog – October 27, 2025

    Changelog – October 27, 2025

    🐛 Critical Bug Fix

    Order Type Filtering System Fixed

    • Problem Identified: Order type filtering on orders page was not working correctly
    • Filters showed no results even when matching orders existed
    • Found 9 orders (4 pending, 5 invoiced) missing order_type_id values
    • LEFT JOIN to order_types table returned NULL for orders without type assignment
    • Filter query looking for ot.slug = 'print-on-demand' couldn’t match NULL values

    Solution Implemented

    • Bulk Order Type Assignment: Ran scripts/assign-order-types.js to fix missing order types
    • Analyzed line items for each order to determine correct type
    • Successfully assigned types to all 9 orders:
      • 1 print-on-demand order (#5480)
      • 7 raffle-sticker orders
      • 1 pod-raffle order (mixed POD + raffle sticker)
    • Database Verification: Confirmed all orders now have order_type_id populated
    • 0 orders remaining without order types
    • Filtering now works correctly for all order type combinations

    System Verification

    • Automatic Assignment Confirmed: Verified that new orders automatically get order types assigned
    • Both Shopify orders and manual orders call assignOrderType() on creation
    • Future orders will not experience this issue
    • Filter Testing: Confirmed filtering by “Pending” + “Print-on-demand” now correctly shows order #5480

    🔍 Investigation & Analysis

    Database Query Analysis

    • SQL Filter Logic: Examined order filtering logic in /api/orders route
    • Filter correctly implemented using ot.slug = $N parameter
    • Issue was missing data, not broken code
    • Order Type Structure: Reviewed order_types table and relationships
    • Migration 027 added order_type_id to mama_tried_orders
    • Order types: print-on-demand, inventory, raffle-sticker, pod-raffle, mixed, external

    Root Cause

    • Missing Migration: Some orders created before or during migration didn’t get order types assigned
    • Gaps in Automatic Assignment: While auto-assignment exists, some orders slipped through
    • Data Integrity: No mechanism to detect or alert on missing order types

    🎯 Technical Details

    Database Changes

    -- Before Fix
    SELECT COUNT(*) as orders_without_type 
    FROM mama_tried_orders 
    WHERE order_type_id IS NULL;
    -- Result: 9 orders
    
    -- After Fix  
    SELECT COUNT(*) as orders_without_type 
    FROM mama_tried_orders 
    WHERE order_type_id IS NULL;
    -- Result: 0 orders

    Order Type Assignments

    • Order #5480 (Scott Coffey): print-on-demand
    • Order #5479 (Randy Gonzalez): raffle-sticker
    • Order #5478 (Nolan Hanke): raffle-sticker
    • Order #5477 (Anthony J Leone Jr): raffle-sticker
    • Order #5476 (Javier Snell): raffle-sticker
    • Order #5475 (Michael Holderbaum): raffle-sticker
    • Order #5474 (Roman Coronado): pod-raffle (2 line items)
    • Order #5473 (Tony Raphael): raffle-sticker
    • Order #5472 (Cristian Jimenez): raffle-sticker

    📊 Impact

    User Experience

    • Order Filtering Now Works: Users can successfully filter orders by type
    • Accurate Results: All matching orders appear in filtered views
    • Complete Data: Every order now properly categorized

    System Health

    • Data Integrity Restored: All orders have proper type assignments
    • Future Protection: Automatic assignment prevents recurrence
    • Filter Reliability: Order type filters now function as designed

    🔧 Scripts Used

    Order Type Assignment Script

    • Script: scripts/assign-order-types.js
    • Function: Analyzes line items and assigns appropriate order type
    • Logic:
    • Examines product types in each order
    • Determines if POD, inventory, raffle-sticker, or mixed
    • Updates order_type_id based on item composition
    • Results: 9/9 orders successfully processed with no errors

    📝 Notes

    Prevention

    • Order type assignment already automated in order creation flow
    • This was a one-time fix for historical data
    • No code changes needed, only data correction

    Testing

    • Verified filtering works with multiple combinations:
    • Status: pending + Type: print-on-demand ✅
    • Status: invoiced + Type: raffle-sticker ✅
    • Mixed filters ✅

    Orders Fixed: 9
    Script Runtime: < 1 second
    Status: Complete – All orders now properly typed and filterable

  • Fulfillment – Daily Changelog – October 24, 2025

    Fulfillment – Daily Changelog – October 24, 2025

    Changelog – October 24, 2025

    🔧 Bug Fixes & Refinements

    Shipment Reference System Improvements

    • COALESCE Logic Enhancement: Updated SQL queries in shipment reference API to use COALESCE for improved style ID handling
    • Ensures fallback to default styles when primary style is unavailable
    • Improves reliability of shipment reference data retrieval
    • Query Optimization: Streamlined shipment reference queries for better performance
    • Data Integrity: Enhanced fallback mechanisms to prevent null reference errors

    Print System Enhancements

    • Print Formatting Improvements: Enhanced print styles in BulkPackingListsPage component
    • Better print-specific element visibility control
    • Improved layout for print media
    • Cleaner print output with proper spacing and breaks
    • Print Styles Utility Updates: Enhanced multiPagePrintStyles in src/lib/print-styles.ts
    • More robust print media queries
    • Better page break handling
    • Improved print-specific CSS rules
    • Component Structure: Streamlined rendering logic for packing lists
    • Improved code clarity and maintainability
    • Better separation of print vs screen rendering

    Python Script Updates

    • Shipment References Population: Updated scripts/populate_shipment_references.py for improved data handling
    • Better error handling
    • More efficient database operations

    🎯 Technical Improvements

    API Routes

    • src/app/api/orders/[id]/shipment-references/route.ts: Enhanced COALESCE logic for style ID handling

    Frontend Components

    • src/app/(authenticated)/batches-new/[id]/packing-lists/page.tsx: Refactored for better print handling
    • src/components/batches/shipment-reference-display.tsx: Minor refinements for style display

    Utilities

    • src/lib/print-styles.ts: Enhanced print style generation with better formatting rules

    📊 Impact

    User Experience

    • More Reliable Shipment References: Fallback logic ensures shipment references always display correctly
    • Better Print Quality: Improved print formatting for packing lists
    • Consistent Output: More predictable print results across different browsers

    Code Quality

    • Improved Maintainability: Cleaner component structure and better separation of concerns
    • Better Error Handling: COALESCE logic prevents null reference errors
    • Enhanced Readability: Streamlined rendering logic
  • Fulfillment – Daily Changelog – October 23, 2025

    Fulfillment – Daily Changelog – October 23, 2025

    Changelog – October 23, 2025

    🚀 New Features & Improvements

    New Batch Page Enhancements

    • Fixed ShippingEasy Preview: Resolved “shippingeasy” preview not working on new batch page by removing non-existent database columns (o.shipping_address2, o.shipping_phone)
    • Customer Information Display: Fixed missing customer information display on new batch page by updating display logic to check order.shipping_name || order.customer_name || order.shipping_address1
    • Individual Shipment Creation: Fixed “Create Shipment” button to create shipments for individual orders instead of adding all line items from all orders to one shipment
    • Individual Packing Lists: Implemented one packing list per order instead of per batch, with individual “Print Packing List” buttons for each order
    • Bulk Packing Lists: Added “Print Packing Lists” button at batch level to print all order packing lists at once
    • Work Order Generation: Modified work order creation to group by decoration process instead of product, creating one work order with multiple pages (001, 002, 003, etc.)
    • Bulk Work Orders: Added “Print Work Orders” button to print all work orders for a batch

    Database & API Improvements

    • Connection Pool Management: Fixed “too many clients already” errors by replacing individual pg.Pool instances with shared db connection from @/lib/db in multiple API routes
    • Bulk Packing Lists API: Created new /api/batches/[id]/bulk-packing-lists endpoint to fetch all packing list data for multiple orders in a single query
    • Color Data Integration: Fixed missing color information in packing lists by joining with blank_style_colors table and using bc.color_name
    • Database Schema Corrections: Updated queries to use correct column names (snapshot_variant_size, snapshot_variant_color_name, snapshot_product_title)

    Print System Overhaul

    • Print Layout Fixes: Resolved multiple print layout issues including:
    • Blank pages between packing lists
    • Incorrect page dimensions causing 2 pages per packing list
    • Single page printing all packing lists
    • Width overflow issues
    • Print Styles Optimization: Implemented multiPagePrintStyles utility for consistent print formatting across packing lists
    • Individual Packing List Pages: Created /orders/[id]/packing-list pages with auto-print functionality
    • Bulk Packing List Pages: Created /batches-new/[id]/packing-lists for printing multiple packing lists with proper page breaks

    Inventory & Shipment Management

    • Inventory Check Bypass: Added force: true parameter to shipment creation to bypass inventory checks for new batch page workflow
    • Shipment Dialog Fixes: Removed undefined state variable references (setPendingShipmentData, setNotReadyItems, setShowOverrideDialog)
    • ShippingEasy Integration: Updated ShippingEasy data preparation to match exact format of working send-to-shippingeasy endpoint

    🐛 Bug Fixes

    Database Issues

    • Column Existence Errors: Fixed multiple “column does not exist” errors by removing references to non-existent columns in mama_tried_orders table
    • Type Mismatches: Fixed string vs number ID comparison issues in shipment creation filtering
    • Connection Leaks: Resolved database connection limit errors by standardizing on shared db connection

    Print System Issues

    • Sidebar in Print: Fixed sidebar appearing in printed packing lists by adding proper CSS print media queries
    • Checkbox Issues: Removed header row checkbox and set item checkboxes to checked by default
    • Date Display: Removed unnecessary date from packing list headers
    • Page Break Issues: Fixed multiple page break problems causing incorrect pagination

    UI/UX Issues

    • Customer Information: Fixed missing customer information display on new batch page
    • Shipment Creation: Fixed shipment creation to work with individual orders instead of all orders at once
    • Button Functionality: Fixed “Create Shipment” button to properly filter line items by selected order

    🔧 Technical Improvements

    API Route Updates

    • src/app/api/orders/prepare-shippingeasy-data/route.ts: Fixed column references and data structure
    • src/app/api/orders/[id]/shipment-references/route.ts: Replaced Pool with db connection
    • src/app/api/orders/bulk-dimensions/route.ts: Replaced Pool with db connection
    • src/app/api/shipments/route.ts: Added force parameter for inventory check bypass
    • src/app/api/batches/[id]/bulk-packing-lists/route.ts: New endpoint for bulk packing list data

    Frontend Components

    • src/app/(authenticated)/batches-new/[id]/page.tsx: Enhanced with individual shipment creation and bulk printing
    • src/app/(authenticated)/orders/[id]/packing-list/page.tsx: New individual packing list page
    • src/app/(authenticated)/batches-new/[id]/packing-lists/page.tsx: New bulk packing list page
    • src/components/orders/shipment-dialog.tsx: Fixed undefined state variables and added force parameter

    Database Schema

    • Updated queries to use correct column names from mama_tried_order_line_items
    • Added proper joins to blank_style_colors for color information
    • Implemented COALESCE for fallback data when snapshot data is null

    📊 Performance Improvements

    • Single Query Optimization: Replaced multiple API calls with single bulk queries for packing list data
    • Connection Pool Efficiency: Standardized database connections to prevent connection leaks
    • Print Performance: Optimized print styles to reduce layout calculations and improve rendering speed

    🎯 User Experience Improvements

    • Simplified Workflow: New batch page now “just works” without inventory check impediments
    • Bulk Operations: Added bulk printing capabilities for both packing lists and work orders
    • Visual Consistency: Fixed print layouts to match working individual packing lists
    • Error Prevention: Added proper error handling and data validation throughout the workflow

    📝 Documentation Updates

    • Updated database management instructions
    • Added local server management guidelines
    • Enhanced API documentation for new endpoints

    Total Commits: 7
    Files Modified: 15+
    New Files Created: 4
    Major Features Added: Bulk packing lists, individual shipment creation, print system overhaul

  • Fulfillment – Daily Changelog – October 22, 2025

    Fulfillment – Daily Changelog – October 22, 2025

    Changelog – October 22, 2025

    📋 Planning & Preparation

    New Batch Page Development Planning

    • Requirements Analysis: Analyzed requirements for new batch page functionality including:
    • Individual shipment creation per order
    • Individual packing lists per order instead of per batch
    • Bulk printing capabilities for multiple packing lists
    • Work order generation with proper page structure
    • ShippingEasy integration for real shipment sending

    Database Schema Investigation

    • Column Analysis: Investigated mama_tried_orders table structure to identify missing columns (shipping_address2, shipping_phone)
    • Relationship Mapping: Analyzed relationships between orders, line items, variants, and products for proper data fetching
    • Color Data Research: Investigated color information storage in blank_style_colors table for packing list display

    Print System Research

    • Layout Analysis: Studied existing working print layouts from individual packing lists
    • Page Break Strategy: Planned approach for multiple packing lists with proper page breaks
    • Print Style Architecture: Designed print style system for consistent formatting across different document types

    Workflow Design

    • User Experience Planning: Designed simplified workflow for new batch page to “just work” without inventory check impediments
    • Bulk Operations Design: Planned bulk printing and shipment creation workflows
    • Error Handling Strategy: Designed approach for bypassing inventory checks while maintaining data integrity

    🔍 Technical Investigation

    API Endpoint Analysis

    • Existing Endpoints: Reviewed current API endpoints for packing lists, shipments, and ShippingEasy integration
    • Data Flow Mapping: Traced data flow from database to frontend for packing list generation
    • Connection Management: Investigated database connection pool issues causing “too many clients” errors

    Print Layout Challenges

    • Browser Print Behavior: Researched browser print behavior for multiple documents
    • CSS Print Media: Analyzed CSS print media query limitations and solutions
    • Page Break Implementation: Studied different approaches for forcing page breaks between documents

    Database Connection Issues

    • Connection Leak Analysis: Investigated causes of database connection limit errors
    • Pool Management: Analyzed current database connection management patterns
    • Optimization Strategy: Planned approach for shared connection pool usage

    📝 Documentation Preparation

    Requirements Documentation

    • Feature Specifications: Documented requirements for new batch page functionality
    • User Stories: Defined user stories for individual vs bulk operations
    • Acceptance Criteria: Established criteria for successful implementation

    Technical Documentation

    • Database Schema Notes: Documented findings about missing columns and relationships
    • API Design: Planned new API endpoints for bulk operations
    • Print System Architecture: Documented planned print system improvements

    🎯 Strategic Planning

    Development Priorities

    • Critical Path Identification: Identified critical path for new batch page functionality
    • Risk Assessment: Assessed risks of inventory check bypass and mitigation strategies
    • Testing Strategy: Planned testing approach for print layouts and bulk operations

    User Experience Goals

    • Simplicity Focus: Emphasized “just works” philosophy for new batch page
    • Efficiency Goals: Planned bulk operations to improve workflow efficiency
    • Error Prevention: Designed error handling to prevent common workflow blockers

    Note: October 22nd appears to have been primarily a planning and investigation day, with the actual implementation work committed on October 23rd. This day focused on understanding requirements, investigating technical challenges, and planning the implementation approach for the new batch page enhancements.

    Key Focus Areas:

    • New batch page functionality planning
    • Database schema investigation
    • Print system architecture design
    • Workflow simplification strategy
    • Technical risk assessment and mitigation planning
  • Fulfillment – Daily Changelog – October 20, 2025

    Fulfillment – Daily Changelog – October 20, 2025

    Changelog – October 20, 2025

    🎯 Blank Category Assignment Feature Implementation

    Overview

    Implemented the ability to assign blank categories to products instead of individual styles, allowing for more flexible inventory management and automatic SKU creation across multiple interchangeable styles.

    🚀 New Features

    Product Details – Blank Category Assignment

    • Added category selection UI in product details page
    • Toggle between Individual Styles and Blank Category modes
    • Category dropdown with live preview of styles in selected category
    • Automatic SKU creation for all styles in assigned category
    • Preference ranking display showing which style is default

    UI Components

    • Radio button toggle for choosing between individual styles vs category
    • Category selector dropdown with style preview
    • Real-time style display showing brand, name, and preference ranking
    • Visual feedback for current assignment mode

    🔧 Technical Implementation

    Database & API Integration

    • Leveraged existing /api/products/[id]/assign-category endpoint
    • Automatic variant_sku creation for all styles in category
    • Priority-based SKU assignment using preference rankings
    • Default style marking for highest preference (rank 1)

    Form State Management

    • Added blank_category_id to form schema and validation
    • Local state management for UI mode switching
    • Form change detection including category assignments
    • Mutual exclusivity between individual styles and categories

    Type System Updates

    • Enhanced MamaTriedProduct interface with blank_category_id field
    • Added BlankCategory import for type safety
    • Form validation for category assignment

    📊 Data Flow

    Category Assignment Process

    1. User selects “Blank Category” mode
    2. Chooses category from dropdown
    3. System displays all styles in category with preference rankings
    4. On save, calls assign-category API
    5. Creates variant_skus for all styles based on size/color combinations
    6. Sets priority and default based on preference rankings

    SKU Management

    • For each variant (size + color): Creates one variant_sku per style in category
    • Example: 8 sizes × 1 color × 2 styles = 16 variant_sku records
    • Priority matching: Uses preference_rank from category_styles table
    • Default assignment: Highest preference (rank 1) marked as default

    🎨 User Experience

    Visual Design

    • Clean toggle interface with clear mode indicators
    • Category preview showing all styles with rankings
    • Real-time feedback on form changes
    • Consistent styling with existing product details form

    Workflow Integration

    • Seamless switching between individual styles and categories
    • Preserved existing functionality for individual style management
    • Clear visual indicators for current assignment mode
    • Form validation prevents conflicting assignments

    🔍 Files Modified

    Core Implementation

    • src/types/mama-tried.ts – Added blank_category_id to product interface
    • src/components/products/product-sections/product-details.tsx – Main UI implementation

    Key Changes

    • Form schema updates with blank_category_id field
    • React Query integration for fetching categories
    • Local state management for UI mode switching
    • Form submission logic with category assignment API calls
    • Conditional rendering based on assignment mode

    🧪 Testing & Validation

    Functionality Verified

    • Button interactions working correctly
    • Category selection displaying proper styles
    • Form state updates reflecting user choices
    • Style display showing brand, name, and preference rankings
    • Mode switching between individual and category

    Data Integrity

    • Category data loading with style relationships
    • Preference rankings displaying correctly
    • Form validation preventing invalid states
    • API integration ready for category assignment

    🚧 Current Status

    Completed

    • ✅ UI implementation with toggle buttons
    • ✅ Category selection and display
    • ✅ Style preview with preference rankings
    • ✅ Form state management
    • ✅ Type system integration

    In Progress

    • 🔄 Persistence testing – Category assignments not persisting after save
    • 🔄 API debugging – Investigating category assignment API calls
    • 🔄 Form submission – Ensuring proper data flow to backend

    🎯 Next Steps

    Immediate Tasks

    1. Debug persistence issue – Category assignments not saving
    2. Verify API integration – Ensure assign-category endpoint is called
    3. Test end-to-end flow – Complete category assignment workflow
    4. Remove debug code – Clean up temporary debugging elements

    Future Enhancements

    • Bulk category assignment for multiple products
    • Category inventory dashboard for monitoring
    • Dynamic style updates when categories change
    • Advanced preference management for style selection

    📝 Notes

    Technical Decisions

    • Used local state instead of form.watch() for better UI responsiveness
    • Maintained backward compatibility with existing individual styles
    • Leveraged existing API rather than creating new endpoints
    • Preserved form validation and change detection

    User Impact

    • No breaking changes to existing workflows
    • Enhanced flexibility for inventory management
    • Simplified SKU management for interchangeable styles
    • Better scalability for products with multiple style options
  • Fulfillment – Daily Changelog – October 18, 2025

    Fulfillment – Daily Changelog – October 18, 2025

    Daily Changelog – October 18, 2025

    4×6 Packing Slip Improvements for Thermal Printing

    Overview

    Completely redesigned the 4×6 packing slip layout to improve readability on thermal printers, making them landscape-oriented with larger, bolder text and better visual structure.

    Changes Made

    1. Layout Orientation

    • Changed from portrait to landscape: Updated page dimensions from 4in × 6in to 6in × 4in
    • Added UPS label bleed area: Added 0.5″ right margin to prevent printing over UPS shipping labels

    2. Typography Improvements

    • Increased base font size: From 11px to 14px for better readability
    • Enhanced header fonts: Title and order numbers increased to 16px with 800 font weight
    • Improved address text: From 9px to 12px with 800 font weight for labels
    • Bolder customer names: Increased to 15px with 700 font weight
    • Larger item text: Increased to 16px with 800 font weight for quantities
    • Enhanced footer: Increased to 13px with 600 font weight

    3. Visual Structure (ShippingEasy-style Layout)

    • Side-by-side addresses: “From:” and “To:” sections now positioned horizontally with clear separation
    • Added visual borders: Thick black lines (2px) around address and item sections for better definition
    • Improved spacing: Increased margins and line height (1.3) for better readability

    4. Raffle Message Optimization

    • Shortened disclaimer text: Reduced from long paragraph to concise message:
    • Before: “Each sticker represents an entry to win the 2026 Mama Tried Show Harley-Davidson Low Rider S Giveaway Bike. The profits from this giveaway help us create a better Mama Tried experience. We really appreciate all the support, without you all we are nothing!! Let’s do this! Buy as many stickers as you want. Buy so many that you can cover your garage refrigerator in giveaway bike stickers. There is no limit to how many stickers you can buy. Good-Luck! Your order number is your ticket entry.”
    • After: “Each sticker represents an entry to win the 2026 Mama Tried Show Harley-Davidson Low Rider S Giveaway Bike. Your order number is your ticket entry.”
    • Increased disclaimer font size: From 11px to 13px for better thermal printer readability

    5. Database Updates

    • Updated production database: Modified raffle_packing_message field in mama_tried_products table for product ID 3215
    • Updated local database: Synchronized local development database with production changes

    Technical Details

    Files Modified

    • src/app/api/orders/labels-4x6/route.ts – Main packing slip generation API
    • src/app/api/orders/labels-4x6/debug/route.ts – Debug route for browser preview
    • src/components/batches/raffle-4x6-labels-button.tsx – Button component (reverted to use debug route)

    Database Changes

    • Updated mama_tried_products.raffle_packing_message for 2026 Mama Tried Giveaway Bike Entry product
    • Both production (Heroku) and local (Docker) databases updated

    Impact

    • Improved thermal printer output: Larger, bolder text is much more readable on thermal printers
    • Better space utilization: Landscape orientation provides more horizontal space for content
    • Professional appearance: Side-by-side addresses with clear borders match industry standards
    • Reduced printing issues: 0.5″ right margin prevents overlap with UPS shipping labels
    • Enhanced user experience: Shorter, clearer raffle message reduces visual clutter

    Testing

    • Verified changes work in both browser preview (debug route) and PDF generation (main route)
    • Confirmed database updates resolve message length issues
    • Tested landscape orientation and improved typography on thermal printer output

    Notes

    • The challenge was that raffle messages were stored in the database, not just in code defaults
    • Required updating both production and local databases to see changes
    • Debug route and main route needed to be kept in sync for consistent behavior
  • Fulfillment – Daily Changelog – October 17, 2025

    Fulfillment – Daily Changelog – October 17, 2025

    Changelog – October 17, 2025

    Blank Category System Implementation

    New Category-Based Blank Selection

    • Problem: Need to group interchangeable blank styles for flexible inventory management
    • Solution: Implemented comprehensive category system for blank products
    • Created 3 new database tables:
      • blank_categories – Define categories (e.g., “Black Short Sleeve Tee – Cotton – Standard Quality”)
      • blank_category_styles – Map styles to categories with preference ranking
      • warehouse_category_items – Track inventory by category instead of specific style
    • Added blank_category_id to mama_tried_product_variants for category assignment
    • Features:
    • Full CRUD API for category management (/api/blank-categories)
    • Style assignment with preference ranking (rank 1 = preferred, rank 2 = fallback)
    • Auto-generation of category names from form fields (material + quality + color + garment type)
    • Updated batch production to auto-select SKUs from categories based on availability
    • Built category management UI at /blank-categories
    • Migration: Migrated 68 black Jerzees variants to new category system
    • Category includes Jerzees 29MR (rank 1) and Gildan 8000 (rank 2) as interchangeable options
    • Files Created:
    • database_migrations/add_blank_categories.sql
    • scripts/migrate_to_black_category.sql
    • scripts/verify_category_migration.sql
    • src/app/blank-categories/page.tsx
    • src/components/blank-categories/category-form.tsx
    • src/components/blank-categories/category-styles-manager.tsx
    • src/components/products/category-selector.tsx
    • Multiple API routes under /api/blank-categories/
    • Documentation:
    • BLANK_CATEGORY_IMPLEMENTATION_SUMMARY.md
    • BLANK_CATEGORY_QUICKSTART.md
    • BLANK_CATEGORY_SYSTEM.md

    Blank Categories API Fix

    • Problem: Category list/detail endpoints failing with 500 errors
    • Root Cause: API tried to join with non-existent blank_colors table
    • Solution: Removed LEFT JOIN references to blank_colors table
    • Files Modified:
    • src/app/api/blank-categories/[id]/route.ts
    • src/app/api/blank-categories/route.ts

    Category Name Auto-Generation

    • Feature: Category names now auto-populate as user fills form fields
    • Behavior:
    • Only auto-generates if name field is empty or matches previous auto-generated name
    • Allows manual override by typing directly in name field
    • Impact: Reduces manual typing and ensures consistent naming conventions
    • File Modified: src/components/blank-categories/category-form.tsx

    Critical QuickBooks Rate Limiting Fix

    QuickBooks API Throttling Issue

    • Problem: Attempting to send 25+ invoices to QuickBooks resulted in HTTP 429 “ThrottleExceeded” errors
    • Root Cause: October 3rd commit changed invoice sending from sequential with delays to parallel execution using Promise.all()
    • Previous code sent invoices one at a time with 500ms delays
    • “Optimization” removed delays and sent all invoices simultaneously
    • Worked with 14 invoices on Oct 3, failed with 25+ invoices today
    • QuickBooks API limits: ~30 calls per minute, 500 calls per 5 minutes
    • Impact: Unable to send 80 uninvoiced shipped orders to QuickBooks, system throttled for extended period
    • Solution:
    • Reverted to sequential processing with increased 2-second delays between requests
    • Applied fix to both invoice sending code paths:
      • invoice-creation-success.tsx – “Send All to QuickBooks” button in creation dialog
      • send-selected-to-quickbooks-button.tsx – Bulk send button on invoices page
    • Added progress indicators showing “Sending X/Y…” so users can track progress
    • Files Modified:
    • src/components/orders/invoice-creation-success.tsx
    • src/components/invoices/send-selected-to-quickbooks-button.tsx
    • Deployments: v871, v876, v877
    • Result: Invoices now send reliably without hitting rate limits, users can see progress during bulk sends

    Database Investigation & Upgrade

    Shipped Orders Without Invoices Audit

    • Query: Identified 80 orders marked as “shipped” status that hadn’t been invoiced yet
    • Findings:
    • Most orders from Oct 2-17, 2025 (expected to be uninvoiced)
    • One older order #5346 from Sept 19, 2025 – potentially had status changed manually
    • All had invoiced = false and no records in mama_tried_invoice_orders junction table
    • Action: Prepared for batch invoicing once rate limit issues resolved

    Database Plan Upgrade

    • Action: Upgraded Heroku Postgres from Essential-0 to Essential-1
    • Cost: $5/mo → $9/mo (+$4/mo)
    • Expected: 60 database connections (3x increase)
    • Actual: 20 connections (no change)
    • Essential-0: $5/mo, 20 connections, 1 GB storage
    • Essential-1: $9/mo, 20 connections, 10 GB storage
    • Lesson Learned: Connection limit increase requires Standard-0 plan ($50/mo, 120 connections)
    • Note: Storage increase not needed (was at 9.67% of 1 GB limit)
    • Status: May downgrade back to Essential-0 as upgrade provided minimal benefit for cost

    Order Data Fixes

    Order #5405 Variant Correction

    • Problem: Order 629 (Shopify #5405) showed XXL variant instead of L variant
    • Customer ordered 2 shirts in size L
    • Database showed line item 669 with XXL variant (5687) after variant data restoration
    • Would have been invoiced incorrectly for more expensive XXL size
    • Solution: Updated line item 669 to correct L size variant (5685)
    • Impact: Order will now invoice correctly for the size that was actually ordered
    • Related: This order already had reprint #5405-REPRINT created for the incorrect 2XL that was shipped

    Minor Fixes

    Reprint Dialog Import Path

    • Fixed: Corrected toast hook import path in create-reprint-dialog.tsx
    • Changed: @/hooks/use-toast@/components/ui/use-toast

    Shipment API Error Logging

    • Enhanced: Added error logging to batch lock failure in mark-as-shipped/route.ts
    • File: src/app/api/shipments/mark-as-shipped/route.ts

    Temporary Files Cleanup

    • Removed experimental scripts created during troubleshooting:
    • scripts/send_draft_invoices_to_qb.js
    • scripts/send_draft_invoices_to_qb.cjs

    Outstanding Issues

    API Endpoint Errors

    • Observation: Some API endpoints returning 500 errors when loading order details
    • /api/orders/629 – Failed to load order data
    • /api/orders/629/line-items – Failed to load line items
    • Suspected Cause: Possibly related to raffle sticker orders with no variants, or snapshot system changes not yet deployed
    • Impact: UI errors but invoicing still functions correctly
    • Status: Deferred for future fix

    Lessons Learned

    1. Rate Limiting: Always preserve delays/throttling when interfacing with external APIs – “optimizations” can break integration limits
    2. Cloud Service Pricing: Always verify current Heroku pricing/features rather than relying on assumptions
    3. Progress Indicators: Critical for long-running operations so users know system is working
    4. Database Connections: Issue was connection pool size (5), not total limit (20) – code optimizations may be more valuable than plan upgrades

    Next Steps

    • Monitor QuickBooks integration for rate limiting issues
    • Consider downgrading database back to Essential-0 if connection limits remain adequate
    • Deploy remaining connection pool optimizations from undeployed commits when ready
    • Address API 500 errors for order detail pages (low priority)
  • Fulfillment – Daily Changelog – October 16, 2025

    Fulfillment – Daily Changelog – October 16, 2025

    Changelog – October 16, 2025

    Order Snapshot System Implementation

    Immutable Order Data Snapshots

    • Problem: Order line items lost critical data when variants were modified or deleted
    • Order #5405 showed incorrect sizes after Oct 10 variant data restoration
    • Line items depended on live variant data, which could change or disappear
    • No historical record of what was actually ordered/shipped
    • Solution: Implemented comprehensive snapshot system to capture immutable order data at creation time
    • Added new columns to mama_tried_order_line_items:
      • snapshot_product_data (JSONB) – Complete product details
      • snapshot_variant_data (JSONB) – Complete variant details including size, color, SKU
      • snapshot_pricing_data (JSONB) – Pricing breakdown (blank + print costs)
    • Captures data from:
      • Product details (title, type flags, QuickBooks ID)
      • Variant details (size, color, SKU, style info)
      • Pricing details (blank price, print price, total)
    • Implementation:
    • Modified order creation endpoint to capture snapshots
    • Updated line items endpoint to include snapshot data
    • Added TypeScript types for snapshot data structures
    • Created backfill script for existing orders
    • Database Migration: database_migrations/add_line_item_snapshots.sql
    • Files Modified:
    • src/app/api/orders/route.ts – Capture snapshots on order creation
    • src/app/api/orders/[id]/line-items/route.ts – Include snapshot data in responses
    • src/app/api/orders/[id]/route.ts – Return snapshot data
    • src/types/orders.ts – Added snapshot type definitions
    • src/lib/orderUtils.ts – Enhanced order type assignment
    • Documentation:
    • SNAPSHOT_IMPLEMENTATION_SUMMARY.md – Complete technical overview
    • SNAPSHOT_QUICKSTART.md – Quick reference guide
    • SNAPSHOT_TESTING_GUIDE.md – Testing procedures
    • Scripts Created:
    • scripts/backfill_order_snapshots.py – Backfill snapshots for existing orders
    • scripts/verify_snapshots.sql – Verify snapshot data integrity

    Raffle Sticker Order Type Fix

    • Problem: 176 raffle sticker orders not being classified correctly after variant data reset
    • Orders not appearing in raffle sticker filtered views
    • assignOrderType() function missing is_raffle_sticker field
    • Root Cause: Order type detection couldn’t identify raffle stickers without the flag
    • Solution:
    • Updated assignOrderType() to include is_raffle_sticker field from product data
    • Database fix applied to update 176 orders with correct raffle-sticker type
    • Removed erroneous variant associations
    • Files Modified: src/lib/orderUtils.ts
    • Impact: All raffle sticker orders now properly classified and filterable

    Create Reprint Functionality

    • Feature: Added ability to create reprint orders for incorrect shipments
    • Implementation:
    • New API endpoint: /api/orders/[id]/create-reprint
    • Creates new order with -REPRINT suffix
    • Copies customer info and allows variant selection
    • Marks as is_reprint=TRUE with original_order_id reference
    • Sets total price to $0.00 (no charge to customer)
    • UI Component: CreateReprintDialog for easy reprint creation
    • Files Created:
    • src/app/api/orders/[id]/create-reprint/route.ts
    • src/components/orders/create-reprint-dialog.tsx
    • Use Case: Created reprint order #5405-REPRINT for incorrect 2XL shipment

    Order #5405 Investigation & Fix

    • Investigation: Comprehensive analysis of variant data corruption impact
    • Verified all orders that shipped since Oct 10 variant restoration
    • Only 1 order (out of 80+ shipped) had incorrect size sent
    • Order #5405 Details:
    • Customer ordered 2 shirts in size L
    • Shipped 1 correct (L Solid Gold) + 1 incorrect (2XL Western Stacked instead of L)
    • Shopify showed correct L variant (41889779384456)
    • System shipped 2XL variant (41889779449992)
    • Resolution: Created reprint order #5405-REPRINT with correct L size
    • Documentation:
    • REAL_IMPACT_SUMMARY.md – Analysis of actual damage
    • ACTUAL_DAMAGE_ASSESSMENT.md – Detailed assessment
    • AFFECTED_ORDERS_SUMMARY.md – Complete order analysis
    • CUSTOMER_CONTACT_PLAN.md – Customer communication strategy
    • VARIANT_DATA_CORRUPTION_INVESTIGATION.md – Technical investigation
    • Scripts:
    • fix_order_variants.py – Tool to detect and fix variant mismatches
    • verify_order_variants.py – Verification script
    • investigate_actual_shipments.py – Analyze what was actually shipped
    • create_reprint_5405.sql – SQL for creating reprint order
    • show_5405_change.sql – Document variant changes

    Shipment Sync Optimization & Hang Prevention

    Shipment Processing Deadlock Fix

    • Problem: Shipment sync operations hanging and blocking other database operations
    • Mark-as-shipped endpoint had long-running transactions
    • Concurrent batch updates causing deadlocks
    • Multiple sync operations exhausting database connection pool
    • Root Cause:
    • No transaction timeouts on long operations
    • Batch updates lacking row-level locking
    • Redundant calls between sync endpoints
    • Each sync creating new database connections
    • Solutions Implemented:
    1. Transaction Timeout: Added 30-second timeout to mark-as-shipped endpoint
    2. Row-Level Locking: Implemented SELECT FOR UPDATE SKIP LOCKED for batch updates
    3. Streamlined Sync Flow:
      • sync-shopify endpoint now handles status updates inline instead of calling mark-as-shipped
      • sync-tracking endpoint handles status updates inline, reducing connections
    4. Server-Side Lock System:
      • New sync operation lock to prevent overlapping syncs
      • Lock check before starting bulk operations
      • Auto-release after timeout
    5. Connection Pool Optimization: Updated src/lib/db.ts with better pool settings
    • New API Endpoints:
    • /api/sync-operations/acquire-lock – Acquire exclusive sync lock
    • /api/sync-operations/check-lock – Check if sync is currently running
    • /api/sync-operations/release-lock – Manually release stuck locks
    • Files Modified:
    • src/app/api/shipments/mark-as-shipped/route.ts – Added timeout & locking
    • src/app/api/shipments/sync-shopify/route.ts – Inline status updates
    • src/app/api/shippingeasy/sync-tracking/route.ts – Inline status updates
    • src/components/shipments/BulkSyncTrackingButton.tsx – Lock checking
    • src/lib/db.ts – Connection pool optimization
    • src/lib/syncLock.ts – New lock management utility
    • src/utils/fetchWithTimeout.ts – Timeout utility
    • Documentation: SHIPMENT_SYNC_HANG_FIX_SUMMARY.md
    • Impact: Eliminated sync hangs, reduced connection exhaustion, improved concurrent operation handling

    Minor Enhancements

    Batch API Improvements

    • Enhanced: Batch endpoints now include proper error handling for variant assignments
    • Files Modified:
    • src/app/api/batches/[id]/bulk-weight/route.ts
    • src/app/api/batches/[id]/send-to-shippingeasy/route.ts
    • src/app/api/batches/[id]/sync-shippingeasy/route.ts

    UI Updates

    • Updated: Order list and detail pages to support new snapshot data
    • Files Modified:
    • src/app/(authenticated)/orders/[id]/page.tsx
    • src/app/(authenticated)/orders/page.tsx

    Auth & Middleware

    • Improved: Authentication handling and middleware logging
    • Files Modified:
    • src/lib/auth.ts
    • src/middleware.ts

    Testing & Verification

    Comprehensive Testing Tools

    • Created Python scripts for data verification:
    • fix_order_variants.py – 380 lines – Detect and fix variant issues
    • verify_order_variants.py – 330 lines – Verify order data integrity
    • investigate_actual_shipments.py – 365 lines – Analyze shipment history
    • check_what_i_changed.py – Track database changes
    • Created SQL verification scripts:
    • scripts/verify_snapshots.sql – Verify snapshot backfill
    • temp_line_items.sql – Temporary line item analysis

    Investigation Results

    • Output Files:
    • shipment_investigation_output.txt – Detailed shipment analysis
    • shipment_investigation_report.json – Structured investigation data
    • variant_verification_results.json – Variant verification results

    Database Backups

    • Created pre-change backup: pre_change_backup.dump (4.1 MB)
    • Backup taken before applying major snapshot system changes

    Summary Statistics

    • Total Changes: 8,501 lines added, 63 lines deleted (snapshot system commit)
    • Additional Changes: 616 lines added, 90 deleted (shipment sync commit)
    • New Files: 47 files created (documentation, scripts, components, API routes)
    • Orders Fixed: 176 raffle sticker orders reclassified
    • Orders Analyzed: 80+ shipped orders verified for data corruption
    • Actual Impact: 1 order shipped with wrong size (out of 80+)

    Deployment Status

    • Not Yet Deployed: Changes committed but awaiting production deployment
    • Reason: Awaiting thorough testing due to scope of changes
    • Next Deployment: Will include both snapshot system and shipment sync optimizations