attr-extraction-new.js 45 KB

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