attr-extraction.js 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634
  1. jQuery.noConflict(); // Release $ to other libraries
  2. // console.log(typeof jQuery);
  3. // $ = jQuery;
  4. // --- Config ---
  5. const UPLOAD_API_URL = '/attr/products/upload-excel/'; // TODO: set to your upload endpoint
  6. const ACCEPT_TYPES = '*'; // e.g., 'image/*,.csv,.xlsx'
  7. const thresholdInput = document.getElementById('thresholdRange');
  8. const thresholdValueDisplay = document.getElementById('thresholdValue');
  9. var PRODUCT_BASE = [
  10. // { 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' },
  11. // { 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' },
  12. // { 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' },
  13. // { 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' },
  14. // { 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' }
  15. ];
  16. // --- Data ---
  17. const mediaUrl = "./../";
  18. document.addEventListener('DOMContentLoaded', () => {
  19. jQuery('#full-page-loader').show();
  20. fetch('/attr/products', {
  21. method: 'GET', // or 'POST' if your API expects POST
  22. headers: {
  23. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
  24. }
  25. })
  26. .then(response => response.json())
  27. .then(data => {
  28. // console.log("data",data);
  29. // --- Wire up ---
  30. PRODUCT_BASE = data;
  31. PRODUCT_BASE = PRODUCT_BASE.map((d)=>{return {...d,mandatoryAttributes:["color","size"]}});
  32. // console.log("PRODUCT_BASE",PRODUCT_BASE);
  33. if(PRODUCT_BASE.length > 0){
  34. $('#paginationBar').style.display = 'block';
  35. }
  36. renderProducts();
  37. getAtributeList();
  38. document.getElementById('btnSubmit').addEventListener('click', submitAttributes);
  39. // document.getElementById('btnReset').addEventListener('click', resetAll);
  40. // document.getElementById('btnSelectAll').addEventListener('click', () => {
  41. // if (selectedIds.size === PRODUCT_BASE.length) { selectedIds.clear(); } else { selectedIds = new Set(PRODUCT_BASE.map(p => p.id)); }
  42. // // renderProducts();
  43. // });
  44. // Replace your existing Select All listener with this:
  45. document.getElementById('btnSelectAll').addEventListener('click', () => {
  46. // Use the container for the active layout
  47. const container = (layoutMode === 'cards')
  48. ? document.getElementById('cardsContainer')
  49. : document.getElementById('tableContainer');
  50. // Collect all visible checkboxes
  51. const boxes = Array.from(container.querySelectorAll('input[type="checkbox"]'));
  52. // If every visible checkbox is already checked, we'll deselect; otherwise select all
  53. const allChecked = boxes.length > 0 && boxes.every(cb => cb.checked);
  54. boxes.forEach(cb => {
  55. const target = !allChecked; // true to select, false to deselect
  56. if (cb.checked !== target) {
  57. cb.checked = target;
  58. // Trigger your existing "change" handler so selectedIds & row .selected class update
  59. cb.dispatchEvent(new Event('change', { bubbles: true }));
  60. }
  61. });
  62. // Update the selection pill text (doesn't re-render the list)
  63. updateSelectionInfo();
  64. });
  65. document.getElementById('btnCards').addEventListener('click', () => setLayout('cards'));
  66. document.getElementById('btnTable').addEventListener('click', () => setLayout('table'));
  67. jQuery('#full-page-loader').hide();
  68. // if (data.success) {
  69. // }
  70. });
  71. });
  72. var API_RESPONSE_AI = {
  73. // results: [
  74. // { 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' } },
  75. // { 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' } },
  76. // { 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' } },
  77. // { 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' } },
  78. // { 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' } }
  79. // ],
  80. // total_products: 5,
  81. // successful: 5,
  82. // failed: 0
  83. };
  84. // --- State ---
  85. let selectedIds = new Set();
  86. // NEW: Array of objects { item_id: string, mandatory_attrs: { [attribute_name]: string[] } }
  87. let selectedProductsWithAttributes = [];
  88. let selectedAttributes = new Array();
  89. const lastSeen = new Map(); // per-product memory for NEW highlighting (product_id -> maps)
  90. let layoutMode = 'table'; // 'cards' | 'table'
  91. // --- Helpers ---
  92. const $ = (sel) => document.querySelector(sel);
  93. const el = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; return e; }
  94. function updateSelectionInfo() {
  95. const pill = $('#selectionInfo');
  96. const total = PRODUCT_BASE.length;
  97. // const count = selectedIds.size;
  98. const count = selectedProductsWithAttributes.length;
  99. pill.textContent = count === 0 ? 'No products selected' : `${count} of ${total} selected`;
  100. }
  101. function setChecked(id, checked) { if (checked) selectedIds.add(id); else selectedIds.delete(id); updateSelectionInfo(); }
  102. // function setCheckedAttributes(id,attribute, checked) { if (checked) selectedAttributes.add({id: [attribute]}); else selectedIds.delete({id:[attribute]}); updateSelectionInfo(); }
  103. function formatString(str) {
  104. return str
  105. // Replace underscores with spaces
  106. .replace(/_/g, ' ')
  107. // Insert a space before any uppercase letter (except at the start)
  108. .replace(/([a-z])([A-Z])/g, '$1 $2')
  109. // Capitalize the first letter
  110. .replace(/^./, char => char.toUpperCase());
  111. }
  112. // --- Chips rendering ---
  113. function renderChips(container, obj, memoryMap) {
  114. container.innerHTML = '';
  115. let count = 0;
  116. Object.entries(obj || {}).forEach(([k, v]) => {
  117. const chip = el('span', 'chip');
  118. const kEl = el('span', 'k'); kEl.textContent = formatString(k) + ':';
  119. // console.log("v",v);
  120. let resVal = "";
  121. let sourceVal = "";
  122. if(v instanceof Array){
  123. resVal = String(v.map(v => formatString(v.value)).join(", "));
  124. sourceVal = String(formatString(v[0]?.source));
  125. const vEl = el('span', 'v'); vEl.textContent = ' ' + resVal +' (' + sourceVal + ')';
  126. chip.appendChild(kEl); chip.appendChild(vEl);
  127. }
  128. // console.log("k",k);
  129. if(v instanceof Array){
  130. const was = memoryMap.get(k);
  131. if (was === undefined || was !== v) chip.classList.add('new');
  132. container.appendChild(chip);
  133. memoryMap.set(k, v);
  134. count++;
  135. }
  136. });
  137. return count;
  138. }
  139. function findApiResultForProduct(p, index, api) { return api.results?.find(r => r.product_id === p.item_id) || api.results?.[index] || null; }
  140. // --- Cards layout ---
  141. function createProductCard(p) {
  142. const row = el('div', 'product');
  143. // Check selection using the new helper
  144. if (isProductSelected(p.item_id)) row.classList.add('selected');
  145. // if (selectedIds.has(p.item_id)) row.classList.add('selected');
  146. // const left = el('div', 'thumb');
  147. // const img = new Image(); img.src = p.image_path || p.image || '';
  148. // // console.log("image path",p.image_path);
  149. // img.alt = `${p.product_name} image`;
  150. // // console.log("img",img);
  151. // // 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); };
  152. // img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  153. // left.appendChild(img);
  154. // Assume 'el' is a function that creates an element (e.g., document.createElement)
  155. // Assume 'p' (product data) and 'mediaUrl' are available in scope.
  156. // 1. Create the main container for the hover effect
  157. const container = el('div', 'mini-thumb-container');
  158. // 2. Create the visible thumbnail wrapper (your original 'left' element)
  159. // This will serve as the base for the small image
  160. const left = el('div', 'thumb');
  161. // Get the image source (same as before)
  162. const imageSrc = p.image_path || p.image || '';
  163. // 3. Create the thumbnail image element (same as before)
  164. const thumbImg = new Image();
  165. thumbImg.src = imageSrc;
  166. thumbImg.alt = `${p.product_name} image`;
  167. thumbImg.onerror = () => { thumbImg.src = mediaUrl+"media/images/no-product.png" };
  168. // Use thumbImg instead of img to avoid naming conflict with other code if possible
  169. // We will call it 'img' here to match your original code:
  170. const img = thumbImg;
  171. left.appendChild(img);
  172. container.appendChild(left); // Add the visible thumbnail to the main container
  173. // 4. Create the full-size image element for hover (new part)
  174. const fullImgWrapper = el('div', 'full-image-hover'); // Class for CSS control
  175. const fullImg = new Image();
  176. fullImg.src = imageSrc; // Use the same source, or p.full_image_path if available
  177. fullImg.alt = `${p.product_name} full view`;
  178. fullImg.onerror = () => { fullImg.src = mediaUrl + "media/images/no-product.png" }; // Same fallback
  179. fullImgWrapper.appendChild(fullImg);
  180. container.appendChild(fullImgWrapper); // Add full image wrapper to the main container
  181. // The variable to use when appending this element to the DOM is 'container'.
  182. // return container; // If this block is inside a function
  183. const mid = el('div', 'meta');
  184. const name = el('div', 'name'); name.textContent = p.product_name || '—';
  185. const desc = el('div', 'desc'); desc.innerHTML = p.product_short_description || '';
  186. const badges = el('div', 'badges');
  187. const sku = el('span', 'pill'); sku.textContent = `SKU: ${p.item_id || '—'}`; badges.appendChild(sku);
  188. const type = el('span', 'pill'); type.textContent = p.product_type || '—'; badges.appendChild(type);
  189. const long = el('div', 'desc'); long.innerHTML = p.product_long_description || ''; long.style.marginTop = '4px';
  190. mid.appendChild(name); mid.appendChild(desc); mid.appendChild(badges); mid.appendChild(long);
  191. // Helper function to create the chip UI for attributes
  192. function createAttributeChips(p, attr, initialSelected, isMandatory, updateCallback) {
  193. const wrapper = el('div', 'attribute-chip-group');
  194. wrapper.dataset.attrName = attr.attribute_name;
  195. wrapper.innerHTML = `<p class="attribute-header">${attr.attribute_name} (${isMandatory ? 'Mandatory' : 'Optional'}):</p>`;
  196. const chipContainer = el('div', 'chips-container');
  197. attr.possible_values.forEach(value => {
  198. const chip = el('label', 'attribute-chip');
  199. // Checkbox input is hidden, but drives the selection state
  200. const checkbox = document.createElement('input');
  201. checkbox.type = 'checkbox';
  202. checkbox.value = value;
  203. checkbox.name = `${p.item_id}-${attr.attribute_name}`;
  204. // Set initial state
  205. checkbox.checked = initialSelected.includes(value);
  206. // The visual part of the chip
  207. const span = el('span');
  208. span.textContent = value;
  209. chip.appendChild(checkbox);
  210. chip.appendChild(span);
  211. chipContainer.appendChild(chip);
  212. });
  213. // Use event delegation on the container for performance
  214. chipContainer.addEventListener('change', updateCallback);
  215. wrapper.appendChild(chipContainer);
  216. return wrapper;
  217. }
  218. // --- Main Select Checkbox (Product Selection) ---
  219. const right = el('label', 'select');
  220. const cb = document.createElement('input'); cb.type = 'checkbox';
  221. cb.checked = isProductSelected(p.item_id);
  222. const lbl = el('span'); lbl.textContent = 'Select Product';
  223. right.appendChild(cb); right.appendChild(lbl);
  224. // --- Dynamic Attribute Selects ---
  225. const attrContainer = el('div', 'attribute-selectors');
  226. if(p.product_type_details.length > 0){
  227. // Find all mandatory and non-mandatory attributes for this product
  228. const mandatoryAttributes = p.product_type_details?.filter(a => a.is_mandatory === 'Yes') || [];
  229. const optionalAttributes = p.product_type_details?.filter(a => a.is_mandatory !== 'Yes') || [];
  230. // Helper to update the main state object with all current selections
  231. const updateProductState = () => {
  232. const isSelected = cb.checked;
  233. const currentSelections = {};
  234. if (isSelected) {
  235. // Iterate over all attribute groups (Mandatory and Optional)
  236. attrContainer.querySelectorAll('.attribute-chip-group').forEach(group => {
  237. const attrName = group.dataset.attrName;
  238. // Collect selected chip values
  239. const selectedOptions = Array.from(group.querySelectorAll('input[type="checkbox"]:checked'))
  240. .map(checkbox => checkbox.value);
  241. if (selectedOptions.length > 0) {
  242. currentSelections[attrName] = selectedOptions;
  243. }
  244. });
  245. }
  246. toggleProductSelection(p.item_id, isSelected, currentSelections);
  247. row.classList.toggle('selected', isSelected);
  248. };
  249. // Attach listener to main checkbox
  250. cb.addEventListener('change', () => {
  251. attrContainer.classList.toggle('disabled', !cb.checked);
  252. updateProductState();
  253. });
  254. // --- Render Mandatory Attributes ---
  255. // if (mandatoryAttributes.length > 0) {
  256. // const manTitle = el('p', "pSelectRight mandatory-title");
  257. // manTitle.innerHTML = "Mandatory Attributes:";
  258. // attrContainer.appendChild(manTitle);
  259. // mandatoryAttributes.forEach(attr => {
  260. // const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  261. // const chipGroup = createAttributeChips(p, attr, initialSelected, true, updateProductState);
  262. // attrContainer.appendChild(chipGroup);
  263. // });
  264. // }
  265. // --- Render Optional Attributes ---
  266. if (optionalAttributes.length > 0) {
  267. const br = el('br');
  268. const optTitle = el('p', "pSelectRight optional-title");
  269. optTitle.innerHTML = "Additional Attributes:";
  270. attrContainer.appendChild(br);
  271. attrContainer.appendChild(optTitle);
  272. optionalAttributes.forEach(attr => {
  273. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  274. const chipGroup = createAttributeChips(p, attr, initialSelected, false, updateProductState);
  275. attrContainer.appendChild(chipGroup);
  276. });
  277. }
  278. // Initialize attribute selectors' enabled state and state data
  279. attrContainer.classList.toggle('disabled', !cb.checked);
  280. // Initial state setup if the product was already selected (e.g., after a re-render)
  281. if (cb.checked) {
  282. // This is important to set the initial state correctly on load
  283. // We defer this until all selects are mounted, or ensure the initial state is correct.
  284. // For simplicity, we assume the data from PRODUCT_BASE already includes selected attributes if a selection exists
  285. // (which it won't in this case, so they default to all/empty)
  286. }
  287. }
  288. const inline = el('div', 'attr-inline');
  289. inline.dataset.pid = p.item_id; // use item_id for mapping
  290. row.appendChild(container); row.appendChild(mid);
  291. if(p.product_type_details.length > 0){
  292. console.log("IN ");
  293. // row.appendChild(attrContainer); // Append the new attribute selectors container
  294. }
  295. row.appendChild(right);
  296. // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  297. // const hr = el('hr');
  298. // row.appendChild(hr);
  299. // row.appendChild(attri);
  300. // row.appendChild(secondRight);
  301. // }
  302. row.appendChild(inline);
  303. return row;
  304. }
  305. // Cards layout
  306. function renderProductsCards(items = getCurrentSlice()) {
  307. const cards = document.getElementById('cardsContainer');
  308. cards.innerHTML = '';
  309. if(items.length > 0){
  310. items.forEach(p => cards.appendChild(createProductCard(p)));
  311. }else{
  312. cards.innerHTML = "<p>No Products Found.</p>"
  313. }
  314. }
  315. // --- Table layout ---
  316. // function createMiniThumb(p) {
  317. // const mt = el('div', 'mini-thumb');
  318. // const img = new Image(); img.src = p.image_path || p.image || ''; img.alt = `${p.product_name} image`;
  319. // // console.log("image path",p.image_path);
  320. // // console.log("img",img);
  321. // img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  322. // // 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); };
  323. // mt.appendChild(img);
  324. // return mt;
  325. // }
  326. function createMiniThumb(p) {
  327. // 1. Create a container for the hover effect
  328. const container = document.createElement('div');
  329. container.className = 'mini-thumb-container';
  330. // 2. Create the visible thumbnail (Mini Thumb)
  331. const mt = document.createElement('div');
  332. mt.className = 'mini-thumb';
  333. // Get the image source
  334. const imageSrc = p.image_path || p.image || '';
  335. // 3. Create the thumbnail image element
  336. const thumbImg = new Image();
  337. thumbImg.src = imageSrc;
  338. thumbImg.alt = `${p.product_name} thumbnail`;
  339. thumbImg.onerror = () => { thumbImg.src = mediaUrl + "media/images/no-product.png" };
  340. mt.appendChild(thumbImg);
  341. container.appendChild(mt); // Add thumbnail to container
  342. // 4. Create the full-size image element for hover
  343. const fullImgWrapper = document.createElement('div');
  344. fullImgWrapper.className = 'full-image-hover'; // Class for CSS control
  345. const fullImg = new Image();
  346. // Assuming the same source is used for the full image, but you can change this
  347. // to p.full_image_path if your product object has a separate full-size URL.
  348. fullImg.src = imageSrc;
  349. fullImg.alt = `${p.product_name} full view`;
  350. fullImg.onerror = () => { fullImg.src = mediaUrl + "media/images/no-product.png" }; // Same fallback
  351. fullImgWrapper.appendChild(fullImg);
  352. container.appendChild(fullImgWrapper); // Add full image wrapper to container
  353. // Return the main container instead of just the mini-thumb
  354. return container;
  355. }
  356. // function createMiniThumb(p) {
  357. // const container = document.createElement('div');
  358. // container.className = 'mini-thumb-container';
  359. // const mt = document.createElement('div');
  360. // mt.className = 'mini-thumb';
  361. // const imageSrc = p.image_path || p.image || '';
  362. // const thumbImg = new Image();
  363. // thumbImg.src = imageSrc;
  364. // thumbImg.alt = `${p.product_name} thumbnail`;
  365. // thumbImg.onerror = () => { thumbImg.src = mediaUrl + "media/images/no-product.png" };
  366. // mt.appendChild(thumbImg);
  367. // container.appendChild(mt);
  368. // const fullImgWrapper = document.createElement('div');
  369. // fullImgWrapper.className = 'full-image-hover';
  370. // const fullImg = new Image();
  371. // fullImg.src = imageSrc;
  372. // fullImg.alt = `${p.product_name} full view`;
  373. // fullImg.onerror = () => { fullImg.src = mediaUrl + "media/images/no-product.png" };
  374. // fullImgWrapper.appendChild(fullImg);
  375. // document.body.appendChild(fullImgWrapper); // Append to body, not container
  376. // // Hover logic
  377. // mt.addEventListener('mouseenter', () => {
  378. // fullImgWrapper.style.display = 'block';
  379. // });
  380. // mt.addEventListener('mousemove', (e) => {
  381. // fullImgWrapper.style.top = (e.clientY + 20) + 'px'; // 20px offset
  382. // fullImgWrapper.style.left = (e.clientX + 20) + 'px';
  383. // });
  384. // mt.addEventListener('mouseleave', () => {
  385. // fullImgWrapper.style.display = 'none';
  386. // });
  387. // return container;
  388. // }
  389. // Create one global hover container
  390. // const hoverContainer = document.createElement('div');
  391. // hoverContainer.className = 'full-image-hover';
  392. // const hoverImg = new Image();
  393. // hoverContainer.appendChild(hoverImg);
  394. // document.body.appendChild(hoverContainer);
  395. // let hoverActive = false;
  396. // function createMiniThumb(p) {
  397. // const container = document.createElement('div');
  398. // container.className = 'mini-thumb-container';
  399. // const mt = document.createElement('div');
  400. // mt.className = 'mini-thumb';
  401. // const imageSrc = p.image_path || p.image || '';
  402. // const thumbImg = new Image();
  403. // thumbImg.src = imageSrc;
  404. // thumbImg.alt = `${p.product_name} thumbnail`;
  405. // thumbImg.onerror = () => { thumbImg.src = mediaUrl + "media/images/no-product.png" };
  406. // mt.appendChild(thumbImg);
  407. // container.appendChild(mt);
  408. // // Hover logic
  409. // mt.addEventListener('mouseenter', () => {
  410. // hoverImg.src = imageSrc;
  411. // hoverImg.alt = `${p.product_name} full view`;
  412. // hoverContainer.style.display = 'block';
  413. // });
  414. // mt.addEventListener('mousemove', (e) => {
  415. // hoverContainer.style.top = (e.clientY + 20) + 'px';
  416. // hoverContainer.style.left = (e.clientX + 20) + 'px';
  417. // });
  418. // mt.addEventListener('mouseleave', () => {
  419. // setTimeout(() => {
  420. // if (!hoverActive) hoverContainer.style.display = 'none';
  421. // }, 100);
  422. // });
  423. // hoverContainer.addEventListener('mouseenter', () => {
  424. // hoverActive = true;
  425. // });
  426. // hoverContainer.addEventListener('mouseleave', () => {
  427. // hoverActive = false;
  428. // hoverContainer.style.display = 'none';
  429. // });
  430. // return container;
  431. // }
  432. // Table layout
  433. // function renderProductsTable(items = getCurrentSlice()) {
  434. // const wrap = document.getElementById('tableContainer');
  435. // wrap.innerHTML = '';
  436. // const table = document.createElement('table');
  437. // const thead = document.createElement('thead'); const trh = document.createElement('tr');
  438. // ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
  439. // const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
  440. // });
  441. // thead.appendChild(trh); table.appendChild(thead);
  442. // const tbody = document.createElement('tbody');
  443. // if(items.length > 0 ){
  444. // items.forEach(p => {
  445. // const tr = document.createElement('tr'); tr.id = `row-${p.id}`;
  446. // const tdSel = document.createElement('td'); tdSel.className = 'select-cell';
  447. // const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
  448. // cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); tr.classList.toggle('selected', cb.checked); });
  449. // tdSel.appendChild(cb); tr.appendChild(tdSel);
  450. // const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  451. // const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  452. // const tdSku = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  453. // const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  454. // const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
  455. // tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  456. // tbody.appendChild(tr);
  457. // });
  458. // }else{
  459. // const tr = el('tr');
  460. // // tr.id = `row-${p.id}`;
  461. // const tdName = el('td');
  462. // tdName.colSpan = 6;
  463. // tdName.innerHTML = "No Products Found."
  464. // tr.appendChild(tdName);
  465. // // tr.colspan = 6;
  466. // // tr.innerHTML
  467. // tbody.appendChild(tr);
  468. // }
  469. // table.appendChild(tbody);
  470. // wrap.appendChild(table);
  471. // }
  472. // NOTE: Ensure getProductStateUpdater and generateAttributeUI functions are defined globally or accessible here.
  473. /**
  474. * Returns a closure function that updates the global selectedProductsWithAttributes state
  475. * based on the current selections (chips) found in the DOM for a specific product.
  476. * This is used for both card and table views.
  477. * * @param {Object} p - The product object.
  478. * @param {HTMLElement} cb - The main product selection checkbox element.
  479. * @param {HTMLElement} tr - The main row/card element (used for toggling 'selected' class).
  480. * @returns {function} A function to be used as the attribute change handler.
  481. */
  482. const getProductStateUpdater = (p, cb, tr) => () => {
  483. const isSelected = cb.checked;
  484. const currentSelections = {};
  485. // Find the attribute container using its unique ID, which is the same structure
  486. // used in both card and table detail views (e.g., 'attr-container-124353498' or just the main card element).
  487. // For card view, the container is often the attrContainer element itself.
  488. // For table view, we use the explicit ID.
  489. const attrContainer = document.getElementById(`attr-container-${p.item_id}`) || tr.querySelector('.attribute-selectors');
  490. if (isSelected && attrContainer) {
  491. // Iterate over all attribute groups (Mandatory and Optional) within the container
  492. attrContainer.querySelectorAll('.attribute-chip-group').forEach(group => {
  493. const attrName = group.dataset.attrName;
  494. // Collect selected chip values
  495. const selectedOptions = Array.from(group.querySelectorAll('input[type="checkbox"]:checked'))
  496. .map(checkbox => checkbox.value);
  497. // Only add to the selection if at least one option is selected
  498. if (selectedOptions.length > 0) {
  499. currentSelections[attrName] = selectedOptions;
  500. }
  501. });
  502. }
  503. // Update the global state array (selectedProductsWithAttributes)
  504. toggleProductSelection(p.item_id, isSelected, currentSelections);
  505. // Update the visual status of the row/card
  506. tr.classList.toggle('selected', isSelected);
  507. };
  508. /**
  509. * Generates the full attribute selection UI (chips) for a given product.
  510. * NOTE: Assumes el(), createAttributeChips(), and getSelectedAttributes() are defined globally.
  511. * @param {Object} p - The product object from PRODUCT_BASE.
  512. * @param {function} updateProductState - The callback to run on chip changes.
  513. * @param {HTMLElement} attrContainer - The container to append the UI to.
  514. */
  515. function generateAttributeUI(p, updateProductState, attrContainer) {
  516. // Clear the container first, just in case
  517. attrContainer.innerHTML = '';
  518. const mandatoryAttributes = p.product_type_details?.filter(a => a.is_mandatory === 'Yes') || [];
  519. const optionalAttributes = p.product_type_details?.filter(a => a.is_mandatory !== 'Yes') || [];
  520. // --- Render Mandatory Attributes ---
  521. if (mandatoryAttributes.length > 0) {
  522. // Use a general title for the section header
  523. const manTitle = el('p', "pSelectRight mandatory-title");
  524. manTitle.innerHTML = "Mandatory Attributes:";
  525. attrContainer.appendChild(manTitle);
  526. mandatoryAttributes.forEach(attr => {
  527. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  528. // The createAttributeChips function must be globally available
  529. const chipGroup = createAttributeChips(p, attr, initialSelected, true, updateProductState);
  530. attrContainer.appendChild(chipGroup);
  531. });
  532. }
  533. // --- Render Optional Attributes ---
  534. if (optionalAttributes.length > 0) {
  535. // Add visual separation using the optional-title class
  536. const optTitle = el('p', "pSelectRight optional-title");
  537. optTitle.innerHTML = "Additional Attributes:";
  538. // Append the title for separation
  539. attrContainer.appendChild(optTitle);
  540. optionalAttributes.forEach(attr => {
  541. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  542. const chipGroup = createAttributeChips(p, attr, initialSelected, false, updateProductState);
  543. attrContainer.appendChild(chipGroup);
  544. });
  545. }
  546. }
  547. /**
  548. * Creates the HTML structure for a single attribute group using chip/checkbox labels.
  549. * Assumes the helper function 'el' is available.
  550. * * @param {Object} p - The product object.
  551. * @param {Object} attr - The specific attribute detail object.
  552. * @param {string[]} initialSelected - Array of values that should be pre-checked.
  553. * @param {boolean} isMandatory - True if the attribute is mandatory.
  554. * @param {function} updateCallback - The function to call when a chip selection changes.
  555. * @returns {HTMLElement} The attribute chip group container (div).
  556. */
  557. function createAttributeChips(p, attr, initialSelected, isMandatory, updateCallback) {
  558. const wrapper = el('div', 'attribute-chip-group');
  559. wrapper.dataset.attrName = attr.attribute_name;
  560. // Determine the header text based on structure preference (e.g., just the name)
  561. const statusText = isMandatory ? ' (Mandatory)' : ' (Optional)';
  562. wrapper.innerHTML = `<p class="attribute-header">${attr.attribute_name}${statusText}:</p>`;
  563. const chipContainer = el('div', 'chips-container');
  564. attr.possible_values.forEach(value => {
  565. const chip = el('label', 'attribute-chip');
  566. // Checkbox input is hidden, but drives the selection state
  567. const checkbox = document.createElement('input');
  568. checkbox.type = 'checkbox';
  569. checkbox.value = value;
  570. // Ensure the name is unique per product/attribute group
  571. checkbox.name = `${p.item_id}-${attr.attribute_name}`;
  572. // Set initial state
  573. checkbox.checked = initialSelected.includes(value);
  574. // The visual part of the chip
  575. const span = el('span');
  576. span.textContent = value;
  577. chip.appendChild(checkbox);
  578. chip.appendChild(span);
  579. chipContainer.appendChild(chip);
  580. });
  581. // Attach listener to the container using event delegation
  582. chipContainer.addEventListener('change', updateCallback);
  583. wrapper.appendChild(chipContainer);
  584. return wrapper;
  585. }
  586. function renderProductsTable(items = getCurrentSlice()) {
  587. const wrap = document.getElementById('tableContainer');
  588. wrap.innerHTML = '';
  589. const table = document.createElement('table');
  590. table.classList.add('table', 'table-striped', 'table-bordered','table-responsive');
  591. const thead = document.createElement('thead');
  592. const trh = document.createElement('tr');
  593. // Table Headers
  594. ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
  595. const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
  596. });
  597. thead.appendChild(trh); table.appendChild(thead);
  598. const tbody = document.createElement('tbody');
  599. if (items.length > 0) {
  600. items.forEach(p => {
  601. const tr = document.createElement('tr');
  602. tr.id = `row-${p.id}`;
  603. if (isProductSelected(p.item_id)) tr.classList.add('selected');
  604. // --- Define Checkbox (cb) and State Updater ---
  605. const cb = document.createElement('input');
  606. cb.type = 'checkbox';
  607. cb.checked = isProductSelected(p.item_id);
  608. // console.log("checkkkkk")
  609. // The state updater function is bound to this specific row/checkbox
  610. const updateProductState = getProductStateUpdater(p, cb, tr);
  611. // --- Select Cell ---
  612. const tdSel = document.createElement('td');
  613. tdSel.className = 'select-cell';
  614. tdSel.appendChild(cb);
  615. tr.appendChild(tdSel);
  616. // --- Other Cells ---
  617. const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  618. const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  619. const tdSku  = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  620. const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  621. const tdDesc = document.createElement('td'); tdDesc.innerHTML = p.product_short_description || ''; tr.appendChild(tdDesc);
  622. // ---------------------------------------------
  623. // --- ATTRIBUTE SELECTION IMPLEMENTATION ---
  624. // ---------------------------------------------
  625. // 1. DETAIL ROW STRUCTURE
  626. const detailRow = document.createElement('tr');
  627. detailRow.classList.add('attribute-detail-row'); // Custom class for styling
  628. detailRow.style.display = 'none'; // Initially hidden
  629. detailRow.id = `detail-row-${p.id}`;
  630. const detailCell = document.createElement('td');
  631. detailCell.colSpan = 6; // Must span all columns
  632. const attrContainer = document.createElement('div');
  633. attrContainer.id = `attr-container-${p.item_id}`; // Unique ID for targeting by updateProductState
  634. attrContainer.classList.add('attribute-selectors', 'table-selectors');
  635. // 2. GENERATE CHIPS UI
  636. generateAttributeUI(p, updateProductState, attrContainer);
  637. // Initially disable the chips if the product is not selected
  638. attrContainer.classList.toggle('disabled', !cb.checked);
  639. detailCell.appendChild(attrContainer);
  640. detailRow.appendChild(detailCell);
  641. if(p.product_type_details.length > 0){
  642. // 3. TOGGLE BUTTON (in the main row)
  643. const tdAttr = document.createElement('td');
  644. const toggleButton = document.createElement('button');
  645. toggleButton.textContent = 'Configure';
  646. toggleButton.classList.add('btn', 'btn-sm', 'btn-info', 'attribute-toggle-btn');
  647. tdAttr.appendChild(toggleButton);
  648. // tr.appendChild(tdAttr);
  649. // 4. EVENT LISTENERS
  650. // a) Toggle Button Logic
  651. toggleButton.addEventListener('click', (e) => {
  652. e.stopPropagation(); // Stop row click event
  653. const isHidden = detailRow.style.display === 'none';
  654. detailRow.style.display = isHidden ? '' : 'none'; // Toggle visibility
  655. toggleButton.textContent = isHidden ? 'Hide Attributes' : 'Configure';
  656. toggleButton.classList.toggle('btn-info', !isHidden);
  657. toggleButton.classList.toggle('btn-secondary', isHidden);
  658. });
  659. // b) Main Checkbox Change Logic
  660. cb.addEventListener('change', () => {
  661. // console.log("cheeeeeeeeee");
  662. updateProductState(); // Update state on check/uncheck
  663. attrContainer.classList.toggle('disabled', !cb.checked); // Enable/Disable chips
  664. });
  665. // c) Row Click Listener (Updated to ignore button clicks)
  666. tr.addEventListener('click', (e) => {
  667. const tag = e.target.tagName.toLowerCase();
  668. // console.log("clikk")
  669. if (tag !== 'input' && tag !== 'button') {
  670. cb.checked = !cb.checked;
  671. cb.dispatchEvent(new Event('change'));
  672. }
  673. });
  674. }else{
  675. const tdAttr = document.createElement('td');
  676. tr.appendChild(tdAttr);
  677. // b) Main Checkbox Change Logic
  678. cb.addEventListener('change', () => {
  679. // console.log("cheeeeeeeeee");
  680. updateProductState(); // Update state on check/uncheck
  681. attrContainer.classList.toggle('disabled', !cb.checked); // Enable/Disable chips
  682. });
  683. tr.addEventListener('click', (e) => {
  684. const tag = e.target.tagName.toLowerCase();
  685. // console.log("clikk")
  686. if (tag !== 'input' && tag !== 'button') {
  687. cb.checked = !cb.checked;
  688. cb.dispatchEvent(new Event('change'));
  689. }
  690. });
  691. }
  692. // 5. Append Rows to TBODY
  693. tbody.appendChild(tr);
  694. tbody.appendChild(detailRow); // Append the detail row right after the main row
  695. });
  696. } else {
  697. const tr = el('tr');
  698. const tdName = el('td');
  699. tdName.colSpan = 6;
  700. tdName.innerHTML = "No Products Found.";
  701. tr.appendChild(tdName);
  702. tbody.appendChild(tr);
  703. }
  704. table.appendChild(tbody);
  705. wrap.appendChild(table);
  706. }
  707. // function renderInlineForCards() {
  708. // const api = API_RESPONSE_AI;
  709. // // Clear all inline sections first
  710. // document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  711. // PRODUCT_BASE.forEach((p, idx) => {
  712. // const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  713. // if (!inline) return;
  714. // // --- CHANGE HERE: Use the new helper function ---
  715. // if (!isProductSelected(p.item_id)) return; // only show for selected
  716. // const res = findApiResultForProduct(p, idx, api);
  717. // const pid = p.item_id;
  718. // if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
  719. // const mem = lastSeen.get(pid);
  720. // // Build sections
  721. // const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  722. // const manChips = el('div', 'chips');
  723. // const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  724. // const addChips = el('div', 'chips');
  725. // const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
  726. // const ocrChips = el('div', 'chips');
  727. // const addVisual = el('div', 'section-title'); addVisual.innerHTML = '<strong>Visual</strong>';
  728. // const visualChips = el('div', 'chips');
  729. // const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  730. // const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  731. // const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem?.ocr_results);
  732. // const visualCount = renderChips(visualChips, res?.visual_results?.visual_attributes || {}, mem?.visual_results);
  733. // const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  734. // const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  735. // const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  736. // const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
  737. // const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  738. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  739. // inline.appendChild(manTitle); inline.appendChild(manChips);
  740. // inline.appendChild(addTitle); inline.appendChild(addChips);
  741. // inline.appendChild(addOcr); inline.appendChild(ocrChips);
  742. // inline.appendChild(addVisual); inline.appendChild(visualChips);
  743. // inline.appendChild(counts);
  744. // });
  745. // // Update summary
  746. // $('#statTotal').textContent = api.total_products ?? 0;
  747. // $('#statOk').textContent = api.successful ?? 0;
  748. // $('#statKo').textContent = api.failed ?? 0;
  749. // $('#api-summary').style.display = 'block';
  750. // }
  751. // -----------------------------------------------------------
  752. // function renderInlineForTable() {
  753. // const api = API_RESPONSE_AI;
  754. // const table = $('#tableContainer');
  755. // if (!table) return;
  756. // // Remove existing detail rows
  757. // table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  758. // PRODUCT_BASE.forEach((p, idx) => {
  759. // // --- CHANGE HERE: Use the new helper function ---
  760. // if (!isProductSelected(p.item_id)) return;
  761. // const res = findApiResultForProduct(p, idx, api);
  762. // const pid = p.item_id;
  763. // if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
  764. // const mem = lastSeen.get(pid);
  765. // const tbody = table.querySelector('tbody');
  766. // // NOTE: The table rendering uses p.id for the row ID: `row-${p.id}`.
  767. // // Assuming p.id is still valid for finding the base row, as your original code used it.
  768. // const baseRow = tbody.querySelector(`#row-${p.id}`);
  769. // if (!baseRow) return;
  770. // const detail = el('tr', 'detail-row');
  771. // const td = el('td'); td.colSpan = 6; // number of columns
  772. // const content = el('div', 'detail-content');
  773. // const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  774. // const manChips = el('div', 'chips');
  775. // const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  776. // const addChips = el('div', 'chips');
  777. // const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
  778. // const ocrChips = el('div', 'chips');
  779. // const addVisuals = el('div', 'section-title'); addVisuals.innerHTML = '<strong>Visuals</strong>';
  780. // const visualsChips = el('div', 'chips');
  781. // const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  782. // const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  783. // const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem.ocr_results);
  784. // const visualCount = renderChips(visualsChips, res?.visual_results?.visual_attributes || {}, mem.visual_results);
  785. // const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  786. // const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  787. // const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  788. // const c3 = el('span', 'pill'); c3.textContent = `Ocr: ${ocrCount}`;
  789. // const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  790. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  791. // content.appendChild(manTitle); content.appendChild(manChips);
  792. // content.appendChild(addTitle); content.appendChild(addChips);
  793. // content.appendChild(addOcr); content.appendChild(ocrChips);
  794. // content.appendChild(addVisuals); content.appendChild(visualsChips);
  795. // content.appendChild(counts);
  796. // td.appendChild(content); detail.appendChild(td);
  797. // // insert after base row
  798. // baseRow.insertAdjacentElement('afterend', detail);
  799. // });
  800. // // Update summary
  801. // $('#statTotal').textContent = api.total_products ?? 0;
  802. // $('#statOk').textContent = api.successful ?? 0;
  803. // $('#statKo').textContent = api.failed ?? 0;
  804. // $('#api-summary').style.display = 'block';
  805. // }
  806. function renderInlineForCards() {
  807. const api = API_RESPONSE_AI;
  808. document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  809. PRODUCT_BASE.forEach((p, idx) => {
  810. const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  811. if (!inline) return;
  812. if (!isProductSelected(p.item_id)) return;
  813. const res = findApiResultForProduct(p, idx, api);
  814. // Clear existing content
  815. inline.innerHTML = '';
  816. // 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS
  817. const mandatorySection = renderMandatoryComparisonCards(
  818. res?.mandatory || {},
  819. 'Mandatory Attributes Comparison'
  820. );
  821. inline.appendChild(mandatorySection);
  822. const mandCount = Object.keys(res?.mandatory || {}).length;
  823. const combinedTitle = el('div', 'section-title');
  824. combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  825. inline.appendChild(combinedTitle);
  826. const combinedAttributesContainer = el('div', 'combined-attributes-container');
  827. // 2. ADDITIONAL SECTION: RENDER AS SIMPLE TABLE
  828. const additionalSection = renderAttributesAsTable(
  829. res?.additional || {},
  830. 'Additional Attributes'
  831. );
  832. // inline.appendChild(additionalSection);
  833. const addCount = Object.keys(res?.additional || {}).length;
  834. // 3. OCR SECTION: RENDER AS SIMPLE TABLE
  835. const ocrSection = renderAttributesAsTable(
  836. res?.ocr_results?.extracted_attributes || {},
  837. 'OCR Results'
  838. );
  839. // inline.appendChild(ocrSection);
  840. const ocrCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
  841. // 4. VISUAL SECTION: RENDER AS SIMPLE TABLE
  842. const visualSection = renderAttributesAsTable(
  843. res?.visual_results?.visual_attributes || {},
  844. 'Visual Attributes'
  845. );
  846. // inline.appendChild(visualSection);
  847. const visualCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
  848. combinedAttributesContainer.appendChild(additionalSection);
  849. combinedAttributesContainer.appendChild(ocrSection);
  850. combinedAttributesContainer.appendChild(visualSection);
  851. inline.appendChild(combinedAttributesContainer);
  852. // --- Summary Counts (Pills) ---
  853. const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  854. const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  855. const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  856. const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
  857. const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  858. counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  859. inline.appendChild(counts);
  860. });
  861. // Update summary
  862. $('#statTotal').textContent = api.total_products ?? 0;
  863. $('#statOk').textContent = api.successful ?? 0;
  864. $('#statKo').textContent = api.failed ?? 0;
  865. $('#api-summary').style.display = 'block';
  866. }
  867. // function renderInlineForCards() {
  868. // const api = API_RESPONSE_AI;
  869. // // Clear all inline sections first
  870. // document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  871. // PRODUCT_BASE.forEach((p, idx) => {
  872. // const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  873. // if (!inline) return;
  874. // if (!isProductSelected(p.item_id)) return;
  875. // const res = findApiResultForProduct(p, idx, api);
  876. // const pid = p.item_id;
  877. // // Memory map (mem) is no longer needed since we removed chip rendering
  878. // // I'll keep the variable declarations for count consistency, but remove the memory map usage.
  879. // // --- 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS ---
  880. // const mandatorySection = renderMandatoryComparisonCards(
  881. // res?.mandatory || {},
  882. // 'Mandatory Attributes Comparison'
  883. // );
  884. // inline.appendChild(mandatorySection);
  885. // const mandCount = Object.keys(res?.mandatory || {}).length;
  886. // // --- 2. ADDITIONAL SECTION: RENDER AS SIMPLE CARDS ---
  887. // const additionalSection = renderAttributesAsTable(
  888. // res?.additional || {},
  889. // 'Additional Attributes'
  890. // );
  891. // inline.appendChild(additionalSection);
  892. // const addCount = Object.keys(res?.additional || {}).length;
  893. // // --- 3. OCR SECTION: RENDER AS SIMPLE CARDS ---
  894. // const ocrSection = renderAttributesAsTable(
  895. // res?.ocr_results?.extracted_attributes || {},
  896. // 'OCR Results'
  897. // );
  898. // inline.appendChild(ocrSection);
  899. // const ocrCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
  900. // // --- 4. VISUAL SECTION: RENDER AS SIMPLE CARDS ---
  901. // const visualSection = renderAttributesAsTable(
  902. // res?.visual_results?.visual_attributes || {},
  903. // 'Visual Results'
  904. // );
  905. // inline.appendChild(visualSection);
  906. // const visualCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
  907. // // --- Summary Counts (Pills) ---
  908. // const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  909. // const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  910. // const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  911. // const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
  912. // const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  913. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  914. // inline.appendChild(counts);
  915. // });
  916. // // Update summary
  917. // $('#statTotal').textContent = api.total_products ?? 0;
  918. // $('#statOk').textContent = api.successful ?? 0;
  919. // $('#statKo').textContent = api.failed ?? 0;
  920. // $('#api-summary').style.display = 'block';
  921. // }
  922. // ----------------------------------------------------------------
  923. // NOTE: You MUST include renderMandatoryComparisonCards (from previous response)
  924. // and the necessary CSS for both card styles!
  925. // ----------------------------------------------------------------
  926. // ------------------------------------------------------------------
  927. // --- 1. MANDATORY COMPARISON HELPER (Existing vs. AI, with Highlighting) ---
  928. // ------------------------------------------------------------------
  929. // function renderInlineForCards() {
  930. // const api = API_RESPONSE_AI;
  931. // // Clear all inline sections first
  932. // document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  933. // PRODUCT_BASE.forEach((p, idx) => {
  934. // const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  935. // if (!inline) return;
  936. // // --- CHANGE HERE: Use the new helper function ---
  937. // if (!isProductSelected(p.item_id)) return; // only show for selected
  938. // const res = findApiResultForProduct(p, idx, api);
  939. // const pid = p.item_id;
  940. // // Keep memory logic for old chip renderer, even though card renderer doesn't need it
  941. // if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
  942. // const mem = lastSeen.get(pid);
  943. // // ------------------------------------------------
  944. // // 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS
  945. // // ------------------------------------------------
  946. // const mandatorySection = renderMandatoryComparisonCards(
  947. // res?.mandatory || {},
  948. // 'Mandatory Attributes Comparison'
  949. // );
  950. // inline.appendChild(mandatorySection);
  951. // // Count the attributes for the summary pill
  952. // const mandCount = Object.keys(res?.mandatory || {}).length;
  953. // // ------------------------------------------------
  954. // // 2. ADDITIONAL/OCR/VISUALS: RENDER AS CHIPS (Original Logic)
  955. // // ------------------------------------------------
  956. // // ADDITIONAL
  957. // const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  958. // const addChips = el('div', 'chips');
  959. // const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  960. // inline.appendChild(addTitle); inline.appendChild(addChips);
  961. // // OCR
  962. // const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
  963. // const ocrChips = el('div', 'chips');
  964. // const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem?.ocr_results);
  965. // inline.appendChild(addOcr); inline.appendChild(ocrChips);
  966. // // VISUALS
  967. // const addVisual = el('div', 'section-title'); addVisual.innerHTML = '<strong>Visual</strong>';
  968. // const visualChips = el('div', 'chips');
  969. // const visualCount = renderChips(visualChips, res?.visual_results?.visual_attributes || {}, mem?.visual_results);
  970. // inline.appendChild(addVisual); inline.appendChild(visualChips);
  971. // // --- Summary Counts (Pills) ---
  972. // const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  973. // const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  974. // const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  975. // const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
  976. // const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  977. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  978. // inline.appendChild(counts);
  979. // });
  980. // // Update summary
  981. // $('#statTotal').textContent = api.total_products ?? 0;
  982. // $('#statOk').textContent = api.successful ?? 0;
  983. // $('#statKo').textContent = api.failed ?? 0;
  984. // $('#api-summary').style.display = 'block';
  985. // }
  986. /**
  987. * Renders a table for Mandatory attributes, comparing AI-extracted value ('value')
  988. * against the existing value ('original_value'). Includes a scroll wrapper.
  989. * @param {Object} attributes - The mandatory attribute data.
  990. * @param {string} title - The title for the table section.
  991. * @returns {HTMLElement} A div containing the comparison table.
  992. */
  993. // function renderMandatoryComparisonTable(attributes, title) {
  994. // const section = el('div', 'attribute-section');
  995. // let attributeEntries = [];
  996. // Object.keys(attributes).forEach(key => {
  997. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  998. // valuesArray.forEach(v => {
  999. // const aiValue = v.value || 'N/A';
  1000. // const originalValue = v.original_value || 'N/A';
  1001. // const source = v.source || 'N/A';
  1002. // // Comparison is case-insensitive and ignores leading/trailing whitespace
  1003. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  1004. // attributeEntries.push({
  1005. // name: key,
  1006. // aiValue: aiValue,
  1007. // originalValue: originalValue,
  1008. // source: source,
  1009. // isMatch: isMatch
  1010. // });
  1011. // });
  1012. // });
  1013. // const titleEl = el('div', 'section-title');
  1014. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1015. // section.appendChild(titleEl);
  1016. // if (attributeEntries.length === 0) {
  1017. // const msg = el('p', 'no-attributes-message');
  1018. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1019. // section.appendChild(msg);
  1020. // return section;
  1021. // }
  1022. // // --- SCROLL WRAPPER ADDITION ---
  1023. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1024. // const table = el('table', 'attribute-detail-table comparison-table');
  1025. // const thead = el('thead');
  1026. // const headerRow = el('tr');
  1027. // ['Attribute Name', 'Source', 'Manually Identified Value', 'AI Generated Value'].forEach(text => {
  1028. // const th = el('th');
  1029. // th.textContent = text;
  1030. // headerRow.appendChild(th);
  1031. // });
  1032. // thead.appendChild(headerRow);
  1033. // table.appendChild(thead);
  1034. // const tbody = el('tbody');
  1035. // attributeEntries.forEach(attr => {
  1036. // // Highlight the entire row in red if the values do not match
  1037. // const row = el('tr', attr.isMatch ? 'match' : 'mismatch-row');
  1038. // // 1. Attribute Name
  1039. // const nameTd = el('td', 'attribute-name');
  1040. // nameTd.textContent = attr.name.replace(/_/g, ' ');
  1041. // row.appendChild(nameTd);
  1042. // // 2. Source
  1043. // const sourceTd = el('td', 'attribute-source');
  1044. // sourceTd.textContent = formatString(attr.source);
  1045. // row.appendChild(sourceTd);
  1046. // // 3. Existing Value
  1047. // const originalTd = el('td', 'original-value');
  1048. // originalTd.textContent = formatString(attr.originalValue);
  1049. // row.appendChild(originalTd);
  1050. // // 4. AI Extracted Value (Highlight if mismatch)
  1051. // const aiTd = el('td', `ai-value ${attr.aiValue ? '' : 'mismatch-value'}`);
  1052. // aiTd.textContent = attr.aiValue;
  1053. // row.appendChild(aiTd);
  1054. // // 5. Match Status
  1055. // // const matchTd = el('td', 'match-status');
  1056. // // const matchPill = el('span', `pill status-pill status-${attr.isMatch ? 'match' : 'mismatch'}`);
  1057. // // matchPill.textContent = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  1058. // // matchTd.appendChild(matchPill);
  1059. // // row.appendChild(matchTd);
  1060. // tbody.appendChild(row);
  1061. // });
  1062. // table.appendChild(tbody);
  1063. // scrollWrapper.appendChild(table); // Append table to wrapper
  1064. // section.appendChild(scrollWrapper); // Append wrapper to section
  1065. // return section;
  1066. // }
  1067. // ------------------------------------------------------------------
  1068. // --- 2. GENERAL ATTRIBUTE HELPER (Name, Value, Source, with Scroll) ---
  1069. // ------------------------------------------------------------------
  1070. /**
  1071. * Renders a table for Mandatory attributes, comparing AI-extracted value ('value')
  1072. * against the existing value ('original_value'). Includes a scroll wrapper and mismatch highlighting.
  1073. * @param {Object} attributes - The mandatory attribute data.
  1074. * @param {string} title - The title for the table section.
  1075. * @returns {HTMLElement} A div containing the comparison table.
  1076. */
  1077. function renderMandatoryComparisonTable(attributes, title) {
  1078. const section = el('div', 'attribute-section');
  1079. let attributeEntries = [];
  1080. Object.keys(attributes).forEach(key => {
  1081. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1082. valuesArray.forEach(v => {
  1083. const aiValue = v.value || 'N/A';
  1084. const originalValue = v.original_value || 'N/A';
  1085. const source = v.source || 'N/A';
  1086. // Comparison is case-insensitive and ignores leading/trailing whitespace
  1087. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  1088. attributeEntries.push({
  1089. name: key,
  1090. aiValue: aiValue,
  1091. originalValue: originalValue,
  1092. source: source,
  1093. isMatch: isMatch
  1094. });
  1095. });
  1096. });
  1097. const titleEl = el('div', 'section-title');
  1098. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1099. section.appendChild(titleEl);
  1100. if (attributeEntries.length === 0) {
  1101. const msg = el('p', 'no-attributes-message');
  1102. msg.textContent = `No ${title.toLowerCase()} found.`;
  1103. section.appendChild(msg);
  1104. return section;
  1105. }
  1106. // --- SCROLL WRAPPER ADDITION ---
  1107. const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1108. const table = el('table', 'attribute-detail-table comparison-table');
  1109. const thead = el('thead');
  1110. const headerRow = el('tr');
  1111. // Updated Headers for Comparison Table
  1112. ['Attribute Name', 'Manually Identified Value', 'AI Generated Value', 'Source', 'Match'].forEach(text => {
  1113. const th = el('th');
  1114. th.textContent = text;
  1115. headerRow.appendChild(th);
  1116. });
  1117. thead.appendChild(headerRow);
  1118. table.appendChild(thead);
  1119. const tbody = el('tbody');
  1120. attributeEntries.forEach(attr => {
  1121. // Highlight the entire row in red if the values do not match
  1122. const row = el('tr', attr.isMatch ? 'match-row' : 'mismatch-row');
  1123. // 1. Attribute Name
  1124. const nameTd = el('td', 'attribute-name');
  1125. nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1126. row.appendChild(nameTd);
  1127. // 2. Existing Value (Manually added value)
  1128. const originalTd = el('td', 'original-value');
  1129. originalTd.textContent = formatString(attr.originalValue);
  1130. row.appendChild(originalTd);
  1131. // 3. AI Extracted Value
  1132. const aiTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1133. aiTd.textContent = attr.aiValue;
  1134. row.appendChild(aiTd);
  1135. // 4. Source
  1136. const sourceTd = el('td', 'attribute-source');
  1137. sourceTd.textContent = formatString(attr.source);
  1138. row.appendChild(sourceTd);
  1139. // 5. Match Status
  1140. const matchTd = el('td', 'match-status');
  1141. const matchPill = el('span', `pill status-pill status-${attr.isMatch ? 'match' : 'mismatch'}`);
  1142. matchPill.textContent = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  1143. matchTd.appendChild(matchPill);
  1144. row.appendChild(matchTd);
  1145. tbody.appendChild(row);
  1146. });
  1147. table.appendChild(tbody);
  1148. scrollWrapper.appendChild(table); // Append table to wrapper
  1149. section.appendChild(scrollWrapper); // Append wrapper to section
  1150. return section;
  1151. }
  1152. /**
  1153. * Renders a table for Additional, OCR, or Visual attributes (Name, Value, Source).
  1154. * @param {Object} attributes - The attribute data.
  1155. * @param {string} title - The title for the table section.
  1156. * @returns {HTMLElement} A div containing the table.
  1157. */
  1158. function renderAttributesAsTable(attributes, title, mandatoryData = null) {
  1159. const section = el('div', 'attribute-section');
  1160. let attributeEntries = [];
  1161. // --- STEP 1: Create a Set of all Mandatory Original Values (Normalized) ---
  1162. // A Set is used for fast lookups. Values are normalized (trimmed, lowercase)
  1163. const mandatoryOriginalValuesSet = new Set();
  1164. if (mandatoryData) {
  1165. Object.values(mandatoryData).forEach(attrArray => {
  1166. const originalValue = attrArray[0]?.original_value;
  1167. if (originalValue) {
  1168. mandatoryOriginalValuesSet.add(String(originalValue).trim().toLowerCase());
  1169. }
  1170. });
  1171. }
  1172. // Helper to extract attribute entries consistently
  1173. const processAttribute = (key, values) => {
  1174. const valuesArray = Array.isArray(values) ? values : [values];
  1175. valuesArray.forEach(v => {
  1176. attributeEntries.push({
  1177. name: key,
  1178. value: v.value,
  1179. source: v.source || 'N/A'
  1180. });
  1181. });
  1182. };
  1183. // Iterate through attributes (OCR/Visual/Additional) and flatten them
  1184. Object.keys(attributes).forEach(key => {
  1185. const attribute = attributes[key];
  1186. if (Array.isArray(attribute)) {
  1187. processAttribute(key, attribute);
  1188. } else if (typeof attribute === 'object' && attribute !== null) {
  1189. // Handle simple { "key": { "value": "X", "source": "Y" } } structure
  1190. if (attribute.value !== undefined) {
  1191. attributeEntries.push({
  1192. name: key,
  1193. value: attribute.value,
  1194. source: attribute.source || 'N/A'
  1195. });
  1196. } else {
  1197. // Handle nested objects
  1198. Object.keys(attribute).forEach(subKey => {
  1199. const subAttribute = attribute[subKey];
  1200. if (Array.isArray(subAttribute)) {
  1201. processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  1202. }
  1203. });
  1204. }
  1205. }
  1206. });
  1207. const titleEl = el('div', 'section-title');
  1208. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1209. section.appendChild(titleEl);
  1210. if (attributeEntries.length === 0) {
  1211. const msg = el('p', 'no-attributes-message');
  1212. msg.textContent = `No ${title.toLowerCase()} found.`;
  1213. section.appendChild(msg);
  1214. return section;
  1215. }
  1216. const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1217. const table = el('table', 'attribute-detail-table');
  1218. const thead = el('thead');
  1219. const headerRow = el('tr');
  1220. ['Attribute Name', 'Value'].forEach(text => {
  1221. const th = el('th');
  1222. th.textContent = text;
  1223. headerRow.appendChild(th);
  1224. });
  1225. thead.appendChild(headerRow);
  1226. table.appendChild(thead);
  1227. const tbody = el('tbody');
  1228. attributeEntries.forEach(attr => {
  1229. const row = el('tr');
  1230. // --- CORE COMPARISON LOGIC (Global Check) ---
  1231. let colorClass = '';
  1232. const hasMandatoryBaseline = mandatoryOriginalValuesSet.size > 0;
  1233. if (hasMandatoryBaseline) {
  1234. // Normalize the current attribute's value
  1235. const currentValueNormalized = String(attr.value).trim().toLowerCase();
  1236. // Check if the current value exists ANYWHERE in the mandatory original values set
  1237. if (mandatoryOriginalValuesSet.has(currentValueNormalized)) {
  1238. colorClass = 'green-text'; // Found a match in the global mandatory set
  1239. } else {
  1240. colorClass = 'red-text'; // Did NOT find a match
  1241. }
  1242. }
  1243. // --- END CORE COMPARISON LOGIC ---
  1244. const nameTd = el('td', 'attribute-name');
  1245. nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1246. row.appendChild(nameTd);
  1247. const valueTd = el('td', 'attribute-value');
  1248. const displayValue = formatString(attr.value) + ' (' + formatString(attr.source) + ')';
  1249. valueTd.textContent = displayValue || 'N/A';
  1250. // Apply the determined color class to the value cell
  1251. if (colorClass) {
  1252. valueTd.classList.add(colorClass);
  1253. }
  1254. row.appendChild(valueTd);
  1255. tbody.appendChild(row);
  1256. });
  1257. table.appendChild(tbody);
  1258. scrollWrapper.appendChild(table);
  1259. section.appendChild(scrollWrapper);
  1260. return section;
  1261. }
  1262. // function renderAttributesAsTable(attributes, title, mandatoryData = null) {
  1263. // const section = el('div', 'attribute-section');
  1264. // let attributeEntries = [];
  1265. // const processAttribute = (key, values) => {
  1266. // const valuesArray = Array.isArray(values) ? values : [values];
  1267. // valuesArray.forEach(v => {
  1268. // attributeEntries.push({
  1269. // name: key,
  1270. // value: v.value,
  1271. // source: v.source || 'N/A'
  1272. // });
  1273. // });
  1274. // };
  1275. // Object.keys(attributes).forEach(key => {
  1276. // const attribute = attributes[key];
  1277. // if (Array.isArray(attribute)) {
  1278. // processAttribute(key, attribute);
  1279. // } else if (typeof attribute === 'object' && attribute !== null) {
  1280. // Object.keys(attribute).forEach(subKey => {
  1281. // const subAttribute = attribute[subKey];
  1282. // if (Array.isArray(subAttribute)) {
  1283. // // Combines parent key (e.g., 'size') and sub-key (e.g., 'waist_size')
  1284. // processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  1285. // }
  1286. // });
  1287. // }
  1288. // });
  1289. // const titleEl = el('div', 'section-title');
  1290. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1291. // section.appendChild(titleEl);
  1292. // if (attributeEntries.length === 0) {
  1293. // const msg = el('p', 'no-attributes-message');
  1294. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1295. // section.appendChild(msg);
  1296. // return section;
  1297. // }
  1298. // // --- SCROLL WRAPPER ADDITION ---
  1299. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1300. // const table = el('table', 'attribute-detail-table');
  1301. // const thead = el('thead');
  1302. // const headerRow = el('tr');
  1303. // ['Attribute Name', 'Value'].forEach(text => {
  1304. // const th = el('th');
  1305. // th.textContent = text;
  1306. // headerRow.appendChild(th);
  1307. // });
  1308. // thead.appendChild(headerRow);
  1309. // table.appendChild(thead);
  1310. // const tbody = el('tbody');
  1311. // attributeEntries.forEach(attr => {
  1312. // const row = el('tr');
  1313. // const nameTd = el('td', 'attribute-name');
  1314. // nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1315. // row.appendChild(nameTd);
  1316. // const valueTd = el('td', 'attribute-value');
  1317. // const displayValue = Array.isArray(attr.value)
  1318. // ? (attr.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr.source)+ ')'
  1319. // : formatString(attr.value) +'('+ formatString(attr.source)+ ')';
  1320. // valueTd.textContent = displayValue || 'N/A';
  1321. // row.appendChild(valueTd);
  1322. // // const sourceTd = el('td', 'attribute-source');
  1323. // // sourceTd.textContent = attr.source || 'Unknown';
  1324. // // row.appendChild(sourceTd);
  1325. // tbody.appendChild(row);
  1326. // });
  1327. // table.appendChild(tbody);
  1328. // scrollWrapper.appendChild(table); // Append table to wrapper
  1329. // section.appendChild(scrollWrapper); // Append wrapper to section
  1330. // return section;
  1331. // }
  1332. // ------------------------------------------------------------------
  1333. // --- 3. MAIN RENDER FUNCTION (REPLACEMENT) ---
  1334. // ------------------------------------------------------------------
  1335. // function renderInlineForTable() {
  1336. // const api = API_RESPONSE_AI;
  1337. // const table = $('#tableContainer');
  1338. // if (!table) return;
  1339. // // Remove existing detail rows
  1340. // table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  1341. // PRODUCT_BASE.forEach((p, idx) => {
  1342. // if (!isProductSelected(p.item_id)) return;
  1343. // const res = findApiResultForProduct(p, idx, api);
  1344. // const tbody = table.querySelector('tbody');
  1345. // const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null;
  1346. // if (!baseRow) return;
  1347. // // --- Detail Row Construction ---
  1348. // const detail = el('tr', 'detail-row');
  1349. // // td.colSpan must match the number of columns in your main table
  1350. // const td = el('td'); td.colSpan = 7;
  1351. // const content = el('div', 'detail-content-tables');
  1352. // // // 1. MANDATORY Attributes Table (NOW USES CARD COMPARISON)
  1353. // // const mandatorySection = renderMandatoryComparisonCards( // <-- NEW FUNCTION NAME
  1354. // // res?.mandatory || {},
  1355. // // 'Mandatory Attributes Comparison'
  1356. // // );
  1357. // // content.appendChild(mandatorySection);
  1358. // // // 2. COMBINED Attributes Section (Additional, OCR, Visuals) - REMAINS THE SAME
  1359. // // content.appendChild(el('hr', 'section-separator'));
  1360. // // 1. MANDATORY Attributes Table (USES COMPARISON FUNCTION)
  1361. // const mandatoryTable = renderMandatoryComparisonTable(
  1362. // res?.mandatory || {},
  1363. // 'Mandatory Attributes Comparison'
  1364. // );
  1365. // content.appendChild(mandatoryTable);
  1366. // // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
  1367. // content.appendChild(el('hr', 'section-separator'));
  1368. // const combinedTitle = el('div', 'section-title');
  1369. // combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  1370. // content.appendChild(combinedTitle);
  1371. // const combinedAttributesContainer = el('div', 'combined-attributes-container');
  1372. // // Use the general renderer for these sections
  1373. // const additionalTable = renderAttributesAsTable(
  1374. // res?.additional || {},
  1375. // 'Additional Attributes'
  1376. // );
  1377. // const ocrTable = renderAttributesAsTable(
  1378. // res?.ocr_results?.extracted_attributes || {},
  1379. // 'OCR Results'
  1380. // );
  1381. // const visualsTable = renderAttributesAsTable(
  1382. // res?.visual_results?.visual_attributes || {},
  1383. // 'Visual Results'
  1384. // );
  1385. // // Append all sections to the combined container
  1386. // combinedAttributesContainer.appendChild(additionalTable);
  1387. // combinedAttributesContainer.appendChild(ocrTable);
  1388. // combinedAttributesContainer.appendChild(visualsTable);
  1389. // content.appendChild(combinedAttributesContainer);
  1390. // // --- Summary Counts ---
  1391. // const mandCount = Object.keys(res?.mandatory || {}).length;
  1392. // const addCount = Object.keys(res?.additional || {}).length;
  1393. // const ocrExtractedCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
  1394. // const visualExtractedCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
  1395. // const counts = el('div', 'attribute-summary-pills');
  1396. // const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
  1397. // const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
  1398. // const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
  1399. // const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
  1400. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1401. // content.appendChild(counts);
  1402. // // Final assembly and insertion
  1403. // td.appendChild(content);
  1404. // detail.appendChild(td);
  1405. // baseRow.insertAdjacentElement('afterend', detail);
  1406. // });
  1407. // // Update summary statistics
  1408. // $('#statTotal').textContent = api.total_products ?? 0;
  1409. // $('#statOk').textContent = api.successful ?? 0;
  1410. // $('#statKo').textContent = api.failed ?? 0;
  1411. // const apiSummary = $('#api-summary');
  1412. // if (apiSummary) apiSummary.style.display = 'block';
  1413. // }
  1414. function renderInlineForTable() {
  1415. const api = API_RESPONSE_AI;
  1416. const table = $('#tableContainer');
  1417. if (!table) return;
  1418. // Remove existing detail rows
  1419. table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  1420. PRODUCT_BASE.forEach((p, idx) => {
  1421. if (!isProductSelected(p.item_id)) return;
  1422. const res = findApiResultForProduct(p, idx, api);
  1423. const tbody = table.querySelector('tbody');
  1424. const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null;
  1425. if (!baseRow) return;
  1426. // --- Detail Row Construction ---
  1427. const detail = el('tr', 'detail-row');
  1428. // td.colSpan must match the number of columns in your main table
  1429. const td = el('td'); td.colSpan = 6;
  1430. const content = el('div', 'detail-content-tables');
  1431. // 1. MANDATORY Attributes Table
  1432. // 🚨 Note: The color check (Requirement #2) must be implemented inside renderMandatoryComparisonTable.
  1433. const mandatoryData = res?.mandatory || {};
  1434. if (Object.keys(mandatoryData).length > 0) {
  1435. const mandatoryTable = renderMandatoryComparisonTable(
  1436. mandatoryData,
  1437. 'Mandatory Attributes Comparison'
  1438. );
  1439. content.appendChild(mandatoryTable);
  1440. }
  1441. // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
  1442. const additionalData = res?.additional || {};
  1443. const ocrData = res?.ocr_results?.extracted_attributes || {};
  1444. const visualsData = res?.visual_results?.visual_attributes || {};
  1445. const hasCombinedData = Object.keys(additionalData).length > 0 ||
  1446. Object.keys(ocrData).length > 0 ||
  1447. Object.keys(visualsData).length > 0;
  1448. if (hasCombinedData) {
  1449. content.appendChild(el('hr', 'section-separator'));
  1450. const combinedTitle = el('div', 'section-title');
  1451. combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  1452. content.appendChild(combinedTitle);
  1453. const combinedAttributesContainer = el('div', 'combined-attributes-container');
  1454. // Render Additional Table (Conditional based on data existence)
  1455. if (Object.keys(additionalData).length > 0) {
  1456. const additionalTable = renderAttributesAsTable(
  1457. additionalData,
  1458. 'Additional Attributes',
  1459. mandatoryData
  1460. );
  1461. combinedAttributesContainer.appendChild(additionalTable);
  1462. }
  1463. // Render OCR Table (Conditional based on data existence)
  1464. if (Object.keys(ocrData).length > 0) {
  1465. const ocrTable = renderAttributesAsTable(
  1466. ocrData,
  1467. 'OCR Results',
  1468. mandatoryData
  1469. );
  1470. combinedAttributesContainer.appendChild(ocrTable);
  1471. }
  1472. // Render Visuals Table (Conditional based on data existence)
  1473. if (Object.keys(visualsData).length > 0) {
  1474. const visualsTable = renderAttributesAsTable(
  1475. visualsData,
  1476. 'Visual Results',
  1477. mandatoryData
  1478. );
  1479. combinedAttributesContainer.appendChild(visualsTable);
  1480. }
  1481. content.appendChild(combinedAttributesContainer);
  1482. }
  1483. // --- Summary Counts ---
  1484. const mandCount = Object.keys(mandatoryData).length;
  1485. const addCount = Object.keys(additionalData).length;
  1486. const ocrExtractedCount = Object.keys(ocrData).length;
  1487. const visualExtractedCount = Object.keys(visualsData).length;
  1488. const counts = el('div', 'attribute-summary-pills');
  1489. const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
  1490. const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
  1491. const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
  1492. const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
  1493. counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1494. content.appendChild(counts);
  1495. // Final assembly and insertion
  1496. td.appendChild(content);
  1497. detail.appendChild(td);
  1498. baseRow.insertAdjacentElement('afterend', detail);
  1499. });
  1500. // Update summary statistics
  1501. $('#statTotal').textContent = api.total_products ?? 0;
  1502. $('#statOk').textContent = api.successful ?? 0;
  1503. $('#statKo').textContent = api.failed ?? 0;
  1504. const apiSummary = $('#api-summary');
  1505. if (apiSummary) apiSummary.style.display = 'block';
  1506. }
  1507. function renderInlineAttributes() {
  1508. if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
  1509. // renderInlineForCards();
  1510. // renderInlineForTable();
  1511. }
  1512. // --- Main rendering ---
  1513. function renderProducts() {
  1514. if (layoutMode === 'cards') {
  1515. $('#cardsContainer').style.display = '';
  1516. $('#tableContainer').style.display = 'none';
  1517. // console.log("PRODUCT_BASE",PRODUCT_BASE);
  1518. renderProductsCards();
  1519. } else {
  1520. $('#cardsContainer').style.display = 'none';
  1521. $('#tableContainer').style.display = '';
  1522. renderProductsTable();
  1523. }
  1524. updateSelectionInfo();
  1525. renderPagination();
  1526. // If there is a selection, re-render inline attributes (persist across toggle)
  1527. if (selectedProductsWithAttributes.length > 0) renderInlineAttributes();
  1528. }
  1529. // --- Submit & Reset ---
  1530. function submitAttributes() {
  1531. // Check the length of the new array
  1532. if (selectedProductsWithAttributes.length === 0) {
  1533. alert('Please select at least one product.');
  1534. return;
  1535. }
  1536. // if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
  1537. // console.log("selectedIds",selectedIds);
  1538. jQuery('#full-page-loader').show();
  1539. // let inputArray = {
  1540. // "product_ids" : [...selectedIds]
  1541. // }
  1542. const extractAdditional = document.getElementById('extract_additional').checked;
  1543. const processImage = document.getElementById('process_image').checked;
  1544. // const selectedMultiples = document.getElementById('#mandatory-attributes');
  1545. // const selectedValues = Array.from(selectedMultiples.selectedOptions).map(option => option.value);
  1546. const selectElement = document.getElementById('mandatory-attributes');
  1547. const selectedValues = Array.from(selectElement.selectedOptions).map(option => option.value);
  1548. // console.log(selectedValues); // Logs an array of selected values
  1549. // console.log("thresholdValueDisplay",thresholdValueDisplay.value);
  1550. const threshold = parseFloat(document.getElementById('thresholdRange').value);
  1551. // Transform the new state array into the required API format
  1552. const itemIds = selectedProductsWithAttributes.map(p => p.item_id);
  1553. // Create the mandatory_attrs map: { item_id: { attr_name: [values] } }
  1554. // NOTE: The backend API you showed expects a flattened list of "mandatory_attrs"
  1555. // like: { "color": ["color", "shade"], "size": ["size", "fit"] }
  1556. // It seems to ignore the selected product-specific values and uses a general list of synonyms.
  1557. // Assuming the request needs a general map of *all unique* selected attributes across all selected products:
  1558. let mandatoryAttrsMap = {};
  1559. selectedProductsWithAttributes.forEach(product => {
  1560. // Merge attributes from all selected products
  1561. Object.assign(mandatoryAttrsMap, product.mandatory_attrs);
  1562. });
  1563. // If the API expects the complex, product-specific payload from your Q1 example:
  1564. const payloadForQ1 = selectedProductsWithAttributes.map(p => ({
  1565. item_id: p.item_id,
  1566. mandatory_attrs: p.mandatory_attrs
  1567. }));
  1568. let inputArray = {
  1569. "products": payloadForQ1,
  1570. "model": "llama-3.1-8b-instant",
  1571. "extract_additional": extractAdditional,
  1572. "process_image": processImage,
  1573. "multiple": selectedValues,
  1574. "threshold_abs": 0.6, // Lower threshold to be more permissive
  1575. // "margin": 0.3, // Larger margin to include more candidates
  1576. // "use_adaptive_margin": true,
  1577. // "use_semantic_clustering": true
  1578. }
  1579. let raw = JSON.stringify(inputArray);
  1580. fetch('/attr/batch-extract/', {
  1581. method: 'POST', // or 'POST' if your API expects POST
  1582. headers: {
  1583. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
  1584. 'Content-Type': "application/json"
  1585. },
  1586. body: raw
  1587. })
  1588. .then(response => response.json())
  1589. .then(data => {
  1590. // console.log("response data",data);
  1591. API_RESPONSE_AI = data;
  1592. renderInlineAttributes();
  1593. jQuery('#full-page-loader').hide();
  1594. });
  1595. }
  1596. function resetAll() {
  1597. selectedProductsWithAttributes = []; // Reset the main array
  1598. // selectedIds.clear();
  1599. lastSeen.clear();
  1600. renderProducts();
  1601. // Clear summary
  1602. document.getElementById('statTotal').textContent = '0';
  1603. document.getElementById('statOk').textContent = '0';
  1604. document.getElementById('statKo').textContent = '0';
  1605. $('#api-summary').style.display = 'none';
  1606. // ✅ Clear Select2 selections
  1607. jQuery('#mandatory-attributes').val(null).trigger('change');
  1608. // ✅ Reset threshold input (and display)
  1609. const thresholdInput = document.getElementById('thresholdRange');
  1610. const thresholdDisplay = document.getElementById('thresholdValue');
  1611. thresholdInput.value = '0.65'; // or any default value you prefer
  1612. if (thresholdDisplay) {
  1613. thresholdDisplay.textContent = '0.65';
  1614. }
  1615. }
  1616. function setLayout(mode) {
  1617. layoutMode = mode;
  1618. const btnCards = document.getElementById('btnCards');
  1619. const btnTable = document.getElementById('btnTable');
  1620. if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
  1621. else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
  1622. renderProducts();
  1623. }
  1624. // Upload elements (Bootstrap modal version)
  1625. const uploadModalEl = document.getElementById('uploadModal');
  1626. const dropzone = document.getElementById('dropzone');
  1627. const uploadFiles = document.getElementById('uploadFiles');
  1628. const fileInfo = document.getElementById('fileInfo');
  1629. const uploadBar = document.getElementById('uploadBar');
  1630. const uploadStatus = document.getElementById('uploadStatus');
  1631. // Reset modal on show
  1632. uploadModalEl.addEventListener('shown.bs.modal', () => {
  1633. uploadStatus.textContent = '';
  1634. uploadStatus.className = ''; // clear success/error class
  1635. uploadBar.style.width = '0%';
  1636. uploadBar.setAttribute('aria-valuenow', '0');
  1637. uploadFiles.value = '';
  1638. uploadFiles.setAttribute('accept', ACCEPT_TYPES);
  1639. fileInfo.textContent = 'No files selected.';
  1640. });
  1641. function describeFiles(list) {
  1642. if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
  1643. const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
  1644. fileInfo.textContent = names.join(', ');
  1645. }
  1646. // Drag & drop feedback
  1647. ['dragenter','dragover'].forEach(evt => {
  1648. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
  1649. });
  1650. ['dragleave','drop'].forEach(evt => {
  1651. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
  1652. });
  1653. // Handle drop
  1654. dropzone.addEventListener('drop', e => {
  1655. uploadFiles.files = e.dataTransfer.files;
  1656. describeFiles(uploadFiles.files);
  1657. });
  1658. // Click to browse
  1659. // dropzone.addEventListener('click', () => uploadFiles.click());
  1660. // Picker change
  1661. uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
  1662. function startUpload() {
  1663. const files = uploadFiles.files;
  1664. if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
  1665. jQuery('#full-page-loader').show();
  1666. uploadStatus.textContent = 'Uploading...';
  1667. uploadStatus.className = ''; // neutral
  1668. uploadBar.style.width = '0%';
  1669. uploadBar.setAttribute('aria-valuenow', '0');
  1670. const form = new FormData();
  1671. Array.from(files).forEach(f => form.append('file', f));
  1672. // form.append('uploaded_by', 'Vishal'); // example extra field
  1673. const xhr = new XMLHttpRequest();
  1674. xhr.open('POST', UPLOAD_API_URL, true);
  1675. // If you need auth:
  1676. // xhr.setRequestHeader('Authorization', 'Bearer <token>');
  1677. xhr.upload.onprogress = (e) => {
  1678. if (e.lengthComputable) {
  1679. const pct = Math.round((e.loaded / e.total) * 100);
  1680. uploadBar.style.width = pct + '%';
  1681. uploadBar.setAttribute('aria-valuenow', String(pct));
  1682. }
  1683. };
  1684. xhr.onreadystatechange = () => {
  1685. if (xhr.readyState === 4) {
  1686. const ok = (xhr.status >= 200 && xhr.status < 300);
  1687. try {
  1688. const resp = JSON.parse(xhr.responseText || '{}');
  1689. uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
  1690. } catch {
  1691. uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
  1692. }
  1693. uploadStatus.className = ok ? 'success' : 'error';
  1694. // Optional: auto-close the modal on success after 1.2s:
  1695. // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
  1696. }
  1697. };
  1698. xhr.onerror = () => {
  1699. uploadStatus.textContent = 'Network error during upload.';
  1700. uploadStatus.className = 'error';
  1701. };
  1702. xhr.send(form);
  1703. setTimeout(()=>{
  1704. jQuery('#uploadModal').modal('hide');
  1705. window.location.reload();
  1706. },3000)
  1707. jQuery('#full-page-loader').hide();
  1708. }
  1709. // Wire Start button
  1710. document.getElementById('uploadStart').addEventListener('click', startUpload);
  1711. // Cancel button already closes the modal via data-bs-dismiss
  1712. // --- Pagination state ---
  1713. let page = 1;
  1714. let pageSize = 50; // default rows per page
  1715. function totalPages() {
  1716. return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
  1717. }
  1718. function clampPage() {
  1719. page = Math.min(Math.max(1, page), totalPages());
  1720. }
  1721. function getCurrentSlice() {
  1722. clampPage();
  1723. const start = (page - 1) * pageSize;
  1724. return PRODUCT_BASE.slice(start, start + pageSize);
  1725. }
  1726. function renderPagination() {
  1727. const bar = document.getElementById('paginationBar');
  1728. if (!bar) return;
  1729. const tp = totalPages();
  1730. clampPage();
  1731. bar.innerHTML = `
  1732. <div class="page-size">
  1733. <label for="pageSizeSelect">Rows per page</label>
  1734. <select id="pageSizeSelect">
  1735. <option value="5" ${pageSize===5 ? 'selected' : ''}>5</option>
  1736. <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
  1737. <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
  1738. <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
  1739. <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
  1740. </select>
  1741. </div>
  1742. <div class="pager">
  1743. <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
  1744. <span class="page-info">Page ${page} of ${tp}</span>
  1745. <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
  1746. </div>
  1747. `;
  1748. // wire events
  1749. document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
  1750. document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
  1751. const sel = document.getElementById('pageSizeSelect');
  1752. if (sel) {
  1753. sel.addEventListener('change', () => {
  1754. const val = sel.value;
  1755. pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
  1756. page = 1; // reset to first page when size changes
  1757. renderProducts();
  1758. });
  1759. }
  1760. }
  1761. // Function to add/remove product from the state and manage its attributes
  1762. function toggleProductSelection(itemId, isChecked, attributes = {}) {
  1763. const index = selectedProductsWithAttributes.findIndex(p => p.item_id === itemId);
  1764. // console.log("index",index);
  1765. if (isChecked) {
  1766. // If selecting, ensure the product object exists in the array
  1767. if (index === -1) {
  1768. selectedProductsWithAttributes.push({
  1769. item_id: itemId,
  1770. mandatory_attrs: attributes
  1771. });
  1772. } else {
  1773. // Update attributes if the product is already selected
  1774. selectedProductsWithAttributes[index].mandatory_attrs = attributes;
  1775. }
  1776. } else {
  1777. // If deselecting, remove the product object from the array
  1778. if (index !== -1) {
  1779. selectedProductsWithAttributes.splice(index, 1);
  1780. }
  1781. }
  1782. updateSelectionInfo();
  1783. }
  1784. // Function to get the current mandatory attributes for a selected item
  1785. function getSelectedAttributes(itemId) {
  1786. const productEntry = selectedProductsWithAttributes.find(p => p.item_id === itemId);
  1787. return productEntry ? productEntry.mandatory_attrs : {};
  1788. }
  1789. // Helper to check if a product is selected
  1790. function isProductSelected(itemId) {
  1791. return selectedProductsWithAttributes.some(p => p.item_id === itemId);
  1792. }
  1793. // Helper to check if a specific attribute/value is selected
  1794. function isAttributeValueSelected(itemId, attrName, value) {
  1795. const attrs = getSelectedAttributes(itemId);
  1796. const values = attrs[attrName];
  1797. return values ? values.includes(value) : false; // Default all selected when first loaded
  1798. }
  1799. // $('.attribute-select').select2({
  1800. // placeholder: 'Select product attributes'
  1801. // });
  1802. function getAtributeList(){
  1803. jQuery('#full-page-loader').show();
  1804. try{
  1805. fetch('/attr/products/attributes', {
  1806. method: 'GET', // or 'POST' if your API expects POST
  1807. headers: {
  1808. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
  1809. }
  1810. })
  1811. .then(response => response.json())
  1812. .then(data => {
  1813. // console.log("data",data);
  1814. let attributesData = data;
  1815. // Step 1: Extract unique mandatory attribute names
  1816. const mandatoryAttributes = [...new Set(
  1817. attributesData
  1818. .filter(attr => attr.is_mandatory === "Yes")
  1819. .map(attr => attr.attribute_name)
  1820. )];
  1821. // Step 2: Populate the select element
  1822. const $select = jQuery('#mandatory-attributes');
  1823. $select.append(new Option("Select All", "select_all")); // Add "Select All" option first
  1824. mandatoryAttributes.forEach(attr => {
  1825. $select.append(new Option(attr, attr));
  1826. });
  1827. // Step 3: Initialize Select2 with placeholder
  1828. // $select.select2({
  1829. // placeholder: "Select mandatory attributes",
  1830. // allowClear: true
  1831. // });
  1832. // Step 4: Handle 'Select All' logic
  1833. $select.on('select2:select', function (e) {
  1834. if (e.params.data.id === "select_all") {
  1835. // Select all real options except "Select All"
  1836. const allOptions = mandatoryAttributes;
  1837. $select.val(allOptions).trigger('change');
  1838. }
  1839. });
  1840. jQuery('#full-page-loader').hide();
  1841. });
  1842. }catch(err){
  1843. console.log("err",err);
  1844. jQuery('#full-page-loader').hide();
  1845. }
  1846. }
  1847. document.addEventListener("DOMContentLoaded", function () {
  1848. // Update span when range changes
  1849. thresholdInput.addEventListener('input', function () {
  1850. // console.log("this.value",this.value);
  1851. thresholdValueDisplay.textContent = this.value;
  1852. });
  1853. });
  1854. // Get threshold value when needed
  1855. function getThreshold() {
  1856. // console.log("parseFloat(thresholdInput.value)",parseFloat(thresholdInput.value));
  1857. return parseFloat(thresholdInput.value);
  1858. }
  1859. /**
  1860. * Renders Mandatory attributes using a card-based comparison layout.
  1861. * Highlights mismatches prominently.
  1862. * @param {Object} attributes - The mandatory attribute data.
  1863. * @param {string} title - The title for the section.
  1864. * @returns {HTMLElement} A div containing the comparison cards.
  1865. */
  1866. function renderMandatoryComparisonCards(attributes, title) {
  1867. const section = el('div', 'attribute-section');
  1868. // --- 1. Flatten Mandatory Attributes ---
  1869. let attributeEntries = [];
  1870. Object.keys(attributes).forEach(key => {
  1871. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1872. valuesArray.forEach(v => {
  1873. const aiValue = v.value || 'N/A';
  1874. const originalValue = v.original_value || 'N/A';
  1875. // Comparison is case-insensitive and ignores leading/trailing whitespace
  1876. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  1877. attributeEntries.push({
  1878. name: key,
  1879. aiValue: aiValue,
  1880. originalValue: originalValue,
  1881. isMatch: isMatch,
  1882. source: v.source || 'N/A'
  1883. });
  1884. });
  1885. });
  1886. // --- 2. Section Header ---
  1887. const titleEl = el('div', 'section-title');
  1888. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1889. section.appendChild(titleEl);
  1890. if (attributeEntries.length === 0) {
  1891. const msg = el('p', 'no-attributes-message');
  1892. msg.textContent = `No ${title.toLowerCase()} found.`;
  1893. section.appendChild(msg);
  1894. return section;
  1895. }
  1896. // --- 3. Card Container ---
  1897. const cardsContainer = el('div', 'comparison-cards-container');
  1898. attributeEntries.forEach(attr => {
  1899. // Main Card Element
  1900. const card = el('div', `comparison-card ${attr.isMatch ? 'match' : 'mismatch-card'}`);
  1901. // Card Header (Attribute Name)
  1902. const header = el('div', 'card-header');
  1903. header.textContent = attr.name.replace(/_/g, ' ');
  1904. card.appendChild(header);
  1905. // Content Wrapper
  1906. const content = el('div', 'card-content');
  1907. // Existing Value Box
  1908. const originalBox = el('div', 'value-box original-box');
  1909. originalBox.innerHTML = `
  1910. <div class="value-label">Manually Identified Value</div>
  1911. <div class="value-text">${attr.originalValue}</div>
  1912. `;
  1913. content.appendChild(originalBox);
  1914. // AI Value Box
  1915. const aiBox = el('div', `value-box ai-box ${attr.isMatch ? 'found-value' : 'mismatch-value'}`);
  1916. aiBox.innerHTML = `
  1917. <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  1918. <div class="value-text">${attr.aiValue}</div>
  1919. `;
  1920. content.appendChild(aiBox);
  1921. card.appendChild(content);
  1922. // Mismatch Indicator (only visible on mismatch-card via CSS)
  1923. if (!attr.isMatch) {
  1924. const indicator = el('div', 'mismatch-indicator');
  1925. // indicator.innerHTML = '❌ MISMATCH';
  1926. indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  1927. card.appendChild(indicator);
  1928. }
  1929. cardsContainer.appendChild(card);
  1930. });
  1931. section.appendChild(cardsContainer);
  1932. return section;
  1933. }
  1934. // Example JavaScript (Assuming you have access to API_RESPONSE_AI)
  1935. // document.getElementById('downloadResultBtn').addEventListener('click', () => {
  1936. // // 1. Convert the data to a JSON string
  1937. // const jsonString = JSON.stringify(API_RESPONSE_AI, null, 2);
  1938. // // 2. Create a Blob from the JSON string
  1939. // const blob = new Blob([jsonString], { type: 'application/json' });
  1940. // // 3. Create a temporary URL and link element
  1941. // const url = URL.createObjectURL(blob);
  1942. // const a = document.createElement('a');
  1943. // // 4. Set download attributes
  1944. // a.href = url;
  1945. // a.download = 'api_generated_results.json';
  1946. // // 5. Simulate a click to trigger download
  1947. // document.body.appendChild(a);
  1948. // a.click();
  1949. // // 6. Clean up
  1950. // document.body.removeChild(a);
  1951. // URL.revokeObjectURL(url);
  1952. // });
  1953. /**
  1954. * Renders Mandatory attributes using a card-based comparison layout.
  1955. * Highlights mismatches prominently.
  1956. * @param {Object} attributes - The mandatory attribute data.
  1957. * @param {string} title - The title for the section (used for the header).
  1958. * @returns {HTMLElement} A div containing the comparison cards.
  1959. */
  1960. // function renderMandatoryComparisonCards(attributes, title) {
  1961. // const section = el('div', 'attribute-section mandatory-comparison-section');
  1962. // // --- 1. Flatten Mandatory Attributes ---
  1963. // let attributeEntries = [];
  1964. // Object.keys(attributes).forEach(key => {
  1965. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1966. // valuesArray.forEach(v => {
  1967. // const aiValue = v.value || 'N/A';
  1968. // const originalValue = v.original_value || 'N/A';
  1969. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  1970. // attributeEntries.push({
  1971. // name: key,
  1972. // aiValue: aiValue,
  1973. // originalValue: originalValue,
  1974. // isMatch: isMatch,
  1975. // source: v.source || 'N/A'
  1976. // });
  1977. // });
  1978. // });
  1979. // // --- 2. Section Header ---
  1980. // const titleEl = el('div', 'section-title');
  1981. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1982. // section.appendChild(titleEl);
  1983. // if (attributeEntries.length === 0) {
  1984. // const msg = el('p', 'no-attributes-message');
  1985. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1986. // section.appendChild(msg);
  1987. // return section;
  1988. // }
  1989. // // --- 3. Card Container ---
  1990. // const cardsContainer = el('div', 'comparison-cards-container');
  1991. // attributeEntries.forEach(attr => {
  1992. // const card = el('div', `comparison-card ${attr.isMatch ? 'match' : 'mismatch-card'}`);
  1993. // const header = el('div', 'card-header');
  1994. // header.textContent = attr.name.replace(/_/g, ' ');
  1995. // card.appendChild(header);
  1996. // const content = el('div', 'card-content');
  1997. // // Existing Value Box
  1998. // const originalBox = el('div', 'value-box original-box');
  1999. // originalBox.innerHTML = `
  2000. // <div class="value-label">Manually Identified Value</div>
  2001. // <div class="value-text">${attr.originalValue}</div>
  2002. // `;
  2003. // content.appendChild(originalBox);
  2004. // // AI Value Box
  2005. // const aiBox = el('div', `value-box ai-box ${attr.isMatch ? 'found-value' : 'mismatch-value'}`);
  2006. // aiBox.innerHTML = `
  2007. // <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  2008. // <div class="value-text">${attr.aiValue}</div>
  2009. // `;
  2010. // content.appendChild(aiBox);
  2011. // card.appendChild(content);
  2012. // // Mismatch Indicator
  2013. // if (!attr.isMatch) {
  2014. // const indicator = el('div', 'mismatch-indicator');
  2015. // // indicator.innerHTML = '❌ MISMATCH';
  2016. // indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2017. // card.appendChild(indicator);
  2018. // }
  2019. // cardsContainer.appendChild(card);
  2020. // });
  2021. // section.appendChild(cardsContainer);
  2022. // return section;
  2023. // }
  2024. function renderMandatoryComparisonCards(attributes, title) {
  2025. const section = el('div', 'attribute-section mandatory-comparison-section');
  2026. // --- 1. Flatten Mandatory Attributes ---
  2027. let attributeEntries = [];
  2028. Object.keys(attributes).forEach(key => {
  2029. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2030. valuesArray.forEach(v => {
  2031. const aiValue = v.value || 'N/A';
  2032. const originalValue = v.original_value || 'N/A';
  2033. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2034. attributeEntries.push({
  2035. name: key,
  2036. aiValue: aiValue,
  2037. originalValue: originalValue,
  2038. isMatch: isMatch,
  2039. source: v.source || 'N/A'
  2040. });
  2041. });
  2042. });
  2043. // --- 2. Section Header ---
  2044. const titleEl = el('div', 'section-title');
  2045. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2046. section.appendChild(titleEl);
  2047. if (attributeEntries.length === 0) {
  2048. const msg = el('p', 'no-attributes-message');
  2049. msg.textContent = `No ${title.toLowerCase()} found.`;
  2050. section.appendChild(msg);
  2051. return section;
  2052. }
  2053. // --- 3. Card Container ---
  2054. const cardsContainer = el('div', 'comparison-cards-container');
  2055. attributeEntries.forEach(attr => {
  2056. // --- CHANGE 1: Apply 'match-card' or 'mismatch-card' explicitly ---
  2057. const cardClass = attr.isMatch ? 'match-card' : 'mismatch-card';
  2058. const card = el('div', `comparison-card ${cardClass}`);
  2059. const header = el('div', 'card-header');
  2060. header.textContent = attr.name.replace(/_/g, ' ');
  2061. card.appendChild(header);
  2062. const content = el('div', 'card-content');
  2063. // Existing Value Box
  2064. const originalBox = el('div', 'value-box original-box');
  2065. originalBox.innerHTML = `
  2066. <div class="value-label">Manually Identified Value</div>
  2067. <div class="value-text">${attr.originalValue}</div>
  2068. `;
  2069. content.appendChild(originalBox);
  2070. // AI Value Box
  2071. // Removed 'found-value' class here as styling should rely on the parent card class
  2072. const aiBox = el('div', `value-box ai-box ${attr.isMatch ? '' : 'mismatch-value'}`);
  2073. aiBox.innerHTML = `
  2074. <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  2075. <div class="value-text">${attr.aiValue}</div>
  2076. `;
  2077. content.appendChild(aiBox);
  2078. card.appendChild(content);
  2079. // --- CHANGE 2: Display the indicator for ALL cards, controlling color via CSS ---
  2080. const indicator = el('div', 'match-status-indicator');
  2081. indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2082. card.appendChild(indicator);
  2083. cardsContainer.appendChild(card);
  2084. });
  2085. section.appendChild(cardsContainer);
  2086. return section;
  2087. }
  2088. /**
  2089. * Renders Additional, OCR, or Visual attributes in a simple card layout.
  2090. * @param {Object} attributes - The attribute data (Additional, OCR, or Visual).
  2091. * @param {string} title - The title for the section.
  2092. * @returns {HTMLElement} A div containing the attribute cards.
  2093. */
  2094. function renderSimpleAttributeCards(attributes, title) {
  2095. const section = el('div', 'attribute-section simple-attribute-section');
  2096. // --- 1. Flatten Attributes ---
  2097. let attributeEntries = [];
  2098. const processAttribute = (key, values) => {
  2099. const valuesArray = Array.isArray(values) ? values : [values];
  2100. valuesArray.forEach(v => {
  2101. attributeEntries.push({
  2102. name: key,
  2103. value: v.value,
  2104. source: v.source || 'N/A'
  2105. });
  2106. });
  2107. };
  2108. Object.keys(attributes).forEach(key => {
  2109. const attribute = attributes[key];
  2110. if (Array.isArray(attribute)) {
  2111. processAttribute(key, attribute);
  2112. } else if (typeof attribute === 'object' && attribute !== null) {
  2113. Object.keys(attribute).forEach(subKey => {
  2114. const subAttribute = attribute[subKey];
  2115. if (Array.isArray(subAttribute)) {
  2116. processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  2117. }
  2118. });
  2119. }
  2120. });
  2121. // --- 2. Section Header ---
  2122. const titleEl = el('div', 'section-title');
  2123. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2124. section.appendChild(titleEl);
  2125. if (attributeEntries.length === 0) {
  2126. const msg = el('p', 'no-attributes-message');
  2127. msg.textContent = `No ${title.toLowerCase()} found.`;
  2128. section.appendChild(msg);
  2129. return section;
  2130. }
  2131. // --- 3. Card Container ---
  2132. const cardsContainer = el('div', 'comparison-cards-container simple-cards-container');
  2133. attributeEntries.forEach(attr => {
  2134. // Simple Card Element
  2135. const card = el('div', 'simple-card');
  2136. // Card Header (Attribute Name)
  2137. const header = el('div', 'card-header');
  2138. header.textContent = formatString(attr.name).replace(/_/g, ' ');
  2139. card.appendChild(header);
  2140. // Content Wrapper
  2141. const content = el('div', 'card-content');
  2142. // Value Box
  2143. const valueBox = el('div', 'value-box single-value-box');
  2144. const displayValue = Array.isArray(attr.value)
  2145. ? (attr.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr.source)+ ')'
  2146. : formatString(attr.value) +'('+ formatString(attr.source)+ ')';
  2147. // : attr.value;
  2148. valueBox.innerHTML = `
  2149. <div class="value-label">Extracted Value <span class="value-source">(${formatString(attr.source)})</span></div>
  2150. <div class="value-text">${displayValue || 'N/A'}</div>
  2151. `;
  2152. content.appendChild(valueBox);
  2153. card.appendChild(content);
  2154. cardsContainer.appendChild(card);
  2155. });
  2156. section.appendChild(cardsContainer);
  2157. return section;
  2158. }