# Code Reference: Collapsed Row Structure (NEW Page)

This document shows the exact code sections that define the collapsed row layout in the NEW profitability page.

**File:** `/home/centralgoparts/public_html/resources/views/filament/pages/profitability.blade.php`

---

## Complete Collapsed Row Structure (Lines 1799-1883)

### Outer Card Container
```blade
<div class="order-item-card {{ $profitClass }}" data-order-id="{{ $order->id }}">
```

**Variables:**
- `$profitClass`: Either `'negative-profit'` or `'positive-profit'` (with optional `' own-stock'` appended)
- Applied styling:
  - `.negative-profit`: Red left border, light red background
  - `.positive-profit`: Green left border
  - `.own-stock`: Additional background color coding

---

### The Collapsed Summary Row (Lines 1801-1883)

```blade
<div class="order-summary" onclick="toggleOrderDetails({{ $order->id }})">
    <div class="order-summary-grid">
```

**CSS Classes:**
- `.order-summary`: Clickable row that triggers expansion
- `.order-summary-grid`: Flexbox layout for sections

---

## Section 1: Order Info (Lines 1803-1808)

```blade
<!-- Order Info -->
<div class="summary-item order-info">
    <div class="summary-label">Order / Date</div>
    <div class="summary-value">#{{ $order->external_order_id }}</div>
    <div class="summary-subvalue">{{ \Carbon\Carbon::parse($order->date_placed)->format('M d, Y') }}</div>
</div>
```

