Browse Source

changes for the table view structure

VISHAL BHANUSHALI 3 tháng trước cách đây
mục cha
commit
0dd2d894af

+ 0 - 0
content_quality_tool_public/static/css/attr-extraction-bkp.css


+ 379 - 0
content_quality_tool_public/static/css/attr-extraction.css

@@ -406,4 +406,383 @@ td{
 
 .select2-container--default .select2-selection--multiple .select2-selection__clear{
     color: red;
+}
+
+
+
+/* inline table css for inside table */
+
+/* Container for the inline detail content */
+.detail-content-tables {
+    padding: 15px;
+    background-color: #f7f7f7;
+    border-top: 3px solid #007bff; /* Primary color separator */
+    border-bottom: 1px solid #ddd;
+}
+
+/* Titles and Separators */
+.section-title h2 {
+    color: #333;
+    font-size: 1.2em;
+    margin-top: 20px;
+    margin-bottom: 10px;
+    border-bottom: 2px solid #ccc;
+    padding-bottom: 5px;
+}
+
+.section-title h3 {
+    color: #555;
+    font-size: 1em;
+    font-weight: 600;
+    margin: 15px 0 8px;
+}
+
+.section-separator {
+    border: 0;
+    height: 1px;
+    background-color: #ddd;
+    margin: 20px 0;
+}
+
+/* Table Styling for Attribute Details */
+.attribute-detail-table {
+    width: 100%;
+    border-collapse: collapse;
+    margin-bottom: 2px;
+    background-color: #fff;
+    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
+}
+
+.attribute-detail-table th, 
+.attribute-detail-table td {
+    padding: 10px 15px;
+    text-align: left;
+    border-bottom: 1px solid #eee;
+}
+
+.attribute-detail-table thead th {
+    background-color: #e9ecef;
+    color: #333;
+    font-weight: bold;
+    text-transform: uppercase;
+    font-size: 0.85em;
+}
+
+/* Row Styling */
+.attribute-detail-table tbody tr:hover {
+    background-color: #f0f8ff; /* Light hover effect */
+}
+
+/* Combined Table Layout */
+.combined-attributes-container {
+    display: grid;
+    /* 3 sections in a row, with slight gap */
+    grid-template-columns: repeat(3, 1fr); 
+    gap: 20px;
+    margin-bottom: 20px;
+}
+
+/* Ensure tables inside the combined container fit */
+.combined-attributes-container .attribute-section {
+    width: 100%;
+}
+
+/* Pills (Badges) for Status and Summary */
+.pill {
+    display: inline-block;
+    padding: 4px 10px;
+    border-radius: 12px;
+    font-size: 0.8em;
+    font-weight: bold;
+    text-transform: uppercase;
+    margin: 0 4px 4px 0;
+}
+
+/* Status-specific pills */
+.status-pill.status-ok {
+    background-color: #d4edda;
+    color: #155724;
+}
+
+.status-pill.status-ko {
+    background-color: #f8d7da;
+    color: #721c24;
+}
+
+.status-pill.status-missing {
+    background-color: #fff3cd;
+    color: #856404;
+}
+
+.status-pill.status-unknown {
+    background-color: #e2e3e5;
+    color: #383d41;
+}
+
+/* Row color based on main status (optional) */
+.attribute-detail-table tr.status-ko {
+    background-color: #fff0f0; 
+}
+
+/* Attribute Summary Pills */
+.attribute-summary-pills {
+    display: flex;
+    gap: 10px;
+    margin: 20px 0;
+    padding-top: 10px;
+    border-top: 1px dashed #ccc;
+}
+.attribute-summary-pills .pill.primary {
+    background-color: #007bff;
+    color: white;
+}
+.attribute-summary-pills .pill.secondary {
+    background-color: #6c757d;
+    color: white;
+}
+
+/* --- Styles for Mandatory Comparison Table --- */
+
+/* Highlight the entire row for a mismatch */
+.comparison-table .mismatch-row {
+    background-color: #fcebeb; /* Very light red background for the whole row */
+    border-left: 5px solid #dc3545; /* Red border on the left */
+}
+
+/* Highlight the AI Value cell when there is a mismatch */
+.comparison-table .mismatch-value {
+    font-weight: bold;
+    color: #dc3545; /* Darker red text */
+}
+
+.comparison-table .found-value {
+    font-weight: bold;
+    color: green; /* Darker red text */
+}
+
+
+
+
+/* Pill for match/mismatch status */
+.status-pill.status-mismatch {
+    background-color: #dc3545; /* Red background */
+    color: white;
+}
+
+.status-pill.status-match {
+    background-color: #28a745; /* Green background */
+    color: white;
+}
+
+/* --- Required Styles for Scrolling, Highlighting, and Layout --- */
+
+/* General Scroll Wrapper for all tables */
+.attribute-scroll-wrapper {
+    max-height: 300px; /* Adjust height as needed */
+    overflow-y: auto; 
+    overflow-x: hidden; 
+    position: relative; 
+    border: 1px solid #ddd; 
+    margin-top: 5px;
+}
+
+/* Fix table headers when scrolling */
+.attribute-scroll-wrapper .attribute-detail-table th {
+    position: sticky; 
+    top: 0; 
+    z-index: 10;
+    background-color: #e9ecef; 
+}
+
+/* Mandatory Comparison Table Highlighting */
+.comparison-table .mismatch-row {
+    background-color: #fcebeb; /* Light red background for the whole row */
+    border-left: 5px solid #dc3545; /* Red border on the left */
+}
+
+.comparison-table .mismatch-value {
+    font-weight: bold;
+    color: #dc3545; /* Darker red text for the AI value cell */
+}
+
+/* Status Pills for Match/Mismatch */
+.status-pill.status-mismatch {
+    background-color: #dc3545; 
+    color: white;
+}
+
+.status-pill.status-match {
+    background-color: #28a745; 
+    color: white;
+}
+
+/* General Table Styling (from previous responses, ensure these are present too) */
+.attribute-detail-table {
+    width: 100%;
+    border-collapse: collapse;
+    background-color: #fff;
+}
+.attribute-detail-table th, .attribute-detail-table td {
+    padding: 10px 15px;
+    text-align: left;
+    border-bottom: 1px solid #eee;
+}
+.combined-attributes-container {
+    display: grid;
+    grid-template-columns: repeat(3, 1fr); 
+    gap: 20px;
+    margin-bottom: 20px;
+}
+
+/* Ensure the general table styles still apply */
+/* .comparison-table th, .comparison-table td { */
+    /* Adjust padding if needed, but inherit from .attribute-detail-table */
+/* } */
+
+/* --- Mandatory Comparison Card Styles --- */
+
+.comparison-cards-container {
+    display: flex;
+    flex-wrap: wrap;
+    gap: 20px;
+    padding: 10px 0;
+}
+
+.comparison-card {
+    flex: 0 0 calc(33.333% - 14px); /* Three cards per row on wider screens */
+    min-width: 300px;
+    border: 1px solid #e0e0e0;
+    border-radius: 8px;
+    overflow: hidden;
+    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
+    transition: transform 0.2s;
+    position: relative;
+    background-color: #fff;
+}
+
+.comparison-card:hover {
+    transform: translateY(-2px);
+    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
+}
+
+.card-header {
+    background-color: #f8f9fa;
+    padding: 12px 15px;
+    font-weight: bold;
+    font-size: 1.1em;
+    color: #333;
+    border-bottom: 1px solid #e0e0e0;
+}
+
+.card-content {
+    display: flex;
+}
+
+.value-box {
+    flex: 1;
+    padding: 15px;
+    min-height: 80px;
+    position: relative;
+}
+
+.original-box {
+    border-right: 1px solid #e0e0e0;
+    background-color: #fcfcfc;
+}
+
+.value-label {
+    font-size: 0.8em;
+    color: #6c757d;
+    text-transform: uppercase;
+    margin-bottom: 5px;
+}
+
+.value-text {
+    font-size: 1em;
+    font-weight: 500;
+    color: #212529;
+}
+
+.value-source {
+    font-size: 0.8em;
+    font-weight: normal;
+    color: #adb5bd;
+    margin-left: 5px;
+}
+
+/* --- MISMATCH STYLES --- */
+
+.mismatch-card {
+    border: 2px solid #dc3545; /* Prominent red border on the card */
+    background-color: #fff8f8; /* Light red background tint */
+}
+
+.mismatch-value {
+    background-color: #fff0f0; /* Very light red background for the AI value box */
+}
+
+.mismatch-indicator {
+    position: absolute;
+    top: 0;
+    right: 0;
+    background-color: #dc3545;
+    color: white;
+    padding: 2px 8px;
+    border-bottom-left-radius: 8px;
+    font-size: 0.85em;
+    font-weight: bold;
+    transform: translateY(-1px); /* Just adjust alignment */
+}
+
+/* Custom CSS to align the button to the right of the header text */
+.api-header-flex {
+    /* Ensures H2 and button are spaced out */
+    display: flex;
+    justify-content: space-between; 
+    align-items: center; 
+    /* Standard Bootstrap card header usually has padding (e.g., 1rem or 16px) */
+    /* If your .card-header has padding-right: 16px, using -6px below gives you 10px (16 - 6 = 10) */
+}
+
+.download-section {
+    /* Adjust this value based on your card-header's existing padding to get exactly 10px spacing. */
+    /* For standard Bootstrap padding (usually around 1rem or 16px), a negative margin is needed */
+    margin-right: -6px; /* Example: If card-header padding is 16px, this results in 10px visible space */
+}
+
+/* Ensure the h2 doesn't take up the full width */
+.api-header-flex h2 {
+    margin-bottom: 0; 
+    line-height: 1.2;
+}
+
+.card-header.api-header-flex {
+    /* Example: Override default padding to 0 on the right */
+    padding-right: 0; 
+}
+
+.download-section {
+    /* Now, this padding controls the 10px spacing from the card's edge */
+    padding-right: 10px; 
+        right: 0px;
+    position: absolute;
+}
+
+
+/* Small button size for card toolbar */
+.btn-sm { padding: 4px 8px; border-radius: 8px; font-size: .85rem; }
+
+/* Slight spacing when the button is beside the Select checkbox */
+.card-config-btn { margin-left: 8px; }
+
+/* Optional: when the attribute chip UI is hidden, keep layout neat */
+.attribute-selectors { transition: opacity .15s ease; }
+.attribute-selectors.hidden { display: none; } /* in case you prefer class toggle */
+
+
+.card-config-btn:hover { filter: brightness(0.98); }
+
+
+#cardsContainer .attribute-selectors{
+    display: inline-block;
 }

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 466 - 379
content_quality_tool_public/static/js/attr-extraction-bkp.js


+ 0 - 917
content_quality_tool_public/static/js/attr-extraction-oldselect.js

