attr-extraction.js 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120
  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. let attributeEntries = [];
  1234. // --- Build attributeEntries ---
  1235. Object.keys(attributes).forEach(key => {
  1236. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1237. valuesArray.forEach(v => {
  1238. const aiValue = v.value || 'N/A';
  1239. const originalValue = v.original_value || 'N/A';
  1240. const source = v.source || 'N/A';
  1241. const reason = v.reason || 'N/A';
  1242. // Find possible values for this attribute from full data
  1243. const attrConfig = attributesFullData.find(item => item.attribute_name === key);
  1244. let possibleValues = [];
  1245. if (attrConfig && attrConfig.possible_values) {
  1246. possibleValues = attrConfig.possible_values.split(',').map(s => s.trim());
  1247. }
  1248. // Determine match flag
  1249. const isFoundInPossible = possibleValues.includes(aiValue);
  1250. const matchFlag = isFoundInPossible ? true : false;
  1251. attributeEntries.push({
  1252. name: key,
  1253. aiValue: aiValue,
  1254. possibleValues: possibleValues,
  1255. originalValue: originalValue,
  1256. source: source,
  1257. isMatch: matchFlag,
  1258. reason: reason
  1259. });
  1260. });
  1261. });
  1262. // --- Section title ---
  1263. const titleEl = el('div', 'section-title');
  1264. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1265. section.appendChild(titleEl);
  1266. if (attributeEntries.length === 0) {
  1267. const msg = el('p', 'no-attributes-message');
  1268. msg.textContent = `No ${title.toLowerCase()} found.`;
  1269. section.appendChild(msg);
  1270. return section;
  1271. }
  1272. // --- Split attributes in half ---
  1273. const midIndex = Math.ceil(attributeEntries.length / 2);
  1274. const leftAttributes = attributeEntries.slice(0, midIndex);
  1275. const rightAttributes = attributeEntries.slice(midIndex);
  1276. // --- Create a container for two tables ---
  1277. const tableContainer = el('div', 'two-column-table-container');
  1278. // Helper function to build a table
  1279. function buildTable(attrArray) {
  1280. const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1281. const table = el('table', 'attribute-detail-table comparison-table');
  1282. const thead = el('thead');
  1283. const headerRow = el('tr');
  1284. ['Attribute Name', 'AI Generated Value', 'Action'].forEach(text => {
  1285. const th = el('th');
  1286. th.textContent = text;
  1287. headerRow.appendChild(th);
  1288. });
  1289. thead.appendChild(headerRow);
  1290. table.appendChild(thead);
  1291. const tbody = el('tbody');
  1292. attrArray.forEach(attr => {
  1293. const row = el('tr', attr.isMatch ? 'match-row' : 'mismatch-row');
  1294. // Attribute name
  1295. const nameTd = el('td', 'attribute-name');
  1296. nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1297. row.appendChild(nameTd);
  1298. // AI Value display
  1299. // AI Value cell with info icon
  1300. const aiValueTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1301. // Create a wrapper for text and icon
  1302. const aiValueWrapper = document.createElement('div');
  1303. aiValueWrapper.style.display = 'flex';
  1304. aiValueWrapper.style.alignItems = 'center';
  1305. aiValueWrapper.style.gap = '6px';
  1306. // Text node
  1307. const valueText = document.createElement('span');
  1308. valueText.textContent = formatString(attr.aiValue);
  1309. aiValueWrapper.appendChild(valueText);
  1310. // Info icon (Bootstrap Icons)
  1311. if (attr.reason && attr.reason.trim() !== '') {
  1312. const infoIcon = document.createElement('i');
  1313. infoIcon.className = 'bi bi-info-circle';
  1314. infoIcon.style.cursor = 'pointer';
  1315. infoIcon.setAttribute('title', attr.reason); // Tooltip on hover
  1316. infoIcon.style.color = '#0d6efd'; // Bootstrap blue
  1317. aiValueWrapper.appendChild(infoIcon);
  1318. }
  1319. aiValueTd.appendChild(aiValueWrapper);
  1320. row.appendChild(aiValueTd);
  1321. // const aiValueTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1322. // aiValueTd.textContent = formatString(attr.aiValue);
  1323. // row.appendChild(aiValueTd);
  1324. // Dropdown
  1325. // const aiTd = el('td', 'attribute-source');
  1326. // const select = document.createElement('select');
  1327. // select.classList.add('select2-dropdown');
  1328. // select.setAttribute('data-attribute', attr.name);
  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.id = 'manually-attributes'; // You may want to make this unique per row
  1334. select.name = 'manuallyUpdatedAttributes[]';
  1335. // select.setAttribute('aria-labelledby', 'select a attribute for which multiple data required');
  1336. select.setAttribute('multiple', 'multiple');
  1337. // select.style.width = '100%';
  1338. select.setAttribute('data-attribute', attr.name);
  1339. // Populate options
  1340. attr.possibleValues.forEach(val => {
  1341. const option = document.createElement('option');
  1342. option.value = val;
  1343. option.textContent = val;
  1344. if (val === attr.aiValue) option.selected = true;
  1345. select.appendChild(option);
  1346. });
  1347. // if (!attr.isMatch && attr.aiValue !== 'N/A') {
  1348. // const newOpt = document.createElement('option');
  1349. // newOpt.value = attr.aiValue;
  1350. // newOpt.textContent = attr.aiValue; // + " (new)";
  1351. // newOpt.selected = true;
  1352. // select.appendChild(newOpt);
  1353. // }
  1354. aiTd.appendChild(select);
  1355. row.appendChild(aiTd);
  1356. tbody.appendChild(row);
  1357. // Initialize Select2
  1358. jQuery(select).select2({
  1359. tags: true,
  1360. width: 'resolve'
  1361. });
  1362. });
  1363. table.appendChild(tbody);
  1364. scrollWrapper.appendChild(table);
  1365. return scrollWrapper;
  1366. }
  1367. // --- Build and append both tables ---
  1368. const leftTable = buildTable(leftAttributes);
  1369. const rightTable = buildTable(rightAttributes);
  1370. tableContainer.appendChild(leftTable);
  1371. tableContainer.appendChild(rightTable);
  1372. section.appendChild(tableContainer);
  1373. return section;
  1374. }
  1375. // function renderMandatoryComparisonTable(attributes, title, productType) {
  1376. // const section = el('div', 'attribute-section');
  1377. // let attributeEntries = [];
  1378. // Object.keys(attributes).forEach(key => {
  1379. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1380. // valuesArray.forEach(v => {
  1381. // const aiValue = v.value || 'N/A';
  1382. // const originalValue = v.original_value || 'N/A';
  1383. // const source = v.source || 'N/A';
  1384. // // Find possible values for this attribute from `a`
  1385. // const attrConfig = attributesFullData.find(item =>
  1386. // item.attribute_name === key
  1387. // );
  1388. // let possibleValues = [];
  1389. // if (attrConfig && attrConfig.possible_values) {
  1390. // possibleValues = attrConfig.possible_values.split(',').map(s => s.trim());
  1391. // }
  1392. // // Determine if AI value exists in possible values
  1393. // const isFoundInPossible = possibleValues.includes(aiValue);
  1394. // const matchFlag = isFoundInPossible ? true : false;
  1395. // attributeEntries.push({
  1396. // name: key,
  1397. // aiValue: aiValue,
  1398. // possibleValues: possibleValues,
  1399. // originalValue: originalValue,
  1400. // source: source,
  1401. // isMatch: matchFlag
  1402. // });
  1403. // });
  1404. // });
  1405. // const titleEl = el('div', 'section-title');
  1406. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1407. // section.appendChild(titleEl);
  1408. // if (attributeEntries.length === 0) {
  1409. // const msg = el('p', 'no-attributes-message');
  1410. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1411. // section.appendChild(msg);
  1412. // return section;
  1413. // }
  1414. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1415. // const table = el('table', 'attribute-detail-table comparison-table');
  1416. // const thead = el('thead');
  1417. // const headerRow = el('tr');
  1418. // ['Attribute Name', 'AI Generated Value', 'Action'].forEach(text => {
  1419. // const th = el('th');
  1420. // th.textContent = text;
  1421. // headerRow.appendChild(th);
  1422. // });
  1423. // thead.appendChild(headerRow);
  1424. // table.appendChild(thead);
  1425. // const tbody = el('tbody');
  1426. // attributeEntries.forEach(attr => {
  1427. // const row = el('tr', attr.isMatch ? 'match-row' : 'mismatch-row');
  1428. // // 1. Attribute Name
  1429. // const nameTd = el('td', 'attribute-name');
  1430. // nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1431. // row.appendChild(nameTd);
  1432. // // 3. Source Column
  1433. // const sourceTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1434. // sourceTd.textContent = formatString(attr.aiValue);
  1435. // row.appendChild(sourceTd);
  1436. // // 2. AI Value Dropdown (Select2)
  1437. // const aiTd = el('td', 'attribute-source');
  1438. // const select = document.createElement('select');
  1439. // select.classList.add('select2-dropdown');
  1440. // select.setAttribute('data-attribute', attr.name);
  1441. // // Populate possible values
  1442. // attr.possibleValues.forEach(val => {
  1443. // const option = document.createElement('option');
  1444. // option.value = val;
  1445. // option.textContent = val;
  1446. // if (val === attr.aiValue) option.selected = true;
  1447. // select.appendChild(option);
  1448. // });
  1449. // // If not found in possible values, add it as a new option
  1450. // if (!attr.isMatch && attr.aiValue !== 'N/A') {
  1451. // const newOpt = document.createElement('option');
  1452. // newOpt.value = attr.aiValue;
  1453. // newOpt.textContent = attr.aiValue + " (new)";
  1454. // newOpt.selected = true;
  1455. // select.appendChild(newOpt);
  1456. // }
  1457. // aiTd.appendChild(select);
  1458. // row.appendChild(aiTd);
  1459. // tbody.appendChild(row);
  1460. // // Initialize Select2 after element is added
  1461. // jQuery(select).select2({
  1462. // tags: true, // allows new values
  1463. // width: 'resolve'
  1464. // });
  1465. // });
  1466. // table.appendChild(tbody);
  1467. // scrollWrapper.appendChild(table);
  1468. // section.appendChild(scrollWrapper);
  1469. // return section;
  1470. // }
  1471. // function renderMandatoryComparisonTable(attributes, title) {
  1472. // const section = el('div', 'attribute-section');
  1473. // let attributeEntries = [];
  1474. // Object.keys(attributes).forEach(key => {
  1475. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  1476. // valuesArray.forEach(v => {
  1477. // const aiValue = v.value || 'N/A';
  1478. // const originalValue = v.original_value || 'N/A';
  1479. // const source = v.source || 'N/A';
  1480. // // Comparison is case-insensitive and ignores leading/trailing whitespace
  1481. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  1482. // attributeEntries.push({
  1483. // name: key,
  1484. // aiValue: aiValue,
  1485. // originalValue: originalValue,
  1486. // source: source,
  1487. // isMatch: isMatch
  1488. // });
  1489. // });
  1490. // });
  1491. // const titleEl = el('div', 'section-title');
  1492. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1493. // section.appendChild(titleEl);
  1494. // if (attributeEntries.length === 0) {
  1495. // const msg = el('p', 'no-attributes-message');
  1496. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1497. // section.appendChild(msg);
  1498. // return section;
  1499. // }
  1500. // // --- SCROLL WRAPPER ADDITION ---
  1501. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1502. // const table = el('table', 'attribute-detail-table comparison-table');
  1503. // const thead = el('thead');
  1504. // const headerRow = el('tr');
  1505. // // Updated Headers for Comparison Table
  1506. // ['Attribute Name', 'AI Generated Value', 'Action'].forEach(text => {
  1507. // const th = el('th');
  1508. // th.textContent = text;
  1509. // headerRow.appendChild(th);
  1510. // });
  1511. // thead.appendChild(headerRow);
  1512. // table.appendChild(thead);
  1513. // const tbody = el('tbody');
  1514. // attributeEntries.forEach(attr => {
  1515. // // Highlight the entire row in red if the values do not match
  1516. // const row = el('tr', attr.isMatch ? 'match-row' : 'mismatch-row');
  1517. // // 1. Attribute Name
  1518. // const nameTd = el('td', 'attribute-name');
  1519. // nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1520. // row.appendChild(nameTd);
  1521. // // 3. AI Extracted Value
  1522. // const aiTd = el('td', `ai-value ${attr.isMatch ? '' : 'mismatch-value'}`);
  1523. // aiTd.textContent = attr.aiValue;
  1524. // row.appendChild(aiTd);
  1525. // // 4. Source
  1526. // const sourceTd = el('td', 'attribute-source');
  1527. // sourceTd.textContent = formatString(attr.source);
  1528. // row.appendChild(sourceTd);
  1529. // tbody.appendChild(row);
  1530. // });
  1531. // table.appendChild(tbody);
  1532. // scrollWrapper.appendChild(table); // Append table to wrapper
  1533. // section.appendChild(scrollWrapper); // Append wrapper to section
  1534. // return section;
  1535. // }
  1536. /**
  1537. * Renders a table for Additional, OCR, or Visual attributes (Name, Value, Source).
  1538. * @param {Object} attributes - The attribute data.
  1539. * @param {string} title - The title for the table section.
  1540. * @returns {HTMLElement} A div containing the table.
  1541. */
  1542. function renderAttributesAsTable(attributes, title, mandatoryData = null) {
  1543. const section = el('div', 'attribute-section');
  1544. let attributeEntries = [];
  1545. // --- STEP 1: Create a Set of all Mandatory Original Values (Normalized) ---
  1546. // A Set is used for fast lookups. Values are normalized (trimmed, lowercase)
  1547. const mandatoryOriginalValuesSet = new Set();
  1548. if (mandatoryData) {
  1549. Object.values(mandatoryData).forEach(attrArray => {
  1550. const originalValue = attrArray[0]?.original_value;
  1551. if (originalValue) {
  1552. mandatoryOriginalValuesSet.add(String(originalValue).trim().toLowerCase());
  1553. }
  1554. });
  1555. }
  1556. // Helper to extract attribute entries consistently
  1557. const processAttribute = (key, values) => {
  1558. const valuesArray = Array.isArray(values) ? values : [values];
  1559. valuesArray.forEach(v => {
  1560. attributeEntries.push({
  1561. name: key,
  1562. value: v.value,
  1563. source: v.source || 'N/A'
  1564. });
  1565. });
  1566. };
  1567. // Iterate through attributes (OCR/Visual/Additional) and flatten them
  1568. Object.keys(attributes).forEach(key => {
  1569. const attribute = attributes[key];
  1570. if (Array.isArray(attribute)) {
  1571. processAttribute(key, attribute);
  1572. } else if (typeof attribute === 'object' && attribute !== null) {
  1573. // Handle simple { "key": { "value": "X", "source": "Y" } } structure
  1574. if (attribute.value !== undefined) {
  1575. attributeEntries.push({
  1576. name: key,
  1577. value: attribute.value,
  1578. source: attribute.source || 'N/A'
  1579. });
  1580. } else {
  1581. // Handle nested objects
  1582. Object.keys(attribute).forEach(subKey => {
  1583. const subAttribute = attribute[subKey];
  1584. if (Array.isArray(subAttribute)) {
  1585. processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  1586. }
  1587. });
  1588. }
  1589. }
  1590. });
  1591. const titleEl = el('div', 'section-title');
  1592. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1593. section.appendChild(titleEl);
  1594. if (attributeEntries.length === 0) {
  1595. const msg = el('p', 'no-attributes-message');
  1596. msg.textContent = `No ${title.toLowerCase()} found.`;
  1597. section.appendChild(msg);
  1598. return section;
  1599. }
  1600. const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1601. const table = el('table', 'attribute-detail-table');
  1602. const thead = el('thead');
  1603. const headerRow = el('tr');
  1604. ['Attribute Name', 'Value'].forEach(text => {
  1605. const th = el('th');
  1606. th.textContent = text;
  1607. headerRow.appendChild(th);
  1608. });
  1609. thead.appendChild(headerRow);
  1610. table.appendChild(thead);
  1611. const tbody = el('tbody');
  1612. attributeEntries.forEach(attr => {
  1613. const row = el('tr');
  1614. // --- CORE COMPARISON LOGIC (Global Check) ---
  1615. let colorClass = '';
  1616. const hasMandatoryBaseline = mandatoryOriginalValuesSet.size > 0;
  1617. if (hasMandatoryBaseline) {
  1618. // Normalize the current attribute's value
  1619. const currentValueNormalized = String(attr.value).trim().toLowerCase();
  1620. // Check if the current value exists ANYWHERE in the mandatory original values set
  1621. if (mandatoryOriginalValuesSet.has(currentValueNormalized)) {
  1622. colorClass = 'green-text'; // Found a match in the global mandatory set
  1623. } else {
  1624. colorClass = 'red-text'; // Did NOT find a match
  1625. }
  1626. }
  1627. // --- END CORE COMPARISON LOGIC ---
  1628. const nameTd = el('td', 'attribute-name');
  1629. nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1630. row.appendChild(nameTd);
  1631. const valueTd = el('td', 'attribute-value');
  1632. const displayValue = formatString(attr.value) + ' (' + formatString(attr.source) + ')';
  1633. valueTd.textContent = displayValue || 'N/A';
  1634. // Apply the determined color class to the value cell
  1635. if (colorClass) {
  1636. valueTd.classList.add(colorClass);
  1637. }
  1638. row.appendChild(valueTd);
  1639. tbody.appendChild(row);
  1640. });
  1641. table.appendChild(tbody);
  1642. scrollWrapper.appendChild(table);
  1643. section.appendChild(scrollWrapper);
  1644. return section;
  1645. }
  1646. // function renderAttributesAsTable(attributes, title, mandatoryData = null) {
  1647. // const section = el('div', 'attribute-section');
  1648. // let attributeEntries = [];
  1649. // const processAttribute = (key, values) => {
  1650. // const valuesArray = Array.isArray(values) ? values : [values];
  1651. // valuesArray.forEach(v => {
  1652. // attributeEntries.push({
  1653. // name: key,
  1654. // value: v.value,
  1655. // source: v.source || 'N/A'
  1656. // });
  1657. // });
  1658. // };
  1659. // Object.keys(attributes).forEach(key => {
  1660. // const attribute = attributes[key];
  1661. // if (Array.isArray(attribute)) {
  1662. // processAttribute(key, attribute);
  1663. // } else if (typeof attribute === 'object' && attribute !== null) {
  1664. // Object.keys(attribute).forEach(subKey => {
  1665. // const subAttribute = attribute[subKey];
  1666. // if (Array.isArray(subAttribute)) {
  1667. // // Combines parent key (e.g., 'size') and sub-key (e.g., 'waist_size')
  1668. // processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  1669. // }
  1670. // });
  1671. // }
  1672. // });
  1673. // const titleEl = el('div', 'section-title');
  1674. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  1675. // section.appendChild(titleEl);
  1676. // if (attributeEntries.length === 0) {
  1677. // const msg = el('p', 'no-attributes-message');
  1678. // msg.textContent = `No ${title.toLowerCase()} found.`;
  1679. // section.appendChild(msg);
  1680. // return section;
  1681. // }
  1682. // // --- SCROLL WRAPPER ADDITION ---
  1683. // const scrollWrapper = el('div', 'attribute-scroll-wrapper');
  1684. // const table = el('table', 'attribute-detail-table');
  1685. // const thead = el('thead');
  1686. // const headerRow = el('tr');
  1687. // ['Attribute Name', 'Value'].forEach(text => {
  1688. // const th = el('th');
  1689. // th.textContent = text;
  1690. // headerRow.appendChild(th);
  1691. // });
  1692. // thead.appendChild(headerRow);
  1693. // table.appendChild(thead);
  1694. // const tbody = el('tbody');
  1695. // attributeEntries.forEach(attr => {
  1696. // const row = el('tr');
  1697. // const nameTd = el('td', 'attribute-name');
  1698. // nameTd.textContent = formatString(attr.name).replace(/_/g, ' ');
  1699. // row.appendChild(nameTd);
  1700. // const valueTd = el('td', 'attribute-value');
  1701. // const displayValue = Array.isArray(attr.value)
  1702. // ? (attr.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr.source)+ ')'
  1703. // : formatString(attr.value) +'('+ formatString(attr.source)+ ')';
  1704. // valueTd.textContent = displayValue || 'N/A';
  1705. // row.appendChild(valueTd);
  1706. // // const sourceTd = el('td', 'attribute-source');
  1707. // // sourceTd.textContent = attr.source || 'Unknown';
  1708. // // row.appendChild(sourceTd);
  1709. // tbody.appendChild(row);
  1710. // });
  1711. // table.appendChild(tbody);
  1712. // scrollWrapper.appendChild(table); // Append table to wrapper
  1713. // section.appendChild(scrollWrapper); // Append wrapper to section
  1714. // return section;
  1715. // }
  1716. // ------------------------------------------------------------------
  1717. // --- 3. MAIN RENDER FUNCTION (REPLACEMENT) ---
  1718. // ------------------------------------------------------------------
  1719. // function renderInlineForTable() {
  1720. // const api = API_RESPONSE_AI;
  1721. // const table = $('#tableContainer');
  1722. // if (!table) return;
  1723. // // Remove existing detail rows
  1724. // table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  1725. // PRODUCT_BASE.forEach((p, idx) => {
  1726. // if (!isProductSelected(p.item_id)) return;
  1727. // const res = findApiResultForProduct(p, idx, api);
  1728. // const tbody = table.querySelector('tbody');
  1729. // const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null;
  1730. // if (!baseRow) return;
  1731. // // --- Detail Row Construction ---
  1732. // const detail = el('tr', 'detail-row');
  1733. // // td.colSpan must match the number of columns in your main table
  1734. // const td = el('td'); td.colSpan = 7;
  1735. // const content = el('div', 'detail-content-tables');
  1736. // // // 1. MANDATORY Attributes Table (NOW USES CARD COMPARISON)
  1737. // // const mandatorySection = renderMandatoryComparisonCards( // <-- NEW FUNCTION NAME
  1738. // // res?.mandatory || {},
  1739. // // 'Mandatory Attributes Comparison'
  1740. // // );
  1741. // // content.appendChild(mandatorySection);
  1742. // // // 2. COMBINED Attributes Section (Additional, OCR, Visuals) - REMAINS THE SAME
  1743. // // content.appendChild(el('hr', 'section-separator'));
  1744. // // 1. MANDATORY Attributes Table (USES COMPARISON FUNCTION)
  1745. // const mandatoryTable = renderMandatoryComparisonTable(
  1746. // res?.mandatory || {},
  1747. // 'Mandatory Attributes Comparison'
  1748. // );
  1749. // content.appendChild(mandatoryTable);
  1750. // // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
  1751. // content.appendChild(el('hr', 'section-separator'));
  1752. // const combinedTitle = el('div', 'section-title');
  1753. // combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  1754. // content.appendChild(combinedTitle);
  1755. // const combinedAttributesContainer = el('div', 'combined-attributes-container');
  1756. // // Use the general renderer for these sections
  1757. // const additionalTable = renderAttributesAsTable(
  1758. // res?.additional || {},
  1759. // 'Additional Attributes'
  1760. // );
  1761. // const ocrTable = renderAttributesAsTable(
  1762. // res?.ocr_results?.extracted_attributes || {},
  1763. // 'OCR Results'
  1764. // );
  1765. // const visualsTable = renderAttributesAsTable(
  1766. // res?.visual_results?.visual_attributes || {},
  1767. // 'Visual Results'
  1768. // );
  1769. // // Append all sections to the combined container
  1770. // combinedAttributesContainer.appendChild(additionalTable);
  1771. // combinedAttributesContainer.appendChild(ocrTable);
  1772. // combinedAttributesContainer.appendChild(visualsTable);
  1773. // content.appendChild(combinedAttributesContainer);
  1774. // // --- Summary Counts ---
  1775. // const mandCount = Object.keys(res?.mandatory || {}).length;
  1776. // const addCount = Object.keys(res?.additional || {}).length;
  1777. // const ocrExtractedCount = Object.keys(res?.ocr_results?.extracted_attributes || {}).length;
  1778. // const visualExtractedCount = Object.keys(res?.visual_results?.visual_attributes || {}).length;
  1779. // const counts = el('div', 'attribute-summary-pills');
  1780. // const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
  1781. // const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
  1782. // const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
  1783. // const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
  1784. // counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1785. // content.appendChild(counts);
  1786. // // Final assembly and insertion
  1787. // td.appendChild(content);
  1788. // detail.appendChild(td);
  1789. // baseRow.insertAdjacentElement('afterend', detail);
  1790. // });
  1791. // // Update summary statistics
  1792. // $('#statTotal').textContent = api.total_products ?? 0;
  1793. // $('#statOk').textContent = api.successful ?? 0;
  1794. // $('#statKo').textContent = api.failed ?? 0;
  1795. // const apiSummary = $('#api-summary');
  1796. // if (apiSummary) apiSummary.style.display = 'block';
  1797. // }
  1798. function renderInlineForTable() {
  1799. const api = API_RESPONSE_AI;
  1800. const table = $('#tableContainer');
  1801. if (!table) return;
  1802. // Remove existing detail rows
  1803. table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  1804. PRODUCT_BASE.forEach((p, idx) => {
  1805. if (!isProductSelected(p.item_id)) return;
  1806. const res = findApiResultForProduct(p, idx, api);
  1807. const tbody = table.querySelector('tbody');
  1808. const baseRow = tbody ? tbody.querySelector(`#row-${p.id}`) : null;
  1809. if (!baseRow) return;
  1810. // --- Detail Row Construction ---
  1811. const detail = el('tr', 'detail-row');
  1812. // td.colSpan must match the number of columns in your main table
  1813. const td = el('td'); td.colSpan = 6;
  1814. const content = el('div', 'detail-content-tables');
  1815. // 1. MANDATORY Attributes Table
  1816. // 🚨 Note: The color check (Requirement #2) must be implemented inside renderMandatoryComparisonTable.
  1817. const mandatoryData = res?.mandatory || {};
  1818. if (Object.keys(mandatoryData).length > 0) {
  1819. const mandatoryTable = renderMandatoryComparisonTable(
  1820. mandatoryData,
  1821. 'Mandatory Attributes Comparison'
  1822. );
  1823. content.appendChild(mandatoryTable);
  1824. }
  1825. // 2. COMBINED Attributes Section (Additional, OCR, Visuals)
  1826. const additionalData = res?.additional || {};
  1827. const ocrData = res?.ocr_results?.extracted_attributes || {};
  1828. const visualsData = res?.visual_results?.visual_attributes || {};
  1829. const hasCombinedData = Object.keys(additionalData).length > 0 ||
  1830. Object.keys(ocrData).length > 0 ||
  1831. Object.keys(visualsData).length > 0;
  1832. if (hasCombinedData) {
  1833. content.appendChild(el('hr', 'section-separator'));
  1834. const combinedTitle = el('div', 'section-title');
  1835. combinedTitle.innerHTML = '<h2>Additional & AI-Driven Attributes</h2>';
  1836. content.appendChild(combinedTitle);
  1837. const combinedAttributesContainer = el('div', 'combined-attributes-container');
  1838. // Render Additional Table (Conditional based on data existence)
  1839. if (Object.keys(additionalData).length > 0) {
  1840. const additionalTable = renderAttributesAsTable(
  1841. additionalData,
  1842. 'Additional Attributes',
  1843. mandatoryData
  1844. );
  1845. combinedAttributesContainer.appendChild(additionalTable);
  1846. }
  1847. // Render OCR Table (Conditional based on data existence)
  1848. if (Object.keys(ocrData).length > 0) {
  1849. const ocrTable = renderAttributesAsTable(
  1850. ocrData,
  1851. 'OCR Results',
  1852. mandatoryData
  1853. );
  1854. combinedAttributesContainer.appendChild(ocrTable);
  1855. }
  1856. // Render Visuals Table (Conditional based on data existence)
  1857. if (Object.keys(visualsData).length > 0) {
  1858. const visualsTable = renderAttributesAsTable(
  1859. visualsData,
  1860. 'Visual Results',
  1861. mandatoryData
  1862. );
  1863. combinedAttributesContainer.appendChild(visualsTable);
  1864. }
  1865. content.appendChild(combinedAttributesContainer);
  1866. }
  1867. // --- Summary Counts ---
  1868. const mandCount = Object.keys(mandatoryData).length;
  1869. const addCount = Object.keys(additionalData).length;
  1870. const ocrExtractedCount = Object.keys(ocrData).length;
  1871. const visualExtractedCount = Object.keys(visualsData).length;
  1872. const counts = el('div', 'attribute-summary-pills');
  1873. const c1 = el('span', 'pill primary'); c1.textContent = `Mandatory: ${mandCount}`;
  1874. const c2 = el('span', 'pill secondary'); c2.textContent = `Additional: ${addCount}`;
  1875. const c3 = el('span', 'pill secondary'); c3.textContent = `OCR Keys: ${ocrExtractedCount}`;
  1876. const c4 = el('span', 'pill secondary'); c4.textContent = `Visual Keys: ${visualExtractedCount}`;
  1877. counts.appendChild(c1); counts.appendChild(c2); counts.appendChild(c3); counts.appendChild(c4);
  1878. content.appendChild(counts);
  1879. // Final assembly and insertion
  1880. td.appendChild(content);
  1881. detail.appendChild(td);
  1882. baseRow.insertAdjacentElement('afterend', detail);
  1883. });
  1884. // Update summary statistics
  1885. $('#statTotal').textContent = api.total_products ?? 0;
  1886. $('#statOk').textContent = api.successful ?? 0;
  1887. $('#statKo').textContent = api.failed ?? 0;
  1888. const apiSummary = $('#api-summary');
  1889. if (apiSummary) apiSummary.style.display = 'block';
  1890. }
  1891. function renderInlineAttributes() {
  1892. if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
  1893. // renderInlineForCards();
  1894. // renderInlineForTable();
  1895. }
  1896. // --- Main rendering ---
  1897. function renderProducts() {
  1898. if (layoutMode === 'cards') {
  1899. $('#cardsContainer').style.display = '';
  1900. $('#tableContainer').style.display = 'none';
  1901. // console.log("PRODUCT_BASE",PRODUCT_BASE);
  1902. renderProductsCards();
  1903. } else {
  1904. $('#cardsContainer').style.display = 'none';
  1905. $('#tableContainer').style.display = '';
  1906. renderProductsTable();
  1907. }
  1908. updateSelectionInfo();
  1909. renderPagination();
  1910. // If there is a selection, re-render inline attributes (persist across toggle)
  1911. if (selectedProductsWithAttributes.length > 0) renderInlineAttributes();
  1912. }
  1913. // --- Submit & Reset ---
  1914. function submitAttributes() {
  1915. // Check the length of the new array
  1916. if (selectedProductsWithAttributes.length === 0) {
  1917. alert('Please select at least one product.');
  1918. return;
  1919. }
  1920. // if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
  1921. // console.log("selectedIds",selectedIds);
  1922. jQuery('#full-page-loader').show();
  1923. // let inputArray = {
  1924. // "product_ids" : [...selectedIds]
  1925. // }
  1926. const extractAdditional = document.getElementById('extract_additional').checked;
  1927. const processImage = document.getElementById('process_image').checked;
  1928. // const selectedMultiples = document.getElementById('#mandatory-attributes');
  1929. // const selectedValues = Array.from(selectedMultiples.selectedOptions).map(option => option.value);
  1930. const selectElement = document.getElementById('mandatory-attributes');
  1931. const selectedValues = Array.from(selectElement.selectedOptions).map(option => option.value);
  1932. // console.log(selectedValues); // Logs an array of selected values
  1933. // console.log("thresholdValueDisplay",thresholdValueDisplay.value);
  1934. const threshold = parseFloat(document.getElementById('thresholdRange').value);
  1935. // Transform the new state array into the required API format
  1936. const itemIds = selectedProductsWithAttributes.map(p => p.item_id);
  1937. // Create the mandatory_attrs map: { item_id: { attr_name: [values] } }
  1938. // NOTE: The backend API you showed expects a flattened list of "mandatory_attrs"
  1939. // like: { "color": ["color", "shade"], "size": ["size", "fit"] }
  1940. // It seems to ignore the selected product-specific values and uses a general list of synonyms.
  1941. // Assuming the request needs a general map of *all unique* selected attributes across all selected products:
  1942. let mandatoryAttrsMap = {};
  1943. selectedProductsWithAttributes.forEach(product => {
  1944. // Merge attributes from all selected products
  1945. Object.assign(mandatoryAttrsMap, product.mandatory_attrs);
  1946. });
  1947. // If the API expects the complex, product-specific payload from your Q1 example:
  1948. const payloadForQ1 = selectedProductsWithAttributes.map(p => ({
  1949. item_id: p.item_id,
  1950. mandatory_attrs: p.mandatory_attrs
  1951. }));
  1952. let inputArray = {
  1953. "products": payloadForQ1,
  1954. "model": "llama-3.1-8b-instant",
  1955. "extract_additional": extractAdditional,
  1956. "process_image": processImage,
  1957. "multiple": selectedValues,
  1958. "threshold_abs": 0.6, // Lower threshold to be more permissive
  1959. // "margin": 0.3, // Larger margin to include more candidates
  1960. // "use_adaptive_margin": true,
  1961. // "use_semantic_clustering": true
  1962. }
  1963. let raw = JSON.stringify(inputArray);
  1964. fetch('/attr/batch-extract/', {
  1965. method: 'POST', // or 'POST' if your API expects POST
  1966. headers: {
  1967. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
  1968. 'Content-Type': "application/json"
  1969. },
  1970. body: raw
  1971. })
  1972. .then(response => response.json())
  1973. .then(data => {
  1974. // console.log("response data",data);
  1975. API_RESPONSE_AI = data;
  1976. renderInlineAttributes();
  1977. jQuery('#full-page-loader').hide();
  1978. });
  1979. }
  1980. function resetAll() {
  1981. selectedProductsWithAttributes = []; // Reset the main array
  1982. // selectedIds.clear();
  1983. lastSeen.clear();
  1984. renderProducts();
  1985. // Clear summary
  1986. document.getElementById('statTotal').textContent = '0';
  1987. document.getElementById('statOk').textContent = '0';
  1988. document.getElementById('statKo').textContent = '0';
  1989. $('#api-summary').style.display = 'none';
  1990. // ✅ Clear Select2 selections
  1991. jQuery('#mandatory-attributes').val(null).trigger('change');
  1992. // ✅ Reset threshold input (and display)
  1993. const thresholdInput = document.getElementById('thresholdRange');
  1994. const thresholdDisplay = document.getElementById('thresholdValue');
  1995. thresholdInput.value = '0.65'; // or any default value you prefer
  1996. if (thresholdDisplay) {
  1997. thresholdDisplay.textContent = '0.65';
  1998. }
  1999. }
  2000. function setLayout(mode) {
  2001. layoutMode = mode;
  2002. const btnCards = document.getElementById('btnCards');
  2003. const btnTable = document.getElementById('btnTable');
  2004. if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
  2005. else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
  2006. renderProducts();
  2007. }
  2008. // Upload elements (Bootstrap modal version)
  2009. const uploadModalEl = document.getElementById('uploadModal');
  2010. const dropzone = document.getElementById('dropzone');
  2011. const uploadFiles = document.getElementById('uploadFiles');
  2012. const fileInfo = document.getElementById('fileInfo');
  2013. const uploadBar = document.getElementById('uploadBar');
  2014. const uploadStatus = document.getElementById('uploadStatus');
  2015. // Reset modal on show
  2016. uploadModalEl.addEventListener('shown.bs.modal', () => {
  2017. uploadStatus.textContent = '';
  2018. uploadStatus.className = ''; // clear success/error class
  2019. uploadBar.style.width = '0%';
  2020. uploadBar.setAttribute('aria-valuenow', '0');
  2021. uploadFiles.value = '';
  2022. uploadFiles.setAttribute('accept', ACCEPT_TYPES);
  2023. fileInfo.textContent = 'No files selected.';
  2024. });
  2025. function describeFiles(list) {
  2026. if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
  2027. const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
  2028. fileInfo.textContent = names.join(', ');
  2029. }
  2030. // Drag & drop feedback
  2031. ['dragenter','dragover'].forEach(evt => {
  2032. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
  2033. });
  2034. ['dragleave','drop'].forEach(evt => {
  2035. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
  2036. });
  2037. // Handle drop
  2038. dropzone.addEventListener('drop', e => {
  2039. uploadFiles.files = e.dataTransfer.files;
  2040. describeFiles(uploadFiles.files);
  2041. });
  2042. // Click to browse
  2043. // dropzone.addEventListener('click', () => uploadFiles.click());
  2044. // Picker change
  2045. uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
  2046. function startUpload() {
  2047. const files = uploadFiles.files;
  2048. if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
  2049. jQuery('#full-page-loader').show();
  2050. uploadStatus.textContent = 'Uploading...';
  2051. uploadStatus.className = ''; // neutral
  2052. uploadBar.style.width = '0%';
  2053. uploadBar.setAttribute('aria-valuenow', '0');
  2054. const form = new FormData();
  2055. Array.from(files).forEach(f => form.append('file', f));
  2056. // form.append('uploaded_by', 'Vishal'); // example extra field
  2057. const xhr = new XMLHttpRequest();
  2058. xhr.open('POST', UPLOAD_API_URL, true);
  2059. // If you need auth:
  2060. // xhr.setRequestHeader('Authorization', 'Bearer <token>');
  2061. xhr.upload.onprogress = (e) => {
  2062. if (e.lengthComputable) {
  2063. const pct = Math.round((e.loaded / e.total) * 100);
  2064. uploadBar.style.width = pct + '%';
  2065. uploadBar.setAttribute('aria-valuenow', String(pct));
  2066. }
  2067. };
  2068. xhr.onreadystatechange = () => {
  2069. if (xhr.readyState === 4) {
  2070. const ok = (xhr.status >= 200 && xhr.status < 300);
  2071. try {
  2072. const resp = JSON.parse(xhr.responseText || '{}');
  2073. uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
  2074. } catch {
  2075. uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
  2076. }
  2077. uploadStatus.className = ok ? 'success' : 'error';
  2078. // Optional: auto-close the modal on success after 1.2s:
  2079. // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
  2080. }
  2081. };
  2082. xhr.onerror = () => {
  2083. uploadStatus.textContent = 'Network error during upload.';
  2084. uploadStatus.className = 'error';
  2085. };
  2086. xhr.send(form);
  2087. setTimeout(()=>{
  2088. jQuery('#uploadModal').modal('hide');
  2089. window.location.reload();
  2090. },3000)
  2091. jQuery('#full-page-loader').hide();
  2092. }
  2093. // Wire Start button
  2094. document.getElementById('uploadStart').addEventListener('click', startUpload);
  2095. // Cancel button already closes the modal via data-bs-dismiss
  2096. // --- Pagination state ---
  2097. let page = 1;
  2098. let pageSize = 50; // default rows per page
  2099. function totalPages() {
  2100. return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
  2101. }
  2102. function clampPage() {
  2103. page = Math.min(Math.max(1, page), totalPages());
  2104. }
  2105. function getCurrentSlice() {
  2106. clampPage();
  2107. const start = (page - 1) * pageSize;
  2108. return PRODUCT_BASE.slice(start, start + pageSize);
  2109. }
  2110. function renderPagination() {
  2111. const bar = document.getElementById('paginationBar');
  2112. if (!bar) return;
  2113. const tp = totalPages();
  2114. clampPage();
  2115. bar.innerHTML = `
  2116. <div class="page-size">
  2117. <label for="pageSizeSelect">Rows per page</label>
  2118. <select id="pageSizeSelect">
  2119. <option value="5" ${pageSize===5 ? 'selected' : ''}>5</option>
  2120. <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
  2121. <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
  2122. <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
  2123. <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
  2124. </select>
  2125. </div>
  2126. <div class="pager">
  2127. <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
  2128. <span class="page-info">Page ${page} of ${tp}</span>
  2129. <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
  2130. </div>
  2131. `;
  2132. // wire events
  2133. document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
  2134. document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
  2135. const sel = document.getElementById('pageSizeSelect');
  2136. if (sel) {
  2137. sel.addEventListener('change', () => {
  2138. const val = sel.value;
  2139. pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
  2140. page = 1; // reset to first page when size changes
  2141. renderProducts();
  2142. });
  2143. }
  2144. }
  2145. // Function to add/remove product from the state and manage its attributes
  2146. function toggleProductSelection(itemId, isChecked, attributes = {}) {
  2147. const index = selectedProductsWithAttributes.findIndex(p => p.item_id === itemId);
  2148. // console.log("index",index);
  2149. if (isChecked) {
  2150. // If selecting, ensure the product object exists in the array
  2151. if (index === -1) {
  2152. selectedProductsWithAttributes.push({
  2153. item_id: itemId,
  2154. mandatory_attrs: attributes
  2155. });
  2156. } else {
  2157. // Update attributes if the product is already selected
  2158. selectedProductsWithAttributes[index].mandatory_attrs = attributes;
  2159. }
  2160. } else {
  2161. // If deselecting, remove the product object from the array
  2162. if (index !== -1) {
  2163. selectedProductsWithAttributes.splice(index, 1);
  2164. }
  2165. }
  2166. updateSelectionInfo();
  2167. }
  2168. // Function to get the current mandatory attributes for a selected item
  2169. function getSelectedAttributes(itemId) {
  2170. const productEntry = selectedProductsWithAttributes.find(p => p.item_id === itemId);
  2171. return productEntry ? productEntry.mandatory_attrs : {};
  2172. }
  2173. // Helper to check if a product is selected
  2174. function isProductSelected(itemId) {
  2175. return selectedProductsWithAttributes.some(p => p.item_id === itemId);
  2176. }
  2177. // Helper to check if a specific attribute/value is selected
  2178. function isAttributeValueSelected(itemId, attrName, value) {
  2179. const attrs = getSelectedAttributes(itemId);
  2180. const values = attrs[attrName];
  2181. return values ? values.includes(value) : false; // Default all selected when first loaded
  2182. }
  2183. // $('.attribute-select').select2({
  2184. // placeholder: 'Select product attributes'
  2185. // });
  2186. function getAtributeList(){
  2187. jQuery('#full-page-loader').show();
  2188. try{
  2189. fetch('/attr/products/attributes', {
  2190. method: 'GET', // or 'POST' if your API expects POST
  2191. headers: {
  2192. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
  2193. }
  2194. })
  2195. .then(response => response.json())
  2196. .then(data => {
  2197. // console.log("data",data);
  2198. attributesFullData = data;
  2199. let attributesData = data;
  2200. // Step 1: Extract unique mandatory attribute names
  2201. const mandatoryAttributes = [...new Set(
  2202. attributesData
  2203. .filter(attr => attr.is_mandatory === "Yes")
  2204. .map(attr => attr.attribute_name)
  2205. )];
  2206. // Step 2: Populate the select element
  2207. const $select = jQuery('#mandatory-attributes');
  2208. $select.append(new Option("Select All", "select_all")); // Add "Select All" option first
  2209. mandatoryAttributes.forEach(attr => {
  2210. $select.append(new Option(attr, attr));
  2211. });
  2212. // Step 3: Initialize Select2 with placeholder
  2213. // $select.select2({
  2214. // placeholder: "Select mandatory attributes",
  2215. // allowClear: true
  2216. // });
  2217. // Step 4: Handle 'Select All' logic
  2218. $select.on('select2:select', function (e) {
  2219. if (e.params.data.id === "select_all") {
  2220. // Select all real options except "Select All"
  2221. const allOptions = mandatoryAttributes;
  2222. $select.val(allOptions).trigger('change');
  2223. }
  2224. });
  2225. jQuery('#full-page-loader').hide();
  2226. });
  2227. }catch(err){
  2228. console.log("err",err);
  2229. jQuery('#full-page-loader').hide();
  2230. }
  2231. }
  2232. document.addEventListener("DOMContentLoaded", function () {
  2233. // Update span when range changes
  2234. thresholdInput.addEventListener('input', function () {
  2235. // console.log("this.value",this.value);
  2236. thresholdValueDisplay.textContent = this.value;
  2237. });
  2238. });
  2239. // Get threshold value when needed
  2240. function getThreshold() {
  2241. // console.log("parseFloat(thresholdInput.value)",parseFloat(thresholdInput.value));
  2242. return parseFloat(thresholdInput.value);
  2243. }
  2244. /**
  2245. * Renders Mandatory attributes using a card-based comparison layout.
  2246. * Highlights mismatches prominently.
  2247. * @param {Object} attributes - The mandatory attribute data.
  2248. * @param {string} title - The title for the section.
  2249. * @returns {HTMLElement} A div containing the comparison cards.
  2250. */
  2251. function renderMandatoryComparisonCards(attributes, title) {
  2252. const section = el('div', 'attribute-section');
  2253. // --- 1. Flatten Mandatory Attributes ---
  2254. let attributeEntries = [];
  2255. Object.keys(attributes).forEach(key => {
  2256. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2257. valuesArray.forEach(v => {
  2258. const aiValue = v.value || 'N/A';
  2259. const originalValue = v.original_value || 'N/A';
  2260. // Comparison is case-insensitive and ignores leading/trailing whitespace
  2261. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2262. attributeEntries.push({
  2263. name: key,
  2264. aiValue: aiValue,
  2265. originalValue: originalValue,
  2266. isMatch: isMatch,
  2267. source: v.source || 'N/A'
  2268. });
  2269. });
  2270. });
  2271. // --- 2. Section Header ---
  2272. const titleEl = el('div', 'section-title');
  2273. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2274. section.appendChild(titleEl);
  2275. if (attributeEntries.length === 0) {
  2276. const msg = el('p', 'no-attributes-message');
  2277. msg.textContent = `No ${title.toLowerCase()} found.`;
  2278. section.appendChild(msg);
  2279. return section;
  2280. }
  2281. // --- 3. Card Container ---
  2282. const cardsContainer = el('div', 'comparison-cards-container');
  2283. attributeEntries.forEach(attr => {
  2284. // Main Card Element
  2285. const card = el('div', `comparison-card ${attr.isMatch ? 'match' : 'mismatch-card'}`);
  2286. // Card Header (Attribute Name)
  2287. const header = el('div', 'card-header');
  2288. header.textContent = attr.name.replace(/_/g, ' ');
  2289. card.appendChild(header);
  2290. // Content Wrapper
  2291. const content = el('div', 'card-content');
  2292. // Existing Value Box
  2293. const originalBox = el('div', 'value-box original-box');
  2294. originalBox.innerHTML = `
  2295. <div class="value-label">Manually Identified Value</div>
  2296. <div class="value-text">${attr.originalValue}</div>
  2297. `;
  2298. content.appendChild(originalBox);
  2299. // AI Value Box
  2300. const aiBox = el('div', `value-box ai-box ${attr.isMatch ? 'found-value' : 'mismatch-value'}`);
  2301. aiBox.innerHTML = `
  2302. <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  2303. <div class="value-text">${attr.aiValue}</div>
  2304. `;
  2305. content.appendChild(aiBox);
  2306. card.appendChild(content);
  2307. // Mismatch Indicator (only visible on mismatch-card via CSS)
  2308. if (!attr.isMatch) {
  2309. const indicator = el('div', 'mismatch-indicator');
  2310. // indicator.innerHTML = '❌ MISMATCH';
  2311. indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2312. card.appendChild(indicator);
  2313. }
  2314. cardsContainer.appendChild(card);
  2315. });
  2316. section.appendChild(cardsContainer);
  2317. return section;
  2318. }
  2319. // Example JavaScript (Assuming you have access to API_RESPONSE_AI)
  2320. // document.getElementById('downloadResultBtn').addEventListener('click', () => {
  2321. // // 1. Convert the data to a JSON string
  2322. // const jsonString = JSON.stringify(API_RESPONSE_AI, null, 2);
  2323. // // 2. Create a Blob from the JSON string
  2324. // const blob = new Blob([jsonString], { type: 'application/json' });
  2325. // // 3. Create a temporary URL and link element
  2326. // const url = URL.createObjectURL(blob);
  2327. // const a = document.createElement('a');
  2328. // // 4. Set download attributes
  2329. // a.href = url;
  2330. // a.download = 'api_generated_results.json';
  2331. // // 5. Simulate a click to trigger download
  2332. // document.body.appendChild(a);
  2333. // a.click();
  2334. // // 6. Clean up
  2335. // document.body.removeChild(a);
  2336. // URL.revokeObjectURL(url);
  2337. // });
  2338. /**
  2339. * Renders Mandatory attributes using a card-based comparison layout.
  2340. * Highlights mismatches prominently.
  2341. * @param {Object} attributes - The mandatory attribute data.
  2342. * @param {string} title - The title for the section (used for the header).
  2343. * @returns {HTMLElement} A div containing the comparison cards.
  2344. */
  2345. // function renderMandatoryComparisonCards(attributes, title) {
  2346. // const section = el('div', 'attribute-section mandatory-comparison-section');
  2347. // // --- 1. Flatten Mandatory Attributes ---
  2348. // let attributeEntries = [];
  2349. // Object.keys(attributes).forEach(key => {
  2350. // const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2351. // valuesArray.forEach(v => {
  2352. // const aiValue = v.value || 'N/A';
  2353. // const originalValue = v.original_value || 'N/A';
  2354. // const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2355. // attributeEntries.push({
  2356. // name: key,
  2357. // aiValue: aiValue,
  2358. // originalValue: originalValue,
  2359. // isMatch: isMatch,
  2360. // source: v.source || 'N/A'
  2361. // });
  2362. // });
  2363. // });
  2364. // // --- 2. Section Header ---
  2365. // const titleEl = el('div', 'section-title');
  2366. // titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2367. // section.appendChild(titleEl);
  2368. // if (attributeEntries.length === 0) {
  2369. // const msg = el('p', 'no-attributes-message');
  2370. // msg.textContent = `No ${title.toLowerCase()} found.`;
  2371. // section.appendChild(msg);
  2372. // return section;
  2373. // }
  2374. // // --- 3. Card Container ---
  2375. // const cardsContainer = el('div', 'comparison-cards-container');
  2376. // attributeEntries.forEach(attr => {
  2377. // const card = el('div', `comparison-card ${attr.isMatch ? 'match' : 'mismatch-card'}`);
  2378. // const header = el('div', 'card-header');
  2379. // header.textContent = attr.name.replace(/_/g, ' ');
  2380. // card.appendChild(header);
  2381. // const content = el('div', 'card-content');
  2382. // // Existing Value Box
  2383. // const originalBox = el('div', 'value-box original-box');
  2384. // originalBox.innerHTML = `
  2385. // <div class="value-label">Manually Identified Value</div>
  2386. // <div class="value-text">${attr.originalValue}</div>
  2387. // `;
  2388. // content.appendChild(originalBox);
  2389. // // AI Value Box
  2390. // const aiBox = el('div', `value-box ai-box ${attr.isMatch ? 'found-value' : 'mismatch-value'}`);
  2391. // aiBox.innerHTML = `
  2392. // <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  2393. // <div class="value-text">${attr.aiValue}</div>
  2394. // `;
  2395. // content.appendChild(aiBox);
  2396. // card.appendChild(content);
  2397. // // Mismatch Indicator
  2398. // if (!attr.isMatch) {
  2399. // const indicator = el('div', 'mismatch-indicator');
  2400. // // indicator.innerHTML = '❌ MISMATCH';
  2401. // indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2402. // card.appendChild(indicator);
  2403. // }
  2404. // cardsContainer.appendChild(card);
  2405. // });
  2406. // section.appendChild(cardsContainer);
  2407. // return section;
  2408. // }
  2409. function renderMandatoryComparisonCards(attributes, title) {
  2410. const section = el('div', 'attribute-section mandatory-comparison-section');
  2411. // --- 1. Flatten Mandatory Attributes ---
  2412. let attributeEntries = [];
  2413. Object.keys(attributes).forEach(key => {
  2414. const valuesArray = Array.isArray(attributes[key]) ? attributes[key] : [attributes[key]];
  2415. valuesArray.forEach(v => {
  2416. const aiValue = v.value || 'N/A';
  2417. const originalValue = v.original_value || 'N/A';
  2418. const isMatch = (String(aiValue).trim().toLowerCase() === String(originalValue).trim().toLowerCase());
  2419. attributeEntries.push({
  2420. name: key,
  2421. aiValue: aiValue,
  2422. originalValue: originalValue,
  2423. isMatch: isMatch,
  2424. source: v.source || 'N/A'
  2425. });
  2426. });
  2427. });
  2428. // --- 2. Section Header ---
  2429. const titleEl = el('div', 'section-title');
  2430. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2431. section.appendChild(titleEl);
  2432. if (attributeEntries.length === 0) {
  2433. const msg = el('p', 'no-attributes-message');
  2434. msg.textContent = `No ${title.toLowerCase()} found.`;
  2435. section.appendChild(msg);
  2436. return section;
  2437. }
  2438. // --- 3. Card Container ---
  2439. const cardsContainer = el('div', 'comparison-cards-container');
  2440. attributeEntries.forEach(attr => {
  2441. // --- CHANGE 1: Apply 'match-card' or 'mismatch-card' explicitly ---
  2442. const cardClass = attr.isMatch ? 'match-card' : 'mismatch-card';
  2443. const card = el('div', `comparison-card ${cardClass}`);
  2444. const header = el('div', 'card-header');
  2445. header.textContent = attr.name.replace(/_/g, ' ');
  2446. card.appendChild(header);
  2447. const content = el('div', 'card-content');
  2448. // Existing Value Box
  2449. const originalBox = el('div', 'value-box original-box');
  2450. originalBox.innerHTML = `
  2451. <div class="value-label">Manually Identified Value</div>
  2452. <div class="value-text">${attr.originalValue}</div>
  2453. `;
  2454. content.appendChild(originalBox);
  2455. // AI Value Box
  2456. // Removed 'found-value' class here as styling should rely on the parent card class
  2457. const aiBox = el('div', `value-box ai-box ${attr.isMatch ? '' : 'mismatch-value'}`);
  2458. aiBox.innerHTML = `
  2459. <div class="value-label">AI Generated Value <span class="value-source">(${attr.source})</span></div>
  2460. <div class="value-text">${attr.aiValue}</div>
  2461. `;
  2462. content.appendChild(aiBox);
  2463. card.appendChild(content);
  2464. // --- CHANGE 2: Display the indicator for ALL cards, controlling color via CSS ---
  2465. const indicator = el('div', 'match-status-indicator');
  2466. indicator.innerHTML = attr.isMatch ? '✅ MATCH' : '❌ MISMATCH';
  2467. card.appendChild(indicator);
  2468. cardsContainer.appendChild(card);
  2469. });
  2470. section.appendChild(cardsContainer);
  2471. return section;
  2472. }
  2473. /**
  2474. * Renders Additional, OCR, or Visual attributes in a simple card layout.
  2475. * @param {Object} attributes - The attribute data (Additional, OCR, or Visual).
  2476. * @param {string} title - The title for the section.
  2477. * @returns {HTMLElement} A div containing the attribute cards.
  2478. */
  2479. function renderSimpleAttributeCards(attributes, title) {
  2480. const section = el('div', 'attribute-section simple-attribute-section');
  2481. // --- 1. Flatten Attributes ---
  2482. let attributeEntries = [];
  2483. const processAttribute = (key, values) => {
  2484. const valuesArray = Array.isArray(values) ? values : [values];
  2485. valuesArray.forEach(v => {
  2486. attributeEntries.push({
  2487. name: key,
  2488. value: v.value,
  2489. source: v.source || 'N/A'
  2490. });
  2491. });
  2492. };
  2493. Object.keys(attributes).forEach(key => {
  2494. const attribute = attributes[key];
  2495. if (Array.isArray(attribute)) {
  2496. processAttribute(key, attribute);
  2497. } else if (typeof attribute === 'object' && attribute !== null) {
  2498. Object.keys(attribute).forEach(subKey => {
  2499. const subAttribute = attribute[subKey];
  2500. if (Array.isArray(subAttribute)) {
  2501. processAttribute(`${key} (${subKey.replace(/_/g, ' ')})`, subAttribute);
  2502. }
  2503. });
  2504. }
  2505. });
  2506. // --- 2. Section Header ---
  2507. const titleEl = el('div', 'section-title');
  2508. titleEl.innerHTML = `<h3>${title} (${attributeEntries.length})</h3>`;
  2509. section.appendChild(titleEl);
  2510. if (attributeEntries.length === 0) {
  2511. const msg = el('p', 'no-attributes-message');
  2512. msg.textContent = `No ${title.toLowerCase()} found.`;
  2513. section.appendChild(msg);
  2514. return section;
  2515. }
  2516. // --- 3. Card Container ---
  2517. const cardsContainer = el('div', 'comparison-cards-container simple-cards-container');
  2518. attributeEntries.forEach(attr => {
  2519. // Simple Card Element
  2520. const card = el('div', 'simple-card');
  2521. // Card Header (Attribute Name)
  2522. const header = el('div', 'card-header');
  2523. header.textContent = formatString(attr.name).replace(/_/g, ' ');
  2524. card.appendChild(header);
  2525. // Content Wrapper
  2526. const content = el('div', 'card-content');
  2527. // Value Box
  2528. const valueBox = el('div', 'value-box single-value-box');
  2529. const displayValue = Array.isArray(attr.value)
  2530. ? (attr.value.map(v => formatString(v.value))).join(', ') +'('+ formatString(attr.source)+ ')'
  2531. : formatString(attr.value) +'('+ formatString(attr.source)+ ')';
  2532. // : attr.value;
  2533. valueBox.innerHTML = `
  2534. <div class="value-label">Extracted Value <span class="value-source">(${formatString(attr.source)})</span></div>
  2535. <div class="value-text">${displayValue || 'N/A'}</div>
  2536. `;
  2537. content.appendChild(valueBox);
  2538. card.appendChild(content);
  2539. cardsContainer.appendChild(card);
  2540. });
  2541. section.appendChild(cardsContainer);
  2542. return section;
  2543. }