attr-extraction.js 120 KB

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