@@ -1,917 +0,0 @@
-jQuery.noConflict(); // Release $ to other libraries
-console.log(typeof jQuery);
-// $ = jQuery;
-
-// --- Config ---
-const UPLOAD_API_URL = '/attr/products/upload-excel/'; // TODO: set to your upload endpoint
-const ACCEPT_TYPES = '*'; // e.g., 'image/*,.csv,.xlsx'
-
-var PRODUCT_BASE = [
-    // { id: 1, item_id: 'SKU001', product_name: "Levi's Jeans", product_long_description: 'Classic blue denim jeans with straight fit.', product_short_description: 'Blue denim jeans.', product_type: 'Clothing', image_path: 'media/products/jeans.jpg', image: 'http://127.0.0.1:8000/media/products/jeans.png' },
-    // { id: 2, item_id: 'SKU002', product_name: 'Adidas Running Shoes', product_long_description: 'Lightweight running shoes with breathable mesh and cushioned sole.', product_short_description: "Men's running shoes.", product_type: 'Footwear', image_path: 'media/products/shoes.png', image: 'http://127.0.0.1:8000/media/products/shoes.png' },
-    // { id: 3, item_id: 'SKU003', product_name: 'Nike Sports T-Shirt', product_long_description: 'Moisture-wicking sports tee ideal for training and outdoor activities.', product_short_description: 'Performance t-shirt.', product_type: 'Clothing', image_path: 'media/products/tshirt.png', image: 'http://127.0.0.1:8000/media/products/tshirt.png' },
-    // { id: 4, item_id: 'SKU004', product_name: 'Puma Hoodie', product_long_description: 'Soft fleece hoodie with kangaroo pocket and adjustable drawstring.', product_short_description: 'Casual hoodie.', product_type: 'Clothing', image_path: 'media/products/hoodie.png', image: 'http://127.0.0.1:8000/media/products/hoodie.png' },
-    // { id: 5, item_id: 'SKU005', product_name: 'Ray-Ban Sunglasses', product_long_description: 'Classic aviator sunglasses with UV protection lenses.', product_short_description: 'Aviator sunglasses.', product_type: 'Accessories', image_path: 'media/products/sunglasses.png', image: 'http://127.0.0.1:8000/media/products/sunglasses.png' }
-];
-// --- Data ---
-const mediaUrl = "./../";
-
-document.addEventListener('DOMContentLoaded', () => {
-    jQuery('#full-page-loader').show();  
-    fetch('/attr/products', {
-        method: 'GET', // or 'POST' if your API expects POST
-        headers: {
-            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
-        }
-    })
-    .then(response => response.json())
-    .then(data => {
-        console.log("data",data);
-        // --- Wire up ---
-        PRODUCT_BASE = data;
-        PRODUCT_BASE = PRODUCT_BASE.map((d)=>{return {...d,mandatoryAttributes:["color","size"]}});
-        console.log("PRODUCT_BASE",PRODUCT_BASE);
-        if(PRODUCT_BASE.length > 0){
-            $('#paginationBar').style.display = 'block';
-        }
-        renderProducts();
-        document.getElementById('btnSubmit').addEventListener('click', submitAttributes);
-        document.getElementById('btnReset').addEventListener('click', resetAll);
-        // document.getElementById('btnSelectAll').addEventListener('click', () => {
-        // if (selectedIds.size === PRODUCT_BASE.length) { selectedIds.clear(); } else { selectedIds = new Set(PRODUCT_BASE.map(p => p.id)); }
-        // // renderProducts();
-        // });
-
-        // Replace your existing Select All listener with this:
-          document.getElementById('btnSelectAll').addEventListener('click', () => {
-            // Use the container for the active layout
-            const container = (layoutMode === 'cards')
-              ? document.getElementById('cardsContainer')
-              : document.getElementById('tableContainer');
-
-            // Collect all visible checkboxes
-            const boxes = Array.from(container.querySelectorAll('input[type="checkbox"]'));
-
-            // If every visible checkbox is already checked, we'll deselect; otherwise select all
-            const allChecked = boxes.length > 0 && boxes.every(cb => cb.checked);
-
-            boxes.forEach(cb => {
-              const target = !allChecked; // true to select, false to deselect
-              if (cb.checked !== target) {
-                cb.checked = target;
-                // Trigger your existing "change" handler so selectedIds & row .selected class update
-                cb.dispatchEvent(new Event('change', { bubbles: true }));
-              }
-            });
-
-            // Update the selection pill text (doesn't re-render the list)
-            updateSelectionInfo();
-          });
-        document.getElementById('btnCards').addEventListener('click', () => setLayout('cards'));
-        document.getElementById('btnTable').addEventListener('click', () => setLayout('table'));
-        jQuery('#full-page-loader').hide();
-        // if (data.success) {
-        // }
-    });
-});
-
-var FAKE_API_RESPONSE = {
-    // results: [
-    // { product_id: 'SKU001', mandatory: { 'Clothing Neck Style': 'V-Neck', 'Clothing Top Style': 'Pullover', 'Condition': 'New', 'T-Shirt Type': 'Classic T-Shirt' }, additional: { 'Material': 'Turkish Pima Cotton', 'Size': 'Large', 'Color': 'Blue', 'Brand': 'Sierra', 'Fabric Type': 'Soft & Breathable', 'Fabric Composition': '95% Turkish Pima cotton', 'Care Instructions': 'Machine Washable', 'Sizes Available': 'S-XL' } },
-    // { product_id: 'SKU002', mandatory: { 'Shoe Type': 'Running', 'Closure': 'Lace-Up', 'Condition': 'New', 'Gender': 'Men' }, additional: { 'Upper Material': 'Engineered Mesh', 'Midsole': 'EVA Foam', 'Outsole': 'Rubber', 'Color': 'Black/White', 'Brand': 'Adidas', 'Size': 'UK 9', 'Care Instructions': 'Surface Clean' } },
-    // { product_id: 'SKU003', mandatory: { 'Clothing Neck Style': 'Crew Neck', 'Sleeve Length': 'Short Sleeve', 'Condition': 'New', 'T-Shirt Type': 'Performance' }, additional: { 'Material': 'Polyester Blend', 'Color': 'Red', 'Brand': 'Nike', 'Size': 'Medium', 'Fabric Technology': 'Dri-FIT', 'Care Instructions': 'Machine Wash Cold' } },
-    // { product_id: 'SKU004', mandatory: { 'Clothing Top Style': 'Hoodie', 'Closure': 'Pullover', 'Condition': 'New', 'Fit': 'Relaxed' }, additional: { 'Material': 'Cotton Fleece', 'Color': 'Charcoal', 'Brand': 'Puma', 'Size': 'Large', 'Care Instructions': 'Machine Wash Warm' } },
-    // { product_id: 'SKU005', mandatory: { 'Accessory Type': 'Sunglasses', 'Frame Style': 'Aviator', 'Condition': 'New', 'Lens Protection': 'UV 400' }, additional: { 'Frame Material': 'Metal', 'Lens Color': 'Green', 'Brand': 'Ray-Ban', 'Size': 'Standard', 'Case Included': 'Yes', 'Care Instructions': 'Clean with microfiber' } }
-    // ],
-    // total_products: 5,
-    // successful: 5,
-    // failed: 0
-};
-
-// --- State ---
-let selectedIds = new Set();
-// NEW: Array of objects { item_id: string, mandatory_attrs: { [attribute_name]: string[] } }
-let selectedProductsWithAttributes = [];
-let selectedAttributes = new Array();
-const lastSeen = new Map(); // per-product memory for NEW highlighting (product_id -> maps)
-let layoutMode = 'cards'; // 'cards' | 'table'
-
-// --- Helpers ---
-const $ = (sel) => document.querySelector(sel);
-const el = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; return e; }
-
-function updateSelectionInfo() {
-    const pill = $('#selectionInfo');
-    const total = PRODUCT_BASE.length;
-    // const count = selectedIds.size;
-    const count = selectedProductsWithAttributes.length;
-    pill.textContent = count === 0 ? 'No products selected' : `${count} of ${total} selected`;
-}
-
-function setChecked(id, checked) { if (checked) selectedIds.add(id); else selectedIds.delete(id); updateSelectionInfo(); }
-// function setCheckedAttributes(id,attribute, checked) { if (checked) selectedAttributes.add({id: [attribute]}); else selectedIds.delete({id:[attribute]}); updateSelectionInfo(); }
-
-// --- Chips rendering ---
-function renderChips(container, obj, memoryMap) {
-    container.innerHTML = '';
-    let count = 0;
-    Object.entries(obj || {}).forEach(([k, v]) => {
-    const chip = el('span', 'chip');
-    const kEl = el('span', 'k'); kEl.textContent = k + ':';
-    const vEl = el('span', 'v'); vEl.textContent = ' ' + String(v);
-    chip.appendChild(kEl); chip.appendChild(vEl);
-    const was = memoryMap.get(k);
-    if (was === undefined || was !== v) chip.classList.add('new');
-    container.appendChild(chip);
-    memoryMap.set(k, v);
-    count++;
-    });
-    return count;
-}
-
-function findApiResultForProduct(p, index, api) { return api.results?.find(r => r.product_id === p.item_id) || api.results?.[index] || null; }
-
-// --- Cards layout ---
-function createProductCard(p) {
-    const row = el('div', 'product');
-    // Check selection using the new helper
-    if (isProductSelected(p.item_id)) row.classList.add('selected');
-    // if (selectedIds.has(p.item_id)) row.classList.add('selected');
-
-    const left = el('div', 'thumb');
-    const img = new Image(); img.src = mediaUrl+p.image_path || p.image || '';
-     img.alt = `${p.product_name} image`;
-    console.log("img",img);
-    // img.onerror = () => { img.remove(); const fb = el('div', 'fallback'); fb.textContent = (p.product_name || 'Product').split(' ').map(w => w[0]).slice(0,2).join('').toUpperCase(); left.appendChild(fb); };
-    img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
-    left.appendChild(img);
-
-    const mid = el('div', 'meta');
-    const name = el('div', 'name'); name.textContent = p.product_name || '—';
-    const desc = el('div', 'desc'); desc.innerHTML = p.product_short_description || '';
-    const badges = el('div', 'badges');
-    const sku = el('span', 'pill'); sku.textContent = `SKU: ${p.item_id || '—'}`; badges.appendChild(sku);
-    const type = el('span', 'pill'); type.textContent = p.product_type || '—'; badges.appendChild(type);
-    const long = el('div', 'desc'); long.innerHTML = p.product_long_description || ''; long.style.marginTop = '4px';
-    mid.appendChild(name); mid.appendChild(desc); mid.appendChild(badges); mid.appendChild(long);
-
-
-    // const rightAttribute = el('label', 'select');
-
-    // // Main checkbox: "Select"
-    // const cb_attribute = document.createElement('input');
-    // cb_attribute.type = 'checkbox';
-    // cb_attribute.checked = selectedIds.has(p.item_id);
-    // cb_attribute.addEventListener('change', () => {
-    //   setChecked(p.item_id, cb_attribute.checked);
-    //   row.classList.toggle('selected', cb_attribute.checked);
-    // });
-    // const lbl_attribute = el('span');
-    // lbl_attribute.textContent = 'Select';
-
-    // rightAttribute.appendChild(cb_attribute);
-    // rightAttribute.appendChild(lbl_attribute);
-
-    // // --- New checkbox for mandatory attributes ---
-    // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
-    //   const attrLabel = el('label', 'select-attr');
-    //   const attrCb = document.createElement('input');
-    //   attrCb.type = 'checkbox';
-    //   attrCb.checked = false;  // Not selected by default
-
-    //   attrCb.addEventListener('change', () => {
-    //     if (attrCb.checked) {
-    //       // Select the main checkbox
-    //       cb_attribute.checked = true;
-    //       setChecked(p.item_id, true);
-    //       row.classList.add('selected');
-    //     } else {
-    //       // Optionally uncheck main if attrCb is unchecked
-    //       // (optional logic)
-    //     }
-    //   });
-
-    //   const attrSpan = el('span');
-    //   attrSpan.textContent = `Select mandatory (${p.mandatoryAttributes.join(', ')})`;
-
-    //   attrLabel.appendChild(attrCb);
-    //   attrLabel.appendChild(attrSpan);
-
-    //   rightAttribute.appendChild(attrLabel);
-    // }
-     
-    // const attri = el('p',"pSelectRight");
-    // attri.innerHTML = "Select Attribute : ";
-    // var secondRight = el('label', 'selectRight');
-    // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
-      
-    //   p.mandatoryAttributes.forEach((data,index)=>{  
-             
-    //     const cbSeond = document.createElement('input'); 
-    //     cbSeond.type = 'checkbox'; 
-    //     cbSeond.checked = selectedIds.has(p.item_id);
-    //     cbSeond.addEventListener('change', () => { setChecked(p.item_id, cbSeond.checked); 
-    //     row.classList.toggle('selected', cbSeond.checked); });
-        
-    //     const lblsecond = el('span');
-    //     lblsecond.className = "attributeName"; 
-    //     lblsecond.textContent = data ;
-    //     secondRight.appendChild(cbSeond); secondRight.appendChild(lblsecond);
-    //   })
-
-    // }
-
-    
-    // const right = el('label', 'select');
-    // const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
-    // cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); row.classList.toggle('selected', cb.checked); });
-    // const lbl = el('span'); lbl.textContent = 'Select';
-    // right.appendChild(cb); right.appendChild(lbl);
-
-    // // Inline attributes container (rendered on Submit)
-    // const inline = el('div', 'attr-inline');
-    // inline.dataset.pid = p.item_id; // use item_id for mapping
-
-    // row.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
-
-
-    // --- Main Select Checkbox (Product Selection) ---
-    const right = el('label', 'select');
-    const cb = document.createElement('input'); cb.type = 'checkbox';
-    cb.checked = isProductSelected(p.item_id);
-    const lbl = el('span'); lbl.textContent = 'Select Product';
-    right.appendChild(cb); right.appendChild(lbl);
-
-    // --- Dynamic Attribute Selects ---
-    const attrContainer = el('div', 'attribute-selectors');
-
-    // Find all mandatory and non-mandatory attributes for this product
-    const mandatoryAttributes = p.product_type_details?.filter(a => a.is_mandatory === 'Yes') || [];
-    const optionalAttributes = p.product_type_details?.filter(a => a.is_mandatory !== 'Yes') || [];
-
-    // Helper to update the main state object with all current selections
-    const updateProductState = () => {
-        const isSelected = cb.checked;
-        const currentSelections = {};
-
-        // Only process attributes if the main product is selected
-        if (isSelected) {
-            // Get selections from the dynamic selects
-            attrContainer.querySelectorAll('select').forEach(select => {
-                const attrName = select.dataset.attrName;
-                const selectedOptions = Array.from(select.options)
-                    .filter(option => option.selected)
-                    .map(option => option.value);
-
-                if (selectedOptions.length > 0) {
-                    currentSelections[attrName] = selectedOptions;
-                }
-            });
-        }
-        
-        // Use toggleProductSelection to update the state
-        toggleProductSelection(p.item_id, isSelected, currentSelections);
-        row.classList.toggle('selected', isSelected);
-    };
-
-    // Attach listener to main checkbox
-    cb.addEventListener('change', () => {
-        // Toggle the visibility/enabled state of the attribute selects
-        attrContainer.classList.toggle('disabled', !cb.checked);
-        updateProductState();
-    });
-    
-    // --- Render Mandatory Attributes ---
-    if (mandatoryAttributes.length > 0) {
-        const manTitle = el('p', "pSelectRight mandatory-title");
-        manTitle.innerHTML = "Mandatory Attributes:";
-        attrContainer.appendChild(manTitle);
-
-        mandatoryAttributes.forEach(attr => {
-            const label = el('label', 'attribute-label');
-            label.textContent = `${attr.attribute_name} (${attr.is_mandatory === 'Yes' ? 'Mandatory' : 'Optional'}):`;
-            
-            const select = el('select', 'attribute-select');
-            select.multiple = true;
-            select.dataset.attrName = attr.attribute_name;
-
-            // Get previously selected values or default to all
-            const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
-
-            attr.possible_values.forEach(value => {
-                const option = document.createElement('option');
-                option.value = value;
-                option.textContent = value;
-                // Check if this option should be pre-selected
-                option.selected = initialSelected.includes(value); 
-                select.appendChild(option);
-            });
-
-            select.addEventListener('change', updateProductState); // Update state when a selection changes
-            
-            label.appendChild(select);
-            attrContainer.appendChild(label);
-        });
-    }
-
-    // --- Render Optional Attributes (Same structure, different title) ---
-    if (optionalAttributes.length > 0) {
-        const optTitle = el('p', "pSelectRight optional-title");
-        optTitle.innerHTML = "Optional Attributes:";
-        attrContainer.appendChild(optTitle);
-
-        optionalAttributes.forEach(attr => {
-            const label = el('label', 'attribute-label');
-            label.textContent = `${attr.attribute_name} (Optional):`;
-            
-            const select = el('select', 'attribute-select');
-            select.multiple = true;
-            select.dataset.attrName = attr.attribute_name;
-
-            // Get previously selected values or default to all
-            const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
-
-            attr.possible_values.forEach(value => {
-                const option = document.createElement('option');
-                option.value = value;
-                option.textContent = value;
-                // Check if this option should be pre-selected
-                option.selected = initialSelected.includes(value);
-                select.appendChild(option);
-            });
-
-            select.addEventListener('change', updateProductState);
-            
-            label.appendChild(select);
-            attrContainer.appendChild(label);
-        });
-    }
-
-    // Initialize attribute selectors' enabled state and state data
-    attrContainer.classList.toggle('disabled', !cb.checked);
-    // Initial state setup if the product was already selected (e.g., after a re-render)
-    if (cb.checked) {
-        // This is important to set the initial state correctly on load
-        // We defer this until all selects are mounted, or ensure the initial state is correct.
-        // For simplicity, we assume the data from PRODUCT_BASE already includes selected attributes if a selection exists
-        // (which it won't in this case, so they default to all/empty)
-    }
-
-    const inline = el('div', 'attr-inline');
-    inline.dataset.pid = p.item_id; // use item_id for mapping
-
-    row.addEventListener('click', (e) => {
-        // Only toggle main checkbox if an attribute select or its option wasn't clicked
-        if (e.target.tagName.toLowerCase() !== 'input' && e.target.tagName.toLowerCase() !== 'select' && e.target.tagName.toLowerCase() !== 'option') {
-            cb.checked = !cb.checked;
-            cb.dispatchEvent(new Event('change'));
-        }
-    });
-
-    row.appendChild(left); row.appendChild(mid);
-    
-    row.appendChild(right);
-    // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) { 
-      // const hr = el('hr');
-      // row.appendChild(hr);
-      // row.appendChild(attri);
-      // row.appendChild(secondRight);
-    // }
-    row.appendChild(attrContainer); // Append the new attribute selectors container
-    row.appendChild(inline);
-    
-    return row;
-}
-
-// function renderProductsCards() {
-//     const cards = $('#cardsContainer');
-//     cards.innerHTML = '';
-//     if(PRODUCT_BASE.length > 0){
-//         PRODUCT_BASE.forEach(p => cards.appendChild(createProductCard(p)));
-//     }else{
-//         cards.innerHTML = "<p>No Products Found.</p>"
-//     }
-// }
-
-
-// Cards layout
-function renderProductsCards(items = getCurrentSlice()) {
-  const cards = document.getElementById('cardsContainer');
-  cards.innerHTML = '';
-  if(items.length > 0){
-    items.forEach(p => cards.appendChild(createProductCard(p)));
-  }else{
-      cards.innerHTML = "<p>No Products Found.</p>"
-  }
-}
-
-
-// --- Table layout ---
-function createMiniThumb(p) {
-    const mt = el('div', 'mini-thumb');
-    const img = new Image(); img.src = mediaUrl+p.image_path || p.image || ''; img.alt = `${p.product_name} image`;
-    console.log("img",img);
-    img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
-    // img.onerror = () => { img.remove(); const fb = el('div', 'fallback'); fb.textContent = (p.product_name || 'Product').split(' ').map(w => w[0]).slice(0,2).join('').toUpperCase(); mt.appendChild(fb); };
-    mt.appendChild(img);
-    return mt;
-}
-
-// function renderProductsTable() {
-//     const wrap = $('#tableContainer');
-//     wrap.innerHTML = '';
-//     const table = el('table');
-//     const thead = el('thead'); const trh = el('tr');
-//     const headers = ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'];
-//     headers.forEach(h => { const th = el('th'); th.textContent = h; trh.appendChild(th); });
-//     thead.appendChild(trh); table.appendChild(thead);
-//     const tbody = el('tbody');
-//     if(PRODUCT_BASE.length > 0){
-//         PRODUCT_BASE.forEach(p => {
-//         const tr = el('tr'); tr.id = `row-${p.id}`;
-//         // Select cell
-//         const tdSel = el('td', 'select-cell'); const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.id);
-//         cb.addEventListener('change', () => { setChecked(p.id, cb.checked); tr.classList.toggle('selected', cb.checked); }); tdSel.appendChild(cb); tr.appendChild(tdSel);
-//         // Image
-//         const tdImg = el('td', 'thumb-cell'); tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
-//         // Product name
-//         const tdName = el('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
-//         // SKU
-//         const tdSku = el('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
-//         // Type
-//         const tdType = el('td'); const b = el('span', 'badge'); b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
-//         // Short description
-//         const tdDesc = el('td'); tdDesc.innerHTML = p.product_short_description || ''; tr.appendChild(tdDesc);
-
-//         tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
-//         tbody.appendChild(tr);
-//         });
-//     }else{
-//         const tr = el('tr'); 
-//         // tr.id = `row-${p.id}`;
-//         const tdName = el('td');
-//         tdName.colSpan = 6;
-//         tdName.innerHTML = "No Products Found."
-//         tr.appendChild(tdName);
-//         // tr.colspan = 6;
-//         // tr.innerHTML 
-//         tbody.appendChild(tr);
-//     }
-
-//     table.appendChild(tbody);
-//     wrap.appendChild(table);
-// }
-
-// --- Inline attributes rendering ---
-
-
-// Table layout
-function renderProductsTable(items = getCurrentSlice()) {
-  const wrap = document.getElementById('tableContainer');
-  wrap.innerHTML = '';
-  const table = document.createElement('table');
-  const thead = document.createElement('thead'); const trh = document.createElement('tr');
-  ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
-    const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
-  });
-  thead.appendChild(trh); table.appendChild(thead);
-  const tbody = document.createElement('tbody');
-  if(items.length > 0 ){
-    items.forEach(p => {
-        const tr = document.createElement('tr'); tr.id = `row-${p.id}`;
-        const tdSel = document.createElement('td'); tdSel.className = 'select-cell';
-        const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
-        cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); tr.classList.toggle('selected', cb.checked); });
-        tdSel.appendChild(cb); tr.appendChild(tdSel);
-
-        const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
-        const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
-        const tdSku  = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
-        const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
-        const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
-
-        tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
-        tbody.appendChild(tr);
-    });
-  }else{
-    const tr = el('tr'); 
-    // tr.id = `row-${p.id}`;
-    const tdName = el('td');
-    tdName.colSpan = 6;
-    tdName.innerHTML = "No Products Found."
-    tr.appendChild(tdName);
-    // tr.colspan = 6;
-    // tr.innerHTML 
-    tbody.appendChild(tr);
-  }
-
-  table.appendChild(tbody);
-  wrap.appendChild(table);
-}
-
-
-function renderInlineForCards() {
-    const api = FAKE_API_RESPONSE;
-    // Clear all inline sections first
-    document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
-
-    PRODUCT_BASE.forEach((p, idx) => {
-    const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
-    if (!inline) return;
-    if (!selectedIds.has(p.item_id)) return; // only show for selected
-    const res = findApiResultForProduct(p, idx, api);
-    const pid = p.item_id;
-    if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
-    const mem = lastSeen.get(pid);
-
-    // Build sections
-    const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
-    const manChips = el('div', 'chips');
-    const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
-    const addChips = el('div', 'chips');
-
-    const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
-    const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
-
-    const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
-    const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
-    const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
-    counts.appendChild(c1); counts.appendChild(c2);
-
-    inline.appendChild(manTitle); inline.appendChild(manChips);
-    inline.appendChild(addTitle); inline.appendChild(addChips);
-    inline.appendChild(counts);
-    });
-
-    // Update summary
-    $('#statTotal').textContent = api.total_products ?? 0;
-    $('#statOk').textContent = api.successful ?? 0;
-    $('#statKo').textContent = api.failed ?? 0;
-    $('#api-summary').style.display = 'block';
-    
-    
-}
-
-function renderInlineForTable() {
-    const api = FAKE_API_RESPONSE;
-    const table = $('#tableContainer');
-    if (!table) return;
-    // Remove existing detail rows
-    table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
-
-    PRODUCT_BASE.forEach((p, idx) => {
-    if (!selectedIds.has(p.item_id)) return;
-    const res = findApiResultForProduct(p, idx, api);
-    const pid = p.item_id;
-    if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
-    const mem = lastSeen.get(pid);
-
-    const tbody = table.querySelector('tbody');
-    const baseRow = tbody.querySelector(`#row-${p.id}`);
-    if (!baseRow) return;
-
-    const detail = el('tr', 'detail-row');
-    const td = el('td'); td.colSpan = 6; // number of columns
-    const content = el('div', 'detail-content');
-
-    const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
-    const manChips = el('div', 'chips');
-    const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
-    const addChips = el('div', 'chips');
-
-    const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
-    const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
-
-    const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
-    const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
-    const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
-    counts.appendChild(c1); counts.appendChild(c2);
-
-    content.appendChild(manTitle); content.appendChild(manChips);
-    content.appendChild(addTitle); content.appendChild(addChips);
-    content.appendChild(counts);
-    td.appendChild(content); detail.appendChild(td);
-
-    // insert after base row
-    baseRow.insertAdjacentElement('afterend', detail);
-    });
-
-    // Update summary
-    $('#statTotal').textContent = api.total_products ?? 0;
-    $('#statOk').textContent = api.successful ?? 0;
-    $('#statKo').textContent = api.failed ?? 0;
-}
-
-function renderInlineAttributes() {
-    if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
-}
-
-// --- Main rendering ---
-function renderProducts() {
-    if (layoutMode === 'cards') {
-    $('#cardsContainer').style.display = '';
-    $('#tableContainer').style.display = 'none';
-    console.log("PRODUCT_BASE",PRODUCT_BASE);
-    renderProductsCards();
-    } else {
-    $('#cardsContainer').style.display = 'none';
-    $('#tableContainer').style.display = '';
-    renderProductsTable();
-    }
-    updateSelectionInfo();
-    renderPagination();               
-
-    // If there is a selection, re-render inline attributes (persist across toggle)
-    if (selectedIds.size > 0) renderInlineAttributes();
-}
-
-// --- Submit & Reset ---
-function submitAttributes() {
-  // Check the length of the new array
-    if (selectedProductsWithAttributes.length === 0) { 
-        alert('Please select at least one product.'); 
-        return; 
-    } 
-    // if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
-    console.log("selectedIds",selectedIds);
-    jQuery('#full-page-loader').show();  
-    // let inputArray = {
-    //       "product_ids" : [...selectedIds]
-    //     }
-    const extractAdditional = document.getElementById('extract_additional').checked;
-    const processImage = document.getElementById('process_image').checked;
-
-    // Transform the new state array into the required API format
-    const itemIds = selectedProductsWithAttributes.map(p => p.item_id);
-    
-    // Create the mandatory_attrs map: { item_id: { attr_name: [values] } }
-    // NOTE: The backend API you showed expects a flattened list of "mandatory_attrs"
-    // like: { "color": ["color", "shade"], "size": ["size", "fit"] } 
-    // It seems to ignore the selected product-specific values and uses a general list of synonyms.
-    // Assuming the request needs a general map of *all unique* selected attributes across all selected products:
-    
-    let mandatoryAttrsMap = {};
-    selectedProductsWithAttributes.forEach(product => {
-        // Merge attributes from all selected products
-        Object.assign(mandatoryAttrsMap, product.mandatory_attrs);
-    });
-
-    // If the API expects the complex, product-specific payload from your Q1 example:
-    const payloadForQ1 = selectedProductsWithAttributes.map(p => ({
-        item_id: p.item_id,
-        mandatory_attrs: p.mandatory_attrs
-    }));
-
-    let inputArray = {
-              "products": payloadForQ1,
-              
-              "model": "llama-3.1-8b-instant",
-              "extract_additional": extractAdditional,
-              "process_image": processImage
-            }
-    let raw = JSON.stringify(inputArray);
-     fetch('/attr/batch-extract/', {
-        method: 'POST', // or 'POST' if your API expects POST
-        headers: {
-            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
-            'Content-Type': "application/json"
-        },
-        body: raw
-    })
-    .then(response => response.json())
-    .then(data => {
-        console.log("response data",data); 
-        FAKE_API_RESPONSE = data;   
-        renderInlineAttributes();
-        jQuery('#full-page-loader').hide();  
-     });
-}
-
-function resetAll() {
-  selectedProductsWithAttributes = []; // Reset the main array
-    // selectedIds.clear();
-    lastSeen.clear();
-    renderProducts();
-    // Clear summary
-    document.getElementById('statTotal').textContent = '0';
-    document.getElementById('statOk').textContent = '0';
-    document.getElementById('statKo').textContent = '0';
-    $('#api-summary').style.display = 'none';
-}
-
-function setLayout(mode) {
-    layoutMode = mode;
-    const btnCards = document.getElementById('btnCards');
-    const btnTable = document.getElementById('btnTable');
-    if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
-    else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
-    renderProducts();
-}
-
-
-// Upload elements (Bootstrap modal version)
-const uploadModalEl = document.getElementById('uploadModal');
-const dropzone      = document.getElementById('dropzone');
-const uploadFiles   = document.getElementById('uploadFiles');
-const fileInfo      = document.getElementById('fileInfo');
-const uploadBar     = document.getElementById('uploadBar');
-const uploadStatus  = document.getElementById('uploadStatus');
-
-// Reset modal on show
-uploadModalEl.addEventListener('shown.bs.modal', () => {
-  uploadStatus.textContent = '';
-  uploadStatus.className = '';             // clear success/error class
-  uploadBar.style.width = '0%';
-  uploadBar.setAttribute('aria-valuenow', '0');
-  uploadFiles.value = '';
-  uploadFiles.setAttribute('accept', ACCEPT_TYPES);
-  fileInfo.textContent = 'No files selected.';
-});
-
-function describeFiles(list) {
-  if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
-  const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
-  fileInfo.textContent = names.join(', ');
-}
-
-// Drag & drop feedback
-['dragenter','dragover'].forEach(evt => {
-  dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
-});
-['dragleave','drop'].forEach(evt => {
-  dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
-});
-
-// Handle drop
-dropzone.addEventListener('drop', e => {
-  uploadFiles.files = e.dataTransfer.files;
-  describeFiles(uploadFiles.files);
-});
-
-// Click to browse
-// dropzone.addEventListener('click', () => uploadFiles.click());
-
-// Picker change
-uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
-
-function startUpload() {
-  const files = uploadFiles.files;
-  if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
-  jQuery('#full-page-loader').show();
-  uploadStatus.textContent = 'Uploading...';
-  uploadStatus.className = ''; // neutral
-  uploadBar.style.width = '0%';
-  uploadBar.setAttribute('aria-valuenow', '0');
-
-  const form = new FormData();
-  Array.from(files).forEach(f => form.append('file', f));
-  // form.append('uploaded_by', 'Vishal'); // example extra field
-
-  const xhr = new XMLHttpRequest();
-  xhr.open('POST', UPLOAD_API_URL, true);
-  // If you need auth:
-  // xhr.setRequestHeader('Authorization', 'Bearer <token>');
-
-  xhr.upload.onprogress = (e) => {
-    if (e.lengthComputable) {
-      const pct = Math.round((e.loaded / e.total) * 100);
-      uploadBar.style.width = pct + '%';
-      uploadBar.setAttribute('aria-valuenow', String(pct));
-    }
-  };
-
-  xhr.onreadystatechange = () => {
-    if (xhr.readyState === 4) {
-      const ok = (xhr.status >= 200 && xhr.status < 300);
-      try {
-        const resp = JSON.parse(xhr.responseText || '{}');
-        uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
-      } catch {
-        uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
-      }
-      uploadStatus.className = ok ? 'success' : 'error';
-      // Optional: auto-close the modal on success after 1.2s:
-      // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
-    }
-  };
-
-  xhr.onerror = () => {
-    uploadStatus.textContent = 'Network error during upload.';
-    uploadStatus.className = 'error';
-  };
-
-  xhr.send(form);
-  setTimeout(()=>{
-      jQuery('#uploadModal').modal('hide');
-  },3000)
-  jQuery('#full-page-loader').hide();
-
-}
-
-// Wire Start button
-document.getElementById('uploadStart').addEventListener('click', startUpload);
-// Cancel button already closes the modal via data-bs-dismiss
-
-
-
-
-// --- Pagination state ---
-let page = 1;
-let pageSize = 5; // default rows per page
-
-function totalPages() {
-  return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
-}
-
-function clampPage() {
-  page = Math.min(Math.max(1, page), totalPages());
-}
-
-function getCurrentSlice() {
-  clampPage();
-  const start = (page - 1) * pageSize;
-  return PRODUCT_BASE.slice(start, start + pageSize);
-}
-
-function renderPagination() {
-  const bar = document.getElementById('paginationBar');
-  if (!bar) return;
-
-  const tp = totalPages();
-  clampPage();
-
-  bar.innerHTML = `
-    <div class="page-size">
-      <label for="pageSizeSelect">Rows per page</label>
-      <select id="pageSizeSelect">
-        <option value="5"  ${pageSize===5  ? 'selected' : ''}>5</option>
-        <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
-        <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
-        <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
-        <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
-      </select>
-    </div>
-
-    <div class="pager">
-      <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
-      <span class="page-info">Page ${page} of ${tp}</span>
-      <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
-    </div>
-  `;
-
-  // wire events
-  document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
-  document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
-
-  const sel = document.getElementById('pageSizeSelect');
-  if (sel) {
-    sel.addEventListener('change', () => {
-      const val = sel.value;
-      pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
-      page = 1;            // reset to first page when size changes
-      renderProducts();
-    });
-  }
-}
-
-// Function to add/remove product from the state and manage its attributes
-function toggleProductSelection(itemId, isChecked, attributes = {}) {
-    const index = selectedProductsWithAttributes.findIndex(p => p.item_id === itemId);
-
-    if (isChecked) {
-        // If selecting, ensure the product object exists in the array
-        if (index === -1) {
-            selectedProductsWithAttributes.push({
-                item_id: itemId,
-                mandatory_attrs: attributes
-            });
-        } else {
-            // Update attributes if the product is already selected
-            selectedProductsWithAttributes[index].mandatory_attrs = attributes;
-        }
-    } else {
-        // If deselecting, remove the product object from the array
-        if (index !== -1) {
-            selectedProductsWithAttributes.splice(index, 1);
-        }
-    }
-    updateSelectionInfo();
-}
-
-// Function to get the current mandatory attributes for a selected item
-function getSelectedAttributes(itemId) {
-    const productEntry = selectedProductsWithAttributes.find(p => p.item_id === itemId);
-    return productEntry ? productEntry.mandatory_attrs : {};
-}
-
-// Helper to check if a product is selected
-function isProductSelected(itemId) {
-    return selectedProductsWithAttributes.some(p => p.item_id === itemId);
-}
-
-// Helper to check if a specific attribute/value is selected
-function isAttributeValueSelected(itemId, attrName, value) {
-    const attrs = getSelectedAttributes(itemId);
-    const values = attrs[attrName];
-    return values ? values.includes(value) : false; // Default all selected when first loaded
-}

