attr-extraction.js 52 KB

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