attr-extraction.js 30 KB

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