attr-extraction.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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 = 'table'; // '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. // Helper function to create the chip UI for attributes
  140. function createAttributeChips(p, attr, initialSelected, isMandatory, updateCallback) {
  141. const wrapper = el('div', 'attribute-chip-group');
  142. wrapper.dataset.attrName = attr.attribute_name;
  143. wrapper.innerHTML = `<p class="attribute-header">${attr.attribute_name} (${isMandatory ? 'Mandatory' : 'Optional'}):</p>`;
  144. const chipContainer = el('div', 'chips-container');
  145. attr.possible_values.forEach(value => {
  146. const chip = el('label', 'attribute-chip');
  147. // Checkbox input is hidden, but drives the selection state
  148. const checkbox = document.createElement('input');
  149. checkbox.type = 'checkbox';
  150. checkbox.value = value;
  151. checkbox.name = `${p.item_id}-${attr.attribute_name}`;
  152. // Set initial state
  153. checkbox.checked = initialSelected.includes(value);
  154. // The visual part of the chip
  155. const span = el('span');
  156. span.textContent = value;
  157. chip.appendChild(checkbox);
  158. chip.appendChild(span);
  159. chipContainer.appendChild(chip);
  160. });
  161. // Use event delegation on the container for performance
  162. chipContainer.addEventListener('change', updateCallback);
  163. wrapper.appendChild(chipContainer);
  164. return wrapper;
  165. }
  166. // --- Main Select Checkbox (Product Selection) ---
  167. const right = el('label', 'select');
  168. const cb = document.createElement('input'); cb.type = 'checkbox';
  169. cb.checked = isProductSelected(p.item_id);
  170. const lbl = el('span'); lbl.textContent = 'Select Product';
  171. right.appendChild(cb); right.appendChild(lbl);
  172. // --- Dynamic Attribute Selects ---
  173. const attrContainer = el('div', 'attribute-selectors');
  174. // Find all mandatory and non-mandatory attributes for this product
  175. const mandatoryAttributes = p.product_type_details?.filter(a => a.is_mandatory === 'Yes') || [];
  176. const optionalAttributes = p.product_type_details?.filter(a => a.is_mandatory !== 'Yes') || [];
  177. // Helper to update the main state object with all current selections
  178. const updateProductState = () => {
  179. const isSelected = cb.checked;
  180. const currentSelections = {};
  181. if (isSelected) {
  182. // Iterate over all attribute groups (Mandatory and Optional)
  183. attrContainer.querySelectorAll('.attribute-chip-group').forEach(group => {
  184. const attrName = group.dataset.attrName;
  185. // Collect selected chip values
  186. const selectedOptions = Array.from(group.querySelectorAll('input[type="checkbox"]:checked'))
  187. .map(checkbox => checkbox.value);
  188. if (selectedOptions.length > 0) {
  189. currentSelections[attrName] = selectedOptions;
  190. }
  191. });
  192. }
  193. toggleProductSelection(p.item_id, isSelected, currentSelections);
  194. row.classList.toggle('selected', isSelected);
  195. };
  196. // Attach listener to main checkbox
  197. cb.addEventListener('change', () => {
  198. attrContainer.classList.toggle('disabled', !cb.checked);
  199. updateProductState();
  200. });
  201. // --- Render Mandatory Attributes ---
  202. if (mandatoryAttributes.length > 0) {
  203. const manTitle = el('p', "pSelectRight mandatory-title");
  204. manTitle.innerHTML = "Mandatory Attributes:";
  205. attrContainer.appendChild(manTitle);
  206. mandatoryAttributes.forEach(attr => {
  207. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  208. const chipGroup = createAttributeChips(p, attr, initialSelected, true, updateProductState);
  209. attrContainer.appendChild(chipGroup);
  210. });
  211. }
  212. // --- Render Optional Attributes ---
  213. if (optionalAttributes.length > 0) {
  214. const br = el('br');
  215. const optTitle = el('p', "pSelectRight optional-title");
  216. optTitle.innerHTML = "Optional Attributes:";
  217. attrContainer.appendChild(br);
  218. attrContainer.appendChild(optTitle);
  219. optionalAttributes.forEach(attr => {
  220. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  221. const chipGroup = createAttributeChips(p, attr, initialSelected, false, updateProductState);
  222. attrContainer.appendChild(chipGroup);
  223. });
  224. }
  225. // Initialize attribute selectors' enabled state and state data
  226. attrContainer.classList.toggle('disabled', !cb.checked);
  227. // Initial state setup if the product was already selected (e.g., after a re-render)
  228. if (cb.checked) {
  229. // This is important to set the initial state correctly on load
  230. // We defer this until all selects are mounted, or ensure the initial state is correct.
  231. // For simplicity, we assume the data from PRODUCT_BASE already includes selected attributes if a selection exists
  232. // (which it won't in this case, so they default to all/empty)
  233. }
  234. const inline = el('div', 'attr-inline');
  235. inline.dataset.pid = p.item_id; // use item_id for mapping
  236. row.appendChild(left); row.appendChild(mid);
  237. row.appendChild(attrContainer); // Append the new attribute selectors container
  238. row.appendChild(right);
  239. // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  240. // const hr = el('hr');
  241. // row.appendChild(hr);
  242. // row.appendChild(attri);
  243. // row.appendChild(secondRight);
  244. // }
  245. row.appendChild(inline);
  246. return row;
  247. }
  248. // Cards layout
  249. function renderProductsCards(items = getCurrentSlice()) {
  250. const cards = document.getElementById('cardsContainer');
  251. cards.innerHTML = '';
  252. if(items.length > 0){
  253. items.forEach(p => cards.appendChild(createProductCard(p)));
  254. }else{
  255. cards.innerHTML = "<p>No Products Found.</p>"
  256. }
  257. }
  258. // --- Table layout ---
  259. function createMiniThumb(p) {
  260. const mt = el('div', 'mini-thumb');
  261. const img = new Image(); img.src = mediaUrl+p.image_path || p.image || ''; img.alt = `${p.product_name} image`;
  262. console.log("img",img);
  263. img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  264. // 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); };
  265. mt.appendChild(img);
  266. return mt;
  267. }
  268. // Table layout
  269. // function renderProductsTable(items = getCurrentSlice()) {
  270. // const wrap = document.getElementById('tableContainer');
  271. // wrap.innerHTML = '';
  272. // const table = document.createElement('table');
  273. // const thead = document.createElement('thead'); const trh = document.createElement('tr');
  274. // ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
  275. // const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
  276. // });
  277. // thead.appendChild(trh); table.appendChild(thead);
  278. // const tbody = document.createElement('tbody');
  279. // if(items.length > 0 ){
  280. // items.forEach(p => {
  281. // const tr = document.createElement('tr'); tr.id = `row-${p.id}`;
  282. // const tdSel = document.createElement('td'); tdSel.className = 'select-cell';
  283. // const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
  284. // cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); tr.classList.toggle('selected', cb.checked); });
  285. // tdSel.appendChild(cb); tr.appendChild(tdSel);
  286. // const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  287. // const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  288. // const tdSku = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  289. // const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  290. // const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
  291. // tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  292. // tbody.appendChild(tr);
  293. // });
  294. // }else{
  295. // const tr = el('tr');
  296. // // tr.id = `row-${p.id}`;
  297. // const tdName = el('td');
  298. // tdName.colSpan = 6;
  299. // tdName.innerHTML = "No Products Found."
  300. // tr.appendChild(tdName);
  301. // // tr.colspan = 6;
  302. // // tr.innerHTML
  303. // tbody.appendChild(tr);
  304. // }
  305. // table.appendChild(tbody);
  306. // wrap.appendChild(table);
  307. // }
  308. // NOTE: Ensure getProductStateUpdater and generateAttributeUI functions are defined globally or accessible here.
  309. /**
  310. * Returns a closure function that updates the global selectedProductsWithAttributes state
  311. * based on the current selections (chips) found in the DOM for a specific product.
  312. * This is used for both card and table views.
  313. * * @param {Object} p - The product object.
  314. * @param {HTMLElement} cb - The main product selection checkbox element.
  315. * @param {HTMLElement} tr - The main row/card element (used for toggling 'selected' class).
  316. * @returns {function} A function to be used as the attribute change handler.
  317. */
  318. const getProductStateUpdater = (p, cb, tr) => () => {
  319. const isSelected = cb.checked;
  320. const currentSelections = {};
  321. // Find the attribute container using its unique ID, which is the same structure
  322. // used in both card and table detail views (e.g., 'attr-container-124353498' or just the main card element).
  323. // For card view, the container is often the attrContainer element itself.
  324. // For table view, we use the explicit ID.
  325. const attrContainer = document.getElementById(`attr-container-${p.item_id}`) || tr.querySelector('.attribute-selectors');
  326. if (isSelected && attrContainer) {
  327. // Iterate over all attribute groups (Mandatory and Optional) within the container
  328. attrContainer.querySelectorAll('.attribute-chip-group').forEach(group => {
  329. const attrName = group.dataset.attrName;
  330. // Collect selected chip values
  331. const selectedOptions = Array.from(group.querySelectorAll('input[type="checkbox"]:checked'))
  332. .map(checkbox => checkbox.value);
  333. // Only add to the selection if at least one option is selected
  334. if (selectedOptions.length > 0) {
  335. currentSelections[attrName] = selectedOptions;
  336. }
  337. });
  338. }
  339. // Update the global state array (selectedProductsWithAttributes)
  340. toggleProductSelection(p.item_id, isSelected, currentSelections);
  341. // Update the visual status of the row/card
  342. tr.classList.toggle('selected', isSelected);
  343. };
  344. /**
  345. * Generates the full attribute selection UI (chips) for a given product.
  346. * NOTE: Assumes el(), createAttributeChips(), and getSelectedAttributes() are defined globally.
  347. * @param {Object} p - The product object from PRODUCT_BASE.
  348. * @param {function} updateProductState - The callback to run on chip changes.
  349. * @param {HTMLElement} attrContainer - The container to append the UI to.
  350. */
  351. function generateAttributeUI(p, updateProductState, attrContainer) {
  352. // Clear the container first, just in case
  353. attrContainer.innerHTML = '';
  354. const mandatoryAttributes = p.product_type_details?.filter(a => a.is_mandatory === 'Yes') || [];
  355. const optionalAttributes = p.product_type_details?.filter(a => a.is_mandatory !== 'Yes') || [];
  356. // --- Render Mandatory Attributes ---
  357. if (mandatoryAttributes.length > 0) {
  358. // Use a general title for the section header
  359. const manTitle = el('p', "pSelectRight mandatory-title");
  360. manTitle.innerHTML = "Mandatory Attributes:";
  361. attrContainer.appendChild(manTitle);
  362. mandatoryAttributes.forEach(attr => {
  363. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  364. // The createAttributeChips function must be globally available
  365. const chipGroup = createAttributeChips(p, attr, initialSelected, true, updateProductState);
  366. attrContainer.appendChild(chipGroup);
  367. });
  368. }
  369. // --- Render Optional Attributes ---
  370. if (optionalAttributes.length > 0) {
  371. // Add visual separation using the optional-title class
  372. const optTitle = el('p', "pSelectRight optional-title");
  373. optTitle.innerHTML = "Optional Attributes:";
  374. // Append the title for separation
  375. attrContainer.appendChild(optTitle);
  376. optionalAttributes.forEach(attr => {
  377. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  378. const chipGroup = createAttributeChips(p, attr, initialSelected, false, updateProductState);
  379. attrContainer.appendChild(chipGroup);
  380. });
  381. }
  382. }
  383. /**
  384. * Creates the HTML structure for a single attribute group using chip/checkbox labels.
  385. * Assumes the helper function 'el' is available.
  386. * * @param {Object} p - The product object.
  387. * @param {Object} attr - The specific attribute detail object.
  388. * @param {string[]} initialSelected - Array of values that should be pre-checked.
  389. * @param {boolean} isMandatory - True if the attribute is mandatory.
  390. * @param {function} updateCallback - The function to call when a chip selection changes.
  391. * @returns {HTMLElement} The attribute chip group container (div).
  392. */
  393. function createAttributeChips(p, attr, initialSelected, isMandatory, updateCallback) {
  394. const wrapper = el('div', 'attribute-chip-group');
  395. wrapper.dataset.attrName = attr.attribute_name;
  396. // Determine the header text based on structure preference (e.g., just the name)
  397. const statusText = isMandatory ? ' (Mandatory)' : ' (Optional)';
  398. wrapper.innerHTML = `<p class="attribute-header">${attr.attribute_name}${statusText}:</p>`;
  399. const chipContainer = el('div', 'chips-container');
  400. attr.possible_values.forEach(value => {
  401. const chip = el('label', 'attribute-chip');
  402. // Checkbox input is hidden, but drives the selection state
  403. const checkbox = document.createElement('input');
  404. checkbox.type = 'checkbox';
  405. checkbox.value = value;
  406. // Ensure the name is unique per product/attribute group
  407. checkbox.name = `${p.item_id}-${attr.attribute_name}`;
  408. // Set initial state
  409. checkbox.checked = initialSelected.includes(value);
  410. // The visual part of the chip
  411. const span = el('span');
  412. span.textContent = value;
  413. chip.appendChild(checkbox);
  414. chip.appendChild(span);
  415. chipContainer.appendChild(chip);
  416. });
  417. // Attach listener to the container using event delegation
  418. chipContainer.addEventListener('change', updateCallback);
  419. wrapper.appendChild(chipContainer);
  420. return wrapper;
  421. }
  422. function renderProductsTable(items = getCurrentSlice()) {
  423. const wrap = document.getElementById('tableContainer');
  424. wrap.innerHTML = '';
  425. const table = document.createElement('table');
  426. table.classList.add('table', 'table-striped', 'table-bordered');
  427. const thead = document.createElement('thead');
  428. const trh = document.createElement('tr');
  429. // Table Headers
  430. ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description', 'Attributes'].forEach(h => {
  431. const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
  432. });
  433. thead.appendChild(trh); table.appendChild(thead);
  434. const tbody = document.createElement('tbody');
  435. if (items.length > 0) {
  436. items.forEach(p => {
  437. const tr = document.createElement('tr');
  438. tr.id = `row-${p.id}`;
  439. if (isProductSelected(p.item_id)) tr.classList.add('selected');
  440. // --- Define Checkbox (cb) and State Updater ---
  441. const cb = document.createElement('input');
  442. cb.type = 'checkbox';
  443. cb.checked = isProductSelected(p.item_id);
  444. // The state updater function is bound to this specific row/checkbox
  445. const updateProductState = getProductStateUpdater(p, cb, tr);
  446. // --- Select Cell ---
  447. const tdSel = document.createElement('td');
  448. tdSel.className = 'select-cell';
  449. tdSel.appendChild(cb);
  450. tr.appendChild(tdSel);
  451. // --- Other Cells ---
  452. const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  453. const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  454. const tdSku  = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  455. const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  456. const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
  457. // ---------------------------------------------
  458. // --- ATTRIBUTE SELECTION IMPLEMENTATION ---
  459. // ---------------------------------------------
  460. // 1. DETAIL ROW STRUCTURE
  461. const detailRow = document.createElement('tr');
  462. detailRow.classList.add('attribute-detail-row'); // Custom class for styling
  463. detailRow.style.display = 'none'; // Initially hidden
  464. detailRow.id = `detail-row-${p.id}`;
  465. const detailCell = document.createElement('td');
  466. detailCell.colSpan = 7; // Must span all columns
  467. const attrContainer = document.createElement('div');
  468. attrContainer.id = `attr-container-${p.item_id}`; // Unique ID for targeting by updateProductState
  469. attrContainer.classList.add('attribute-selectors', 'table-selectors');
  470. // 2. GENERATE CHIPS UI
  471. generateAttributeUI(p, updateProductState, attrContainer);
  472. // Initially disable the chips if the product is not selected
  473. attrContainer.classList.toggle('disabled', !cb.checked);
  474. detailCell.appendChild(attrContainer);
  475. detailRow.appendChild(detailCell);
  476. // 3. TOGGLE BUTTON (in the main row)
  477. const tdAttr = document.createElement('td');
  478. const toggleButton = document.createElement('button');
  479. toggleButton.textContent = 'Configure';
  480. toggleButton.classList.add('btn', 'btn-sm', 'btn-info', 'attribute-toggle-btn');
  481. tdAttr.appendChild(toggleButton);
  482. tr.appendChild(tdAttr);
  483. // 4. EVENT LISTENERS
  484. // a) Toggle Button Logic
  485. toggleButton.addEventListener('click', (e) => {
  486. e.stopPropagation(); // Stop row click event
  487. const isHidden = detailRow.style.display === 'none';
  488. detailRow.style.display = isHidden ? '' : 'none'; // Toggle visibility
  489. toggleButton.textContent = isHidden ? 'Hide Attributes' : 'Configure';
  490. toggleButton.classList.toggle('btn-info', !isHidden);
  491. toggleButton.classList.toggle('btn-secondary', isHidden);
  492. });
  493. // b) Main Checkbox Change Logic
  494. cb.addEventListener('change', () => {
  495. updateProductState(); // Update state on check/uncheck
  496. attrContainer.classList.toggle('disabled', !cb.checked); // Enable/Disable chips
  497. });
  498. // c) Row Click Listener (Updated to ignore button clicks)
  499. tr.addEventListener('click', (e) => {
  500. const tag = e.target.tagName.toLowerCase();
  501. if (tag !== 'input' && tag !== 'button') {
  502. cb.checked = !cb.checked;
  503. cb.dispatchEvent(new Event('change'));
  504. }
  505. });
  506. // 5. Append Rows to TBODY
  507. tbody.appendChild(tr);
  508. tbody.appendChild(detailRow); // Append the detail row right after the main row
  509. });
  510. } else {
  511. const tr = el('tr');
  512. const tdName = el('td');
  513. tdName.colSpan = 7;
  514. tdName.innerHTML = "No Products Found.";
  515. tr.appendChild(tdName);
  516. tbody.appendChild(tr);
  517. }
  518. table.appendChild(tbody);
  519. wrap.appendChild(table);
  520. }
  521. function renderInlineForCards() {
  522. const api = FAKE_API_RESPONSE;
  523. // Clear all inline sections first
  524. document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  525. PRODUCT_BASE.forEach((p, idx) => {
  526. const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  527. if (!inline) return;
  528. // --- CHANGE HERE: Use the new helper function ---
  529. if (!isProductSelected(p.item_id)) return; // only show for selected
  530. const res = findApiResultForProduct(p, idx, api);
  531. const pid = p.item_id;
  532. if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
  533. const mem = lastSeen.get(pid);
  534. // Build sections
  535. const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  536. const manChips = el('div', 'chips');
  537. const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  538. const addChips = el('div', 'chips');
  539. const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  540. const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  541. const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  542. const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  543. const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  544. counts.appendChild(c1); counts.appendChild(c2);
  545. inline.appendChild(manTitle); inline.appendChild(manChips);
  546. inline.appendChild(addTitle); inline.appendChild(addChips);
  547. inline.appendChild(counts);
  548. });
  549. // Update summary
  550. $('#statTotal').textContent = api.total_products ?? 0;
  551. $('#statOk').textContent = api.successful ?? 0;
  552. $('#statKo').textContent = api.failed ?? 0;
  553. $('#api-summary').style.display = 'block';
  554. }
  555. // -----------------------------------------------------------
  556. function renderInlineForTable() {
  557. const api = FAKE_API_RESPONSE;
  558. const table = $('#tableContainer');
  559. if (!table) return;
  560. // Remove existing detail rows
  561. table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  562. PRODUCT_BASE.forEach((p, idx) => {
  563. // --- CHANGE HERE: Use the new helper function ---
  564. if (!isProductSelected(p.item_id)) return;
  565. const res = findApiResultForProduct(p, idx, api);
  566. const pid = p.item_id;
  567. if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
  568. const mem = lastSeen.get(pid);
  569. const tbody = table.querySelector('tbody');
  570. // NOTE: The table rendering uses p.id for the row ID: `row-${p.id}`.
  571. // Assuming p.id is still valid for finding the base row, as your original code used it.
  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 = 50; // 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. });