attr-extraction-oldselect.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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. // NEW: Array of objects { item_id: string, mandatory_attrs: { [attribute_name]: string[] } }
  84. let selectedProductsWithAttributes = [];
  85. let selectedAttributes = new Array();
  86. const lastSeen = new Map(); // per-product memory for NEW highlighting (product_id -> maps)
  87. let layoutMode = 'cards'; // 'cards' | 'table'
  88. // --- Helpers ---
  89. const $ = (sel) => document.querySelector(sel);
  90. const el = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; return e; }
  91. function updateSelectionInfo() {
  92. const pill = $('#selectionInfo');
  93. const total = PRODUCT_BASE.length;
  94. // const count = selectedIds.size;
  95. const count = selectedProductsWithAttributes.length;
  96. pill.textContent = count === 0 ? 'No products selected' : `${count} of ${total} selected`;
  97. }
  98. function setChecked(id, checked) { if (checked) selectedIds.add(id); else selectedIds.delete(id); updateSelectionInfo(); }
  99. // function setCheckedAttributes(id,attribute, checked) { if (checked) selectedAttributes.add({id: [attribute]}); else selectedIds.delete({id:[attribute]}); updateSelectionInfo(); }
  100. // --- Chips rendering ---
  101. function renderChips(container, obj, memoryMap) {
  102. container.innerHTML = '';
  103. let count = 0;
  104. Object.entries(obj || {}).forEach(([k, v]) => {
  105. const chip = el('span', 'chip');
  106. const kEl = el('span', 'k'); kEl.textContent = k + ':';
  107. const vEl = el('span', 'v'); vEl.textContent = ' ' + String(v);
  108. chip.appendChild(kEl); chip.appendChild(vEl);
  109. const was = memoryMap.get(k);
  110. if (was === undefined || was !== v) chip.classList.add('new');
  111. container.appendChild(chip);
  112. memoryMap.set(k, v);
  113. count++;
  114. });
  115. return count;
  116. }
  117. function findApiResultForProduct(p, index, api) { return api.results?.find(r => r.product_id === p.item_id) || api.results?.[index] || null; }
  118. // --- Cards layout ---
  119. function createProductCard(p) {
  120. const row = el('div', 'product');
  121. // Check selection using the new helper
  122. if (isProductSelected(p.item_id)) row.classList.add('selected');
  123. // if (selectedIds.has(p.item_id)) row.classList.add('selected');
  124. const left = el('div', 'thumb');
  125. const img = new Image(); img.src = mediaUrl+p.image_path || p.image || '';
  126. img.alt = `${p.product_name} image`;
  127. console.log("img",img);
  128. // 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); };
  129. img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  130. left.appendChild(img);
  131. const mid = el('div', 'meta');
  132. const name = el('div', 'name'); name.textContent = p.product_name || '—';
  133. const desc = el('div', 'desc'); desc.innerHTML = p.product_short_description || '';
  134. const badges = el('div', 'badges');
  135. const sku = el('span', 'pill'); sku.textContent = `SKU: ${p.item_id || '—'}`; badges.appendChild(sku);
  136. const type = el('span', 'pill'); type.textContent = p.product_type || '—'; badges.appendChild(type);
  137. const long = el('div', 'desc'); long.innerHTML = p.product_long_description || ''; long.style.marginTop = '4px';
  138. mid.appendChild(name); mid.appendChild(desc); mid.appendChild(badges); mid.appendChild(long);
  139. // const rightAttribute = el('label', 'select');
  140. // // Main checkbox: "Select"
  141. // const cb_attribute = document.createElement('input');
  142. // cb_attribute.type = 'checkbox';
  143. // cb_attribute.checked = selectedIds.has(p.item_id);
  144. // cb_attribute.addEventListener('change', () => {
  145. // setChecked(p.item_id, cb_attribute.checked);
  146. // row.classList.toggle('selected', cb_attribute.checked);
  147. // });
  148. // const lbl_attribute = el('span');
  149. // lbl_attribute.textContent = 'Select';
  150. // rightAttribute.appendChild(cb_attribute);
  151. // rightAttribute.appendChild(lbl_attribute);
  152. // // --- New checkbox for mandatory attributes ---
  153. // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  154. // const attrLabel = el('label', 'select-attr');
  155. // const attrCb = document.createElement('input');
  156. // attrCb.type = 'checkbox';
  157. // attrCb.checked = false; // Not selected by default
  158. // attrCb.addEventListener('change', () => {
  159. // if (attrCb.checked) {
  160. // // Select the main checkbox
  161. // cb_attribute.checked = true;
  162. // setChecked(p.item_id, true);
  163. // row.classList.add('selected');
  164. // } else {
  165. // // Optionally uncheck main if attrCb is unchecked
  166. // // (optional logic)
  167. // }
  168. // });
  169. // const attrSpan = el('span');
  170. // attrSpan.textContent = `Select mandatory (${p.mandatoryAttributes.join(', ')})`;
  171. // attrLabel.appendChild(attrCb);
  172. // attrLabel.appendChild(attrSpan);
  173. // rightAttribute.appendChild(attrLabel);
  174. // }
  175. // const attri = el('p',"pSelectRight");
  176. // attri.innerHTML = "Select Attribute : ";
  177. // var secondRight = el('label', 'selectRight');
  178. // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  179. // p.mandatoryAttributes.forEach((data,index)=>{
  180. // const cbSeond = document.createElement('input');
  181. // cbSeond.type = 'checkbox';
  182. // cbSeond.checked = selectedIds.has(p.item_id);
  183. // cbSeond.addEventListener('change', () => { setChecked(p.item_id, cbSeond.checked);
  184. // row.classList.toggle('selected', cbSeond.checked); });
  185. // const lblsecond = el('span');
  186. // lblsecond.className = "attributeName";
  187. // lblsecond.textContent = data ;
  188. // secondRight.appendChild(cbSeond); secondRight.appendChild(lblsecond);
  189. // })
  190. // }
  191. // const right = el('label', 'select');
  192. // const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
  193. // cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); row.classList.toggle('selected', cb.checked); });
  194. // const lbl = el('span'); lbl.textContent = 'Select';
  195. // right.appendChild(cb); right.appendChild(lbl);
  196. // // Inline attributes container (rendered on Submit)
  197. // const inline = el('div', 'attr-inline');
  198. // inline.dataset.pid = p.item_id; // use item_id for mapping
  199. // row.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  200. // --- Main Select Checkbox (Product Selection) ---
  201. const right = el('label', 'select');
  202. const cb = document.createElement('input'); cb.type = 'checkbox';
  203. cb.checked = isProductSelected(p.item_id);
  204. const lbl = el('span'); lbl.textContent = 'Select Product';
  205. right.appendChild(cb); right.appendChild(lbl);
  206. // --- Dynamic Attribute Selects ---
  207. const attrContainer = el('div', 'attribute-selectors');
  208. // Find all mandatory and non-mandatory attributes for this product
  209. const mandatoryAttributes = p.product_type_details?.filter(a => a.is_mandatory === 'Yes') || [];
  210. const optionalAttributes = p.product_type_details?.filter(a => a.is_mandatory !== 'Yes') || [];
  211. // Helper to update the main state object with all current selections
  212. const updateProductState = () => {
  213. const isSelected = cb.checked;
  214. const currentSelections = {};
  215. // Only process attributes if the main product is selected
  216. if (isSelected) {
  217. // Get selections from the dynamic selects
  218. attrContainer.querySelectorAll('select').forEach(select => {
  219. const attrName = select.dataset.attrName;
  220. const selectedOptions = Array.from(select.options)
  221. .filter(option => option.selected)
  222. .map(option => option.value);
  223. if (selectedOptions.length > 0) {
  224. currentSelections[attrName] = selectedOptions;
  225. }
  226. });
  227. }
  228. // Use toggleProductSelection to update the state
  229. toggleProductSelection(p.item_id, isSelected, currentSelections);
  230. row.classList.toggle('selected', isSelected);
  231. };
  232. // Attach listener to main checkbox
  233. cb.addEventListener('change', () => {
  234. // Toggle the visibility/enabled state of the attribute selects
  235. attrContainer.classList.toggle('disabled', !cb.checked);
  236. updateProductState();
  237. });
  238. // --- Render Mandatory Attributes ---
  239. if (mandatoryAttributes.length > 0) {
  240. const manTitle = el('p', "pSelectRight mandatory-title");
  241. manTitle.innerHTML = "Mandatory Attributes:";
  242. attrContainer.appendChild(manTitle);
  243. mandatoryAttributes.forEach(attr => {
  244. const label = el('label', 'attribute-label');
  245. label.textContent = `${attr.attribute_name} (${attr.is_mandatory === 'Yes' ? 'Mandatory' : 'Optional'}):`;
  246. const select = el('select', 'attribute-select');
  247. select.multiple = true;
  248. select.dataset.attrName = attr.attribute_name;
  249. // Get previously selected values or default to all
  250. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  251. attr.possible_values.forEach(value => {
  252. const option = document.createElement('option');
  253. option.value = value;
  254. option.textContent = value;
  255. // Check if this option should be pre-selected
  256. option.selected = initialSelected.includes(value);
  257. select.appendChild(option);
  258. });
  259. select.addEventListener('change', updateProductState); // Update state when a selection changes
  260. label.appendChild(select);
  261. attrContainer.appendChild(label);
  262. });
  263. }
  264. // --- Render Optional Attributes (Same structure, different title) ---
  265. if (optionalAttributes.length > 0) {
  266. const optTitle = el('p', "pSelectRight optional-title");
  267. optTitle.innerHTML = "Optional Attributes:";
  268. attrContainer.appendChild(optTitle);
  269. optionalAttributes.forEach(attr => {
  270. const label = el('label', 'attribute-label');
  271. label.textContent = `${attr.attribute_name} (Optional):`;
  272. const select = el('select', 'attribute-select');
  273. select.multiple = true;
  274. select.dataset.attrName = attr.attribute_name;
  275. // Get previously selected values or default to all
  276. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  277. attr.possible_values.forEach(value => {
  278. const option = document.createElement('option');
  279. option.value = value;
  280. option.textContent = value;
  281. // Check if this option should be pre-selected
  282. option.selected = initialSelected.includes(value);
  283. select.appendChild(option);
  284. });
  285. select.addEventListener('change', updateProductState);
  286. label.appendChild(select);
  287. attrContainer.appendChild(label);
  288. });
  289. }
  290. // Initialize attribute selectors' enabled state and state data
  291. attrContainer.classList.toggle('disabled', !cb.checked);
  292. // Initial state setup if the product was already selected (e.g., after a re-render)
  293. if (cb.checked) {
  294. // This is important to set the initial state correctly on load
  295. // We defer this until all selects are mounted, or ensure the initial state is correct.
  296. // For simplicity, we assume the data from PRODUCT_BASE already includes selected attributes if a selection exists
  297. // (which it won't in this case, so they default to all/empty)
  298. }
  299. const inline = el('div', 'attr-inline');
  300. inline.dataset.pid = p.item_id; // use item_id for mapping
  301. row.addEventListener('click', (e) => {
  302. // Only toggle main checkbox if an attribute select or its option wasn't clicked
  303. if (e.target.tagName.toLowerCase() !== 'input' && e.target.tagName.toLowerCase() !== 'select' && e.target.tagName.toLowerCase() !== 'option') {
  304. cb.checked = !cb.checked;
  305. cb.dispatchEvent(new Event('change'));
  306. }
  307. });
  308. row.appendChild(left); row.appendChild(mid);
  309. row.appendChild(right);
  310. // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  311. // const hr = el('hr');
  312. // row.appendChild(hr);
  313. // row.appendChild(attri);
  314. // row.appendChild(secondRight);
  315. // }
  316. row.appendChild(attrContainer); // Append the new attribute selectors container
  317. row.appendChild(inline);
  318. return row;
  319. }
  320. // function renderProductsCards() {
  321. // const cards = $('#cardsContainer');
  322. // cards.innerHTML = '';
  323. // if(PRODUCT_BASE.length > 0){
  324. // PRODUCT_BASE.forEach(p => cards.appendChild(createProductCard(p)));
  325. // }else{
  326. // cards.innerHTML = "<p>No Products Found.</p>"
  327. // }
  328. // }
  329. // Cards layout
  330. function renderProductsCards(items = getCurrentSlice()) {
  331. const cards = document.getElementById('cardsContainer');
  332. cards.innerHTML = '';
  333. if(items.length > 0){
  334. items.forEach(p => cards.appendChild(createProductCard(p)));
  335. }else{
  336. cards.innerHTML = "<p>No Products Found.</p>"
  337. }
  338. }
  339. // --- Table layout ---
  340. function createMiniThumb(p) {
  341. const mt = el('div', 'mini-thumb');
  342. const img = new Image(); img.src = mediaUrl+p.image_path || p.image || ''; img.alt = `${p.product_name} image`;
  343. console.log("img",img);
  344. img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  345. // 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); };
  346. mt.appendChild(img);
  347. return mt;
  348. }
  349. // function renderProductsTable() {
  350. // const wrap = $('#tableContainer');
  351. // wrap.innerHTML = '';
  352. // const table = el('table');
  353. // const thead = el('thead'); const trh = el('tr');
  354. // const headers = ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'];
  355. // headers.forEach(h => { const th = el('th'); th.textContent = h; trh.appendChild(th); });
  356. // thead.appendChild(trh); table.appendChild(thead);
  357. // const tbody = el('tbody');
  358. // if(PRODUCT_BASE.length > 0){
  359. // PRODUCT_BASE.forEach(p => {
  360. // const tr = el('tr'); tr.id = `row-${p.id}`;
  361. // // Select cell
  362. // const tdSel = el('td', 'select-cell'); const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.id);
  363. // cb.addEventListener('change', () => { setChecked(p.id, cb.checked); tr.classList.toggle('selected', cb.checked); }); tdSel.appendChild(cb); tr.appendChild(tdSel);
  364. // // Image
  365. // const tdImg = el('td', 'thumb-cell'); tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  366. // // Product name
  367. // const tdName = el('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  368. // // SKU
  369. // const tdSku = el('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  370. // // Type
  371. // const tdType = el('td'); const b = el('span', 'badge'); b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  372. // // Short description
  373. // const tdDesc = el('td'); tdDesc.innerHTML = p.product_short_description || ''; tr.appendChild(tdDesc);
  374. // tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  375. // tbody.appendChild(tr);
  376. // });
  377. // }else{
  378. // const tr = el('tr');
  379. // // tr.id = `row-${p.id}`;
  380. // const tdName = el('td');
  381. // tdName.colSpan = 6;
  382. // tdName.innerHTML = "No Products Found."
  383. // tr.appendChild(tdName);
  384. // // tr.colspan = 6;
  385. // // tr.innerHTML
  386. // tbody.appendChild(tr);
  387. // }
  388. // table.appendChild(tbody);
  389. // wrap.appendChild(table);
  390. // }
  391. // --- Inline attributes rendering ---
  392. // Table layout
  393. function renderProductsTable(items = getCurrentSlice()) {
  394. const wrap = document.getElementById('tableContainer');
  395. wrap.innerHTML = '';
  396. const table = document.createElement('table');
  397. const thead = document.createElement('thead'); const trh = document.createElement('tr');
  398. ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
  399. const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
  400. });
  401. thead.appendChild(trh); table.appendChild(thead);
  402. const tbody = document.createElement('tbody');
  403. if(items.length > 0 ){
  404. items.forEach(p => {
  405. const tr = document.createElement('tr'); tr.id = `row-${p.id}`;
  406. const tdSel = document.createElement('td'); tdSel.className = 'select-cell';
  407. const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
  408. cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); tr.classList.toggle('selected', cb.checked); });
  409. tdSel.appendChild(cb); tr.appendChild(tdSel);
  410. const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  411. const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  412. const tdSku = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  413. const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  414. const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
  415. tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  416. tbody.appendChild(tr);
  417. });
  418. }else{
  419. const tr = el('tr');
  420. // tr.id = `row-${p.id}`;
  421. const tdName = el('td');
  422. tdName.colSpan = 6;
  423. tdName.innerHTML = "No Products Found."
  424. tr.appendChild(tdName);
  425. // tr.colspan = 6;
  426. // tr.innerHTML
  427. tbody.appendChild(tr);
  428. }
  429. table.appendChild(tbody);
  430. wrap.appendChild(table);
  431. }
  432. function renderInlineForCards() {
  433. const api = FAKE_API_RESPONSE;
  434. // Clear all inline sections first
  435. document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  436. PRODUCT_BASE.forEach((p, idx) => {
  437. const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  438. if (!inline) return;
  439. if (!selectedIds.has(p.item_id)) return; // only show for selected
  440. const res = findApiResultForProduct(p, idx, api);
  441. const pid = p.item_id;
  442. if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
  443. const mem = lastSeen.get(pid);
  444. // Build sections
  445. const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  446. const manChips = el('div', 'chips');
  447. const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  448. const addChips = el('div', 'chips');
  449. const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  450. const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  451. const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  452. const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  453. const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  454. counts.appendChild(c1); counts.appendChild(c2);
  455. inline.appendChild(manTitle); inline.appendChild(manChips);
  456. inline.appendChild(addTitle); inline.appendChild(addChips);
  457. inline.appendChild(counts);
  458. });
  459. // Update summary
  460. $('#statTotal').textContent = api.total_products ?? 0;
  461. $('#statOk').textContent = api.successful ?? 0;
  462. $('#statKo').textContent = api.failed ?? 0;
  463. $('#api-summary').style.display = 'block';
  464. }
  465. function renderInlineForTable() {
  466. const api = FAKE_API_RESPONSE;
  467. const table = $('#tableContainer');
  468. if (!table) return;
  469. // Remove existing detail rows
  470. table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  471. PRODUCT_BASE.forEach((p, idx) => {
  472. if (!selectedIds.has(p.item_id)) return;
  473. const res = findApiResultForProduct(p, idx, api);
  474. const pid = p.item_id;
  475. if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
  476. const mem = lastSeen.get(pid);
  477. const tbody = table.querySelector('tbody');
  478. const baseRow = tbody.querySelector(`#row-${p.id}`);
  479. if (!baseRow) return;
  480. const detail = el('tr', 'detail-row');
  481. const td = el('td'); td.colSpan = 6; // number of columns
  482. const content = el('div', 'detail-content');
  483. const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  484. const manChips = el('div', 'chips');
  485. const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  486. const addChips = el('div', 'chips');
  487. const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  488. const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  489. const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  490. const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  491. const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  492. counts.appendChild(c1); counts.appendChild(c2);
  493. content.appendChild(manTitle); content.appendChild(manChips);
  494. content.appendChild(addTitle); content.appendChild(addChips);
  495. content.appendChild(counts);
  496. td.appendChild(content); detail.appendChild(td);
  497. // insert after base row
  498. baseRow.insertAdjacentElement('afterend', detail);
  499. });
  500. // Update summary
  501. $('#statTotal').textContent = api.total_products ?? 0;
  502. $('#statOk').textContent = api.successful ?? 0;
  503. $('#statKo').textContent = api.failed ?? 0;
  504. }
  505. function renderInlineAttributes() {
  506. if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
  507. }
  508. // --- Main rendering ---
  509. function renderProducts() {
  510. if (layoutMode === 'cards') {
  511. $('#cardsContainer').style.display = '';
  512. $('#tableContainer').style.display = 'none';
  513. console.log("PRODUCT_BASE",PRODUCT_BASE);
  514. renderProductsCards();
  515. } else {
  516. $('#cardsContainer').style.display = 'none';
  517. $('#tableContainer').style.display = '';
  518. renderProductsTable();
  519. }
  520. updateSelectionInfo();
  521. renderPagination();
  522. // If there is a selection, re-render inline attributes (persist across toggle)
  523. if (selectedIds.size > 0) renderInlineAttributes();
  524. }
  525. // --- Submit & Reset ---
  526. function submitAttributes() {
  527. // Check the length of the new array
  528. if (selectedProductsWithAttributes.length === 0) {
  529. alert('Please select at least one product.');
  530. return;
  531. }
  532. // if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
  533. console.log("selectedIds",selectedIds);
  534. jQuery('#full-page-loader').show();
  535. // let inputArray = {
  536. // "product_ids" : [...selectedIds]
  537. // }
  538. const extractAdditional = document.getElementById('extract_additional').checked;
  539. const processImage = document.getElementById('process_image').checked;
  540. // Transform the new state array into the required API format
  541. const itemIds = selectedProductsWithAttributes.map(p => p.item_id);
  542. // Create the mandatory_attrs map: { item_id: { attr_name: [values] } }
  543. // NOTE: The backend API you showed expects a flattened list of "mandatory_attrs"
  544. // like: { "color": ["color", "shade"], "size": ["size", "fit"] }
  545. // It seems to ignore the selected product-specific values and uses a general list of synonyms.
  546. // Assuming the request needs a general map of *all unique* selected attributes across all selected products:
  547. let mandatoryAttrsMap = {};
  548. selectedProductsWithAttributes.forEach(product => {
  549. // Merge attributes from all selected products
  550. Object.assign(mandatoryAttrsMap, product.mandatory_attrs);
  551. });
  552. // If the API expects the complex, product-specific payload from your Q1 example:
  553. const payloadForQ1 = selectedProductsWithAttributes.map(p => ({
  554. item_id: p.item_id,
  555. mandatory_attrs: p.mandatory_attrs
  556. }));
  557. let inputArray = {
  558. "products": payloadForQ1,
  559. "model": "llama-3.1-8b-instant",
  560. "extract_additional": extractAdditional,
  561. "process_image": processImage
  562. }
  563. let raw = JSON.stringify(inputArray);
  564. fetch('/attr/batch-extract/', {
  565. method: 'POST', // or 'POST' if your API expects POST
  566. headers: {
  567. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
  568. 'Content-Type': "application/json"
  569. },
  570. body: raw
  571. })
  572. .then(response => response.json())
  573. .then(data => {
  574. console.log("response data",data);
  575. FAKE_API_RESPONSE = data;
  576. renderInlineAttributes();
  577. jQuery('#full-page-loader').hide();
  578. });
  579. }
  580. function resetAll() {
  581. selectedProductsWithAttributes = []; // Reset the main array
  582. // selectedIds.clear();
  583. lastSeen.clear();
  584. renderProducts();
  585. // Clear summary
  586. document.getElementById('statTotal').textContent = '0';
  587. document.getElementById('statOk').textContent = '0';
  588. document.getElementById('statKo').textContent = '0';
  589. $('#api-summary').style.display = 'none';
  590. }
  591. function setLayout(mode) {
  592. layoutMode = mode;
  593. const btnCards = document.getElementById('btnCards');
  594. const btnTable = document.getElementById('btnTable');
  595. if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
  596. else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
  597. renderProducts();
  598. }
  599. // Upload elements (Bootstrap modal version)
  600. const uploadModalEl = document.getElementById('uploadModal');
  601. const dropzone = document.getElementById('dropzone');
  602. const uploadFiles = document.getElementById('uploadFiles');
  603. const fileInfo = document.getElementById('fileInfo');
  604. const uploadBar = document.getElementById('uploadBar');
  605. const uploadStatus = document.getElementById('uploadStatus');
  606. // Reset modal on show
  607. uploadModalEl.addEventListener('shown.bs.modal', () => {
  608. uploadStatus.textContent = '';
  609. uploadStatus.className = ''; // clear success/error class
  610. uploadBar.style.width = '0%';
  611. uploadBar.setAttribute('aria-valuenow', '0');
  612. uploadFiles.value = '';
  613. uploadFiles.setAttribute('accept', ACCEPT_TYPES);
  614. fileInfo.textContent = 'No files selected.';
  615. });
  616. function describeFiles(list) {
  617. if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
  618. const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
  619. fileInfo.textContent = names.join(', ');
  620. }
  621. // Drag & drop feedback
  622. ['dragenter','dragover'].forEach(evt => {
  623. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
  624. });
  625. ['dragleave','drop'].forEach(evt => {
  626. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
  627. });
  628. // Handle drop
  629. dropzone.addEventListener('drop', e => {
  630. uploadFiles.files = e.dataTransfer.files;
  631. describeFiles(uploadFiles.files);
  632. });
  633. // Click to browse
  634. // dropzone.addEventListener('click', () => uploadFiles.click());
  635. // Picker change
  636. uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
  637. function startUpload() {
  638. const files = uploadFiles.files;
  639. if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
  640. jQuery('#full-page-loader').show();
  641. uploadStatus.textContent = 'Uploading...';
  642. uploadStatus.className = ''; // neutral
  643. uploadBar.style.width = '0%';
  644. uploadBar.setAttribute('aria-valuenow', '0');
  645. const form = new FormData();
  646. Array.from(files).forEach(f => form.append('file', f));
  647. // form.append('uploaded_by', 'Vishal'); // example extra field
  648. const xhr = new XMLHttpRequest();
  649. xhr.open('POST', UPLOAD_API_URL, true);
  650. // If you need auth:
  651. // xhr.setRequestHeader('Authorization', 'Bearer <token>');
  652. xhr.upload.onprogress = (e) => {
  653. if (e.lengthComputable) {
  654. const pct = Math.round((e.loaded / e.total) * 100);
  655. uploadBar.style.width = pct + '%';
  656. uploadBar.setAttribute('aria-valuenow', String(pct));
  657. }
  658. };
  659. xhr.onreadystatechange = () => {
  660. if (xhr.readyState === 4) {
  661. const ok = (xhr.status >= 200 && xhr.status < 300);
  662. try {
  663. const resp = JSON.parse(xhr.responseText || '{}');
  664. uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
  665. } catch {
  666. uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
  667. }
  668. uploadStatus.className = ok ? 'success' : 'error';
  669. // Optional: auto-close the modal on success after 1.2s:
  670. // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
  671. }
  672. };
  673. xhr.onerror = () => {
  674. uploadStatus.textContent = 'Network error during upload.';
  675. uploadStatus.className = 'error';
  676. };
  677. xhr.send(form);
  678. setTimeout(()=>{
  679. jQuery('#uploadModal').modal('hide');
  680. },3000)
  681. jQuery('#full-page-loader').hide();
  682. }
  683. // Wire Start button
  684. document.getElementById('uploadStart').addEventListener('click', startUpload);
  685. // Cancel button already closes the modal via data-bs-dismiss
  686. // --- Pagination state ---
  687. let page = 1;
  688. let pageSize = 5; // default rows per page
  689. function totalPages() {
  690. return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
  691. }
  692. function clampPage() {
  693. page = Math.min(Math.max(1, page), totalPages());
  694. }
  695. function getCurrentSlice() {
  696. clampPage();
  697. const start = (page - 1) * pageSize;
  698. return PRODUCT_BASE.slice(start, start + pageSize);
  699. }
  700. function renderPagination() {
  701. const bar = document.getElementById('paginationBar');
  702. if (!bar) return;
  703. const tp = totalPages();
  704. clampPage();
  705. bar.innerHTML = `
  706. <div class="page-size">
  707. <label for="pageSizeSelect">Rows per page</label>
  708. <select id="pageSizeSelect">
  709. <option value="5" ${pageSize===5 ? 'selected' : ''}>5</option>
  710. <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
  711. <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
  712. <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
  713. <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
  714. </select>
  715. </div>
  716. <div class="pager">
  717. <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
  718. <span class="page-info">Page ${page} of ${tp}</span>
  719. <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
  720. </div>
  721. `;
  722. // wire events
  723. document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
  724. document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
  725. const sel = document.getElementById('pageSizeSelect');
  726. if (sel) {
  727. sel.addEventListener('change', () => {
  728. const val = sel.value;
  729. pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
  730. page = 1; // reset to first page when size changes
  731. renderProducts();
  732. });
  733. }
  734. }
  735. // Function to add/remove product from the state and manage its attributes
  736. function toggleProductSelection(itemId, isChecked, attributes = {}) {
  737. const index = selectedProductsWithAttributes.findIndex(p => p.item_id === itemId);
  738. if (isChecked) {
  739. // If selecting, ensure the product object exists in the array
  740. if (index === -1) {
  741. selectedProductsWithAttributes.push({
  742. item_id: itemId,
  743. mandatory_attrs: attributes
  744. });
  745. } else {
  746. // Update attributes if the product is already selected
  747. selectedProductsWithAttributes[index].mandatory_attrs = attributes;
  748. }
  749. } else {
  750. // If deselecting, remove the product object from the array
  751. if (index !== -1) {
  752. selectedProductsWithAttributes.splice(index, 1);
  753. }
  754. }
  755. updateSelectionInfo();
  756. }
  757. // Function to get the current mandatory attributes for a selected item
  758. function getSelectedAttributes(itemId) {
  759. const productEntry = selectedProductsWithAttributes.find(p => p.item_id === itemId);
  760. return productEntry ? productEntry.mandatory_attrs : {};
  761. }
  762. // Helper to check if a product is selected
  763. function isProductSelected(itemId) {
  764. return selectedProductsWithAttributes.some(p => p.item_id === itemId);
  765. }
  766. // Helper to check if a specific attribute/value is selected
  767. function isAttributeValueSelected(itemId, attrName, value) {
  768. const attrs = getSelectedAttributes(itemId);
  769. const values = attrs[attrName];
  770. return values ? values.includes(value) : false; // Default all selected when first loaded
  771. }