+ 0 - 714
content_quality_tool_public/static/js/attr-extraction-working.js

@@ -1,714 +0,0 @@
-jQuery.noConflict(); // Release $ to other libraries
-console.log(typeof jQuery);
-// $ = jQuery;
-
-// --- Config ---
-const UPLOAD_API_URL = '/attr/products/upload-excel/'; // TODO: set to your upload endpoint
-const ACCEPT_TYPES = '*'; // e.g., 'image/*,.csv,.xlsx'
-
-var PRODUCT_BASE = [
-    // { id: 1, item_id: 'SKU001', product_name: "Levi's Jeans", product_long_description: 'Classic blue denim jeans with straight fit.', product_short_description: 'Blue denim jeans.', product_type: 'Clothing', image_path: 'media/products/jeans.jpg', image: 'http://127.0.0.1:8000/media/products/jeans.png' },
-    // { id: 2, item_id: 'SKU002', product_name: 'Adidas Running Shoes', product_long_description: 'Lightweight running shoes with breathable mesh and cushioned sole.', product_short_description: "Men's running shoes.", product_type: 'Footwear', image_path: 'media/products/shoes.png', image: 'http://127.0.0.1:8000/media/products/shoes.png' },
-    // { id: 3, item_id: 'SKU003', product_name: 'Nike Sports T-Shirt', product_long_description: 'Moisture-wicking sports tee ideal for training and outdoor activities.', product_short_description: 'Performance t-shirt.', product_type: 'Clothing', image_path: 'media/products/tshirt.png', image: 'http://127.0.0.1:8000/media/products/tshirt.png' },
-    // { id: 4, item_id: 'SKU004', product_name: 'Puma Hoodie', product_long_description: 'Soft fleece hoodie with kangaroo pocket and adjustable drawstring.', product_short_description: 'Casual hoodie.', product_type: 'Clothing', image_path: 'media/products/hoodie.png', image: 'http://127.0.0.1:8000/media/products/hoodie.png' },
-    // { id: 5, item_id: 'SKU005', product_name: 'Ray-Ban Sunglasses', product_long_description: 'Classic aviator sunglasses with UV protection lenses.', product_short_description: 'Aviator sunglasses.', product_type: 'Accessories', image_path: 'media/products/sunglasses.png', image: 'http://127.0.0.1:8000/media/products/sunglasses.png' }
-];
-// --- Data ---
-const mediaUrl = "./../";
-
-document.addEventListener('DOMContentLoaded', () => {
-    jQuery('#full-page-loader').show();  
-    fetch('/attr/products', {
-        method: 'GET', // or 'POST' if your API expects POST
-        headers: {
-            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
-        }
-    })
-    .then(response => response.json())
-    .then(data => {
-        console.log("data",data);
-        // --- Wire up ---
-        PRODUCT_BASE = data;
-        PRODUCT_BASE = PRODUCT_BASE.map((d)=>{return {...d,mandatoryAttributes:["color","size"]}});
-        console.log("PRODUCT_BASE",PRODUCT_BASE);
-        if(PRODUCT_BASE.length > 0){
-            $('#paginationBar').style.display = 'block';
-        }
-        renderProducts();
-        document.getElementById('btnSubmit').addEventListener('click', submitAttributes);
-        document.getElementById('btnReset').addEventListener('click', resetAll);
-        // document.getElementById('btnSelectAll').addEventListener('click', () => {
-        // if (selectedIds.size === PRODUCT_BASE.length) { selectedIds.clear(); } else { selectedIds = new Set(PRODUCT_BASE.map(p => p.id)); }
-        // // renderProducts();
-        // });
-
-        // Replace your existing Select All listener with this:
-          document.getElementById('btnSelectAll').addEventListener('click', () => {
-            // Use the container for the active layout
-            const container = (layoutMode === 'cards')
-              ? document.getElementById('cardsContainer')
-              : document.getElementById('tableContainer');
-
-            // Collect all visible checkboxes
-            const boxes = Array.from(container.querySelectorAll('input[type="checkbox"]'));
-
-            // If every visible checkbox is already checked, we'll deselect; otherwise select all
-            const allChecked = boxes.length > 0 && boxes.every(cb => cb.checked);
-
-            boxes.forEach(cb => {
-              const target = !allChecked; // true to select, false to deselect
-              if (cb.checked !== target) {
-                cb.checked = target;
-                // Trigger your existing "change" handler so selectedIds & row .selected class update
-                cb.dispatchEvent(new Event('change', { bubbles: true }));
-              }
-            });
-
-            // Update the selection pill text (doesn't re-render the list)
-            updateSelectionInfo();
-          });
-        document.getElementById('btnCards').addEventListener('click', () => setLayout('cards'));
-        document.getElementById('btnTable').addEventListener('click', () => setLayout('table'));
-        jQuery('#full-page-loader').hide();
-        // if (data.success) {
-        // }
-    });
-});
-
-var FAKE_API_RESPONSE = {
-    // results: [
-    // { product_id: 'SKU001', mandatory: { 'Clothing Neck Style': 'V-Neck', 'Clothing Top Style': 'Pullover', 'Condition': 'New', 'T-Shirt Type': 'Classic T-Shirt' }, additional: { 'Material': 'Turkish Pima Cotton', 'Size': 'Large', 'Color': 'Blue', 'Brand': 'Sierra', 'Fabric Type': 'Soft & Breathable', 'Fabric Composition': '95% Turkish Pima cotton', 'Care Instructions': 'Machine Washable', 'Sizes Available': 'S-XL' } },
-    // { product_id: 'SKU002', mandatory: { 'Shoe Type': 'Running', 'Closure': 'Lace-Up', 'Condition': 'New', 'Gender': 'Men' }, additional: { 'Upper Material': 'Engineered Mesh', 'Midsole': 'EVA Foam', 'Outsole': 'Rubber', 'Color': 'Black/White', 'Brand': 'Adidas', 'Size': 'UK 9', 'Care Instructions': 'Surface Clean' } },
-    // { product_id: 'SKU003', mandatory: { 'Clothing Neck Style': 'Crew Neck', 'Sleeve Length': 'Short Sleeve', 'Condition': 'New', 'T-Shirt Type': 'Performance' }, additional: { 'Material': 'Polyester Blend', 'Color': 'Red', 'Brand': 'Nike', 'Size': 'Medium', 'Fabric Technology': 'Dri-FIT', 'Care Instructions': 'Machine Wash Cold' } },
-    // { product_id: 'SKU004', mandatory: { 'Clothing Top Style': 'Hoodie', 'Closure': 'Pullover', 'Condition': 'New', 'Fit': 'Relaxed' }, additional: { 'Material': 'Cotton Fleece', 'Color': 'Charcoal', 'Brand': 'Puma', 'Size': 'Large', 'Care Instructions': 'Machine Wash Warm' } },
-    // { product_id: 'SKU005', mandatory: { 'Accessory Type': 'Sunglasses', 'Frame Style': 'Aviator', 'Condition': 'New', 'Lens Protection': 'UV 400' }, additional: { 'Frame Material': 'Metal', 'Lens Color': 'Green', 'Brand': 'Ray-Ban', 'Size': 'Standard', 'Case Included': 'Yes', 'Care Instructions': 'Clean with microfiber' } }
-    // ],
-    // total_products: 5,
-    // successful: 5,
-    // failed: 0
-};
-
-// --- State ---
-let selectedIds = new Set();
-let selectedAttributes = new Array();
-const lastSeen = new Map(); // per-product memory for NEW highlighting (product_id -> maps)
-let layoutMode = 'cards'; // 'cards' | 'table'
-
-// --- Helpers ---
-const $ = (sel) => document.querySelector(sel);
-const el = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; return e; }
-
-function updateSelectionInfo() {
-    const pill = $('#selectionInfo');
-    const total = PRODUCT_BASE.length;
-    const count = selectedIds.size;
-    pill.textContent = count === 0 ? 'No products selected' : `${count} of ${total} selected`;
-}
-
-function setChecked(id, checked) { if (checked) selectedIds.add(id); else selectedIds.delete(id); updateSelectionInfo(); }
-// function setCheckedAttributes(id,attribute, checked) { if (checked) selectedAttributes.add({id: [attribute]}); else selectedIds.delete({id:[attribute]}); updateSelectionInfo(); }
-
-// --- Chips rendering ---
-function renderChips(container, obj, memoryMap) {
-    container.innerHTML = '';
-    let count = 0;
-    Object.entries(obj || {}).forEach(([k, v]) => {
-    const chip = el('span', 'chip');
-    const kEl = el('span', 'k'); kEl.textContent = k + ':';
-    const vEl = el('span', 'v'); vEl.textContent = ' ' + String(v);
-    chip.appendChild(kEl); chip.appendChild(vEl);
-    const was = memoryMap.get(k);
-    if (was === undefined || was !== v) chip.classList.add('new');
-    container.appendChild(chip);
-    memoryMap.set(k, v);
-    count++;
-    });
-    return count;
-}
-
-function findApiResultForProduct(p, index, api) { return api.results?.find(r => r.product_id === p.item_id) || api.results?.[index] || null; }
-
-// --- Cards layout ---
-function createProductCard(p) {
-    const row = el('div', 'product');
-    if (selectedIds.has(p.item_id)) row.classList.add('selected');
-
-    const left = el('div', 'thumb');
-    const img = new Image(); img.src = mediaUrl+p.image_path || p.image || '';
-     img.alt = `${p.product_name} image`;
-    console.log("img",img);
-    // img.onerror = () => { img.remove(); const fb = el('div', 'fallback'); fb.textContent = (p.product_name || 'Product').split(' ').map(w => w[0]).slice(0,2).join('').toUpperCase(); left.appendChild(fb); };
-    img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
-    left.appendChild(img);
-
-    const mid = el('div', 'meta');
-    const name = el('div', 'name'); name.textContent = p.product_name || '—';
-    const desc = el('div', 'desc'); desc.innerHTML = p.product_short_description || '';
-    const badges = el('div', 'badges');
-    const sku = el('span', 'pill'); sku.textContent = `SKU: ${p.item_id || '—'}`; badges.appendChild(sku);
-    const type = el('span', 'pill'); type.textContent = p.product_type || '—'; badges.appendChild(type);
-    const long = el('div', 'desc'); long.innerHTML = p.product_long_description || ''; long.style.marginTop = '4px';
-    mid.appendChild(name); mid.appendChild(desc); mid.appendChild(badges); mid.appendChild(long);
-
-
-    // const rightAttribute = el('label', 'select');
-
-    // // Main checkbox: "Select"
-    // const cb_attribute = document.createElement('input');
-    // cb_attribute.type = 'checkbox';
-    // cb_attribute.checked = selectedIds.has(p.item_id);
-    // cb_attribute.addEventListener('change', () => {
-    //   setChecked(p.item_id, cb_attribute.checked);
-    //   row.classList.toggle('selected', cb_attribute.checked);
-    // });
-    // const lbl_attribute = el('span');
-    // lbl_attribute.textContent = 'Select';
-
-    // rightAttribute.appendChild(cb_attribute);
-    // rightAttribute.appendChild(lbl_attribute);
-
-    // // --- New checkbox for mandatory attributes ---
-    // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
-    //   const attrLabel = el('label', 'select-attr');
-    //   const attrCb = document.createElement('input');
-    //   attrCb.type = 'checkbox';
-    //   attrCb.checked = false;  // Not selected by default
-
-    //   attrCb.addEventListener('change', () => {
-    //     if (attrCb.checked) {
-    //       // Select the main checkbox
-    //       cb_attribute.checked = true;
-    //       setChecked(p.item_id, true);
-    //       row.classList.add('selected');
-    //     } else {
-    //       // Optionally uncheck main if attrCb is unchecked
-    //       // (optional logic)
-    //     }
-    //   });
-
-    //   const attrSpan = el('span');
-    //   attrSpan.textContent = `Select mandatory (${p.mandatoryAttributes.join(', ')})`;
-
-    //   attrLabel.appendChild(attrCb);
-    //   attrLabel.appendChild(attrSpan);
-
-    //   rightAttribute.appendChild(attrLabel);
-    // }
-     
-    const attri = el('p',"pSelectRight");
-    attri.innerHTML = "Select Attribute : ";
-    var secondRight = el('label', 'selectRight');
-    if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
-      
-      p.mandatoryAttributes.forEach((data,index)=>{  
-             
-        const cbSeond = document.createElement('input'); 
-        cbSeond.type = 'checkbox'; 
-        cbSeond.checked = selectedIds.has(p.item_id);
-        cbSeond.addEventListener('change', () => { setChecked(p.item_id, cbSeond.checked); 
-        row.classList.toggle('selected', cbSeond.checked); });
-        
-        const lblsecond = el('span');
-        lblsecond.className = "attributeName"; 
-        lblsecond.textContent = data;
-        secondRight.appendChild(cbSeond); secondRight.appendChild(lblsecond);
-      })
-
-    }
-
-    
-    const right = el('label', 'select');
-    const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
-    cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); row.classList.toggle('selected', cb.checked); });
-    const lbl = el('span'); lbl.textContent = 'Select';
-    right.appendChild(cb); right.appendChild(lbl);
-
-    // Inline attributes container (rendered on Submit)
-    const inline = el('div', 'attr-inline');
-    inline.dataset.pid = p.item_id; // use item_id for mapping
-
-    row.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
-
-    row.appendChild(left); row.appendChild(mid);
-    
-    row.appendChild(right);
-    if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) { 
-      // const hr = el('hr');
-      // row.appendChild(hr);
-      row.appendChild(attri);
-      row.appendChild(secondRight);
-    }
-    row.appendChild(inline);
-    
-    return row;
-}
-
-// function renderProductsCards() {
-//     const cards = $('#cardsContainer');
-//     cards.innerHTML = '';
-//     if(PRODUCT_BASE.length > 0){
-//         PRODUCT_BASE.forEach(p => cards.appendChild(createProductCard(p)));
-//     }else{
-//         cards.innerHTML = "<p>No Products Found.</p>"
-//     }
-// }
-
-
-// Cards layout
-function renderProductsCards(items = getCurrentSlice()) {
-  const cards = document.getElementById('cardsContainer');
-  cards.innerHTML = '';
-  if(items.length > 0){
-    items.forEach(p => cards.appendChild(createProductCard(p)));
-  }else{
-      cards.innerHTML = "<p>No Products Found.</p>"
-  }
-}
-
-
-// --- Table layout ---
-function createMiniThumb(p) {
-    const mt = el('div', 'mini-thumb');
-    const img = new Image(); img.src = mediaUrl+p.image_path || p.image || ''; img.alt = `${p.product_name} image`;
-    console.log("img",img);
-    img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
-    // img.onerror = () => { img.remove(); const fb = el('div', 'fallback'); fb.textContent = (p.product_name || 'Product').split(' ').map(w => w[0]).slice(0,2).join('').toUpperCase(); mt.appendChild(fb); };
-    mt.appendChild(img);
-    return mt;
-}
-
-// function renderProductsTable() {
-//     const wrap = $('#tableContainer');
-//     wrap.innerHTML = '';
-//     const table = el('table');
-//     const thead = el('thead'); const trh = el('tr');
-//     const headers = ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'];
-//     headers.forEach(h => { const th = el('th'); th.textContent = h; trh.appendChild(th); });
-//     thead.appendChild(trh); table.appendChild(thead);
-//     const tbody = el('tbody');
-//     if(PRODUCT_BASE.length > 0){
-//         PRODUCT_BASE.forEach(p => {
-//         const tr = el('tr'); tr.id = `row-${p.id}`;
-//         // Select cell
-//         const tdSel = el('td', 'select-cell'); const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.id);
-//         cb.addEventListener('change', () => { setChecked(p.id, cb.checked); tr.classList.toggle('selected', cb.checked); }); tdSel.appendChild(cb); tr.appendChild(tdSel);
-//         // Image
-//         const tdImg = el('td', 'thumb-cell'); tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
-//         // Product name
-//         const tdName = el('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
-//         // SKU
-//         const tdSku = el('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
-//         // Type
-//         const tdType = el('td'); const b = el('span', 'badge'); b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
-//         // Short description
-//         const tdDesc = el('td'); tdDesc.innerHTML = p.product_short_description || ''; tr.appendChild(tdDesc);
-
-//         tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
-//         tbody.appendChild(tr);
-//         });
-//     }else{
-//         const tr = el('tr'); 
-//         // tr.id = `row-${p.id}`;
-//         const tdName = el('td');
-//         tdName.colSpan = 6;
-//         tdName.innerHTML = "No Products Found."
-//         tr.appendChild(tdName);
-//         // tr.colspan = 6;
-//         // tr.innerHTML 
-//         tbody.appendChild(tr);
-//     }
-
-//     table.appendChild(tbody);
-//     wrap.appendChild(table);
-// }
-
-// --- Inline attributes rendering ---
-
-
-// Table layout
-function renderProductsTable(items = getCurrentSlice()) {
-  const wrap = document.getElementById('tableContainer');
-  wrap.innerHTML = '';
-  const table = document.createElement('table');
-  const thead = document.createElement('thead'); const trh = document.createElement('tr');
-  ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
-    const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
-  });
-  thead.appendChild(trh); table.appendChild(thead);
-  const tbody = document.createElement('tbody');
-  if(items.length > 0 ){
-    items.forEach(p => {
-        const tr = document.createElement('tr'); tr.id = `row-${p.id}`;
-        const tdSel = document.createElement('td'); tdSel.className = 'select-cell';
-        const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
-        cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); tr.classList.toggle('selected', cb.checked); });
-        tdSel.appendChild(cb); tr.appendChild(tdSel);
-
-        const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
-        const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
-        const tdSku  = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
-        const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
-        const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
-
-        tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
-        tbody.appendChild(tr);
-    });
-  }else{
-    const tr = el('tr'); 
-    // tr.id = `row-${p.id}`;
-    const tdName = el('td');
-    tdName.colSpan = 6;
-    tdName.innerHTML = "No Products Found."
-    tr.appendChild(tdName);
-    // tr.colspan = 6;
-    // tr.innerHTML 
-    tbody.appendChild(tr);
-  }
-
-  table.appendChild(tbody);
-  wrap.appendChild(table);
-}
-
-
-function renderInlineForCards() {
-    const api = FAKE_API_RESPONSE;
-    // Clear all inline sections first
-    document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
-
-    PRODUCT_BASE.forEach((p, idx) => {
-    const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
-    if (!inline) return;
-    if (!selectedIds.has(p.item_id)) return; // only show for selected
-    const res = findApiResultForProduct(p, idx, api);
-    const pid = p.item_id;
-    if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
-    const mem = lastSeen.get(pid);
-
-    // Build sections
-    const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
-    const manChips = el('div', 'chips');
-    const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
-    const addChips = el('div', 'chips');
-
-    const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
-    const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
-
-    const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
-    const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
-    const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
-    counts.appendChild(c1); counts.appendChild(c2);
-
-    inline.appendChild(manTitle); inline.appendChild(manChips);
-    inline.appendChild(addTitle); inline.appendChild(addChips);
-    inline.appendChild(counts);
-    });
-
-    // Update summary
-    $('#statTotal').textContent = api.total_products ?? 0;
-    $('#statOk').textContent = api.successful ?? 0;
-    $('#statKo').textContent = api.failed ?? 0;
-    $('#api-summary').style.display = 'block';
-    
-    
-}
-
-function renderInlineForTable() {
-    const api = FAKE_API_RESPONSE;
-    const table = $('#tableContainer');
-    if (!table) return;
-    // Remove existing detail rows
-    table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
-
-    PRODUCT_BASE.forEach((p, idx) => {
-    if (!selectedIds.has(p.item_id)) return;
-    const res = findApiResultForProduct(p, idx, api);
-    const pid = p.item_id;
-    if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
-    const mem = lastSeen.get(pid);
-
-    const tbody = table.querySelector('tbody');
-    const baseRow = tbody.querySelector(`#row-${p.id}`);
-    if (!baseRow) return;
-
-    const detail = el('tr', 'detail-row');
-    const td = el('td'); td.colSpan = 6; // number of columns
-    const content = el('div', 'detail-content');
-
-    const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
-    const manChips = el('div', 'chips');
-    const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
-    const addChips = el('div', 'chips');
-
-    const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
-    const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
-
-    const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
-    const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
-    const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
-    counts.appendChild(c1); counts.appendChild(c2);
-
-    content.appendChild(manTitle); content.appendChild(manChips);
-    content.appendChild(addTitle); content.appendChild(addChips);
-    content.appendChild(counts);
-    td.appendChild(content); detail.appendChild(td);
-
-    // insert after base row
-    baseRow.insertAdjacentElement('afterend', detail);
-    });
-
-    // Update summary
-    $('#statTotal').textContent = api.total_products ?? 0;
-    $('#statOk').textContent = api.successful ?? 0;
-    $('#statKo').textContent = api.failed ?? 0;
-}
-
-function renderInlineAttributes() {
-    if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
-}
-
-// --- Main rendering ---
-function renderProducts() {
-    if (layoutMode === 'cards') {
-    $('#cardsContainer').style.display = '';
-    $('#tableContainer').style.display = 'none';
-    console.log("PRODUCT_BASE",PRODUCT_BASE);
-    renderProductsCards();
-    } else {
-    $('#cardsContainer').style.display = 'none';
-    $('#tableContainer').style.display = '';
-    renderProductsTable();
-    }
-    updateSelectionInfo();
-    renderPagination();               
-
-    // If there is a selection, re-render inline attributes (persist across toggle)
-    if (selectedIds.size > 0) renderInlineAttributes();
-}
-
-// --- Submit & Reset ---
-function submitAttributes() {
-    if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
-    console.log("selectedIds",selectedIds);
-    jQuery('#full-page-loader').show();  
-    // let inputArray = {
-    //       "product_ids" : [...selectedIds]
-    //     }
-    const extractAdditional = document.getElementById('extract_additional').checked;
-    const processImage = document.getElementById('process_image').checked;
-
-    let inputArray = {
-              "item_ids": [...selectedIds],
-              "mandatory_attrs": {
-                "color": ["color", "shade"],
-                "size": ["size", "fit"],
-                "fabric": ["fabric", "material"]
-              },
-              "model": "llama-3.1-8b-instant",
-              "extract_additional": extractAdditional,
-              "process_image": processImage
-            }
-    let raw = JSON.stringify(inputArray);
-     fetch('/attr/batch-extract/', {
-        method: 'POST', // or 'POST' if your API expects POST
-        headers: {
-            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
-            'Content-Type': "application/json"
-        },
-        body: raw
-    })
-    .then(response => response.json())
-    .then(data => {
-        console.log("response data",data); 
-        FAKE_API_RESPONSE = data;   
-        renderInlineAttributes();
-        jQuery('#full-page-loader').hide();  
-     });
-}
-
-function resetAll() {
-    selectedIds.clear();
-    lastSeen.clear();
-    renderProducts();
-    // Clear summary
-    document.getElementById('statTotal').textContent = '0';
-    document.getElementById('statOk').textContent = '0';
-    document.getElementById('statKo').textContent = '0';
-    $('#api-summary').style.display = 'none';
-}
-
-function setLayout(mode) {
-    layoutMode = mode;
-    const btnCards = document.getElementById('btnCards');
-    const btnTable = document.getElementById('btnTable');
-    if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
-    else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
-    renderProducts();
-}
-
-
-// Upload elements (Bootstrap modal version)
-const uploadModalEl = document.getElementById('uploadModal');
-const dropzone      = document.getElementById('dropzone');
-const uploadFiles   = document.getElementById('uploadFiles');
-const fileInfo      = document.getElementById('fileInfo');
-const uploadBar     = document.getElementById('uploadBar');
-const uploadStatus  = document.getElementById('uploadStatus');
-
-// Reset modal on show
-uploadModalEl.addEventListener('shown.bs.modal', () => {
-  uploadStatus.textContent = '';
-  uploadStatus.className = '';             // clear success/error class
-  uploadBar.style.width = '0%';
-  uploadBar.setAttribute('aria-valuenow', '0');
-  uploadFiles.value = '';
-  uploadFiles.setAttribute('accept', ACCEPT_TYPES);
-  fileInfo.textContent = 'No files selected.';
-});
-
-function describeFiles(list) {
-  if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
-  const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
-  fileInfo.textContent = names.join(', ');
-}
-
-// Drag & drop feedback
-['dragenter','dragover'].forEach(evt => {
-  dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
-});
-['dragleave','drop'].forEach(evt => {
-  dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
-});
-
-// Handle drop
-dropzone.addEventListener('drop', e => {
-  uploadFiles.files = e.dataTransfer.files;
-  describeFiles(uploadFiles.files);
-});
-
-// Click to browse
-// dropzone.addEventListener('click', () => uploadFiles.click());
-
-// Picker change
-uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
-
-function startUpload() {
-  const files = uploadFiles.files;
-  if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
-  jQuery('#full-page-loader').show();
-  uploadStatus.textContent = 'Uploading...';
-  uploadStatus.className = ''; // neutral
-  uploadBar.style.width = '0%';
-  uploadBar.setAttribute('aria-valuenow', '0');
-
-  const form = new FormData();
-  Array.from(files).forEach(f => form.append('file', f));
-  // form.append('uploaded_by', 'Vishal'); // example extra field
-
-  const xhr = new XMLHttpRequest();
-  xhr.open('POST', UPLOAD_API_URL, true);
-  // If you need auth:
-  // xhr.setRequestHeader('Authorization', 'Bearer <token>');
-
-  xhr.upload.onprogress = (e) => {
-    if (e.lengthComputable) {
-      const pct = Math.round((e.loaded / e.total) * 100);
-      uploadBar.style.width = pct + '%';
-      uploadBar.setAttribute('aria-valuenow', String(pct));
-    }
-  };
-
-  xhr.onreadystatechange = () => {
-    if (xhr.readyState === 4) {
-      const ok = (xhr.status >= 200 && xhr.status < 300);
-      try {
-        const resp = JSON.parse(xhr.responseText || '{}');
-        uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
-      } catch {
-        uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
-      }
-      uploadStatus.className = ok ? 'success' : 'error';
-      // Optional: auto-close the modal on success after 1.2s:
-      // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
-    }
-  };
-
-  xhr.onerror = () => {
-    uploadStatus.textContent = 'Network error during upload.';
-    uploadStatus.className = 'error';
-  };
-
-  xhr.send(form);
-  setTimeout(()=>{
-      jQuery('#uploadModal').modal('hide');
-  },3000)
-  jQuery('#full-page-loader').hide();
-
-}
-
-// Wire Start button
-document.getElementById('uploadStart').addEventListener('click', startUpload);
-// Cancel button already closes the modal via data-bs-dismiss
-
-
-
-
-// --- Pagination state ---
-let page = 1;
-let pageSize = 5; // default rows per page
-
-function totalPages() {
-  return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
-}
-
-function clampPage() {
-  page = Math.min(Math.max(1, page), totalPages());
-}
-
-function getCurrentSlice() {
-  clampPage();
-  const start = (page - 1) * pageSize;
-  return PRODUCT_BASE.slice(start, start + pageSize);
-}
-
-function renderPagination() {
-  const bar = document.getElementById('paginationBar');
-  if (!bar) return;
-
-  const tp = totalPages();
-  clampPage();
-
-  bar.innerHTML = `
-    <div class="page-size">
-      <label for="pageSizeSelect">Rows per page</label>
-      <select id="pageSizeSelect">
-        <option value="5"  ${pageSize===5  ? 'selected' : ''}>5</option>
-        <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
-        <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
-        <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
-        <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
-      </select>
-    </div>
-
-    <div class="pager">
-      <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
-      <span class="page-info">Page ${page} of ${tp}</span>
-      <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
-    </div>
-  `;
-
-  // wire events
-  document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
-  document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
-
-  const sel = document.getElementById('pageSizeSelect');
-  if (sel) {
-    sel.addEventListener('change', () => {
-      const val = sel.value;
-      pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
-      page = 1;            // reset to first page when size changes
-      renderProducts();
-    });
-  }
-}
-
-

