attr-extraction.js 28 KB

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