attr-extraction.js 142 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471
  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. // attr?.possibleValues.forEach(val => {
  1348. // // Split by comma if there are multiple values, trim spaces
  1349. // const values = val.split(',').map(v => v.trim());
  1350. // values.forEach(v => {
  1351. // const option = document.createElement('option');
  1352. // option.value = v;
  1353. // option.textContent = v;
  1354. // if (selectedValues.includes(v)) option.selected = true;
  1355. // select.appendChild(option);
  1356. // });
  1357. // });
  1358. // Add AI values not found in possibleValues as new selected options
  1359. // selectedValues.forEach(aiVal => {
  1360. // if (!attr?.possibleValues.includes(aiVal)) {
  1361. // const newOpt = document.createElement('option');
  1362. // newOpt.value = aiVal;
  1363. // newOpt.textContent = aiVal;
  1364. // newOpt.selected = true;
  1365. // select.appendChild(newOpt);
  1366. // }
  1367. // });
  1368. // 1. Prepare and clean the selected values first, flattening the comma-separated data.
  1369. let allSelectedValues = new Set();
  1370. selectedValues.forEach(aiVal => {
  1371. aiVal.split(',')
  1372. .map(value => value.trim())
  1373. .filter(value => value.length > 0)
  1374. .forEach(singleVal => allSelectedValues.add(singleVal));
  1375. });
  1376. // Convert the Set back to an array for easy checking, or keep it as a Set for O(1) lookups.
  1377. // We'll keep it as a Set for efficient checking.
  1378. // ---
  1379. // 2. Add all default possible values.
  1380. attr?.possibleValues.forEach(val => {
  1381. const option = document.createElement('option');
  1382. option.value = val;
  1383. option.textContent = val;
  1384. // Check if the possible value is one of the cleaned selected values
  1385. if (allSelectedValues.has(val)) {
  1386. option.selected = true;
  1387. // IMPORTANT: Remove this value from the Set so we know which ones are left over (the custom ones)
  1388. allSelectedValues.delete(val);
  1389. }
  1390. select.appendChild(option);
  1391. });
  1392. // ---
  1393. // 3. Add any "custom" selected values that weren't in possibleValues.
  1394. // The allSelectedValues Set now only contains values that are NOT in attr?.possibleValues.
  1395. allSelectedValues.forEach(singleVal => {
  1396. const newOpt = document.createElement('option');
  1397. newOpt.value = singleVal;
  1398. newOpt.textContent = singleVal;
  1399. newOpt.selected = true; // These are guaranteed to be selected values
  1400. select.appendChild(newOpt);
  1401. });
  1402. aiTd.appendChild(select);
  1403. row.appendChild(aiTd);
  1404. tbody.appendChild(row);
  1405. // Initialize Select2
  1406. jQuery(select).select2({
  1407. tags: true,
  1408. width: 'resolve'
  1409. });
  1410. });
  1411. table.appendChild(tbody);
  1412. scrollWrapper.appendChild(table);
  1413. return scrollWrapper;
  1414. }
  1415. // --- Build and append both tables ---
  1416. const leftTable = buildTable(leftAttributes);
  1417. const rightTable = buildTable(rightAttributes);
  1418. tableContainer.appendChild(leftTable);
  1419. tableContainer.appendChild(rightTable);
  1420. section.appendChild(tableContainer);
  1421. return section;
  1422. }
  1423. // function renderMandatoryComparisonTable(attributes, title, productType) {
  1424. // const section = el('div', 'attribute-section');
  1425. // let attributeEntries = [];
  1426. // // --- Build attributeEntries ---
  1427. // Object.keys(attributes).forEach(key => {
  1428. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1429. // valuesArray.forEach(v => {
  1430. // const aiValue = v.value || 'N/A';
  1431. // const originalValue = v.original_value || 'N/A';
  1432. // const source = v.source || 'N/A';
  1433. // const reason = v.reason || 'N/A';
  1434. // // Find possible values for this attribute from full data
  1435. // const attrConfig = attributesFullData.find(item => item.attribute_name === key);
  1436. // let possibleValues = [];
  1437. // if (attrConfig && attrConfig.possible_values) {
  1438. // possibleValues = attrConfig.possible_values.split(',').map(s => s.trim());
  1439. // }
  1440. // // Determine match flag
  1441. // const isFoundInPossible = possibleValues.includes(aiValue);
  1442. // const matchFlag = isFoundInPossible ? true : false;
  1443. // attributeEntries.push({
  1444. // name: key,
  1445. // aiValue: aiValue,
  1446. // possibleValues: possibleValues,
  1447. // originalValue: originalValue,
  1448. // source: source,
  1449. // isMatch: matchFlag,
  1450. // reason: reason
  1451. // });
  1452. // });
  1453. // });
  1454. // // --- Section title ---
  1455. // const titleEl = el('div', 'section-title');
  1456. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1457. // section.appendChild(titleEl);
  1458. // if (attributeEntries.length === 0) {
  1459. // const msg = el('p', 'no-attributes-message');
  1460. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1461. // section.appendChild(msg);
  1462. // return section;
  1463. // }
  1464. // // --- Split attributes in half ---
  1465. // const midIndex = Math.ceil(attributeEntries.length / 2);
  1466. // const leftAttributes = attributeEntries.slice(0, midIndex);
  1467. // const rightAttributes = attributeEntries.slice(midIndex);
  1468. // // --- Create a container for two tables ---
  1469. // const tableContainer = el('div', 'two-column-table-container');
  1470. // // Helper function to build a table
  1471. // function buildTable(attrArray) {
  1472. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1473. // const table = el('table', 'attribute-detail-table comparison-table');
  1474. // const thead = el('thead');
  1475. // const headerRow = el('tr');
  1476. // // , 'AI Generated Value'
  1477. // ['Attribute Name', 'Recommended Attribute Value(s)'].forEach(text => {
  1478. // const th = el('th');
  1479. // th.textContent = text;
  1480. // headerRow.appendChild(th);
  1481. // });
  1482. // thead.appendChild(headerRow);
  1483. // table.appendChild(thead);
  1484. // const tbody = el('tbody');
  1485. // attrArray.forEach(attr => {
  1486. // const row = el('tr', attr?.isMatch ? 'match-row' : 'mismatch-row');
  1487. // // Attribute name
  1488. // const nameTd = el('td', 'attribute-name');
  1489. // nameTd.textContent = formatString(attr?.name).replace(/_/g, ' ');
  1490. // row.appendChild(nameTd);
  1491. // // AI Value display
  1492. // // AI Value cell with info icon
  1493. // // const aiValueTd = el('td', `ai-value ${attr?.isMatch ? '' : 'mismatch-value'}`);
  1494. // // // Create a wrapper for text and icon
  1495. // // const aiValueWrapper = document.createElement('div');
  1496. // // aiValueWrapper.style.display = 'flex';
  1497. // // aiValueWrapper.style.alignItems = 'center';
  1498. // // aiValueWrapper.style.gap = '6px';
  1499. // // // Text node
  1500. // // const valueText = document.createElement('span');
  1501. // // valueText.textContent = formatString(attr?.aiValue);
  1502. // // aiValueWrapper.appendChild(valueText);
  1503. // // // Info icon (Bootstrap Icons)
  1504. // // if (attr?.reason && attr?.reason.trim() !== '') {
  1505. // // const infoIcon = document.createElement('i');
  1506. // // infoIcon.className = 'bi bi-info-circle';
  1507. // // infoIcon.style.cursor = 'pointer';
  1508. // // infoIcon.setAttribute('title', attr?.reason); // Tooltip on hover
  1509. // // infoIcon.style.color = '#0d6efd'; // Bootstrap blue
  1510. // // aiValueWrapper.appendChild(infoIcon);
  1511. // // }
  1512. // // aiValueTd.appendChild(aiValueWrapper);
  1513. // // row.appendChild(aiValueTd);
  1514. // // const aiValueTd = el('td', `ai-value ${attr?.isMatch ? '' : 'mismatch-value'}`);
  1515. // // aiValueTd.textContent = formatString(attr?.aiValue);
  1516. // // row.appendChild(aiValueTd);
  1517. // // Dropdown
  1518. // // const aiTd = el('td', 'attribute-source');
  1519. // // const select = document.createElement('select');
  1520. // // select.classList.add('select2-dropdown');
  1521. // // select.setAttribute('data-attribute', attr?.name);
  1522. // const aiTd = el('td', 'attribute-source');
  1523. // // Create a multi-select dropdown
  1524. // const select = document.createElement('select');
  1525. // select.classList.add('select2-dropdown');
  1526. // // select.id = 'manually-attributes'; // You may want to make this unique per row
  1527. // select.name = 'manuallyUpdatedAttributes[]';
  1528. // // select.setAttribute('aria-labelledby', 'select a attribute for which multiple data required');
  1529. // select.setAttribute('multiple', 'multiple');
  1530. // // select.style.width = '100%';
  1531. // select.setAttribute('data-attribute', attr?.name);
  1532. // // Populate options
  1533. // attr?.possibleValues.forEach(val => {
  1534. // const option = document.createElement('option');
  1535. // option.value = val;
  1536. // option.textContent = val;
  1537. // if (val === attr?.aiValue) option.selected = true;
  1538. // select.appendChild(option);
  1539. // });
  1540. // // if (!attr?.isMatch && attr?.aiValue !== 'N/A') {
  1541. // // const newOpt = document.createElement('option');
  1542. // // newOpt.value = attr?.aiValue;
  1543. // // newOpt.textContent = attr?.aiValue; // + " (new)";
  1544. // // newOpt.selected = true;
  1545. // // select.appendChild(newOpt);
  1546. // // }
  1547. // aiTd.appendChild(select);
  1548. // row.appendChild(aiTd);
  1549. // tbody.appendChild(row);
  1550. // // Initialize Select2
  1551. // jQuery(select).select2({
  1552. // tags: true,
  1553. // width: 'resolve'
  1554. // });
  1555. // });
  1556. // table.appendChild(tbody);
  1557. // scrollWrapper.appendChild(table);
  1558. // return scrollWrapper;
  1559. // }
  1560. // // --- Build and append both tables ---
  1561. // const leftTable = buildTable(leftAttributes);
  1562. // const rightTable = buildTable(rightAttributes);
  1563. // tableContainer.appendChild(leftTable);
  1564. // tableContainer.appendChild(rightTable);
  1565. // section.appendChild(tableContainer);
  1566. // return section;
  1567. // }
  1568. // function renderMandatoryComparisonTable(attributes, title, productType) {
  1569. // const section = el('div', 'attribute-section');
  1570. // let attributeEntries = [];
  1571. // Object.keys(attributes).forEach(key => {
  1572. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1573. // valuesArray.forEach(v => {
  1574. // const aiValue = v.value || 'N/A';
  1575. // const originalValue = v.original_value || 'N/A';
  1576. // const source = v.source || 'N/A';
  1577. // // Find possible values for this attribute from `a`
  1578. // const attrConfig = attributesFullData.find(item =>
  1579. // item.attribute_name === key
  1580. // );
  1581. // let possibleValues = [];
  1582. // if (attrConfig && attrConfig.possible_values) {
  1583. // possibleValues = attrConfig.possible_values.split(',').map(s => s.trim());
  1584. // }
  1585. // // Determine if AI value exists in possible values
  1586. // const isFoundInPossible = possibleValues.includes(aiValue);
  1587. // const matchFlag = isFoundInPossible ? true : false;
  1588. // attributeEntries.push({
  1589. // name: key,
  1590. // aiValue: aiValue,
  1591. // possibleValues: possibleValues,
  1592. // originalValue: originalValue,
  1593. // source: source,
  1594. // isMatch: matchFlag
  1595. // });
  1596. // });
  1597. // });
  1598. // const titleEl = el('div', 'section-title');
  1599. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1600. // section.appendChild(titleEl);
  1601. // if (attributeEntries.length === 0) {
  1602. // const msg = el('p', 'no-attributes-message');
  1603. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1604. // section.appendChild(msg);
  1605. // return section;
  1606. // }
  1607. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1608. // const table = el('table', 'attribute-detail-table comparison-table');
  1609. // const thead = el('thead');
  1610. // const headerRow = el('tr');
  1611. // ['Attribute Name', 'AI Generated Value', 'Action'].forEach(text => {
  1612. // const th = el('th');
  1613. // th.textContent = text;
  1614. // headerRow.appendChild(th);
  1615. // });
  1616. // thead.appendChild(headerRow);
  1617. // table.appendChild(thead);
  1618. // const tbody = el('tbody');
  1619. // attributeEntries.forEach(attr => {
  1620. // const row = el('tr', attr?.isMatch ? 'match-row' : 'mismatch-row');
  1621. // // 1. Attribute Name
  1622. // const nameTd = el('td', 'attribute-name');
  1623. // nameTd.textContent = formatString(attr?.name).replace(/_/g, ' ');
  1624. // row.appendChild(nameTd);
  1625. // // 3. Source Column
  1626. // const sourceTd = el('td', `ai-value ${attr?.isMatch ? '' : 'mismatch-value'}`);
  1627. // sourceTd.textContent = formatString(attr?.aiValue);
  1628. // row.appendChild(sourceTd);
  1629. // // 2. AI Value Dropdown (Select2)
  1630. // const aiTd = el('td', 'attribute-source');
  1631. // const select = document.createElement('select');
  1632. // select.classList.add('select2-dropdown');
  1633. // select.setAttribute('data-attribute', attr?.name);
  1634. // // Populate possible values
  1635. // attr?.possibleValues.forEach(val => {
  1636. // const option = document.createElement('option');
  1637. // option.value = val;
  1638. // option.textContent = val;
  1639. // if (val === attr?.aiValue) option.selected = true;
  1640. // select.appendChild(option);
  1641. // });
  1642. // // If not found in possible values, add it as a new option
  1643. // if (!attr?.isMatch && attr?.aiValue !== 'N/A') {
  1644. // const newOpt = document.createElement('option');
  1645. // newOpt.value = attr?.aiValue;
  1646. // newOpt.textContent = attr?.aiValue + " (new)";
  1647. // newOpt.selected = true;
  1648. // select.appendChild(newOpt);
  1649. // }
  1650. // aiTd.appendChild(select);
  1651. // row.appendChild(aiTd);
  1652. // tbody.appendChild(row);
  1653. // // Initialize Select2 after element is added
  1654. // jQuery(select).select2({
  1655. // tags: true, // allows new values
  1656. // width: 'resolve'
  1657. // });
  1658. // });
  1659. // table.appendChild(tbody);
  1660. // scrollWrapper.appendChild(table);
  1661. // section.appendChild(scrollWrapper);
  1662. // return section;
  1663. // }
  1664. // function renderMandatoryComparisonTable(attributes, title) {
  1665. // const section = el('div', 'attribute-section');
  1666. // let attributeEntries = [];
  1667. // Object.keys(attributes).forEach(key => {
  1668. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1669. // valuesArray.forEach(v => {
  1670. // const aiValue = v.value || 'N/A';
  1671. // const originalValue = v.original_value || 'N/A';
  1672. // const source = v.source || 'N/A';
  1673. // // Comparison is case-insensitive and ignores leading/trailing whitespace
  1674. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  1675. // attributeEntries.push({
  1676. // name: key,
  1677. // aiValue: aiValue,
  1678. // originalValue: originalValue,
  1679. // source: source,
  1680. // isMatch: isMatch
  1681. // });
  1682. // });
  1683. // });
  1684. // const titleEl = el('div', 'section-title');
  1685. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1686. // section.appendChild(titleEl);
  1687. // if (attributeEntries.length === 0) {
  1688. // const msg = el('p', 'no-attributes-message');
  1689. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1690. // section.appendChild(msg);
  1691. // return section;
  1692. // }
  1693. // // --- SCROLL WRAPPER ADDITION ---
  1694. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1695. // const table = el('table', 'attribute-detail-table comparison-table');
  1696. // const thead = el('thead');
  1697. // const headerRow = el('tr');
  1698. // // Updated Headers for Comparison Table
  1699. // ['Attribute Name', 'AI Generated Value', 'Action'].forEach(text => {
  1700. // const th = el('th');
  1701. // th.textContent = text;
  1702. // headerRow.appendChild(th);
  1703. // });
  1704. // thead.appendChild(headerRow);
  1705. // table.appendChild(thead);
  1706. // const tbody = el('tbody');
  1707. // attributeEntries.forEach(attr => {
  1708. // // Highlight the entire row in red if the values do not match
  1709. // const row = el('tr', attr?.isMatch ? 'match-row' : 'mismatch-row');
  1710. // // 1. Attribute Name
  1711. // const nameTd = el('td', 'attribute-name');
  1712. // nameTd.textContent = formatString(attr?.name).replace(/_/g, ' ');
  1713. // row.appendChild(nameTd);
  1714. // // 3. AI Extracted Value
  1715. // const aiTd = el('td', `ai-value ${attr?.isMatch ? '' : 'mismatch-value'}`);
  1716. // aiTd.textContent = attr?.aiValue;
  1717. // row.appendChild(aiTd);
  1718. // // 4. Source
  1719. // const sourceTd = el('td', 'attribute-source');
  1720. // sourceTd.textContent = formatString(attr?.source);
  1721. // row.appendChild(sourceTd);
  1722. // tbody.appendChild(row);
  1723. // });
  1724. // table.appendChild(tbody);
  1725. // scrollWrapper.appendChild(table); // Append table to wrapper
  1726. // section.appendChild(scrollWrapper); // Append wrapper to section
  1727. // return section;
  1728. // }
  1729. /**
  1730. * Renders a table for Additional, OCR, or Visual attributes (Name, Value, Source).
  1731. * @param {Object} attributes - The attribute data.
  1732. * @param {string} title - The title for the table section.
  1733. * @returns {HTMLElement} A div containing the table.
  1734. */
  1735. function renderAttributesAsTable(attributes, title, mandatoryData = null) {
  1736. const section = el('div', 'attribute-section');
  1737. let attributeEntries = [];
  1738. // --- STEP 1: Create a Set of all Mandatory Original Values (Normalized) ---
  1739. // A Set is used for fast lookups. Values are normalized (trimmed, lowercase)
  1740. const mandatoryOriginalValuesSet = new Set();
  1741. if (mandatoryData) {
  1742. Object.values(mandatoryData).forEach(attrArray => {
  1743. const originalValue = attrArray[0]?.original_value;
  1744. if (originalValue) {
  1745. mandatoryOriginalValuesSet.add(String(originalValue).trim().toLowerCase());
  1746. }
  1747. });
  1748. }
  1749. // Helper to extract attribute entries consistently
  1750. const processAttribute = (key, values) => {
  1751. const valuesArray = Array.isArray(values) ? values : [values];
  1752. valuesArray.forEach(v => {
  1753. attributeEntries.push({
  1754. name: key,
  1755. value: v.value,
  1756. source: v.source || 'N/A'
  1757. });
  1758. });
  1759. };
  1760. // Iterate through attributes (OCR/Visual/Additional) and flatten them
  1761. Object.keys(attributes).forEach(key => {
  1762. const attribute = attributes[key];
  1763. if (Array.isArray(attribute)) {
  1764. processAttribute(key, attribute);
  1765. } else if (typeof attribute === 'object' && attribute !== null) {
  1766. // Handle simple { "key": { "value": "X", "source": "Y" } } structure
  1767. if (attribute.value !== undefined) {
  1768. attributeEntries.push({
  1769. name: key,
  1770. value: attribute.value,
  1771. source: attribute.source || 'N/A'
  1772. });
  1773. } else {
  1774. // Handle nested objects
  1775. Object.keys(attribute).forEach(subKey => {
  1776. const subAttribute = attribute[subKey];
  1777. if (Array.isArray(subAttribute)) {
  1778. processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  1779. }
  1780. });
  1781. }
  1782. }
  1783. });
  1784. const titleEl = el('div', 'section-title');
  1785. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1786. section.appendChild(titleEl);
  1787. if (attributeEntries.length === 0) {
  1788. const msg = el('p', 'no-attributes-message');
  1789. msg.textContent = `No ${title.toLowerCase()} found.`;
  1790. section.appendChild(msg);
  1791. return section;
  1792. }
  1793. const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1794. const table = el('table', 'attribute-detail-table');
  1795. const thead = el('thead');
  1796. const headerRow = el('tr');
  1797. ['Attribute Name', 'Value'].forEach(text => {
  1798. const th = el('th');
  1799. th.textContent = text;
  1800. headerRow.appendChild(th);
  1801. });
  1802. thead.appendChild(headerRow);
  1803. table.appendChild(thead);
  1804. const tbody = el('tbody');
  1805. attributeEntries.forEach(attr => {
  1806. const row = el('tr');
  1807. // --- CORE COMPARISON LOGIC (Global Check) ---
  1808. let colorClass = '';
  1809. const hasMandatoryBaseline = mandatoryOriginalValuesSet.size > 0;
  1810. if (hasMandatoryBaseline) {
  1811. // Normalize the current attribute's value
  1812. const currentValueNormalized = String(attr?.value).trim().toLowerCase();
  1813. // Check if the current value exists ANYWHERE in the mandatory original values set
  1814. if (mandatoryOriginalValuesSet.has(currentValueNormalized)) {
  1815. colorClass = 'green-text'; // Found a match in the global mandatory set
  1816. } else {
  1817. colorClass = 'red-text'; // Did NOT find a match
  1818. }
  1819. }
  1820. // --- END CORE COMPARISON LOGIC ---
  1821. const nameTd = el('td', 'attribute-name');
  1822. nameTd.textContent = formatString(attr?.name).replace(/_/g, ' ');
  1823. row.appendChild(nameTd);
  1824. const valueTd = el('td', 'attribute-value');
  1825. const displayValue = formatString(attr?.value) + ' (' + formatString(attr?.source) + ')';
  1826. valueTd.textContent = displayValue || 'N/A';
  1827. // Apply the determined color class to the value cell
  1828. if (colorClass) {
  1829. valueTd.classList.add(colorClass);
  1830. }
  1831. row.appendChild(valueTd);
  1832. tbody.appendChild(row);
  1833. });
  1834. table.appendChild(tbody);
  1835. scrollWrapper.appendChild(table);
  1836. section.appendChild(scrollWrapper);
  1837. return section;
  1838. }
  1839. // function renderAttributesAsTable(attributes, title, mandatoryData = null) {
  1840. // const section = el('div', 'attribute-section');
  1841. // let attributeEntries = [];
  1842. // const processAttribute = (key, values) => {
  1843. // const valuesArray = Array.isArray(values) ? values : [values];
  1844. // valuesArray.forEach(v => {
  1845. // attributeEntries.push({
  1846. // name: key,
  1847. // value: v.value,
  1848. // source: v.source || 'N/A'
  1849. // });
  1850. // });
  1851. // };
  1852. // Object.keys(attributes).forEach(key => {
  1853. // const attribute = attributes[key];
  1854. // if (Array.isArray(attribute)) {
  1855. // processAttribute(key, attribute);
  1856. // } else if (typeof attribute === 'object' && attribute !== null) {
  1857. // Object.keys(attribute).forEach(subKey => {
  1858. // const subAttribute = attribute[subKey];
  1859. // if (Array.isArray(subAttribute)) {
  1860. // // Combines parent key (e.g., 'size') and sub-key (e.g., 'waist_size')
  1861. // processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  1862. // }
  1863. // });
  1864. // }
  1865. // });
  1866. // const titleEl = el('div', 'section-title');
  1867. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1868. // section.appendChild(titleEl);
  1869. // if (attributeEntries.length === 0) {
  1870. // const msg = el('p', 'no-attributes-message');
  1871. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1872. // section.appendChild(msg);
  1873. // return section;
  1874. // }
  1875. // // --- SCROLL WRAPPER ADDITION ---
  1876. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1877. // const table = el('table', 'attribute-detail-table');
  1878. // const thead = el('thead');
  1879. // const headerRow = el('tr');
  1880. // ['Attribute Name', 'Value'].forEach(text => {
  1881. // const th = el('th');
  1882. // th.textContent = text;
  1883. // headerRow.appendChild(th);
  1884. // });
  1885. // thead.appendChild(headerRow);
  1886. // table.appendChild(thead);
  1887. // const tbody = el('tbody');
  1888. // attributeEntries.forEach(attr => {
  1889. // const row = el('tr');
  1890. // const nameTd = el('td', 'attribute-name');
  1891. // nameTd.textContent = formatString(attr?.name).replace(/_/g, ' ');
  1892. // row.appendChild(nameTd);
  1893. // const valueTd = el('td', 'attribute-value');
  1894. // const displayValue = Array.isArray(attr?.value)
  1895. // ? (attr?.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr?.source)+ ')'
  1896. // : formatString(attr?.value) +'('+ formatString(attr?.source)+ ')';
  1897. // valueTd.textContent = displayValue || 'N/A';
  1898. // row.appendChild(valueTd);
  1899. // // const sourceTd = el('td', 'attribute-source');
  1900. // // sourceTd.textContent = attr?.source || 'Unknown';
  1901. // // row.appendChild(sourceTd);
  1902. // tbody.appendChild(row);
  1903. // });
  1904. // table.appendChild(tbody);
  1905. // scrollWrapper.appendChild(table); // Append table to wrapper
  1906. // section.appendChild(scrollWrapper); // Append wrapper to section
  1907. // return section;
  1908. // }
  1909. // ------------------------------------------------------------------
  1910. // --- 3. MAIN RENDER FUNCTION (REPLACEMENT) ---
  1911. // ------------------------------------------------------------------
  1912. // function renderInlineForTable() {
  1913. // const api = API_RESPONSE_AI;
  1914. // const table = $('#tableContainer');
  1915. // if (!table) return;
  1916. // // Remove existing detail rows
  1917. // table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  1918. // PRODUCT_BASE.forEach((p, idx) => {
  1919. // if (!isProductSelected(p.item_id)) return;
  1920. // const res = findApiResultForProduct(p, idx, api);
  1921. // const tbody = table.querySelector('tbody');
  1922. // const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null;
  1923. // if (!baseRow) return;
  1924. // // --- Detail Row Construction ---
  1925. // const detail = el('tr', 'detail-row');
  1926. // // td.colSpan must match the number of columns in your main table
  1927. // const td = el('td'); td.colSpan = 7;
  1928. // const content = el('div', 'detail-content-tables');
  1929. // // // 1. MANDATORY Attributes Table (NOW USES CARD COMPARISON)
  1930. // // const mandatorySection = renderMandatoryComparisonCards( // <-- NEW FUNCTION NAME
  1931. // // res?.mandatory || {},
  1932. // // 'Mandatory Attributes Comparison'
  1933. // // );
  1934. // // content.appendChild(mandatorySection);
  1935. // // // 2. COMBINED Attributes Section (Additional, OCR, Visuals) - REMAINS THE SAME
  1936. // // content.appendChild(el('hr', 'section-separator'));
  1937. // // 1. MANDATORY Attributes Table (USES COMPARISON FUNCTION)
  1938. // const mandatoryTable = renderMandatoryComparisonTable(
  1939. // res?.mandatory || {},
  1940. // 'Mandatory Attributes Comparison'
  1941. // );
  1942. // content.appendChild(mandatoryTable);
  1943. // // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
  1944. // content.appendChild(el('hr', 'section-separator'));
  1945. // const combinedTitle = el('div', 'section-title');
  1946. // combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  1947. // content.appendChild(combinedTitle);
  1948. // const combinedAttributesContainer = el('div', 'combined-attributes-container');
  1949. // // Use the general renderer for these sections
  1950. // const additionalTable = renderAttributesAsTable(
  1951. // res?.additional || {},
  1952. // 'Additional Attributes'
  1953. // );
  1954. // const ocrTable = renderAttributesAsTable(
  1955. // res?.ocr_results?.extracted_attributes || {},
  1956. // 'OCR Results'
  1957. // );
  1958. // const visualsTable = renderAttributesAsTable(
  1959. // res?.visual_results?.visual_attributes || {},
  1960. // 'Visual Results'
  1961. // );
  1962. // // Append all sections to the combined container
  1963. // combinedAttributesContainer.appendChild(additionalTable);
  1964. // combinedAttributesContainer.appendChild(ocrTable);
  1965. // combinedAttributesContainer.appendChild(visualsTable);
  1966. // content.appendChild(combinedAttributesContainer);
  1967. // // --- Summary Counts ---
  1968. // const mandCount = Object.keys(res?.mandatory || {}).length;
  1969. // const addCount = Object.keys(res?.additional || {}).length;
  1970. // const ocrExtractedCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
  1971. // const visualExtractedCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
  1972. // const counts = el('div', 'attribute-summary-pills');
  1973. // const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
  1974. // const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
  1975. // const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
  1976. // const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
  1977. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1978. // content.appendChild(counts);
  1979. // // Final assembly and insertion
  1980. // td.appendChild(content);
  1981. // detail.appendChild(td);
  1982. // baseRow.insertAdjacentElement('afterend', detail);
  1983. // });
  1984. // // Update summary statistics
  1985. // $('#statTotal').textContent = api.total_products ?? 0;
  1986. // $('#statOk').textContent = api.successful ?? 0;
  1987. // $('#statKo').textContent = api.failed ?? 0;
  1988. // const apiSummary = $('#api-summary');
  1989. // if (apiSummary) apiSummary.style.display = 'block';
  1990. // }
  1991. // function highlightMatches(text, keywords) {
  1992. // if (!text) return '—';
  1993. // let highlighted = text;
  1994. // keywords.forEach(keyword => {
  1995. // const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Escape regex
  1996. // const regex = new RegExp(`(${escapedKeyword})`, 'gi');
  1997. // highlighted = highlighted.replace(regex, '<span class="highlight-text">$1</span>');
  1998. // });
  1999. // return highlighted;
  2000. // }
  2001. function highlightMatches(text, keywords) {
  2002. if (!text) return '—';
  2003. // 1. Process Keywords: Flatten the array and handle comma-separated strings
  2004. const uniqueKeywords = new Set();
  2005. keywords.forEach(compositeKeyword => {
  2006. // Split by comma, trim whitespace, and add non-empty terms to the Set
  2007. compositeKeyword.split(',')
  2008. .map(kw => kw.trim())
  2009. .filter(kw => kw.length > 0)
  2010. .forEach(singleKeyword => {
  2011. // Only add the keyword if it's not just an empty string
  2012. if (singleKeyword) {
  2013. uniqueKeywords.add(singleKeyword);
  2014. }
  2015. });
  2016. });
  2017. let highlighted = text;
  2018. // 2. Apply Highlighting using the clean, unique keywords
  2019. uniqueKeywords.forEach(keyword => {
  2020. // We still need to check for length in case something slipped through,
  2021. // though the filter and Set should handle most cases.
  2022. if (keyword.length > 0) {
  2023. const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Escape regex special characters
  2024. // Use 'g' (global) and 'i' (case-insensitive) flags
  2025. const regex = new RegExp(`(${escapedKeyword})`, 'gi');
  2026. // Use a function as the replacer to ensure we highlight all matches
  2027. highlighted = highlighted.replace(regex, '<span class="highlight-text">$1</span>');
  2028. }
  2029. });
  2030. return highlighted;
  2031. }
  2032. // WOrking ONe
  2033. function renderInlineForTable() {
  2034. const api = API_RESPONSE_AI;
  2035. const table = $('#tableContainer');
  2036. if (!table) return;
  2037. // Remove existing detail rows
  2038. table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  2039. PRODUCT_BASE.forEach((p, idx) => {
  2040. if (!isProductSelected(p.item_id)) return;
  2041. const res = findApiResultForProduct(p, idx, api);
  2042. const tbody = table.querySelector('tbody');
  2043. const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null;
  2044. if (!baseRow) return;
  2045. // --- Detail Row Construction ---
  2046. const detail = el('tr', 'detail-row');
  2047. // td.colSpan must match the number of columns in your main table
  2048. const td = el('td'); td.colSpan = 6;
  2049. const content = el('div', 'detail-content-tables');
  2050. // 1. MANDATORY Attributes Table
  2051. // 🚨 Note: The color check (Requirement #2) must be implemented inside renderMandatoryComparisonTable.
  2052. const mandatoryData = res?.mandatory || {};
  2053. if (Object.keys(mandatoryData).length > 0) {
  2054. const mandatoryTable = renderMandatoryComparisonTable(
  2055. mandatoryData,
  2056. 'Attributes'
  2057. );
  2058. content.appendChild(mandatoryTable);
  2059. }
  2060. // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
  2061. const additionalData = res?.additional || {};
  2062. const ocrData = res?.ocr_results?.extracted_attributes || {};
  2063. const visualsData = res?.visual_results?.visual_attributes || {};
  2064. const hasCombinedData = Object.keys(additionalData).length > 0 ||
  2065. Object.keys(ocrData).length > 0 ||
  2066. Object.keys(visualsData).length > 0;
  2067. if (hasCombinedData) {
  2068. content.appendChild(el('hr', 'section-separator'));
  2069. const combinedTitle = el('div', 'section-title');
  2070. combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  2071. // content.appendChild(combinedTitle);
  2072. const combinedAttributesContainer = el('div', 'combined-attributes-container');
  2073. // Render Additional Table (Conditional based on data existence)
  2074. if (Object.keys(additionalData).length > 0) {
  2075. const additionalTable = renderAttributesAsTable(
  2076. additionalData,
  2077. 'Additional Attributes',
  2078. mandatoryData
  2079. );
  2080. // combinedAttributesContainer.appendChild(additionalTable);
  2081. }
  2082. // Render OCR Table (Conditional based on data existence)
  2083. if (Object.keys(ocrData).length > 0) {
  2084. const ocrTable = renderAttributesAsTable(
  2085. ocrData,
  2086. 'OCR Results',
  2087. mandatoryData
  2088. );
  2089. // combinedAttributesContainer.appendChild(ocrTable);
  2090. }
  2091. // Render Visuals Table (Conditional based on data existence)
  2092. if (Object.keys(visualsData).length > 0) {
  2093. const visualsTable = renderAttributesAsTable(
  2094. visualsData,
  2095. 'Visual Results',
  2096. mandatoryData
  2097. );
  2098. // combinedAttributesContainer.appendChild(visualsTable);
  2099. }
  2100. // content.appendChild(combinedAttributesContainer);
  2101. }
  2102. // --- Summary Counts ---
  2103. const mandCount = Object.keys(mandatoryData).length;
  2104. const addCount = Object.keys(additionalData).length;
  2105. const ocrExtractedCount = Object.keys(ocrData).length;
  2106. const visualExtractedCount = Object.keys(visualsData).length;
  2107. const counts = el('div', 'attribute-summary-pills');
  2108. const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
  2109. const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
  2110. const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
  2111. const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
  2112. counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  2113. // content.appendChild(counts);
  2114. // Final assembly and insertion
  2115. td.appendChild(content);
  2116. detail.appendChild(td);
  2117. baseRow.insertAdjacentElement('afterend', detail);
  2118. // Extract mandatory values for highlighting
  2119. // const mandatoryValues = Object.values(mandatoryData)
  2120. // .map(v => v?.value?.toString()?.trim())
  2121. // .filter(Boolean);
  2122. // const attrConfig = attributesFullData.find(item => item.attribute_name === key);
  2123. const mandatoryValues = Object.values(mandatoryData)
  2124. // 1. Use flatMap to iterate over the outer array AND flatten the inner arrays.
  2125. // 'arr' here is the array like [ { value: 'Pullover', ... } ]
  2126. .flatMap(arr =>
  2127. // 2. Map the inner array. We safely assume the first element [0]
  2128. // holds the value we want.
  2129. arr.map(item => item?.value?.toString()?.trim())
  2130. )
  2131. // 3. Filter out any potential undefined/null/empty string results.
  2132. .filter(Boolean);
  2133. // Highlight in Product Name
  2134. const nameCell = baseRow.querySelector('td:nth-child(3)');
  2135. if (nameCell) {
  2136. nameCell.innerHTML = highlightMatches(nameCell.textContent, mandatoryValues);
  2137. }
  2138. // Highlight in Short Description
  2139. const descCell = baseRow.querySelector('td:nth-child(6)');
  2140. if (descCell) {
  2141. const shortDescDiv = descCell.querySelector('.short-desc');
  2142. if (shortDescDiv) {
  2143. shortDescDiv.innerHTML = highlightMatches(shortDescDiv.innerHTML, mandatoryValues);
  2144. }
  2145. }
  2146. const desclongCell = baseRow.querySelector('td:nth-child(6)');
  2147. if (desclongCell) {
  2148. const longDescDiv = desclongCell.querySelector('.long-desc');
  2149. if (longDescDiv) {
  2150. longDescDiv.innerHTML = highlightMatches(longDescDiv.innerHTML, mandatoryValues);
  2151. }
  2152. }
  2153. });
  2154. // Update summary statistics
  2155. $('#statTotal').textContent = api.total_products ?? 0;
  2156. $('#statOk').textContent = api.successful ?? 0;
  2157. $('#statKo').textContent = api.failed ?? 0;
  2158. const apiSummary = $('#api-summary');
  2159. if (apiSummary) apiSummary.style.display = 'block';
  2160. }
  2161. // working one
  2162. function applyHighlightingToTableRow(baseRow, mandatoryValues) {
  2163. const nameCell = baseRow.querySelector('td:nth-child(3)');
  2164. if (nameCell) {
  2165. nameCell.innerHTML = highlightMatches(nameCell.textContent, mandatoryValues);
  2166. }
  2167. const descCell = baseRow.querySelector('td:nth-child(6)');
  2168. if (descCell) {
  2169. const shortDescDiv = descCell.querySelector('.short-desc');
  2170. if (shortDescDiv) {
  2171. shortDescDiv.innerHTML = highlightMatches(shortDescDiv.innerHTML, mandatoryValues);
  2172. }
  2173. }
  2174. }
  2175. function renderInlineAttributes() {
  2176. if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
  2177. // renderInlineForCards();
  2178. // renderInlineForTable();
  2179. }
  2180. // --- Main rendering ---
  2181. function renderProducts() {
  2182. if (layoutMode === 'cards') {
  2183. $('#cardsContainer').style.display = '';
  2184. $('#tableContainer').style.display = 'none';
  2185. // console.log("PRODUCT_BASE",PRODUCT_BASE);
  2186. renderProductsCards();
  2187. } else {
  2188. $('#cardsContainer').style.display = 'none';
  2189. $('#tableContainer').style.display = '';
  2190. renderProductsTable();
  2191. }
  2192. updateSelectionInfo();
  2193. renderPagination();
  2194. // If there is a selection, re-render inline attributes (persist across toggle)
  2195. if (selectedProductsWithAttributes.length > 0) renderInlineAttributes();
  2196. }
  2197. // --- Submit & Reset ---
  2198. function submitAttributes() {
  2199. // Check the length of the new array
  2200. if (selectedProductsWithAttributes.length === 0) {
  2201. alert('Please select at least one product.');
  2202. return;
  2203. }
  2204. // if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
  2205. // console.log("selectedIds",selectedIds);
  2206. jQuery('#full-page-loader').show();
  2207. // let inputArray = {
  2208. // "product_ids" : [...selectedIds]
  2209. // }
  2210. const extractAdditional = document.getElementById('extract_additional').checked;
  2211. const processImage = document.getElementById('process_image').checked;
  2212. // const selectedMultiples = document.getElementById('#mandatory-attributes');
  2213. // const selectedValues = Array.from(selectedMultiples.selectedOptions).map(option => option.value);
  2214. const selectElement = document.getElementById('mandatory-attributes');
  2215. const selectedValues = Array.from(selectElement.selectedOptions).map(option => option.value);
  2216. // console.log(selectedValues); // Logs an array of selected values
  2217. // console.log("thresholdValueDisplay",thresholdValueDisplay.value);
  2218. const threshold = parseFloat(document.getElementById('thresholdRange').value);
  2219. // Transform the new state array into the required API format
  2220. const itemIds = selectedProductsWithAttributes.map(p => p.item_id);
  2221. // Create the mandatory_attrs map: { item_id: { attr_name: [values] } }
  2222. // NOTE: The backend API you showed expects a flattened list of "mandatory_attrs"
  2223. // like: { "color": ["color", "shade"], "size": ["size", "fit"] }
  2224. // It seems to ignore the selected product-specific values and uses a general list of synonyms.
  2225. // Assuming the request needs a general map of *all unique* selected attributes across all selected products:
  2226. let mandatoryAttrsMap = {};
  2227. selectedProductsWithAttributes.forEach(product => {
  2228. // Merge attributes from all selected products
  2229. Object.assign(mandatoryAttrsMap, product.mandatory_attrs);
  2230. });
  2231. // If the API expects the complex, product-specific payload from your Q1 example:
  2232. const payloadForQ1 = selectedProductsWithAttributes.map(p => ({
  2233. item_id: p.item_id,
  2234. mandatory_attrs: p.mandatory_attrs
  2235. }));
  2236. let inputArray = {
  2237. "products": payloadForQ1,
  2238. "model": "llama-3.1-8b-instant",
  2239. "extract_additional": extractAdditional,
  2240. "process_image": processImage,
  2241. "multiple": selectedValues,
  2242. "threshold_abs": 0.6, // Lower threshold to be more permissive
  2243. // "margin": 0.3, // Larger margin to include more candidates
  2244. // "use_adaptive_margin": true,
  2245. // "use_semantic_clustering": true
  2246. }
  2247. let raw = JSON.stringify(inputArray);
  2248. fetch('/attr/batch-extract/', {
  2249. method: 'POST', // or 'POST' if your API expects POST
  2250. headers: {
  2251. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
  2252. 'Content-Type': "application/json"
  2253. },
  2254. body: raw
  2255. })
  2256. .then(response => response.json())
  2257. .then(async data => {
  2258. await delay(5000); // waits for 3 seconds
  2259. // console.log("response data",data);
  2260. API_RESPONSE_AI = data;
  2261. renderInlineAttributes();
  2262. jQuery('#full-page-loader').hide();
  2263. });
  2264. }
  2265. function resetAll() {
  2266. selectedProductsWithAttributes = []; // Reset the main array
  2267. // selectedIds.clear();
  2268. lastSeen.clear();
  2269. renderProducts();
  2270. // Clear summary
  2271. document.getElementById('statTotal').textContent = '0';
  2272. document.getElementById('statOk').textContent = '0';
  2273. document.getElementById('statKo').textContent = '0';
  2274. $('#api-summary').style.display = 'none';
  2275. // ✅ Clear Select2 selections
  2276. jQuery('#mandatory-attributes').val(null).trigger('change');
  2277. // ✅ Reset threshold input (and display)
  2278. const thresholdInput = document.getElementById('thresholdRange');
  2279. const thresholdDisplay = document.getElementById('thresholdValue');
  2280. thresholdInput.value = '0.65'; // or any default value you prefer
  2281. if (thresholdDisplay) {
  2282. thresholdDisplay.textContent = '0.65';
  2283. }
  2284. }
  2285. function setLayout(mode) {
  2286. layoutMode = mode;
  2287. const btnCards = document.getElementById('btnCards');
  2288. const btnTable = document.getElementById('btnTable');
  2289. if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
  2290. else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
  2291. renderProducts();
  2292. }
  2293. // Upload elements (Bootstrap modal version)
  2294. const uploadModalEl = document.getElementById('uploadModal');
  2295. const dropzone = document.getElementById('dropzone');
  2296. const uploadFiles = document.getElementById('uploadFiles');
  2297. const fileInfo = document.getElementById('fileInfo');
  2298. const uploadBar = document.getElementById('uploadBar');
  2299. const uploadStatus = document.getElementById('uploadStatus');
  2300. // Reset modal on show
  2301. uploadModalEl.addEventListener('shown.bs.modal', () => {
  2302. uploadStatus.textContent = '';
  2303. uploadStatus.className = ''; // clear success/error class
  2304. uploadBar.style.width = '0%';
  2305. uploadBar.setAttribute('aria-valuenow', '0');
  2306. uploadFiles.value = '';
  2307. uploadFiles.setAttribute('accept', ACCEPT_TYPES);
  2308. fileInfo.textContent = 'No files selected.';
  2309. });
  2310. function describeFiles(list) {
  2311. if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
  2312. const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
  2313. fileInfo.textContent = names.join(', ');
  2314. }
  2315. // Drag & drop feedback
  2316. ['dragenter','dragover'].forEach(evt => {
  2317. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
  2318. });
  2319. ['dragleave','drop'].forEach(evt => {
  2320. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
  2321. });
  2322. // Handle drop
  2323. dropzone.addEventListener('drop', e => {
  2324. uploadFiles.files = e.dataTransfer.files;
  2325. describeFiles(uploadFiles.files);
  2326. });
  2327. // Click to browse
  2328. // dropzone.addEventListener('click', () => uploadFiles.click());
  2329. // Picker change
  2330. uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
  2331. function startUpload() {
  2332. const files = uploadFiles.files;
  2333. if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
  2334. jQuery('#full-page-loader').show();
  2335. uploadStatus.textContent = 'Uploading...';
  2336. uploadStatus.className = ''; // neutral
  2337. uploadBar.style.width = '0%';
  2338. uploadBar.setAttribute('aria-valuenow', '0');
  2339. const form = new FormData();
  2340. Array.from(files).forEach(f => form.append('file', f));
  2341. // form.append('uploaded_by', 'Vishal'); // example extra field
  2342. const xhr = new XMLHttpRequest();
  2343. xhr.open('POST', UPLOAD_API_URL, true);
  2344. // If you need auth:
  2345. // xhr.setRequestHeader('Authorization', 'Bearer <token>');
  2346. xhr.upload.onprogress = (e) => {
  2347. if (e.lengthComputable) {
  2348. const pct = Math.round((e.loaded / e.total) * 100);
  2349. uploadBar.style.width = pct + '%';
  2350. uploadBar.setAttribute('aria-valuenow', String(pct));
  2351. }
  2352. };
  2353. xhr.onreadystatechange = () => {
  2354. if (xhr.readyState === 4) {
  2355. const ok = (xhr.status >= 200 && xhr.status < 300);
  2356. try {
  2357. const resp = JSON.parse(xhr.responseText || '{}');
  2358. uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
  2359. } catch {
  2360. uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
  2361. }
  2362. uploadStatus.className = ok ? 'success' : 'error';
  2363. // Optional: auto-close the modal on success after 1.2s:
  2364. // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
  2365. }
  2366. };
  2367. xhr.onerror = () => {
  2368. uploadStatus.textContent = 'Network error during upload.';
  2369. uploadStatus.className = 'error';
  2370. };
  2371. xhr.send(form);
  2372. setTimeout(()=>{
  2373. jQuery('#uploadModal').modal('hide');
  2374. window.location.reload();
  2375. },3000)
  2376. jQuery('#full-page-loader').hide();
  2377. }
  2378. // Wire Start button
  2379. document.getElementById('uploadStart').addEventListener('click', startUpload);
  2380. // Cancel button already closes the modal via data-bs-dismiss
  2381. // --- Pagination state ---
  2382. let page = 1;
  2383. let pageSize = 50; // default rows per page
  2384. function totalPages() {
  2385. return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
  2386. }
  2387. function clampPage() {
  2388. page = Math.min(Math.max(1, page), totalPages());
  2389. }
  2390. function getCurrentSlice() {
  2391. clampPage();
  2392. const start = (page - 1) * pageSize;
  2393. return PRODUCT_BASE.slice(start, start + pageSize);
  2394. }
  2395. function renderPagination() {
  2396. const bar = document.getElementById('paginationBar');
  2397. if (!bar) return;
  2398. const tp = totalPages();
  2399. clampPage();
  2400. bar.innerHTML = `
  2401. <div class="page-size">
  2402. <label for="pageSizeSelect">Rows per page</label>
  2403. <select id="pageSizeSelect">
  2404. <option value="5" ${pageSize===5 ? 'selected' : ''}>5</option>
  2405. <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
  2406. <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
  2407. <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
  2408. <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
  2409. </select>
  2410. </div>
  2411. <div class="pager">
  2412. <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
  2413. <span class="page-info">Page ${page} of ${tp}</span>
  2414. <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
  2415. </div>
  2416. `;
  2417. // wire events
  2418. document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
  2419. document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
  2420. const sel = document.getElementById('pageSizeSelect');
  2421. if (sel) {
  2422. sel.addEventListener('change', () => {
  2423. const val = sel.value;
  2424. pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
  2425. page = 1; // reset to first page when size changes
  2426. renderProducts();
  2427. });
  2428. }
  2429. }
  2430. // Function to add/remove product from the state and manage its attributes
  2431. function toggleProductSelection(itemId, isChecked, attributes = {}) {
  2432. const index = selectedProductsWithAttributes.findIndex(p => p.item_id === itemId);
  2433. // console.log("index",index);
  2434. if (isChecked) {
  2435. // If selecting, ensure the product object exists in the array
  2436. if (index === -1) {
  2437. selectedProductsWithAttributes.push({
  2438. item_id: itemId,
  2439. mandatory_attrs: attributes
  2440. });
  2441. } else {
  2442. // Update attributes if the product is already selected
  2443. selectedProductsWithAttributes[index].mandatory_attrs = attributes;
  2444. }
  2445. } else {
  2446. // If deselecting, remove the product object from the array
  2447. if (index !== -1) {
  2448. selectedProductsWithAttributes.splice(index, 1);
  2449. }
  2450. }
  2451. updateSelectionInfo();
  2452. }
  2453. // Function to get the current mandatory attributes for a selected item
  2454. function getSelectedAttributes(itemId) {
  2455. const productEntry = selectedProductsWithAttributes.find(p => p.item_id === itemId);
  2456. return productEntry ? productEntry.mandatory_attrs : {};
  2457. }
  2458. // Helper to check if a product is selected
  2459. function isProductSelected(itemId) {
  2460. return selectedProductsWithAttributes.some(p => p.item_id === itemId);
  2461. }
  2462. // Helper to check if a specific attribute/value is selected
  2463. function isAttributeValueSelected(itemId, attrName, value) {
  2464. const attrs = getSelectedAttributes(itemId);
  2465. const values = attrs[attrName];
  2466. return values ? values.includes(value) : false; // Default all selected when first loaded
  2467. }
  2468. // $('.attribute-select').select2({
  2469. // placeholder: 'Select product attributes'
  2470. // });
  2471. function getAtributeList(){
  2472. jQuery('#full-page-loader').show();
  2473. try{
  2474. fetch('/attr/products/attributes', {
  2475. method: 'GET', // or 'POST' if your API expects POST
  2476. headers: {
  2477. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
  2478. }
  2479. })
  2480. .then(response => response.json())
  2481. .then(data => {
  2482. // console.log("data",data);
  2483. attributesFullData = data;
  2484. let attributesData = data;
  2485. // Step 1: Extract unique mandatory attribute names
  2486. const mandatoryAttributes = [...new Set(
  2487. attributesData
  2488. .filter(attr => attr?.is_mandatory === "Yes")
  2489. .map(attr => attr?.attribute_name)
  2490. )];
  2491. // Step 2: Populate the select element
  2492. const $select = jQuery('#mandatory-attributes');
  2493. $select.append(new Option("Select All", "select_all")); // Add "Select All" option first
  2494. mandatoryAttributes.forEach(attr => {
  2495. $select.append(new Option(attr, attr));
  2496. });
  2497. // Step 3: Initialize Select2 with placeholder
  2498. // $select.select2({
  2499. // placeholder: "Select mandatory attributes",
  2500. // allowClear: true
  2501. // });
  2502. // Step 4: Handle 'Select All' logic
  2503. $select.on('select2:select', function (e) {
  2504. if (e.params.data.id === "select_all") {
  2505. // Select all real options except "Select All"
  2506. const allOptions = mandatoryAttributes;
  2507. $select.val(allOptions).trigger('change');
  2508. }
  2509. });
  2510. jQuery('#full-page-loader').hide();
  2511. });
  2512. }catch(err){
  2513. console.log("err",err);
  2514. jQuery('#full-page-loader').hide();
  2515. }
  2516. }
  2517. document.addEventListener("DOMContentLoaded", function () {
  2518. // Update span when range changes
  2519. thresholdInput.addEventListener('input', function () {
  2520. // console.log("this.value",this.value);
  2521. thresholdValueDisplay.textContent = this.value;
  2522. });
  2523. });
  2524. // Get threshold value when needed
  2525. function getThreshold() {
  2526. // console.log("parseFloat(thresholdInput.value)",parseFloat(thresholdInput.value));
  2527. return parseFloat(thresholdInput.value);
  2528. }
  2529. /**
  2530. * Renders Mandatory attributes using a card-based comparison layout.
  2531. * Highlights mismatches prominently.
  2532. * @param {Object} attributes - The mandatory attribute data.
  2533. * @param {string} title - The title for the section.
  2534. * @returns {HTMLElement} A div containing the comparison cards.
  2535. */
  2536. function renderMandatoryComparisonCards(attributes, title) {
  2537. const section = el('div', 'attribute-section');
  2538. // --- 1. Flatten Mandatory Attributes ---
  2539. let attributeEntries = [];
  2540. Object.keys(attributes).forEach(key => {
  2541. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2542. valuesArray.forEach(v => {
  2543. const aiValue = v.value || 'N/A';
  2544. const originalValue = v.original_value || 'N/A';
  2545. // Comparison is case-insensitive and ignores leading/trailing whitespace
  2546. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2547. attributeEntries.push({
  2548. name: key,
  2549. aiValue: aiValue,
  2550. originalValue: originalValue,
  2551. isMatch: isMatch,
  2552. source: v.source || 'N/A'
  2553. });
  2554. });
  2555. });
  2556. // --- 2. Section Header ---
  2557. const titleEl = el('div', 'section-title');
  2558. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2559. section.appendChild(titleEl);
  2560. if (attributeEntries.length === 0) {
  2561. const msg = el('p', 'no-attributes-message');
  2562. msg.textContent = `No ${title.toLowerCase()} found.`;
  2563. section.appendChild(msg);
  2564. return section;
  2565. }
  2566. // --- 3. Card Container ---
  2567. const cardsContainer = el('div', 'comparison-cards-container');
  2568. attributeEntries.forEach(attr => {
  2569. // Main Card Element
  2570. const card = el('div', `comparison-card ${attr?.isMatch ? 'match' : 'mismatch-card'}`);
  2571. // Card Header (Attribute Name)
  2572. const header = el('div', 'card-header');
  2573. header.textContent = attr?.name.replace(/_/g, ' ');
  2574. card.appendChild(header);
  2575. // Content Wrapper
  2576. const content = el('div', 'card-content');
  2577. // Existing Value Box
  2578. const originalBox = el('div', 'value-box original-box');
  2579. originalBox.innerHTML = `
  2580. <div class="value-label">Manually Identified Value</div>
  2581. <div class="value-text">${attr?.originalValue}</div>
  2582. `;
  2583. content.appendChild(originalBox);
  2584. // AI Value Box
  2585. const aiBox = el('div', `value-box ai-box ${attr?.isMatch ? 'found-value' : 'mismatch-value'}`);
  2586. aiBox.innerHTML = `
  2587. <div class="value-label">AI Generated Value <span class="value-source">(${attr?.source})</span></div>
  2588. <div class="value-text">${attr?.aiValue}</div>
  2589. `;
  2590. content.appendChild(aiBox);
  2591. card.appendChild(content);
  2592. // Mismatch Indicator (only visible on mismatch-card via CSS)
  2593. if (!attr?.isMatch) {
  2594. const indicator = el('div', 'mismatch-indicator');
  2595. // indicator.innerHTML = '❌ MISMATCH';
  2596. indicator.innerHTML = attr?.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2597. card.appendChild(indicator);
  2598. }
  2599. cardsContainer.appendChild(card);
  2600. });
  2601. section.appendChild(cardsContainer);
  2602. return section;
  2603. }
  2604. // Example JavaScript (Assuming you have access to API_RESPONSE_AI)
  2605. // document.getElementById('downloadResultBtn').addEventListener('click', () => {
  2606. // // 1. Convert the data to a JSON string
  2607. // const jsonString = JSON.stringify(API_RESPONSE_AI, null, 2);
  2608. // // 2. Create a Blob from the JSON string
  2609. // const blob = new Blob([jsonString], { type: 'application/json' });
  2610. // // 3. Create a temporary URL and link element
  2611. // const url = URL.createObjectURL(blob);
  2612. // const a = document.createElement('a');
  2613. // // 4. Set download attributes
  2614. // a.href = url;
  2615. // a.download = 'api_generated_results.json';
  2616. // // 5. Simulate a click to trigger download
  2617. // document.body.appendChild(a);
  2618. // a.click();
  2619. // // 6. Clean up
  2620. // document.body.removeChild(a);
  2621. // URL.revokeObjectURL(url);
  2622. // });
  2623. /**
  2624. * Renders Mandatory attributes using a card-based comparison layout.
  2625. * Highlights mismatches prominently.
  2626. * @param {Object} attributes - The mandatory attribute data.
  2627. * @param {string} title - The title for the section (used for the header).
  2628. * @returns {HTMLElement} A div containing the comparison cards.
  2629. */
  2630. // function renderMandatoryComparisonCards(attributes, title) {
  2631. // const section = el('div', 'attribute-section mandatory-comparison-section');
  2632. // // --- 1. Flatten Mandatory Attributes ---
  2633. // let attributeEntries = [];
  2634. // Object.keys(attributes).forEach(key => {
  2635. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2636. // valuesArray.forEach(v => {
  2637. // const aiValue = v.value || 'N/A';
  2638. // const originalValue = v.original_value || 'N/A';
  2639. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2640. // attributeEntries.push({
  2641. // name: key,
  2642. // aiValue: aiValue,
  2643. // originalValue: originalValue,
  2644. // isMatch: isMatch,
  2645. // source: v.source || 'N/A'
  2646. // });
  2647. // });
  2648. // });
  2649. // // --- 2. Section Header ---
  2650. // const titleEl = el('div', 'section-title');
  2651. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2652. // section.appendChild(titleEl);
  2653. // if (attributeEntries.length === 0) {
  2654. // const msg = el('p', 'no-attributes-message');
  2655. // msg.textContent = `No ${title.toLowerCase()} found.`;
  2656. // section.appendChild(msg);
  2657. // return section;
  2658. // }
  2659. // // --- 3. Card Container ---
  2660. // const cardsContainer = el('div', 'comparison-cards-container');
  2661. // attributeEntries.forEach(attr => {
  2662. // const card = el('div', `comparison-card ${attr?.isMatch ? 'match' : 'mismatch-card'}`);
  2663. // const header = el('div', 'card-header');
  2664. // header.textContent = attr?.name.replace(/_/g, ' ');
  2665. // card.appendChild(header);
  2666. // const content = el('div', 'card-content');
  2667. // // Existing Value Box
  2668. // const originalBox = el('div', 'value-box original-box');
  2669. // originalBox.innerHTML = `
  2670. // <div class="value-label">Manually Identified Value</div>
  2671. // <div class="value-text">${attr?.originalValue}</div>
  2672. // `;
  2673. // content.appendChild(originalBox);
  2674. // // AI Value Box
  2675. // const aiBox = el('div', `value-box ai-box ${attr?.isMatch ? 'found-value' : 'mismatch-value'}`);
  2676. // aiBox.innerHTML = `
  2677. // <div class="value-label">AI Generated Value <span class="value-source">(${attr?.source})</span></div>
  2678. // <div class="value-text">${attr?.aiValue}</div>
  2679. // `;
  2680. // content.appendChild(aiBox);
  2681. // card.appendChild(content);
  2682. // // Mismatch Indicator
  2683. // if (!attr?.isMatch) {
  2684. // const indicator = el('div', 'mismatch-indicator');
  2685. // // indicator.innerHTML = '❌ MISMATCH';
  2686. // indicator.innerHTML = attr?.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2687. // card.appendChild(indicator);
  2688. // }
  2689. // cardsContainer.appendChild(card);
  2690. // });
  2691. // section.appendChild(cardsContainer);
  2692. // return section;
  2693. // }
  2694. function renderMandatoryComparisonCards(attributes, title) {
  2695. const section = el('div', 'attribute-section mandatory-comparison-section');
  2696. // --- 1. Flatten Mandatory Attributes ---
  2697. let attributeEntries = [];
  2698. Object.keys(attributes).forEach(key => {
  2699. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2700. valuesArray.forEach(v => {
  2701. const aiValue = v.value || 'N/A';
  2702. const originalValue = v.original_value || 'N/A';
  2703. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2704. attributeEntries.push({
  2705. name: key,
  2706. aiValue: aiValue,
  2707. originalValue: originalValue,
  2708. isMatch: isMatch,
  2709. source: v.source || 'N/A'
  2710. });
  2711. });
  2712. });
  2713. // --- 2. Section Header ---
  2714. const titleEl = el('div', 'section-title');
  2715. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2716. section.appendChild(titleEl);
  2717. if (attributeEntries.length === 0) {
  2718. const msg = el('p', 'no-attributes-message');
  2719. msg.textContent = `No ${title.toLowerCase()} found.`;
  2720. section.appendChild(msg);
  2721. return section;
  2722. }
  2723. // --- 3. Card Container ---
  2724. const cardsContainer = el('div', 'comparison-cards-container');
  2725. attributeEntries.forEach(attr => {
  2726. // --- CHANGE 1: Apply 'match-card' or 'mismatch-card' explicitly ---
  2727. const cardClass = attr?.isMatch ? 'match-card' : 'mismatch-card';
  2728. const card = el('div', `comparison-card ${cardClass}`);
  2729. const header = el('div', 'card-header');
  2730. header.textContent = attr?.name.replace(/_/g, ' ');
  2731. card.appendChild(header);
  2732. const content = el('div', 'card-content');
  2733. // Existing Value Box
  2734. const originalBox = el('div', 'value-box original-box');
  2735. originalBox.innerHTML = `
  2736. <div class="value-label">Manually Identified Value</div>
  2737. <div class="value-text">${attr?.originalValue}</div>
  2738. `;
  2739. content.appendChild(originalBox);
  2740. // AI Value Box
  2741. // Removed 'found-value' class here as styling should rely on the parent card class
  2742. const aiBox = el('div', `value-box ai-box ${attr?.isMatch ? '' : 'mismatch-value'}`);
  2743. aiBox.innerHTML = `
  2744. <div class="value-label">AI Generated Value <span class="value-source">(${attr?.source})</span></div>
  2745. <div class="value-text">${attr?.aiValue}</div>
  2746. `;
  2747. content.appendChild(aiBox);
  2748. card.appendChild(content);
  2749. // --- CHANGE 2: Display the indicator for ALL cards, controlling color via CSS ---
  2750. const indicator = el('div', 'match-status-indicator');
  2751. indicator.innerHTML = attr?.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2752. card.appendChild(indicator);
  2753. cardsContainer.appendChild(card);
  2754. });
  2755. section.appendChild(cardsContainer);
  2756. return section;
  2757. }
  2758. /**
  2759. * Renders Additional, OCR, or Visual attributes in a simple card layout.
  2760. * @param {Object} attributes - The attribute data (Additional, OCR, or Visual).
  2761. * @param {string} title - The title for the section.
  2762. * @returns {HTMLElement} A div containing the attribute cards.
  2763. */
  2764. function renderSimpleAttributeCards(attributes, title) {
  2765. const section = el('div', 'attribute-section simple-attribute-section');
  2766. // --- 1. Flatten Attributes ---
  2767. let attributeEntries = [];
  2768. const processAttribute = (key, values) => {
  2769. const valuesArray = Array.isArray(values) ? values : [values];
  2770. valuesArray.forEach(v => {
  2771. attributeEntries.push({
  2772. name: key,
  2773. value: v.value,
  2774. source: v.source || 'N/A'
  2775. });
  2776. });
  2777. };
  2778. Object.keys(attributes).forEach(key => {
  2779. const attribute = attributes[key];
  2780. if (Array.isArray(attribute)) {
  2781. processAttribute(key, attribute);
  2782. } else if (typeof attribute === 'object' && attribute !== null) {
  2783. Object.keys(attribute).forEach(subKey => {
  2784. const subAttribute = attribute[subKey];
  2785. if (Array.isArray(subAttribute)) {
  2786. processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  2787. }
  2788. });
  2789. }
  2790. });
  2791. // --- 2. Section Header ---
  2792. const titleEl = el('div', 'section-title');
  2793. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2794. section.appendChild(titleEl);
  2795. if (attributeEntries.length === 0) {
  2796. const msg = el('p', 'no-attributes-message');
  2797. msg.textContent = `No ${title.toLowerCase()} found.`;
  2798. section.appendChild(msg);
  2799. return section;
  2800. }
  2801. // --- 3. Card Container ---
  2802. const cardsContainer = el('div', 'comparison-cards-container simple-cards-container');
  2803. attributeEntries.forEach(attr => {
  2804. // Simple Card Element
  2805. const card = el('div', 'simple-card');
  2806. // Card Header (Attribute Name)
  2807. const header = el('div', 'card-header');
  2808. header.textContent = formatString(attr?.name).replace(/_/g, ' ');
  2809. card.appendChild(header);
  2810. // Content Wrapper
  2811. const content = el('div', 'card-content');
  2812. // Value Box
  2813. const valueBox = el('div', 'value-box single-value-box');
  2814. const displayValue = Array.isArray(attr?.value)
  2815. ? (attr?.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr?.source)+ ')'
  2816. : formatString(attr?.value) +'('+ formatString(attr?.source)+ ')';
  2817. // : attr?.value;
  2818. valueBox.innerHTML = `
  2819. <div class="value-label">Extracted Value <span class="value-source">(${formatString(attr?.source)})</span></div>
  2820. <div class="value-text">${displayValue || 'N/A'}</div>
  2821. `;
  2822. content.appendChild(valueBox);
  2823. card.appendChild(content);
  2824. cardsContainer.appendChild(card);
  2825. });
  2826. section.appendChild(cardsContainer);
  2827. return section;
  2828. }
  2829. function delay(ms) {
  2830. return new Promise(resolve => setTimeout(resolve, ms));
  2831. }