+ 991 - 72
content_quality_tool_public/static/js/attr-extraction.js

@@ -81,7 +81,7 @@ document.addEventListener('DOMContentLoaded', () => {
     });
 });
 
-var FAKE_API_RESPONSE = {
+var API_RESPONSE_AI = {
     // results: [
     // { product_id: 'SKU001', mandatory: { 'Clothing Neck Style': 'V-Neck', 'Clothing Top Style': 'Pullover', 'Condition': 'New', 'T-Shirt Type': 'Classic T-Shirt' }, additional: { 'Material': 'Turkish Pima Cotton', 'Size': 'Large', 'Color': 'Blue', 'Brand': 'Sierra', 'Fabric Type': 'Soft & Breathable', 'Fabric Composition': '95% Turkish Pima cotton', 'Care Instructions': 'Machine Washable', 'Sizes Available': 'S-XL' } },
     // { product_id: 'SKU002', mandatory: { 'Shoe Type': 'Running', 'Closure': 'Lace-Up', 'Condition': 'New', 'Gender': 'Men' }, additional: { 'Upper Material': 'Engineered Mesh', 'Midsole': 'EVA Foam', 'Outsole': 'Rubber', 'Color': 'Black/White', 'Brand': 'Adidas', 'Size': 'UK 9', 'Care Instructions': 'Surface Clean' } },
@@ -678,51 +678,194 @@ function renderProductsTable(items = getCurrentSlice()) {
     wrap.appendChild(table);
 }
 
+// function renderInlineForCards() {
+//     const api = API_RESPONSE_AI;
+//     // Clear all inline sections first
+//     document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
+
+//     PRODUCT_BASE.forEach((p, idx) => {
+//         const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
+//         if (!inline) return;
+        
+//         // --- CHANGE HERE: Use the new helper function ---
+//         if (!isProductSelected(p.item_id)) return; // only show for selected
+        
+//         const res = findApiResultForProduct(p, idx, api);
+//         const pid = p.item_id;
+//         if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
+//         const mem = lastSeen.get(pid);
+
+//         // Build sections
+//         const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
+//         const manChips = el('div', 'chips');
+//         const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
+//         const addChips = el('div', 'chips');
+
+//         const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
+//         const ocrChips = el('div', 'chips');
+//         const addVisual = el('div', 'section-title'); addVisual.innerHTML = '<strong>Visual</strong>';
+//         const visualChips = el('div', 'chips');
+        
+
+//         const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
+//         const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
+//         const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem?.ocr_results);
+//         const visualCount = renderChips(visualChips, res?.visual_results?.visual_attributes || {}, mem?.visual_results);
+
+//         const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
+//         const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
+//         const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
+//         const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
+//         const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
+//         counts.appendChild(c1); counts.appendChild(c2);  counts.appendChild(c3);  counts.appendChild(c4);
+
+//         inline.appendChild(manTitle); inline.appendChild(manChips);
+//         inline.appendChild(addTitle); inline.appendChild(addChips);
+//         inline.appendChild(addOcr); inline.appendChild(ocrChips);
+//         inline.appendChild(addVisual); inline.appendChild(visualChips);
+//         inline.appendChild(counts);
+//     });
+
+//     // Update summary
+//     $('#statTotal').textContent = api.total_products ?? 0;
+//     $('#statOk').textContent = api.successful ?? 0;
+//     $('#statKo').textContent = api.failed ?? 0;
+//     $('#api-summary').style.display = 'block';
+// }
+
+// -----------------------------------------------------------
+
+// function renderInlineForTable() {
+//     const api = API_RESPONSE_AI;
+//     const table = $('#tableContainer');
+//     if (!table) return;
+//     // Remove existing detail rows
+//     table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
+
+//     PRODUCT_BASE.forEach((p, idx) => {
+//         // --- CHANGE HERE: Use the new helper function ---
+//         if (!isProductSelected(p.item_id)) return;
+        
+//         const res = findApiResultForProduct(p, idx, api);
+//         const pid = p.item_id;
+//         if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
+//         const mem = lastSeen.get(pid);
+
+//         const tbody = table.querySelector('tbody');
+//         // NOTE: The table rendering uses p.id for the row ID: `row-${p.id}`.
+//         // Assuming p.id is still valid for finding the base row, as your original code used it.
+//         const baseRow = tbody.querySelector(`#row-${p.id}`); 
+//         if (!baseRow) return;
+
+//         const detail = el('tr', 'detail-row');
+//         const td = el('td'); td.colSpan = 6; // number of columns
+//         const content = el('div', 'detail-content');
+
+//         const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
+//         const manChips = el('div', 'chips');
+//         const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
+//         const addChips = el('div', 'chips');
+//         const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
+//         const ocrChips = el('div', 'chips');
+//         const addVisuals = el('div', 'section-title'); addVisuals.innerHTML = '<strong>Visuals</strong>';
+//         const visualsChips = el('div', 'chips');
+
+//         const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
+//         const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
+//         const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem.ocr_results);
+//         const visualCount = renderChips(visualsChips, res?.visual_results?.visual_attributes || {}, mem.visual_results);
+
+//         const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
+//         const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
+//         const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
+//         const c3 = el('span', 'pill'); c3.textContent = `Ocr: ${ocrCount}`;
+//         const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
+//         counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
+
+//         content.appendChild(manTitle); content.appendChild(manChips);
+//         content.appendChild(addTitle); content.appendChild(addChips);
+//         content.appendChild(addOcr); content.appendChild(ocrChips);
+//         content.appendChild(addVisuals); content.appendChild(visualsChips);
+//         content.appendChild(counts);
+//         td.appendChild(content); detail.appendChild(td);
+
+//         // insert after base row
+//         baseRow.insertAdjacentElement('afterend', detail);
+//     });
+
+//     // Update summary
+//     $('#statTotal').textContent = api.total_products ?? 0;
+//     $('#statOk').textContent = api.successful ?? 0;
+//     $('#statKo').textContent = api.failed ?? 0;
+//     $('#api-summary').style.display = 'block';
+// }
+
 function renderInlineForCards() {
-    const api = FAKE_API_RESPONSE;
-    // Clear all inline sections first
+    const api = API_RESPONSE_AI;
     document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
 
     PRODUCT_BASE.forEach((p, idx) => {
         const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
         if (!inline) return;
         
-        // --- CHANGE HERE: Use the new helper function ---
-        if (!isProductSelected(p.item_id)) return; // only show for selected
+        if (!isProductSelected(p.item_id)) return;
         
         const res = findApiResultForProduct(p, idx, api);
-        const pid = p.item_id;
-        if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
-        const mem = lastSeen.get(pid);
-
-        // Build sections
-        const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
-        const manChips = el('div', 'chips');
-        const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
-        const addChips = el('div', 'chips');
-
-        const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
-        const ocrChips = el('div', 'chips');
-        const addVisual = el('div', 'section-title'); addVisual.innerHTML = '<strong>Visual</strong>';
-        const visualChips = el('div', 'chips');
+        
+        // Clear existing content
+        inline.innerHTML = '';
+
+
+        // 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS
+        const mandatorySection = renderMandatoryComparisonCards(
+            res?.mandatory || {}, 
+            'Mandatory Attributes Comparison'
+        );
+        inline.appendChild(mandatorySection);
+        const mandCount = Object.keys(res?.mandatory || {}).length;
         
 
-        const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
-        const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
-        const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem?.ocr_results);
-        const visualCount = renderChips(visualChips, res?.visual_results?.visual_attributes || {}, mem?.visual_results);
+        const combinedTitle = el('div', 'section-title');
+        combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
+        inline.appendChild(combinedTitle);
 
+        const combinedAttributesContainer = el('div', 'combined-attributes-container');
+
+        // 2. ADDITIONAL SECTION: RENDER AS SIMPLE TABLE
+        const additionalSection = renderAttributesAsTable(
+            res?.additional || {}, 
+            'Additional Attributes'
+        );
+        // inline.appendChild(additionalSection);
+        const addCount = Object.keys(res?.additional || {}).length;
+        
+        // 3. OCR SECTION: RENDER AS SIMPLE TABLE
+        const ocrSection = renderAttributesAsTable(
+            res?.ocr_results?.extracted_attributes || {}, 
+            'OCR Results'
+        );
+        // inline.appendChild(ocrSection);
+        const ocrCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
+        
+        // 4. VISUAL SECTION: RENDER AS SIMPLE TABLE
+        const visualSection = renderAttributesAsTable(
+            res?.visual_results?.visual_attributes || {}, 
+            'Visual Attributes'
+        );
+        // inline.appendChild(visualSection);
+        const visualCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
+        combinedAttributesContainer.appendChild(additionalSection);
+        combinedAttributesContainer.appendChild(ocrSection);
+        combinedAttributesContainer.appendChild(visualSection);
+        inline.appendChild(combinedAttributesContainer);
+        // --- Summary Counts (Pills) ---
         const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
         const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
         const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
         const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
         const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
-        counts.appendChild(c1); counts.appendChild(c2);  counts.appendChild(c3);  counts.appendChild(c4);
+        counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
 
-        inline.appendChild(manTitle); inline.appendChild(manChips);
-        inline.appendChild(addTitle); inline.appendChild(addChips);
-        inline.appendChild(addOcr); inline.appendChild(ocrChips);
-        inline.appendChild(addVisual); inline.appendChild(visualChips);
         inline.appendChild(counts);
     });
 
@@ -733,76 +876,559 @@ function renderInlineForCards() {
     $('#api-summary').style.display = 'block';
 }
 
-// -----------------------------------------------------------
+// function renderInlineForCards() {
+//     const api = API_RESPONSE_AI;
+//     // Clear all inline sections first
+//     document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
+
+//     PRODUCT_BASE.forEach((p, idx) => {
+//         const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
+//         if (!inline) return;
+        
+//         if (!isProductSelected(p.item_id)) return;
+        
+//         const res = findApiResultForProduct(p, idx, api);
+//         const pid = p.item_id;
+//         // Memory map (mem) is no longer needed since we removed chip rendering
+//         // I'll keep the variable declarations for count consistency, but remove the memory map usage.
+
+//         // --- 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS ---
+//         const mandatorySection = renderMandatoryComparisonCards(
+//             res?.mandatory || {}, 
+//             'Mandatory Attributes Comparison'
+//         );
+//         inline.appendChild(mandatorySection);
+        
+//         const mandCount = Object.keys(res?.mandatory || {}).length;
+        
+//         // --- 2. ADDITIONAL SECTION: RENDER AS SIMPLE CARDS ---
+//         const additionalSection = renderAttributesAsTable(
+//             res?.additional || {}, 
+//             'Additional Attributes'
+//         );
+//         inline.appendChild(additionalSection);
+//         const addCount = Object.keys(res?.additional || {}).length;
+        
+//         // --- 3. OCR SECTION: RENDER AS SIMPLE CARDS ---
+//         const ocrSection = renderAttributesAsTable(
+//             res?.ocr_results?.extracted_attributes || {}, 
+//             'OCR Results'
+//         );
+//         inline.appendChild(ocrSection);
+//         const ocrCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
+        
+//         // --- 4. VISUAL SECTION: RENDER AS SIMPLE CARDS ---
+//         const visualSection = renderAttributesAsTable(
+//             res?.visual_results?.visual_attributes || {}, 
+//             'Visual Results'
+//         );
+//         inline.appendChild(visualSection);
+//         const visualCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
+        
+//         // --- Summary Counts (Pills) ---
+//         const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
+//         const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
+//         const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
+//         const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
+//         const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
+//         counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
+
+//         inline.appendChild(counts);
+//     });
+
+//     // Update summary
+//     $('#statTotal').textContent = api.total_products ?? 0;
+//     $('#statOk').textContent = api.successful ?? 0;
+//     $('#statKo').textContent = api.failed ?? 0;
+//     $('#api-summary').style.display = 'block';
+// }
+
+// ----------------------------------------------------------------
+// NOTE: You MUST include renderMandatoryComparisonCards (from previous response)
+// and the necessary CSS for both card styles!
+// ----------------------------------------------------------------
+
+// ------------------------------------------------------------------
+// --- 1. MANDATORY COMPARISON HELPER (Existing vs. AI, with Highlighting) ---
+// ------------------------------------------------------------------
+
+// function renderInlineForCards() {
+//     const api = API_RESPONSE_AI;
+//     // Clear all inline sections first
+//     document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
+
+//     PRODUCT_BASE.forEach((p, idx) => {
+//         const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
+//         if (!inline) return;
+        
+//         // --- CHANGE HERE: Use the new helper function ---
+//         if (!isProductSelected(p.item_id)) return; // only show for selected
+        
+//         const res = findApiResultForProduct(p, idx, api);
+//         const pid = p.item_id;
+//         // Keep memory logic for old chip renderer, even though card renderer doesn't need it
+//         if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
+//         const mem = lastSeen.get(pid);
+
+//         // ------------------------------------------------
+//         // 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS
+//         // ------------------------------------------------
+//         const mandatorySection = renderMandatoryComparisonCards(
+//             res?.mandatory || {}, 
+//             'Mandatory Attributes Comparison'
+//         );
+//         inline.appendChild(mandatorySection);
+        
+//         // Count the attributes for the summary pill
+//         const mandCount = Object.keys(res?.mandatory || {}).length;
+        
+//         // ------------------------------------------------
+//         // 2. ADDITIONAL/OCR/VISUALS: RENDER AS CHIPS (Original Logic)
+//         // ------------------------------------------------
+        
+//         // ADDITIONAL
+//         const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
+//         const addChips = el('div', 'chips');
+//         const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
+//         inline.appendChild(addTitle); inline.appendChild(addChips);
+        
+//         // OCR
+//         const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
+//         const ocrChips = el('div', 'chips');
+//         const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem?.ocr_results);
+//         inline.appendChild(addOcr); inline.appendChild(ocrChips);
+        
+//         // VISUALS
+//         const addVisual = el('div', 'section-title'); addVisual.innerHTML = '<strong>Visual</strong>';
+//         const visualChips = el('div', 'chips');
+//         const visualCount = renderChips(visualChips, res?.visual_results?.visual_attributes || {}, mem?.visual_results);
+//         inline.appendChild(addVisual); inline.appendChild(visualChips);
+        
+//         // --- Summary Counts (Pills) ---
+//         const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
+//         const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
+//         const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
+//         const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
+//         const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
+//         counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
+
+//         inline.appendChild(counts);
+//     });
+
+//     // Update summary
+//     $('#statTotal').textContent = api.total_products ?? 0;
+//     $('#statOk').textContent = api.successful ?? 0;
+//     $('#statKo').textContent = api.failed ?? 0;
+//     $('#api-summary').style.display = 'block';
+// }
+
+/**
+ * Renders a table for Mandatory attributes, comparing AI-extracted value ('value') 
+ * against the existing value ('original_value'). Includes a scroll wrapper.
+ * @param {Object} attributes - The mandatory attribute data.
+ * @param {string} title - The title for the table section.
+ * @returns {HTMLElement} A div containing the comparison table.
+ */
+// function renderMandatoryComparisonTable(attributes, title) {
+//     const section = el('div', 'attribute-section');
+    
+//     let attributeEntries = [];
+
+//     Object.keys(attributes).forEach(key => {
+//         const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]]; 
+//         valuesArray.forEach(v => {
+//             const aiValue = v.value || 'N/A';
+//             const originalValue = v.original_value || 'N/A';
+//             const source = v.source || 'N/A';
+            
+//             // Comparison is case-insensitive and ignores leading/trailing whitespace
+//             const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
+
+//             attributeEntries.push({
+//                 name: key,
+//                 aiValue: aiValue,
+//                 originalValue: originalValue,
+//                 source: source,
+//                 isMatch: isMatch
+//             });
+//         });
+//     });
+
+//     const titleEl = el('div', 'section-title');
+//     titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
+//     section.appendChild(titleEl);
+    
+//     if (attributeEntries.length === 0) {
+//         const msg = el('p', 'no-attributes-message');
+//         msg.textContent = `No ${title.toLowerCase()} found.`;
+//         section.appendChild(msg);
+//         return section;
+//     }
+
+//     // --- SCROLL WRAPPER ADDITION ---
+//     const scrollWrapper = el('div', 'attribute-scroll-wrapper');
+//     const table = el('table', 'attribute-detail-table comparison-table');
+    
+//     const thead = el('thead');
+//     const headerRow = el('tr');
+    
+//     ['Attribute Name', 'Source', 'Manually Identified Value', 'AI Generated Value'].forEach(text => {
+//         const th = el('th');
+//         th.textContent = text;
+//         headerRow.appendChild(th);
+//     });
+//     thead.appendChild(headerRow);
+//     table.appendChild(thead);
+
+//     const tbody = el('tbody');
+
+//     attributeEntries.forEach(attr => {
+//         // Highlight the entire row in red if the values do not match
+//         const row = el('tr', attr.isMatch ? 'match' : 'mismatch-row'); 
+        
+//         // 1. Attribute Name
+//         const nameTd = el('td', 'attribute-name');
+//         nameTd.textContent = attr.name.replace(/_/g, ' '); 
+//         row.appendChild(nameTd);
+
+//         // 2. Source
+//         const sourceTd = el('td', 'attribute-source');
+//         sourceTd.textContent = formatString(attr.source);
+//         row.appendChild(sourceTd);
+
+
+//         // 3. Existing Value
+//         const originalTd = el('td', 'original-value');
+//         originalTd.textContent = formatString(attr.originalValue);
+//         row.appendChild(originalTd);
+
+//         // 4. AI Extracted Value (Highlight if mismatch)
+//         const aiTd = el('td', `ai-value ${attr.aiValue ? '' : 'mismatch-value'}`);
+//         aiTd.textContent = attr.aiValue;
+//         row.appendChild(aiTd);
+        
+
+//         // 5. Match Status
+//         // const matchTd = el('td', 'match-status');
+//         // const matchPill = el('span', `pill status-pill status-${attr.isMatch ? 'match' : 'mismatch'}`);
+//         // matchPill.textContent = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
+//         // matchTd.appendChild(matchPill);
+//         // row.appendChild(matchTd);
+
+//         tbody.appendChild(row);
+//     });
+
+//     table.appendChild(tbody);
+//     scrollWrapper.appendChild(table); // Append table to wrapper
+//     section.appendChild(scrollWrapper); // Append wrapper to section
+//     return section;
+// }
+
+// ------------------------------------------------------------------
+// --- 2. GENERAL ATTRIBUTE HELPER (Name, Value, Source, with Scroll) ---
+// ------------------------------------------------------------------
+/**
+ * Renders a table for Mandatory attributes, comparing AI-extracted value ('value') 
+ * against the existing value ('original_value'). Includes a scroll wrapper and mismatch highlighting.
+ * @param {Object} attributes - The mandatory attribute data.
+ * @param {string} title - The title for the table section.
+ * @returns {HTMLElement} A div containing the comparison table.
+ */
+function renderMandatoryComparisonTable(attributes, title) {
+    const section = el('div', 'attribute-section');
+    
+    let attributeEntries = [];
+
+    Object.keys(attributes).forEach(key => {
+        const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]]; 
+        valuesArray.forEach(v => {
+            const aiValue = v.value || 'N/A';
+            const originalValue = v.original_value || 'N/A';
+            const source = v.source || 'N/A';
+            
+            // Comparison is case-insensitive and ignores leading/trailing whitespace
+            const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
+
+            attributeEntries.push({
+                name: key,
+                aiValue: aiValue,
+                originalValue: originalValue,
+                source: source,
+                isMatch: isMatch
+            });
+        });
+    });
+
+    const titleEl = el('div', 'section-title');
+    titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
+    section.appendChild(titleEl);
+    
+    if (attributeEntries.length === 0) {
+        const msg = el('p', 'no-attributes-message');
+        msg.textContent = `No ${title.toLowerCase()} found.`;
+        section.appendChild(msg);
+        return section;
+    }
+
+    // --- SCROLL WRAPPER ADDITION ---
+    const scrollWrapper = el('div', 'attribute-scroll-wrapper');
+    const table = el('table', 'attribute-detail-table comparison-table');
+    
+    const thead = el('thead');
+    const headerRow = el('tr');
+    
+    // Updated Headers for Comparison Table
+    ['Attribute Name', 'Manually Identified Value', 'AI Generated Value', 'Source', 'Match'].forEach(text => {
+        const th = el('th');
+        th.textContent = text;
+        headerRow.appendChild(th);
+    });
+    thead.appendChild(headerRow);
+    table.appendChild(thead);
+
+    const tbody = el('tbody');
+
+    attributeEntries.forEach(attr => {
+        // Highlight the entire row in red if the values do not match
+        const row = el('tr', attr.isMatch ? 'match-row' : 'mismatch-row'); 
+        
+        // 1. Attribute Name
+        const nameTd = el('td', 'attribute-name');
+        nameTd.textContent = formatString(attr.name).replace(/_/g, ' '); 
+        row.appendChild(nameTd);
+
+        // 2. Existing Value (Manually added value)
+        const originalTd = el('td', 'original-value');
+        originalTd.textContent = formatString(attr.originalValue);
+        row.appendChild(originalTd);
+
+        // 3. AI Extracted Value
+        const aiTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
+        aiTd.textContent = attr.aiValue;
+        row.appendChild(aiTd);
+        
+        // 4. Source
+        const sourceTd = el('td', 'attribute-source');
+        sourceTd.textContent = formatString(attr.source);
+        row.appendChild(sourceTd);
+
+        // 5. Match Status
+        const matchTd = el('td', 'match-status');
+        const matchPill = el('span', `pill status-pill status-${attr.isMatch ? 'match' : 'mismatch'}`);
+        matchPill.textContent = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
+        matchTd.appendChild(matchPill);
+        row.appendChild(matchTd);
+
+        tbody.appendChild(row);
+    });
+
+    table.appendChild(tbody);
+    scrollWrapper.appendChild(table); // Append table to wrapper
+    section.appendChild(scrollWrapper); // Append wrapper to section
+    return section;
+}
+
+/**
+ * Renders a table for Additional, OCR, or Visual attributes (Name, Value, Source).
+ * @param {Object} attributes - The attribute data.
+ * @param {string} title - The title for the table section.
+ * @returns {HTMLElement} A div containing the table.
+ */
+function renderAttributesAsTable(attributes, title) {
+    const section = el('div', 'attribute-section');
+    let attributeEntries = [];
+
+    const processAttribute = (key, values) => {
+        const valuesArray = Array.isArray(values) ? values : [values]; 
+        valuesArray.forEach(v => {
+            attributeEntries.push({
+                name: key,
+                value: v.value,
+                source: v.source || 'N/A'
+            });
+        });
+    };
+
+    Object.keys(attributes).forEach(key => {
+        const attribute = attributes[key];
+        
+        if (Array.isArray(attribute)) {
+            processAttribute(key, attribute);
+        } else if (typeof attribute === 'object' && attribute !== null) {
+            Object.keys(attribute).forEach(subKey => {
+                const subAttribute = attribute[subKey];
+                if (Array.isArray(subAttribute)) {
+                    // Combines parent key (e.g., 'size') and sub-key (e.g., 'waist_size')
+                    processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
+                }
+            });
+        }
+    });
+
+    const titleEl = el('div', 'section-title');
+    titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
+    section.appendChild(titleEl);
+    
+    if (attributeEntries.length === 0) {
+        const msg = el('p', 'no-attributes-message');
+        msg.textContent = `No ${title.toLowerCase()} found.`;
+        section.appendChild(msg);
+        return section;
+    }
+
+    // --- SCROLL WRAPPER ADDITION ---
+    const scrollWrapper = el('div', 'attribute-scroll-wrapper');
+    const table = el('table', 'attribute-detail-table');
+
+    const thead = el('thead');
+    const headerRow = el('tr');
+    
+    ['Attribute Name', 'Value'].forEach(text => {
+        const th = el('th');
+        th.textContent = text;
+        headerRow.appendChild(th);
+    });
+    thead.appendChild(headerRow);
+    table.appendChild(thead);
+
+    const tbody = el('tbody');
+
+    attributeEntries.forEach(attr => {
+        const row = el('tr'); 
+        
+        const nameTd = el('td', 'attribute-name');
+        nameTd.textContent = formatString(attr.name).replace(/_/g, ' '); 
+        row.appendChild(nameTd);
+
+        const valueTd = el('td', 'attribute-value');
+        const displayValue = Array.isArray(attr.value) 
+            ? (attr.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr.source)+ ')' 
+            : formatString(attr.value) +'('+ formatString(attr.source)+ ')';
+        valueTd.textContent = displayValue || 'N/A';
+        row.appendChild(valueTd);
+
+        // const sourceTd = el('td', 'attribute-source');
+        // sourceTd.textContent = attr.source || 'Unknown';
+        // row.appendChild(sourceTd);
+
+        tbody.appendChild(row);
+    });
+
+    table.appendChild(tbody);
+    scrollWrapper.appendChild(table); // Append table to wrapper
+    section.appendChild(scrollWrapper); // Append wrapper to section
+    return section;
+}
+
+// ------------------------------------------------------------------
+// --- 3. MAIN RENDER FUNCTION (REPLACEMENT) ---
+// ------------------------------------------------------------------
 
 function renderInlineForTable() {
-    const api = FAKE_API_RESPONSE;
+    const api = API_RESPONSE_AI;
     const table = $('#tableContainer');
     if (!table) return;
+
     // Remove existing detail rows
     table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
 
     PRODUCT_BASE.forEach((p, idx) => {
-        // --- CHANGE HERE: Use the new helper function ---
         if (!isProductSelected(p.item_id)) return;
         
         const res = findApiResultForProduct(p, idx, api);
-        const pid = p.item_id;
-        if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
-        const mem = lastSeen.get(pid);
-
+        
         const tbody = table.querySelector('tbody');
-        // NOTE: The table rendering uses p.id for the row ID: `row-${p.id}`.
-        // Assuming p.id is still valid for finding the base row, as your original code used it.
-        const baseRow = tbody.querySelector(`#row-${p.id}`); 
+        const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null; 
         if (!baseRow) return;
 
+        // --- Detail Row Construction ---
         const detail = el('tr', 'detail-row');
-        const td = el('td'); td.colSpan = 6; // number of columns
-        const content = el('div', 'detail-content');
-
-        const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
-        const manChips = el('div', 'chips');
-        const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
-        const addChips = el('div', 'chips');
-        const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
-        const ocrChips = el('div', 'chips');
-        const addVisuals = el('div', 'section-title'); addVisuals.innerHTML = '<strong>Visuals</strong>';
-        const visualsChips = el('div', 'chips');
-
-        const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
-        const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
-        const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem.ocr_results);
-        const visualCount = renderChips(visualsChips, res?.visual_results?.visual_attributes || {}, mem.visual_results);
-
-        const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
-        const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
-        const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
-        const c3 = el('span', 'pill'); c3.textContent = `Ocr: ${ocrCount}`;
-        const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
+        // td.colSpan must match the number of columns in your main table
+        const td = el('td'); td.colSpan = 7; 
+        const content = el('div', 'detail-content-tables');
+
+
+        // // 1. MANDATORY Attributes Table (NOW USES CARD COMPARISON)
+        // const mandatorySection = renderMandatoryComparisonCards( // <-- NEW FUNCTION NAME
+        //     res?.mandatory || {}, 
+        //     'Mandatory Attributes Comparison'
+        // );
+        // content.appendChild(mandatorySection);
+
+        // // 2. COMBINED Attributes Section (Additional, OCR, Visuals) - REMAINS THE SAME
+        // content.appendChild(el('hr', 'section-separator'));
+
+        // 1. MANDATORY Attributes Table (USES COMPARISON FUNCTION)
+        const mandatoryTable = renderMandatoryComparisonTable(
+            res?.mandatory || {}, 
+            'Mandatory Attributes Comparison'
+        );
+        content.appendChild(mandatoryTable);
+
+        // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
+        content.appendChild(el('hr', 'section-separator')); 
+        
+        const combinedTitle = el('div', 'section-title');
+        combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
+        content.appendChild(combinedTitle);
+        
+        const combinedAttributesContainer = el('div', 'combined-attributes-container');
+        
+        // Use the general renderer for these sections
+        const additionalTable = renderAttributesAsTable(
+            res?.additional || {}, 
+            'Additional Attributes'
+        );
+        
+        const ocrTable = renderAttributesAsTable(
+            res?.ocr_results?.extracted_attributes || {}, 
+            'OCR Results'
+        );
+        
+        const visualsTable = renderAttributesAsTable(
+            res?.visual_results?.visual_attributes || {}, 
+            'Visual Results'
+        );
+
+        // Append all sections to the combined container
+        combinedAttributesContainer.appendChild(additionalTable);
+        combinedAttributesContainer.appendChild(ocrTable);
+        combinedAttributesContainer.appendChild(visualsTable);
+        content.appendChild(combinedAttributesContainer);
+        
+        // --- Summary Counts ---
+        const mandCount = Object.keys(res?.mandatory || {}).length;
+        const addCount = Object.keys(res?.additional || {}).length;
+        const ocrExtractedCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
+        const visualExtractedCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
+        
+        const counts = el('div', 'attribute-summary-pills');
+        const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
+        const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
+        const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
+        const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
         counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
-
-        content.appendChild(manTitle); content.appendChild(manChips);
-        content.appendChild(addTitle); content.appendChild(addChips);
-        content.appendChild(addOcr); content.appendChild(ocrChips);
-        content.appendChild(addVisuals); content.appendChild(visualsChips);
         content.appendChild(counts);
-        td.appendChild(content); detail.appendChild(td);
-
-        // insert after base row
+        
+        // Final assembly and insertion
+        td.appendChild(content); 
+        detail.appendChild(td);
         baseRow.insertAdjacentElement('afterend', detail);
     });
 
