attr-extraction.js 93 KB

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