attr-extraction.js 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077
  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 renderProductsTable(items = getCurrentSlice()) {
  709. const wrap = document.getElementById('tableContainer');
  710. wrap.innerHTML = '';
  711. const table = document.createElement('table');
  712. table.classList.add('table', 'table-striped', 'table-bordered', 'table-responsive');
  713. table.id = 'productsTable'; // ✅ Add a unique table ID
  714. const thead = document.createElement('thead');
  715. const trh = document.createElement('tr');
  716. // --- "Select All" Header with Checkbox ---
  717. const thSelect = document.createElement('th');
  718. const selectAllCheckbox = document.createElement('input');
  719. selectAllCheckbox.type = 'checkbox';
  720. selectAllCheckbox.id = 'selectAllCheckbox';
  721. thSelect.appendChild(selectAllCheckbox);
  722. trh.appendChild(thSelect);
  723. // Other headers
  724. ['Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
  725. const th = document.createElement('th');
  726. th.textContent = h;
  727. trh.appendChild(th);
  728. });
  729. thead.appendChild(trh);
  730. table.appendChild(thead);
  731. const tbody = document.createElement('tbody');
  732. if (items.length > 0) {
  733. items.forEach(p => {
  734. const tr = document.createElement('tr');
  735. tr.id = `row-${p.id}`;
  736. if (isProductSelected(p.item_id)) tr.classList.add('selected');
  737. // Checkbox for each row
  738. const cb = document.createElement('input');
  739. cb.type = 'checkbox';
  740. cb.classList.add('checkbox-productlist'); // ✅ correct way to add class
  741. cb.checked = isProductSelected(p.item_id);
  742. const updateProductState = getProductStateUpdater(p, cb, tr);
  743. const tdSel = document.createElement('td');
  744. tdSel.className = 'select-cell';
  745. tdSel.appendChild(cb);
  746. tr.appendChild(tdSel);
  747. const tdImg = document.createElement('td');
  748. tdImg.className = 'thumb-cell';
  749. tdImg.appendChild(createMiniThumb(p));
  750. tr.appendChild(tdImg);
  751. const tdName = document.createElement('td');
  752. tdName.textContent = p.product_name || '—';
  753. tr.appendChild(tdName);
  754. const tdSku = document.createElement('td');
  755. tdSku.textContent = p.item_id || '—';
  756. tr.appendChild(tdSku);
  757. const tdType = document.createElement('td');
  758. const b = document.createElement('span');
  759. b.className = 'badge';
  760. b.textContent = p.product_type || '—';
  761. tdType.appendChild(b);
  762. tr.appendChild(tdType);
  763. const tdDesc = document.createElement('td');
  764. tdDesc.innerHTML = p.product_short_description || '';
  765. tr.appendChild(tdDesc);
  766. // Handle attribute rows (kept your same logic)
  767. const detailRow = document.createElement('tr');
  768. detailRow.classList.add('attribute-detail-row');
  769. detailRow.style.display = 'none';
  770. detailRow.id = `detail-row-${p.id}`;
  771. const detailCell = document.createElement('td');
  772. detailCell.colSpan = 6;
  773. const attrContainer = document.createElement('div');
  774. attrContainer.id = `attr-container-${p.item_id}`;
  775. attrContainer.classList.add('attribute-selectors', 'table-selectors');
  776. generateAttributeUI(p, updateProductState, attrContainer);
  777. attrContainer.classList.toggle('disabled', !cb.checked);
  778. detailCell.appendChild(attrContainer);
  779. detailRow.appendChild(detailCell);
  780. // Checkbox behavior
  781. cb.addEventListener('change', () => {
  782. updateProductState();
  783. attrContainer.classList.toggle('disabled', !cb.checked);
  784. });
  785. tr.addEventListener('click', (e) => {
  786. const tag = e.target.tagName.toLowerCase();
  787. if (tag !== 'input' && tag !== 'button') {
  788. cb.checked = !cb.checked;
  789. cb.dispatchEvent(new Event('change'));
  790. }
  791. });
  792. tbody.appendChild(tr);
  793. tbody.appendChild(detailRow);
  794. });
  795. } else {
  796. const tr = document.createElement('tr');
  797. const td = document.createElement('td');
  798. td.colSpan = 6;
  799. td.textContent = 'No Products Found.';
  800. tr.appendChild(td);
  801. tbody.appendChild(tr);
  802. }
  803. table.appendChild(tbody);
  804. wrap.appendChild(table);
  805. // --- Select All Checkbox Logic ---
  806. selectAllCheckbox.addEventListener('change', () => {
  807. // ✅ Only get product checkboxes inside *this* table
  808. const allCheckboxes = table.querySelectorAll('tbody .checkbox-productlist');
  809. console.log("allCheckboxes", allCheckboxes);
  810. allCheckboxes.forEach(cb => {
  811. cb.checked = selectAllCheckbox.checked;
  812. cb.dispatchEvent(new Event('change'));
  813. });
  814. });
  815. // --- Keep "Select All" synced with individual selections ---
  816. tbody.addEventListener('change', (e) => {
  817. if (e.target && e.target.classList.contains('checkbox-productlist')) {
  818. // ✅ Again, limit scope to *this* table
  819. const allCheckboxes = table.querySelectorAll('tbody .checkbox-productlist');
  820. const allChecked = Array.from(allCheckboxes).every(cb => cb.checked);
  821. const someChecked = Array.from(allCheckboxes).some(cb => cb.checked);
  822. selectAllCheckbox.checked = allChecked;
  823. selectAllCheckbox.indeterminate = !allChecked && someChecked;
  824. }
  825. });
  826. }
  827. // function renderInlineForCards() {
  828. // const api = API_RESPONSE_AI;
  829. // // Clear all inline sections first
  830. // document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  831. // PRODUCT_BASE.forEach((p, idx) => {
  832. // const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  833. // if (!inline) return;
  834. // // --- CHANGE HERE: Use the new helper function ---
  835. // if (!isProductSelected(p.item_id)) return; // only show for selected
  836. // const res = findApiResultForProduct(p, idx, api);
  837. // const pid = p.item_id;
  838. // if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
  839. // const mem = lastSeen.get(pid);
  840. // // Build sections
  841. // const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  842. // const manChips = el('div', 'chips');
  843. // const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  844. // const addChips = el('div', 'chips');
  845. // const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
  846. // const ocrChips = el('div', 'chips');
  847. // const addVisual = el('div', 'section-title'); addVisual.innerHTML = '<strong>Visual</strong>';
  848. // const visualChips = el('div', 'chips');
  849. // const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  850. // const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  851. // const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem?.ocr_results);
  852. // const visualCount = renderChips(visualChips, res?.visual_results?.visual_attributes || {}, mem?.visual_results);
  853. // const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  854. // const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  855. // const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  856. // const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
  857. // const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  858. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  859. // inline.appendChild(manTitle); inline.appendChild(manChips);
  860. // inline.appendChild(addTitle); inline.appendChild(addChips);
  861. // inline.appendChild(addOcr); inline.appendChild(ocrChips);
  862. // inline.appendChild(addVisual); inline.appendChild(visualChips);
  863. // inline.appendChild(counts);
  864. // });
  865. // // Update summary
  866. // $('#statTotal').textContent = api.total_products ?? 0;
  867. // $('#statOk').textContent = api.successful ?? 0;
  868. // $('#statKo').textContent = api.failed ?? 0;
  869. // $('#api-summary').style.display = 'block';
  870. // }
  871. // -----------------------------------------------------------
  872. // function renderInlineForTable() {
  873. // const api = API_RESPONSE_AI;
  874. // const table = $('#tableContainer');
  875. // if (!table) return;
  876. // // Remove existing detail rows
  877. // table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  878. // PRODUCT_BASE.forEach((p, idx) => {
  879. // // --- CHANGE HERE: Use the new helper function ---
  880. // if (!isProductSelected(p.item_id)) return;
  881. // const res = findApiResultForProduct(p, idx, api);
  882. // const pid = p.item_id;
  883. // if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
  884. // const mem = lastSeen.get(pid);
  885. // const tbody = table.querySelector('tbody');
  886. // // NOTE: The table rendering uses p.id for the row ID: `row-${p.id}`.
  887. // // Assuming p.id is still valid for finding the base row, as your original code used it.
  888. // const baseRow = tbody.querySelector(`#row-${p.id}`);
  889. // if (!baseRow) return;
  890. // const detail = el('tr', 'detail-row');
  891. // const td = el('td'); td.colSpan = 6; // number of columns
  892. // const content = el('div', 'detail-content');
  893. // const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  894. // const manChips = el('div', 'chips');
  895. // const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  896. // const addChips = el('div', 'chips');
  897. // const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
  898. // const ocrChips = el('div', 'chips');
  899. // const addVisuals = el('div', 'section-title'); addVisuals.innerHTML = '<strong>Visuals</strong>';
  900. // const visualsChips = el('div', 'chips');
  901. // const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  902. // const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  903. // const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem.ocr_results);
  904. // const visualCount = renderChips(visualsChips, res?.visual_results?.visual_attributes || {}, mem.visual_results);
  905. // const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  906. // const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  907. // const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  908. // const c3 = el('span', 'pill'); c3.textContent = `Ocr: ${ocrCount}`;
  909. // const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  910. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  911. // content.appendChild(manTitle); content.appendChild(manChips);
  912. // content.appendChild(addTitle); content.appendChild(addChips);
  913. // content.appendChild(addOcr); content.appendChild(ocrChips);
  914. // content.appendChild(addVisuals); content.appendChild(visualsChips);
  915. // content.appendChild(counts);
  916. // td.appendChild(content); detail.appendChild(td);
  917. // // insert after base row
  918. // baseRow.insertAdjacentElement('afterend', detail);
  919. // });
  920. // // Update summary
  921. // $('#statTotal').textContent = api.total_products ?? 0;
  922. // $('#statOk').textContent = api.successful ?? 0;
  923. // $('#statKo').textContent = api.failed ?? 0;
  924. // $('#api-summary').style.display = 'block';
  925. // }
  926. function renderInlineForCards() {
  927. const api = API_RESPONSE_AI;
  928. document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  929. PRODUCT_BASE.forEach((p, idx) => {
  930. const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  931. if (!inline) return;
  932. if (!isProductSelected(p.item_id)) return;
  933. const res = findApiResultForProduct(p, idx, api);
  934. // Clear existing content
  935. inline.innerHTML = '';
  936. // 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS
  937. const mandatorySection = renderMandatoryComparisonCards(
  938. res?.mandatory || {},
  939. 'Mandatory Attributes Comparison'
  940. );
  941. inline.appendChild(mandatorySection);
  942. const mandCount = Object.keys(res?.mandatory || {}).length;
  943. const combinedTitle = el('div', 'section-title');
  944. combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  945. inline.appendChild(combinedTitle);
  946. const combinedAttributesContainer = el('div', 'combined-attributes-container');
  947. // 2. ADDITIONAL SECTION: RENDER AS SIMPLE TABLE
  948. const additionalSection = renderAttributesAsTable(
  949. res?.additional || {},
  950. 'Additional Attributes'
  951. );
  952. // inline.appendChild(additionalSection);
  953. const addCount = Object.keys(res?.additional || {}).length;
  954. // 3. OCR SECTION: RENDER AS SIMPLE TABLE
  955. const ocrSection = renderAttributesAsTable(
  956. res?.ocr_results?.extracted_attributes || {},
  957. 'OCR Results'
  958. );
  959. // inline.appendChild(ocrSection);
  960. const ocrCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
  961. // 4. VISUAL SECTION: RENDER AS SIMPLE TABLE
  962. const visualSection = renderAttributesAsTable(
  963. res?.visual_results?.visual_attributes || {},
  964. 'Visual Attributes'
  965. );
  966. // inline.appendChild(visualSection);
  967. const visualCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
  968. combinedAttributesContainer.appendChild(additionalSection);
  969. combinedAttributesContainer.appendChild(ocrSection);
  970. combinedAttributesContainer.appendChild(visualSection);
  971. inline.appendChild(combinedAttributesContainer);
  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. // function renderInlineForCards() {
  988. // const api = API_RESPONSE_AI;
  989. // // Clear all inline sections first
  990. // document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  991. // PRODUCT_BASE.forEach((p, idx) => {
  992. // const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  993. // if (!inline) return;
  994. // if (!isProductSelected(p.item_id)) return;
  995. // const res = findApiResultForProduct(p, idx, api);
  996. // const pid = p.item_id;
  997. // // Memory map (mem) is no longer needed since we removed chip rendering
  998. // // I'll keep the variable declarations for count consistency, but remove the memory map usage.
  999. // // --- 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS ---
  1000. // const mandatorySection = renderMandatoryComparisonCards(
  1001. // res?.mandatory || {},
  1002. // 'Mandatory Attributes Comparison'
  1003. // );
  1004. // inline.appendChild(mandatorySection);
  1005. // const mandCount = Object.keys(res?.mandatory || {}).length;
  1006. // // --- 2. ADDITIONAL SECTION: RENDER AS SIMPLE CARDS ---
  1007. // const additionalSection = renderAttributesAsTable(
  1008. // res?.additional || {},
  1009. // 'Additional Attributes'
  1010. // );
  1011. // inline.appendChild(additionalSection);
  1012. // const addCount = Object.keys(res?.additional || {}).length;
  1013. // // --- 3. OCR SECTION: RENDER AS SIMPLE CARDS ---
  1014. // const ocrSection = renderAttributesAsTable(
  1015. // res?.ocr_results?.extracted_attributes || {},
  1016. // 'OCR Results'
  1017. // );
  1018. // inline.appendChild(ocrSection);
  1019. // const ocrCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
  1020. // // --- 4. VISUAL SECTION: RENDER AS SIMPLE CARDS ---
  1021. // const visualSection = renderAttributesAsTable(
  1022. // res?.visual_results?.visual_attributes || {},
  1023. // 'Visual Results'
  1024. // );
  1025. // inline.appendChild(visualSection);
  1026. // const visualCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
  1027. // // --- Summary Counts (Pills) ---
  1028. // const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  1029. // const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  1030. // const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  1031. // const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
  1032. // const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  1033. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1034. // inline.appendChild(counts);
  1035. // });
  1036. // // Update summary
  1037. // $('#statTotal').textContent = api.total_products ?? 0;
  1038. // $('#statOk').textContent = api.successful ?? 0;
  1039. // $('#statKo').textContent = api.failed ?? 0;
  1040. // $('#api-summary').style.display = 'block';
  1041. // }
  1042. // ----------------------------------------------------------------
  1043. // NOTE: You MUST include renderMandatoryComparisonCards (from previous response)
  1044. // and the necessary CSS for both card styles!
  1045. // ----------------------------------------------------------------
  1046. // ------------------------------------------------------------------
  1047. // --- 1. MANDATORY COMPARISON HELPER (Existing vs. AI, with Highlighting) ---
  1048. // ------------------------------------------------------------------
  1049. // function renderInlineForCards() {
  1050. // const api = API_RESPONSE_AI;
  1051. // // Clear all inline sections first
  1052. // document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  1053. // PRODUCT_BASE.forEach((p, idx) => {
  1054. // const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  1055. // if (!inline) return;
  1056. // // --- CHANGE HERE: Use the new helper function ---
  1057. // if (!isProductSelected(p.item_id)) return; // only show for selected
  1058. // const res = findApiResultForProduct(p, idx, api);
  1059. // const pid = p.item_id;
  1060. // // Keep memory logic for old chip renderer, even though card renderer doesn't need it
  1061. // if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map(), ocr_results: new Map(), visual_results: new Map() });
  1062. // const mem = lastSeen.get(pid);
  1063. // // ------------------------------------------------
  1064. // // 1. MANDATORY SECTION: RENDER AS COMPARISON CARDS
  1065. // // ------------------------------------------------
  1066. // const mandatorySection = renderMandatoryComparisonCards(
  1067. // res?.mandatory || {},
  1068. // 'Mandatory Attributes Comparison'
  1069. // );
  1070. // inline.appendChild(mandatorySection);
  1071. // // Count the attributes for the summary pill
  1072. // const mandCount = Object.keys(res?.mandatory || {}).length;
  1073. // // ------------------------------------------------
  1074. // // 2. ADDITIONAL/OCR/VISUALS: RENDER AS CHIPS (Original Logic)
  1075. // // ------------------------------------------------
  1076. // // ADDITIONAL
  1077. // const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  1078. // const addChips = el('div', 'chips');
  1079. // const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  1080. // inline.appendChild(addTitle); inline.appendChild(addChips);
  1081. // // OCR
  1082. // const addOcr = el('div', 'section-title'); addOcr.innerHTML = '<strong>Ocr</strong>';
  1083. // const ocrChips = el('div', 'chips');
  1084. // const ocrCount = renderChips(ocrChips, res?.ocr_results?.extracted_attributes || {}, mem?.ocr_results);
  1085. // inline.appendChild(addOcr); inline.appendChild(ocrChips);
  1086. // // VISUALS
  1087. // const addVisual = el('div', 'section-title'); addVisual.innerHTML = '<strong>Visual</strong>';
  1088. // const visualChips = el('div', 'chips');
  1089. // const visualCount = renderChips(visualChips, res?.visual_results?.visual_attributes || {}, mem?.visual_results);
  1090. // inline.appendChild(addVisual); inline.appendChild(visualChips);
  1091. // // --- Summary Counts (Pills) ---
  1092. // const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  1093. // const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  1094. // const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  1095. // const c3 = el('span', 'pill'); c3.textContent = `OCR: ${ocrCount}`;
  1096. // const c4 = el('span', 'pill'); c4.textContent = `Visuals: ${visualCount}`;
  1097. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1098. // inline.appendChild(counts);
  1099. // });
  1100. // // Update summary
  1101. // $('#statTotal').textContent = api.total_products ?? 0;
  1102. // $('#statOk').textContent = api.successful ?? 0;
  1103. // $('#statKo').textContent = api.failed ?? 0;
  1104. // $('#api-summary').style.display = 'block';
  1105. // }
  1106. /**
  1107. * Renders a table for Mandatory attributes, comparing AI-extracted value ('value')
  1108. * against the existing value ('original_value'). Includes a scroll wrapper.
  1109. * @param {Object} attributes - The mandatory attribute data.
  1110. * @param {string} title - The title for the table section.
  1111. * @returns {HTMLElement} A div containing the comparison table.
  1112. */
  1113. // function renderMandatoryComparisonTable(attributes, title) {
  1114. // const section = el('div', 'attribute-section');
  1115. // let attributeEntries = [];
  1116. // Object.keys(attributes).forEach(key => {
  1117. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1118. // valuesArray.forEach(v => {
  1119. // const aiValue = v.value || 'N/A';
  1120. // const originalValue = v.original_value || 'N/A';
  1121. // const source = v.source || 'N/A';
  1122. // // Comparison is case-insensitive and ignores leading/trailing whitespace
  1123. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  1124. // attributeEntries.push({
  1125. // name: key,
  1126. // aiValue: aiValue,
  1127. // originalValue: originalValue,
  1128. // source: source,
  1129. // isMatch: isMatch
  1130. // });
  1131. // });
  1132. // });
  1133. // const titleEl = el('div', 'section-title');
  1134. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1135. // section.appendChild(titleEl);
  1136. // if (attributeEntries.length === 0) {
  1137. // const msg = el('p', 'no-attributes-message');
  1138. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1139. // section.appendChild(msg);
  1140. // return section;
  1141. // }
  1142. // // --- SCROLL WRAPPER ADDITION ---
  1143. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1144. // const table = el('table', 'attribute-detail-table comparison-table');
  1145. // const thead = el('thead');
  1146. // const headerRow = el('tr');
  1147. // ['Attribute Name', 'Source', 'Manually Identified Value', 'AI Generated Value'].forEach(text => {
  1148. // const th = el('th');
  1149. // th.textContent = text;
  1150. // headerRow.appendChild(th);
  1151. // });
  1152. // thead.appendChild(headerRow);
  1153. // table.appendChild(thead);
  1154. // const tbody = el('tbody');
  1155. // attributeEntries.forEach(attr => {
  1156. // // Highlight the entire row in red if the values do not match
  1157. // const row = el('tr', attr.isMatch ? 'match' : 'mismatch-row');
  1158. // // 1. Attribute Name
  1159. // const nameTd = el('td', 'attribute-name');
  1160. // nameTd.textContent = attr.name.replace(/_/g, ' ');
  1161. // row.appendChild(nameTd);
  1162. // // 2. Source
  1163. // const sourceTd = el('td', 'attribute-source');
  1164. // sourceTd.textContent = formatString(attr.source);
  1165. // row.appendChild(sourceTd);
  1166. // // 3. Existing Value
  1167. // const originalTd = el('td', 'original-value');
  1168. // originalTd.textContent = formatString(attr.originalValue);
  1169. // row.appendChild(originalTd);
  1170. // // 4. AI Extracted Value (Highlight if mismatch)
  1171. // const aiTd = el('td', `ai-value ${attr.aiValue ? '' : 'mismatch-value'}`);
  1172. // aiTd.textContent = attr.aiValue;
  1173. // row.appendChild(aiTd);
  1174. // // 5. Match Status
  1175. // // const matchTd = el('td', 'match-status');
  1176. // // const matchPill = el('span', `pill status-pill status-${attr.isMatch ? 'match' : 'mismatch'}`);
  1177. // // matchPill.textContent = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  1178. // // matchTd.appendChild(matchPill);
  1179. // // row.appendChild(matchTd);
  1180. // tbody.appendChild(row);
  1181. // });
  1182. // table.appendChild(tbody);
  1183. // scrollWrapper.appendChild(table); // Append table to wrapper
  1184. // section.appendChild(scrollWrapper); // Append wrapper to section
  1185. // return section;
  1186. // }
  1187. // ------------------------------------------------------------------
  1188. // --- 2. GENERAL ATTRIBUTE HELPER (Name, Value, Source, with Scroll) ---
  1189. // ------------------------------------------------------------------
  1190. /**
  1191. * Renders a table for Mandatory attributes, comparing AI-extracted value ('value')
  1192. * against the existing value ('original_value'). Includes a scroll wrapper and mismatch highlighting.
  1193. * @param {Object} attributes - The mandatory attribute data.
  1194. * @param {string} title - The title for the table section.
  1195. * @returns {HTMLElement} A div containing the comparison table.
  1196. */
  1197. function renderMandatoryComparisonTable(attributes, title, productType) {
  1198. const section = el('div', 'attribute-section');
  1199. let attributeEntries = [];
  1200. // --- Build attributeEntries ---
  1201. Object.keys(attributes).forEach(key => {
  1202. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1203. valuesArray.forEach(v => {
  1204. const aiValue = v.value || 'N/A';
  1205. const originalValue = v.original_value || 'N/A';
  1206. const source = v.source || 'N/A';
  1207. const reason = v.reason || 'N/A';
  1208. // Find possible values for this attribute from full data
  1209. const attrConfig = attributesFullData.find(item => item.attribute_name === key);
  1210. let possibleValues = [];
  1211. if (attrConfig && attrConfig.possible_values) {
  1212. possibleValues = attrConfig.possible_values.split(',').map(s => s.trim());
  1213. }
  1214. // Determine match flag
  1215. const isFoundInPossible = possibleValues.includes(aiValue);
  1216. const matchFlag = isFoundInPossible ? true : false;
  1217. attributeEntries.push({
  1218. name: key,
  1219. aiValue: aiValue,
  1220. possibleValues: possibleValues,
  1221. originalValue: originalValue,
  1222. source: source,
  1223. isMatch: matchFlag,
  1224. reason: reason
  1225. });
  1226. });
  1227. });
  1228. // --- Section title ---
  1229. const titleEl = el('div', 'section-title');
  1230. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1231. section.appendChild(titleEl);
  1232. if (attributeEntries.length === 0) {
  1233. const msg = el('p', 'no-attributes-message');
  1234. msg.textContent = `No ${title.toLowerCase()} found.`;
  1235. section.appendChild(msg);
  1236. return section;
  1237. }
  1238. // --- Split attributes in half ---
  1239. const midIndex = Math.ceil(attributeEntries.length / 2);
  1240. const leftAttributes = attributeEntries.slice(0, midIndex);
  1241. const rightAttributes = attributeEntries.slice(midIndex);
  1242. // --- Create a container for two tables ---
  1243. const tableContainer = el('div', 'two-column-table-container');
  1244. // Helper function to build a table
  1245. function buildTable(attrArray) {
  1246. const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1247. const table = el('table', 'attribute-detail-table comparison-table');
  1248. const thead = el('thead');
  1249. const headerRow = el('tr');
  1250. ['Attribute Name', 'AI Generated Value', 'Action'].forEach(text => {
  1251. const th = el('th');
  1252. th.textContent = text;
  1253. headerRow.appendChild(th);
  1254. });
  1255. thead.appendChild(headerRow);
  1256. table.appendChild(thead);
  1257. const tbody = el('tbody');
  1258. attrArray.forEach(attr => {
  1259. const row = el('tr', attr.isMatch ? 'match-row' : 'mismatch-row');
  1260. // Attribute name
  1261. const nameTd = el('td', 'attribute-name');
  1262. nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1263. row.appendChild(nameTd);
  1264. // AI Value display
  1265. // AI Value cell with info icon
  1266. const aiValueTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1267. // Create a wrapper for text and icon
  1268. const aiValueWrapper = document.createElement('div');
  1269. aiValueWrapper.style.display = 'flex';
  1270. aiValueWrapper.style.alignItems = 'center';
  1271. aiValueWrapper.style.gap = '6px';
  1272. // Text node
  1273. const valueText = document.createElement('span');
  1274. valueText.textContent = formatString(attr.aiValue);
  1275. aiValueWrapper.appendChild(valueText);
  1276. // Info icon (Bootstrap Icons)
  1277. if (attr.reason && attr.reason.trim() !== '') {
  1278. const infoIcon = document.createElement('i');
  1279. infoIcon.className = 'bi bi-info-circle';
  1280. infoIcon.style.cursor = 'pointer';
  1281. infoIcon.setAttribute('title', attr.reason); // Tooltip on hover
  1282. infoIcon.style.color = '#0d6efd'; // Bootstrap blue
  1283. aiValueWrapper.appendChild(infoIcon);
  1284. }
  1285. aiValueTd.appendChild(aiValueWrapper);
  1286. row.appendChild(aiValueTd);
  1287. // const aiValueTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1288. // aiValueTd.textContent = formatString(attr.aiValue);
  1289. // row.appendChild(aiValueTd);
  1290. // Dropdown
  1291. // const aiTd = el('td', 'attribute-source');
  1292. // const select = document.createElement('select');
  1293. // select.classList.add('select2-dropdown');
  1294. // select.setAttribute('data-attribute', attr.name);
  1295. const aiTd = el('td', 'attribute-source');
  1296. // Create a multi-select dropdown
  1297. const select = document.createElement('select');
  1298. select.classList.add('select2-dropdown');
  1299. // select.id = 'manually-attributes'; // You may want to make this unique per row
  1300. select.name = 'manuallyUpdatedAttributes[]';
  1301. // select.setAttribute('aria-labelledby', 'select a attribute for which multiple data required');
  1302. select.setAttribute('multiple', 'multiple');
  1303. // select.style.width = '100%';
  1304. select.setAttribute('data-attribute', attr.name);
  1305. // Populate options
  1306. attr.possibleValues.forEach(val => {
  1307. const option = document.createElement('option');
  1308. option.value = val;
  1309. option.textContent = val;
  1310. if (val === attr.aiValue) option.selected = true;
  1311. select.appendChild(option);
  1312. });
  1313. if (!attr.isMatch && attr.aiValue !== 'N/A') {
  1314. const newOpt = document.createElement('option');
  1315. newOpt.value = attr.aiValue;
  1316. newOpt.textContent = attr.aiValue; // + " (new)";
  1317. newOpt.selected = true;
  1318. select.appendChild(newOpt);
  1319. }
  1320. aiTd.appendChild(select);
  1321. row.appendChild(aiTd);
  1322. tbody.appendChild(row);
  1323. // Initialize Select2
  1324. jQuery(select).select2({
  1325. tags: true,
  1326. width: 'resolve'
  1327. });
  1328. });
  1329. table.appendChild(tbody);
  1330. scrollWrapper.appendChild(table);
  1331. return scrollWrapper;
  1332. }
  1333. // --- Build and append both tables ---
  1334. const leftTable = buildTable(leftAttributes);
  1335. const rightTable = buildTable(rightAttributes);
  1336. tableContainer.appendChild(leftTable);
  1337. tableContainer.appendChild(rightTable);
  1338. section.appendChild(tableContainer);
  1339. return section;
  1340. }
  1341. // function renderMandatoryComparisonTable(attributes, title, productType) {
  1342. // const section = el('div', 'attribute-section');
  1343. // let attributeEntries = [];
  1344. // Object.keys(attributes).forEach(key => {
  1345. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1346. // valuesArray.forEach(v => {
  1347. // const aiValue = v.value || 'N/A';
  1348. // const originalValue = v.original_value || 'N/A';
  1349. // const source = v.source || 'N/A';
  1350. // // Find possible values for this attribute from `a`
  1351. // const attrConfig = attributesFullData.find(item =>
  1352. // item.attribute_name === key
  1353. // );
  1354. // let possibleValues = [];
  1355. // if (attrConfig && attrConfig.possible_values) {
  1356. // possibleValues = attrConfig.possible_values.split(',').map(s => s.trim());
  1357. // }
  1358. // // Determine if AI value exists in possible values
  1359. // const isFoundInPossible = possibleValues.includes(aiValue);
  1360. // const matchFlag = isFoundInPossible ? true : false;
  1361. // attributeEntries.push({
  1362. // name: key,
  1363. // aiValue: aiValue,
  1364. // possibleValues: possibleValues,
  1365. // originalValue: originalValue,
  1366. // source: source,
  1367. // isMatch: matchFlag
  1368. // });
  1369. // });
  1370. // });
  1371. // const titleEl = el('div', 'section-title');
  1372. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1373. // section.appendChild(titleEl);
  1374. // if (attributeEntries.length === 0) {
  1375. // const msg = el('p', 'no-attributes-message');
  1376. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1377. // section.appendChild(msg);
  1378. // return section;
  1379. // }
  1380. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1381. // const table = el('table', 'attribute-detail-table comparison-table');
  1382. // const thead = el('thead');
  1383. // const headerRow = el('tr');
  1384. // ['Attribute Name', 'AI Generated Value', 'Action'].forEach(text => {
  1385. // const th = el('th');
  1386. // th.textContent = text;
  1387. // headerRow.appendChild(th);
  1388. // });
  1389. // thead.appendChild(headerRow);
  1390. // table.appendChild(thead);
  1391. // const tbody = el('tbody');
  1392. // attributeEntries.forEach(attr => {
  1393. // const row = el('tr', attr.isMatch ? 'match-row' : 'mismatch-row');
  1394. // // 1. Attribute Name
  1395. // const nameTd = el('td', 'attribute-name');
  1396. // nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1397. // row.appendChild(nameTd);
  1398. // // 3. Source Column
  1399. // const sourceTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1400. // sourceTd.textContent = formatString(attr.aiValue);
  1401. // row.appendChild(sourceTd);
  1402. // // 2. AI Value Dropdown (Select2)
  1403. // const aiTd = el('td', 'attribute-source');
  1404. // const select = document.createElement('select');
  1405. // select.classList.add('select2-dropdown');
  1406. // select.setAttribute('data-attribute', attr.name);
  1407. // // Populate possible values
  1408. // attr.possibleValues.forEach(val => {
  1409. // const option = document.createElement('option');
  1410. // option.value = val;
  1411. // option.textContent = val;
  1412. // if (val === attr.aiValue) option.selected = true;
  1413. // select.appendChild(option);
  1414. // });
  1415. // // If not found in possible values, add it as a new option
  1416. // if (!attr.isMatch && attr.aiValue !== 'N/A') {
  1417. // const newOpt = document.createElement('option');
  1418. // newOpt.value = attr.aiValue;
  1419. // newOpt.textContent = attr.aiValue + " (new)";
  1420. // newOpt.selected = true;
  1421. // select.appendChild(newOpt);
  1422. // }
  1423. // aiTd.appendChild(select);
  1424. // row.appendChild(aiTd);
  1425. // tbody.appendChild(row);
  1426. // // Initialize Select2 after element is added
  1427. // jQuery(select).select2({
  1428. // tags: true, // allows new values
  1429. // width: 'resolve'
  1430. // });
  1431. // });
  1432. // table.appendChild(tbody);
  1433. // scrollWrapper.appendChild(table);
  1434. // section.appendChild(scrollWrapper);
  1435. // return section;
  1436. // }
  1437. // function renderMandatoryComparisonTable(attributes, title) {
  1438. // const section = el('div', 'attribute-section');
  1439. // let attributeEntries = [];
  1440. // Object.keys(attributes).forEach(key => {
  1441. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1442. // valuesArray.forEach(v => {
  1443. // const aiValue = v.value || 'N/A';
  1444. // const originalValue = v.original_value || 'N/A';
  1445. // const source = v.source || 'N/A';
  1446. // // Comparison is case-insensitive and ignores leading/trailing whitespace
  1447. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  1448. // attributeEntries.push({
  1449. // name: key,
  1450. // aiValue: aiValue,
  1451. // originalValue: originalValue,
  1452. // source: source,
  1453. // isMatch: isMatch
  1454. // });
  1455. // });
  1456. // });
  1457. // const titleEl = el('div', 'section-title');
  1458. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1459. // section.appendChild(titleEl);
  1460. // if (attributeEntries.length === 0) {
  1461. // const msg = el('p', 'no-attributes-message');
  1462. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1463. // section.appendChild(msg);
  1464. // return section;
  1465. // }
  1466. // // --- SCROLL WRAPPER ADDITION ---
  1467. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1468. // const table = el('table', 'attribute-detail-table comparison-table');
  1469. // const thead = el('thead');
  1470. // const headerRow = el('tr');
  1471. // // Updated Headers for Comparison Table
  1472. // ['Attribute Name', 'AI Generated Value', 'Action'].forEach(text => {
  1473. // const th = el('th');
  1474. // th.textContent = text;
  1475. // headerRow.appendChild(th);
  1476. // });
  1477. // thead.appendChild(headerRow);
  1478. // table.appendChild(thead);
  1479. // const tbody = el('tbody');
  1480. // attributeEntries.forEach(attr => {
  1481. // // Highlight the entire row in red if the values do not match
  1482. // const row = el('tr', attr.isMatch ? 'match-row' : 'mismatch-row');
  1483. // // 1. Attribute Name
  1484. // const nameTd = el('td', 'attribute-name');
  1485. // nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1486. // row.appendChild(nameTd);
  1487. // // 3. AI Extracted Value
  1488. // const aiTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1489. // aiTd.textContent = attr.aiValue;
  1490. // row.appendChild(aiTd);
  1491. // // 4. Source
  1492. // const sourceTd = el('td', 'attribute-source');
  1493. // sourceTd.textContent = formatString(attr.source);
  1494. // row.appendChild(sourceTd);
  1495. // tbody.appendChild(row);
  1496. // });
  1497. // table.appendChild(tbody);
  1498. // scrollWrapper.appendChild(table); // Append table to wrapper
  1499. // section.appendChild(scrollWrapper); // Append wrapper to section
  1500. // return section;
  1501. // }
  1502. /**
  1503. * Renders a table for Additional, OCR, or Visual attributes (Name, Value, Source).
  1504. * @param {Object} attributes - The attribute data.
  1505. * @param {string} title - The title for the table section.
  1506. * @returns {HTMLElement} A div containing the table.
  1507. */
  1508. function renderAttributesAsTable(attributes, title, mandatoryData = null) {
  1509. const section = el('div', 'attribute-section');
  1510. let attributeEntries = [];
  1511. // --- STEP 1: Create a Set of all Mandatory Original Values (Normalized) ---
  1512. // A Set is used for fast lookups. Values are normalized (trimmed, lowercase)
  1513. const mandatoryOriginalValuesSet = new Set();
  1514. if (mandatoryData) {
  1515. Object.values(mandatoryData).forEach(attrArray => {
  1516. const originalValue = attrArray[0]?.original_value;
  1517. if (originalValue) {
  1518. mandatoryOriginalValuesSet.add(String(originalValue).trim().toLowerCase());
  1519. }
  1520. });
  1521. }
  1522. // Helper to extract attribute entries consistently
  1523. const processAttribute = (key, values) => {
  1524. const valuesArray = Array.isArray(values) ? values : [values];
  1525. valuesArray.forEach(v => {
  1526. attributeEntries.push({
  1527. name: key,
  1528. value: v.value,
  1529. source: v.source || 'N/A'
  1530. });
  1531. });
  1532. };
  1533. // Iterate through attributes (OCR/Visual/Additional) and flatten them
  1534. Object.keys(attributes).forEach(key => {
  1535. const attribute = attributes[key];
  1536. if (Array.isArray(attribute)) {
  1537. processAttribute(key, attribute);
  1538. } else if (typeof attribute === 'object' && attribute !== null) {
  1539. // Handle simple { "key": { "value": "X", "source": "Y" } } structure
  1540. if (attribute.value !== undefined) {
  1541. attributeEntries.push({
  1542. name: key,
  1543. value: attribute.value,
  1544. source: attribute.source || 'N/A'
  1545. });
  1546. } else {
  1547. // Handle nested objects
  1548. Object.keys(attribute).forEach(subKey => {
  1549. const subAttribute = attribute[subKey];
  1550. if (Array.isArray(subAttribute)) {
  1551. processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  1552. }
  1553. });
  1554. }
  1555. }
  1556. });
  1557. const titleEl = el('div', 'section-title');
  1558. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1559. section.appendChild(titleEl);
  1560. if (attributeEntries.length === 0) {
  1561. const msg = el('p', 'no-attributes-message');
  1562. msg.textContent = `No ${title.toLowerCase()} found.`;
  1563. section.appendChild(msg);
  1564. return section;
  1565. }
  1566. const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1567. const table = el('table', 'attribute-detail-table');
  1568. const thead = el('thead');
  1569. const headerRow = el('tr');
  1570. ['Attribute Name', 'Value'].forEach(text => {
  1571. const th = el('th');
  1572. th.textContent = text;
  1573. headerRow.appendChild(th);
  1574. });
  1575. thead.appendChild(headerRow);
  1576. table.appendChild(thead);
  1577. const tbody = el('tbody');
  1578. attributeEntries.forEach(attr => {
  1579. const row = el('tr');
  1580. // --- CORE COMPARISON LOGIC (Global Check) ---
  1581. let colorClass = '';
  1582. const hasMandatoryBaseline = mandatoryOriginalValuesSet.size > 0;
  1583. if (hasMandatoryBaseline) {
  1584. // Normalize the current attribute's value
  1585. const currentValueNormalized = String(attr.value).trim().toLowerCase();
  1586. // Check if the current value exists ANYWHERE in the mandatory original values set
  1587. if (mandatoryOriginalValuesSet.has(currentValueNormalized)) {
  1588. colorClass = 'green-text'; // Found a match in the global mandatory set
  1589. } else {
  1590. colorClass = 'red-text'; // Did NOT find a match
  1591. }
  1592. }
  1593. // --- END CORE COMPARISON LOGIC ---
  1594. const nameTd = el('td', 'attribute-name');
  1595. nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1596. row.appendChild(nameTd);
  1597. const valueTd = el('td', 'attribute-value');
  1598. const displayValue = formatString(attr.value) + ' (' + formatString(attr.source) + ')';
  1599. valueTd.textContent = displayValue || 'N/A';
  1600. // Apply the determined color class to the value cell
  1601. if (colorClass) {
  1602. valueTd.classList.add(colorClass);
  1603. }
  1604. row.appendChild(valueTd);
  1605. tbody.appendChild(row);
  1606. });
  1607. table.appendChild(tbody);
  1608. scrollWrapper.appendChild(table);
  1609. section.appendChild(scrollWrapper);
  1610. return section;
  1611. }
  1612. // function renderAttributesAsTable(attributes, title, mandatoryData = null) {
  1613. // const section = el('div', 'attribute-section');
  1614. // let attributeEntries = [];
  1615. // const processAttribute = (key, values) => {
  1616. // const valuesArray = Array.isArray(values) ? values : [values];
  1617. // valuesArray.forEach(v => {
  1618. // attributeEntries.push({
  1619. // name: key,
  1620. // value: v.value,
  1621. // source: v.source || 'N/A'
  1622. // });
  1623. // });
  1624. // };
  1625. // Object.keys(attributes).forEach(key => {
  1626. // const attribute = attributes[key];
  1627. // if (Array.isArray(attribute)) {
  1628. // processAttribute(key, attribute);
  1629. // } else if (typeof attribute === 'object' && attribute !== null) {
  1630. // Object.keys(attribute).forEach(subKey => {
  1631. // const subAttribute = attribute[subKey];
  1632. // if (Array.isArray(subAttribute)) {
  1633. // // Combines parent key (e.g., 'size') and sub-key (e.g., 'waist_size')
  1634. // processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  1635. // }
  1636. // });
  1637. // }
  1638. // });
  1639. // const titleEl = el('div', 'section-title');
  1640. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1641. // section.appendChild(titleEl);
  1642. // if (attributeEntries.length === 0) {
  1643. // const msg = el('p', 'no-attributes-message');
  1644. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1645. // section.appendChild(msg);
  1646. // return section;
  1647. // }
  1648. // // --- SCROLL WRAPPER ADDITION ---
  1649. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1650. // const table = el('table', 'attribute-detail-table');
  1651. // const thead = el('thead');
  1652. // const headerRow = el('tr');
  1653. // ['Attribute Name', 'Value'].forEach(text => {
  1654. // const th = el('th');
  1655. // th.textContent = text;
  1656. // headerRow.appendChild(th);
  1657. // });
  1658. // thead.appendChild(headerRow);
  1659. // table.appendChild(thead);
  1660. // const tbody = el('tbody');
  1661. // attributeEntries.forEach(attr => {
  1662. // const row = el('tr');
  1663. // const nameTd = el('td', 'attribute-name');
  1664. // nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1665. // row.appendChild(nameTd);
  1666. // const valueTd = el('td', 'attribute-value');
  1667. // const displayValue = Array.isArray(attr.value)
  1668. // ? (attr.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr.source)+ ')'
  1669. // : formatString(attr.value) +'('+ formatString(attr.source)+ ')';
  1670. // valueTd.textContent = displayValue || 'N/A';
  1671. // row.appendChild(valueTd);
  1672. // // const sourceTd = el('td', 'attribute-source');
  1673. // // sourceTd.textContent = attr.source || 'Unknown';
  1674. // // row.appendChild(sourceTd);
  1675. // tbody.appendChild(row);
  1676. // });
  1677. // table.appendChild(tbody);
  1678. // scrollWrapper.appendChild(table); // Append table to wrapper
  1679. // section.appendChild(scrollWrapper); // Append wrapper to section
  1680. // return section;
  1681. // }
  1682. // ------------------------------------------------------------------
  1683. // --- 3. MAIN RENDER FUNCTION (REPLACEMENT) ---
  1684. // ------------------------------------------------------------------
  1685. // function renderInlineForTable() {
  1686. // const api = API_RESPONSE_AI;
  1687. // const table = $('#tableContainer');
  1688. // if (!table) return;
  1689. // // Remove existing detail rows
  1690. // table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  1691. // PRODUCT_BASE.forEach((p, idx) => {
  1692. // if (!isProductSelected(p.item_id)) return;
  1693. // const res = findApiResultForProduct(p, idx, api);
  1694. // const tbody = table.querySelector('tbody');
  1695. // const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null;
  1696. // if (!baseRow) return;
  1697. // // --- Detail Row Construction ---
  1698. // const detail = el('tr', 'detail-row');
  1699. // // td.colSpan must match the number of columns in your main table
  1700. // const td = el('td'); td.colSpan = 7;
  1701. // const content = el('div', 'detail-content-tables');
  1702. // // // 1. MANDATORY Attributes Table (NOW USES CARD COMPARISON)
  1703. // // const mandatorySection = renderMandatoryComparisonCards( // <-- NEW FUNCTION NAME
  1704. // // res?.mandatory || {},
  1705. // // 'Mandatory Attributes Comparison'
  1706. // // );
  1707. // // content.appendChild(mandatorySection);
  1708. // // // 2. COMBINED Attributes Section (Additional, OCR, Visuals) - REMAINS THE SAME
  1709. // // content.appendChild(el('hr', 'section-separator'));
  1710. // // 1. MANDATORY Attributes Table (USES COMPARISON FUNCTION)
  1711. // const mandatoryTable = renderMandatoryComparisonTable(
  1712. // res?.mandatory || {},
  1713. // 'Mandatory Attributes Comparison'
  1714. // );
  1715. // content.appendChild(mandatoryTable);
  1716. // // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
  1717. // content.appendChild(el('hr', 'section-separator'));
  1718. // const combinedTitle = el('div', 'section-title');
  1719. // combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  1720. // content.appendChild(combinedTitle);
  1721. // const combinedAttributesContainer = el('div', 'combined-attributes-container');
  1722. // // Use the general renderer for these sections
  1723. // const additionalTable = renderAttributesAsTable(
  1724. // res?.additional || {},
  1725. // 'Additional Attributes'
  1726. // );
  1727. // const ocrTable = renderAttributesAsTable(
  1728. // res?.ocr_results?.extracted_attributes || {},
  1729. // 'OCR Results'
  1730. // );
  1731. // const visualsTable = renderAttributesAsTable(
  1732. // res?.visual_results?.visual_attributes || {},
  1733. // 'Visual Results'
  1734. // );
  1735. // // Append all sections to the combined container
  1736. // combinedAttributesContainer.appendChild(additionalTable);
  1737. // combinedAttributesContainer.appendChild(ocrTable);
  1738. // combinedAttributesContainer.appendChild(visualsTable);
  1739. // content.appendChild(combinedAttributesContainer);
  1740. // // --- Summary Counts ---
  1741. // const mandCount = Object.keys(res?.mandatory || {}).length;
  1742. // const addCount = Object.keys(res?.additional || {}).length;
  1743. // const ocrExtractedCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
  1744. // const visualExtractedCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
  1745. // const counts = el('div', 'attribute-summary-pills');
  1746. // const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
  1747. // const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
  1748. // const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
  1749. // const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
  1750. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1751. // content.appendChild(counts);
  1752. // // Final assembly and insertion
  1753. // td.appendChild(content);
  1754. // detail.appendChild(td);
  1755. // baseRow.insertAdjacentElement('afterend', detail);
  1756. // });
  1757. // // Update summary statistics
  1758. // $('#statTotal').textContent = api.total_products ?? 0;
  1759. // $('#statOk').textContent = api.successful ?? 0;
  1760. // $('#statKo').textContent = api.failed ?? 0;
  1761. // const apiSummary = $('#api-summary');
  1762. // if (apiSummary) apiSummary.style.display = 'block';
  1763. // }
  1764. function renderInlineForTable() {
  1765. const api = API_RESPONSE_AI;
  1766. const table = $('#tableContainer');
  1767. if (!table) return;
  1768. // Remove existing detail rows
  1769. table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  1770. PRODUCT_BASE.forEach((p, idx) => {
  1771. if (!isProductSelected(p.item_id)) return;
  1772. const res = findApiResultForProduct(p, idx, api);
  1773. const tbody = table.querySelector('tbody');
  1774. const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null;
  1775. if (!baseRow) return;
  1776. // --- Detail Row Construction ---
  1777. const detail = el('tr', 'detail-row');
  1778. // td.colSpan must match the number of columns in your main table
  1779. const td = el('td'); td.colSpan = 6;
  1780. const content = el('div', 'detail-content-tables');
  1781. // 1. MANDATORY Attributes Table
  1782. // 🚨 Note: The color check (Requirement #2) must be implemented inside renderMandatoryComparisonTable.
  1783. const mandatoryData = res?.mandatory || {};
  1784. if (Object.keys(mandatoryData).length > 0) {
  1785. const mandatoryTable = renderMandatoryComparisonTable(
  1786. mandatoryData,
  1787. 'Mandatory Attributes Comparison'
  1788. );
  1789. content.appendChild(mandatoryTable);
  1790. }
  1791. // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
  1792. const additionalData = res?.additional || {};
  1793. const ocrData = res?.ocr_results?.extracted_attributes || {};
  1794. const visualsData = res?.visual_results?.visual_attributes || {};
  1795. const hasCombinedData = Object.keys(additionalData).length > 0 ||
  1796. Object.keys(ocrData).length > 0 ||
  1797. Object.keys(visualsData).length > 0;
  1798. if (hasCombinedData) {
  1799. content.appendChild(el('hr', 'section-separator'));
  1800. const combinedTitle = el('div', 'section-title');
  1801. combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  1802. content.appendChild(combinedTitle);
  1803. const combinedAttributesContainer = el('div', 'combined-attributes-container');
  1804. // Render Additional Table (Conditional based on data existence)
  1805. if (Object.keys(additionalData).length > 0) {
  1806. const additionalTable = renderAttributesAsTable(
  1807. additionalData,
  1808. 'Additional Attributes',
  1809. mandatoryData
  1810. );
  1811. combinedAttributesContainer.appendChild(additionalTable);
  1812. }
  1813. // Render OCR Table (Conditional based on data existence)
  1814. if (Object.keys(ocrData).length > 0) {
  1815. const ocrTable = renderAttributesAsTable(
  1816. ocrData,
  1817. 'OCR Results',
  1818. mandatoryData
  1819. );
  1820. combinedAttributesContainer.appendChild(ocrTable);
  1821. }
  1822. // Render Visuals Table (Conditional based on data existence)
  1823. if (Object.keys(visualsData).length > 0) {
  1824. const visualsTable = renderAttributesAsTable(
  1825. visualsData,
  1826. 'Visual Results',
  1827. mandatoryData
  1828. );
  1829. combinedAttributesContainer.appendChild(visualsTable);
  1830. }
  1831. content.appendChild(combinedAttributesContainer);
  1832. }
  1833. // --- Summary Counts ---
  1834. const mandCount = Object.keys(mandatoryData).length;
  1835. const addCount = Object.keys(additionalData).length;
  1836. const ocrExtractedCount = Object.keys(ocrData).length;
  1837. const visualExtractedCount = Object.keys(visualsData).length;
  1838. const counts = el('div', 'attribute-summary-pills');
  1839. const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
  1840. const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
  1841. const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
  1842. const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
  1843. counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1844. content.appendChild(counts);
  1845. // Final assembly and insertion
  1846. td.appendChild(content);
  1847. detail.appendChild(td);
  1848. baseRow.insertAdjacentElement('afterend', detail);
  1849. });
  1850. // Update summary statistics
  1851. $('#statTotal').textContent = api.total_products ?? 0;
  1852. $('#statOk').textContent = api.successful ?? 0;
  1853. $('#statKo').textContent = api.failed ?? 0;
  1854. const apiSummary = $('#api-summary');
  1855. if (apiSummary) apiSummary.style.display = 'block';
  1856. }
  1857. function renderInlineAttributes() {
  1858. if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
  1859. // renderInlineForCards();
  1860. // renderInlineForTable();
  1861. }
  1862. // --- Main rendering ---
  1863. function renderProducts() {
  1864. if (layoutMode === 'cards') {
  1865. $('#cardsContainer').style.display = '';
  1866. $('#tableContainer').style.display = 'none';
  1867. // console.log("PRODUCT_BASE",PRODUCT_BASE);
  1868. renderProductsCards();
  1869. } else {
  1870. $('#cardsContainer').style.display = 'none';
  1871. $('#tableContainer').style.display = '';
  1872. renderProductsTable();
  1873. }
  1874. updateSelectionInfo();
  1875. renderPagination();
  1876. // If there is a selection, re-render inline attributes (persist across toggle)
  1877. if (selectedProductsWithAttributes.length > 0) renderInlineAttributes();
  1878. }
  1879. // --- Submit & Reset ---
  1880. function submitAttributes() {
  1881. // Check the length of the new array
  1882. if (selectedProductsWithAttributes.length === 0) {
  1883. alert('Please select at least one product.');
  1884. return;
  1885. }
  1886. // if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
  1887. // console.log("selectedIds",selectedIds);
  1888. jQuery('#full-page-loader').show();
  1889. // let inputArray = {
  1890. // "product_ids" : [...selectedIds]
  1891. // }
  1892. const extractAdditional = document.getElementById('extract_additional').checked;
  1893. const processImage = document.getElementById('process_image').checked;
  1894. // const selectedMultiples = document.getElementById('#mandatory-attributes');
  1895. // const selectedValues = Array.from(selectedMultiples.selectedOptions).map(option => option.value);
  1896. const selectElement = document.getElementById('mandatory-attributes');
  1897. const selectedValues = Array.from(selectElement.selectedOptions).map(option => option.value);
  1898. // console.log(selectedValues); // Logs an array of selected values
  1899. // console.log("thresholdValueDisplay",thresholdValueDisplay.value);
  1900. const threshold = parseFloat(document.getElementById('thresholdRange').value);
  1901. // Transform the new state array into the required API format
  1902. const itemIds = selectedProductsWithAttributes.map(p => p.item_id);
  1903. // Create the mandatory_attrs map: { item_id: { attr_name: [values] } }
  1904. // NOTE: The backend API you showed expects a flattened list of "mandatory_attrs"
  1905. // like: { "color": ["color", "shade"], "size": ["size", "fit"] }
  1906. // It seems to ignore the selected product-specific values and uses a general list of synonyms.
  1907. // Assuming the request needs a general map of *all unique* selected attributes across all selected products:
  1908. let mandatoryAttrsMap = {};
  1909. selectedProductsWithAttributes.forEach(product => {
  1910. // Merge attributes from all selected products
  1911. Object.assign(mandatoryAttrsMap, product.mandatory_attrs);
  1912. });
  1913. // If the API expects the complex, product-specific payload from your Q1 example:
  1914. const payloadForQ1 = selectedProductsWithAttributes.map(p => ({
  1915. item_id: p.item_id,
  1916. mandatory_attrs: p.mandatory_attrs
  1917. }));
  1918. let inputArray = {
  1919. "products": payloadForQ1,
  1920. "model": "llama-3.1-8b-instant",
  1921. "extract_additional": extractAdditional,
  1922. "process_image": processImage,
  1923. "multiple": selectedValues,
  1924. "threshold_abs": 0.6, // Lower threshold to be more permissive
  1925. // "margin": 0.3, // Larger margin to include more candidates
  1926. // "use_adaptive_margin": true,
  1927. // "use_semantic_clustering": true
  1928. }
  1929. let raw = JSON.stringify(inputArray);
  1930. fetch('/attr/batch-extract/', {
  1931. method: 'POST', // or 'POST' if your API expects POST
  1932. headers: {
  1933. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
  1934. 'Content-Type': "application/json"
  1935. },
  1936. body: raw
  1937. })
  1938. .then(response => response.json())
  1939. .then(data => {
  1940. // console.log("response data",data);
  1941. API_RESPONSE_AI = data;
  1942. renderInlineAttributes();
  1943. jQuery('#full-page-loader').hide();
  1944. });
  1945. }
  1946. function resetAll() {
  1947. selectedProductsWithAttributes = []; // Reset the main array
  1948. // selectedIds.clear();
  1949. lastSeen.clear();
  1950. renderProducts();
  1951. // Clear summary
  1952. document.getElementById('statTotal').textContent = '0';
  1953. document.getElementById('statOk').textContent = '0';
  1954. document.getElementById('statKo').textContent = '0';
  1955. $('#api-summary').style.display = 'none';
  1956. // ✅ Clear Select2 selections
  1957. jQuery('#mandatory-attributes').val(null).trigger('change');
  1958. // ✅ Reset threshold input (and display)
  1959. const thresholdInput = document.getElementById('thresholdRange');
  1960. const thresholdDisplay = document.getElementById('thresholdValue');
  1961. thresholdInput.value = '0.65'; // or any default value you prefer
  1962. if (thresholdDisplay) {
  1963. thresholdDisplay.textContent = '0.65';
  1964. }
  1965. }
  1966. function setLayout(mode) {
  1967. layoutMode = mode;
  1968. const btnCards = document.getElementById('btnCards');
  1969. const btnTable = document.getElementById('btnTable');
  1970. if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
  1971. else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
  1972. renderProducts();
  1973. }
  1974. // Upload elements (Bootstrap modal version)
  1975. const uploadModalEl = document.getElementById('uploadModal');
  1976. const dropzone = document.getElementById('dropzone');
  1977. const uploadFiles = document.getElementById('uploadFiles');
  1978. const fileInfo = document.getElementById('fileInfo');
  1979. const uploadBar = document.getElementById('uploadBar');
  1980. const uploadStatus = document.getElementById('uploadStatus');
  1981. // Reset modal on show
  1982. uploadModalEl.addEventListener('shown.bs.modal', () => {
  1983. uploadStatus.textContent = '';
  1984. uploadStatus.className = ''; // clear success/error class
  1985. uploadBar.style.width = '0%';
  1986. uploadBar.setAttribute('aria-valuenow', '0');
  1987. uploadFiles.value = '';
  1988. uploadFiles.setAttribute('accept', ACCEPT_TYPES);
  1989. fileInfo.textContent = 'No files selected.';
  1990. });
  1991. function describeFiles(list) {
  1992. if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
  1993. const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
  1994. fileInfo.textContent = names.join(', ');
  1995. }
  1996. // Drag & drop feedback
  1997. ['dragenter','dragover'].forEach(evt => {
  1998. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
  1999. });
  2000. ['dragleave','drop'].forEach(evt => {
  2001. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
  2002. });
  2003. // Handle drop
  2004. dropzone.addEventListener('drop', e => {
  2005. uploadFiles.files = e.dataTransfer.files;
  2006. describeFiles(uploadFiles.files);
  2007. });
  2008. // Click to browse
  2009. // dropzone.addEventListener('click', () => uploadFiles.click());
  2010. // Picker change
  2011. uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
  2012. function startUpload() {
  2013. const files = uploadFiles.files;
  2014. if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
  2015. jQuery('#full-page-loader').show();
  2016. uploadStatus.textContent = 'Uploading...';
  2017. uploadStatus.className = ''; // neutral
  2018. uploadBar.style.width = '0%';
  2019. uploadBar.setAttribute('aria-valuenow', '0');
  2020. const form = new FormData();
  2021. Array.from(files).forEach(f => form.append('file', f));
  2022. // form.append('uploaded_by', 'Vishal'); // example extra field
  2023. const xhr = new XMLHttpRequest();
  2024. xhr.open('POST', UPLOAD_API_URL, true);
  2025. // If you need auth:
  2026. // xhr.setRequestHeader('Authorization', 'Bearer <token>');
  2027. xhr.upload.onprogress = (e) => {
  2028. if (e.lengthComputable) {
  2029. const pct = Math.round((e.loaded / e.total) * 100);
  2030. uploadBar.style.width = pct + '%';
  2031. uploadBar.setAttribute('aria-valuenow', String(pct));
  2032. }
  2033. };
  2034. xhr.onreadystatechange = () => {
  2035. if (xhr.readyState === 4) {
  2036. const ok = (xhr.status >= 200 && xhr.status < 300);
  2037. try {
  2038. const resp = JSON.parse(xhr.responseText || '{}');
  2039. uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
  2040. } catch {
  2041. uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
  2042. }
  2043. uploadStatus.className = ok ? 'success' : 'error';
  2044. // Optional: auto-close the modal on success after 1.2s:
  2045. // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
  2046. }
  2047. };
  2048. xhr.onerror = () => {
  2049. uploadStatus.textContent = 'Network error during upload.';
  2050. uploadStatus.className = 'error';
  2051. };
  2052. xhr.send(form);
  2053. setTimeout(()=>{
  2054. jQuery('#uploadModal').modal('hide');
  2055. window.location.reload();
  2056. },3000)
  2057. jQuery('#full-page-loader').hide();
  2058. }
  2059. // Wire Start button
  2060. document.getElementById('uploadStart').addEventListener('click', startUpload);
  2061. // Cancel button already closes the modal via data-bs-dismiss
  2062. // --- Pagination state ---
  2063. let page = 1;
  2064. let pageSize = 50; // default rows per page
  2065. function totalPages() {
  2066. return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
  2067. }
  2068. function clampPage() {
  2069. page = Math.min(Math.max(1, page), totalPages());
  2070. }
  2071. function getCurrentSlice() {
  2072. clampPage();
  2073. const start = (page - 1) * pageSize;
  2074. return PRODUCT_BASE.slice(start, start + pageSize);
  2075. }
  2076. function renderPagination() {
  2077. const bar = document.getElementById('paginationBar');
  2078. if (!bar) return;
  2079. const tp = totalPages();
  2080. clampPage();
  2081. bar.innerHTML = `
  2082. <div class="page-size">
  2083. <label for="pageSizeSelect">Rows per page</label>
  2084. <select id="pageSizeSelect">
  2085. <option value="5" ${pageSize===5 ? 'selected' : ''}>5</option>
  2086. <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
  2087. <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
  2088. <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
  2089. <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
  2090. </select>
  2091. </div>
  2092. <div class="pager">
  2093. <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
  2094. <span class="page-info">Page ${page} of ${tp}</span>
  2095. <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
  2096. </div>
  2097. `;
  2098. // wire events
  2099. document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
  2100. document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
  2101. const sel = document.getElementById('pageSizeSelect');
  2102. if (sel) {
  2103. sel.addEventListener('change', () => {
  2104. const val = sel.value;
  2105. pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
  2106. page = 1; // reset to first page when size changes
  2107. renderProducts();
  2108. });
  2109. }
  2110. }
  2111. // Function to add/remove product from the state and manage its attributes
  2112. function toggleProductSelection(itemId, isChecked, attributes = {}) {
  2113. const index = selectedProductsWithAttributes.findIndex(p => p.item_id === itemId);
  2114. // console.log("index",index);
  2115. if (isChecked) {
  2116. // If selecting, ensure the product object exists in the array
  2117. if (index === -1) {
  2118. selectedProductsWithAttributes.push({
  2119. item_id: itemId,
  2120. mandatory_attrs: attributes
  2121. });
  2122. } else {
  2123. // Update attributes if the product is already selected
  2124. selectedProductsWithAttributes[index].mandatory_attrs = attributes;
  2125. }
  2126. } else {
  2127. // If deselecting, remove the product object from the array
  2128. if (index !== -1) {
  2129. selectedProductsWithAttributes.splice(index, 1);
  2130. }
  2131. }
  2132. updateSelectionInfo();
  2133. }
  2134. // Function to get the current mandatory attributes for a selected item
  2135. function getSelectedAttributes(itemId) {
  2136. const productEntry = selectedProductsWithAttributes.find(p => p.item_id === itemId);
  2137. return productEntry ? productEntry.mandatory_attrs : {};
  2138. }
  2139. // Helper to check if a product is selected
  2140. function isProductSelected(itemId) {
  2141. return selectedProductsWithAttributes.some(p => p.item_id === itemId);
  2142. }
  2143. // Helper to check if a specific attribute/value is selected
  2144. function isAttributeValueSelected(itemId, attrName, value) {
  2145. const attrs = getSelectedAttributes(itemId);
  2146. const values = attrs[attrName];
  2147. return values ? values.includes(value) : false; // Default all selected when first loaded
  2148. }
  2149. // $('.attribute-select').select2({
  2150. // placeholder: 'Select product attributes'
  2151. // });
  2152. function getAtributeList(){
  2153. jQuery('#full-page-loader').show();
  2154. try{
  2155. fetch('/attr/products/attributes', {
  2156. method: 'GET', // or 'POST' if your API expects POST
  2157. headers: {
  2158. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
  2159. }
  2160. })
  2161. .then(response => response.json())
  2162. .then(data => {
  2163. // console.log("data",data);
  2164. attributesFullData = data;
  2165. let attributesData = data;
  2166. // Step 1: Extract unique mandatory attribute names
  2167. const mandatoryAttributes = [...new Set(
  2168. attributesData
  2169. .filter(attr => attr.is_mandatory === "Yes")
  2170. .map(attr => attr.attribute_name)
  2171. )];
  2172. // Step 2: Populate the select element
  2173. const $select = jQuery('#mandatory-attributes');
  2174. $select.append(new Option("Select All", "select_all")); // Add "Select All" option first
  2175. mandatoryAttributes.forEach(attr => {
  2176. $select.append(new Option(attr, attr));
  2177. });
  2178. // Step 3: Initialize Select2 with placeholder
  2179. // $select.select2({
  2180. // placeholder: "Select mandatory attributes",
  2181. // allowClear: true
  2182. // });
  2183. // Step 4: Handle 'Select All' logic
  2184. $select.on('select2:select', function (e) {
  2185. if (e.params.data.id === "select_all") {
  2186. // Select all real options except "Select All"
  2187. const allOptions = mandatoryAttributes;
  2188. $select.val(allOptions).trigger('change');
  2189. }
  2190. });
  2191. jQuery('#full-page-loader').hide();
  2192. });
  2193. }catch(err){
  2194. console.log("err",err);
  2195. jQuery('#full-page-loader').hide();
  2196. }
  2197. }
  2198. document.addEventListener("DOMContentLoaded", function () {
  2199. // Update span when range changes
  2200. thresholdInput.addEventListener('input', function () {
  2201. // console.log("this.value",this.value);
  2202. thresholdValueDisplay.textContent = this.value;
  2203. });
  2204. });
  2205. // Get threshold value when needed
  2206. function getThreshold() {
  2207. // console.log("parseFloat(thresholdInput.value)",parseFloat(thresholdInput.value));
  2208. return parseFloat(thresholdInput.value);
  2209. }
  2210. /**
  2211. * Renders Mandatory attributes using a card-based comparison layout.
  2212. * Highlights mismatches prominently.
  2213. * @param {Object} attributes - The mandatory attribute data.
  2214. * @param {string} title - The title for the section.
  2215. * @returns {HTMLElement} A div containing the comparison cards.
  2216. */
  2217. function renderMandatoryComparisonCards(attributes, title) {
  2218. const section = el('div', 'attribute-section');
  2219. // --- 1. Flatten Mandatory Attributes ---
  2220. let attributeEntries = [];
  2221. Object.keys(attributes).forEach(key => {
  2222. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2223. valuesArray.forEach(v => {
  2224. const aiValue = v.value || 'N/A';
  2225. const originalValue = v.original_value || 'N/A';
  2226. // Comparison is case-insensitive and ignores leading/trailing whitespace
  2227. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2228. attributeEntries.push({
  2229. name: key,
  2230. aiValue: aiValue,
  2231. originalValue: originalValue,
  2232. isMatch: isMatch,
  2233. source: v.source || 'N/A'
  2234. });
  2235. });
  2236. });
  2237. // --- 2. Section Header ---
  2238. const titleEl = el('div', 'section-title');
  2239. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2240. section.appendChild(titleEl);
  2241. if (attributeEntries.length === 0) {
  2242. const msg = el('p', 'no-attributes-message');
  2243. msg.textContent = `No ${title.toLowerCase()} found.`;
  2244. section.appendChild(msg);
  2245. return section;
  2246. }
  2247. // --- 3. Card Container ---
  2248. const cardsContainer = el('div', 'comparison-cards-container');
  2249. attributeEntries.forEach(attr => {
  2250. // Main Card Element
  2251. const card = el('div', `comparison-card ${attr.isMatch ? 'match' : 'mismatch-card'}`);
  2252. // Card Header (Attribute Name)
  2253. const header = el('div', 'card-header');
  2254. header.textContent = attr.name.replace(/_/g, ' ');
  2255. card.appendChild(header);
  2256. // Content Wrapper
  2257. const content = el('div', 'card-content');
  2258. // Existing Value Box
  2259. const originalBox = el('div', 'value-box original-box');
  2260. originalBox.innerHTML = `
  2261. <div class="value-label">Manually Identified Value</div>
  2262. <div class="value-text">${attr.originalValue}</div>
  2263. `;
  2264. content.appendChild(originalBox);
  2265. // AI Value Box
  2266. const aiBox = el('div', `value-box ai-box ${attr.isMatch ? 'found-value' : 'mismatch-value'}`);
  2267. aiBox.innerHTML = `
  2268. <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  2269. <div class="value-text">${attr.aiValue}</div>
  2270. `;
  2271. content.appendChild(aiBox);
  2272. card.appendChild(content);
  2273. // Mismatch Indicator (only visible on mismatch-card via CSS)
  2274. if (!attr.isMatch) {
  2275. const indicator = el('div', 'mismatch-indicator');
  2276. // indicator.innerHTML = '❌ MISMATCH';
  2277. indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2278. card.appendChild(indicator);
  2279. }
  2280. cardsContainer.appendChild(card);
  2281. });
  2282. section.appendChild(cardsContainer);
  2283. return section;
  2284. }
  2285. // Example JavaScript (Assuming you have access to API_RESPONSE_AI)
  2286. // document.getElementById('downloadResultBtn').addEventListener('click', () => {
  2287. // // 1. Convert the data to a JSON string
  2288. // const jsonString = JSON.stringify(API_RESPONSE_AI, null, 2);
  2289. // // 2. Create a Blob from the JSON string
  2290. // const blob = new Blob([jsonString], { type: 'application/json' });
  2291. // // 3. Create a temporary URL and link element
  2292. // const url = URL.createObjectURL(blob);
  2293. // const a = document.createElement('a');
  2294. // // 4. Set download attributes
  2295. // a.href = url;
  2296. // a.download = 'api_generated_results.json';
  2297. // // 5. Simulate a click to trigger download
  2298. // document.body.appendChild(a);
  2299. // a.click();
  2300. // // 6. Clean up
  2301. // document.body.removeChild(a);
  2302. // URL.revokeObjectURL(url);
  2303. // });
  2304. /**
  2305. * Renders Mandatory attributes using a card-based comparison layout.
  2306. * Highlights mismatches prominently.
  2307. * @param {Object} attributes - The mandatory attribute data.
  2308. * @param {string} title - The title for the section (used for the header).
  2309. * @returns {HTMLElement} A div containing the comparison cards.
  2310. */
  2311. // function renderMandatoryComparisonCards(attributes, title) {
  2312. // const section = el('div', 'attribute-section mandatory-comparison-section');
  2313. // // --- 1. Flatten Mandatory Attributes ---
  2314. // let attributeEntries = [];
  2315. // Object.keys(attributes).forEach(key => {
  2316. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2317. // valuesArray.forEach(v => {
  2318. // const aiValue = v.value || 'N/A';
  2319. // const originalValue = v.original_value || 'N/A';
  2320. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2321. // attributeEntries.push({
  2322. // name: key,
  2323. // aiValue: aiValue,
  2324. // originalValue: originalValue,
  2325. // isMatch: isMatch,
  2326. // source: v.source || 'N/A'
  2327. // });
  2328. // });
  2329. // });
  2330. // // --- 2. Section Header ---
  2331. // const titleEl = el('div', 'section-title');
  2332. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2333. // section.appendChild(titleEl);
  2334. // if (attributeEntries.length === 0) {
  2335. // const msg = el('p', 'no-attributes-message');
  2336. // msg.textContent = `No ${title.toLowerCase()} found.`;
  2337. // section.appendChild(msg);
  2338. // return section;
  2339. // }
  2340. // // --- 3. Card Container ---
  2341. // const cardsContainer = el('div', 'comparison-cards-container');
  2342. // attributeEntries.forEach(attr => {
  2343. // const card = el('div', `comparison-card ${attr.isMatch ? 'match' : 'mismatch-card'}`);
  2344. // const header = el('div', 'card-header');
  2345. // header.textContent = attr.name.replace(/_/g, ' ');
  2346. // card.appendChild(header);
  2347. // const content = el('div', 'card-content');
  2348. // // Existing Value Box
  2349. // const originalBox = el('div', 'value-box original-box');
  2350. // originalBox.innerHTML = `
  2351. // <div class="value-label">Manually Identified Value</div>
  2352. // <div class="value-text">${attr.originalValue}</div>
  2353. // `;
  2354. // content.appendChild(originalBox);
  2355. // // AI Value Box
  2356. // const aiBox = el('div', `value-box ai-box ${attr.isMatch ? 'found-value' : 'mismatch-value'}`);
  2357. // aiBox.innerHTML = `
  2358. // <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  2359. // <div class="value-text">${attr.aiValue}</div>
  2360. // `;
  2361. // content.appendChild(aiBox);
  2362. // card.appendChild(content);
  2363. // // Mismatch Indicator
  2364. // if (!attr.isMatch) {
  2365. // const indicator = el('div', 'mismatch-indicator');
  2366. // // indicator.innerHTML = '❌ MISMATCH';
  2367. // indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2368. // card.appendChild(indicator);
  2369. // }
  2370. // cardsContainer.appendChild(card);
  2371. // });
  2372. // section.appendChild(cardsContainer);
  2373. // return section;
  2374. // }
  2375. function renderMandatoryComparisonCards(attributes, title) {
  2376. const section = el('div', 'attribute-section mandatory-comparison-section');
  2377. // --- 1. Flatten Mandatory Attributes ---
  2378. let attributeEntries = [];
  2379. Object.keys(attributes).forEach(key => {
  2380. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2381. valuesArray.forEach(v => {
  2382. const aiValue = v.value || 'N/A';
  2383. const originalValue = v.original_value || 'N/A';
  2384. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2385. attributeEntries.push({
  2386. name: key,
  2387. aiValue: aiValue,
  2388. originalValue: originalValue,
  2389. isMatch: isMatch,
  2390. source: v.source || 'N/A'
  2391. });
  2392. });
  2393. });
  2394. // --- 2. Section Header ---
  2395. const titleEl = el('div', 'section-title');
  2396. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2397. section.appendChild(titleEl);
  2398. if (attributeEntries.length === 0) {
  2399. const msg = el('p', 'no-attributes-message');
  2400. msg.textContent = `No ${title.toLowerCase()} found.`;
  2401. section.appendChild(msg);
  2402. return section;
  2403. }
  2404. // --- 3. Card Container ---
  2405. const cardsContainer = el('div', 'comparison-cards-container');
  2406. attributeEntries.forEach(attr => {
  2407. // --- CHANGE 1: Apply 'match-card' or 'mismatch-card' explicitly ---
  2408. const cardClass = attr.isMatch ? 'match-card' : 'mismatch-card';
  2409. const card = el('div', `comparison-card ${cardClass}`);
  2410. const header = el('div', 'card-header');
  2411. header.textContent = attr.name.replace(/_/g, ' ');
  2412. card.appendChild(header);
  2413. const content = el('div', 'card-content');
  2414. // Existing Value Box
  2415. const originalBox = el('div', 'value-box original-box');
  2416. originalBox.innerHTML = `
  2417. <div class="value-label">Manually Identified Value</div>
  2418. <div class="value-text">${attr.originalValue}</div>
  2419. `;
  2420. content.appendChild(originalBox);
  2421. // AI Value Box
  2422. // Removed 'found-value' class here as styling should rely on the parent card class
  2423. const aiBox = el('div', `value-box ai-box ${attr.isMatch ? '' : 'mismatch-value'}`);
  2424. aiBox.innerHTML = `
  2425. <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  2426. <div class="value-text">${attr.aiValue}</div>
  2427. `;
  2428. content.appendChild(aiBox);
  2429. card.appendChild(content);
  2430. // --- CHANGE 2: Display the indicator for ALL cards, controlling color via CSS ---
  2431. const indicator = el('div', 'match-status-indicator');
  2432. indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2433. card.appendChild(indicator);
  2434. cardsContainer.appendChild(card);
  2435. });
  2436. section.appendChild(cardsContainer);
  2437. return section;
  2438. }
  2439. /**
  2440. * Renders Additional, OCR, or Visual attributes in a simple card layout.
  2441. * @param {Object} attributes - The attribute data (Additional, OCR, or Visual).
  2442. * @param {string} title - The title for the section.
  2443. * @returns {HTMLElement} A div containing the attribute cards.
  2444. */
  2445. function renderSimpleAttributeCards(attributes, title) {
  2446. const section = el('div', 'attribute-section simple-attribute-section');
  2447. // --- 1. Flatten Attributes ---
  2448. let attributeEntries = [];
  2449. const processAttribute = (key, values) => {
  2450. const valuesArray = Array.isArray(values) ? values : [values];
  2451. valuesArray.forEach(v => {
  2452. attributeEntries.push({
  2453. name: key,
  2454. value: v.value,
  2455. source: v.source || 'N/A'
  2456. });
  2457. });
  2458. };
  2459. Object.keys(attributes).forEach(key => {
  2460. const attribute = attributes[key];
  2461. if (Array.isArray(attribute)) {
  2462. processAttribute(key, attribute);
  2463. } else if (typeof attribute === 'object' && attribute !== null) {
  2464. Object.keys(attribute).forEach(subKey => {
  2465. const subAttribute = attribute[subKey];
  2466. if (Array.isArray(subAttribute)) {
  2467. processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  2468. }
  2469. });
  2470. }
  2471. });
  2472. // --- 2. Section Header ---
  2473. const titleEl = el('div', 'section-title');
  2474. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2475. section.appendChild(titleEl);
  2476. if (attributeEntries.length === 0) {
  2477. const msg = el('p', 'no-attributes-message');
  2478. msg.textContent = `No ${title.toLowerCase()} found.`;
  2479. section.appendChild(msg);
  2480. return section;
  2481. }
  2482. // --- 3. Card Container ---
  2483. const cardsContainer = el('div', 'comparison-cards-container simple-cards-container');
  2484. attributeEntries.forEach(attr => {
  2485. // Simple Card Element
  2486. const card = el('div', 'simple-card');
  2487. // Card Header (Attribute Name)
  2488. const header = el('div', 'card-header');
  2489. header.textContent = formatString(attr.name).replace(/_/g, ' ');
  2490. card.appendChild(header);
  2491. // Content Wrapper
  2492. const content = el('div', 'card-content');
  2493. // Value Box
  2494. const valueBox = el('div', 'value-box single-value-box');
  2495. const displayValue = Array.isArray(attr.value)
  2496. ? (attr.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr.source)+ ')'
  2497. : formatString(attr.value) +'('+ formatString(attr.source)+ ')';
  2498. // : attr.value;
  2499. valueBox.innerHTML = `
  2500. <div class="value-label">Extracted Value <span class="value-source">(${formatString(attr.source)})</span></div>
  2501. <div class="value-text">${displayValue || 'N/A'}</div>
  2502. `;
  2503. content.appendChild(valueBox);
  2504. card.appendChild(content);
  2505. cardsContainer.appendChild(card);
  2506. });
  2507. section.appendChild(cardsContainer);
  2508. return section;
  2509. }