-    // Update summary
+    // Update summary statistics
     $('#statTotal').textContent = api.total_products ?? 0;
     $('#statOk').textContent = api.successful ?? 0;
     $('#statKo').textContent = api.failed ?? 0;
-    $('#api-summary').style.display = 'block';
+    const apiSummary = $('#api-summary');
+    if (apiSummary) apiSummary.style.display = 'block';
 }
 
 
 function renderInlineAttributes() {
     if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
+    // renderInlineForCards(); 
+    // renderInlineForTable();
 }
 
 // --- Main rendering ---
@@ -821,7 +1447,7 @@ function renderProducts() {
     renderPagination();               
 
     // If there is a selection, re-render inline attributes (persist across toggle)
-    if (selectedIds.size > 0) renderInlineAttributes();
+    if (selectedProductsWithAttributes.length > 0) renderInlineAttributes();
 }
 
 // --- Submit & Reset ---
@@ -894,7 +1520,7 @@ function submitAttributes() {
     .then(response => response.json())
     .then(data => {
         // console.log("response data",data); 
-        FAKE_API_RESPONSE = data;   
+        API_RESPONSE_AI = data;   
         renderInlineAttributes();
         jQuery('#full-page-loader').hide();  
      });
@@ -1212,3 +1838,296 @@ function getThreshold() {
     // console.log("parseFloat(thresholdInput.value)",parseFloat(thresholdInput.value));
     return parseFloat(thresholdInput.value);
 }
+
+
+/**
+ * Renders Mandatory attributes using a card-based comparison layout.
+ * Highlights mismatches prominently.
+ * @param {Object} attributes - The mandatory attribute data.
+ * @param {string} title - The title for the section.
+ * @returns {HTMLElement} A div containing the comparison cards.
+ */
+function renderMandatoryComparisonCards(attributes, title) {
+    const section = el('div', 'attribute-section');
+    
+    // --- 1. Flatten Mandatory Attributes ---
+    let attributeEntries = [];
+
+    Object.keys(attributes).forEach(key => {
+        const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]]; 
+        valuesArray.forEach(v => {
+            const aiValue = v.value || 'N/A';
+            const originalValue = v.original_value || 'N/A';
+            
+            // Comparison is case-insensitive and ignores leading/trailing whitespace
+            const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
+
+            attributeEntries.push({
+                name: key,
+                aiValue: aiValue,
+                originalValue: originalValue,
+                isMatch: isMatch,
+                source: v.source || 'N/A'
+            });
+        });
+    });
+
+    // --- 2. Section Header ---
+    const titleEl = el('div', 'section-title');
+    titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
+    section.appendChild(titleEl);
+    
+    if (attributeEntries.length === 0) {
+        const msg = el('p', 'no-attributes-message');
+        msg.textContent = `No ${title.toLowerCase()} found.`;
+        section.appendChild(msg);
+        return section;
+    }
+
+    // --- 3. Card Container ---
+    const cardsContainer = el('div', 'comparison-cards-container');
+
+    attributeEntries.forEach(attr => {
+        // Main Card Element
+        const card = el('div', `comparison-card ${attr.isMatch ? 'match' : 'mismatch-card'}`);
+
+        // Card Header (Attribute Name)
+        const header = el('div', 'card-header');
+        header.textContent = attr.name.replace(/_/g, ' ');
+        card.appendChild(header);
+
+        // Content Wrapper
+        const content = el('div', 'card-content');
+
+        // Existing Value Box
+        const originalBox = el('div', 'value-box original-box');
+        originalBox.innerHTML = `
+            <div class="value-label">Manually Identified Value</div>
+            <div class="value-text">${attr.originalValue}</div>
+        `;
+        content.appendChild(originalBox);
+
+        // AI Value Box
+        const aiBox = el('div', `value-box ai-box ${attr.isMatch ? '' : 'mismatch-value'}`);
+        aiBox.innerHTML = `
+            <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
+            <div class="value-text">${attr.aiValue}</div>
+        `;
+        content.appendChild(aiBox);
+
+        card.appendChild(content);
+
+        // Mismatch Indicator (only visible on mismatch-card via CSS)
+        if (!attr.isMatch) {
+            const indicator = el('div', 'mismatch-indicator');
+            // indicator.innerHTML = '❌ MISMATCH';
+            indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
+            card.appendChild(indicator);
+        }
+
+        cardsContainer.appendChild(card);
+    });
+
+    section.appendChild(cardsContainer);
+    return section;
+}
+
+// Example JavaScript (Assuming you have access to API_RESPONSE_AI)
+// document.getElementById('downloadResultBtn').addEventListener('click', () => {
+//     // 1. Convert the data to a JSON string
+//     const jsonString = JSON.stringify(API_RESPONSE_AI, null, 2); 
+    
+//     // 2. Create a Blob from the JSON string
+//     const blob = new Blob([jsonString], { type: 'application/json' });
+    
+//     // 3. Create a temporary URL and link element
+//     const url = URL.createObjectURL(blob);
+//     const a = document.createElement('a');
+    
+//     // 4. Set download attributes
+//     a.href = url;
+//     a.download = 'api_generated_results.json';
+    
+//     // 5. Simulate a click to trigger download
+//     document.body.appendChild(a);
+//     a.click();
+    
+//     // 6. Clean up
+//     document.body.removeChild(a);
+//     URL.revokeObjectURL(url);
+// });
+
+
+/**
+ * Renders Mandatory attributes using a card-based comparison layout.
+ * Highlights mismatches prominently.
+ * @param {Object} attributes - The mandatory attribute data.
+ * @param {string} title - The title for the section (used for the header).
+ * @returns {HTMLElement} A div containing the comparison cards.
+ */
+function renderMandatoryComparisonCards(attributes, title) {
+    const section = el('div', 'attribute-section mandatory-comparison-section');
+    
+    // --- 1. Flatten Mandatory Attributes ---
+    let attributeEntries = [];
+
+    Object.keys(attributes).forEach(key => {
+        const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]]; 
+        valuesArray.forEach(v => {
+            const aiValue = v.value || 'N/A';
+            const originalValue = v.original_value || 'N/A';
+            
+            const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
+
+            attributeEntries.push({
+                name: key,
+                aiValue: aiValue,
+                originalValue: originalValue,
+                isMatch: isMatch,
+                source: v.source || 'N/A'
+            });
+        });
+    });
+
+    // --- 2. Section Header ---
+    const titleEl = el('div', 'section-title');
+    titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
+    section.appendChild(titleEl);
+    
+    if (attributeEntries.length === 0) {
+        const msg = el('p', 'no-attributes-message');
+        msg.textContent = `No ${title.toLowerCase()} found.`;
+        section.appendChild(msg);
+        return section;
+    }
+
+    // --- 3. Card Container ---
+    const cardsContainer = el('div', 'comparison-cards-container');
+
+    attributeEntries.forEach(attr => {
+        const card = el('div', `comparison-card ${attr.isMatch ? 'match' : 'mismatch-card'}`);
+
+        const header = el('div', 'card-header');
+        header.textContent = attr.name.replace(/_/g, ' ');
+        card.appendChild(header);
+
+        const content = el('div', 'card-content');
+
+        // Existing Value Box
+        const originalBox = el('div', 'value-box original-box');
+        originalBox.innerHTML = `
+            <div class="value-label">Manually Identified Value</div>
+            <div class="value-text">${attr.originalValue}</div>
+        `;
+        content.appendChild(originalBox);
+
+        // AI Value Box
+        const aiBox = el('div', `value-box ai-box ${attr.isMatch ? 'match' : 'mismatch-value'}`);
+        aiBox.innerHTML = `
+            <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
+            <div class="value-text">${attr.aiValue}</div>
+        `;
+        content.appendChild(aiBox);
+
+        card.appendChild(content);
+
+        // Mismatch Indicator
+        if (!attr.isMatch) {
+            const indicator = el('div', 'mismatch-indicator');
+            // indicator.innerHTML = '❌ MISMATCH';
+            indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
+            card.appendChild(indicator);
+        }
+
+        cardsContainer.appendChild(card);
+    });
+
+    section.appendChild(cardsContainer);
+    return section;
+}
+
+/**
+ * Renders Additional, OCR, or Visual attributes in a simple card layout.
+ * @param {Object} attributes - The attribute data (Additional, OCR, or Visual).
+ * @param {string} title - The title for the section.
+ * @returns {HTMLElement} A div containing the attribute cards.
+ */
+function renderSimpleAttributeCards(attributes, title) {
+    const section = el('div', 'attribute-section simple-attribute-section');
+    
+    // --- 1. Flatten Attributes ---
+    let attributeEntries = [];
+
+    const processAttribute = (key, values) => {
+        const valuesArray = Array.isArray(values) ? values : [values]; 
+        valuesArray.forEach(v => {
+            attributeEntries.push({
+                name: key,
+                value: v.value,
+                source: v.source || 'N/A'
+            });
+        });
+    };
+
+    Object.keys(attributes).forEach(key => {
+        const attribute = attributes[key];
+        
+        if (Array.isArray(attribute)) {
+            processAttribute(key, attribute);
+        } else if (typeof attribute === 'object' && attribute !== null) {
+            Object.keys(attribute).forEach(subKey => {
+                const subAttribute = attribute[subKey];
+                if (Array.isArray(subAttribute)) {
+                    processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
+                }
+            });
+        }
+    });
+
+    // --- 2. Section Header ---
+    const titleEl = el('div', 'section-title');
+    titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
+    section.appendChild(titleEl);
+    
+    if (attributeEntries.length === 0) {
+        const msg = el('p', 'no-attributes-message');
+        msg.textContent = `No ${title.toLowerCase()} found.`;
+        section.appendChild(msg);
+        return section;
+    }
+
+    // --- 3. Card Container ---
+    const cardsContainer = el('div', 'comparison-cards-container simple-cards-container');
+
+    attributeEntries.forEach(attr => {
+        // Simple Card Element
+        const card = el('div', 'simple-card');
+
+        // Card Header (Attribute Name)
+        const header = el('div', 'card-header');
+        header.textContent = formatString(attr.name).replace(/_/g, ' ');
+        card.appendChild(header);
+
+        // Content Wrapper
+        const content = el('div', 'card-content');
+        
+        // Value Box
+        const valueBox = el('div', 'value-box single-value-box');
+        const displayValue = Array.isArray(attr.value) 
+            ? (attr.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr.source)+ ')' 
+            : formatString(attr.value) +'('+ formatString(attr.source)+ ')'; 
+            // : attr.value;
+            
+        valueBox.innerHTML = `
+            <div class="value-label">Extracted Value <span class="value-source">(${formatString(attr.source)})</span></div>
+            <div class="value-text">${displayValue || 'N/A'}</div>
+        `;
+        content.appendChild(valueBox);
+
+        card.appendChild(content);
+        cardsContainer.appendChild(card);
+    });
+
+    section.appendChild(cardsContainer);
+    return section;
+}

