attr-extraction.js 53 KB

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