attr-extraction.js 54 KB

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