+ 111 - 0
content_quality_tool_public/templates/attr-extraction-revised.html

@@ -0,0 +1,111 @@
+
+{% load static %}
+<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+  <title>Attribute Extraction</title>
+  <link rel="stylesheet" href="{% static './css/adminlte.css' %}">
+  <link rel="stylesheet" href="{% static 'css/attr-extraction-revised.css' %}">
+</head>
+<body>
+  {% include 'header.html' %}
+  {% include 'sidebar.html' %}
+
+  <main class="container">
+    <header class="hero">
+      <div class="title">
+        <div class="title-logo" aria-hidden="true">
+          <svg width="26" height="26" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+            <path d="M3 12l7-7v5h4V5l7 7-7 7v-5h-4v5l-7-7z" fill="#fff"/>
+          </svg>
+        </div>
+        <div>
+          <h1>⚒️ Attribute Extraction</h1>
+          <div class="sub">Upload products, select attributes, and compare AI vs. existing values.</div>
+        </div>
+      </div>
+      <div class="actions">
+        <button id="uploadOpen" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#uploadModal">Upload</button>
+        <button id="btnReset" class="btn btn-ghost">Reset</button>
+        <button id="btnSubmit" class="btn btn-success">Extract</button>
+      </div>
+    </header>
+
+    <section class="card">
+      <div class="card-header api-header-flex">
+        <h2>API Summary</h2>
+        <div class="download-section">
+          <button id="downloadResultBtn" class="btn btn-secondary">Download</button>
+        </div>
+      </div>
+      <div id="api-summary" class="card-body" style="display:none;">
+        <div class="summary">
+          <div class="stat"><div class="label">Total products</div><div id="statTotal" class="value">0</div></div>
+          <div class="stat"><div class="label">Successful</div><div id="statOk" class="value">0</div></div>
+          <div class="stat"><div class="label">Failed</div><div id="statKo" class="value">0</div></div>
+        </div>
+      </div>
+    </section>
+
+    <section class="card">
+      <div class="card-header">
+        <h2>Product Inventory</h2>
+        <div class="toolbar">
+          <div class="seg" role="tablist" aria-label="Layout switcher">
+            <button id="btnTable" class="active" role="tab" aria-selected="true">Table</button>
+            <button id="btnCards" role="tab" aria-selected="false">Cards</button>
+          </div>
+          <span id="selectionInfo" class="pill">No products selected</span>
+          <button id="btnSelectAll" class="btn btn-secondary">Select all</button>
+          <label class="pill">Threshold: <input id="thresholdRange" type="range" min="0" max="1" step="0.05" value="0.5"/> <strong id="thresholdValue">0.5</strong></label>
+          <label class="pill"><input id="extract_additional" type="checkbox" checked/> Extract Additional</label>
+          <label class="pill"><input id="process_image" type="checkbox"/> Process Image</label>
+          <select id="mandatory-attributes" class="attribute-select" multiple></select>
+        </div>
+      </div>
+      <div class="card-body">
+        <div id="tableContainer" class="table-wrap"></div>
+        <div id="cardsContainer" class="list" style="display:none;"></div>
+        <div id="paginationBar" class="pagination-bar" style="display:none;"></div>
+      </div>
+    </section>
+  </main>
+
+  <!-- Upload Modal -->
+  <div class="modal fade" id="uploadModal" tabindex="-1" aria-hidden="true">
+    <div class="modal-dialog modal-lg">
+      <div class="modal-content">
+        <div class="modal-header">
+          <h5 class="modal-title">Upload files</h5>
+          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+        </div>
+        <div class="modal-body">
+          <div id="dropzone" class="dropzone">
+            <p>Drag & drop files here or browse</p>
+            <input id="uploadFiles" type="file" multiple hidden>
+            <div id="fileInfo" class="file-info">No files selected.</div>
+          </div>
+          <div class="progress mt-3">
+            <div id="uploadBar" class="progress-bar" role="progressbar" style="width:0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
+          </div>
+          <div id="uploadStatus" class="mt-2 small"></div>
+        </div>
+        <div class="modal-footer">
+          <button type="button" class="btn btn-ghost" data-bs-dismiss="modal">Cancel</button>
+          <button type="button" id="uploadStart" class="btn btn-success">Start upload</button>
+        </div>
+      </div>
+    </div>
+  </div>
+
+  <!-- Full page loader -->
+  <div id="full-page-loader" class="loader-overlay" style="display:none;">
+    <div class="spinner-border text-light" role="status"></div>
+  </div>
+
+  {% include 'footer.html' %}
+  <script src="{% static 'js/attr-extraction.js' %}"></script>
+</body>
+</html>

