attr-extraction-working.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. var PRODUCT_BASE = [
  8. // { 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' },
  9. // { 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' },
  10. // { 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' },
  11. // { 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' },
  12. // { 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' }
  13. ];
  14. // --- Data ---
  15. const mediaUrl = "./../";
  16. document.addEventListener('DOMContentLoaded', () => {
  17. jQuery('#full-page-loader').show();
  18. fetch('/attr/products', {
  19. method: 'GET', // or 'POST' if your API expects POST
  20. headers: {
  21. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
  22. }
  23. })
  24. .then(response => response.json())
  25. .then(data => {
  26. console.log("data",data);
  27. // --- Wire up ---
  28. PRODUCT_BASE = data;
  29. PRODUCT_BASE = PRODUCT_BASE.map((d)=>{return {...d,mandatoryAttributes:["color","size"]}});
  30. console.log("PRODUCT_BASE",PRODUCT_BASE);
  31. if(PRODUCT_BASE.length > 0){
  32. $('#paginationBar').style.display = 'block';
  33. }
  34. renderProducts();
  35. document.getElementById('btnSubmit').addEventListener('click', submitAttributes);
  36. document.getElementById('btnReset').addEventListener('click', resetAll);
  37. // document.getElementById('btnSelectAll').addEventListener('click', () => {
  38. // if (selectedIds.size === PRODUCT_BASE.length) { selectedIds.clear(); } else { selectedIds = new Set(PRODUCT_BASE.map(p => p.id)); }
  39. // // renderProducts();
  40. // });
  41. // Replace your existing Select All listener with this:
  42. document.getElementById('btnSelectAll').addEventListener('click', () => {
  43. // Use the container for the active layout
  44. const container = (layoutMode === 'cards')
  45. ? document.getElementById('cardsContainer')
  46. : document.getElementById('tableContainer');
  47. // Collect all visible checkboxes
  48. const boxes = Array.from(container.querySelectorAll('input[type="checkbox"]'));
  49. // If every visible checkbox is already checked, we'll deselect; otherwise select all
  50. const allChecked = boxes.length > 0 && boxes.every(cb => cb.checked);
  51. boxes.forEach(cb => {
  52. const target = !allChecked; // true to select, false to deselect
  53. if (cb.checked !== target) {
  54. cb.checked = target;
  55. // Trigger your existing "change" handler so selectedIds & row .selected class update
  56. cb.dispatchEvent(new Event('change', { bubbles: true }));
  57. }
  58. });
  59. // Update the selection pill text (doesn't re-render the list)
  60. updateSelectionInfo();
  61. });
  62. document.getElementById('btnCards').addEventListener('click', () => setLayout('cards'));
  63. document.getElementById('btnTable').addEventListener('click', () => setLayout('table'));
  64. jQuery('#full-page-loader').hide();
  65. // if (data.success) {
  66. // }
  67. });
  68. });
  69. var FAKE_API_RESPONSE = {
  70. // results: [
  71. // { 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' } },
  72. // { 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' } },
  73. // { 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' } },
  74. // { 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' } },
  75. // { 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' } }
  76. // ],
  77. // total_products: 5,
  78. // successful: 5,
  79. // failed: 0
  80. };
  81. // --- State ---
  82. let selectedIds = new Set();
  83. let selectedAttributes = new Array();
  84. const lastSeen = new Map(); // per-product memory for NEW highlighting (product_id -> maps)
  85. let layoutMode = 'cards'; // 'cards' | 'table'
  86. // --- Helpers ---
  87. const $ = (sel) => document.querySelector(sel);
  88. const el = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; return e; }
  89. function updateSelectionInfo() {
  90. const pill = $('#selectionInfo');
  91. const total = PRODUCT_BASE.length;
  92. const count = selectedIds.size;
  93. pill.textContent = count === 0 ? 'No products selected' : `${count} of ${total} selected`;
  94. }
  95. function setChecked(id, checked) { if (checked) selectedIds.add(id); else selectedIds.delete(id); updateSelectionInfo(); }
  96. // function setCheckedAttributes(id,attribute, checked) { if (checked) selectedAttributes.add({id: [attribute]}); else selectedIds.delete({id:[attribute]}); updateSelectionInfo(); }
  97. // --- Chips rendering ---
  98. function renderChips(container, obj, memoryMap) {
  99. container.innerHTML = '';
  100. let count = 0;
  101. Object.entries(obj || {}).forEach(([k, v]) => {
  102. const chip = el('span', 'chip');
  103. const kEl = el('span', 'k'); kEl.textContent = k + ':';
  104. const vEl = el('span', 'v'); vEl.textContent = ' ' + String(v);
  105. chip.appendChild(kEl); chip.appendChild(vEl);
  106. const was = memoryMap.get(k);
  107. if (was === undefined || was !== v) chip.classList.add('new');
  108. container.appendChild(chip);
  109. memoryMap.set(k, v);
  110. count++;
  111. });
  112. return count;
  113. }
  114. function findApiResultForProduct(p, index, api) { return api.results?.find(r => r.product_id === p.item_id) || api.results?.[index] || null; }
  115. // --- Cards layout ---
  116. function createProductCard(p) {
  117. const row = el('div', 'product');
  118. if (selectedIds.has(p.item_id)) row.classList.add('selected');
  119. const left = el('div', 'thumb');
  120. const img = new Image(); img.src = mediaUrl+p.image_path || p.image || '';
  121. img.alt = `${p.product_name} image`;
  122. console.log("img",img);
  123. // 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); };
  124. img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  125. left.appendChild(img);
  126. const mid = el('div', 'meta');
  127. const name = el('div', 'name'); name.textContent = p.product_name || '—';
  128. const desc = el('div', 'desc'); desc.innerHTML = p.product_short_description || '';
  129. const badges = el('div', 'badges');
  130. const sku = el('span', 'pill'); sku.textContent = `SKU: ${p.item_id || '—'}`; badges.appendChild(sku);
  131. const type = el('span', 'pill'); type.textContent = p.product_type || '—'; badges.appendChild(type);
  132. const long = el('div', 'desc'); long.innerHTML = p.product_long_description || ''; long.style.marginTop = '4px';
  133. mid.appendChild(name); mid.appendChild(desc); mid.appendChild(badges); mid.appendChild(long);
  134. // const rightAttribute = el('label', 'select');
  135. // // Main checkbox: "Select"
  136. // const cb_attribute = document.createElement('input');
  137. // cb_attribute.type = 'checkbox';
  138. // cb_attribute.checked = selectedIds.has(p.item_id);
  139. // cb_attribute.addEventListener('change', () => {
  140. // setChecked(p.item_id, cb_attribute.checked);
  141. // row.classList.toggle('selected', cb_attribute.checked);
  142. // });
  143. // const lbl_attribute = el('span');
  144. // lbl_attribute.textContent = 'Select';
  145. // rightAttribute.appendChild(cb_attribute);
  146. // rightAttribute.appendChild(lbl_attribute);
  147. // // --- New checkbox for mandatory attributes ---
  148. // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  149. // const attrLabel = el('label', 'select-attr');
  150. // const attrCb = document.createElement('input');
  151. // attrCb.type = 'checkbox';
  152. // attrCb.checked = false; // Not selected by default
  153. // attrCb.addEventListener('change', () => {
  154. // if (attrCb.checked) {
  155. // // Select the main checkbox
  156. // cb_attribute.checked = true;
  157. // setChecked(p.item_id, true);
  158. // row.classList.add('selected');
  159. // } else {
  160. // // Optionally uncheck main if attrCb is unchecked
  161. // // (optional logic)
  162. // }
  163. // });
  164. // const attrSpan = el('span');
  165. // attrSpan.textContent = `Select mandatory (${p.mandatoryAttributes.join(', ')})`;
  166. // attrLabel.appendChild(attrCb);
  167. // attrLabel.appendChild(attrSpan);
  168. // rightAttribute.appendChild(attrLabel);
  169. // }
  170. const attri = el('p',"pSelectRight");
  171. attri.innerHTML = "Select Attribute : ";
  172. var secondRight = el('label', 'selectRight');
  173. if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  174. p.mandatoryAttributes.forEach((data,index)=>{
  175. const cbSeond = document.createElement('input');
  176. cbSeond.type = 'checkbox';
  177. cbSeond.checked = selectedIds.has(p.item_id);
  178. cbSeond.addEventListener('change', () => { setChecked(p.item_id, cbSeond.checked);
  179. row.classList.toggle('selected', cbSeond.checked); });
  180. const lblsecond = el('span');
  181. lblsecond.className = "attributeName";
  182. lblsecond.textContent = data;
  183. secondRight.appendChild(cbSeond); secondRight.appendChild(lblsecond);
  184. })
  185. }
  186. const right = el('label', 'select');
  187. const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
  188. cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); row.classList.toggle('selected', cb.checked); });
  189. const lbl = el('span'); lbl.textContent = 'Select';
  190. right.appendChild(cb); right.appendChild(lbl);
  191. // Inline attributes container (rendered on Submit)
  192. const inline = el('div', 'attr-inline');
  193. inline.dataset.pid = p.item_id; // use item_id for mapping
  194. row.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  195. row.appendChild(left); row.appendChild(mid);
  196. row.appendChild(right);
  197. if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  198. // const hr = el('hr');
  199. // row.appendChild(hr);
  200. row.appendChild(attri);
  201. row.appendChild(secondRight);
  202. }
  203. row.appendChild(inline);
  204. return row;
  205. }
  206. // function renderProductsCards() {
  207. // const cards = $('#cardsContainer');
  208. // cards.innerHTML = '';
  209. // if(PRODUCT_BASE.length > 0){
  210. // PRODUCT_BASE.forEach(p => cards.appendChild(createProductCard(p)));
  211. // }else{
  212. // cards.innerHTML = "<p>No Products Found.</p>"
  213. // }
  214. // }
  215. // Cards layout
  216. function renderProductsCards(items = getCurrentSlice()) {
  217. const cards = document.getElementById('cardsContainer');
  218. cards.innerHTML = '';
  219. if(items.length > 0){
  220. items.forEach(p => cards.appendChild(createProductCard(p)));
  221. }else{
  222. cards.innerHTML = "<p>No Products Found.</p>"
  223. }
  224. }
  225. // --- Table layout ---
  226. function createMiniThumb(p) {
  227. const mt = el('div', 'mini-thumb');
  228. const img = new Image(); img.src = mediaUrl+p.image_path || p.image || ''; img.alt = `${p.product_name} image`;
  229. console.log("img",img);
  230. img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  231. // 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); };
  232. mt.appendChild(img);
  233. return mt;
  234. }
  235. // function renderProductsTable() {
  236. // const wrap = $('#tableContainer');
  237. // wrap.innerHTML = '';
  238. // const table = el('table');
  239. // const thead = el('thead'); const trh = el('tr');
  240. // const headers = ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'];
  241. // headers.forEach(h => { const th = el('th'); th.textContent = h; trh.appendChild(th); });
  242. // thead.appendChild(trh); table.appendChild(thead);
  243. // const tbody = el('tbody');
  244. // if(PRODUCT_BASE.length > 0){
  245. // PRODUCT_BASE.forEach(p => {
  246. // const tr = el('tr'); tr.id = `row-${p.id}`;
  247. // // Select cell
  248. // const tdSel = el('td', 'select-cell'); const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.id);
  249. // cb.addEventListener('change', () => { setChecked(p.id, cb.checked); tr.classList.toggle('selected', cb.checked); }); tdSel.appendChild(cb); tr.appendChild(tdSel);
  250. // // Image
  251. // const tdImg = el('td', 'thumb-cell'); tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  252. // // Product name
  253. // const tdName = el('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  254. // // SKU
  255. // const tdSku = el('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  256. // // Type
  257. // const tdType = el('td'); const b = el('span', 'badge'); b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  258. // // Short description
  259. // const tdDesc = el('td'); tdDesc.innerHTML = p.product_short_description || ''; tr.appendChild(tdDesc);
  260. // tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  261. // tbody.appendChild(tr);
  262. // });
  263. // }else{
  264. // const tr = el('tr');
  265. // // tr.id = `row-${p.id}`;
  266. // const tdName = el('td');
  267. // tdName.colSpan = 6;
  268. // tdName.innerHTML = "No Products Found."
  269. // tr.appendChild(tdName);
  270. // // tr.colspan = 6;
  271. // // tr.innerHTML
  272. // tbody.appendChild(tr);
  273. // }
  274. // table.appendChild(tbody);
  275. // wrap.appendChild(table);
  276. // }
  277. // --- Inline attributes rendering ---
  278. // Table layout
  279. function renderProductsTable(items = getCurrentSlice()) {
  280. const wrap = document.getElementById('tableContainer');
  281. wrap.innerHTML = '';
  282. const table = document.createElement('table');
  283. const thead = document.createElement('thead'); const trh = document.createElement('tr');
  284. ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
  285. const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
  286. });
  287. thead.appendChild(trh); table.appendChild(thead);
  288. const tbody = document.createElement('tbody');
  289. if(items.length > 0 ){
  290. items.forEach(p => {
  291. const tr = document.createElement('tr'); tr.id = `row-${p.id}`;
  292. const tdSel = document.createElement('td'); tdSel.className = 'select-cell';
  293. const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
  294. cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); tr.classList.toggle('selected', cb.checked); });
  295. tdSel.appendChild(cb); tr.appendChild(tdSel);
  296. const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  297. const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  298. const tdSku = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  299. const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  300. const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
  301. tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  302. tbody.appendChild(tr);
  303. });
  304. }else{
  305. const tr = el('tr');
  306. // tr.id = `row-${p.id}`;
  307. const tdName = el('td');
  308. tdName.colSpan = 6;
  309. tdName.innerHTML = "No Products Found."
  310. tr.appendChild(tdName);
  311. // tr.colspan = 6;
  312. // tr.innerHTML
  313. tbody.appendChild(tr);
  314. }
  315. table.appendChild(tbody);
  316. wrap.appendChild(table);
  317. }
  318. function renderInlineForCards() {
  319. const api = FAKE_API_RESPONSE;
  320. // Clear all inline sections first
  321. document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  322. PRODUCT_BASE.forEach((p, idx) => {
  323. const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  324. if (!inline) return;
  325. if (!selectedIds.has(p.item_id)) return; // only show for selected
  326. const res = findApiResultForProduct(p, idx, api);
  327. const pid = p.item_id;
  328. if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
  329. const mem = lastSeen.get(pid);
  330. // Build sections
  331. const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  332. const manChips = el('div', 'chips');
  333. const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  334. const addChips = el('div', 'chips');
  335. const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  336. const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  337. const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  338. const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  339. const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  340. counts.appendChild(c1); counts.appendChild(c2);
  341. inline.appendChild(manTitle); inline.appendChild(manChips);
  342. inline.appendChild(addTitle); inline.appendChild(addChips);
  343. inline.appendChild(counts);
  344. });
  345. // Update summary
  346. $('#statTotal').textContent = api.total_products ?? 0;
  347. $('#statOk').textContent = api.successful ?? 0;
  348. $('#statKo').textContent = api.failed ?? 0;
  349. $('#api-summary').style.display = 'block';
  350. }
  351. function renderInlineForTable() {
  352. const api = FAKE_API_RESPONSE;
  353. const table = $('#tableContainer');
  354. if (!table) return;
  355. // Remove existing detail rows
  356. table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  357. PRODUCT_BASE.forEach((p, idx) => {
  358. if (!selectedIds.has(p.item_id)) return;
  359. const res = findApiResultForProduct(p, idx, api);
  360. const pid = p.item_id;
  361. if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
  362. const mem = lastSeen.get(pid);
  363. const tbody = table.querySelector('tbody');
  364. const baseRow = tbody.querySelector(`#row-${p.id}`);
  365. if (!baseRow) return;
  366. const detail = el('tr', 'detail-row');
  367. const td = el('td'); td.colSpan = 6; // number of columns
  368. const content = el('div', 'detail-content');
  369. const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  370. const manChips = el('div', 'chips');
  371. const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  372. const addChips = el('div', 'chips');
  373. const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  374. const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  375. const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  376. const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  377. const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  378. counts.appendChild(c1); counts.appendChild(c2);
  379. content.appendChild(manTitle); content.appendChild(manChips);
  380. content.appendChild(addTitle); content.appendChild(addChips);
  381. content.appendChild(counts);
  382. td.appendChild(content); detail.appendChild(td);
  383. // insert after base row
  384. baseRow.insertAdjacentElement('afterend', detail);
  385. });
  386. // Update summary
  387. $('#statTotal').textContent = api.total_products ?? 0;
  388. $('#statOk').textContent = api.successful ?? 0;
  389. $('#statKo').textContent = api.failed ?? 0;
  390. }
  391. function renderInlineAttributes() {
  392. if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
  393. }
  394. // --- Main rendering ---
  395. function renderProducts() {
  396. if (layoutMode === 'cards') {
  397. $('#cardsContainer').style.display = '';
  398. $('#tableContainer').style.display = 'none';
  399. console.log("PRODUCT_BASE",PRODUCT_BASE);
  400. renderProductsCards();
  401. } else {
  402. $('#cardsContainer').style.display = 'none';
  403. $('#tableContainer').style.display = '';
  404. renderProductsTable();
  405. }
  406. updateSelectionInfo();
  407. renderPagination();
  408. // If there is a selection, re-render inline attributes (persist across toggle)
  409. if (selectedIds.size > 0) renderInlineAttributes();
  410. }
  411. // --- Submit & Reset ---
  412. function submitAttributes() {
  413. if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
  414. console.log("selectedIds",selectedIds);
  415. jQuery('#full-page-loader').show();
  416. // let inputArray = {
  417. // "product_ids" : [...selectedIds]
  418. // }
  419. const extractAdditional = document.getElementById('extract_additional').checked;
  420. const processImage = document.getElementById('process_image').checked;
  421. let inputArray = {
  422. "item_ids": [...selectedIds],
  423. "mandatory_attrs": {
  424. "color": ["color", "shade"],
  425. "size": ["size", "fit"],
  426. "fabric": ["fabric", "material"]
  427. },
  428. "model": "llama-3.1-8b-instant",
  429. "extract_additional": extractAdditional,
  430. "process_image": processImage
  431. }
  432. let raw = JSON.stringify(inputArray);
  433. fetch('/attr/batch-extract/', {
  434. method: 'POST', // or 'POST' if your API expects POST
  435. headers: {
  436. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
  437. 'Content-Type': "application/json"
  438. },
  439. body: raw
  440. })
  441. .then(response => response.json())
  442. .then(data => {
  443. console.log("response data",data);
  444. FAKE_API_RESPONSE = data;
  445. renderInlineAttributes();
  446. jQuery('#full-page-loader').hide();
  447. });
  448. }
  449. function resetAll() {
  450. selectedIds.clear();
  451. lastSeen.clear();
  452. renderProducts();
  453. // Clear summary
  454. document.getElementById('statTotal').textContent = '0';
  455. document.getElementById('statOk').textContent = '0';
  456. document.getElementById('statKo').textContent = '0';
  457. $('#api-summary').style.display = 'none';
  458. }
  459. function setLayout(mode) {
  460. layoutMode = mode;
  461. const btnCards = document.getElementById('btnCards');
  462. const btnTable = document.getElementById('btnTable');
  463. if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
  464. else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
  465. renderProducts();
  466. }
  467. // Upload elements (Bootstrap modal version)
  468. const uploadModalEl = document.getElementById('uploadModal');
  469. const dropzone = document.getElementById('dropzone');
  470. const uploadFiles = document.getElementById('uploadFiles');
  471. const fileInfo = document.getElementById('fileInfo');
  472. const uploadBar = document.getElementById('uploadBar');
  473. const uploadStatus = document.getElementById('uploadStatus');
  474. // Reset modal on show
  475. uploadModalEl.addEventListener('shown.bs.modal', () => {
  476. uploadStatus.textContent = '';
  477. uploadStatus.className = ''; // clear success/error class
  478. uploadBar.style.width = '0%';
  479. uploadBar.setAttribute('aria-valuenow', '0');
  480. uploadFiles.value = '';
  481. uploadFiles.setAttribute('accept', ACCEPT_TYPES);
  482. fileInfo.textContent = 'No files selected.';
  483. });
  484. function describeFiles(list) {
  485. if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
  486. const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
  487. fileInfo.textContent = names.join(', ');
  488. }
  489. // Drag & drop feedback
  490. ['dragenter','dragover'].forEach(evt => {
  491. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
  492. });
  493. ['dragleave','drop'].forEach(evt => {
  494. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
  495. });
  496. // Handle drop
  497. dropzone.addEventListener('drop', e => {
  498. uploadFiles.files = e.dataTransfer.files;
  499. describeFiles(uploadFiles.files);
  500. });
  501. // Click to browse
  502. // dropzone.addEventListener('click', () => uploadFiles.click());
  503. // Picker change
  504. uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
  505. function startUpload() {
  506. const files = uploadFiles.files;
  507. if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
  508. jQuery('#full-page-loader').show();
  509. uploadStatus.textContent = 'Uploading...';
  510. uploadStatus.className = ''; // neutral
  511. uploadBar.style.width = '0%';
  512. uploadBar.setAttribute('aria-valuenow', '0');
  513. const form = new FormData();
  514. Array.from(files).forEach(f => form.append('file', f));
  515. // form.append('uploaded_by', 'Vishal'); // example extra field
  516. const xhr = new XMLHttpRequest();
  517. xhr.open('POST', UPLOAD_API_URL, true);
  518. // If you need auth:
  519. // xhr.setRequestHeader('Authorization', 'Bearer <token>');
  520. xhr.upload.onprogress = (e) => {
  521. if (e.lengthComputable) {
  522. const pct = Math.round((e.loaded / e.total) * 100);
  523. uploadBar.style.width = pct + '%';
  524. uploadBar.setAttribute('aria-valuenow', String(pct));
  525. }
  526. };
  527. xhr.onreadystatechange = () => {
  528. if (xhr.readyState === 4) {
  529. const ok = (xhr.status >= 200 && xhr.status < 300);
  530. try {
  531. const resp = JSON.parse(xhr.responseText || '{}');
  532. uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
  533. } catch {
  534. uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
  535. }
  536. uploadStatus.className = ok ? 'success' : 'error';
  537. // Optional: auto-close the modal on success after 1.2s:
  538. // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
  539. }
  540. };
  541. xhr.onerror = () => {
  542. uploadStatus.textContent = 'Network error during upload.';
  543. uploadStatus.className = 'error';
  544. };
  545. xhr.send(form);
  546. setTimeout(()=>{
  547. jQuery('#uploadModal').modal('hide');
  548. },3000)
  549. jQuery('#full-page-loader').hide();
  550. }
  551. // Wire Start button
  552. document.getElementById('uploadStart').addEventListener('click', startUpload);
  553. // Cancel button already closes the modal via data-bs-dismiss
  554. // --- Pagination state ---
  555. let page = 1;
  556. let pageSize = 5; // default rows per page
  557. function totalPages() {
  558. return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
  559. }
  560. function clampPage() {
  561. page = Math.min(Math.max(1, page), totalPages());
  562. }
  563. function getCurrentSlice() {
  564. clampPage();
  565. const start = (page - 1) * pageSize;
  566. return PRODUCT_BASE.slice(start, start + pageSize);
  567. }
  568. function renderPagination() {
  569. const bar = document.getElementById('paginationBar');
  570. if (!bar) return;
  571. const tp = totalPages();
  572. clampPage();
  573. bar.innerHTML = `
  574. <div class="page-size">
  575. <label for="pageSizeSelect">Rows per page</label>
  576. <select id="pageSizeSelect">
  577. <option value="5" ${pageSize===5 ? 'selected' : ''}>5</option>
  578. <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
  579. <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
  580. <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
  581. <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
  582. </select>
  583. </div>
  584. <div class="pager">
  585. <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
  586. <span class="page-info">Page ${page} of ${tp}</span>
  587. <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
  588. </div>
  589. `;
  590. // wire events
  591. document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
  592. document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
  593. const sel = document.getElementById('pageSizeSelect');
  594. if (sel) {
  595. sel.addEventListener('change', () => {
  596. const val = sel.value;
  597. pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
  598. page = 1; // reset to first page when size changes
  599. renderProducts();
  600. });
  601. }
  602. }