Author: Mark

  • Time Clock – Daily Changelog – September 22, 2025

    Time Clock – Daily Changelog – September 22, 2025

    Daily Changelog – September 22, 2025

    Fixes

    • Fixed time display formatting on entries page to keep start/end times on single lines

    Improvements

    • Adjusted column widths on entries page to better accommodate time displays and improve layout
    • Made TimePill components more compact with reduced padding and smaller text size
    • Changed Start · End column layout from space-y to flex column for better time display
    • Reduced Duration and Hours column widths to make room for wider time columns
    • Added whitespace-nowrap to prevent time text wrapping in break columns
    • Updated break time displays to use flex column layout with smaller text
    • Fixed all TypeScript errors related to Date vs UTCISOString type mismatches across multiple files
    • Corrected import statements to use date-fns for addDays, startOfWeek, and differenceInCalendarDays functions
    • Fixed formatLocal function calls to properly convert Date objects to UTCISOString before formatting
    • Modified payroll export system to exclude employees in Company Leadership department from payroll exports while keeping them trackable in system for management purposes

    Notes

    • Successfully resolved all TypeScript compilation errors and achieved successful Heroku deployment after extensive debugging
  • Fulfillment – Daily Changelog – September 20, 2025

    Fulfillment – Daily Changelog – September 20, 2025

    2025-09-20 – Duplicate Invoice Prevention System

    Critical Issue – Duplicate Invoice Prevention

    Problem Identified

    • Issue: System created duplicate invoices for the same order yesterday
    • Impact: Both invoices were pushed to QuickBooks and automatically paid
    • Risk: Financial discrepancies and double payments
    • Priority: Critical – needs immediate attention

    Investigation Plan

    • [x] Analyze invoice creation workflow
    • [x] Identify potential race conditions or duplicate triggers
    • [x] Implement safeguards to prevent duplicate invoice generation
    • [x] Add validation checks before QuickBooks integration
    • [x] Test invoice creation process thoroughly

    Root Causes Identified

    • No Database Constraints: mama_tried_invoices table lacks unique constraint on invoice_number
    • No Idempotency Protection: Multiple API calls can create invoices for same orders
    • QuickBooks Integration Risk: No check if invoice already sent to QuickBooks
    • Race Condition Potential: Multiple users can create invoices simultaneously

    Implemented Solutions

    Database-Level Protection

    • Added UNIQUE constraint on mama_tried_invoices.invoice_number to prevent database-level duplicates
    • Created invoice_operations table for idempotency tracking and audit trail

    Invoice Creation Safeguards

    • Pre-invoice validation: Check if orders already have invoices before creation
    • Idempotency key system: Generate unique keys to prevent duplicate API calls
    • Conflict detection: Return 409 status code with detailed error information
    • Audit trail: Track all invoice creation operations with timestamps and user info

    QuickBooks Integration Safety

    • Duplicate push prevention: Check quickbooks_invoice_id and status before sending
    • Status validation: Prevent sending invoices already marked as ‘sent_to_quickbooks’
    • Detailed error responses: Clear messaging when duplicates are detected

    Frontend Protection

    • Idempotency key generation: Unique keys based on timestamp, order IDs, and random string
    • Enhanced error handling: Specific handling for 409 conflict responses
    • User feedback: Clear toast notifications for duplicate prevention triggers

    Current Status

    Completed

    • Comprehensive duplicate invoice prevention system implemented
    • Database constraints and validation in place
    • Idempotency protection for API calls
    • QuickBooks integration safeguards
    • Frontend duplicate prevention with user feedback

    Ready for Testing

    • All safeguards are in place and ready for production testing
    • System will now prevent duplicate invoices at multiple levels
    • Financial risk significantly reduced through layered protection

    Technical Implementation Details

    Database Changes

    • mama_tried_invoices: Added UNIQUE constraint on invoice_number column
    • invoice_operations: New table for idempotency tracking with columns:
    • idempotency_key (VARCHAR, UNIQUE)
    • operation_type (VARCHAR, default ‘invoice_creation’)
    • status (VARCHAR, default ‘completed’)
    • result_data (TEXT, stores JSON response)
    • created_at, created_by (audit fields)

    API Endpoint Changes

    • /api/invoices POST: Added pre-creation duplicate checks and idempotency support
    • /api/intuit/send-db-invoice GET: Added QuickBooks duplicate push prevention
    • Error handling: Enhanced with 409 Conflict status codes and detailed error messages

    Frontend Changes

    • invoice-dialog.tsx: Added idempotency key generation and duplicate error handling
    • User experience: Clear feedback when duplicate prevention triggers

    Notes

    • Critical financial protection: Multi-layered duplicate prevention system now active
    • Immediate deployment: All changes are backward compatible and safe for production
    • Testing recommended: Verify duplicate prevention works as expected before next invoice cycle
    • Monitoring: Watch logs for “DUPLICATE PREVENTION” and “IDEMPOTENCY” messages
  • Time Clock – Daily Changelog – September 19, 2025

    Time Clock – Daily Changelog – September 19, 2025

    Daily Changelog – September 19, 2025

    Fixes

    • Fixed holiday date display issue in calendar settings where Labor Day showed as Aug 31 instead of Sep 1 by changing formatLocal() to formatDateOnlyLocal() in HolidaysSection.tsx, resolving timezone conversion error for date-only strings

    Improvements

    • Updated payroll export to include holiday_hours totals in total_holiday_hours and summed into total_hours on API api/payroll/export, improving accuracy for holiday weeks

    New

    • Added daily holiday hours generator API api/holiday-hours/generate to upsert paid holiday entries per eligible employee based on master schedules (8 or 10 hours), enabling automatic holiday population
    • Added script scripts/generate-holiday-hours.js with npm command npm run holiday:generate to trigger holiday generation via deployed app URL, allowing Heroku Scheduler or manual runs
    • Added unified time-off entries API api/time-off/entries to combine PTO requests and holiday hours into single dataset with employee names and filtering
    • Added time-off entries page time-off/entries with data table showing all vacation and holiday entries across employees, accessible from navigation menu
    • Backfilled holiday hours for Memorial Day 2025 and Labor Day 2025 for all eligible employees using deployed script

    Notes

    • Holiday generator script initially failed due to API changes not being deployed; resolved after deployment
    • Time-off entries page initially showed future empty holiday placeholders; fixed by defaulting includeCalendar=false to hide scheduled holidays until actual entries exist
  • Fulfillment – Daily Changelog – September 19, 2025

    Fulfillment – Daily Changelog – September 19, 2025

    2025-09-19 – Shipping Address Badge System Fixes

    Critical Bug Fixes

    Fixed False Positive “Address Updated” Badges

    • Problem: Every order was showing “📍 Address Updated” badge even when no shipping changes occurred
    • Root Cause: Both webhook handler and sync process were calling updateOrderShippingAddress with faulty comparison logic
    • Solution: Temporarily disabled automatic shipping address updates in both webhook and sync processes
    • Result: Only legitimate address changes now show the badge (e.g., order #5303 from 8/29)

    Database Cleanup

    • Cleared all false positive shipping_updated_at timestamps from recent orders
    • Restored only the legitimate shipping update for order #5303
    • Prevented system from appearing unreliable to staff/customers

    Code Changes

    • src/app/api/webhooks/shopify/route.ts: Disabled updateOrderShippingAddress calls in webhook handler
    • src/app/api/orders/sync/route.ts: Disabled shipping updates during order sync process
    • Database: Reset shipping_updated_at values to prevent false badge displays

    Build & Deployment Fixes

    Fixed Multiple Build Errors

    • JSX Syntax Error: Fixed missing fragment wrapper in invoice-dialog.tsx
    • Import Path Error: Corrected useToast import path in invoice-creation-success.tsx
    • Linting Errors: Commented out unused variables and fixed unescaped entities
    • Route Conflict: Removed duplicate API route causing Next.js build failures

    Current Status

    Working

    • Badge system now shows accurate shipping address change indicators
    • Invoice creation flow functional
    • Build and deployment process stable

    Root cause: updateOrderShippingAddress comparison logic is faulty – treats every address as “changed”

    What needs to be done RIGHT NOW:

    1. Debug the address comparison in updateOrderShippingAddress function
    2. Fix the logic so it only flags actual changes
    3. Re-enable webhook and sync shipping updates
    4. Test with real address changes to make sure it works

    System Reliability

    • Address root cause of frequent Friday system failures
    • Implement better testing for critical workflows
    • Consider staging environment for testing changes
  • Time Clock – Daily Changelog – September 18, 2025

    Time Clock – Daily Changelog – September 18, 2025

    Daily Changelog – September 18, 2025

    Fixes

    • Fixed missing calendar entries causing schedule generation failures by adding auto-creation of calendar entries in generateWeeklySchedulesRefactored function
    • Resolved “generate more weeks” functionality breaking when calendar entries don’t exist for future dates
    • Added defensive programming to schedule generation to automatically create missing calendar dates instead of failing
    • Fixed PTO requests API to return date fields as plain text strings using ::text casting to prevent timezone conversion of date-only values
    • Resolved date display issues where manual PTO requests showed incorrect dates due to UTC timestamp conversion in API layer

    Improvements

    • Enhanced schedule generation robustness by ensuring calendar entries exist before attempting to generate schedules
    • Added automatic calendar entry creation for any missing dates during schedule generation process
    • Cleaned up import modal styling by removing unprofessional emojis and fixing contrast issues with yellow file upload button
    • Improved schedule page layout with proper button grouping, spacing between header and content, and better department section separation
    • Fixed cramped UI elements across multiple pages by adding appropriate gaps and breathing room
    • Enhanced payroll export page to automatically select the most recent relevant pay period instead of defaulting to blank selection
    • Fixed payroll export SQL GROUP BY error by adding missing columns to GROUP BY clause
    • Added CSV export functionality to payroll export API with proper Content-Disposition headers for file downloads
    • Simplified payroll export query to resolve complex recursive CTE issues causing data retrieval failures
    • Added defensive programming to payroll export frontend to handle non-numeric values with Number() conversion
  • Time Clock – Daily Changelog – September 17, 2025

    Time Clock – Daily Changelog – September 17, 2025

    Daily Changelog – September 17, 2025

    Fixes

    • Fixed timezone display issues in PTO request dates where date-only values (2025-10-20) were being incorrectly interpreted as UTC and shifted by timezone conversion, causing 10/20 to display as 10/19
    • Updated time-off-requests page to use formatDateOnlyLocal instead of formatLocal for proper date-only formatting
    • Fixed DateTime.fromISO calls in employee portal, main dashboard, and leave of absence components to specify America/Chicago timezone for date-only strings
    • Resolved date shifting in FileMaker PTO import display where imported 10/20 and 11/20 requests appeared as 10/19 and 11/19 in frontend
    • Fixed PTO import functions to use simple date component parsing instead of timezone-aware parseAppDate for date-only values
    • Removed unnecessary timezone conversion from both FileMaker PTO import and regular PTO import routes
    • Standardized date-only parsing across all import functions to match time clock import approach (direct MM/DD/YYYY to YYYY-MM-DD conversion)
    • Resolved massive TypeScript build regression where 208+ errors were caused by systematic removal of date-fns imports while leaving function calls intact
    • Restored missing date-fns imports to 23+ files including format, parseISO, addDays, startOfWeek functions
    • Fixed duplicate DateTime import causing webpack compilation failure in payroll pay-periods page
    • Fixed UTCISOString type casting errors across 15+ components by adding proper type assertions
    • Fixed Luxon DateTime method calls (.toISOString() → .toISO(), .getTime() → .toJSDate().getTime())
    • Resolved import conflicts in time.ts library where date-fns functions conflicted with existing implementations
    • Fixed missing fs import in wordpress-simple.ts and various API route type errors
    • Installed missing @types/luxon and date-fns packages to restore proper TypeScript definitions
    • Fixed function declaration order issues where useEffect hooks referenced functions before they were declared
  • Fulfillment – Daily Changelog – September 17, 2025

    Fulfillment – Daily Changelog – September 17, 2025

    2025-09-17 – Invoice Creation Flow Redesign

    Problem Solved

    • Fixed unreliable automatic QuickBooks sending during invoice creation that was causing failures and frustration
    • Eliminated need to navigate to separate invoices page to send invoices to QuickBooks after creation

    New Invoice Creation Workflow

    • Removed problematic automatic QuickBooks integration from invoice creation API that was failing due to timing issues
    • Created new success dialog that appears immediately after invoice creation
    • Added immediate QuickBooks sending options without leaving the creation flow

    User Experience Improvements

    • Success dialog shows all created invoices with details (invoice number, customer, amount)
    • Individual “Send to QuickBooks” buttons for each invoice
    • “Send All to QuickBooks” button to send all invoices at once
    • Real-time status updates showing success/failure for each QuickBooks send attempt
    • Clear visual feedback with badges showing sent/not sent/failed status

    Technical Changes

    • Modified /api/invoices route to remove automatic QuickBooks sending after transaction commit
    • Created new InvoiceCreationSuccess component for post-creation QuickBooks integration
    • Updated InvoiceDialog component to use new success flow instead of automatic sending
    • Maintained proven QuickBooks sending logic from existing manual process

    Benefits

    • Reliable invoice creation – no more failures due to QuickBooks timing issues
    • Streamlined workflow – create invoices and send to QuickBooks in one flow
    • Better error handling – clear feedback on what succeeded/failed
    • Flexible sending – send individual invoices or all at once
    • No navigation required – everything happens in one dialog

    Impact

    • Eliminates the frustrating “failed” messages during invoice creation
    • Reduces workflow from 3 steps (create → navigate → send) to 2 steps (create → send)
    • Uses the same proven QuickBooks integration that works reliably in manual mode
    • Provides immediate feedback and control over QuickBooks synchronization

    Testing Status

    • Ready for testing during next invoice creation cycle
    • Falls back to existing manual QuickBooks sending process if needed

    Shipping Address Update System – Final Fixes

    Webhook Validation Improvements

    • Fixed webhook payload validation to prevent database errors from malformed Shopify webhooks
    • Added order ID validation before processing to avoid NaN conversion errors
    • Improved error handling for incomplete webhook payloads

    Badge Display Issues Resolved

    • Fixed false positive badges showing on all orders due to sync process setting shipping_updated_at incorrectly
    • Cleared test order flags while preserving legitimate address change indicators
    • Restored proper badge for order #5303 – the original real address change that caused shipping issues

    System Status

    • Webhook system working – successfully processes address changes from Shopify
    • Badge system accurate – only shows for legitimate address changes after order creation
    • Ready for production – system will properly flag future customer address changes
  • Time Clock – Daily Changelog – September 16, 2025

    Time Clock – Daily Changelog – September 16, 2025

    Daily Changelog – September 16, 2025

    Improvements

    • Changed agent terminology from “PTO” to “vacation” throughout system prompts and interface to match company usage
    • Added confirmation step to agent time off requests – agent now presents request details for user approval before submitting
    • Improved agent response format to display natural text instead of raw JSON in conversation history
    • Enhanced agent system prompt to default to “vacation” type unless user specifies sick leave, personal time, or other types

    Fixes

    • Fixed 400+ linting violations across 70+ files by removing eslint.ignoreDuringBuilds and typescript.ignoreBuildErrors from next.config.ts
    • Replaced all Date instantiations with proper time library functions from src/lib/time.ts
    • Converted all date-fns imports to use centralized time utilities
    • Fixed TypeScript any types with proper type definitions
    • Removed unused variables and imports across codebase
    • Achieved 100% reduction in linting violations (400+ → 0)

    Notes

    • Agent now follows two-step process: confirm_time_off tool for user confirmation, then create_time_off_request after approval
    • Build process now properly enforces code quality standards and will fail on violations
  • Fulfillment – Daily Changelog – September 15, 2025

    Fulfillment – Daily Changelog – September 15, 2025

    Changelog – September 15, 2025

    Order Sync Logic Updates

    Enhanced Shipping Address Synchronization

    • Added shipping address update utility in src/lib/orderUtils.ts
    • New updateOrderShippingAddress() function to update shipping fields in mama_tried_orders
    • Updates: shipping_address, shipping_name, shipping_address1, shipping_city, shipping_state, shipping_country, shipping_zip, and updated_at

    Shopify Webhook Enhancements

    • Updated webhook handler in src/app/api/webhooks/shopify/route.ts
    • Added support for orders/updated and orders/edited webhook topics
    • Automatically refreshes shipping address when Shopify order is modified
    • Returns early for order updates to avoid duplicate processing

    Scheduled Sync Improvements

    • Enhanced order sync in src/app/api/orders/sync/route.ts
    • Added shipping address refresh for existing orders during sync
    • Ensures shipping data stays current even for orders not recently updated

    Packing-Time Final Check

    • Added final shipping verification at packing time in multiple endpoints:
    • src/app/api/shipments/route.ts – Before creating shipments
    • src/app/api/batches/[id]/send-to-shippingeasy/route.ts – Before sending to ShippingEasy
    • src/app/api/batches/[id]/bulk-weight/route.ts – Before bulk weight operations
    • Fetches latest Shopify order data and updates shipping fields as final safeguard

    Multi-Layer Protection Strategy

    • Implemented three-tier shipping address sync:
    1. Immediate: Webhook updates on orders/updated events
    2. Scheduled: Regular sync refreshes existing orders
    3. Final: Packing-time check ensures accuracy before shipment creation

    Technical Details

    • Uses existing getShopifyOrder() utility to fetch latest order data
    • Leverages transformRestOrder() for consistent data normalization
    • All updates are idempotent and safe to run multiple times
    • Graceful error handling – failures don’t break core functionality

    Visual Indicators

    • Added “Address Updated” badge on orders page (src/app/(authenticated)/orders/page.tsx)
    • Shows orange badge when shipping_updated_at is set
    • Indicates when shipping address was modified after order creation
    • Helps identify orders with address changes at a glance

    Database Schema Updates

    • Added shipping_updated_at column to mama_tried_orders table
    • Tracks timestamp of actual shipping address changes
    • Only set when address actually changes (not on every order update)
    • Used for visual indicators and change tracking

    Debug and Testing Tools

    • Created comprehensive debug endpoints:
    • /api/debug/shipping-updates – List orders with shipping updates
    • /api/debug/shipping-changes – Show before/after address changes
    • /api/debug/test-webhook-endpoint – Test webhook accessibility
    • /api/debug/webhook-diagnostics – Troubleshooting guide
    • /api/debug/latest-updates – Recent order activity
    • /api/debug/test-shipping-update – Simulate address changes
    • /api/debug/reset-shipping-updated-at – Clear false positives

    Shopify Webhook Configuration

    • Configured three webhook events in Shopify Admin:
    • Order creation → https://fulfillment.orchardstreetpress.com/api/webhooks/shopify
    • Order updated → https://fulfillment.orchardstreetpress.com/api/webhooks/shopify
    • Order edited → https://fulfillment.orchardstreetpress.com/api/webhooks/shopify
    • All webhooks use JSON format and proper HMAC signature verification

    Benefits

    • Ensures shipping addresses are always current when orders are packed
    • Handles edge cases where orders are modified after initial import
    • Provides redundancy to catch any missed updates
    • Maintains data integrity throughout the fulfillment process
    • Visual feedback for staff to quickly identify address changes
    • Comprehensive debugging tools for troubleshooting
  • Time Clock – Daily Changelog – September 15, 2025

    Daily Changelog – September 15, 2025

    Fixes

    • Fixed break constraint violation in time clock import by adding validation to skip breaks with identical start/end times
    • Updated import scripts to check break_end > break_start before insertion in all import processes
    • Added logging for invalid breaks to help debug future import issues
    • Prevented database constraint violation errors during time clock data import

    Notes

    • Import process now handles edge cases where break start and end times are identical
    • All import scripts (Python and JavaScript) now include proper break validation