+ 30 - 2
content_quality_tool_public/templates/attr-extraction.html

@@ -39,7 +39,7 @@
               <div class="row">
                   <div class="col-sm-6">
                       <h3 class="mb-0">⛏️ Attribute Extraction
-                            &nbsp;<span><a href="./../media/examples/actual_product_list.xlsx"    title="Example file" download><i class="bi bi-download"></i></a></span>
+                            &nbsp;<span><a href="./../media/examples/sample_products.xlsx"    title="Example file" download><i class="bi bi-download"></i></a></span>
                       </h3>
                   </div>
                   <div class="col-sm-6">
@@ -102,6 +102,34 @@
 
                     <div class="grid">
                     <section class="card" id="api-summary" style="display: none;">
+                        <div class="card-header api-header-flex">
+                            <h2>API Summary</h2>
+                            <div class="download-section">
+                                <!-- <button id="downloadResultBtn" class="btn btn-sm btn-primary">
+                                    <i class="bi bi-download"></i> Download
+                                </button> -->
+                                <a href="./../media/generated_outputs/generated_products.xlsx"  title="Example file" download>
+                                    <button id="downloadResultBtn" class="btn btn-sm btn-primary">
+                                        <i class="bi bi-download"></i> Download
+                                    </button>
+                                </a>
+                            </div>
+                        </div>
+                        <div class="card-body">
+                            <div class="summary">
+                                <div class="stat"><div class="label">Total products</div><div class="value" id="statTotal">0</div></div>
+                                <div class="stat"><div class="label">Successful</div><div class="value" id="statOk">0</div></div>
+                                <div class="stat"><div class="label">Failed</div><div class="value" id="statKo">0</div></div>
+                                
+                                <!-- <div class="stat summary-action-button">
+                                    <button id="downloadSummaryRowBtn" class="btn btn-sm btn-outline-secondary">
+                                        <i class="bi bi-download"></i> Download Summary
+                                    </button>
+                                </div> -->
+                                </div>
+                        </div>
+                    </section>
+                    <!-- <section class="card" id="api-summary" style="display: none;">
                         <div class="card-header">
                         <h2>API Summary</h2>
                         </div>
@@ -112,7 +140,7 @@
                             <div class="stat"><div class="label">Failed</div><div class="value" id="statKo">0</div></div>
                         </div>
                         </div>
-                    </section>    
+                    </section>     -->
                     <section class="card">
                         <div class="card-header">
                         <h2>Products</h2>

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác