attr-extraction.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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. const thresholdInput = document.getElementById('thresholdRange');
  8. const thresholdValueDisplay = document.getElementById('thresholdValue');
  9. var PRODUCT_BASE = [
  10. // { 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' },
  11. // { 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' },
  12. // { 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' },
  13. // { 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' },
  14. // { 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' }
  15. ];
  16. // --- Data ---
  17. const mediaUrl = "./../";
  18. document.addEventListener('DOMContentLoaded', () => {
  19. jQuery('#full-page-loader').show();
  20. fetch('/attr/products', {
  21. method: 'GET', // or 'POST' if your API expects POST
  22. headers: {
  23. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
  24. }
  25. })
  26. .then(response => response.json())
  27. .then(data => {
  28. // console.log("data",data);
  29. // --- Wire up ---
  30. PRODUCT_BASE = data;
  31. PRODUCT_BASE = PRODUCT_BASE.map((d)=>{return {...d,mandatoryAttributes:["color","size"]}});
  32. // console.log("PRODUCT_BASE",PRODUCT_BASE);
  33. if(PRODUCT_BASE.length > 0){
  34. $('#paginationBar').style.display = 'block';
  35. }
  36. renderProducts();
  37. getAtributeList();
  38. document.getElementById('btnSubmit').addEventListener('click', submitAttributes);
  39. document.getElementById('btnReset').addEventListener('click', resetAll);
  40. // document.getElementById('btnSelectAll').addEventListener('click', () => {
  41. // if (selectedIds.size === PRODUCT_BASE.length) { selectedIds.clear(); } else { selectedIds = new Set(PRODUCT_BASE.map(p => p.id)); }
  42. // // renderProducts();
  43. // });
  44. // Replace your existing Select All listener with this:
  45. document.getElementById('btnSelectAll').addEventListener('click', () => {
  46. // Use the container for the active layout
  47. const container = (layoutMode === 'cards')
  48. ? document.getElementById('cardsContainer')
  49. : document.getElementById('tableContainer');
  50. // Collect all visible checkboxes
  51. const boxes = Array.from(container.querySelectorAll('input[type="checkbox"]'));
  52. // If every visible checkbox is already checked, we'll deselect; otherwise select all
  53. const allChecked = boxes.length > 0 && boxes.every(cb => cb.checked);
  54. boxes.forEach(cb => {
  55. const target = !allChecked; // true to select, false to deselect
  56. if (cb.checked !== target) {
  57. cb.checked = target;
  58. // Trigger your existing "change" handler so selectedIds & row .selected class update
  59. cb.dispatchEvent(new Event('change', { bubbles: true }));
  60. }
  61. });
  62. // Update the selection pill text (doesn't re-render the list)
  63. updateSelectionInfo();
  64. });
  65. document.getElementById('btnCards').addEventListener('click', () => setLayout('cards'));
  66. document.getElementById('btnTable').addEventListener('click', () => setLayout('table'));
  67. jQuery('#full-page-loader').hide();
  68. // if (data.success) {
  69. // }
  70. });
  71. });
  72. var FAKE_API_RESPONSE = {
  73. // results: [
  74. // { 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' } },
  75. // { 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' } },
  76. // { 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' } },
  77. // { 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' } },
  78. // { 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' } }
  79. // ],
  80. // total_products: 5,
  81. // successful: 5,
  82. // failed: 0
  83. };
  84. // --- State ---
  85. let selectedIds = new Set();
  86. // NEW: Array of objects { item_id: string, mandatory_attrs: { [attribute_name]: string[] } }
  87. let selectedProductsWithAttributes = [];
  88. let selectedAttributes = new Array();
  89. const lastSeen = new Map(); // per-product memory for NEW highlighting (product_id -> maps)
  90. let layoutMode = 'table'; // 'cards' | 'table'
  91. // --- Helpers ---
  92. const $ = (sel) => document.querySelector(sel);
  93. const el = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; return e; }
  94. function updateSelectionInfo() {
  95. const pill = $('#selectionInfo');
  96. const total = PRODUCT_BASE.length;
  97. // const count = selectedIds.size;
  98. const count = selectedProductsWithAttributes.length;
  99. pill.textContent = count === 0 ? 'No products selected' : `${count} of ${total} selected`;
  100. }
  101. function setChecked(id, checked) { if (checked) selectedIds.add(id); else selectedIds.delete(id); updateSelectionInfo(); }
  102. // function setCheckedAttributes(id,attribute, checked) { if (checked) selectedAttributes.add({id: [attribute]}); else selectedIds.delete({id:[attribute]}); updateSelectionInfo(); }
  103. // --- Chips rendering ---
  104. function renderChips(container, obj, memoryMap) {
  105. container.innerHTML = '';
  106. let count = 0;
  107. Object.entries(obj || {}).forEach(([k, v]) => {
  108. const chip = el('span', 'chip');
  109. const kEl = el('span', 'k'); kEl.textContent = k + ':';
  110. // console.log("v",v);
  111. const vEl = el('span', 'v'); vEl.textContent = ' ' + String(v[0].value) +' (' +String(v[0].source) + ')';
  112. chip.appendChild(kEl); chip.appendChild(vEl);
  113. const was = memoryMap.get(k);
  114. if (was === undefined || was !== v) chip.classList.add('new');
  115. container.appendChild(chip);
  116. memoryMap.set(k, v);
  117. count++;
  118. });
  119. return count;
  120. }
  121. function findApiResultForProduct(p, index, api) { return api.results?.find(r => r.product_id === p.item_id) || api.results?.[index] || null; }
  122. // --- Cards layout ---
  123. function createProductCard(p) {
  124. const row = el('div', 'product');
  125. // Check selection using the new helper
  126. if (isProductSelected(p.item_id)) row.classList.add('selected');
  127. // if (selectedIds.has(p.item_id)) row.classList.add('selected');
  128. const left = el('div', 'thumb');
  129. const img = new Image(); img.src = p.image_path || p.image || '';
  130. // console.log("image path",p.image_path);
  131. img.alt = `${p.product_name} image`;
  132. // console.log("img",img);
  133. // 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); };
  134. img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  135. left.appendChild(img);
  136. const mid = el('div', 'meta');
  137. const name = el('div', 'name'); name.textContent = p.product_name || '—';
  138. const desc = el('div', 'desc'); desc.innerHTML = p.product_short_description || '';
  139. const badges = el('div', 'badges');
  140. const sku = el('span', 'pill'); sku.textContent = `SKU: ${p.item_id || '—'}`; badges.appendChild(sku);
  141. const type = el('span', 'pill'); type.textContent = p.product_type || '—'; badges.appendChild(type);
  142. const long = el('div', 'desc'); long.innerHTML = p.product_long_description || ''; long.style.marginTop = '4px';
  143. mid.appendChild(name); mid.appendChild(desc); mid.appendChild(badges); mid.appendChild(long);
  144. // Helper function to create the chip UI for attributes
  145. function createAttributeChips(p, attr, initialSelected, isMandatory, updateCallback) {
  146. const wrapper = el('div', 'attribute-chip-group');
  147. wrapper.dataset.attrName = attr.attribute_name;
  148. wrapper.innerHTML = `<p class="attribute-header">${attr.attribute_name} (${isMandatory ? 'Mandatory' : 'Optional'}):</p>`;
  149. const chipContainer = el('div', 'chips-container');
  150. attr.possible_values.forEach(value => {
  151. const chip = el('label', 'attribute-chip');
  152. // Checkbox input is hidden, but drives the selection state
  153. const checkbox = document.createElement('input');
  154. checkbox.type = 'checkbox';
  155. checkbox.value = value;
  156. checkbox.name = `${p.item_id}-${attr.attribute_name}`;
  157. // Set initial state
  158. checkbox.checked = initialSelected.includes(value);
  159. // The visual part of the chip
  160. const span = el('span');
  161. span.textContent = value;
  162. chip.appendChild(checkbox);
  163. chip.appendChild(span);
  164. chipContainer.appendChild(chip);
  165. });
  166. // Use event delegation on the container for performance
  167. chipContainer.addEventListener('change', updateCallback);
  168. wrapper.appendChild(chipContainer);
  169. return wrapper;
  170. }
  171. // --- Main Select Checkbox (Product Selection) ---
  172. const right = el('label', 'select');
  173. const cb = document.createElement('input'); cb.type = 'checkbox';
  174. cb.checked = isProductSelected(p.item_id);
  175. const lbl = el('span'); lbl.textContent = 'Select Product';
  176. right.appendChild(cb); right.appendChild(lbl);
  177. // --- Dynamic Attribute Selects ---
  178. const attrContainer = el('div', 'attribute-selectors');
  179. // Find all mandatory and non-mandatory attributes for this product
  180. const mandatoryAttributes = p.product_type_details?.filter(a => a.is_mandatory === 'Yes') || [];
  181. const optionalAttributes = p.product_type_details?.filter(a => a.is_mandatory !== 'Yes') || [];
  182. // Helper to update the main state object with all current selections
  183. const updateProductState = () => {
  184. const isSelected = cb.checked;
  185. const currentSelections = {};
  186. if (isSelected) {
  187. // Iterate over all attribute groups (Mandatory and Optional)
  188. attrContainer.querySelectorAll('.attribute-chip-group').forEach(group => {
  189. const attrName = group.dataset.attrName;
  190. // Collect selected chip values
  191. const selectedOptions = Array.from(group.querySelectorAll('input[type="checkbox"]:checked'))
  192. .map(checkbox => checkbox.value);
  193. if (selectedOptions.length > 0) {
  194. currentSelections[attrName] = selectedOptions;
  195. }
  196. });
  197. }
  198. toggleProductSelection(p.item_id, isSelected, currentSelections);
  199. row.classList.toggle('selected', isSelected);
  200. };
  201. // Attach listener to main checkbox
  202. cb.addEventListener('change', () => {
  203. attrContainer.classList.toggle('disabled', !cb.checked);
  204. updateProductState();
  205. });
  206. // --- Render Mandatory Attributes ---
  207. if (mandatoryAttributes.length > 0) {
  208. const manTitle = el('p', "pSelectRight mandatory-title");
  209. manTitle.innerHTML = "Mandatory Attributes:";
  210. attrContainer.appendChild(manTitle);
  211. mandatoryAttributes.forEach(attr => {
  212. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  213. const chipGroup = createAttributeChips(p, attr, initialSelected, true, updateProductState);
  214. attrContainer.appendChild(chipGroup);
  215. });
  216. }
  217. // --- Render Optional Attributes ---
  218. if (optionalAttributes.length > 0) {
  219. const br = el('br');
  220. const optTitle = el('p', "pSelectRight optional-title");
  221. optTitle.innerHTML = "Additional Attributes:";
  222. attrContainer.appendChild(br);
  223. attrContainer.appendChild(optTitle);
  224. optionalAttributes.forEach(attr => {
  225. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  226. const chipGroup = createAttributeChips(p, attr, initialSelected, false, updateProductState);
  227. attrContainer.appendChild(chipGroup);
  228. });
  229. }
  230. // Initialize attribute selectors' enabled state and state data
  231. attrContainer.classList.toggle('disabled', !cb.checked);
  232. // Initial state setup if the product was already selected (e.g., after a re-render)
  233. if (cb.checked) {
  234. // This is important to set the initial state correctly on load
  235. // We defer this until all selects are mounted, or ensure the initial state is correct.
  236. // For simplicity, we assume the data from PRODUCT_BASE already includes selected attributes if a selection exists
  237. // (which it won't in this case, so they default to all/empty)
  238. }
  239. const inline = el('div', 'attr-inline');
  240. inline.dataset.pid = p.item_id; // use item_id for mapping
  241. row.appendChild(left); row.appendChild(mid);
  242. row.appendChild(attrContainer); // Append the new attribute selectors container
  243. row.appendChild(right);
  244. // if (p.mandatoryAttributes && p.mandatoryAttributes.length > 0) {
  245. // const hr = el('hr');
  246. // row.appendChild(hr);
  247. // row.appendChild(attri);
  248. // row.appendChild(secondRight);
  249. // }
  250. row.appendChild(inline);
  251. return row;
  252. }
  253. // Cards layout
  254. function renderProductsCards(items = getCurrentSlice()) {
  255. const cards = document.getElementById('cardsContainer');
  256. cards.innerHTML = '';
  257. if(items.length > 0){
  258. items.forEach(p => cards.appendChild(createProductCard(p)));
  259. }else{
  260. cards.innerHTML = "<p>No Products Found.</p>"
  261. }
  262. }
  263. // --- Table layout ---
  264. function createMiniThumb(p) {
  265. const mt = el('div', 'mini-thumb');
  266. const img = new Image(); img.src = p.image_path || p.image || ''; img.alt = `${p.product_name} image`;
  267. // console.log("image path",p.image_path);
  268. // console.log("img",img);
  269. img.onerror = () => { img.src = mediaUrl+"media/images/no-product.png" };
  270. // 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); };
  271. mt.appendChild(img);
  272. return mt;
  273. }
  274. // Table layout
  275. // function renderProductsTable(items = getCurrentSlice()) {
  276. // const wrap = document.getElementById('tableContainer');
  277. // wrap.innerHTML = '';
  278. // const table = document.createElement('table');
  279. // const thead = document.createElement('thead'); const trh = document.createElement('tr');
  280. // ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description'].forEach(h => {
  281. // const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
  282. // });
  283. // thead.appendChild(trh); table.appendChild(thead);
  284. // const tbody = document.createElement('tbody');
  285. // if(items.length > 0 ){
  286. // items.forEach(p => {
  287. // const tr = document.createElement('tr'); tr.id = `row-${p.id}`;
  288. // const tdSel = document.createElement('td'); tdSel.className = 'select-cell';
  289. // const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = selectedIds.has(p.item_id);
  290. // cb.addEventListener('change', () => { setChecked(p.item_id, cb.checked); tr.classList.toggle('selected', cb.checked); });
  291. // tdSel.appendChild(cb); tr.appendChild(tdSel);
  292. // const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  293. // const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  294. // const tdSku = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  295. // const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  296. // const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
  297. // tr.addEventListener('click', (e) => { if (e.target.tagName.toLowerCase() !== 'input') { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); } });
  298. // tbody.appendChild(tr);
  299. // });
  300. // }else{
  301. // const tr = el('tr');
  302. // // tr.id = `row-${p.id}`;
  303. // const tdName = el('td');
  304. // tdName.colSpan = 6;
  305. // tdName.innerHTML = "No Products Found."
  306. // tr.appendChild(tdName);
  307. // // tr.colspan = 6;
  308. // // tr.innerHTML
  309. // tbody.appendChild(tr);
  310. // }
  311. // table.appendChild(tbody);
  312. // wrap.appendChild(table);
  313. // }
  314. // NOTE: Ensure getProductStateUpdater and generateAttributeUI functions are defined globally or accessible here.
  315. /**
  316. * Returns a closure function that updates the global selectedProductsWithAttributes state
  317. * based on the current selections (chips) found in the DOM for a specific product.
  318. * This is used for both card and table views.
  319. * * @param {Object} p - The product object.
  320. * @param {HTMLElement} cb - The main product selection checkbox element.
  321. * @param {HTMLElement} tr - The main row/card element (used for toggling 'selected' class).
  322. * @returns {function} A function to be used as the attribute change handler.
  323. */
  324. const getProductStateUpdater = (p, cb, tr) => () => {
  325. const isSelected = cb.checked;
  326. const currentSelections = {};
  327. // Find the attribute container using its unique ID, which is the same structure
  328. // used in both card and table detail views (e.g., 'attr-container-124353498' or just the main card element).
  329. // For card view, the container is often the attrContainer element itself.
  330. // For table view, we use the explicit ID.
  331. const attrContainer = document.getElementById(`attr-container-${p.item_id}`) || tr.querySelector('.attribute-selectors');
  332. if (isSelected && attrContainer) {
  333. // Iterate over all attribute groups (Mandatory and Optional) within the container
  334. attrContainer.querySelectorAll('.attribute-chip-group').forEach(group => {
  335. const attrName = group.dataset.attrName;
  336. // Collect selected chip values
  337. const selectedOptions = Array.from(group.querySelectorAll('input[type="checkbox"]:checked'))
  338. .map(checkbox => checkbox.value);
  339. // Only add to the selection if at least one option is selected
  340. if (selectedOptions.length > 0) {
  341. currentSelections[attrName] = selectedOptions;
  342. }
  343. });
  344. }
  345. // Update the global state array (selectedProductsWithAttributes)
  346. toggleProductSelection(p.item_id, isSelected, currentSelections);
  347. // Update the visual status of the row/card
  348. tr.classList.toggle('selected', isSelected);
  349. };
  350. /**
  351. * Generates the full attribute selection UI (chips) for a given product.
  352. * NOTE: Assumes el(), createAttributeChips(), and getSelectedAttributes() are defined globally.
  353. * @param {Object} p - The product object from PRODUCT_BASE.
  354. * @param {function} updateProductState - The callback to run on chip changes.
  355. * @param {HTMLElement} attrContainer - The container to append the UI to.
  356. */
  357. function generateAttributeUI(p, updateProductState, attrContainer) {
  358. // Clear the container first, just in case
  359. attrContainer.innerHTML = '';
  360. const mandatoryAttributes = p.product_type_details?.filter(a => a.is_mandatory === 'Yes') || [];
  361. const optionalAttributes = p.product_type_details?.filter(a => a.is_mandatory !== 'Yes') || [];
  362. // --- Render Mandatory Attributes ---
  363. if (mandatoryAttributes.length > 0) {
  364. // Use a general title for the section header
  365. const manTitle = el('p', "pSelectRight mandatory-title");
  366. manTitle.innerHTML = "Mandatory Attributes:";
  367. attrContainer.appendChild(manTitle);
  368. mandatoryAttributes.forEach(attr => {
  369. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  370. // The createAttributeChips function must be globally available
  371. const chipGroup = createAttributeChips(p, attr, initialSelected, true, updateProductState);
  372. attrContainer.appendChild(chipGroup);
  373. });
  374. }
  375. // --- Render Optional Attributes ---
  376. if (optionalAttributes.length > 0) {
  377. // Add visual separation using the optional-title class
  378. const optTitle = el('p', "pSelectRight optional-title");
  379. optTitle.innerHTML = "Additional Attributes:";
  380. // Append the title for separation
  381. attrContainer.appendChild(optTitle);
  382. optionalAttributes.forEach(attr => {
  383. const initialSelected = getSelectedAttributes(p.item_id)[attr.attribute_name] || attr.possible_values;
  384. const chipGroup = createAttributeChips(p, attr, initialSelected, false, updateProductState);
  385. attrContainer.appendChild(chipGroup);
  386. });
  387. }
  388. }
  389. /**
  390. * Creates the HTML structure for a single attribute group using chip/checkbox labels.
  391. * Assumes the helper function 'el' is available.
  392. * * @param {Object} p - The product object.
  393. * @param {Object} attr - The specific attribute detail object.
  394. * @param {string[]} initialSelected - Array of values that should be pre-checked.
  395. * @param {boolean} isMandatory - True if the attribute is mandatory.
  396. * @param {function} updateCallback - The function to call when a chip selection changes.
  397. * @returns {HTMLElement} The attribute chip group container (div).
  398. */
  399. function createAttributeChips(p, attr, initialSelected, isMandatory, updateCallback) {
  400. const wrapper = el('div', 'attribute-chip-group');
  401. wrapper.dataset.attrName = attr.attribute_name;
  402. // Determine the header text based on structure preference (e.g., just the name)
  403. const statusText = isMandatory ? ' (Mandatory)' : ' (Optional)';
  404. wrapper.innerHTML = `<p class="attribute-header">${attr.attribute_name}${statusText}:</p>`;
  405. const chipContainer = el('div', 'chips-container');
  406. attr.possible_values.forEach(value => {
  407. const chip = el('label', 'attribute-chip');
  408. // Checkbox input is hidden, but drives the selection state
  409. const checkbox = document.createElement('input');
  410. checkbox.type = 'checkbox';
  411. checkbox.value = value;
  412. // Ensure the name is unique per product/attribute group
  413. checkbox.name = `${p.item_id}-${attr.attribute_name}`;
  414. // Set initial state
  415. checkbox.checked = initialSelected.includes(value);
  416. // The visual part of the chip
  417. const span = el('span');
  418. span.textContent = value;
  419. chip.appendChild(checkbox);
  420. chip.appendChild(span);
  421. chipContainer.appendChild(chip);
  422. });
  423. // Attach listener to the container using event delegation
  424. chipContainer.addEventListener('change', updateCallback);
  425. wrapper.appendChild(chipContainer);
  426. return wrapper;
  427. }
  428. function renderProductsTable(items = getCurrentSlice()) {
  429. const wrap = document.getElementById('tableContainer');
  430. wrap.innerHTML = '';
  431. const table = document.createElement('table');
  432. table.classList.add('table', 'table-striped', 'table-bordered','table-responsive');
  433. const thead = document.createElement('thead');
  434. const trh = document.createElement('tr');
  435. // Table Headers
  436. ['Select', 'Image', 'Product', 'SKU', 'Type', 'Short Description', 'Attributes'].forEach(h => {
  437. const th = document.createElement('th'); th.textContent = h; trh.appendChild(th);
  438. });
  439. thead.appendChild(trh); table.appendChild(thead);
  440. const tbody = document.createElement('tbody');
  441. if (items.length > 0) {
  442. items.forEach(p => {
  443. const tr = document.createElement('tr');
  444. tr.id = `row-${p.id}`;
  445. if (isProductSelected(p.item_id)) tr.classList.add('selected');
  446. // --- Define Checkbox (cb) and State Updater ---
  447. const cb = document.createElement('input');
  448. cb.type = 'checkbox';
  449. cb.checked = isProductSelected(p.item_id);
  450. // The state updater function is bound to this specific row/checkbox
  451. const updateProductState = getProductStateUpdater(p, cb, tr);
  452. // --- Select Cell ---
  453. const tdSel = document.createElement('td');
  454. tdSel.className = 'select-cell';
  455. tdSel.appendChild(cb);
  456. tr.appendChild(tdSel);
  457. // --- Other Cells ---
  458. const tdImg = document.createElement('td'); tdImg.className = 'thumb-cell'; tdImg.appendChild(createMiniThumb(p)); tr.appendChild(tdImg);
  459. const tdName = document.createElement('td'); tdName.textContent = p.product_name || '—'; tr.appendChild(tdName);
  460. const tdSku  = document.createElement('td'); tdSku.textContent = p.item_id || '—'; tr.appendChild(tdSku);
  461. const tdType = document.createElement('td'); const b = document.createElement('span'); b.className = 'badge'; b.textContent = p.product_type || '—'; tdType.appendChild(b); tr.appendChild(tdType);
  462. const tdDesc = document.createElement('td'); tdDesc.textContent = p.product_short_description || ''; tr.appendChild(tdDesc);
  463. // ---------------------------------------------
  464. // --- ATTRIBUTE SELECTION IMPLEMENTATION ---
  465. // ---------------------------------------------
  466. // 1. DETAIL ROW STRUCTURE
  467. const detailRow = document.createElement('tr');
  468. detailRow.classList.add('attribute-detail-row'); // Custom class for styling
  469. detailRow.style.display = 'none'; // Initially hidden
  470. detailRow.id = `detail-row-${p.id}`;
  471. const detailCell = document.createElement('td');
  472. detailCell.colSpan = 7; // Must span all columns
  473. const attrContainer = document.createElement('div');
  474. attrContainer.id = `attr-container-${p.item_id}`; // Unique ID for targeting by updateProductState
  475. attrContainer.classList.add('attribute-selectors', 'table-selectors');
  476. // 2. GENERATE CHIPS UI
  477. generateAttributeUI(p, updateProductState, attrContainer);
  478. // Initially disable the chips if the product is not selected
  479. attrContainer.classList.toggle('disabled', !cb.checked);
  480. detailCell.appendChild(attrContainer);
  481. detailRow.appendChild(detailCell);
  482. // 3. TOGGLE BUTTON (in the main row)
  483. const tdAttr = document.createElement('td');
  484. const toggleButton = document.createElement('button');
  485. toggleButton.textContent = 'Configure';
  486. toggleButton.classList.add('btn', 'btn-sm', 'btn-info', 'attribute-toggle-btn');
  487. tdAttr.appendChild(toggleButton);
  488. tr.appendChild(tdAttr);
  489. // 4. EVENT LISTENERS
  490. // a) Toggle Button Logic
  491. toggleButton.addEventListener('click', (e) => {
  492. e.stopPropagation(); // Stop row click event
  493. const isHidden = detailRow.style.display === 'none';
  494. detailRow.style.display = isHidden ? '' : 'none'; // Toggle visibility
  495. toggleButton.textContent = isHidden ? 'Hide Attributes' : 'Configure';
  496. toggleButton.classList.toggle('btn-info', !isHidden);
  497. toggleButton.classList.toggle('btn-secondary', isHidden);
  498. });
  499. // b) Main Checkbox Change Logic
  500. cb.addEventListener('change', () => {
  501. updateProductState(); // Update state on check/uncheck
  502. attrContainer.classList.toggle('disabled', !cb.checked); // Enable/Disable chips
  503. });
  504. // c) Row Click Listener (Updated to ignore button clicks)
  505. tr.addEventListener('click', (e) => {
  506. const tag = e.target.tagName.toLowerCase();
  507. if (tag !== 'input' && tag !== 'button') {
  508. cb.checked = !cb.checked;
  509. cb.dispatchEvent(new Event('change'));
  510. }
  511. });
  512. // 5. Append Rows to TBODY
  513. tbody.appendChild(tr);
  514. tbody.appendChild(detailRow); // Append the detail row right after the main row
  515. });
  516. } else {
  517. const tr = el('tr');
  518. const tdName = el('td');
  519. tdName.colSpan = 7;
  520. tdName.innerHTML = "No Products Found.";
  521. tr.appendChild(tdName);
  522. tbody.appendChild(tr);
  523. }
  524. table.appendChild(tbody);
  525. wrap.appendChild(table);
  526. }
  527. function renderInlineForCards() {
  528. const api = FAKE_API_RESPONSE;
  529. // Clear all inline sections first
  530. document.querySelectorAll('.attr-inline').forEach(div => div.innerHTML = '');
  531. PRODUCT_BASE.forEach((p, idx) => {
  532. const inline = document.querySelector(`.attr-inline[data-pid="${p.item_id}"]`);
  533. if (!inline) return;
  534. // --- CHANGE HERE: Use the new helper function ---
  535. if (!isProductSelected(p.item_id)) return; // only show for selected
  536. const res = findApiResultForProduct(p, idx, api);
  537. const pid = p.item_id;
  538. if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
  539. const mem = lastSeen.get(pid);
  540. // Build sections
  541. const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  542. const manChips = el('div', 'chips');
  543. const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  544. const addChips = el('div', 'chips');
  545. const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  546. const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  547. const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  548. const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  549. const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  550. counts.appendChild(c1); counts.appendChild(c2);
  551. inline.appendChild(manTitle); inline.appendChild(manChips);
  552. inline.appendChild(addTitle); inline.appendChild(addChips);
  553. inline.appendChild(counts);
  554. });
  555. // Update summary
  556. $('#statTotal').textContent = api.total_products ?? 0;
  557. $('#statOk').textContent = api.successful ?? 0;
  558. $('#statKo').textContent = api.failed ?? 0;
  559. $('#api-summary').style.display = 'block';
  560. }
  561. // -----------------------------------------------------------
  562. function renderInlineForTable() {
  563. const api = FAKE_API_RESPONSE;
  564. const table = $('#tableContainer');
  565. if (!table) return;
  566. // Remove existing detail rows
  567. table.querySelectorAll('tr.detail-row').forEach(r => r.remove());
  568. PRODUCT_BASE.forEach((p, idx) => {
  569. // --- CHANGE HERE: Use the new helper function ---
  570. if (!isProductSelected(p.item_id)) return;
  571. const res = findApiResultForProduct(p, idx, api);
  572. const pid = p.item_id;
  573. if (!lastSeen.has(pid)) lastSeen.set(pid, { mandatory: new Map(), additional: new Map() });
  574. const mem = lastSeen.get(pid);
  575. const tbody = table.querySelector('tbody');
  576. // NOTE: The table rendering uses p.id for the row ID: `row-${p.id}`.
  577. // Assuming p.id is still valid for finding the base row, as your original code used it.
  578. const baseRow = tbody.querySelector(`#row-${p.id}`);
  579. if (!baseRow) return;
  580. const detail = el('tr', 'detail-row');
  581. const td = el('td'); td.colSpan = 6; // number of columns
  582. const content = el('div', 'detail-content');
  583. const manTitle = el('div', 'section-title'); manTitle.innerHTML = '<strong>Mandatory</strong>';
  584. const manChips = el('div', 'chips');
  585. const addTitle = el('div', 'section-title'); addTitle.innerHTML = '<strong>Additional</strong>';
  586. const addChips = el('div', 'chips');
  587. const mandCount = renderChips(manChips, res?.mandatory || {}, mem.mandatory);
  588. const addCount = renderChips(addChips, res?.additional || {}, mem.additional);
  589. const counts = el('div'); counts.style.display = 'flex'; counts.style.gap = '8px'; counts.style.margin = '8px 0 0';
  590. const c1 = el('span', 'pill'); c1.textContent = `Mandatory: ${mandCount}`;
  591. const c2 = el('span', 'pill'); c2.textContent = `Additional: ${addCount}`;
  592. counts.appendChild(c1); counts.appendChild(c2);
  593. content.appendChild(manTitle); content.appendChild(manChips);
  594. content.appendChild(addTitle); content.appendChild(addChips);
  595. content.appendChild(counts);
  596. td.appendChild(content); detail.appendChild(td);
  597. // insert after base row
  598. baseRow.insertAdjacentElement('afterend', detail);
  599. });
  600. // Update summary
  601. $('#statTotal').textContent = api.total_products ?? 0;
  602. $('#statOk').textContent = api.successful ?? 0;
  603. $('#statKo').textContent = api.failed ?? 0;
  604. $('#api-summary').style.display = 'block';
  605. }
  606. function renderInlineAttributes() {
  607. if (layoutMode === 'cards') renderInlineForCards(); else renderInlineForTable();
  608. }
  609. // --- Main rendering ---
  610. function renderProducts() {
  611. if (layoutMode === 'cards') {
  612. $('#cardsContainer').style.display = '';
  613. $('#tableContainer').style.display = 'none';
  614. // console.log("PRODUCT_BASE",PRODUCT_BASE);
  615. renderProductsCards();
  616. } else {
  617. $('#cardsContainer').style.display = 'none';
  618. $('#tableContainer').style.display = '';
  619. renderProductsTable();
  620. }
  621. updateSelectionInfo();
  622. renderPagination();
  623. // If there is a selection, re-render inline attributes (persist across toggle)
  624. if (selectedIds.size > 0) renderInlineAttributes();
  625. }
  626. // --- Submit & Reset ---
  627. function submitAttributes() {
  628. // Check the length of the new array
  629. if (selectedProductsWithAttributes.length === 0) {
  630. alert('Please select at least one product.');
  631. return;
  632. }
  633. // if (selectedIds.size === 0) { alert('Please select at least one product.'); return; }
  634. // console.log("selectedIds",selectedIds);
  635. jQuery('#full-page-loader').show();
  636. // let inputArray = {
  637. // "product_ids" : [...selectedIds]
  638. // }
  639. const extractAdditional = document.getElementById('extract_additional').checked;
  640. const processImage = document.getElementById('process_image').checked;
  641. // const selectedMultiples = document.getElementById('#mandatory-attributes');
  642. // const selectedValues = Array.from(selectedMultiples.selectedOptions).map(option => option.value);
  643. const selectElement = document.getElementById('mandatory-attributes');
  644. const selectedValues = Array.from(selectElement.selectedOptions).map(option => option.value);
  645. // console.log(selectedValues); // Logs an array of selected values
  646. // console.log("thresholdValueDisplay",thresholdValueDisplay.value);
  647. const threshold = parseFloat(document.getElementById('thresholdRange').value);
  648. // Transform the new state array into the required API format
  649. const itemIds = selectedProductsWithAttributes.map(p => p.item_id);
  650. // Create the mandatory_attrs map: { item_id: { attr_name: [values] } }
  651. // NOTE: The backend API you showed expects a flattened list of "mandatory_attrs"
  652. // like: { "color": ["color", "shade"], "size": ["size", "fit"] }
  653. // It seems to ignore the selected product-specific values and uses a general list of synonyms.
  654. // Assuming the request needs a general map of *all unique* selected attributes across all selected products:
  655. let mandatoryAttrsMap = {};
  656. selectedProductsWithAttributes.forEach(product => {
  657. // Merge attributes from all selected products
  658. Object.assign(mandatoryAttrsMap, product.mandatory_attrs);
  659. });
  660. // If the API expects the complex, product-specific payload from your Q1 example:
  661. const payloadForQ1 = selectedProductsWithAttributes.map(p => ({
  662. item_id: p.item_id,
  663. mandatory_attrs: p.mandatory_attrs
  664. }));
  665. let inputArray = {
  666. "products": payloadForQ1,
  667. "model": "llama-3.1-8b-instant",
  668. "extract_additional": extractAdditional,
  669. "process_image": processImage,
  670. "multiple": selectedValues,
  671. "threshold_abs": threshold, // Lower threshold to be more permissive
  672. // "margin": 0.3, // Larger margin to include more candidates
  673. // "use_adaptive_margin": true,
  674. // "use_semantic_clustering": true
  675. }
  676. let raw = JSON.stringify(inputArray);
  677. fetch('/attr/batch-extract/', {
  678. method: 'POST', // or 'POST' if your API expects POST
  679. headers: {
  680. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
  681. 'Content-Type': "application/json"
  682. },
  683. body: raw
  684. })
  685. .then(response => response.json())
  686. .then(data => {
  687. // console.log("response data",data);
  688. FAKE_API_RESPONSE = data;
  689. renderInlineAttributes();
  690. jQuery('#full-page-loader').hide();
  691. });
  692. }
  693. function resetAll() {
  694. selectedProductsWithAttributes = []; // Reset the main array
  695. // selectedIds.clear();
  696. lastSeen.clear();
  697. renderProducts();
  698. // Clear summary
  699. document.getElementById('statTotal').textContent = '0';
  700. document.getElementById('statOk').textContent = '0';
  701. document.getElementById('statKo').textContent = '0';
  702. $('#api-summary').style.display = 'none';
  703. // ✅ Clear Select2 selections
  704. jQuery('#mandatory-attributes').val(null).trigger('change');
  705. // ✅ Reset threshold input (and display)
  706. const thresholdInput = document.getElementById('thresholdRange');
  707. const thresholdDisplay = document.getElementById('thresholdValue');
  708. thresholdInput.value = '0.2'; // or any default value you prefer
  709. if (thresholdDisplay) {
  710. thresholdDisplay.textContent = '0.2';
  711. }
  712. }
  713. function setLayout(mode) {
  714. layoutMode = mode;
  715. const btnCards = document.getElementById('btnCards');
  716. const btnTable = document.getElementById('btnTable');
  717. if (mode === 'cards') { btnCards.classList.add('active'); btnCards.setAttribute('aria-selected', 'true'); btnTable.classList.remove('active'); btnTable.setAttribute('aria-selected', 'false'); }
  718. else { btnTable.classList.add('active'); btnTable.setAttribute('aria-selected', 'true'); btnCards.classList.remove('active'); btnCards.setAttribute('aria-selected', 'false'); }
  719. renderProducts();
  720. }
  721. // Upload elements (Bootstrap modal version)
  722. const uploadModalEl = document.getElementById('uploadModal');
  723. const dropzone = document.getElementById('dropzone');
  724. const uploadFiles = document.getElementById('uploadFiles');
  725. const fileInfo = document.getElementById('fileInfo');
  726. const uploadBar = document.getElementById('uploadBar');
  727. const uploadStatus = document.getElementById('uploadStatus');
  728. // Reset modal on show
  729. uploadModalEl.addEventListener('shown.bs.modal', () => {
  730. uploadStatus.textContent = '';
  731. uploadStatus.className = ''; // clear success/error class
  732. uploadBar.style.width = '0%';
  733. uploadBar.setAttribute('aria-valuenow', '0');
  734. uploadFiles.value = '';
  735. uploadFiles.setAttribute('accept', ACCEPT_TYPES);
  736. fileInfo.textContent = 'No files selected.';
  737. });
  738. function describeFiles(list) {
  739. if (!list || list.length === 0) { fileInfo.textContent = 'No files selected.'; return; }
  740. const names = Array.from(list).map(f => `${f.name} (${Math.round(f.size/1024)} KB)`);
  741. fileInfo.textContent = names.join(', ');
  742. }
  743. // Drag & drop feedback
  744. ['dragenter','dragover'].forEach(evt => {
  745. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('drag'); });
  746. });
  747. ['dragleave','drop'].forEach(evt => {
  748. dropzone.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('drag'); });
  749. });
  750. // Handle drop
  751. dropzone.addEventListener('drop', e => {
  752. uploadFiles.files = e.dataTransfer.files;
  753. describeFiles(uploadFiles.files);
  754. });
  755. // Click to browse
  756. // dropzone.addEventListener('click', () => uploadFiles.click());
  757. // Picker change
  758. uploadFiles.addEventListener('change', () => describeFiles(uploadFiles.files));
  759. function startUpload() {
  760. const files = uploadFiles.files;
  761. if (!files || files.length === 0) { alert('Please select file(s) to upload.'); return; }
  762. jQuery('#full-page-loader').show();
  763. uploadStatus.textContent = 'Uploading...';
  764. uploadStatus.className = ''; // neutral
  765. uploadBar.style.width = '0%';
  766. uploadBar.setAttribute('aria-valuenow', '0');
  767. const form = new FormData();
  768. Array.from(files).forEach(f => form.append('file', f));
  769. // form.append('uploaded_by', 'Vishal'); // example extra field
  770. const xhr = new XMLHttpRequest();
  771. xhr.open('POST', UPLOAD_API_URL, true);
  772. // If you need auth:
  773. // xhr.setRequestHeader('Authorization', 'Bearer <token>');
  774. xhr.upload.onprogress = (e) => {
  775. if (e.lengthComputable) {
  776. const pct = Math.round((e.loaded / e.total) * 100);
  777. uploadBar.style.width = pct + '%';
  778. uploadBar.setAttribute('aria-valuenow', String(pct));
  779. }
  780. };
  781. xhr.onreadystatechange = () => {
  782. if (xhr.readyState === 4) {
  783. const ok = (xhr.status >= 200 && xhr.status < 300);
  784. try {
  785. const resp = JSON.parse(xhr.responseText || '{}');
  786. uploadStatus.textContent = ok ? (resp.message || 'Upload successful') : (resp.error || `Upload failed (${xhr.status})`);
  787. } catch {
  788. uploadStatus.textContent = ok ? 'Upload successful' : `Upload failed (${xhr.status})`;
  789. }
  790. uploadStatus.className = ok ? 'success' : 'error';
  791. // Optional: auto-close the modal on success after 1.2s:
  792. // if (ok) setTimeout(() => bootstrap.Modal.getInstance(uploadModalEl).hide(), 1200);
  793. }
  794. };
  795. xhr.onerror = () => {
  796. uploadStatus.textContent = 'Network error during upload.';
  797. uploadStatus.className = 'error';
  798. };
  799. xhr.send(form);
  800. setTimeout(()=>{
  801. jQuery('#uploadModal').modal('hide');
  802. },3000)
  803. jQuery('#full-page-loader').hide();
  804. }
  805. // Wire Start button
  806. document.getElementById('uploadStart').addEventListener('click', startUpload);
  807. // Cancel button already closes the modal via data-bs-dismiss
  808. // --- Pagination state ---
  809. let page = 1;
  810. let pageSize = 50; // default rows per page
  811. function totalPages() {
  812. return Math.max(1, Math.ceil(PRODUCT_BASE.length / pageSize));
  813. }
  814. function clampPage() {
  815. page = Math.min(Math.max(1, page), totalPages());
  816. }
  817. function getCurrentSlice() {
  818. clampPage();
  819. const start = (page - 1) * pageSize;
  820. return PRODUCT_BASE.slice(start, start + pageSize);
  821. }
  822. function renderPagination() {
  823. const bar = document.getElementById('paginationBar');
  824. if (!bar) return;
  825. const tp = totalPages();
  826. clampPage();
  827. bar.innerHTML = `
  828. <div class="page-size">
  829. <label for="pageSizeSelect">Rows per page</label>
  830. <select id="pageSizeSelect">
  831. <option value="5" ${pageSize===5 ? 'selected' : ''}>5</option>
  832. <option value="10" ${pageSize===10 ? 'selected' : ''}>10</option>
  833. <option value="20" ${pageSize===20 ? 'selected' : ''}>20</option>
  834. <option value="50" ${pageSize===50 ? 'selected' : ''}>50</option>
  835. <option value="all" ${pageSize>=PRODUCT_BASE.length ? 'selected' : ''}>All</option>
  836. </select>
  837. </div>
  838. <div class="pager">
  839. <button class="pager-btn" id="prevPage" ${page<=1 ? 'disabled' : ''} aria-label="Previous page">‹</button>
  840. <span class="page-info">Page ${page} of ${tp}</span>
  841. <button class="pager-btn" id="nextPage" ${page>=tp ? 'disabled' : ''} aria-label="Next page">›</button>
  842. </div>
  843. `;
  844. // wire events
  845. document.getElementById('prevPage')?.addEventListener('click', () => { if (page > 1) { page--; renderProducts(); } });
  846. document.getElementById('nextPage')?.addEventListener('click', () => { if (page < tp) { page++; renderProducts(); } });
  847. const sel = document.getElementById('pageSizeSelect');
  848. if (sel) {
  849. sel.addEventListener('change', () => {
  850. const val = sel.value;
  851. pageSize = (val === 'all') ? PRODUCT_BASE.length : parseInt(val, 10);
  852. page = 1; // reset to first page when size changes
  853. renderProducts();
  854. });
  855. }
  856. }
  857. // Function to add/remove product from the state and manage its attributes
  858. function toggleProductSelection(itemId, isChecked, attributes = {}) {
  859. const index = selectedProductsWithAttributes.findIndex(p => p.item_id === itemId);
  860. if (isChecked) {
  861. // If selecting, ensure the product object exists in the array
  862. if (index === -1) {
  863. selectedProductsWithAttributes.push({
  864. item_id: itemId,
  865. mandatory_attrs: attributes
  866. });
  867. } else {
  868. // Update attributes if the product is already selected
  869. selectedProductsWithAttributes[index].mandatory_attrs = attributes;
  870. }
  871. } else {
  872. // If deselecting, remove the product object from the array
  873. if (index !== -1) {
  874. selectedProductsWithAttributes.splice(index, 1);
  875. }
  876. }
  877. updateSelectionInfo();
  878. }
  879. // Function to get the current mandatory attributes for a selected item
  880. function getSelectedAttributes(itemId) {
  881. const productEntry = selectedProductsWithAttributes.find(p => p.item_id === itemId);
  882. return productEntry ? productEntry.mandatory_attrs : {};
  883. }
  884. // Helper to check if a product is selected
  885. function isProductSelected(itemId) {
  886. return selectedProductsWithAttributes.some(p => p.item_id === itemId);
  887. }
  888. // Helper to check if a specific attribute/value is selected
  889. function isAttributeValueSelected(itemId, attrName, value) {
  890. const attrs = getSelectedAttributes(itemId);
  891. const values = attrs[attrName];
  892. return values ? values.includes(value) : false; // Default all selected when first loaded
  893. }
  894. // $('.attribute-select').select2({
  895. // placeholder: 'Select product attributes'
  896. // });
  897. function getAtributeList(){
  898. jQuery('#full-page-loader').show();
  899. try{
  900. fetch('/attr/products/attributes', {
  901. method: 'GET', // or 'POST' if your API expects POST
  902. headers: {
  903. 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
  904. }
  905. })
  906. .then(response => response.json())
  907. .then(data => {
  908. // console.log("data",data);
  909. let attributesData = data;
  910. // Step 1: Extract unique mandatory attribute names
  911. const mandatoryAttributes = [...new Set(
  912. attributesData
  913. .filter(attr => attr.is_mandatory === "Yes")
  914. .map(attr => attr.attribute_name)
  915. )];
  916. // Step 2: Populate the select element
  917. const $select = jQuery('#mandatory-attributes');
  918. $select.append(new Option("Select All", "select_all")); // Add "Select All" option first
  919. mandatoryAttributes.forEach(attr => {
  920. $select.append(new Option(attr, attr));
  921. });
  922. // Step 3: Initialize Select2 with placeholder
  923. // $select.select2({
  924. // placeholder: "Select mandatory attributes",
  925. // allowClear: true
  926. // });
  927. // Step 4: Handle 'Select All' logic
  928. $select.on('select2:select', function (e) {
  929. if (e.params.data.id === "select_all") {
  930. // Select all real options except "Select All"
  931. const allOptions = mandatoryAttributes;
  932. $select.val(allOptions).trigger('change');
  933. }
  934. });
  935. jQuery('#full-page-loader').hide();
  936. });
  937. }catch(err){
  938. console.log("err",err);
  939. jQuery('#full-page-loader').hide();
  940. }
  941. }
  942. document.addEventListener("DOMContentLoaded", function () {
  943. // Update span when range changes
  944. thresholdInput.addEventListener('input', function () {
  945. // console.log("this.value",this.value);
  946. thresholdValueDisplay.textContent = this.value;
  947. });
  948. });
  949. // Get threshold value when needed
  950. function getThreshold() {
  951. // console.log("parseFloat(thresholdInput.value)",parseFloat(thresholdInput.value));
  952. return parseFloat(thresholdInput.value);
  953. }