**Data Displayed:**
- Primary: Order number (e.g., #12345)
- Secondary: Date in "Aug 15, 2025" format

**CSS Classes:**
- `.summary-item.order-info`: flex: 1.5 (slightly wider than default)
- `.summary-label`: Small uppercase label
- `.summary-value`: Main value (12px, bold)
- `.summary-subvalue`: Secondary value (10px, grey)

---

## Section 2: Product Info (Lines 1810-1815)

```blade
<!-- Product Info -->
<div class="summary-item">
    <div class="summary-label">Product / Category</div>
    <div class="summary-value" title="{{ $order->item_name }}">{{ $order->partslink }}</div>
    <div class="summary-subvalue">{{ $order->category }}</div>
</div>
```

**Data Displayed:**
- Primary: Partslink (part number)
- Secondary: Category name
- Hover: Full item name via title attribute

**CSS Classes:**
- `.summary-item`: flex: 1 (default width)
- Text overflow: ellipsis for long part numbers

---

## Section 3: Supplier (Lines 1817-1821)

```blade
<!-- Supplier -->
<div class="summary-item">
    <div class="summary-label">Supplier</div>
    <div class="summary-value">{{ $order->supplier ?: 'N/A' }}</div>
</div>
```

**Data Displayed:**
- Supplier name or "N/A" if not available

**CSS Classes:**
- `.summary-item`: flex: 1 (default width)

---

## Section 4: Channel & Customer (Lines 1823-1830)

```blade
<!-- Channel & Customer -->
<div class="summary-item">
    <div class="summary-label">Channel / Customer</div>
    <div class="summary-value">{{ $order->sales_channel }}</div>
    <div class="summary-subvalue" style="font-size: 11px; color: #6c757d; margin-top: 2px;">
        {{ \Illuminate\Support\Str::limit($order->billing_name ?? 'N/A', 25) }}
    </div>
</div>
```

**Data Displayed:**
- Primary: Sales channel (Amazon, eBay, etc.)
- Secondary: Customer name (truncated to 25 characters)

**CSS Classes:**
- `.summary-item`: flex: 1 (default width)
- Inline style for customer name: 11px, grey text

---

## Section 5: Financial Summary (Lines 1832-1852)

### Container & Financial Metrics (Lines 1832-1847)

```blade
<!-- Financial Summary -->
<div class="summary-item financial">
    <div class="financial-summary">
        <div class="financial-metric">
            <div class="label">Sale</div>
            <div class="value">${{ number_format($order->sales_price, 2) }}</div>
        </div>
        <div class="financial-metric">
            <div class="label">Cost</div>
            <div class="value">${{ number_format($totalCosts, 2) }}</div>
        </div>
        <div class="financial-metric">
            <div class="label">COGS %</div>
            <div class="value {{ $cogsClass }}">{{ number_format($cogsPercent, 1) }}%</div>
        </div>
    </div>
```

**Data Displayed:**
1. **Sale**: Total sales price (`$order->sales_price`)
2. **Cost**: Total costs (`$totalCosts`)
3. **COGS %**: Cost as percentage of sale (`$cogsPercent`)

**Key Variables (calculated earlier in blade, lines 1772-1796):**

```php
// Total Costs calculation
$totalCosts = $order->our_buy_price
            + ($order->commission_and_fee ?: 0)
            + ($order->channel_advertisement_fee_amount ?: 0)
            + ($order->payment_processor_fee ?: 0)
            + ($order->repayment_processor_fees ?: 0)
            + ($order->sales_price * (($order->loss_rate ?: 0) / 100))
            + ($order->additional_cost ?: 0)
            + $amazonAdditionalCost
            + ($order->label_cost ?: 0);

// COGS % calculation
$cogsPercent = $order->sales_price > 0 ? ($totalCosts / $order->sales_price) * 100 : 0;
$cogsClass = $cogsPercent >= 100 ? 'text-danger' : ($cogsPercent >= 70 ? 'text-warning' : 'text-success');
```

**CSS Classes:**
- `.summary-item.financial`: text-align: center, position: relative
- `.financial-summary`: flex layout with gap
- `.financial-metric`: centered text
- `$cogsClass`: Dynamic class for color coding
  - `text-success`: Green (< 70%)
  - `text-warning`: Yellow (70-99%)
  - `text-danger`: Red (≥ 100%)

### Expand Indicator (Lines 1848-1852)

```blade
    <!-- Expand Indicator -->
    <div style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); font-size: 14px; color: #9ca3af;">
        <i class="fa fa-chevron-down expand-chevron" id="chevron-{{ $order->id }}"></i>
    </div>
</div>
```

**Purpose:**
- Chevron icon to indicate expandability
- Positioned absolutely within financial summary section
- Rotates 180° when row is expanded (via CSS class `.rotated`)

---

## Section 6: Profit Summary (Lines 1854-1869)

```blade
<!-- Profit Summary -->
<div class="summary-item profit">
    <div class="summary-label">Standard / Calculated</div>
    <div class="summary-value {{ $order->gross_profit >= 0 ? 'positive' : 'negative' }}">
        {{ number_format($order->gross_profit, 1) }}%
        <span style="color: #666; font-size: 12px;">/</span>
        <span class="{{ $calculatedGrossProfit >= 0 ? 'positive' : 'negative' }}">
            {{ number_format($calculatedGrossProfit, 1) }}%
        </span>
    </div>
    <div class="summary-subvalue">
        {{ ($order->gross_margin < 0 ? '-' : '') }}${{ number_format(abs($order->gross_margin), 2) }}
        <span style="color: #666;">/</span>
        {{ ($calculatedGrossMargin < 0 ? '-' : '') }}${{ number_format(abs($calculatedGrossMargin), 2) }}
    </div>
</div>
```

**Data Displayed:**

**Primary Value (Line 1):**
- Standard Gross Profit %: `$order->gross_profit`
- "/" separator (grey)
- Calculated Gross Profit %: `$calculatedGrossProfit`

**Secondary Value (Line 2):**
- Standard Gross Margin $: `$order->gross_margin`
- "/" separator (grey)
- Calculated Gross Margin $: `$calculatedGrossMargin`

**Key Variables (calculated earlier, lines 1785-1792):**

```php
// Total Credits
$totalCredits = ($order->usauto_rebate ?: 0)
              + ($order->supplier_credits ?: 0)
              + ($order->carrier_credits ?: 0);

// Calculated Gross Margin $
$calculatedGrossMargin = $order->sales_price - $totalCosts + $totalCredits;

// Calculated Gross Profit %
$calculatedGrossProfit = $order->sales_price > 0
    ? (($calculatedGrossMargin / $order->sales_price) * 100)
    : 0;
```

**CSS Classes:**
- `.summary-item.profit`: flex: 1.2, text-align: right
- `.summary-value.positive`: Green color (#0d6e0d)
- `.summary-value.negative`: Red color (#dc3545)
- Individual spans for each value get independent color coding

**Color Logic:**
- Each percentage independently colored (Standard and Calculated can differ)
- Each dollar amount independently colored
- "/" separator is always grey (#666)

---

## Section 7: Badges (Lines 1871-1880)

```blade
<!-- Badges -->
<div class="summary-item" style="flex: 0.5; text-align: right; padding-right: 35px;">
    @if($isOwnStock)
        <span class="badge badge-secondary">Own Stock</span>
    @else
        <span class="confidence-indicator confidence-{{ $confidence }}">
            {{ ucfirst($confidence) }}
        </span>
    @endif
</div>
```

**Data Displayed:**
- Either "Own Stock" badge (grey)
- OR Confidence level badge (High/Medium/Low)

**Variable: `$isOwnStock` (calculated earlier, lines 1760-1764):**

```php
$isOwnStock = \App\Models\Note::where('order_id', $order->order_id)
    ->where(function($q) {
        $q->whereRaw("LOWER(note) LIKE '%own stock%'")
          ->orWhereRaw("LOWER(note) LIKE '%our stock%'");
    })->exists();
```

**CSS Classes:**
- `.badge.badge-secondary`: Grey background, white text
- `.confidence-indicator.confidence-high`: Green background (#d4edda)
- `.confidence-indicator.confidence-medium`: Yellow background (#fff3cd)
- `.confidence-indicator.confidence-low`: Red background (#f8d7da)

---

## Section 8: Closing Tags & Expand Icon (Lines 1881-1883)

```blade
        </div>
        <i class="fa fa-chevron-down expand-icon"></i>
    </div>
```

**Note:**
- Additional expand icon at far right of summary row
- Rotates 180° when card is expanded via CSS class manipulation

---

## CSS Styling Reference

### Key CSS Classes (from lines 233-397)

#### Card Container
```css
.order-item-card {
    border-radius: 4px;
    box-shadow: 0 1px 2px rgba(0,0,0,0.08);
    margin-bottom: 12px;
    overflow: hidden;
    transition: all 0.2s ease;
    background: #fff;
    border: 1px solid #e9ecef;
}

.order-item-card.negative-profit {
    border-left: 4px solid #dc3545;
    background-color: #fff5f5;
}

.order-item-card.positive-profit {
    border-left: 4px solid #28a745;
}

.order-item-card.own-stock.positive-profit {
    background-color: #e8f5e9;
}
```

#### Summary Row
```css
.order-summary {
    padding: 8px 12px;
    cursor: pointer;
    position: relative;
    background: rgba(255,255,255,0.7);
}

.order-summary-grid {
    display: flex;
    align-items: center;
    gap: 10px;
}
```

#### Summary Items
```css
.summary-item {
    flex: 1;
    min-width: 0;
}

.summary-item.order-info {
    flex: 1.5;
}

.summary-item.financial {
    text-align: center;
    position: relative;
}

.summary-item.profit {
    text-align: right;
    flex: 1.2;
}
```

#### Labels and Values
```css
.summary-label {
    font-size: 9px;
    color: #6c757d;
    text-transform: uppercase;
    margin-bottom: 1px;
}

.summary-value {
    font-size: 12px;
    font-weight: 600;
    color: #212529;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.summary-value.positive {
    color: #0d6e0d;
}

.summary-value.negative {
    color: #dc3545;
}

.summary-subvalue {
    font-size: 10px;
    color: #6c757d;
    margin-top: 1px;
}
```

#### Financial Summary
```css
.financial-summary {
    display: flex;
    gap: 10px;
    align-items: center;
    justify-content: center;
}

.financial-metric {
    text-align: center;
}

.financial-metric .label {
    font-size: 9px;
    color: #6c757d;
    text-transform: uppercase;
}

.financial-metric .value {
    font-size: 13px;
    font-weight: 600;
}
```

---

## Complete Data Flow Diagram

```
Order Data
    │
    ├─→ external_order_id ──────→ Order / Date section (primary)
    ├─→ date_placed ─────────────→ Order / Date section (secondary)
    │
    ├─→ partslink ───────────────→ Product / Category section (primary)
    ├─→ item_name ───────────────→ Product / Category section (hover)
    ├─→ category ────────────────→ Product / Category section (secondary)
    │
    ├─→ supplier ────────────────→ Supplier section
    │
    ├─→ sales_channel ───────────→ Channel / Customer section (primary)
    ├─→ billing_name ────────────→ Channel / Customer section (secondary)
    │
    ├─→ sales_price ─────────────→ Financial Summary: Sale
    │
    ├─→ [Calculated totalCosts]──→ Financial Summary: Cost
    │   ├─ our_buy_price
    │   ├─ commission_and_fee
    │   ├─ channel_advertisement_fee_amount
    │   ├─ payment_processor_fee
    │   ├─ repayment_processor_fees
    │   ├─ loss_rate (% of sales_price)
    │   ├─ additional_cost
    │   ├─ amazon_additional_cost (if Amazon)
    │   └─ label_cost
    │
    ├─→ [Calculated cogsPercent]─→ Financial Summary: COGS %
    │   └─ (totalCosts / sales_price) * 100
    │
    ├─→ gross_profit ────────────→ Profit Summary: Standard %
    ├─→ gross_margin ────────────→ Profit Summary: Standard $
    │
    ├─→ [Calculated Gross Profit]→ Profit Summary: Calculated %
    │   └─ ((sales_price - totalCosts + totalCredits) / sales_price) * 100
    │
    ├─→ [Calculated Gross Margin]→ Profit Summary: Calculated $
    │   └─ sales_price - totalCosts + totalCredits
    │
    └─→ confidence_level ─────────→ Badge section (if not own stock)
    └─→ [Own Stock Check] ───────→ Badge section (if own stock)
```

---

## Key Formulas

### COGS % (Line 1795-1796)
```php
$cogsPercent = $order->sales_price > 0
    ? ($totalCosts / $order->sales_price) * 100
    : 0;

$cogsClass = $cogsPercent >= 100
    ? 'text-danger'      // Red: ≥ 100%
    : ($cogsPercent >= 70
        ? 'text-warning'  // Yellow: 70-99%
        : 'text-success'  // Green: < 70%
    );
```

### Calculated Gross Margin (Line 1789)
```php
$calculatedGrossMargin = $order->sales_price - $totalCosts + $totalCredits;
```

### Calculated Gross Profit % (Lines 1790-1792)
```php
$calculatedGrossProfit = $order->sales_price > 0
    ? (($calculatedGrossMargin / $order->sales_price) * 100)
    : 0;
```

---

## JavaScript Interaction

### Toggle Function (Lines 1143-1152)
```javascript
function toggleOrderDetails(orderId) {
    const card = document.querySelector('[data-order-id="' + orderId + '"]');
    const chevron = document.getElementById('chevron-' + orderId);
    if (card) {
        card.classList.toggle('expanded');
        if (chevron) {
            chevron.classList.toggle('rotated');
        }
    }
}
```

**Behavior:**
- Clicking anywhere on `.order-summary` triggers this function
- Adds/removes `.expanded` class from card
- Rotates chevron icon 180°
- Reveals `.order-details` section (display: none → display: block)

---

## Summary: Where Each Metric Lives

| Metric | Section | Line(s) | Data Source |
|--------|---------|---------|-------------|
| Order # | Order / Date | 1805 | `$order->external_order_id` |
| Date | Order / Date | 1806 | `$order->date_placed` |
| Partslink | Product / Category | 1812 | `$order->partslink` |
| Category | Product / Category | 1813 | `$order->category` |
| Supplier | Supplier | 1819 | `$order->supplier` |
| Channel | Channel / Customer | 1825 | `$order->sales_channel` |
| Customer | Channel / Customer | 1826-1828 | `$order->billing_name` |
| Sale | Financial Summary | 1836-1837 | `$order->sales_price` |
| Cost | Financial Summary | 1839-1840 | `$totalCosts` (calculated) |
| COGS % | Financial Summary | 1842-1844 | `$cogsPercent` (calculated) |
| Standard % | Profit Summary | 1857-1859 | `$order->gross_profit` |
| Calculated % | Profit Summary | 1860-1862 | `$calculatedGrossProfit` |
| Standard $ | Profit Summary | 1865 | `$order->gross_margin` |
| Calculated $ | Profit Summary | 1867 | `$calculatedGrossMargin` |
| Confidence | Badges | 1876-1878 | `$order->confidence_level` |
| Own Stock | Badges | 1874 | Queried from Notes table |

---

This code reference shows exactly how the collapsed row is structured in the NEW profitability page, with all calculations and data sources documented.
