attr-extraction.js 138 KB

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